Kernels:
Trusted publisher
Uploaded using `kernel-builder` (batch 16/18).
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/detail/sm103_blockscaled_layout.hppAdded+107
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/device_kernel.hAdded+129
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/collective_builder.hppAdded+126
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/collective_epilogue.hppAdded+75
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/default_epilogue.hppAdded+265
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/default_epilogue_array.hppAdded+287
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/detail.hppAdded+887
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/epilogue_tensor_broadcast.hppAdded+271
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_array_nosmem.hppAdded+937
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_array_tma_warpspecialized.hppAdded+1526
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_nosmem.hppAdded+856
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_tma_warpspecialized.hppAdded+1299
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm70_epilogue_vectorized.hppAdded+549
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm70_epilogue_vectorized_array.hppAdded+412
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm90_epilogue_array_tma_warpspecialized.hppAdded+1245
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm90_epilogue_tma_warpspecialized.hppAdded+958
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm90_epilogue_tma_warpspecialized_bias_elementwise.hppAdded+164
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/dispatch_policy.hppAdded+302
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/callbacks.hppAdded+91
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/operations.hppAdded+645
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm100_callbacks_tma_warpspecialized.hppAdded+1322
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm100_visitor_compute_tma_warpspecialized.hppAdded+500
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm100_visitor_store_tma_warpspecialized.hppAdded+666
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm120_callbacks_tma_warpspecialized.hppAdded+1593
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm120_visitor_store_tma_warpspecialized.hppAdded+899
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_callbacks_tma_warpspecialized.hppAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_compute_tma_warpspecialized.hppAdded+842
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_load_tma_warpspecialized.hppAdded+1492
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_store_tma_warpspecialized.hppAdded+1722
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hppAdded+1149
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_topk_softmax.hppAdded+763
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/activation.hAdded+914
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/conversion_op.hAdded+148
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/detail.hppAdded+52
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination.hAdded+527
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_bias_elementwise.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_bias_relu.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_clamp.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_dgelu.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_drelu.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_gelu.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_generic.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_generic_with_scaling.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_hardswish.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_leaky_relu.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_params.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_planar_complex.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_relu.hAdded
- build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_relu0.hAdded
68 unmodified lines69707168 unmodified linesbuild/torch214-cu130-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -textbuild/torch214-cu132-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -textbuild/torch215-cu132-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -text68 unmodified lines6970717268 unmodified linesbuild/torch214-cu130-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -textbuild/torch214-cu132-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -textbuild/torch215-cu132-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -textbuild/torch215-cu134-aarch64-linux/_deep_gemm_cuda_d0f05a9.abi3.so filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107/*************************************************************************************************** * Copyright (c) 2025 - 2025 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. * **************************************************************************************************/
/*! \file \brief Blocked Scale configs specific for SM103 BlockScaled MMA*/
#pragma once
#include "cutlass/layout/matrix.h"
#include "cute/int_tuple.hpp"#include "cute/atom/mma_traits_sm100.hpp"
namespace cutlass::detail{
/////////////////////////////////////////////////////////////////////////////////////////////////using namespace cute;
template <int SFVecSize, UMMA::Major major = UMMA::Major::K>struct Sm103BlockScaledBasicChunk {
using Blk_MN = _128; using Blk_SF = _4;
using SfKMajorAtom = Layout< Shape< Shape< _8, _4, _4>, Shape<Int<SFVecSize>, _4>>, Stride<Stride<_16,_128, _4>, Stride< _0, _1>>>; using SfMNMajorAtom = Layout< Shape< Shape<Int<SFVecSize>, _4>, Shape<_8, _4, _4>>, Stride<Stride< _0, _1>, Stride<_16,_128, _4>>>; using SfAtom = cute::conditional_t<major == UMMA::Major::K, SfKMajorAtom, SfMNMajorAtom>;};
template <int SFVecSize_>struct Sm103BlockScaledConfig { // We are creating the SFA and SFB tensors' layouts in the collective since they always have the same layout. // k-major order static constexpr int SFVecSize = SFVecSize_; using Sm103BlkScaledChunk = Sm103BlockScaledBasicChunk<SFVecSize>; using Blk_MN = typename Sm103BlkScaledChunk::Blk_MN; using Blk_SF = typename Sm103BlkScaledChunk::Blk_SF; using SfAtom = typename Sm103BlkScaledChunk::SfAtom;
using LayoutSF = decltype(tile_to_shape(SfAtom{}, make_shape(int(0),int(0),int(0)),Step<_2,_1,_3>{}));
CUTE_HOST_DEVICE static constexpr auto deduce_layoutSFA() { return LayoutSF{}; }
CUTE_HOST_DEVICE static constexpr auto deduce_layoutSFB() { return LayoutSF{}; }
// The following function is provided for user fill dynamic problem size to the layout_SFA. template < class ProblemShape, class LayoutSFA = LayoutSF> CUTE_HOST_DEVICE static constexpr auto tile_atom_to_shape_SFA(ProblemShape problem_shape, LayoutSFA layout_sfa = LayoutSFA{}) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_MNKL; return tile_to_shape(SfAtom{}, make_shape(M,K,L), Step<_2,_1,_3>{}); }
// The following function is provided for user fill dynamic problem size to the layout_SFB. template <class ProblemShape, class LayoutSFB = LayoutSF> CUTE_HOST_DEVICE static constexpr auto tile_atom_to_shape_SFB(ProblemShape problem_shape, LayoutSFB layout_sfb = LayoutSFB{}) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_MNKL; return tile_to_shape(SfAtom{}, make_shape(N,K,L), Step<_2,_1,_3>{}); }};/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::detail123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129/*************************************************************************************************** * Copyright (c) 2017 - 2025 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. * **************************************************************************************************//*! \file \brief Template for generic CUTLASS kernel.*/
#pragma once
#include <cutlass/detail/helper_macros.hpp> // CUTLASS_HOST_DEVICE#include <cutlass/arch/synclog.hpp> // cutlass::arch::synclog_*#include <cutlass/platform/platform.h> // uint64_t
// __grid_constant__ was introduced in CUDA 11.7.#if ((__CUDACC_VER_MAJOR__ >= 12) || ((__CUDACC_VER_MAJOR__ == 11) && (__CUDACC_VER_MINOR__ >= 7))) && !CUTLASS_CLANG_CUDA# define CUTLASS_GRID_CONSTANT_SUPPORTED#endif
// __grid_constant__ can be enabled only on SM70+#if defined(CUTLASS_GRID_CONSTANT_SUPPORTED) && defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 700)# define CUTLASS_GRID_CONSTANT_ENABLED#endif
#if ! defined(CUTLASS_GRID_CONSTANT)# if defined(CUTLASS_GRID_CONSTANT_ENABLED)# define CUTLASS_GRID_CONSTANT __grid_constant__# else# define CUTLASS_GRID_CONSTANT# endif#endif
////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
template <typename T> struct Type2Type { using type=T; };// using the simple type to replace the complex type to reduce this symbol sizetemplate <typename T> struct GetUnderlyingKernel : public Type2Type<T> {};template <uint64_t shader_guid, unsigned index, template <uint64_t, unsigned> class Wrapper > struct GetUnderlyingKernel<Wrapper<shader_guid,index>> : public Wrapper<shader_guid,index> {};template <typename T> using GetUnderlyingKernel_t = typename GetUnderlyingKernel<T>::type;
////////////////////////////////////////////////////////////////////////////////
/// Generic CUTLASS kernel template.template <typename Operator>CUTLASS_GLOBALvoid Kernel(typename Operator::Params params) { // Dynamic shared memory base pointer extern __shared__ int SharedStorageBase[]; // Declare pointer to dynamic shared memory. typename Operator::SharedStorage *shared_storage = reinterpret_cast<typename Operator::SharedStorage *>(SharedStorageBase);
Operator op;
op(params, *shared_storage); cutlass::arch::synclog_print();}
/// Generic CUTLASS kernel template.template <typename Operator>CUTLASS_GLOBALvoid Kernel2(typename Operator::Params params) { // Dynamic shared memory base pointer extern __shared__ int SharedStorageBase[]; // Declare pointer to dynamic shared memory. typename Operator::SharedStorage *shared_storage = reinterpret_cast<typename Operator::SharedStorage *>(SharedStorageBase);
Operator::invoke(params, *shared_storage); cutlass::arch::synclog_print();
}
//////////////////////////////////////////////////////////////////////////////////// 3.0 specific launch//////////////////////////////////////////////////////////////////////////////////
/// Generic CUTLASS kernel template.template <typename Operator>CUTLASS_GLOBAL#ifdef __CUDACC__// Enclosing this in __CUDACC__ suppresses MSVC warnings.__launch_bounds__(Operator::MaxThreadsPerBlock, Operator::MinBlocksPerMultiprocessor)#endif // __CUDACC__void device_kernel(CUTLASS_GRID_CONSTANT typename Operator::Params const params){ // Dynamic shared memory base pointer extern __shared__ char smem[]; Operator op; op(params, smem); cutlass::arch::synclog_print();
}
////////////////////////////////////////////////////////////////////////////////} /// namespace cutlass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/#pragma once
#include <cute/arch/copy.hpp> // cute::DefaultCopy#include <cute/util/type_traits.hpp> // cute::is_base_of_v
#include "cutlass/detail/dependent_false.hpp"#include "cutlass/epilogue/fusion/callbacks.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Used to specify epilogue subtile shape or dispatch to automatic computation of subtile shapestruct EpilogueTileAuto {};
// Used to let the builder pick the epilogue schedule automatically.// Can be overridden with kernel schedule tags in cutlass/gemm/dispatch_policy.hppstruct EpilogueScheduleAuto {};
template < class ArchTag, class OpClass, class TileShape_MNK, class ClusterShape_MNK, class EpilogueTileType, class ElementAccumulator, class ElementCompute, class ElementC, class GmemLayoutTagC, int AlignmentC, class ElementD, class GmemLayoutTagD, int AlignmentD, class EpilogueScheduleType, class FusionOpOrCallbacks = cutlass::epilogue::fusion::LinearCombination<ElementD,ElementCompute,ElementC,ElementCompute>, class Enable = void>struct CollectiveBuilder { static_assert(cutlass::detail::dependent_false<ArchTag>, "Could not build a collective epilogue for given parameters.");};
// helper sub-builder for epilogue fusion callbacks (for internal use by CollectiveBuilder only)namespace detail {
// callbacks builder with operation tagtemplate< class DispatchPolicy, class FusionOp, class TileShape_MNK, class EpilogueTile_MN, class ElementAccumulator, class AccLoadOp = cute::DefaultCopy, class = void>struct CallbacksBuilder { using Callbacks = fusion::FusionCallbacks<DispatchPolicy, FusionOp, TileShape_MNK, EpilogueTile_MN>;};
// callbacks builder with callbacks passthroughtemplate < class DispatchPolicy, class FusionCallbacks, class TileShape_MNK, class EpilogueTile_MN, class AccLoadOp, class ElementAccumulator>struct CallbacksBuilder< DispatchPolicy, FusionCallbacks, TileShape_MNK, EpilogueTile_MN, ElementAccumulator, AccLoadOp, cute::enable_if_t<not cute::is_base_of_v<fusion::FusionOperation, FusionCallbacks>>> { using Callbacks = FusionCallbacks;};
} // namespace detail
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::collective
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "builders/sm90_builder.inl"#include "builders/sm100_builder.inl" #include "builders/sm103_builder.inl"#include "builders/sm120_builder.inl"
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/#pragma once
#include <cutlass/detail/dependent_false.hpp>
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < class DispatchPolicy, class... Args>class CollectiveEpilogue { static_assert(cutlass::detail::dependent_false<DispatchPolicy>, "Could not find an epilogue specialization.");};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::collective
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "detail.hpp"
//// Gemm//#include "default_epilogue.hpp"#include "default_epilogue_array.hpp"#include "epilogue_tensor_broadcast.hpp"#include "sm70_epilogue_vectorized.hpp"#include "sm70_epilogue_vectorized_array.hpp"#include "sm90_epilogue_tma_warpspecialized.hpp"#include "sm90_epilogue_tma_warpspecialized_bias_elementwise.hpp"#include "sm90_epilogue_array_tma_warpspecialized.hpp"#include "sm100_epilogue_nosmem.hpp" #include "sm100_epilogue_array_nosmem.hpp" #include "sm100_epilogue_tma_warpspecialized.hpp" #include "sm100_epilogue_array_tma_warpspecialized.hpp" //// Conv///////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/arch/memory.h"#include "cutlass/gemm/dispatch_policy.hpp"#include "cutlass/epilogue/collective/detail.hpp"
#include "cute/tensor.hpp"#include "cute/numeric/numeric_types.hpp"#include "cutlass/cuda_host_adapter.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Applies an element wise operation to all elements within the fragment/// and writes them out to destination storage.template < class ElementC_, class StrideC_, class StrideD_, class ThreadEpilogueOp_, class EpilogueSchedule_>class DefaultEpilogue {public: // // Type Aliases // using EpilogueSchedule = EpilogueSchedule_; using DispatchPolicy = EpilogueSchedule_;
// derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementC = ElementC_; using StrideC = StrideC_; using ElementD = typename ThreadEpilogueOp::ElementD; using StrideD = StrideD_;
using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>, ElementD, ElementC>; // prevents void ref breakages
using GmemTiledCopyC = void; using GmemTiledCopyD = void;
static const int kOutputAlignment = ThreadEpilogueOp::kCount; using AlignmentType = typename cute::uint_bit<sizeof_bits<ElementOutput>::value * kOutputAlignment>::type;
static_assert(cute::rank(StrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]"); static_assert(cute::rank(StrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");
struct SharedStorage { };
using TensorStorage = SharedStorage;
// Host side epilogue arguments struct Arguments { typename ThreadEpilogueOp::Params thread{}; ElementC const* ptr_C = nullptr; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params using Params = Arguments;
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& _, Arguments const& args, [[maybe_unused]] void* workspace) { return args; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template<class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { return true; }
// Note: SharedStorage is unused for DefaultEpilogue CUTLASS_HOST_DEVICE DefaultEpilogue(Params const& params_, SharedStorage const& shared_storage = SharedStorage()) : params(params_), epilogue_op(params_.thread) { }
CUTLASS_DEVICE bool is_source_needed() { return epilogue_op.is_source_needed(); }
template< class ProblemShapeMNKL, class BlockShapeMNK, class BlockCoordMNKL, class FrgEngine, class FrgLayout, class TiledMma, class ResidueMNK > CUTLASS_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, BlockShapeMNK blk_shape_MNK, BlockCoordMNKL blk_coord_mnkl, cute::Tensor<FrgEngine, FrgLayout> const& accumulators, TiledMma tiled_mma, [[maybe_unused]] ResidueMNK, int thread_idx, [[maybe_unused]] char*) { using namespace cute; using X = Underscore;
static_assert(cute::rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<BlockShapeMNK>::value, "ThreadBlock tile shape must be static"); static_assert(cute::rank(BlockShapeMNK{}) == 3, "BlockShapeMNK must be rank 3"); static_assert(cute::rank(BlockCoordMNKL{}) == 4, "BlockCoordMNKL must be rank 3");
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl);
auto stride_c = detail::get_epilogue_stride<EpilogueSchedule>(params.dC); auto stride_d = detail::get_epilogue_stride<EpilogueSchedule>(params.dD);
// Represent the full output tensor Tensor mC_mnl = make_tensor(make_gmem_ptr<GmemElementC>(params.ptr_C), make_shape(M,N,L), stride_c); // (m,n,l) Tensor mD_mnl = make_tensor(make_gmem_ptr(params.ptr_D), make_shape(M,N,L), stride_d); // (m,n,l) Tensor gC_mnl = local_tile(mC_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gD_mnl = local_tile(mD_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l)
// Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = blk_coord_mnkl; Tensor gC = gC_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N) Tensor gD = gD_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N)
// Partition source and destination tiles to match the accumulator partitioning auto thr_mma = tiled_mma.get_thread_slice(thread_idx); Tensor tCgD = thr_mma.partition_C(gD); // (VEC,THR_M,THR_N) Tensor tCgC = thr_mma.partition_C(gC); // (VEC,THR_M,THR_N)
static_assert(is_static<FrgLayout>::value, "Accumulator layout must be static"); CUTE_STATIC_ASSERT_V(size(tCgC) == size(tCgD), "Source and destination must have the same number of elements."); CUTE_STATIC_ASSERT_V(size(tCgD) == size(accumulators), "Accumulator count must have the same destination element count.");
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) auto shape_MN = make_shape(M,N); Tensor mD_crd = make_identity_tensor(shape_MN); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(blk_shape_MNK), make_coord(m_coord, n_coord)); // (BLK_M,BLK_N) Tensor tCcD_mn = thr_mma.partition_C(cD_mn); // (VEC,THR_M,THR_N) // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (BLK_M,BLK_N) Tensor tCcD = make_coord_tensor(tCcD_mn.layout()); // (VEC,THR_M,THR_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = shape_MN - cD_mn(_0{}); // (m,n) auto residue_tCcD = shape_MN - tCcD_mn(_0{}); // (m,n)
// Fully OOB tile if (not elem_less(repeat_like(residue_cD, _0{}), residue_cD)) { return; }
using FragCType = remove_cvref_t<decltype(tCgC(0))>; using FragDType = remove_cvref_t<decltype(tCgD(0))>;
// source is needed if (epilogue_op.is_source_needed()) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accumulators); ++i) { FragCType fragC; bool pred = elem_less(tCcD(i), residue_tCcD); arch::global_load<FragCType, sizeof(FragCType)>(fragC, &tCgC(i), pred); FragDType fragD = epilogue_op(accumulators(i), fragC); arch::global_store<FragDType, sizeof(FragDType)>(fragD, &tCgD(i), pred); } } // source is not needed, avoid load else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accumulators); ++i) { bool pred = elem_less(tCcD(i), residue_tCcD); FragDType fragD = epilogue_op(accumulators(i)); arch::global_store<FragDType, sizeof(FragDType)>(fragD, &tCgD(i), pred); } } }
private: Params params; ThreadEpilogueOp epilogue_op;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/gemm/dispatch_policy.hpp"#include "cutlass/epilogue/collective/detail.hpp"
#include "cute/tensor.hpp"#include "cute/numeric/numeric_types.hpp"#include "cutlass/trace.h"
#include "cutlass/cuda_host_adapter.hpp"/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Applies an element wise operation to all elements within the fragment// and writes them out to destination storage.template < class ElementC_, class StrideC_, class StrideD_, class ThreadEpilogueOp_, class EpilogueSchedule_>class DefaultEpilogueArray {public: // // Type Aliases // using EpilogueSchedule = EpilogueSchedule_; using DispatchPolicy = EpilogueSchedule_; // derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementC = ElementC_; using StrideC = StrideC_; using InternalStrideC = cute::remove_pointer_t<StrideC>; using ElementD = typename ThreadEpilogueOp::ElementD; using StrideD = StrideD_; using InternalStrideD = cute::remove_pointer_t<StrideD>;
using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>, ElementD, ElementC>; // prevents void ref breakages
using GmemTiledCopyC = void; using GmemTiledCopyD = void;
static const int kOutputAlignment = ThreadEpilogueOp::kCount; using AlignmentType = typename cute::uint_bit<sizeof_bits<ElementOutput>::value * kOutputAlignment>::type;
static_assert(cute::is_same_v<EpilogueSchedule, PtrArrayNoSmemWarpSpecialized> || cute::is_same_v<EpilogueSchedule, PtrArrayDefault> || cute::is_same_v<EpilogueSchedule, PtrArrayNoSmemWarpSpecializedTransposed>, "Incompatible epilogue schedule."); static_assert(rank(InternalStrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]"); static_assert(rank(InternalStrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");
struct SharedStorage { };
using TensorMapStorage = SharedStorage;
// Host side epilogue arguments struct Arguments { typename ThreadEpilogueOp::Params thread{}; ElementC const** ptr_C = nullptr; StrideC dC{}; ElementD** ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params using Params = Arguments;
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( ProblemShape const&, Arguments const& args, [[maybe_unused]] void* workspace) { return args; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int sm_count) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template<class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { return true; }
CUTLASS_HOST_DEVICE DefaultEpilogueArray(Params const& params_) : params(params_) { }
CUTLASS_DEVICE bool is_source_needed() { // For Ptr-Array or Grouped Gemm we cannot determine if source is needed based on first beta. return true; }
template< class ProblemShapeMNKL, class BlockShapeMNK, class BlockCoordMNKL, class FrgEngine, class FrgLayout, class TiledMma, class ResidueMNK > CUTLASS_HOST_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, BlockShapeMNK blk_shape_MNK, BlockCoordMNKL blk_coord_mnkl, cute::Tensor<FrgEngine, FrgLayout> const& accumulators, TiledMma tiled_mma, [[maybe_unused]] ResidueMNK, int thread_idx, [[maybe_unused]] char*) { using namespace cute; using X = Underscore;
static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<BlockShapeMNK>::value, "ThreadBlock tile shape must be static"); static_assert(rank(BlockShapeMNK{}) == 3, "BlockShapeMNK must be rank 3"); static_assert(rank(BlockCoordMNKL{}) == 4, "BlockCoordMNKL must be rank 3");
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl); // Batches are managed by using appropriate pointers to C and D matrices const int32_t mock_L = 1; const int32_t mock_l_coord = 0; // Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = blk_coord_mnkl;
// If scalar alpha/beta are provided, i.e., same alpha/beta applies to all batches/groups. // If pointers to alpha/beta are provided, i.e., alpha/beta can differ between batches/groups, // we get the correct alpha/beta values for the current batch/group using group index. ThreadEpilogueOp epilogue_op = ThreadEpilogueOp(params.thread, l_coord);
if (epilogue_op.is_source_needed() && params.dC == nullptr) { // Beta value is non-zero while pointer to C is a nullptr assert(0); }
auto [stride_c, stride_d] = [&, l = l_coord]() { if constexpr (!cute::is_same_v<InternalStrideC, StrideC>) { // If grouped gemm if (epilogue_op.is_source_needed()) { return make_tuple( detail::get_epilogue_stride<EpilogueSchedule>(params.dC[l]), detail::get_epilogue_stride<EpilogueSchedule>(params.dD[l]) ); } else { return make_tuple( InternalStrideC{}, detail::get_epilogue_stride<EpilogueSchedule>(params.dD[l]) ); } } else { return make_tuple( detail::get_epilogue_stride<EpilogueSchedule>(params.dC), detail::get_epilogue_stride<EpilogueSchedule>(params.dD) ); } }(); // Represent the full output tensor ElementC const* ptr_C_l = nullptr; if (epilogue_op.is_source_needed()) { ptr_C_l = params.ptr_C[l_coord]; } Tensor mC_mnl = make_tensor(make_gmem_ptr<GmemElementC>(ptr_C_l), make_shape(M,N,mock_L), stride_c); // (m,n,l) Tensor mD_mnl = make_tensor(make_gmem_ptr(params.ptr_D[l_coord]), make_shape(M,N,mock_L), stride_d); // (m,n,l) Tensor gC_mnl = local_tile(mC_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gD_mnl = local_tile(mD_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l)
Tensor gC = gC_mnl(_,_,m_coord,n_coord, mock_l_coord); // (BLK_M,BLK_N) Tensor gD = gD_mnl(_,_,m_coord,n_coord, mock_l_coord); // (BLK_M,BLK_N)
// Partition source and destination tiles to match the accumulator partitioning auto thr_mma = tiled_mma.get_thread_slice(thread_idx); Tensor tCgD = thr_mma.partition_C(gD); // (VEC,THR_M,THR_N) Tensor tCgC = thr_mma.partition_C(gC); // (VEC,THR_M,THR_N)
static_assert(is_static<FrgLayout>::value, "Accumulator layout must be static"); CUTE_STATIC_ASSERT_V(size(tCgC) == size(tCgD), "Source and destination must have the same number of elements."); CUTE_STATIC_ASSERT_V(size(tCgD) == size(accumulators), "Accumulator count must have the same destination element count.");
// Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(blk_shape_MNK), make_coord(m_coord, n_coord)); // (BLK_M,BLK_N) Tensor tCcD = thr_mma.partition_C(cD_mn); // (VEC,THR_M,THR_N)
// source is needed if (epilogue_op.is_source_needed()) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accumulators); ++i) { if (elem_less(tCcD(i), make_shape(M,N))) { tCgD(i) = epilogue_op(accumulators(i), tCgC(i)); } } } // source is not needed, avoid load else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accumulators); ++i) { if (elem_less(tCcD(i), make_shape(M,N))) { tCgD(i) = epilogue_op(accumulators(i)); } } } }
private: Params params;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/pipeline/pipeline.hpp"#include "cutlass/gemm/gemm.h"#include "cutlass/gemm/dispatch_policy.hpp"#include "cutlass/epilogue/dispatch_policy.hpp"
#include "cute/tensor.hpp"#include "cute/numeric/numeric_types.hpp"#include "cute/util/type_traits.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
namespace detail {
/////////////////////////////////////////////////////////////////////////////////////////////////
template <class Stride>constexpr boolis_m_major() { return cutlass::gemm::detail::is_major<0,Stride>();}
template <class Stride>constexpr boolis_n_major() { return cutlass::gemm::detail::is_major<1,Stride>();}
template <class Stride>constexpr boolis_im2col() { return cute::is_same_v<Stride, cutlass::detail::TagToStrideC_t<cutlass::layout::TensorNWC>> || cute::is_same_v<Stride, cutlass::detail::TagToStrideC_t<cutlass::layout::TensorNHWC>> || cute::is_same_v<Stride, cutlass::detail::TagToStrideC_t<cutlass::layout::TensorNDHWC>>;}
template<class Schedule>struct sm90_is_ptr_array_tma : cute::false_type {};
template<>struct sm90_is_ptr_array_tma<PtrArrayTmaWarpSpecializedCooperative> : cute::true_type {};
template<>struct sm90_is_ptr_array_tma<PtrArrayTmaWarpSpecializedPingpong> : cute::true_type {};
template<>struct sm90_is_ptr_array_tma<PtrArrayTmaWarpSpecialized> : cute::true_type {};
template<class Schedule>static constexpr bool sm90_is_ptr_array_tma_v = sm90_is_ptr_array_tma<Schedule>::value;
template<class Schedule>struct sm90_is_ptr_array_tma_cooperative : cute::false_type {};
template<>struct sm90_is_ptr_array_tma_cooperative<PtrArrayTmaWarpSpecializedCooperative> : cute::true_type {};
template<class Schedule>static constexpr bool sm90_is_ptr_array_tma_cooperative_v = sm90_is_ptr_array_tma_cooperative<Schedule>::value;
template<class Schedule>struct sm90_is_ptr_array_tma_pingpong : cute::false_type {};
template<>struct sm90_is_ptr_array_tma_pingpong<PtrArrayTmaWarpSpecializedPingpong> : cute::true_type {};
template<class Schedule>static constexpr bool sm90_is_ptr_array_tma_pingpong_v = sm90_is_ptr_array_tma_pingpong<Schedule>::value;
template<class DispatchPolicy>struct sm90_is_ptr_array_tma_dispatch_policy : cute::false_type {};
template< int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, int NumEpilogueWarpGroups>struct sm90_is_ptr_array_tma_dispatch_policy< Sm90PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>> : cute::true_type {};
template< int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, int NumEpilogueWarpGroups>struct sm90_is_ptr_array_tma_dispatch_policy< Sm120PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>> : cute::true_type {};
template<class DispatchPolicy>static constexpr bool sm90_is_ptr_array_tma_dispatch_policy_v = sm90_is_ptr_array_tma_dispatch_policy<DispatchPolicy>::value;
using cutlass::atomic_maximum;
template <class T>static constexpr int elements_per_access_v = cutlass::sizeof_bits<uint32_t>::value / cutlass::sizeof_bits<T>::value;
template <class EpilogueSchedule>static constexpr bool sm90_is_cooperative_v = cute::is_base_of_v<cutlass::epilogue::TmaWarpSpecializedCooperative, EpilogueSchedule> || sm90_is_ptr_array_tma_cooperative_v<EpilogueSchedule>;
template <class EpilogueSchedule>static constexpr bool sm90_is_warp_specialized_v = (!sm90_is_ptr_array_tma_cooperative_v<EpilogueSchedule> && sm90_is_ptr_array_tma_v<EpilogueSchedule>) || cute::is_base_of_v<cutlass::epilogue::TmaWarpSpecialized, EpilogueSchedule>;
template <class GmemLayoutTag>static constexpr bool is_im2col_mode = cute::is_same_v<GmemLayoutTag, cutlass::layout::TensorNWC> || cute::is_same_v<GmemLayoutTag, cutlass::layout::TensorNHWC> || cute::is_same_v<GmemLayoutTag, cutlass::layout::TensorNDHWC>;
template <class T>struct EmptyStorage { CUTLASS_HOST_DEVICE T* data() { return nullptr; }};
template<class EpilogueSchedule, class Stride>CUTLASS_HOST_DEVICEauto get_epilogue_stride(Stride stride){ if constexpr (cute::is_base_of_v<cutlass::gemm::EpilogueTransposed, EpilogueSchedule>|| cute::is_base_of_v<cutlass::epilogue::PtrArrayNoSmemWarpSpecializedTransposed, EpilogueSchedule>) { return cute::make_stride(cute::get<1>(stride), cute::get<0>(stride), cute::get<2>(stride)); } else { return stride; }}
template <typename ThreadEpilogueOp, typename = void>struct IsThreadEpilogueOpWithBias { static constexpr bool value = false; using type = typename ThreadEpilogueOp::ElementCompute; };
template <typename ThreadEpilogueOp>struct IsThreadEpilogueOpWithBias <ThreadEpilogueOp, cute::void_t<typename ThreadEpilogueOp::ElementBias>> { static constexpr bool value = true; using type = typename ThreadEpilogueOp::ElementBias; };
template <typename ThreadEpilogueOp, typename = void>struct IsThreadEpilogueOpWithPerChannelScaling { static constexpr bool value = false;};
template <typename ThreadEpilogueOp>struct IsThreadEpilogueOpWithPerChannelScaling <ThreadEpilogueOp, cute::enable_if_t<ThreadEpilogueOp::IsPerChannelScalingSupported>> { static constexpr bool value = true;};
template <typename ThreadEpilogueOp, typename = void>struct IsThreadEpilogueOpWithResidualAdd { static constexpr bool value = false;};
template <typename ThreadEpilogueOp>struct IsThreadEpilogueOpWithResidualAdd <ThreadEpilogueOp, cute::void_t<decltype(ThreadEpilogueOp::IsResidualSupported)>> { static constexpr bool value = ThreadEpilogueOp::IsResidualSupported;};
template <typename ThreadEpilogueOp, typename = void>struct IsThreadEpilogueOpWithActivation { static constexpr bool value = false; using type = void;};
template <typename ThreadEpilogueOp>struct IsThreadEpilogueOpWithActivation <ThreadEpilogueOp, cute::enable_if_t<ThreadEpilogueOp::IsEltActSupported>> { static constexpr bool value = true; using type = typename ThreadEpilogueOp::ActivationFn;};
template <typename ThreadEpilogueOp, typename = void>struct IsThreadEpilogueOpWithPerChannelScaled { static constexpr bool value = false;};
template <typename ThreadEpilogueOp>struct IsThreadEpilogueOpWithPerChannelScaled <ThreadEpilogueOp, cute::void_t<decltype(ThreadEpilogueOp::IsPerRowScaleSupported)>> { static constexpr bool value = ThreadEpilogueOp::IsPerRowScaleSupported || ThreadEpilogueOp::IsPerColScaleSupported;};
template <typename ThreadEpilogueOp, typename = void>struct IsThreadEpilogueOpWithElementwiseArguments : cute::false_type {};
template <typename ThreadEpilogueOp>struct IsThreadEpilogueOpWithElementwiseArguments< ThreadEpilogueOp, cute::void_t<typename ThreadEpilogueOp::ElementwiseOp::Arguments>> : cute::true_type {};
// Check if ActivationFn has 'Arguments' type definedtemplate <class ActivationFn, class = void>struct sm100_act_has_arguments : cute::false_type {};
template <class ActivationFn>struct sm100_act_has_arguments<ActivationFn, cute::void_t<typename ActivationFn::Arguments> > : cute::true_type {};
template<typename EpilogueOp, typename = void>struct Sm100EpilogueOpNumAccumulatorMtxs { static constexpr int value = 1;};
template<typename EpilogueOp>struct Sm100EpilogueOpNumAccumulatorMtxs<EpilogueOp, cute::void_t<decltype(EpilogueOp::NumAccumulatorMtxs)>> { static constexpr int value = EpilogueOp::NumAccumulatorMtxs;};
// Wrapper class to use operator-style epilogues in sm90 TMA warp-specialized kernelstemplate <class EpilogueOp>class Sm90TmaWarpSpecializedAdapter : public EpilogueOp {public: using GmemTiledCopyC = void; using GmemTiledCopyD = void;
using LoadPipeline = cutlass::PipelineTransactionAsync<0>; using LoadPipelineState = cutlass::PipelineState<0>; constexpr static uint32_t TmaTransactionBytes = 0; constexpr static bool RequiresTransactionBytes = false;
using StorePipeline = cutlass::PipelineTmaStore<0>; using StorePipelineState = cutlass::PipelineState<0>;
using TensorStorage = typename EpilogueOp::SharedStorage; using TensorMapStorage = typename EpilogueOp::SharedStorage; using PipelineStorage = typename LoadPipeline::SharedStorage;
template<class CtaTileMNK> CUTLASS_HOST_DEVICE static constexpr int get_load_pipe_increment(CtaTileMNK) { return 1; }
template<class CtaTileMNK> CUTLASS_HOST_DEVICE static constexpr int get_store_pipe_increment(CtaTileMNK) { return 1; }
CUTLASS_DEVICE static void prefetch_tma_descriptors([[maybe_unused]] typename EpilogueOp::Params const&) { }
// ctor inheritance using EpilogueOp::EpilogueOp;
CUTLASS_HOST_DEVICE Sm90TmaWarpSpecializedAdapter( typename EpilogueOp::Params const& params, [[maybe_unused]] TensorStorage& shared_tensors) : EpilogueOp(params) { }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE auto load_init( [[maybe_unused]] typename EpilogueOp::Params const& params, [[maybe_unused]] TensorMapStorage& shared_tensormaps, [[maybe_unused]] int32_t sm_count, [[maybe_unused]] int32_t sm_idx) { return cute::make_tuple(nullptr); }
template< class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class TiledMma > CUTLASS_DEVICE auto load( [[maybe_unused]] LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, [[maybe_unused]] ProblemShapeMNKL problem_shape_mnkl, [[maybe_unused]] CtaTileMNK cta_tile_mnk, [[maybe_unused]] CtaCoordMNKL cta_coord_mnkl, [[maybe_unused]] TiledMma tiled_mma, [[maybe_unused]] int thread_idx, [[maybe_unused]] TensorStorage& shared_tensors, [[maybe_unused]] int subtile_idx=-1) { return load_pipe_producer_state; }
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class TiledMma, class TensorMapC > CUTLASS_DEVICE auto load( [[maybe_unused]] LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, [[maybe_unused]] ProblemShapeMNKL problem_shape_mnkl, [[maybe_unused]] TileShapeMNK tile_shape_MNK, [[maybe_unused]] TileCoordMNKL tile_coord_mnkl, [[maybe_unused]] TiledMma tiled_mma, [[maybe_unused]] int thread_idx, [[maybe_unused]] TensorStorage& shared_tensors, [[maybe_unused]] TensorMapC const& load_tensormap, [[maybe_unused]] int subtile_idx=-1, [[maybe_unused]] bool wait = false) { return load_pipe_producer_state; }
CUTLASS_DEVICE auto load_tail( [[maybe_unused]] LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state) { return load_pipe_producer_state; }
CUTLASS_DEVICE auto store_init( [[maybe_unused]] typename EpilogueOp::Params const& params, [[maybe_unused]] TensorMapStorage& shared_tensormaps, [[maybe_unused]] int32_t sm_count, [[maybe_unused]] int32_t sm_idx, [[maybe_unused]] int32_t warp_group_idx) { return cute::make_tuple(nullptr); }
template< class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class AccEngine, class AccLayout, class TiledMma > CUTLASS_DEVICE auto store( [[maybe_unused]] LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, [[maybe_unused]] StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine,AccLayout> accumulators, TiledMma tiled_mma, int thread_idx, TensorStorage& shared_tensors, int subtile_index = -1) { constexpr int BLK_M_RANK = cute::rank<0>(cta_tile_mnk); auto m_max_coord = unwrap(cute::transform(make_seq<BLK_M_RANK>{}, [&](auto i) { return get<0,i>(problem_shape_mnkl) - get<0,i>(cta_tile_mnk) * get<0,i>(cta_coord_mnkl); }));
constexpr int BLK_N_RANK = cute::rank<1>(cta_tile_mnk); auto n_max_coord = unwrap(cute::transform(make_seq<BLK_N_RANK>{}, [&](auto i) { return get<1,i>(problem_shape_mnkl) - get<1,i>(cta_tile_mnk) * get<1,i>(cta_coord_mnkl); }));
auto residue_mnk = make_tuple(m_max_coord, n_max_coord, Int<0>{});
(*this)( problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, accumulators, tiled_mma, residue_mnk, thread_idx, reinterpret_cast<char*>(&shared_tensors));
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout, class TiledMma, class TensorMapD > CUTLASS_DEVICE auto store( [[maybe_unused]] LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, [[maybe_unused]] StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_MNK, TileCoordMNKL tile_coord_mnkl, cute::Tensor<AccEngine,AccLayout> accumulators, TiledMma tiled_mma, int thread_idx, TensorStorage& shared_tensors, [[maybe_unused]] TensorMapD const& store_tensormap, int subtile_index = -1) { constexpr int BLK_M_RANK = cute::rank<0>(tile_shape_MNK); auto m_max_coord = unwrap(cute::transform(make_seq<BLK_M_RANK>{}, [&](auto i) { return get<0,i>(problem_shape_mnkl) - get<0,i>(tile_shape_MNK) * get<0,i>(tile_coord_mnkl); }));
constexpr int BLK_N_RANK = cute::rank<1>(tile_shape_MNK); auto n_max_coord = unwrap(cute::transform(make_seq<BLK_N_RANK>{}, [&](auto i) { return get<1,i>(problem_shape_mnkl) - get<1,i>(tile_shape_MNK) * get<1,i>(tile_coord_mnkl); }));
auto residue_mnk = make_tuple(m_max_coord, n_max_coord, Int<0>{});
(*this)( problem_shape_mnkl, tile_shape_MNK, tile_coord_mnkl, accumulators, tiled_mma, residue_mnk, thread_idx, reinterpret_cast<char*>(&shared_tensors));
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
CUTLASS_DEVICE auto store_tail( [[maybe_unused]] LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, [[maybe_unused]] StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state) { return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
// Dummy methods to perform different parts of TMA/Tensormap modifications
template <bool IsLoad, class ProblemShapeMNKL> CUTLASS_DEVICE void tensormaps_perform_update( [[maybe_unused]] TensorMapStorage& shared_tensormaps, [[maybe_unused]] typename EpilogueOp::Params const& params, [[maybe_unused]] cute::TmaDescriptor const* tensormap, [[maybe_unused]] ProblemShapeMNKL problem_shape, [[maybe_unused]] int32_t next_batch, [[maybe_unused]] int32_t warp_group_idx) { }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_cp_fence_release( [[maybe_unused]] TensorMapStorage& shared_tensormaps, [[maybe_unused]] cute::TmaDescriptor const* tensormap, [[maybe_unused]] int32_t warp_group_idx) { }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_fence_acquire([[maybe_unused]] cute::TmaDescriptor const* tensormap) { }};
// Wrapper class to use operator-style epilogues in sm100 TMA warp-specialized kernelstemplate <class EpilogueOp>class Sm100TmaWarpSpecializedAdapter : public EpilogueOp {public: using LoadPipeline = cutlass::PipelineTransactionAsync<0>; // 0 stage to disable smem alloc using LoadPipelineState = cutlass::PipelineState<0>;
using StorePipeline = cutlass::PipelineTmaStore<1>; // tma store pipe has no smem alloc using StorePipelineState = cutlass::PipelineState<1>;
using TensorStorage = typename EpilogueOp::SharedStorage; using TensorMapStorage = typename EpilogueOp::SharedStorage; using PipelineStorage = typename LoadPipeline::SharedStorage;
static constexpr int NumAccumulatorMtxs = Sm100EpilogueOpNumAccumulatorMtxs<EpilogueOp>::value;
template<class CtaTileMNK> CUTLASS_HOST_DEVICE static constexpr int get_load_pipe_increment(CtaTileMNK) { return 1; }
template<class CtaTileMNK> CUTLASS_HOST_DEVICE static constexpr int get_store_pipe_increment(CtaTileMNK) { return 1; }
CUTLASS_DEVICE static void prefetch_tma_descriptors([[maybe_unused]] typename EpilogueOp::Params const&) { }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
// ctor inheritance using EpilogueOp::EpilogueOp;
CUTLASS_DEVICE auto load_init( [[maybe_unused]] typename EpilogueOp::Params const& params, [[maybe_unused]] TensorMapStorage& shared_tensormap, [[maybe_unused]] int32_t const sm_count, [[maybe_unused]] int32_t const sm_idx) const { return cute::make_tuple(nullptr); }
template< bool ReuseTmem = false, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma > CUTLASS_DEVICE auto load( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, TensorStorage& shared_tensors, bool reverse_epi_n = false) { // C load is performed in epilogue operator return load_pipe_producer_state; }
// with Tensormap template< bool ReuseTmem = false, class ProblemShapeMNKL, class CtaTileShapeMNK, class CtaTileCoordMNKL, class MmaTileMNK, class TiledMma, class TensorMap > CUTLASS_DEVICE auto load( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileShapeMNK tile_shape_mnk, CtaTileCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, TensorStorage& shared_tensors, [[maybe_unused]] cute::tuple<TensorMap, bool> const& load_tensormap_info, bool reverse_epi_n = false) { // C load is performed in epilogue operator return load_pipe_producer_state; }
CUTLASS_DEVICE void load_tail( [[maybe_unused]] LoadPipeline load_pipeline, [[maybe_unused]] LoadPipelineState load_pipe_producer_state, [[maybe_unused]] StorePipeline store_pipeline, [[maybe_unused]] StorePipelineState store_pipe_producer_state) { }
CUTLASS_DEVICE auto store_init( [[maybe_unused]] typename EpilogueOp::Params const& params, [[maybe_unused]] TensorMapStorage& shared_tensormap, [[maybe_unused]] int32_t const sm_count, [[maybe_unused]] int32_t const sm_idx) const { return cute::make_tuple(nullptr); }
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine,AccLayout> accumulators, TensorStorage& shared_tensors ) { // Wait for mma warp to fill tmem buffer with accumulator results acc_pipeline.consumer_wait(acc_pipe_consumer_state);
auto [acc_state_next] = (*this).template operator()<ReuseTmem>( acc_pipeline, acc_pipe_consumer_state, problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, accumulators, shared_tensors);
// Let mma warp know tmem buffer is consumed and empty ++load_pipe_consumer_state; ++store_pipe_producer_state;
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state, acc_state_next); }
// FastF32 API template< class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout, class TiledCopyT2R > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine, AccLayout>& tTR_rAcc, TensorStorage& shared_tensors, TiledCopyT2R tiled_t2r) { (*this)( problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tTR_rAcc, shared_tensors, tiled_t2r); return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
// FastF32 API with Tensor Map template< class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout, class TiledCopyT2R, class TensorMap > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine, AccLayout>& tTR_rAcc, TensorStorage& shared_tensors, TensorMap tensormap, TiledCopyT2R tiled_t2r) { (*this)( problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tTR_rAcc, shared_tensors, tiled_t2r); return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class CtaTileMNK, class TileCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout, class TensorMap > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, TileCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine,AccLayout> accumulators, TensorStorage& shared_tensors, TensorMap tensormap ) { // Wait for mma warp to fill tmem buffer with accumulator results acc_pipeline.consumer_wait(acc_pipe_consumer_state);
auto [acc_state_next] = (*this).template operator()<ReuseTmem>( acc_pipeline, acc_pipe_consumer_state, problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, accumulators, shared_tensors);
// Let mma warp know tmem buffer is consumed and empty ++load_pipe_consumer_state; ++store_pipe_producer_state;
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state, acc_state_next); }
template <class CtaTileMNK> CUTLASS_DEVICE void store_tail( [[maybe_unused]] LoadPipeline load_pipeline, [[maybe_unused]] LoadPipelineState load_pipe_consumer_state, [[maybe_unused]] StorePipeline store_pipeline, [[maybe_unused]] StorePipelineState store_pipe_producer_state, [[maybe_unused]] CtaTileMNK cta_tile_mnk) { }
// Dummy methods to perform different parts of TMA/Tensormap modifications
template <bool IsLoad, class ProblemShape> CUTLASS_DEVICE void tensormaps_perform_update( [[maybe_unused]] TensorMapStorage& shared_tensormap, [[maybe_unused]] typename EpilogueOp::Params const& params, [[maybe_unused]] cute::TmaDescriptor const* tensormap, [[maybe_unused]] ProblemShape problem_shape, [[maybe_unused]] int32_t next_batch) { }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_cp_fence_release( [[maybe_unused]] TensorMapStorage& shared_tensormap, [[maybe_unused]] cute::TmaDescriptor const* tensormap) { }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_fence_acquire([[maybe_unused]] cute::TmaDescriptor const* tensormap) { }};
// SFINAE helpers for detecting beta/beta_ptr/beta_ptr_array in EVT arguments.template <class Arguments, class = void>struct has_beta { static constexpr bool value = false;};
template <class Arguments>struct has_beta<Arguments, cute::void_t<decltype(Arguments{}.thread.beta)>> { static constexpr bool value = true;};
template <class Arguments, class = void>struct has_beta_ptr { static constexpr bool value = false;};
template <class Arguments>struct has_beta_ptr<Arguments, cute::void_t<decltype(Arguments{}.thread.beta_ptr)>> { static constexpr bool value = true;};
template <class Arguments, class = void>struct has_beta_ptr_array { static constexpr bool value = false;};
template <class Arguments>struct has_beta_ptr_array<Arguments, cute::void_t<decltype(Arguments{}.thread.beta_ptr_array)>> { static constexpr bool value = true;};
} // namespace detail} // namespace collective} // namespace epilogue} // namespace cutlass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Functor for performing tensor-tensor broadacasts atop existing epilogues.
Concretely, the opeartion performed is the following: UnaryOp( BinaryOp1( BinaryOp0( Activation((alpha * A @ B) + bias), beta * C0 ), beta * C1 ) )
where: - C0 and C1 have the same extents as the output - BinaryOp0 and BinaryOp1 perform elementwise binary operations - UnaryOp is an elementwise operation*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/epilogue/collective/detail.hpp"
#include "cute/tensor.hpp"#include "cutlass/cuda_host_adapter.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {/////////////////////////////////////////////////////////////////////////////////////////////////
/// Collective epilogue that applies elementwise tensor-tensor operations atop other epilogues///template < class StrideC_, class StrideD_, class ThreadEpilogueOp_, class EpilogueSchedule_, bool PerColumnBias_ = false>class EpilogueTensorBroadcast {public: // // Type Aliases // using EpilogueSchedule = EpilogueSchedule_;
// derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementBias = typename ThreadEpilogueOp::ElementBias; using ElementC = typename ThreadEpilogueOp::ElementC; using StrideC = StrideC_; using ElementD = typename ThreadEpilogueOp::ElementD; using StrideD = StrideD_; using ActivationFunctor = typename ThreadEpilogueOp::ActivationFunctor;
static_assert(cute::rank(StrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]"); static_assert(cute::rank(StrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");
static constexpr int kOutputAlignment = ThreadEpilogueOp::kCount; using AlignmentType = typename cute::uint_bit<sizeof_bits<ElementOutput>::value * kOutputAlignment>::type;
static constexpr bool IsBinaryOp0Enabled = ThreadEpilogueOp::IsBinaryOp0Enabled; static constexpr bool IsBinaryOp1Enabled = ThreadEpilogueOp::IsBinaryOp1Enabled; static constexpr bool IsUnaryOpEnabled = ThreadEpilogueOp::IsUnaryOpEnabled;
static constexpr bool PerColumnBias = PerColumnBias_; using BiasStride = typename cute::conditional_t<PerColumnBias, Stride<_0, _1, _0>, Stride<_1, _0, _0>>;
struct SharedStorage { };
// Host side epilogue arguments struct Arguments { typename ThreadEpilogueOp::Params thread{}; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; ElementBias* ptr_Bias = nullptr; ElementC* ptr_C0 = nullptr; ElementC* ptr_C1 = nullptr; };
// Device side epilogue params using Params = Arguments;
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& _, Arguments const& args, [[maybe_unused]] void* workspace) { return args; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { return true; }
CUTLASS_HOST_DEVICE EpilogueTensorBroadcast(Params const& params_) : params(params_), epilogue_op(params_.thread) { }
CUTLASS_DEVICE bool is_source_needed() { return epilogue_op.is_source0_needed() || epilogue_op.is_source1_needed(); }
template< class ProblemShapeMNKL, class BlockShapeMNK, class BlockCoordMNKL, class FrgEngine, class FrgLayout, class TiledMma, class ResidueMNK > CUTLASS_HOST_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, BlockShapeMNK blk_shape_MNK, BlockCoordMNKL blk_coord_mnkl, cute::Tensor<FrgEngine, FrgLayout> const& accumulators, TiledMma tiled_mma, ResidueMNK residue_mnk, int thread_idx, [[maybe_unused]] char* smem_buf) { using namespace cute; using X = Underscore;
static_assert(cute::rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<BlockShapeMNK>::value, "ThreadBlock tile shape must be static"); static_assert(cute::rank(BlockShapeMNK{}) == 3, "BlockShapeMNK must be rank 3"); static_assert(cute::rank(BlockCoordMNKL{}) == 4, "BlockCoordMNKL must be rank 4");
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl);
auto stride_c = detail::get_epilogue_stride<EpilogueSchedule>(params.dC); auto stride_d = detail::get_epilogue_stride<EpilogueSchedule>(params.dD); auto stride_bias = detail::get_epilogue_stride<EpilogueSchedule>(BiasStride{});
// Represent the full output tensor Tensor mC0_mnl = make_tensor(make_gmem_ptr(params.ptr_C0), make_shape(M,N,L), stride_c); // (m,n,l) Tensor mC1_mnl = make_tensor(make_gmem_ptr(params.ptr_C1), make_shape(M,N,L), stride_c); // (m,n,l) Tensor mD_mnl = make_tensor(make_gmem_ptr(params.ptr_D), make_shape(M,N,L), stride_d); // (m,n,l) Tensor mBias_mnl = make_tensor(make_gmem_ptr(params.ptr_Bias), make_shape(M,N,L), stride_bias); // (m,n,l)
Tensor gC0_mnl = local_tile(mC0_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gC1_mnl = local_tile(mC1_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l)
Tensor gD_mnl = local_tile(mD_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gBias_mnl = local_tile(mBias_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l)
// Slice to get the tile this thread block is responsible for auto [m_coord, n_coord, k_coord, l_coord] = blk_coord_mnkl; Tensor gC0 = gC0_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N) Tensor gC1 = gC1_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N) Tensor gD = gD_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N) Tensor gBias = gBias_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N)
// Partition source and destination tiles to match the accumulator partitioning auto thr_mma = tiled_mma.get_thread_slice(thread_idx); Tensor tCgD = thr_mma.partition_C(gD); // (VEC,THR_M,THR_N) Tensor tCgC0 = thr_mma.partition_C(gC0); // (VEC,THR_M,THR_N) Tensor tCgC1 = thr_mma.partition_C(gC1); // (VEC,THR_M,THR_N) Tensor tCgBias = thr_mma.partition_C(gBias); // (VEC,THR_M,THR_N)
static_assert(is_static<FrgLayout>::value, "Accumulator layout must be static"); CUTE_STATIC_ASSERT_V(size(tCgC0) == size(tCgD), "Source and destination must have the same number of elements."); CUTE_STATIC_ASSERT_V(size(tCgC1) == size(tCgD), "Source and destination must have the same number of elements."); CUTE_STATIC_ASSERT_V(size(tCgD) == size(accumulators), "Accumulator count must have the same destination element count."); CUTE_STATIC_ASSERT_V(size(tCgBias) == size(accumulators), "Accumulator count must have the same destination element count.");
auto cD = make_identity_tensor(make_shape(unwrap(shape<0>(gD)), unwrap(shape<1>(gD)))); Tensor tCcD = thr_mma.partition_C(cD);
bool bias_needed = params.ptr_Bias != nullptr; bool c0_needed = (params.ptr_C0 != nullptr) && epilogue_op.is_source0_needed(); bool c1_needed = (params.ptr_C1 != nullptr) && epilogue_op.is_source1_needed(); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accumulators); ++i) { if (elem_less(tCcD(i), make_coord(get<0>(residue_mnk), get<1>(residue_mnk)))) { ElementBias bias = bias_needed ? tCgBias(i) : ElementBias(0); ElementC c0 = c0_needed ? tCgC0(i) : ElementC(0); ElementC c1 = c1_needed ? tCgC1(i) : ElementC(0);
tCgD(i) = epilogue_op(accumulators(i), c0, c1, bias); } } }
private: Params params; ThreadEpilogueOp epilogue_op;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by Ptr-Array and Grouped GEMM epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/epilogue/collective/detail.hpp"
#include "cute/tensor.hpp"#include "cute/numeric/numeric_types.hpp"#include "cutlass/cuda_host_adapter.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Applies an element wise operation to all elements within the fragment/// and writes it out to destination storage.template < class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class ThreadEpilogueOp_, class CopyOpT2R_, class AlignmentC_, class AlignmentD_>class CollectiveEpilogue< Sm100PtrArrayNoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC_, AlignmentD_, cute::enable_if_t<IsDefaultFusionOp<ThreadEpilogueOp_>::value>> {public: // // Type Aliases // using DispatchPolicy = Sm100PtrArrayNoSmem; using EpilogueTile = EpilogueTile_; // derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementBias = typename detail::IsThreadEpilogueOpWithBias<ThreadEpilogueOp>::type; using ElementC = typename ThreadEpilogueOp::ElementC; using StrideC = StrideC_; using InternalStrideC = cute::remove_pointer_t<StrideC>; using ElementD = ElementD_; using StrideD = StrideD_; using InternalStrideD = cute::remove_pointer_t<StrideD>; using CopyOpT2R = CopyOpT2R_; using AlignmentC = AlignmentC_; using AlignmentD = AlignmentD_;
using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>,ElementD,ElementC>; // prevents void ref breakages
using GmemTiledCopyC = void; using GmemTiledCopyD = void;
constexpr static int ThreadCount = 128; constexpr static int kOutputAlignment = ThreadEpilogueOp::kCount; constexpr static bool isEpilogueBiasSupported = detail::IsThreadEpilogueOpWithBias<ThreadEpilogueOp>::value; using AlignmentType = typename cute::uint_bit<sizeof_bits<ElementOutput>::value * kOutputAlignment>::type; constexpr static uint32_t TmaTransactionBytes = 0;
struct SharedStorage { struct TensorStorage { }; struct TensorMapStorage { }; }; using TensorStorage = typename SharedStorage::TensorStorage; using TensorMapStorage = typename SharedStorage::TensorMapStorage;
// Host side epilogue arguments struct Arguments { typename ThreadEpilogueOp::Params thread{}; ElementC const** ptr_C = nullptr; StrideC dC{}; ElementD** ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params using Params = Arguments;
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { return args; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int /*sm_count*/ = 0) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { return true; }
CUTLASS_HOST_DEVICE CollectiveEpilogue(Params const& params, SharedStorage&) : params(params) { };
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout > CUTLASS_DEVICE auto operator()( AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK cta_tile_shape_mnk, TileCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine, AccLayout> const& accumulators, // (MMA,MMA_M,MMA_N) [[maybe_unused]] SharedStorage&) {
using namespace cute; using X = Underscore;
static_assert(is_tmem<AccEngine>::value, "Accumulator must be TMEM resident."); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(TileCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4");
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl); // Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl;
// Batches are managed by using appropriate pointers to C and D matrices auto problem_shape_mnl = append<3>(make_shape(M,N),Int<1>{}); auto cta_coord_mnl = append<3>(make_shape(m_coord, n_coord),Int<0>{}); auto cta_tiler = take<0,2>(cta_tile_shape_mnk);
// If scalar alpha/beta are provided, i.e., same alpha/beta applies to all batches/groups. // If pointers to alpha/beta are provided, i.e., alpha/beta can differ between batches/groups, // we get the correct alpha/beta values for the current batch/group using group index. ThreadEpilogueOp epilogue_op = ThreadEpilogueOp(params.thread, l_coord);
auto [stride_c, stride_d] = [&, l = l_coord]() { if constexpr (!cute::is_same_v<InternalStrideC, StrideC>) { // If grouped gemm if (epilogue_op.is_source_needed()) { return make_tuple( detail::get_epilogue_stride<DispatchPolicy>(params.dC[l]), detail::get_epilogue_stride<DispatchPolicy>(params.dD[l]) ); } else { return make_tuple( InternalStrideC{}, detail::get_epilogue_stride<DispatchPolicy>(params.dD[l]) ); } } else { return make_tuple( detail::get_epilogue_stride<DispatchPolicy>(params.dC), detail::get_epilogue_stride<DispatchPolicy>(params.dD) ); } }();
// Get the residual tensor for the current batch ElementC const* ptr_C_l = nullptr; if (epilogue_op.is_source_needed()) { ptr_C_l = params.ptr_C[l_coord]; }
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mC = make_tensor(make_gmem_ptr(ptr_C_l), problem_shape_mnl, stride_c); // (M,N,L) Tensor mD = make_tensor(make_gmem_ptr(params.ptr_D[l_coord]), problem_shape_mnl, stride_d); // (M,N,L) Tensor gC = local_tile(mC, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) Tensor gD = local_tile(mD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N)
// Partition source and destination tiles according to tmem copy T2R partitioning (tTR_) auto tiled_t2r = make_tmem_copy(CopyOpT2R{}, tensor<0>(accumulators)); auto thread_idx = threadIdx.x % size(tiled_t2r);
auto thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_gC = thread_t2r.partition_D(gC); // (T2R,T2R_M,T2R_N) Tensor tTR_gD = thread_t2r.partition_D(gD); // (T2R,T2R_M,T2R_N) Tensor tTR_rAcc = make_tensor<ElementAccumulator>(shape(tTR_gD)); // (T2R,T2R_M,T2R_N)
Tensor tTR_rC = make_tensor<GmemElementC>(shape(tTR_gC)); // (T2R,T2R_M,T2R_N)
Tensor coordCD = make_identity_tensor(problem_shape_mnl); // (M,N,L) -> (m,n,l) Tensor cCD = local_tile(coordCD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) -> (m,n,l) Tensor tTR_cCD = thread_t2r.partition_D(cCD); // (T2R,T2R_M,T2R_N) -> (m,n,l)
constexpr auto mclD = decltype(max_common_layout(tTR_rAcc.layout(), tTR_gD.layout())){}; constexpr int VD = cute::min(AlignmentD{}, size(mclD)); Tensor tTR_rD_frag = make_tensor<ElementD>(shape(tTR_rAcc)); Tensor tTR_rD_src = recast<Array<ElementD, VD>>(coalesce(tTR_rD_frag)); Tensor tR2G_rD_dst = recast<Array<ElementD, VD>>(coalesce(tTR_gD));
Tensor tTR_cD_mn_frg = tensor<1>(zipped_divide(coalesce(tTR_cCD), mclD.compose(Int<VD>{}))); Tensor tDpD = make_tensor<bool>(shape(tR2G_rD_dst));
CUTLASS_PRAGMA_UNROLL for (int t = 0; t < size(tDpD); t++) { tDpD(t) = elem_less(tTR_cD_mn_frg(t), problem_shape_mnl); }
constexpr auto mclC = decltype(max_common_layout(tTR_rAcc.layout(), tTR_gC.layout())){}; constexpr int VC = cute::min(AlignmentC{}, size(mclC));
Tensor tTR_cC_mn_frg = tensor<1>(zipped_divide(coalesce(tTR_cCD), mclC.compose(Int<VC>{}))); Tensor tG2R_rC_dst = recast<Array<GmemElementC, VC>>(coalesce(tTR_gC)); Tensor tCpC = make_tensor<bool>(shape(tG2R_rC_dst));
CUTLASS_PRAGMA_UNROLL for (int t = 0; t < size(tCpC); t++) { tCpC(t) = elem_less(tTR_cC_mn_frg(t), problem_shape_mnl); } Tensor tTR_rC_src = recast<Array<GmemElementC, VC>>(coalesce(tTR_gC)); Tensor tTR_rC_dst = recast<Array<GmemElementC, VC>>(coalesce(tTR_rC));
// Detect interleaved complex fp32 kernels [[maybe_unused]] Tensor accs = accumulators; using ElementTmem = typename decltype(accs)::value_type; constexpr bool is_interleaved_complex_f32 = is_complex<ElementAccumulator>::value && cute::is_same_v<ElementTmem, float>;
// 1. Load accumulators into register from tmem // Tmem -> rmem and transformation for interleaved complex kernels if constexpr (is_interleaved_complex_f32) { using ElementComputeAccumulator = float;
Tensor tAccReal = accumulators(make_coord(_,_),_0{},_0{},_0{}); // (CTA_M,CTA_N) Tensor tAccImag = accumulators(make_coord(_,_),_0{},_0{},_1{}); // (CTA_M,CTA_N) Tensor tTR_tAccReal = thread_t2r.partition_S(tAccReal); // (T2R,T2R_M,T2R_N) Tensor tTR_tAccImag = thread_t2r.partition_S(tAccImag); // (T2R,T2R_M,T2R_N) Tensor tTR_rAccReal = make_tensor<ElementComputeAccumulator>(shape(tTR_gD)); // (T2R,T2R_M,T2R_N) Tensor tTR_rAccImag = make_tensor<ElementComputeAccumulator>(shape(tTR_gD)); // (T2R,T2R_M,T2R_N)
copy(tiled_t2r, tTR_tAccReal, tTR_rAccReal); copy(tiled_t2r, tTR_tAccImag, tTR_rAccImag);
// 1.1. Transform accumulators in registers CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rAccReal); i++) { tTR_rAcc(i) = {tTR_rAccReal(i), tTR_rAccImag(i)}; } }
// Standard tmem -> rmem epilogue else { Tensor tAcc = accumulators(make_coord(_,_),_0{},_0{}); // (CTA_M,CTA_N) Tensor tTR_tAcc = thread_t2r.partition_S(tAcc); // (T2R,T2R_M,T2R_N)
copy(tiled_t2r, tTR_tAcc, tTR_rAcc); }
cutlass::arch::fence_view_async_tmem_load(); acc_pipeline.consumer_release(acc_pipe_consumer_state); ++acc_pipe_consumer_state;
// 2. Apply element-wise operation and store to gmem // source is needed if (epilogue_op.is_source_needed()) { copy_if(tCpC, tTR_rC_src, tTR_rC_dst); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rAcc); i++) { tTR_rD_frag(i) = epilogue_op(tTR_rAcc(i), tTR_rC(i)); }
copy_if(tDpD, tTR_rD_src, tR2G_rD_dst); } // source is not needed, avoid load else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rAcc); i++) { tTR_rD_frag(i) = epilogue_op(tTR_rAcc(i)); }
copy_if(tDpD, tTR_rD_src, tR2G_rD_dst); }
return cute::make_tuple(acc_pipe_consumer_state); }
// API with Global Accumulator in registers for FastFP32 (emulated MMA) kernels. // The accumulator in TMEM periodically loaded into the registers so that the MMA can clear out the TMEM accumulator // values for better accuracy. This epilogue accepts the accumulator in registers and take TiledCopy for the // TMEM->Reg as a parameter to be used in partitioning GMEM tensors C and D. template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout, class TiledCopy > CUTLASS_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK cta_tile_shape_mnk, TileCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine, AccLayout>& tTR_rGlobAcc, // (MMA,MMA_M,MMA_N) [[maybe_unused]] SharedStorage&, TiledCopy tiled_t2r) {
using namespace cute; using X = Underscore;
static_assert(is_rmem<AccEngine>::value, "Accumulator must be Register resident."); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(AccLayout{}) == 5, "Accumulators must be copy-partitioned: (T2R,T2R_M,T2R_N,EPI_M,EPI_N)"); static_assert(rank(TileCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4");
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl); // Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl;
// Batches are managed by using appropriate pointers to C and D matrices auto problem_shape_mnl = append<3>(make_shape(M,N),Int<1>{}); auto cta_coord_mnl = append<3>(make_shape(m_coord, n_coord),Int<0>{}); auto cta_tiler = take<0,2>(cta_tile_shape_mnk);
ThreadEpilogueOp epilogue_op{params.thread}; // Get the residual tensor for the current batch ElementC const* ptr_C_l = nullptr; if (epilogue_op.is_source_needed()) { ptr_C_l = params.ptr_C[l_coord]; }
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mC = make_tensor(make_gmem_ptr(ptr_C_l), problem_shape_mnl, append<3>(params.dC,_0{})); // (M,N,L) Tensor mD = make_tensor(make_gmem_ptr(params.ptr_D[l_coord]), problem_shape_mnl, append<3>(params.dD,_0{})); // (M,N,L) Tensor gC = local_tile(mC, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) Tensor gD = local_tile(mD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N)
// Partition source and destination tiles according to tmem copy T2R partitioning (tTR_) auto thread_t2r = tiled_t2r.get_slice(threadIdx.x % size(tiled_t2r)); Tensor tTR_gC = thread_t2r.partition_D(gC); // (T2R,T2R_M,T2R_N) Tensor tTR_gD = thread_t2r.partition_D(gD); // (T2R,T2R_M,T2R_N)
Tensor coordD = make_identity_tensor(problem_shape_mnl); // (M,N,L) -> (m,n,l) Tensor cD = local_tile(coordD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) -> (m,n,l) Tensor tTR_cD = thread_t2r.partition_D(cD); // (T2R,T2R_M,T2R_N) -> (m,n,l)
// 2. Apply element-wise operation and store to gmem // source is needed if (epilogue_op.is_source_needed()) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rGlobAcc); ++i) { if (elem_less(tTR_cD(i), problem_shape_mnl)) { tTR_gD(i) = epilogue_op(tTR_rGlobAcc(i), tTR_gC(i)); } } } // source is not needed, avoid load else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rGlobAcc); ++i) { if (elem_less(tTR_cD(i), problem_shape_mnl)) { tTR_gD(i) = epilogue_op(tTR_rGlobAcc(i)); } } } }
protected: Params const& params;};
template < class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpT2R_, class AlignmentC_, class AlignmentD_>class CollectiveEpilogue< Sm100PtrArrayNoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpT2R_, AlignmentC_, AlignmentD_, cute::enable_if_t<not IsDefaultFusionOp<FusionCallbacks_>::value>> {public: // // Type Aliases // // Required by the gemm::kernel using DispatchPolicy = Sm100PtrArrayNoSmem; using ElementC = ElementC_; using ElementD = ElementD_; using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>,ElementD,ElementC>; // prevents void ref breakages using StrideC = StrideC_; using StrideD = StrideD_; using InternalStrideC = cute::remove_pointer_t<StrideC>; using InternalStrideD = cute::remove_pointer_t<StrideD>; using EpilogueTile = EpilogueTile_; using CopyOpT2R = CopyOpT2R_; using FusionCallbacks = FusionCallbacks_; using ThreadEpilogueOp = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::Operation;
using GmemTiledCopyC = void; using GmemTiledCopyD = void;
private: constexpr static bool IsReductionBufferNeeded = ThreadEpilogueOp::IsDePerRowBiasSupported || is_same_v<ThreadEpilogueOp, epilogue::fusion::FusionOperation>; // alloc reduction buffer for custom EVTs constexpr static size_t ImplicitSharedStorageSize = IsReductionBufferNeeded ? size(EpilogueTile{}) : 0;
// Not unroll epi subtile loop when the activation op is heavy to reduce instruction size and register pressure. constexpr static bool UnrollEpiLoop = not cutlass::epilogue::thread::kIsHeavy_member_or_false<typename ThreadEpilogueOp::ActivationFn>::value;
public: constexpr static int ThreadCount = 128; constexpr static uint32_t TmaTransactionBytes = 0;
struct SharedStorage { using FusionStorage = typename FusionCallbacks::SharedStorage; FusionStorage thread; array_aligned<uint8_t, ImplicitSharedStorageSize> buffer; };
// Host side epilogue arguments struct Arguments { typename FusionCallbacks::Arguments thread{}; ElementC const** ptr_C = nullptr; StrideC dC = {}; ElementD** ptr_D = nullptr; StrideD dD = {}; };
// Device side epilogue params struct Params { typename FusionCallbacks::Params thread{}; ElementC const** ptr_C = nullptr; StrideC dC = {}; ElementD** ptr_D = nullptr; StrideD dD = {}; };
// // Constructor and Data Members // CUTLASS_DEVICE CollectiveEpilogue(Params const& params_, SharedStorage& shared_tensors) : fusion_callbacks(params_.thread, shared_tensors.thread) , smem_buffer_ptr(shared_tensors.buffer.data()) , params(params_) {};
protected: FusionCallbacks fusion_callbacks; uint8_t* smem_buffer_ptr; Params const& params;
public:
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { return { FusionCallbacks::to_underlying_arguments(problem_shape, args.thread, workspace), args.ptr_C, args.dC, args.ptr_D, args.dD }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int /*sm_count*/ = 0) { return FusionCallbacks::get_workspace_size(problem_shape, args.thread); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return FusionCallbacks::initialize_workspace(problem_shape, args.thread, workspace, stream, cuda_adapter); }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) {
bool fusion_implementable = FusionCallbacks::can_implement(problem_shape, args.thread); if (!fusion_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum requirements for FusionCallbacks.\n"); } return fusion_implementable; }
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class AccEngine, class AccLayout > CUTLASS_DEVICE auto operator()( AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine,AccLayout> accumulators, [[maybe_unused]] SharedStorage& ) { using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
// Wait for mma warp to fill tmem buffer with accumulator results static_assert(is_tmem<AccEngine>::value, "Accumulator must be TMEM resident."); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(CtaCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4"); static_assert(cute::sizeof_bits_v<ElementD> != 6, "Output element requires smem");
auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl);
// Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl;
// Batches are managed by using appropriate pointers to C and D matrices auto problem_shape_mnl = append<3>(make_shape(M,N),Int<1>{}); auto cta_coord_mnl = append<3>(make_shape(m_coord, n_coord),Int<0>{}); auto cta_tiler = take<0,2>(cta_tile_mnk); auto cta_coord_mnk = cute::make_coord(m_coord, n_coord, k_coord, cute::Int<0>{});
bool is_C_load_needed = fusion_callbacks.is_C_load_needed();
auto [stride_c, stride_d] = [&, l = l_coord]() { if constexpr (!cute::is_same_v<InternalStrideC, StrideC>) { // If grouped gemm if (is_C_load_needed) { return make_tuple( detail::get_epilogue_stride<DispatchPolicy>(params.dC[l]), detail::get_epilogue_stride<DispatchPolicy>(params.dD[l]) ); } else { return make_tuple( InternalStrideC{}, detail::get_epilogue_stride<DispatchPolicy>(params.dD[l]) ); } } else { return make_tuple( detail::get_epilogue_stride<DispatchPolicy>(params.dC), detail::get_epilogue_stride<DispatchPolicy>(params.dD) ); } }();
// Get the residual tensor for the current batch ElementC const* ptr_C_l = nullptr; if (is_C_load_needed) { ptr_C_l = params.ptr_C[l_coord]; }
int thread_idx = threadIdx.x % ThreadCount;
Tensor tAcc = accumulators(make_coord(_,_),_0{},_0{}); // (CTA_M,CTA_N) Tensor tAcc_epi = flat_divide(tAcc, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) TiledCopy tiled_t2r = make_tmem_copy(CopyOpT2R{}, tAcc_epi(_,_,_0{},_0{})); ThrCopy thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_tAcc = thread_t2r.partition_S(tAcc_epi); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N)
constexpr int FragmentSize = size(EpilogueTile{}) / ThreadCount;
Tensor coordD = make_identity_tensor(problem_shape_mnl); // (M,N,L) -> (m,n,l) Tensor cD = local_tile(coordD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) -> (m,n,l) Tensor cD_epi = flat_divide(cD, EpilogueTile{}); Tensor tTR_cD = thread_t2r.partition_D(cD_epi); // (T2R,T2R_M,T2R_N) -> (m,n,l)
Tensor tTR_rAcc = make_tensor<ElementAccumulator>(shape(tTR_cD(_,_,_,_0{},_0{})));
// Construct the EVT consumer callbacks auto residue_cD = make_coord(M,N) - cD(_0{}); auto residue_tTR_cD = make_coord(M,N) - tTR_cD(_0{}); Tensor cD_ = make_coord_tensor(cD.layout()); Tensor tTR_cD_ = make_coord_tensor(tTR_cD.layout()); constexpr bool RefSrc = false;
Tensor mC = make_tensor(make_gmem_ptr<GmemElementC>(ptr_C_l), problem_shape_mnl, stride_c);
Tensor tTR_gC = cutlass::epilogue::fusion::sm90_partition_for_epilogue<RefSrc>( mC, cta_tile_mnk, cta_coord_mnk, EpilogueTile{}, tiled_t2r, thread_idx);
Tensor mD = make_tensor(make_gmem_ptr(recast_ptr<ElementD>(params.ptr_D[l_coord])), problem_shape_mnl, stride_d);
Tensor tTR_gD = cutlass::epilogue::fusion::sm90_partition_for_epilogue<RefSrc>( mD, cta_tile_mnk, cta_coord_mnk, EpilogueTile{}, tiled_t2r, thread_idx);
// Register Tensor Tensor tTR_rD = make_tensor<ElementD>(take<0,3>(shape(tTR_gD)));
Tensor coord_cCD = make_identity_tensor(problem_shape_mnl); Tensor tTR_cCD = cutlass::epilogue::fusion::sm90_partition_for_epilogue<RefSrc>( coord_cCD, cta_tile_mnk, cta_coord_mnk, EpilogueTile{}, tiled_t2r, thread_idx); constexpr auto mclD = decltype(max_common_layout(tTR_gD(_,_,_,_0{},_0{}), tTR_rD)){}; constexpr int VD = cute::min(AlignmentD_{}, size(mclD));
auto tCrC = make_tensor<GmemElementC>(take<0,3>(shape(tTR_gC))); constexpr auto mclC = decltype(max_common_layout(tTR_gC(_,_,_,_0{},_0{}), tCrC)){}; constexpr int VC = cute::min(AlignmentC_{}, size(mclC));
Tensor tTR_rD_frg = recast<Array<ElementD, FragmentSize>>(coalesce(tTR_rD));
auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, int(0), EpilogueTile{}, tiled_t2r, cD_, residue_cD, tTR_cD_, residue_tTR_cD, tCrC, thread_idx };
auto synchronize = [] () CUTLASS_LAMBDA_FUNC_INLINE { cutlass::arch::NamedBarrier::sync(ThreadCount, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// The Epilogue Loop auto epi_loop_fn = [&] (auto& cst_callbacks) CUTLASS_LAMBDA_FUNC_INLINE { // Ensure there are no threads from the previous wave writing to shared memory being utilized for the current wave. synchronize(); cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// If tmem doesn't have enough capacity to support double buffering, a portion of tmem (a column of epilogue tiles) // is overlapped between 2 pseudo-buffers. The shared tmem portion corresponds to the last epilogue tile column of // tmem accumulator buffer 0, and the first epilogue tile column of tmem accumulator 1. // Thus, whenever we are processing tmem accumulator buffer 0, we process the epilogue tiles with reversed column order. // Once the last epilogue tile column is loaded from tmem, the acc_pipeline is released. // Then, the next accumulation stage for buffer 1 can start. [[maybe_unused]] bool reverse_epi_n = ReuseTmem && acc_pipe_consumer_state.phase() == 0; static_assert(not (ReuseTmem && AccumulatorPipeline::Stages != 1), "Tmem reuse requires 1 accumulator stage");
// For each epilogue subtile within the CTA tile constexpr int NumEpiSubtilesN = CUTE_STATIC_V(size<4>(tTR_tAcc)); constexpr int NumEpiSubtilesM = CUTE_STATIC_V(size<3>(tTR_tAcc)); // Lambda to process a single epilogue tile auto process_tile = [&](int epi_m, int epi_n, int iter_m, int iter_n) CUTLASS_LAMBDA_FUNC_INLINE { bool is_last_iteration = iter_m == NumEpiSubtilesM-1 && iter_n == NumEpiSubtilesN-1; bool do_acc_release = is_last_iteration;
// Adjust release condition for tmem reuse if constexpr (ReuseTmem) { do_acc_release = iter_m == NumEpiSubtilesM-1 && iter_n == 0; // Release on first N iteration }
Tensor tTR_cCD_mn = tTR_cCD(_,_,_,epi_m,epi_n); Tensor tTR_pCD_mn = cute::lazy::transform(tTR_cCD_mn, [&] (auto const& c) CUTLASS_LAMBDA_FUNC_INLINE { return elem_less(c, problem_shape_mnl); }); cst_callbacks.begin_loop(epi_m, epi_n);
if constexpr (not cute::is_void_v<ElementC>) { if (is_C_load_needed) { using CVecType = uint_bit_t<VC * sizeof_bits_v<ElementC>>;
if constexpr (!is_same_v<CVecType, uint256_t>) { Tensor tTR_gC_frg = recast<CVecType>(coalesce(tTR_gC(_,_,_,epi_m,epi_n))); Tensor tTR_rC_frg = recast<CVecType>(coalesce(tCrC)); Tensor tTR_pC_frg = tensor<1>(zipped_divide(coalesce(tTR_pCD_mn), mclC.compose(Int<VC>{}))); copy_if(tTR_pC_frg, tTR_gC_frg, tTR_rC_frg); } else { auto tiled_g2r = make_tiled_copy_D(Copy_Atom<SM100_LOAD_256bit_CACHE_NOALLOCATION, ElementC>{}, tiled_t2r); auto thr_g2r = tiled_g2r.get_slice(threadIdx.x); Tensor c_src = thr_g2r.retile_S(tTR_gC(_,_,_,epi_m,epi_n)); Tensor c_dst = thr_g2r.retile_D(tCrC); Tensor c_prd = thr_g2r.retile_D(tTR_pCD_mn); copy_if(tiled_g2r, c_prd, c_src, c_dst); } } }
// Copy accumulator tile from tmem to register // The current tile in tmem Tensor tTR_tAcc_mn = tTR_tAcc(_,_,_,epi_m,epi_n);
Tensor tTR_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(coalesce(tTR_rAcc));
copy(tiled_t2r, tTR_tAcc_mn, tTR_rAcc);
// After the last tmem load, signal that tmem buffer is consumed and empty if (do_acc_release) { cutlass::arch::fence_view_async_tmem_load(); acc_pipeline.consumer_release(acc_pipe_consumer_state); ++acc_pipe_consumer_state; }
CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tTR_rAcc_frg); ++epi_v) { tTR_rD_frg(epi_v) = cst_callbacks.visit(tTR_rAcc_frg(epi_v), epi_v, epi_m, epi_n); }
Tensor reduction_buffer = make_tensor( raw_pointer_cast(make_smem_ptr(smem_buffer_ptr)), make_layout(Shape<Int<ImplicitSharedStorageSize>>{}));
cst_callbacks.reduce(reduction_buffer, synchronize, epi_m, epi_n, is_last_iteration, tTR_rAcc /*not used*/);
cst_callbacks.end_loop(epi_m, epi_n);
using VecType = uint_bit_t<VD * sizeof_bits_v<ElementD>>; if constexpr (!is_same_v<VecType, uint256_t>) { Tensor tTR_gD_frg = recast<VecType>(coalesce(tTR_gD(_,_,_,epi_m,epi_n))); Tensor tTR_rD_frg = recast<VecType>(coalesce(tTR_rD)); Tensor tTR_pD_frg = tensor<1>(zipped_divide(coalesce(tTR_pCD_mn), mclD.compose(Int<VD>{}))); copy_if(tTR_pD_frg, tTR_rD_frg, tTR_gD_frg); } else { auto tiled_r2g = make_tiled_copy_D(Copy_Atom<SM100_STORE_256bit_CACHE_NOALLOCATION, ElementD>{}, tiled_t2r); auto thr_r2g = tiled_r2g.get_slice(threadIdx.x); Tensor src = thr_r2g.retile_S(tTR_rD); Tensor dst = thr_r2g.retile_D(tTR_gD(_,_,_,epi_m,epi_n)); Tensor prd = thr_r2g.retile_D(tTR_pCD_mn); copy_if(tiled_r2g, prd, src, dst); } };
// Use static iteration with appropriate ordering // When ReuseTmem is true and reverse_epi_n is true, we need reverse N iteration auto n_seq = cute::make_int_sequence<NumEpiSubtilesN>{}; auto m_seq = cute::make_int_sequence<NumEpiSubtilesM>{}; if constexpr (UnrollEpiLoop) { // Fully unrolled static iteration cute::for_each(n_seq, [&](auto I_N) CUTLASS_LAMBDA_FUNC_INLINE { constexpr int iter_n = I_N; int epi_n = iter_n; if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = NumEpiSubtilesN - 1 - iter_n; // Reverse N iteration } } cute::for_each(m_seq, [&](auto I_M) CUTLASS_LAMBDA_FUNC_INLINE { constexpr int iter_m = I_M; process_tile(iter_m, epi_n, iter_m, iter_n); }); }); } else { // Runtime loop with pragma unroll(1) #pragma unroll 1 for (int iter_n = 0; iter_n < NumEpiSubtilesN; ++iter_n) { int epi_n = iter_n; if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = NumEpiSubtilesN - 1 - iter_n; // Reverse N iteration } } #pragma unroll 1 for (int iter_m = 0; iter_m < NumEpiSubtilesM; ++iter_m) { process_tile(iter_m, epi_n, iter_m, iter_n); } } }
cst_callbacks.end(); };
// // BEGIN EPILOGUE // auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); epi_loop_fn(cst_callbacks); return cute::make_tuple(acc_pipe_consumer_state); }
};
/////////////////////////////////////////////////////////////////////////////////////////////////
// For sm100 kernels requiring warp specialized epiloguestemplate < class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class ThreadEpilogueOp_, class CopyOpT2R_, class AlignmentC, class AlignmentD>class CollectiveEpilogue< Sm100PtrArrayNoSmemWarpSpecialized, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC, AlignmentD> : public detail::Sm100TmaWarpSpecializedAdapter<CollectiveEpilogue< Sm100PtrArrayNoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC, AlignmentD, void>>{public: // ctor inheritance using detail::Sm100TmaWarpSpecializedAdapter<CollectiveEpilogue< Sm100PtrArrayNoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC, AlignmentD, void>>::Sm100TmaWarpSpecializedAdapter;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Functor performing elementwise operations used by Ptr-Array and Grouped Gemm epilogue.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/arch/barrier.h"#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/collective/detail.hpp"#include "cutlass/epilogue/thread/scale_type.h"#include "cutlass/epilogue/fusion/callbacks.hpp"#include "cutlass/epilogue/fusion/sm100_callbacks_tma_warpspecialized.hpp"#include "cutlass/detail/layout.hpp"#include "cutlass/trace.h"
#include "cute/tensor.hpp"#include "cutlass/cuda_host_adapter.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_, class CtaTileShape_, // (CTA_M,CTA_N,CTA_K) class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpT2R_, class CopyOpG2S_, class SmemLayoutAtomC_, class CopyOpS2R_, class CopyOpS2G_, class SmemLayoutAtomD_, class CopyOpR2S_, class CopyOpR2R_>class CollectiveEpilogue< Sm100PtrArrayTmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, ReuseSmemC_, DelayTmaStore_>, CtaTileShape_, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpT2R_, CopyOpG2S_, SmemLayoutAtomC_, CopyOpS2R_, CopyOpS2G_, SmemLayoutAtomD_, CopyOpR2S_, CopyOpR2R_> {public: // // Type Aliases // using DispatchPolicy = Sm100PtrArrayTmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, ReuseSmemC_, DelayTmaStore_>; using CtaTileShape = CtaTileShape_; using EpilogueTile = EpilogueTile_; using FusionCallbacks = FusionCallbacks_; using ElementC = ElementC_; using StrideC = StrideC_; using InternalStrideC = cute::remove_pointer_t<StrideC>; using ElementD = ElementD_; using StrideD = StrideD_; using InternalStrideD = cute::remove_pointer_t<StrideD>; using CopyOpT2R = CopyOpT2R_; using CopyOpG2S = CopyOpG2S_; using SmemLayoutAtomC = SmemLayoutAtomC_; using CopyOpS2R = CopyOpS2R_; using CopyOpS2G = CopyOpS2G_; using SmemLayoutAtomD = SmemLayoutAtomD_; using CopyOpR2S = CopyOpR2S_; using CopyOpR2R = CopyOpR2R_;
using ThreadEpilogueOp = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::Operation; using GmemTiledCopyC = CopyOpG2S; using GmemTiledCopyD = CopyOpS2G;
constexpr static int ThreadCount = 128;
static_assert(!is_layout<EpilogueTile>::value && is_tuple<EpilogueTile>::value, "EpilogueTile must be a cute::Tile or cute::Shape"); static_assert(rank(EpilogueTile{}) == 2, "EpilogueTile must be rank-2: [EPI_TILE_M, EPI_TILE_N]");
private:
constexpr static bool is_source_supported = not cute::is_void_v<ElementC>; constexpr static bool is_destination_supported = not cute::is_void_v<ElementD>; using GmemElementD = cute::conditional_t<is_destination_supported, ElementD, fusion::get_element_aux_t<FusionCallbacks>>; using GmemElementC = cute::conditional_t<is_source_supported, ElementC, GmemElementD>; // prevents void ref breakages static_assert(not cute::is_void_v<GmemElementD>, "GmemElementD is void");
using SmemElementD = typename cutlass::detail::get_unpacked_element_type<GmemElementD>::type; using SmemElementC = typename cutlass::detail::get_unpacked_element_type<GmemElementC>::type; constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; static_assert(StagesC >= 1, "StagesC must be >= 1"); static_assert(StagesD >= 1, "StagesD must be >= 1"); constexpr static bool ReuseSmemC = ReuseSmemC_ && is_destination_supported;
constexpr static bool is_m_major_C = detail::is_m_major<InternalStrideC>(); constexpr static bool is_m_major_D = detail::is_m_major<InternalStrideD>();
using SmemLayoutStageC = decltype(tile_to_shape(SmemLayoutAtomC{}, product_each(shape(EpilogueTile{})), cute::conditional_t<is_m_major_C, Step<_2,_1>, Step<_1,_2>>{} )); using SmemLayoutStageD = decltype(tile_to_shape(SmemLayoutAtomD{}, product_each(shape(EpilogueTile{})), cute::conditional_t<is_m_major_D, Step<_2,_1>, Step<_1,_2>>{} ));
constexpr static int StageCBits = cosize_v<SmemLayoutStageC> * sizeof_bits_v<SmemElementC>; constexpr static int StageDBits = cosize_v<SmemLayoutStageD> * sizeof_bits_v<SmemElementD>; constexpr static int MaxStageBits = cute::max(StageCBits, StageDBits); constexpr static int StrideStageC = (ReuseSmemC ? MaxStageBits : StageCBits) / sizeof_bits_v<SmemElementC>; constexpr static int StrideStageD = (ReuseSmemC ? MaxStageBits : StageDBits) / sizeof_bits_v<SmemElementD>;
using SmemLayoutC = decltype(cute::append<3>(SmemLayoutStageC{}, Layout<Int<StagesC>, Int<StrideStageC>>{})); using SmemLayoutD = decltype(cute::append<3>(SmemLayoutStageD{}, Layout<Int<ReuseSmemC ? StagesC : StagesD>, Int<StrideStageD>>{}));
constexpr static bool support_smem_reuse = is_source_supported && is_destination_supported && StagesD <= StagesC && MaxStageBits % sizeof_bits_v<SmemElementC> == 0 && MaxStageBits % sizeof_bits_v<SmemElementD> == 0; static_assert(not (ReuseSmemC && not support_smem_reuse), "Smem reuse requirements not met");
constexpr static size_t SmemAlignmentC = cutlass::detail::alignment_for_swizzle(SmemLayoutC{}); constexpr static size_t SmemAlignmentD = cutlass::detail::alignment_for_swizzle(SmemLayoutD{}); constexpr static size_t MaxSmemAlignment = cute::max(SmemAlignmentC, SmemAlignmentD);
// Not unroll epi subtile loop when the activation op is heavy to reduce instruction size and register pressure. constexpr static bool UnrollEpiLoop = not cutlass::epilogue::thread::kIsHeavy_member_or_false<typename ThreadEpilogueOp::ActivationFn>::value; // TMA store delay only benefits with loop unrolling constexpr static bool DelayTmaStore = DelayTmaStore_ and UnrollEpiLoop;
struct CollectiveStorageWithC { alignas(SmemAlignmentC) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageWithoutC { cute::array<SmemElementC, 0> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageReuseC { alignas(MaxSmemAlignment) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(MaxSmemAlignment) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
public: // TMA pipeline for loading C using LoadPipeline = cutlass::PipelineTransactionAsync<StagesC>; using LoadPipelineState = cutlass::PipelineState<StagesC>; constexpr static uint32_t TmaTransactionBytes = StageCBits / 8; constexpr static uint32_t MinTensorMapWorkspaceAlignment = 64;
// TMA pipeline for storing D using StorePipeline = cute::conditional_t<ReuseSmemC, cutlass::PipelineTmaStore<StagesC, StagesD-1>, cutlass::PipelineTmaStore<StagesD>>; using StorePipelineState = cutlass::PipelineState<ReuseSmemC ? StagesC : StagesD>;
struct SharedStorage { struct TensorStorage { using CollectiveStorage = cute::conditional_t<not is_source_supported, CollectiveStorageWithoutC, cute::conditional_t<ReuseSmemC, CollectiveStorageReuseC, CollectiveStorageWithC>>; CollectiveStorage collective;
using FusionStorage = typename FusionCallbacks::SharedStorage; FusionStorage thread; } tensors;
struct TensorMapStorage : cute::aligned_struct<128, _0> { cute::TmaDescriptor smem_tensormap_C; cute::TmaDescriptor smem_tensormap_D; } tensormaps;
using PipelineStorage = typename LoadPipeline::SharedStorage; PipelineStorage pipeline; }; using TensorStorage = typename SharedStorage::TensorStorage; using TensorMapStorage = typename SharedStorage::TensorMapStorage; using PipelineStorage = typename SharedStorage::PipelineStorage;
// Planar complex kernels have two accumulator copies for the real and imaginary tensors. constexpr static int NumAccumulatorMtxs = 1;
static constexpr bool IsGroupedGemmKernel = !cute::is_same_v<InternalStrideD, StrideD>;
// Host side epilogue arguments struct Arguments { typename FusionCallbacks::Arguments thread{}; ElementC const** ptr_C = nullptr; StrideC dC{}; ElementD** ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params struct Params { using TensorShapeC = decltype(repeat_like(append<3>(StrideC{}, _1{}), int32_t(0))); using TensorShapeD = decltype(repeat_like(append<3>(StrideD{}, _1{}), int32_t(0))); using TMA_C = decltype(make_tma_copy( CopyOpG2S{}, make_tensor( make_gmem_ptr(static_cast<GmemElementC const*>(nullptr)), TensorShapeC{}, append<3>(InternalStrideC{}, _0{})), SmemLayoutStageC{}, EpilogueTile{}, _1{})); using TMA_D = decltype(make_tma_copy( CopyOpS2G{}, make_tensor( make_gmem_ptr(static_cast<GmemElementD*>(nullptr)), TensorShapeD{}, append<3>(InternalStrideD{}, _0{})), SmemLayoutStageD{}, EpilogueTile{}, _1{}));
typename FusionCallbacks::Params thread{}; TMA_C tma_load_c; TMA_D tma_store_d; cute::TmaDescriptor* tensormaps; ElementC const** ptr_C; StrideC dC; ElementD** ptr_D; StrideD dD; };
// // Gemm Host Functions //
template <class ProblemShape> static constexpr Params to_underlying_arguments( ProblemShape const& problem_shape, Arguments const& args, void* workspace) { // These tensor shapes (only applicable for grouped gemm) and pointers are only used to create tensormap/tma desc. // These will be replaced with correct values before the initial tma load. auto init_M = int32_t(size<0>(CtaTileShape{})); auto init_N = int32_t(size<1>(CtaTileShape{})); auto init_L = 1;
InternalStrideC stride_c; InternalStrideD stride_d; if constexpr (IsGroupedGemmKernel) { // Strides for Grouped Gemm will be replaced prior to the first access regardless. stride_c = InternalStrideC{}; stride_d = InternalStrideD{}; } else { // Tensor shapes for Ptr-Array are initialized correctly only here. auto problem_shape_MNKL = append<4>(problem_shape.get_host_problem_shape(0), 1); init_M = get<0>(problem_shape_MNKL); init_N = get<1>(problem_shape_MNKL);
stride_c = args.dC; stride_d = args.dD; }
typename Params::TMA_C tma_load_c{}; if constexpr (is_source_supported) { // Tensor pointers will be fixed before the first access ElementC const* ptr_C_first_batch = nullptr; Tensor tensor_c = make_tensor(ptr_C_first_batch, make_layout(make_shape(init_M,init_N,init_L), append<3>(stride_c, _0{}))); tma_load_c = make_tma_copy(CopyOpG2S{}, tensor_c, SmemLayoutStageC{}, EpilogueTile{}, _1{}); }
typename Params::TMA_D tma_store_d{}; if constexpr (is_destination_supported) { // Tensor pointers will be fixed before the first access ElementD* ptr_D_first_batch = nullptr; Tensor tensor_d = make_tensor(ptr_D_first_batch, make_layout(make_shape(init_M,init_N,init_L), append<3>(stride_d, _0{}))); tma_store_d = make_tma_copy(CopyOpS2G{}, tensor_d, SmemLayoutStageD{}, EpilogueTile{}, _1{}); }
auto fusion_workspace = static_cast<char*>(workspace); auto fusion_workspace_size = round_nearest(FusionCallbacks::get_workspace_size(problem_shape, args.thread), MinTensorMapWorkspaceAlignment); auto tma_descriptor_workspace = reinterpret_cast<cute::TmaDescriptor*>( static_cast<char*>(workspace) + fusion_workspace_size);
return { FusionCallbacks::to_underlying_arguments(problem_shape, args.thread, fusion_workspace), tma_load_c, tma_store_d, tma_descriptor_workspace, args.ptr_C, args.dC, args.ptr_D, args.dD }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int sm_count) { constexpr uint32_t NumInputTensors = cute::is_void_v<ElementC> ? 1 : 2; constexpr size_t SizeOfCuTensorMap = sizeof(cute::TmaDescriptor); // Allocate gmem space for input tensormaps per each SM, A tensormap copies followed by B tensormap copies return (NumInputTensors * SizeOfCuTensorMap * sm_count) + (round_nearest(FusionCallbacks::get_workspace_size(problem_shape, args.thread), MinTensorMapWorkspaceAlignment)); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return FusionCallbacks::initialize_workspace(problem_shape, args.thread, workspace, stream, cuda_adapter); }
template <class ProblemShape> static bool can_implement( ProblemShape problem_shape, [[maybe_unused]] Arguments const& args) { bool implementable = true; bool fusion_implementable = true;
if (problem_shape.is_host_problem_shape_available()) { for (int i = 0; i < problem_shape.groups(); ++i) { auto problem_shape_MNKL = append<4>(problem_shape.get_host_problem_shape(i), 1); auto [M,N,K,L] = problem_shape_MNKL;
if constexpr (is_destination_supported) { constexpr int tma_alignment_bits_D = cutlass::detail::get_output_alignment_bits<ElementD>(); constexpr int min_tma_aligned_elements_D = tma_alignment_bits_D / cutlass::sizeof_bits<ElementD>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_D>(cute::make_shape(M,N,L), InternalStrideD{}); }
if constexpr (is_source_supported) { constexpr int tma_alignment_bits_C = cutlass::detail::get_input_alignment_bits<ElementC>(); constexpr int min_tma_aligned_elements_C = tma_alignment_bits_C / cutlass::sizeof_bits<ElementC>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_C>(cute::make_shape(M,N,L), InternalStrideC{}); }
fusion_implementable = fusion_implementable && FusionCallbacks::can_implement(problem_shape_MNKL, args.thread); } } else { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Ignoring check to can implement because host problem shape is not available.\n"); }
if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); }
if (!fusion_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum requirements for FusionCallbacks.\n"); }
bool beta_implementable = true;
if (cute::is_void_v<ElementC> || args.ptr_C == nullptr) { if constexpr (detail::has_beta<Arguments>::value) { beta_implementable = args.thread.beta == 0.0; } if constexpr (detail::has_beta_ptr<Arguments>::value) { beta_implementable = beta_implementable && args.thread.beta_ptr == nullptr; } if constexpr (detail::has_beta_ptr_array<Arguments>::value) { beta_implementable = beta_implementable && args.thread.beta_ptr_array == nullptr; } }
if (!beta_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Beta/beta pointer was set, but epilogue is sourceless (void-C).\n"); }
return implementable && fusion_implementable && beta_implementable; }
// // Static Device Functions //
template<class CtaTileMNK> CUTLASS_DEVICE static constexpr int get_load_pipe_increment(CtaTileMNK const& cta_tile_mnk) { // Compute number of epilogue subtiles return size<1>(zipped_divide(make_layout(take<0,2>(cta_tile_mnk)), EpilogueTile{})); }
template<class CtaTileMNK> CUTLASS_DEVICE static constexpr int get_store_pipe_increment(CtaTileMNK const& cta_tile_mnk) { return get_load_pipe_increment(cta_tile_mnk); }
// // Constructor and Data Members // CUTLASS_DEVICE CollectiveEpilogue(Params const& params_, TensorStorage& shared_tensors) : params(params_), fusion_callbacks(params_.thread, shared_tensors.thread) {}
private: Params const& params; FusionCallbacks fusion_callbacks;
// // Non-static Device Functions //public: CUTLASS_DEVICE bool is_producer_load_needed() const { return fusion_callbacks.is_producer_load_needed(); }
CUTLASS_DEVICE auto load_init( Params const& params, TensorMapStorage& shared_tensormap, int32_t const sm_count, int32_t const sm_idx) const { // Fetch a copy of tensormaps for the CTA from Params constexpr bool IsEpiLoad = true; auto load_tensormap = tensormaps_init<IsEpiLoad>(params, shared_tensormap, sm_count, sm_idx); return cute::make_tuple(load_tensormap); }
template< bool ReuseTmem = false, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class TensorMapC > CUTLASS_DEVICE auto load( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, TensorStorage& shared_tensors, cute::tuple<TensorMapC, bool> load_tensormap_info, bool reverse_epi_n = false) { using namespace cute;
// Check to see if tensormaps have been replaced in gmem if (get<1>(load_tensormap_info) /* did_batch_change */) { tensormaps_fence_acquire<true /* IsEpiLoad */>(get<0>(load_tensormap_info)); }
int lane_idx = canonical_lane_idx(); auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl;
auto coord_shape = append<3>(make_shape(m_coord, n_coord),Int<0>{});
// Represent the full source tensor, slice to get the tile this CTA is currently responsible for Tensor mC_mn = params.tma_load_c.get_tma_tensor(append<3>(make_shape(M,N),Int<1>{})); // (M,N,L) Tensor mC = coalesce(mC_mn, take<0,2>(cta_tile_mnk)); Tensor gC = local_tile(mC, take<0,2>(cta_tile_mnk), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtile, get matching smem tensor auto ptr_sC = shared_tensors.collective.smem_C.begin(); Tensor gC_epi = flat_divide(gC, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor sC_epi = make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{}); // (EPI_TILE_M,EPI_TILE_N,PIPE_C)
// Prepare the thread(b)lock's (G)mem to (S)mem TMA tiled copy (bGS_) ThrCopy thrblk_g2s = params.tma_load_c.get_slice(Int<0>{}); Tensor bGS_gC = thrblk_g2s.partition_S(gC_epi); // (TMA,TMA_M,TMA_N,EPI_M,EPI_N) Tensor bGS_sC = thrblk_g2s.partition_D(sC_epi); // (TMA,TMA_M,TMA_N,PIPE_C)
// Get the fusion callbacks for the producer load warp auto pld_args = cutlass::epilogue::fusion::detail::ProducerLoadArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tiled_mma, EpilogueTile{}, lane_idx }; auto pld_callbacks = fusion_callbacks.get_producer_load_callbacks(pld_args); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// Predication for TMA load (one thread issues TMA load) bool issue_tma_load = cute::elect_one_sync();
// Pre-loop fusion callback entry point pld_callbacks.begin();
CUTLASS_PRAGMA_UNROLL for (int iter_n = 0; iter_n < size<3>(gC_epi); ++iter_n) { CUTLASS_PRAGMA_UNROLL for (int iter_m = 0; iter_m < size<2>(gC_epi); ++iter_m) { int epi_m = iter_m, epi_n = iter_n; if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = size<3>(gC_epi) - 1 - iter_n; } } // Acquire the lock for this stage constexpr uint16_t mcast_mask = 0; uint64_t* tma_barrier = load_pipeline.producer_get_barrier(load_pipe_producer_state); load_pipeline.producer_acquire(load_pipe_producer_state);
// Execute the TMA load for C if needed if (issue_tma_load && is_C_load_needed) { copy(params.tma_load_c.with(get<0>(load_tensormap_info), *tma_barrier, mcast_mask), bGS_gC(_,_,_,epi_m,epi_n), bGS_sC(_,_,_,load_pipe_producer_state.index())); load_pipeline.producer_expect_transaction(load_pipe_producer_state); }
// Loop fusion callback entry point pld_callbacks.step(tma_barrier, epi_m, epi_n, load_pipe_producer_state.count(), issue_tma_load);
// Commit TMA loads for this stage and release the lock load_pipeline.producer_commit(load_pipe_producer_state); ++load_pipe_producer_state; } }
// Post-loop fusion callback entry point pld_callbacks.end();
return load_pipe_producer_state; }
CUTLASS_DEVICE void load_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, [[maybe_unused]] StorePipeline store_pipeline, [[maybe_unused]] StorePipelineState store_pipe_producer_state) { load_pipeline.producer_tail(load_pipe_producer_state); }
CUTLASS_DEVICE auto store_init( Params const& params, TensorMapStorage& shared_tensormap, int32_t const sm_count, int32_t const sm_idx) const { // Fetch a copy of tensormaps for the CTA from Params constexpr bool IsEpiLoad = false; cute::TmaDescriptor* store_tensormap = nullptr; int thread_idx = threadIdx.x % ThreadCount; int warp_idx = thread_idx / NumThreadsPerWarp; // Only the first epilogue warp needs to perform TMA related operations if (warp_idx == 0) { store_tensormap = tensormaps_init<IsEpiLoad>(params, shared_tensormap, sm_count, sm_idx); } return cute::make_tuple(store_tensormap); }
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout, class TensorMapD > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine,AccLayout> accumulators, TensorStorage& shared_tensors, cute::tuple<TensorMapD, bool> store_tensormap_info ) { using namespace cute; using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
static_assert(is_tmem<AccEngine>::value, "Accumulator must be TMEM resident."); static_assert(rank(accumulators) == 3, "Accumulators must be MMA-partitioned: [MMA, MMA_M, MMA_N]"); static_assert(size<1>(accumulators) == 1 && size<2>(accumulators) == 1, "TiledMMA must match partitioned ShapeMN"); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(CtaCoordMNKL{}) == 4, "CoordMNKL must be rank 4");
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl; int thread_idx = threadIdx.x % ThreadCount; int warp_idx = thread_idx / NumThreadsPerWarp; [[maybe_unused]] int lane_idx = thread_idx % NumThreadsPerWarp;
// Check to see if tensormaps have been replaced in gmem // Only the first epilogue warp needs to perform TMA related operations if (get<1>(store_tensormap_info) /* did_batch_change */ && warp_idx == 0) { tensormaps_fence_acquire<false /* IsEpiLoad */>(get<0>(store_tensormap_info)); }
auto coord_shape = append<3>(make_shape(m_coord, n_coord),Int<0>{});
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mD_mn = params.tma_store_d.get_tma_tensor(append<3>(make_shape(M,N),Int<1>{})); // (M,N,L) Tensor mD = coalesce(mD_mn, take<0,2>(cta_tile_mnk)); Tensor gD = local_tile(mD, take<0,2>(cta_tile_mnk), coord_shape); // (CTA_M,CTA_N)
Tensor tAcc = accumulators(make_coord(_,_),_0{},_0{}); // (CTA_M,CTA_N)
// Apply epilogue subtiling Tensor tAcc_epi = flat_divide(tAcc, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor gD_epi = flat_divide( gD, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
// Construct the corresponding pipelined smem tensors auto ptr_sC = shared_tensors.collective.smem_C.begin(); auto ptr_sD = shared_tensors.collective.smem_D.begin(); Tensor sC_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_C) Tensor sD_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sD), SmemLayoutD{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_D)
// (t)hread-partition for (t)mem to (r)egister copy (tTR_) TiledCopy tiled_t2r = make_tmem_copy(CopyOpT2R{}, tAcc_epi(_,_,_0{},_0{})); ThrCopy thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_tAcc = thread_t2r.partition_S(tAcc_epi); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) Tensor tTR_sD = thread_t2r.partition_D(sD_epi(_,_,_0{})); // (T2R,T2R_M,T2R_N)
// Allocate D and accumulator registers // Does directly store the visitor into smem. constexpr bool IsDirectR2S = cute::is_same_v<CopyOpR2R, AutoVectorizingCopyWithAssumedAlignment<128>>; using RegisterElementD = cute::conditional_t<!IsDirectR2S, ElementCompute, SmemElementD>; Tensor tTR_rAcc = make_tensor<ElementAccumulator>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N) Tensor tTR_rD = make_tensor<RegisterElementD>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N)
// Vectorized fragment view constexpr int FragmentSize = DispatchPolicy::FragmentSize; Tensor tTR_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(coalesce(tTR_rAcc)); // (EPI_V) Tensor tTR_rD_frg = recast<Array<RegisterElementD, FragmentSize>>(coalesce(tTR_rD)); // (EPI_V) CUTE_STATIC_ASSERT(size(tTR_rAcc) % DispatchPolicy::FragmentSize == 0, "Fragment size does not vectorize properly");
// (t)hread-partition for (s)mem to (r)egister copy (tSR_) TiledCopy tiled_s2r = make_tiled_copy_D(Copy_Atom<CopyOpS2R, SmemElementC>{}, tiled_t2r); ThrCopy thread_s2r = tiled_s2r.get_slice(thread_idx); Tensor tSR_sC = thread_s2r.partition_S(sC_epi); // (S2R,S2R_M,S2R_N,PIPE_C) Layout tSR_rC_layout = thread_s2r.retile_D(tTR_rD).layout(); // (S2R,S2R_M,S2R_N)
// Allocate C registers // If C smem load is a non-vectorized dst(i) = src(i) then we can allocate C registers directly in the compute type // to eliminate some redundant pack+unpack instruction sequences for sub-word types constexpr bool IsDirectS2R = cute::is_same_v<CopyOpS2R, AutoVectorizingCopyWithAssumedAlignment<128>> && decltype(max_common_vector(tSR_rC_layout, tSR_sC.layout()))::value <= 1; using RegisterElementC = cute::conditional_t<IsDirectS2R, ElementCompute, SmemElementC>; Tensor tTR_rC = make_tensor<RegisterElementC>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N) Tensor tSR_rC = thread_s2r.retile_D(tTR_rC); // (S2R,S2R_M,S2R_N)
// (t)hread-partition for (r)egister to (r)egister copy (tRR_) TiledCopy tiled_r2r = make_tiled_copy_D(Copy_Atom<CopyOpR2R, RegisterElementD>{}, tiled_t2r); ThrCopy thread_r2r = tiled_r2r.get_slice(thread_idx); Tensor tRR_rD_src = thread_r2r.retile_S(tTR_rD); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N) Tensor tRR_rD_dst = thread_r2r.retile_D(tTR_rD); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N)
// (t)hread-partition for (r)egister to (s)mem copy (tRS_) TiledCopy tiled_r2s = make_tiled_copy_D(Copy_Atom<CopyOpR2S, SmemElementD>{}, tiled_r2r); ThrCopy thread_r2s = tiled_r2s.get_slice(thread_idx); Tensor tRS_sD = thread_r2s.partition_D(sD_epi); // (R2S,R2S_M,R2S_N,PIPE_D) Tensor tRS_rD = [&]() { if constexpr (!IsDirectR2S) { return make_tensor<SmemElementD>(shape(tRS_sD(_,_,_,_0{}))); } else{ return thread_r2s.retile_S(tTR_rD); // (R2S,R2S_M,R2S_N) } }();
Tensor tRR_rD_dst_frg = recast<Array<RegisterElementD, FragmentSize>>(coalesce(tRR_rD_dst)); Tensor tRS_rD_frg = recast<Array<SmemElementD, FragmentSize>>(coalesce(tRS_rD));
// thread(b)lock-partition for (s)mem to (g)mem copy (bSG_) ThrCopy thrblk_s2g = params.tma_store_d.get_slice(Int<0>{}); Tensor bSG_sD = thrblk_s2g.partition_S(sD_epi); // (S2G,S2G_M,S2G_N,PIPE_D) Tensor bSG_gD = thrblk_s2g.partition_D(gD_epi); // (S2G,S2G_M,S2G_N,EPI_M,EPI_N)
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(cta_tile_mnk), make_coord(m_coord, n_coord)); // (CTA_M,CTA_N) Tensor tTR_cD_mn = thread_t2r.partition_D(flat_divide(cD_mn, EpilogueTile{})); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (CTA_M,CTA_N) Tensor tTR_cD = make_coord_tensor(tTR_cD_mn.layout()); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = make_coord(M,N) - cD_mn(_0{}); // (m,n) auto residue_tTR_cD = make_coord(M,N) - tTR_cD_mn(_0{}); // (m,n)
// Get the fusion callbacks for the consumer store warps constexpr bool RefSrc = false; // Register tensors reference T2R copy dst layout auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tiled_mma, EpilogueTile{}, tiled_t2r, cD, residue_cD, tTR_cD, residue_tTR_cD, tTR_rC, thread_idx };
// Thread synchronizer for previously issued waits or fences // to ensure visibility of smem reads/writes to threads or TMA unit auto synchronize = [] () CUTLASS_LAMBDA_FUNC_INLINE { cutlass::arch::NamedBarrier::sync(ThreadCount, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// Predication for sub-128 thread T2R tiled copy Layout tmem_warp_layout = typename decltype(make_tmem_warp_partitioner(tAcc_epi(_,_,0,0)))::TiledLayout_TV{}; constexpr bool predicate_tmem_load = size(tmem_warp_layout) != cosize(tmem_warp_layout); bool issue_tmem_load = true;
// If tmem doesn't have enough capacity to support double buffering, a portion of tmem (a column of epilogue tiles) // is overlapped between 2 pseudo-buffers. The shared tmem portion corresponds to the last epilogue tile column of // tmem accumulator buffer 0, and the first epilogue tile column of tmem accumulator 1. // Thus, whenever we are processing tmem accumulator buffer 0, we process the epilogue tiles with reversed column order. // Once the last epilogue tile column is loaded from tmem, the acc_pipeline is released. // Then, the next accumulation stage for buffer 1 can start. [[maybe_unused]] bool reverse_epi_n = ReuseTmem && acc_pipe_consumer_state.phase() == 0; static_assert(not (ReuseTmem && AccumulatorPipeline::Stages != 1), "Tmem reuse requires 1 accumulator stage");
// Predication for TMA store (a single thread from one warp issues TMA store) bool issue_tma_store = (warp_idx == 0) && cute::elect_one_sync();
// In the reuse smem configuration we have StagesC smem buffers and at most StagesD committed TMA stores in flight. // The TMA store pipeline producer acquire returns when at most StagesD-1 committed stores are in-flight, so we can // only guarantee store completion after StagesD iterations, then we can begin issuing releases on the smem buffer locks. // store_pipe_producer_state tracks the acquire and load_pipe_consumer_state tracks the release, in circular buffer fashion. // If TMA store supported async transaction mbarriers we would not need this synchronous release behavior. LoadPipelineState load_wait_state = load_pipe_consumer_state; if constexpr (ReuseSmemC) { load_wait_state = store_pipe_producer_state; load_wait_state.phase_ ^= 1; }
// We can delay issue of TMA store by one iteration to achieve better interleaving of non-TMA instructions // Sync requirements of smem reuse may preclude this optimization // Delayed stores cause delayed stage releases which causes deadlock when StagesC == StagesD [[maybe_unused]] int epi_m_prev = 0; [[maybe_unused]] int epi_n_prev = 0; static_assert(not (DelayTmaStore and ReuseSmemC and StagesC <= StagesD), "This TMA epilogue configuration will deadlock");
// The Epilogue Loop auto epi_loop_fn = [&] (auto& cst_callbacks) CUTLASS_LAMBDA_FUNC_INLINE { bool is_producer_load_needed = fusion_callbacks.is_producer_load_needed(); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// The TMA store sequence for one epilogue loop iteration auto tma_store_fn = [&] (int epi_m, int epi_n) CUTLASS_LAMBDA_FUNC_INLINE { // Write the tile from smem to gmem with TMA cutlass::arch::fence_view_async_shared(); // ensure smem writes are visible to TMA synchronize(); // ensure all threads have issued their async fence
if constexpr (is_destination_supported) { if (issue_tma_store) { copy(params.tma_store_d.with(get<0>(store_tensormap_info)), bSG_sD(_,_,_,store_pipe_producer_state.index()), bSG_gD(_,_,_,epi_m,epi_n)); } } // Post async fence, pre TMA commit callback entry point cst_callbacks.tma_store(epi_m, epi_n, store_pipe_producer_state.count(), issue_tma_store); // Commit the TMA stores for this stage if (issue_tma_store) { store_pipeline.producer_commit(store_pipe_producer_state); } ++store_pipe_producer_state; // Wait for the next smem buffer to be available if (issue_tma_store) { store_pipeline.producer_acquire(store_pipe_producer_state); } synchronize(); if constexpr (ReuseSmemC) { // producer_acquire returns when at most StagesD-1 committed stores are pending bool store_finished = store_pipe_producer_state.count() > StorePipeline::UnacquiredStages; // Let dma warp know earliest smem buffer is consumed and empty after StagesD producer commits if (store_finished) { if (is_producer_load_needed) { load_pipeline.consumer_release(load_pipe_consumer_state); } ++load_pipe_consumer_state; } } }; // tma_store_fn
// Begin the wait for the producer load results ConsumerToken load_wait_token{BarrierStatus::WaitDone}; if (is_producer_load_needed) { load_wait_token = load_pipeline.consumer_try_wait(load_wait_state); } // Begin the wait for the accumulator results ConsumerToken acc_wait_token = acc_pipeline.consumer_try_wait(acc_pipe_consumer_state);
cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); } // For each epilogue subtile within the CTA tile constexpr int NumEpiSubtilesN = CUTE_STATIC_V(size<3>(gD_epi)); constexpr int NumEpiSubtilesM = CUTE_STATIC_V(size<2>(gD_epi)); #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesN : 1) for (int iter_n = 0; iter_n < NumEpiSubtilesN; ++iter_n) { #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesM : 1) for (int iter_m = 0; iter_m < NumEpiSubtilesM; ++iter_m) { int epi_m = iter_m, epi_n = iter_n; bool is_first_iteration = iter_m == 0 && iter_n == 0; bool is_last_iteration = iter_m == size<2>(gD_epi)-1 && iter_n == size<3>(gD_epi)-1; bool do_acc_release = is_last_iteration;
// Reverse subtile order for tmem reuse if necessary if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = size<3>(gD_epi) - 1 - iter_n; } do_acc_release = iter_m == size<2>(gD_epi)-1 && iter_n == 0; }
cst_callbacks.begin_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Wait for the producer load to fill smem load_pipeline.consumer_wait(load_wait_state, load_wait_token);
if (is_C_load_needed) { // Copy source tile from smem to register copy(tiled_s2r, tSR_sC(_,_,_,load_wait_state.index()), tSR_rC); // Ensure smem loads are complete before reusing smem for mixed types/layouts if constexpr (ReuseSmemC && not (SmemLayoutC{} == SmemLayoutD{})) { synchronize(); } } }
// First loop fusion callback entry point cst_callbacks.previsit(epi_m, epi_n, load_wait_state.count(), is_producer_load_needed);
if (is_producer_load_needed) { // Let producer load warp know smem buffers are consumed and empty if constexpr (not ReuseSmemC) { cutlass::arch::fence_view_async_shared(); load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } ++load_wait_state; }
if (is_first_iteration) { // Wait for mma warp to fill tmem buffer with accumulator results acc_pipeline.consumer_wait(acc_pipe_consumer_state, acc_wait_token); }
// The current tile in tmem Tensor tTR_tAcc_mn = tTR_tAcc(_,_,_,epi_m,epi_n);
// Compute tmem load predication if necessary if constexpr (predicate_tmem_load) { // Issue tmem load if this tile's tmem subpartition is accessible by this warp int subpart_idx = (tTR_tAcc_mn.data().dp_ / 32) % 4; issue_tmem_load = warp_idx == subpart_idx; }
// Copy accumulator tile from tmem to register if (issue_tmem_load) { copy(tiled_t2r, tTR_tAcc_mn, tTR_rAcc); }
// After the last tmem load, signal that tmem buffer is consumed and empty if (do_acc_release) { cutlass::arch::fence_view_async_tmem_load(); acc_pipeline.consumer_release(acc_pipe_consumer_state); ++acc_pipe_consumer_state; }
// Vectorized fragment loop with visitor callback entry point CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tTR_rD_frg); ++epi_v) { tTR_rD_frg(epi_v) = cst_callbacks.visit(tTR_rAcc_frg(epi_v), epi_v, epi_m, epi_n); }
// The latest we can delay the TMA store is right before the smem store of the next iteration // since the current TMA store needs to be committed before we can acquire the next smem buffer if constexpr (DelayTmaStore) { // Issue TMA stores for the previous subtile if (not is_first_iteration) { tma_store_fn(epi_m_prev, epi_n_prev); } epi_m_prev = epi_m; epi_n_prev = epi_n; } if constexpr (!IsDirectR2S) { // At present, only FP4 col output with scalefactor generation fusion would go into these branch copy(tiled_r2r, tRR_rD_src, tRR_rD_dst); } tRS_rD_frg(_0{}) = cutlass::NumericArrayConverter<SmemElementD, RegisterElementD, FragmentSize>{}(tRR_rD_dst_frg(_0{}));
// Smem reduction callback entry point using current store buffer for workspace Tensor reduction_buffer = make_tensor(raw_pointer_cast(sD_epi(_,_,store_pipe_producer_state.index()).data()), make_layout(stride<2>(get_nonswizzle_portion(SmemLayoutD{})), _1{})); cst_callbacks.reduce(reduction_buffer, synchronize, epi_m, epi_n, is_last_iteration, tRS_rD_frg);
// Copy output tile from register to smem bool issue_smem_store = issue_tmem_load; if constexpr (is_destination_supported) { if (issue_smem_store) { copy(tiled_r2s, tRS_rD, tRS_sD(_,_,_,store_pipe_producer_state.index())); } }
// Post reduction, pre TMA store callback entry point cst_callbacks.postreduce(epi_m, epi_n, store_pipe_producer_state.count(), issue_smem_store);
if constexpr (not DelayTmaStore) { // Issue TMA stores for this subtile tma_store_fn(epi_m, epi_n); }
cst_callbacks.end_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Begin the wait for the next subtile producer load load_wait_token = load_pipeline.consumer_try_wait(load_wait_state, is_last_iteration); } } // for epi_m } // for epi_n
if constexpr (DelayTmaStore) { // Issue TMA stores for the last subtile tma_store_fn(epi_m_prev, epi_n_prev); }
cst_callbacks.end(); };
// // BEGIN EPILOGUE // auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); epi_loop_fn(cst_callbacks); return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state, acc_pipe_consumer_state); }
// API with Global Accumulator in registers for FastFP32 (emulated MMA) kernels. // The accumulator in TMEM periodically loaded into the registers so that the MMA can clear out the TMEM accumulator // values for better accuracy. This epilogue accepts the accumulator in registers and take TiledCopy for the // TMEM->Reg as a parameter to be used in partitioning GMEM tensors C and D. template< class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout, class TiledCopyT2R, class TensorMapD > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine, AccLayout>& tTR_rAcc, // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) TensorStorage& shared_tensors, TensorMapD store_tensormap, TiledCopyT2R tiled_t2r ) { using namespace cute; using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
static_assert(is_rmem<AccEngine>::value, "Accumulator must be Register resident."); static_assert(rank(AccLayout{}) == 5, "Accumulators must be copy-partitioned: (T2R,T2R_M,T2R_N,EPI_M,EPI_N)"); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(CtaCoordMNKL{}) == 4, "CoordMNKL must be rank 4");
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl; int thread_idx = threadIdx.x % ThreadCount; int warp_idx = thread_idx / NumThreadsPerWarp; [[maybe_unused]] int lane_idx = thread_idx % NumThreadsPerWarp;
auto coord_shape = append<3>(make_shape(m_coord, n_coord),Int<0>{});
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mD_mn = params.tma_store_d.get_tma_tensor(append<3>(make_shape(M,N),Int<1>{})); // (M,N,L) Tensor mD = coalesce(mD_mn, take<0,2>(cta_tile_mnk)); Tensor gD = local_tile(mD, take<0,2>(cta_tile_mnk), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtiling Tensor gD_epi = flat_divide( gD, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
// Construct the corresponding pipelined smem tensors auto ptr_sC = shared_tensors.collective.smem_C.begin(); auto ptr_sD = shared_tensors.collective.smem_D.begin(); Tensor sC_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_C) Tensor sD_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sD), SmemLayoutD{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_D)
// (t)hread-partition for (t)mem to (r)egister copy (tTR_) ThrCopy thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_sD = thread_t2r.partition_D(sD_epi(_,_,_0{})); // (T2R,T2R_M,T2R_N)
// Allocate D and accumulator registers Tensor tTR_rD = make_tensor<SmemElementD>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N)
// Vectorized fragment view constexpr int FragmentSize = DispatchPolicy::FragmentSize; Tensor tTR_rD_frg = recast<Array<SmemElementD, FragmentSize>>(coalesce(tTR_rD)); // (EPI_V)
// (t)hread-partition for (s)mem to (r)egister copy (tSR_) TiledCopy tiled_s2r = make_tiled_copy_D(Copy_Atom<CopyOpS2R, SmemElementC>{}, tiled_t2r); ThrCopy thread_s2r = tiled_s2r.get_slice(thread_idx); Tensor tSR_sC = thread_s2r.partition_S(sC_epi); // (S2R,S2R_M,S2R_N,PIPE_C) Layout tSR_rC_layout = thread_s2r.retile_D(tTR_rD).layout(); // (S2R,S2R_M,S2R_N)
// Allocate C registers // If C smem load is a non-vectorized dst(i) = src(i) then we can allocate C registers directly in the compute type // to eliminate some redundant pack+unpack instruction sequences for sub-word types constexpr bool IsDirectS2R = cute::is_same_v<CopyOpS2R, AutoVectorizingCopyWithAssumedAlignment<128>> && decltype(max_common_vector(tSR_rC_layout, tSR_sC.layout()))::value <= 1; using RegisterElementC = cute::conditional_t<IsDirectS2R, ElementCompute, SmemElementC>; Tensor tTR_rC = make_tensor<RegisterElementC>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N) Tensor tSR_rC = thread_s2r.retile_D(tTR_rC); // (S2R,S2R_M,S2R_N)
// (t)hread-partition for (r)egister to (s)mem copy (tRS_) TiledCopy tiled_r2s = make_tiled_copy_D(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_t2r); ThrCopy thread_r2s = tiled_r2s.get_slice(thread_idx); Tensor tRS_rD = thread_r2s.retile_S(tTR_rD); // (R2S,R2S_M,R2S_N) Tensor tRS_sD = thread_r2s.partition_D(sD_epi); // (R2S,R2S_M,R2S_N,PIPE_D)
// thread(b)lock-partition for (s)mem to (g)mem copy (bSG_) ThrCopy thrblk_s2g = params.tma_store_d.get_slice(Int<0>{}); Tensor bSG_sD = thrblk_s2g.partition_S(sD_epi); // (S2G,S2G_M,S2G_N,PIPE_D) Tensor bSG_gD = thrblk_s2g.partition_D(gD_epi); // (S2G,S2G_M,S2G_N,EPI_M,EPI_N)
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(cta_tile_mnk), make_coord(m_coord, n_coord)); // (CTA_M,CTA_N) Tensor tTR_cD_mn = thread_t2r.partition_D(flat_divide(cD_mn, EpilogueTile{})); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (CTA_M,CTA_N) Tensor tTR_cD = make_coord_tensor(tTR_cD_mn.layout()); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = make_coord(M,N) - cD_mn(_0{}); // (m,n) auto residue_tTR_cD = make_coord(M,N) - tTR_cD_mn(_0{}); // (m,n)
// Get the fusion callbacks for the consumer store warps constexpr bool RefSrc = false; // Register tensors reference T2R copy dst layout auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tiled_mma, EpilogueTile{}, tiled_t2r, cD, residue_cD, tTR_cD, residue_tTR_cD, tTR_rC, thread_idx };
auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); bool is_producer_load_needed = fusion_callbacks.is_producer_load_needed(); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// Thread synchronizer for previously issued waits or fences // to ensure visibility of smem reads/writes to threads or TMA unit auto synchronize = [] () { cutlass::arch::NamedBarrier::sync(ThreadCount, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// Predication for TMA store (one warp issues TMA store) bool issue_tma_store = warp_idx == 0;
// In the reuse smem configuration we have StagesC smem buffers and at most StagesD committed TMA stores in flight. // The TMA store pipeline producer acquire returns when at most StagesD-1 committed stores are in-flight, so we can // only guarantee store completion after StagesD iterations, then we can begin issuing releases on the smem buffer locks. // store_pipe_producer_state tracks the acquire and load_pipe_consumer_state tracks the release, in circular buffer fashion. // If TMA store supported async transaction mbarriers we would not need this synchronous release behavior. LoadPipelineState load_wait_state = load_pipe_consumer_state; if constexpr (ReuseSmemC) { load_wait_state = store_pipe_producer_state; load_wait_state.phase_ ^= 1; }
// We can delay issue of TMA store by one iteration to achieve better interleaving of non-TMA instructions // Sync requirements of smem reuse may preclude this optimization // Delayed stores cause delayed stage releases which causes deadlock when StagesC == StagesD int epi_m_prev = 0, epi_n_prev = 0; static_assert(not (DelayTmaStore and ReuseSmemC and StagesC <= StagesD), "This TMA epilogue configuration will deadlock");
// The TMA store sequence for one subtile iteration auto tma_store_fn = [&] (int epi_m, int epi_n) { // Write the tile from smem to gmem with TMA cutlass::arch::fence_view_async_shared(); // ensure smem writes are visible to TMA synchronize(); // ensure all threads have issued their async fence if (issue_tma_store) { copy(params.tma_store_d.with(store_tensormap), bSG_sD(_,_,_,store_pipe_producer_state.index()), bSG_gD(_,_,_,epi_m,epi_n)); }
// Post async fence, pre TMA commit callback entry point cst_callbacks.tma_store(epi_m, epi_n, store_pipe_producer_state.count(), issue_tma_store);
// Commit the TMA stores for this stage if (issue_tma_store) { store_pipeline.producer_commit(store_pipe_producer_state); } ++store_pipe_producer_state;
// Wait for the next smem buffer to be available if (issue_tma_store) { store_pipeline.producer_acquire(store_pipe_producer_state); } synchronize();
if constexpr (ReuseSmemC) { // producer_acquire returns when at most StagesD-1 committed stores are pending bool store_finished = store_pipe_producer_state.count() > StorePipeline::UnacquiredStages; // Let dma warp know earliest smem buffer is consumed and empty after StagesD producer commits if (store_finished) { if (is_producer_load_needed) { load_pipeline.consumer_release(load_pipe_consumer_state); } ++load_pipe_consumer_state; } } };
// // BEGIN EPILOGUE //
// Begin the wait for the producer load results ConsumerToken load_wait_token{BarrierStatus::WaitDone}; if (is_producer_load_needed) { load_wait_token = load_pipeline.consumer_try_wait(load_wait_state); }
cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// For each epilogue subtile within the CTA tile constexpr int NumEpiSubtilesN = CUTE_STATIC_V(size<3>(gD_epi)); constexpr int NumEpiSubtilesM = CUTE_STATIC_V(size<2>(gD_epi)); #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesN : 1) for (int iter_n = 0; iter_n < NumEpiSubtilesN; ++iter_n) { #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesM : 1) for (int iter_m = 0; iter_m < NumEpiSubtilesM; ++iter_m) { int epi_m = iter_m, epi_n = iter_n; bool is_first_iteration = iter_m == 0 && iter_n == 0; bool is_last_iteration = iter_m == size<2>(gD_epi)-1 && iter_n == size<3>(gD_epi)-1;
cst_callbacks.begin_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Wait for the producer load to fill smem load_pipeline.consumer_wait(load_wait_state, load_wait_token);
if (is_C_load_needed) { // Copy source tile from smem to register copy(tiled_s2r, tSR_sC(_,_,_,load_wait_state.index()), tSR_rC); // Ensure smem loads are complete before reusing smem for mixed types/layouts if constexpr (ReuseSmemC && not (SmemLayoutC{} == SmemLayoutD{})) { synchronize(); } } }
// First loop fusion callback entry point cst_callbacks.previsit(epi_m, epi_n, load_wait_state.count(), is_producer_load_needed);
if (is_producer_load_needed) { // Let producer load warp know smem buffers are consumed and empty if constexpr (not ReuseSmemC) { cutlass::arch::fence_view_async_shared(); load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } ++load_wait_state; }
bool issue_smem_store = true; Tensor tTR_rAcc_epi_tile = tTR_rAcc(_,_,_,epi_m,epi_n); Tensor tTR_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(coalesce(tTR_rAcc_epi_tile)); // (EPI_V)
// Vectorized fragment loop with visitor callback entry point CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tTR_rD_frg); ++epi_v) { tTR_rD_frg(epi_v) = cst_callbacks.visit(tTR_rAcc_frg(epi_v), epi_v, epi_m, epi_n); }
// The latest we can delay the TMA store is right before the smem store of the next iteration // since the current TMA store needs to be committed before we can acquire the next smem buffer if constexpr (DelayTmaStore) { // Issue TMA stores for the previous subtile if (not is_first_iteration) { tma_store_fn(epi_m_prev, epi_n_prev); } epi_m_prev = epi_m; epi_n_prev = epi_n; }
// Smem reduction callback entry point using current store buffer for workspace Tensor reduction_buffer = make_tensor(raw_pointer_cast(sD_epi(_,_,store_pipe_producer_state.index()).data()), make_layout(stride<2>(get_nonswizzle_portion(SmemLayoutD{})), _1{})); cst_callbacks.reduce(reduction_buffer, synchronize, epi_m, epi_n, is_last_iteration, tTR_rD_frg);
// Copy output tile from register to smem if (issue_smem_store) { copy(tiled_r2s, tRS_rD, tRS_sD(_,_,_,store_pipe_producer_state.index())); }
// Post reduction, pre TMA store callback entry point cst_callbacks.postreduce(epi_m, epi_n, store_pipe_producer_state.count(), issue_smem_store);
if constexpr (not DelayTmaStore) { // Issue TMA stores for this subtile tma_store_fn(epi_m, epi_n); }
cst_callbacks.end_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Begin the wait for the next subtile producer load load_wait_token = load_pipeline.consumer_try_wait(load_wait_state, is_last_iteration); } } // for epi_m } // for epi_n
if constexpr (DelayTmaStore) { // Issue TMA stores for the last subtile tma_store_fn(epi_m_prev, epi_n_prev); }
cst_callbacks.end();
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
template <class CtaTileMNK> CUTLASS_DEVICE void store_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, CtaTileMNK cta_tile_mnk) { if constexpr (ReuseSmemC) { if (fusion_callbacks.is_producer_load_needed()) { // wait for all TMA stores to complete store_pipeline.producer_tail(store_pipe_producer_state);
// Issue releases on up to StagesD-1 previously issued TMA stores constexpr int release_stages = cute::min(StorePipeline::UnacquiredStages, get_load_pipe_increment(cta_tile_mnk)); CUTLASS_PRAGMA_UNROLL for (int stage = 0; stage < release_stages; ++stage) { load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } } } }
// // Methods to perform different parts of TMA/Tensormap modifications //
template <bool IsLoad> CUTLASS_DEVICE auto tensormaps_init(Params const& params, TensorMapStorage& shared_tensormap, int32_t const sm_count, int32_t const sm_idx) const { cute::TmaDescriptor* tma_desc = nullptr; cute::TmaDescriptor* gmem_tensormap = params.tensormaps; if constexpr (IsLoad) { if (is_source_supported) { tma_desc = &gmem_tensormap[sm_idx]; if (cute::elect_one_sync()) { // Bringing tensormaps from params to smem for modification later Tensor pC_tensormap = make_tensor(params.tma_load_c.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sC_tensormap = make_tensor(make_smem_ptr(&shared_tensormap.smem_tensormap_C), Int<1>{}, Int<1>{}); copy(recast<uint128_t>(pC_tensormap), recast<uint128_t>(sC_tensormap)); } __syncwarp(); } } else if constexpr (is_destination_supported) { int const offset_Ddesc = cute::is_void_v<ElementC> ? 0 : sm_count; tma_desc = &gmem_tensormap[sm_idx + offset_Ddesc]; if (cute::elect_one_sync()) { // Bringing tensormaps from params to smem for modification later Tensor pD_tensormap = make_tensor(params.tma_store_d.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sD_tensormap = make_tensor(make_smem_ptr(&shared_tensormap.smem_tensormap_D), Int<1>{}, Int<1>{}); copy(recast<uint128_t>(pD_tensormap), recast<uint128_t>(sD_tensormap)); } __syncwarp(); }
return tma_desc; }
// Replace address for the global tensor (to be done by single thread) template <bool IsLoad> CUTLASS_DEVICE void tensormaps_replace_global_address( TensorMapStorage& shared_tensormap, Params const& params, int32_t next_batch) { // Replacing global_address for the next batch if constexpr (IsLoad) { if constexpr (is_source_supported) { if (params.ptr_C != nullptr) { cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormap.smem_tensormap_C, params.ptr_C[next_batch]); } } } else if constexpr (is_destination_supported) { cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormap.smem_tensormap_D, params.ptr_D[next_batch]); } }
// Replace dim and strides for the global tensor - used only for Grouped GEMM (to be done by single thread) template <bool IsLoad, class ProblemShape_MNKL> CUTLASS_DEVICE void tensormaps_replace_global_tensor_properties( TensorMapStorage& shared_tensormaps, Params const& params, int32_t next_group, ProblemShape_MNKL problem_shape_mnkl) { const uint32_t M = get<0>(problem_shape_mnkl); const uint32_t N = get<1>(problem_shape_mnkl); // Replace all dims for consistency constexpr int MaxTensorRank = 5; cute::array<uint32_t, MaxTensorRank> prob_shape = {1,1,1,1,1}; cute::array<uint64_t, MaxTensorRank> prob_stride = {0,0,0,0,0};
if constexpr (IsLoad) { if constexpr (is_source_supported) { if (params.dC != nullptr) { ElementC const* ptr_C = nullptr; Tensor tensor_c = make_tensor(ptr_C, make_layout(make_shape(M,N,Int<1>{}), params.dC[next_group]));
cute::detail::fill_tma_gmem_shape_stride(params.tma_load_c, tensor_c, prob_shape, prob_stride); // Convert strides to byte strides for (uint64_t& stride : prob_stride) { stride = (stride * sizeof_bits_v<ElementC>) / 8; } cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_C, prob_shape, prob_stride); } } } else if constexpr (is_destination_supported) { ElementD const* ptr_D = nullptr; Tensor tensor_d = make_tensor(ptr_D, make_layout(make_shape(M,N,Int<1>{}), params.dD[next_group]));
cute::detail::fill_tma_gmem_shape_stride(params.tma_store_d, tensor_d, prob_shape, prob_stride); // Convert strides to byte strides for (uint64_t& stride : prob_stride) { stride = (stride * sizeof_bits_v<ElementD>) / 8; }
cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_D, prob_shape, prob_stride); } }
// The entire warp must call this function collectively (that is, the instructions are aligned) template <bool IsLoad, class ProblemShape> CUTLASS_DEVICE void tensormaps_perform_update( TensorMapStorage& shared_tensormap, Params const& params, cute::TmaDescriptor const* tensormap, ProblemShape problem_shape, int32_t next_batch) { if (cute::elect_one_sync()) { // Replacing global_address for the next batch tensormaps_replace_global_address<IsLoad>(shared_tensormap, params, next_batch);
if constexpr (IsGroupedGemmKernel) { auto problem_shape_MNKL = append<4>(problem_shape.get_problem_shape(next_batch), 1); // Replacing global dims and strides for the next batch tensormaps_replace_global_tensor_properties<IsLoad>( shared_tensormap, params, next_batch, problem_shape_MNKL); } } // Ensure warp is converged before issuing tensormap fence release __syncwarp(); // Entire warp must do this (ie its aligned) tensormaps_cp_fence_release<IsLoad>(shared_tensormap, tensormap); }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_cp_fence_release( TensorMapStorage& shared_tensormap, cute::TmaDescriptor const* tensormap) { // Commit and wait for all TMA load/store instructions before updating the tensormap in gmem. // This operation only happens when the group/batch changes between consecutive tiles. // If there are no uncommitted instructions then tma_desc_commit_group results in an empty bulk async-group. auto tma_desc_wait_all_fn = [] () CUTLASS_LAMBDA_FUNC_INLINE { if (cute::elect_one_sync()) { cute::tma_desc_commit_group(); cute::tma_desc_wait_group(); } }; // Entire warp must do this (ie its aligned) if constexpr (IsLoad) { if (is_source_supported) { tma_desc_wait_all_fn(); tma_descriptor_cp_fence_release(tensormap, shared_tensormap.smem_tensormap_C); } } else if constexpr (is_destination_supported) { tma_desc_wait_all_fn(); tma_descriptor_cp_fence_release(tensormap, shared_tensormap.smem_tensormap_D); } }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_fence_acquire(cute::TmaDescriptor const* tensormap) { if constexpr (IsLoad) { if (is_source_supported) { cute::tma_descriptor_fence_acquire(tensormap); } } else if constexpr (is_destination_supported) { cute::tma_descriptor_fence_acquire(tensormap); } }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::collective
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/epilogue/collective/detail.hpp"#include "cutlass/detail/helper_macros.hpp"#include "cutlass/conv/convnd_problem_shape.hpp"#include "cutlass/conv/detail.hpp"
#include "cute/tensor.hpp"#include "cute/numeric/numeric_types.hpp"#include "cutlass/cuda_host_adapter.hpp"#include "cutlass/epilogue/thread/linear_combination.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
template<class T>struct IsDefaultFusionOp { static constexpr bool value = false;};
template< class ElementD, class ElementCompute, class ElementC, FloatRoundStyle RoundStyle>struct IsDefaultFusionOp< epilogue::fusion::LinearCombination< ElementD, ElementCompute, ElementC, ElementCompute, RoundStyle>> { static constexpr bool value = true;};
template< class ElementOutput, int Count, class ElementAccumulator, class ElementCompute, epilogue::thread::ScaleType::Kind Scale, FloatRoundStyle Round, class ElementSource>struct IsDefaultFusionOp< epilogue::thread::LinearCombination< ElementOutput, Count, ElementAccumulator, ElementCompute, Scale, Round, ElementSource>> { static constexpr bool value = true;};
// Legacy direct store sm100 epilogue using thread::LinearCombination, do not expect this to be stabletemplate < class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class ThreadEpilogueOp_, class CopyOpT2R_, class AlignmentC_, class AlignmentD_>class CollectiveEpilogue< Sm100NoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC_, AlignmentD_, cute::enable_if_t<IsDefaultFusionOp<ThreadEpilogueOp_>::value>> {public: // // Type Aliases // using DispatchPolicy = Sm100NoSmem; using EpilogueTile = EpilogueTile_; // derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementBias = typename detail::IsThreadEpilogueOpWithBias<ThreadEpilogueOp>::type; using ElementC = ElementC_; using StrideC = StrideC_; using ElementD = ElementD_; using StrideD = StrideD_; using CopyOpT2R = CopyOpT2R_; using AlignmentC = AlignmentC_; using AlignmentD = AlignmentD_; using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>,ElementD,ElementC>; // prevents void ref breakages
using GmemTiledCopyC = void; using GmemTiledCopyD = void;
constexpr static int ThreadCount = 128; constexpr static int kOutputAlignment = ThreadEpilogueOp::kCount; constexpr static bool isEpilogueBiasSupported = detail::IsThreadEpilogueOpWithBias<ThreadEpilogueOp>::value; constexpr static bool isSourceNeeded = not cute::is_void_v<ElementC>;
using AlignmentType = typename cute::uint_bit<sizeof_bits<ElementOutput>::value * kOutputAlignment>::type; constexpr static uint32_t TmaTransactionBytes = 0;
struct SharedStorage { };
// Host side epilogue arguments struct Arguments { typename ThreadEpilogueOp::Params thread{}; ElementC const* ptr_C = nullptr; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { return args; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template <conv::Operator ConvOp, int NumDims> static bool can_implement(cutlass::conv::ConvProblemShape<ConvOp,NumDims> const& problem_shape, Arguments const& args) { return can_implement(cutlass::conv::detail::get_transformed_problem_shape_MNKL(problem_shape), args); }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; auto shape = cute::make_shape(M,N,L);
bool implementable = true; implementable = implementable && cutlass::detail::check_alignment<AlignmentD{}>(shape, StrideD{}); if constexpr (isSourceNeeded) { implementable = implementable && cutlass::detail::check_alignment<AlignmentC{}>(shape, StrideC{}); } return implementable; }
// // Constructor and Data Members // CUTLASS_DEVICE CollectiveEpilogue(Params const& params, SharedStorage&) : params(params) { };
protected: Params const& params;
// // Non-static Device Methods //public: template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout > CUTLASS_DEVICE auto operator()( AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK cta_tile_shape_mnk, TileCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine, AccLayout> const& accumulators, // (MMA,MMA_M,MMA_N) [[maybe_unused]] SharedStorage&) {
using namespace cute; using X = Underscore;
static_assert(is_tmem<AccEngine>::value, "Accumulator must be TMEM resident."); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(TileCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4");
auto problem_shape_mnl = select<0,1,3>(problem_shape_mnkl); auto cta_coord_mnl = select<0,1,3>(cta_coord_mnkl); auto cta_tiler = take<0,2>(cta_tile_shape_mnk);
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mC = make_tensor(make_gmem_ptr<GmemElementC>(params.ptr_C), problem_shape_mnl, append<3>(params.dC,_0{})); // (M,N,L) Tensor mD = make_tensor(make_gmem_ptr(params.ptr_D), problem_shape_mnl, append<3>(params.dD,_0{})); // (M,N,L) Tensor gC = local_tile(mC, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) Tensor gD = local_tile(mD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N)
// Partition source and destination tiles according to tmem copy T2R partitioning (tTR_) auto tiled_t2r = make_tmem_copy(CopyOpT2R{}, tensor<0>(accumulators)); auto thread_idx = threadIdx.x % size(tiled_t2r);
auto thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_gC = thread_t2r.partition_D(gC); // (T2R,T2R_M,T2R_N) Tensor tTR_gD = thread_t2r.partition_D(gD); // (T2R,T2R_M,T2R_N) Tensor tTR_rAcc = make_tensor<ElementAccumulator>(shape(tTR_gD)); // (T2R,T2R_M,T2R_N)
Tensor tTR_rC = make_tensor<GmemElementC>(shape(tTR_gC)); // (T2R,T2R_M,T2R_N)
Tensor coordCD = make_identity_tensor(problem_shape_mnl); // (M,N,L) -> (m,n,l) Tensor cCD = local_tile(coordCD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) -> (m,n,l) Tensor tTR_cCD = thread_t2r.partition_D(cCD); // (T2R,T2R_M,T2R_N) -> (m,n,l)
constexpr auto mclD = decltype(max_common_layout(tTR_rAcc.layout(), tTR_gD.layout())){}; constexpr int VD = cute::min(AlignmentD{}, size(mclD)); Tensor tTR_rD_frag = make_tensor<ElementD>(shape(tTR_rAcc)); Tensor tTR_rD_src = recast<Array<ElementD, VD>>(coalesce(tTR_rD_frag)); Tensor tR2G_rD_dst = recast<Array<ElementD, VD>>(coalesce(tTR_gD));
Tensor tTR_cD_mn_frg = tensor<1>(zipped_divide(coalesce(tTR_cCD), mclD.compose(Int<VD>{}))); Tensor tDpD = make_tensor<bool>(shape(tR2G_rD_dst));
CUTLASS_PRAGMA_UNROLL for (int t = 0; t < size(tDpD); t++) { tDpD(t) = elem_less(tTR_cD_mn_frg(t), problem_shape_mnl); }
constexpr auto mclC = decltype(max_common_layout(tTR_rAcc.layout(), tTR_gC.layout())){}; constexpr int VC = cute::min(AlignmentC{}, size(mclC));
Tensor tTR_cC_mn_frg = tensor<1>(zipped_divide(coalesce(tTR_cCD), mclC.compose(Int<VC>{}))); Tensor tG2R_rC_dst = recast<Array<GmemElementC, VC>>(coalesce(tTR_gC)); Tensor tCpC = make_tensor<bool>(shape(tG2R_rC_dst));
CUTLASS_PRAGMA_UNROLL for (int t = 0; t < size(tCpC); t++) { tCpC(t) = elem_less(tTR_cC_mn_frg(t), problem_shape_mnl); } Tensor tTR_rC_src = recast<Array<GmemElementC, VC>>(coalesce(tTR_gC)); Tensor tTR_rC_dst = recast<Array<GmemElementC, VC>>(coalesce(tTR_rC));
// Detect interleaved complex fp32 kernels [[maybe_unused]] Tensor accs = accumulators; using ElementTmem = typename decltype(accs)::value_type; constexpr bool is_interleaved_complex_f32 = is_complex<ElementAccumulator>::value && cute::is_same_v<ElementTmem, float>;
// 1. Load accumulators into register from tmem // Tmem -> rmem and transformation for interleaved complex kernels if constexpr (is_interleaved_complex_f32) { using ElementComputeAccumulator = float;
Tensor tAccReal = accumulators(make_coord(_,_),_0{},_0{},_0{}); // (CTA_M,CTA_N) Tensor tAccImag = accumulators(make_coord(_,_),_0{},_0{},_1{}); // (CTA_M,CTA_N) Tensor tTR_tAccReal = thread_t2r.partition_S(tAccReal); // (T2R,T2R_M,T2R_N) Tensor tTR_tAccImag = thread_t2r.partition_S(tAccImag); // (T2R,T2R_M,T2R_N) Tensor tTR_rAccReal = make_tensor<ElementComputeAccumulator>(shape(tTR_gD)); // (T2R,T2R_M,T2R_N) Tensor tTR_rAccImag = make_tensor<ElementComputeAccumulator>(shape(tTR_gD)); // (T2R,T2R_M,T2R_N)
copy(tiled_t2r, tTR_tAccReal, tTR_rAccReal); copy(tiled_t2r, tTR_tAccImag, tTR_rAccImag);
// 1.1. Transform accumulators in registers CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rAccReal); i++) { tTR_rAcc(i) = {tTR_rAccReal(i), tTR_rAccImag(i)}; } }
// Standard tmem -> rmem epilogue else { Tensor tAcc = accumulators(make_coord(_,_),_0{},_0{}); // (CTA_M,CTA_N) Tensor tTR_tAcc = thread_t2r.partition_S(tAcc); // (T2R,T2R_M,T2R_N)
copy(tiled_t2r, tTR_tAcc, tTR_rAcc); }
cutlass::arch::fence_view_async_tmem_load(); acc_pipeline.consumer_release(acc_pipe_consumer_state); ++acc_pipe_consumer_state;
// 2. Apply element-wise operation and store to gmem ThreadEpilogueOp epilogue_op{params.thread}; // source is needed if (epilogue_op.is_source_needed()) { copy_if(tCpC, tTR_rC_src, tTR_rC_dst); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rAcc); i++) { tTR_rD_frag(i) = epilogue_op(tTR_rAcc(i), tTR_rC(i)); }
copy_if(tDpD, tTR_rD_src, tR2G_rD_dst); } // source is not needed, avoid load else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rAcc); i++) { tTR_rD_frag(i) = epilogue_op(tTR_rAcc(i)); }
copy_if(tDpD, tTR_rD_src, tR2G_rD_dst); }
return cute::make_tuple(acc_pipe_consumer_state); }
// API with Global Accumulator in registers for FastFP32 (emulated MMA) kernels. // The accumulator in TMEM periodically loaded into the registers so that the MMA can clear out the TMEM accumulator // values for better accuracy. This epilogue accepts the accumulator in registers and take TiledCopy for the // TMEM->Reg as a parameter to be used in partitioning GMEM tensors C and D. template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout, class TiledCopy > CUTLASS_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK cta_tile_shape_mnk, TileCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine, AccLayout>& tTR_rGlobAcc, // (MMA,MMA_M,MMA_N) [[maybe_unused]] SharedStorage&, TiledCopy tiled_t2r) {
using namespace cute; using X = Underscore;
static_assert(is_rmem<AccEngine>::value, "Accumulator must be Register resident."); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(AccLayout{}) == 5, "Accumulators must be copy-partitioned: (T2R,T2R_M,T2R_N,EPI_M,EPI_N)"); static_assert(rank(TileCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4");
auto problem_shape_mnl = select<0,1,3>(problem_shape_mnkl); auto cta_coord_mnl = select<0,1,3>(cta_coord_mnkl); auto cta_tiler = take<0,2>(cta_tile_shape_mnk);
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mC = make_tensor(make_gmem_ptr<GmemElementC>(params.ptr_C), problem_shape_mnl, append<3>(params.dC,_0{})); // (M,N,L) Tensor mD = make_tensor(make_gmem_ptr(params.ptr_D), problem_shape_mnl, append<3>(params.dD,_0{})); // (M,N,L) Tensor gC = local_tile(mC, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) Tensor gD = local_tile(mD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N)
// Partition source and destination tiles according to tmem copy T2R partitioning (tTR_) auto thread_t2r = tiled_t2r.get_slice(threadIdx.x % size(tiled_t2r)); Tensor tTR_gC = thread_t2r.partition_D(gC); // (T2R,T2R_M,T2R_N) Tensor tTR_gD = thread_t2r.partition_D(gD); // (T2R,T2R_M,T2R_N)
Tensor coordCD = make_identity_tensor(problem_shape_mnl); // (M,N,L) -> (m,n,l) Tensor cCD = local_tile(coordCD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) -> (m,n,l) Tensor tTR_cCD = thread_t2r.partition_D(cCD); // (T2R,T2R_M,T2R_N) -> (m,n,l)
// 2. Apply element-wise operation and store to gmem ThreadEpilogueOp epilogue_op{params.thread}; // source is needed if (epilogue_op.is_source_needed()) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rGlobAcc); ++i) { if (elem_less(tTR_cCD(i), problem_shape_mnl)) { tTR_gD(i) = epilogue_op(tTR_rGlobAcc(i), tTR_gC(i)); } } } // source is not needed, avoid load else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tTR_rGlobAcc); ++i) { if (elem_less(tTR_cCD(i), problem_shape_mnl)) { tTR_gD(i) = epilogue_op(tTR_rGlobAcc(i)); } } } }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Direct store sm100 epilogue supporting EVTtemplate < class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpT2R_, class AlignmentC_, class AlignmentD_>class CollectiveEpilogue< Sm100NoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpT2R_, AlignmentC_, AlignmentD_, cute::enable_if_t<not IsDefaultFusionOp<FusionCallbacks_>::value>> {public: // // Type Aliases // // Required by the gemm::kernel using DispatchPolicy = Sm100NoSmem; using ElementC = ElementC_; using ElementD = ElementD_; using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>,ElementD,ElementC>; // prevents void ref breakages using StrideC = StrideC_; using StrideD = StrideD_; using EpilogueTile = EpilogueTile_; using CopyOpT2R = CopyOpT2R_; using FusionCallbacks = FusionCallbacks_; using ThreadEpilogueOp = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::Operation;
using GmemTiledCopyC = void; using GmemTiledCopyD = void;
private: constexpr static bool IsReductionBufferNeeded = ThreadEpilogueOp::IsDePerRowBiasSupported || is_same_v<ThreadEpilogueOp, epilogue::fusion::FusionOperation>; // alloc reduction buffer for custom EVTs constexpr static size_t ImplicitSharedStorageSize = IsReductionBufferNeeded ? size(EpilogueTile{}) : 0;
// Not unroll epi subtile loop when the activation op is heavy to reduce instruction size and register pressure. constexpr static bool UnrollEpiLoop = not cutlass::epilogue::thread::kIsHeavy_member_or_false<typename ThreadEpilogueOp::ActivationFn>::value;
public: constexpr static int ThreadCount = 128; constexpr static uint32_t TmaTransactionBytes = 0;
struct SharedStorage { using FusionStorage = typename FusionCallbacks::SharedStorage; FusionStorage thread; array_aligned<uint8_t, ImplicitSharedStorageSize> buffer; };
// Host side epilogue arguments struct Arguments { typename FusionCallbacks::Arguments thread{}; ElementC const* ptr_C = nullptr; StrideC dC = {}; ElementD* ptr_D = nullptr; StrideD dD = {}; };
// Device side epilogue params struct Params { typename FusionCallbacks::Params thread{}; ElementC const* ptr_C = nullptr; StrideC dC = {}; ElementD* ptr_D = nullptr; StrideD dD = {}; };
// // Constructor and Data Members // CUTLASS_DEVICE CollectiveEpilogue(Params const& params_, SharedStorage& shared_tensors) : fusion_callbacks(params_.thread, shared_tensors.thread) , smem_buffer_ptr(shared_tensors.buffer.data()) , params(params_) {};
protected: FusionCallbacks fusion_callbacks; uint8_t* smem_buffer_ptr; Params const& params;
public:
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { return { FusionCallbacks::to_underlying_arguments(problem_shape, args.thread, workspace), args.ptr_C, args.dC, args.ptr_D, args.dD }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return FusionCallbacks::get_workspace_size(problem_shape, args.thread); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return FusionCallbacks::initialize_workspace(problem_shape, args.thread, workspace, stream, cuda_adapter); }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) {
bool fusion_implementable = FusionCallbacks::can_implement(problem_shape, args.thread); if (!fusion_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum requirements for FusionCallbacks.\n"); } return fusion_implementable; }
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class AccEngine, class AccLayout > CUTLASS_DEVICE auto operator()( AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, cute::Tensor<AccEngine,AccLayout> accumulators, [[maybe_unused]] SharedStorage& ) { using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
// Wait for mma warp to fill tmem buffer with accumulator results static_assert(is_tmem<AccEngine>::value, "Accumulator must be TMEM resident."); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(CtaCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4"); static_assert(cute::sizeof_bits_v<ElementD> != 6, "Output element requires smem");
auto [M, N, K, L] = problem_shape_mnkl; auto problem_shape_mnl = select<0,1,3>(problem_shape_mnkl); auto cta_coord_mnl = select<0,1,3>(cta_coord_mnkl); auto cta_tiler = take<0,2>(cta_tile_mnk);
int thread_idx = threadIdx.x % ThreadCount;
Tensor tAcc = accumulators(make_coord(_,_),_0{},_0{}); // (CTA_M,CTA_N) Tensor tAcc_epi = flat_divide(tAcc, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) TiledCopy tiled_t2r = make_tmem_copy(CopyOpT2R{}, tAcc_epi(_,_,_0{},_0{})); ThrCopy thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_tAcc = thread_t2r.partition_S(tAcc_epi); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N)
constexpr int FragmentSize = size(EpilogueTile{}) / ThreadCount;
Tensor coordD = make_identity_tensor(problem_shape_mnl); // (M,N,L) -> (m,n,l) Tensor cD = local_tile(coordD, cta_tiler, cta_coord_mnl); // (CTA_M,CTA_N) -> (m,n,l) Tensor cD_epi = flat_divide(cD, EpilogueTile{}); Tensor tTR_cD = thread_t2r.partition_D(cD_epi); // (T2R,T2R_M,T2R_N) -> (m,n,l)
Tensor tTR_rAcc = make_tensor<ElementAccumulator>(shape(tTR_cD(_,_,_,_0{},_0{})));
// Construct the EVT consumer callbacks auto residue_cD = make_coord(M,N) - cD(_0{}); auto residue_tTR_cD = make_coord(M,N) - tTR_cD(_0{}); Tensor cD_ = make_coord_tensor(cD.layout()); Tensor tTR_cD_ = make_coord_tensor(tTR_cD.layout()); constexpr bool RefSrc = false;
Tensor mC = make_tensor(make_gmem_ptr<GmemElementC>(params.ptr_C), make_shape(M,N,L), params.dC);
Tensor tTR_gC = cutlass::epilogue::fusion::sm90_partition_for_epilogue<RefSrc>( mC, cta_tile_mnk, cta_coord_mnkl, EpilogueTile{}, tiled_t2r, thread_idx);
Tensor mD = make_tensor(make_gmem_ptr(recast_ptr<ElementD>(params.ptr_D)), make_shape(M,N,L), params.dD);
Tensor tTR_gD = cutlass::epilogue::fusion::sm90_partition_for_epilogue<RefSrc>( mD, cta_tile_mnk, cta_coord_mnkl, EpilogueTile{}, tiled_t2r, thread_idx);
// Register Tensor Tensor tTR_rD = make_tensor<ElementD>(take<0,3>(shape(tTR_gD)));
Tensor coord_cCD = make_identity_tensor(problem_shape_mnl); Tensor tTR_cCD = cutlass::epilogue::fusion::sm90_partition_for_epilogue<RefSrc>( coord_cCD, cta_tile_mnk, cta_coord_mnkl, EpilogueTile{}, tiled_t2r, thread_idx); constexpr auto mclD = decltype(max_common_layout(tTR_gD(_,_,_,_0{},_0{}), tTR_rD)){}; constexpr int VD = cute::min(AlignmentD_{}, size(mclD));
auto tCrC = make_tensor<GmemElementC>(take<0,3>(shape(tTR_gC))); constexpr auto mclC = decltype(max_common_layout(tTR_gC(_,_,_,_0{},_0{}), tCrC)){}; constexpr int VC = cute::min(AlignmentC_{}, size(mclC));
Tensor tTR_rD_frg = recast<Array<ElementD, FragmentSize>>(coalesce(tTR_rD));
auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, int(0), EpilogueTile{}, tiled_t2r, cD_, residue_cD, tTR_cD_, residue_tTR_cD, tCrC, thread_idx };
auto synchronize = [] () CUTLASS_LAMBDA_FUNC_INLINE { cutlass::arch::NamedBarrier::sync(ThreadCount, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// The Epilogue Loop auto epi_loop_fn = [&] (auto& cst_callbacks) CUTLASS_LAMBDA_FUNC_INLINE { bool is_C_load_needed = fusion_callbacks.is_C_load_needed();
// Ensure there are no threads from the previous wave writing to shared memory being utilized for the current wave. synchronize(); cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// If tmem doesn't have enough capacity to support double buffering, a portion of tmem (a column of epilogue tiles) // is overlapped between 2 pseudo-buffers. The shared tmem portion corresponds to the last epilogue tile column of // tmem accumulator buffer 0, and the first epilogue tile column of tmem accumulator 1. // Thus, whenever we are processing tmem accumulator buffer 0, we process the epilogue tiles with reversed column order. // Once the last epilogue tile column is loaded from tmem, the acc_pipeline is released. // Then, the next accumulation stage for buffer 1 can start. [[maybe_unused]] bool reverse_epi_n = ReuseTmem && acc_pipe_consumer_state.phase() == 0; static_assert(not (ReuseTmem && AccumulatorPipeline::Stages != 1), "Tmem reuse requires 1 accumulator stage");
// For each epilogue subtile within the CTA tile constexpr int NumEpiSubtilesN = CUTE_STATIC_V(size<4>(tTR_tAcc)); constexpr int NumEpiSubtilesM = CUTE_STATIC_V(size<3>(tTR_tAcc)); #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesN : 1) for (int iter_n = 0; iter_n < NumEpiSubtilesN; ++iter_n) { #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesM : 1) for (int iter_m = 0; iter_m < NumEpiSubtilesM; ++iter_m) { int epi_m = iter_m, epi_n = iter_n;
bool is_last_iteration = iter_m == size<3>(tTR_tAcc)-1 && iter_n == size<4>(tTR_tAcc)-1; bool do_acc_release = is_last_iteration;
// Reverse subtile order for tmem reuse if necessary if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = size<4>(tTR_tAcc) - 1 - iter_n; } do_acc_release = iter_m == size<3>(tTR_tAcc)-1 && iter_n == 0; }
Tensor tTR_cCD_mn = tTR_cCD(_,_,_,epi_m,epi_n); Tensor tTR_pCD_mn = cute::lazy::transform(tTR_cCD_mn, [&] (auto const& c) CUTLASS_LAMBDA_FUNC_INLINE { return elem_less(c, problem_shape_mnl); }); cst_callbacks.begin_loop(epi_m, epi_n);
if constexpr (not cute::is_void_v<ElementC>) { if (is_C_load_needed) { using CVecType = uint_bit_t<VC * sizeof_bits_v<ElementC>>;
if constexpr (!is_same_v<CVecType, uint256_t>) { Tensor tTR_gC_frg = recast<CVecType>(coalesce(tTR_gC(_,_,_,epi_m,epi_n))); Tensor tTR_rC_frg = recast<CVecType>(coalesce(tCrC)); Tensor tTR_pC_frg = tensor<1>(zipped_divide(coalesce(tTR_pCD_mn), mclC.compose(Int<VC>{}))); copy_if(tTR_pC_frg, tTR_gC_frg, tTR_rC_frg); } else { auto tiled_g2r = make_tiled_copy_D(Copy_Atom<SM100_LOAD_256bit_CACHE_NOALLOCATION, ElementC>{}, tiled_t2r); auto thr_g2r = tiled_g2r.get_slice(threadIdx.x); Tensor c_src = thr_g2r.retile_S(tTR_gC(_,_,_,epi_m,epi_n)); Tensor c_dst = thr_g2r.retile_D(tCrC); Tensor c_prd = thr_g2r.retile_D(tTR_pCD_mn); copy_if(tiled_g2r, c_prd, c_src, c_dst); } } }
// Copy accumulator tile from tmem to register // The current tile in tmem Tensor tTR_tAcc_mn = tTR_tAcc(_,_,_,epi_m,epi_n);
Tensor tTR_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(coalesce(tTR_rAcc));
copy(tiled_t2r, tTR_tAcc_mn, tTR_rAcc);
// After the last tmem load, signal that tmem buffer is consumed and empty if (do_acc_release) { cutlass::arch::fence_view_async_tmem_load(); acc_pipeline.consumer_release(acc_pipe_consumer_state); ++acc_pipe_consumer_state; }
CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tTR_rAcc_frg); ++epi_v) { tTR_rD_frg(epi_v) = cst_callbacks.visit(tTR_rAcc_frg(epi_v), epi_v, epi_m, epi_n); }
Tensor reduction_buffer = make_tensor( raw_pointer_cast(make_smem_ptr(smem_buffer_ptr)), make_layout(Shape<Int<ImplicitSharedStorageSize>>{}));
cst_callbacks.reduce(reduction_buffer, synchronize, epi_m, epi_n, is_last_iteration, tTR_rAcc /*not used*/);
cst_callbacks.end_loop(epi_m, epi_n);
using VecType = uint_bit_t<VD * sizeof_bits_v<ElementD>>; if constexpr (!is_same_v<VecType, uint256_t>) { Tensor tTR_gD_frg = recast<VecType>(coalesce(tTR_gD(_,_,_,epi_m,epi_n))); Tensor tTR_rD_frg = recast<VecType>(coalesce(tTR_rD)); Tensor tTR_pD_frg = tensor<1>(zipped_divide(coalesce(tTR_pCD_mn), mclD.compose(Int<VD>{}))); copy_if(tTR_pD_frg, tTR_rD_frg, tTR_gD_frg); } else { auto tiled_r2g = make_tiled_copy_D(Copy_Atom<SM100_STORE_256bit_CACHE_NOALLOCATION, ElementD>{}, tiled_t2r); auto thr_r2g = tiled_r2g.get_slice(threadIdx.x); Tensor src = thr_r2g.retile_S(tTR_rD); Tensor dst = thr_r2g.retile_D(tTR_gD(_,_,_,epi_m,epi_n)); Tensor prd = thr_r2g.retile_D(tTR_pCD_mn); copy_if(tiled_r2g, prd, src, dst); }
} // for epi_m } // for epi_n
cst_callbacks.end(); };
// // BEGIN EPILOGUE // auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); epi_loop_fn(cst_callbacks); return cute::make_tuple(acc_pipe_consumer_state); }
};
/////////////////////////////////////////////////////////////////////////////////////////////////// For sm100 kernels requiring warp specialized epiloguestemplate < class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class ThreadEpilogueOp_, class CopyOpT2R_, class AlignmentC_, class AlignmentD_>class CollectiveEpilogue< Sm100NoSmemWarpSpecialized, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC_, AlignmentD_> : public detail::Sm100TmaWarpSpecializedAdapter<CollectiveEpilogue< Sm100NoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC_, AlignmentD_, void>>{public: // ctor inheritance using detail::Sm100TmaWarpSpecializedAdapter<CollectiveEpilogue< Sm100NoSmem, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, ThreadEpilogueOp_, CopyOpT2R_, AlignmentC_, AlignmentD_, void>>::Sm100TmaWarpSpecializedAdapter;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/arch/barrier.h"#include "cutlass/conv/convnd_problem_shape.hpp"#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/collective/detail.hpp"#include "cutlass/epilogue/thread/scale_type.h"#include "cutlass/epilogue/fusion/callbacks.hpp"#include "cutlass/epilogue/fusion/sm100_callbacks_tma_warpspecialized.hpp"#include "cutlass/detail/layout.hpp"#include "cutlass/detail/helper_macros.hpp"#include "cutlass/trace.h"
#include "cutlass/conv/detail.hpp"#include "cute/tensor.hpp"#include "cutlass/cuda_host_adapter.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_, class CtaTileShape_, // (CTA_M,CTA_N,CTA_K, optional: Tile_L) class EpilogueTile_, // (EPI_TILE_M, EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpT2R_, class CopyOpG2S_, class SmemLayoutAtomC_, class CopyOpS2R_, class CopyOpS2G_, class SmemLayoutAtomD_, class CopyOpR2S_, class CopyOpR2R_>class CollectiveEpilogue< Sm100TmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, ReuseSmemC_, DelayTmaStore_>, CtaTileShape_, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpT2R_, CopyOpG2S_, SmemLayoutAtomC_, CopyOpS2R_, CopyOpS2G_, SmemLayoutAtomD_, CopyOpR2S_, CopyOpR2R_> {public: // // Type Aliases // using DispatchPolicy = Sm100TmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, ReuseSmemC_, DelayTmaStore_>; using CtaTileShape = CtaTileShape_; using EpilogueTile = EpilogueTile_; using FusionCallbacks = FusionCallbacks_; using ElementC = ElementC_; using StrideC = StrideC_; using ElementD = ElementD_; using StrideD = StrideD_; using CopyOpT2R = CopyOpT2R_; using CopyOpG2S = CopyOpG2S_; using SmemLayoutAtomC = SmemLayoutAtomC_; using CopyOpS2R = CopyOpS2R_; using CopyOpS2G = CopyOpS2G_; using SmemLayoutAtomD = SmemLayoutAtomD_; using CopyOpR2S = CopyOpR2S_; using CopyOpR2R = CopyOpR2R_;
using ThreadEpilogueOp = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::Operation; using GmemTiledCopyC = CopyOpG2S; using GmemTiledCopyD = CopyOpS2G;
constexpr static int ThreadCount = 128;
static_assert(!is_layout<EpilogueTile>::value && is_tuple<EpilogueTile>::value, "EpilogueTile must be a cute::Tile or cute::Shape"); static_assert(rank(EpilogueTile{}) == 2, "EpilogueTile must be rank-2: [EPI_TILE_M, EPI_TILE_N]");
private: using GmemElementD = ElementD; using GmemElementC = cute::conditional_t<cute::is_void_v<ElementC>,ElementD,ElementC>; // prevents void ref breakages using SmemElementD = typename cutlass::detail::get_unpacked_element_type<GmemElementD>::type; using SmemElementC = typename cutlass::detail::get_unpacked_element_type<GmemElementC>::type; constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; static_assert(StagesC >= 1, "StagesC must be >= 1"); static_assert(StagesD >= 1, "StagesD must be >= 1"); constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool is_source_supported = not cute::is_void_v<ElementC>;
constexpr static bool is_m_major_C = detail::is_m_major<StrideC>(); constexpr static bool is_m_major_D = detail::is_m_major<StrideD>();
constexpr static bool is_im2col_C = cute::is_same_v<CopyOpG2S, SM90_TMA_LOAD_IM2COL>; constexpr static bool is_im2col_D = cute::is_same_v<CopyOpS2G, SM90_TMA_STORE_IM2COL>;
using SmemLayoutStageC = decltype(tile_to_shape(SmemLayoutAtomC{}, product_each(shape(EpilogueTile{})), cute::conditional_t<is_m_major_C, Step<_2,_1>, Step<_1,_2>>{} )); using SmemLayoutStageD = decltype(tile_to_shape(SmemLayoutAtomD{}, product_each(shape(EpilogueTile{})), cute::conditional_t<is_m_major_D, Step<_2,_1>, Step<_1,_2>>{} ));
constexpr static int StageCBits = cosize_v<SmemLayoutStageC> * sizeof_bits_v<SmemElementC>; constexpr static int StageDBits = cosize_v<SmemLayoutStageD> * sizeof_bits_v<SmemElementD>; constexpr static int MaxStageBits = cute::max(StageCBits, StageDBits); constexpr static int StrideStageC = (ReuseSmemC ? MaxStageBits : StageCBits) / sizeof_bits_v<SmemElementC>; constexpr static int StrideStageD = (ReuseSmemC ? MaxStageBits : StageDBits) / sizeof_bits_v<SmemElementD>;
using SmemLayoutC = decltype(cute::append<3>(SmemLayoutStageC{}, Layout<Int<StagesC>, Int<StrideStageC>>{})); using SmemLayoutD = decltype(cute::append<3>(SmemLayoutStageD{}, Layout<Int<ReuseSmemC ? StagesC : StagesD>, Int<StrideStageD>>{}));
constexpr static bool support_smem_reuse = is_source_supported && StagesD <= StagesC && MaxStageBits % sizeof_bits_v<SmemElementC> == 0 && MaxStageBits % sizeof_bits_v<SmemElementD> == 0; static_assert(not (ReuseSmemC && not support_smem_reuse), "Smem reuse requirements not met");
constexpr static size_t SmemAlignmentC = cutlass::detail::alignment_for_swizzle(SmemLayoutC{}); constexpr static size_t SmemAlignmentD = cutlass::detail::alignment_for_swizzle(SmemLayoutD{}); constexpr static size_t MaxSmemAlignment = cute::max(SmemAlignmentC, SmemAlignmentD);
// Not unroll epi subtile loop when the activation op is heavy to reduce instruction size and register pressure. constexpr static bool UnrollEpiLoop = not cutlass::epilogue::thread::kIsHeavy_member_or_false<typename ThreadEpilogueOp::ActivationFn>::value; // TMA store delay only benefits with loop unrolling constexpr static bool DelayTmaStore = DelayTmaStore_ and UnrollEpiLoop;
struct CollectiveStorageWithC { alignas(SmemAlignmentC) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageWithoutC { cute::array<SmemElementC, 0> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageReuseC { alignas(MaxSmemAlignment) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(MaxSmemAlignment) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
public: // TMA pipeline for loading C using LoadPipeline = cutlass::PipelineTransactionAsync<StagesC>; using LoadPipelineState = cutlass::PipelineState<StagesC>; constexpr static uint32_t TmaTransactionBytes = StageCBits / 8;
// TMA pipeline for storing D using StorePipeline = cute::conditional_t<ReuseSmemC, cutlass::PipelineTmaStore<StagesC, StagesD-1>, cutlass::PipelineTmaStore<StagesD>>; using StorePipelineState = cutlass::PipelineState<ReuseSmemC ? StagesC : StagesD>;
struct SharedStorage { struct TensorStorage { using CollectiveStorage = cute::conditional_t<not is_source_supported, CollectiveStorageWithoutC, cute::conditional_t<ReuseSmemC, CollectiveStorageReuseC, CollectiveStorageWithC>>; CollectiveStorage collective;
using FusionStorage = typename FusionCallbacks::SharedStorage; FusionStorage thread; } tensors;
using PipelineStorage = typename LoadPipeline::SharedStorage; PipelineStorage pipeline; }; using TensorStorage = typename SharedStorage::TensorStorage; using PipelineStorage = typename SharedStorage::PipelineStorage;
// Planar complex kernels have two accumulator copies for the real and imaginary tensors. constexpr static int NumAccumulatorMtxs = 1;
// Host side epilogue arguments struct Arguments { typename FusionCallbacks::Arguments thread{}; ElementC const* ptr_C = nullptr; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; };
private: static constexpr auto get_tma_epi_tile() { return cute::transform_apply(EpilogueTile{}, seq<0,1>{}, [] (auto epi_tiler, auto mode) { auto cta_tiler_shape = get<mode>(CtaTileShape{}); // Use a dynamic stride to prevent mode coalescing auto cta_tiler_stride = repeat_like(cta_tiler_shape, 0); auto cta_tiler = make_layout(cta_tiler_shape, cta_tiler_stride); // This is a multimodal CTA tiler, transform before returning if constexpr (depth(cta_tiler) > 0) { // This is an implicit multimodal tiler, match profile and return if constexpr (tuple_size_v<decltype(shape(cta_tiler))> == 1) { return make_tile(epi_tiler); } // This is an explicit multimodal tiler, compose out epi tiler else { return shape(composition(cta_tiler, epi_tiler)); } } // This is a flat CTA tiler, no need for transformation else { return epi_tiler; } }, [] (auto... epi_tilers) { return make_tile(epi_tilers...); } ); }
using TmaEpilogueTile = decltype(get_tma_epi_tile());
template <class ProblemShapeMNL> static constexpr auto get_tma_load_c(ProblemShapeMNL const& problem_shape_mnl, Arguments const& args) { Tensor tensor_c = make_tensor(make_gmem_ptr<GmemElementC>(args.ptr_C), make_layout(problem_shape_mnl, append<3>(args.dC, _0{}))); return make_tma_copy(CopyOpG2S{}, tensor_c, SmemLayoutStageC{}, TmaEpilogueTile{}, _1{}); }
template <class ProblemShapeMNL> static constexpr auto get_tma_store_d(ProblemShapeMNL const& problem_shape_mnl, Arguments const& args) { Tensor tensor_d = make_tensor(make_gmem_ptr<GmemElementD>(args.ptr_D), make_layout(problem_shape_mnl, append<3>(args.dD, _0{}))); return make_tma_copy(CopyOpS2G{}, tensor_d, SmemLayoutStageD{}, TmaEpilogueTile{}, _1{}); } public: // Device side epilogue params struct Params { using TMA_C = decltype(get_tma_load_c (repeat_like(append<3>(StrideC{},_1{}), int32_t(0)), Arguments{})); using TMA_D = decltype(get_tma_store_d(repeat_like(append<3>(StrideD{},_1{}), int32_t(0)), Arguments{}));
typename FusionCallbacks::Params thread{}; TMA_C tma_load_c; TMA_D tma_store_d; };
// // Gemm Host Functions //
template <class ProblemShape> static constexpr Params to_underlying_arguments( ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { // Optionally append 1s until problem shape is rank-4 in case its is only rank-3 (MNK) auto problem_shape_mnl = select<0,1,3>(append<4>(problem_shape, 1)); typename Params::TMA_C tma_load_c{}; if constexpr (is_source_supported) { tma_load_c = get_tma_load_c(problem_shape_mnl, args); }
typename Params::TMA_D tma_store_d = get_tma_store_d(problem_shape_mnl, args);
return { FusionCallbacks::to_underlying_arguments(problem_shape, args.thread, workspace), tma_load_c, tma_store_d }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return FusionCallbacks::get_workspace_size(problem_shape, args.thread); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return FusionCallbacks::initialize_workspace(problem_shape, args.thread, workspace, stream, cuda_adapter); }
template <class ProblemShape> static bool can_implement( ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { constexpr int tma_alignment_bits_d = cutlass::detail::get_output_alignment_bits<ElementD>(); auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; auto shape = cute::make_shape(M,N,L);
bool implementable = true; constexpr int min_tma_aligned_elements_D = tma_alignment_bits_d / cutlass::sizeof_bits<ElementD>::value; if constexpr (cute::is_same_v<CopyOpS2G, SM90_TMA_STORE_IM2COL>) { // ignore L stride for implicit gemm implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_D>(take<0,2>(shape), take<0,2>(StrideD{})); } else { implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_D>(shape, StrideD{}); }
if constexpr (is_source_supported) { constexpr int tma_alignment_bits_c = cutlass::detail::get_output_alignment_bits<ElementC>(); constexpr int min_tma_aligned_elements_C = tma_alignment_bits_c / cutlass::sizeof_bits<ElementC>::value; if constexpr (cute::is_same_v<CopyOpG2S, SM90_TMA_LOAD_IM2COL>) { // ignore L stride for implicit gemm implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_C>(take<0,2>(shape), take<0,2>(StrideC{})); } else { implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_C>(shape, StrideC{}); } }
if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); }
bool fusion_implementable = FusionCallbacks::can_implement(problem_shape, args.thread);
if (!fusion_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum requirements for FusionCallbacks.\n"); }
return implementable && fusion_implementable; }
// // Conv Host Functions //
template <conv::Operator ConvOp, int NumDims> static constexpr Params to_underlying_arguments(cutlass::conv::ConvProblemShape<ConvOp,NumDims> const& problem_shape, Arguments const& args, void* workspace) { return to_underlying_arguments(cutlass::conv::detail::get_transformed_problem_shape_MNKL(problem_shape), args, workspace); }
template <conv::Operator ConvOp, int NumDims> static size_t get_workspace_size(cutlass::conv::ConvProblemShape<ConvOp,NumDims> const& problem_shape, Arguments const& args) { return get_workspace_size(cutlass::conv::detail::get_transformed_problem_shape_MNKL(problem_shape), args); }
template <conv::Operator ConvOp, int NumDims> static cutlass::Status initialize_workspace(cutlass::conv::ConvProblemShape<ConvOp,NumDims> const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return initialize_workspace(cutlass::conv::detail::get_transformed_problem_shape_MNKL(problem_shape), args, workspace, stream, cuda_adapter); }
template <conv::Operator ConvOp, int NumDims> static bool can_implement(cutlass::conv::ConvProblemShape<ConvOp,NumDims> const& problem_shape, Arguments const& args) { return can_implement(cutlass::conv::detail::get_transformed_problem_shape_MNKL(problem_shape), args); }
// // Static Device Functions //
template<class CtaTileMNK> CUTLASS_DEVICE static constexpr int get_load_pipe_increment(CtaTileMNK const& cta_tile_mnk) { // Compute number of epilogue subtiles return size<1>(zipped_divide(make_layout(take<0,2>(cta_tile_mnk)), EpilogueTile{})); }
template<class CtaTileMNK> CUTLASS_DEVICE static constexpr int get_store_pipe_increment(CtaTileMNK const& cta_tile_mnk) { return get_load_pipe_increment(cta_tile_mnk); }
/// Issue Tma Descriptor Prefetch -- ideally from a single thread for best performance CUTLASS_DEVICE static void prefetch_tma_descriptors(Params const& epilogue_params) { cute::prefetch_tma_descriptor(epilogue_params.tma_load_c.get_tma_descriptor()); cute::prefetch_tma_descriptor(epilogue_params.tma_store_d.get_tma_descriptor()); }
// // Constructor and Data Members // CUTLASS_DEVICE CollectiveEpilogue(Params const& params_, TensorStorage& shared_tensors) : params(params_), fusion_callbacks(params_.thread, shared_tensors.thread) {}
private: Params const& params; FusionCallbacks fusion_callbacks;
// // Non-static Device Functions //public: CUTLASS_DEVICE bool is_producer_load_needed() const { return fusion_callbacks.is_producer_load_needed(); }
template< bool ReuseTmem = false, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma > CUTLASS_DEVICE auto load( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, TensorStorage& shared_tensors, bool reverse_epi_n = false) { using namespace cute;
int lane_idx = canonical_lane_idx(); auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl;
// The tma tensor C under im2col mode only has two modes (M, N) which // should be local tiled with only (m_coord, n_coord). auto coord_shape = conditional_return<is_im2col_C>(make_coord(m_coord, n_coord), make_coord(m_coord, n_coord, l_coord));
// Represent the full source tensor, slice to get the tile this CTA is currently responsible for Tensor mC_mn = params.tma_load_c.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mC = coalesce(mC_mn, take<0,2>(cta_tile_mnk)); Tensor gC = local_tile(mC, take<0,2>(cta_tile_mnk), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtile, get matching smem tensor auto ptr_sC = shared_tensors.collective.smem_C.begin(); Tensor gC_epi = flat_divide(gC, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor sC_epi = make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{}); // (EPI_TILE_M,EPI_TILE_N,PIPE_C)
// Prepare the thread(b)lock's (G)mem to (S)mem TMA tiled copy (bGS_) ThrCopy thrblk_g2s = params.tma_load_c.get_slice(Int<0>{}); Tensor bGS_gC = thrblk_g2s.partition_S(gC_epi); // (TMA,TMA_M,TMA_N,EPI_M,EPI_N) Tensor bGS_sC = thrblk_g2s.partition_D(sC_epi); // (TMA,TMA_M,TMA_N,PIPE_C)
// Get the fusion callbacks for the producer load warp auto pld_args = cutlass::epilogue::fusion::detail::ProducerLoadArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tiled_mma, EpilogueTile{}, lane_idx }; auto pld_callbacks = fusion_callbacks.get_producer_load_callbacks(pld_args); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// Predication for TMA load (one thread issues TMA load) bool issue_tma_load = cute::elect_one_sync();
// Pre-loop fusion callback entry point pld_callbacks.begin();
CUTLASS_PRAGMA_UNROLL for (int iter_n = 0; iter_n < size<3>(gC_epi); ++iter_n) { CUTLASS_PRAGMA_UNROLL for (int iter_m = 0; iter_m < size<2>(gC_epi); ++iter_m) { int epi_m = iter_m, epi_n = iter_n; if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = size<3>(gC_epi) - 1 - iter_n; } } // Acquire the lock for this stage constexpr uint16_t mcast_mask = 0; uint64_t* tma_barrier = load_pipeline.producer_get_barrier(load_pipe_producer_state); load_pipeline.producer_acquire(load_pipe_producer_state);
// Execute the TMA load for C if needed if (issue_tma_load && is_C_load_needed) { copy(params.tma_load_c.with(*tma_barrier, mcast_mask), bGS_gC(_,_,_,epi_m,epi_n), bGS_sC(_,_,_,load_pipe_producer_state.index())); load_pipeline.producer_expect_transaction(load_pipe_producer_state); }
// Loop fusion callback entry point pld_callbacks.step(tma_barrier, epi_m, epi_n, load_pipe_producer_state.count(), issue_tma_load);
// Commit TMA loads for this stage and release the lock load_pipeline.producer_commit(load_pipe_producer_state); ++load_pipe_producer_state; } }
// Post-loop fusion callback entry point pld_callbacks.end();
return load_pipe_producer_state; }
CUTLASS_DEVICE void load_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, [[maybe_unused]] StorePipeline store_pipeline, [[maybe_unused]] StorePipelineState store_pipe_producer_state) { load_pipeline.producer_tail(load_pipe_producer_state); }
template< bool ReuseTmem = false, class AccumulatorPipeline, class AccumulatorPipelineState, class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, AccumulatorPipeline acc_pipeline, AccumulatorPipelineState acc_pipe_consumer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine,AccLayout> accumulators, TensorStorage& shared_tensors ) { using namespace cute; using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
static_assert(is_tmem<AccEngine>::value, "Accumulator must be TMEM resident."); static_assert(rank(accumulators) == 3, "Accumulators must be MMA-partitioned: [MMA, MMA_M, MMA_N]"); static_assert(size<1>(accumulators) == 1 && size<2>(accumulators) == 1, "TiledMMA must match partitioned ShapeMN"); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(CtaCoordMNKL{}) == 4, "CoordMNKL must be rank 4");
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl; int thread_idx = threadIdx.x % ThreadCount; int warp_idx = thread_idx / NumThreadsPerWarp; [[maybe_unused]] int lane_idx = thread_idx % NumThreadsPerWarp;
// The tma tensor D under im2col mode only has two modes (M, N) which // should be local tiled with only (m_coord, n_coord). auto coord_shape = conditional_return<is_im2col_D>(make_coord(m_coord, n_coord), make_coord(m_coord, n_coord, l_coord));
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mD_mn = params.tma_store_d.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mD = coalesce(mD_mn, take<0,2>(cta_tile_mnk)); Tensor gD = local_tile(mD, take<0,2>(cta_tile_mnk), coord_shape); // (CTA_M,CTA_N)
Tensor tAcc = accumulators(make_coord(_,_),_0{},_0{}); // (CTA_M,CTA_N)
// Apply epilogue subtiling Tensor tAcc_epi = flat_divide(tAcc, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor gD_epi = flat_divide( gD, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
// Construct the corresponding pipelined smem tensors auto ptr_sC = shared_tensors.collective.smem_C.begin(); auto ptr_sD = shared_tensors.collective.smem_D.begin(); Tensor sC_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_C) Tensor sD_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sD), SmemLayoutD{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_D)
// (t)hread-partition for (t)mem to (r)egister copy (tTR_) TiledCopy tiled_t2r = make_tmem_copy(CopyOpT2R{}, tAcc_epi(_,_,_0{},_0{})); ThrCopy thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_tAcc = thread_t2r.partition_S(tAcc_epi); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) Tensor tTR_sD = thread_t2r.partition_D(sD_epi(_,_,_0{})); // (T2R,T2R_M,T2R_N)
// Allocate D and accumulator registers // Does directly store the visitor into smem. constexpr bool IsDirectR2S = cute::is_same_v<CopyOpR2R, AutoVectorizingCopyWithAssumedAlignment<128>>; using RegisterElementD = cute::conditional_t<!IsDirectR2S, ElementCompute, SmemElementD>; Tensor tTR_rAcc = make_tensor<ElementAccumulator>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N) Tensor tTR_rD = make_tensor<RegisterElementD>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N)
// Vectorized fragment view constexpr int FragmentSize = DispatchPolicy::FragmentSize; Tensor tTR_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(coalesce(tTR_rAcc)); // (EPI_V) Tensor tTR_rD_frg = recast<Array<RegisterElementD, FragmentSize>>(coalesce(tTR_rD)); // (EPI_V) CUTE_STATIC_ASSERT(size(tTR_rAcc) % DispatchPolicy::FragmentSize == 0, "Fragment size does not vectorize properly");
// (t)hread-partition for (s)mem to (r)egister copy (tSR_) TiledCopy tiled_s2r = make_tiled_copy_D(Copy_Atom<CopyOpS2R, SmemElementC>{}, tiled_t2r); ThrCopy thread_s2r = tiled_s2r.get_slice(thread_idx); Tensor tSR_sC = thread_s2r.partition_S(sC_epi); // (S2R,S2R_M,S2R_N,PIPE_C) Layout tSR_rC_layout = thread_s2r.retile_D(tTR_rD).layout(); // (S2R,S2R_M,S2R_N)
// Allocate C registers // If C smem load is a non-vectorized dst(i) = src(i) then we can allocate C registers directly in the compute type // to eliminate some redundant pack+unpack instruction sequences for sub-word types constexpr bool IsDirectS2R = cute::is_same_v<CopyOpS2R, AutoVectorizingCopyWithAssumedAlignment<128>> && decltype(max_common_vector(tSR_rC_layout, tSR_sC.layout()))::value <= 1; using RegisterElementC = cute::conditional_t<IsDirectS2R, ElementCompute, SmemElementC>; Tensor tTR_rC = make_tensor<RegisterElementC>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N) Tensor tSR_rC = thread_s2r.retile_D(tTR_rC); // (S2R,S2R_M,S2R_N)
// (t)hread-partition for (r)egister to (r)egister copy (tRR_) TiledCopy tiled_r2r = make_tiled_copy_D(Copy_Atom<CopyOpR2R, RegisterElementD>{}, tiled_t2r); ThrCopy thread_r2r = tiled_r2r.get_slice(thread_idx); Tensor tRR_rD_src = thread_r2r.retile_S(tTR_rD); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N) Tensor tRR_rD_dst = thread_r2r.retile_D(tTR_rD); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N)
// (t)hread-partition for (r)egister to (s)mem copy (tRS_) TiledCopy tiled_r2s = make_tiled_copy_D(Copy_Atom<CopyOpR2S, SmemElementD>{}, tiled_r2r); ThrCopy thread_r2s = tiled_r2s.get_slice(thread_idx); Tensor tRS_sD = thread_r2s.partition_D(sD_epi); // (R2S,R2S_M,R2S_N,PIPE_D) Tensor tRS_rD = [&]() CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (!IsDirectR2S) { return make_tensor<SmemElementD>(shape(tRS_sD(_,_,_,_0{}))); } else{ return thread_r2s.retile_S(tTR_rD); // (R2S,R2S_M,R2S_N) } }();
Tensor tRR_rD_dst_frg = recast<Array<RegisterElementD, FragmentSize>>(coalesce(tRR_rD_dst)); Tensor tRS_rD_frg = recast<Array<SmemElementD, FragmentSize>>(coalesce(tRS_rD));
// thread(b)lock-partition for (s)mem to (g)mem copy (bSG_) ThrCopy thrblk_s2g = params.tma_store_d.get_slice(Int<0>{}); Tensor bSG_sD = thrblk_s2g.partition_S(sD_epi); // (S2G,S2G_M,S2G_N,PIPE_D) Tensor bSG_gD = thrblk_s2g.partition_D(gD_epi); // (S2G,S2G_M,S2G_N,EPI_M,EPI_N)
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(cta_tile_mnk), make_coord(m_coord, n_coord)); // (CTA_M,CTA_N) Tensor tTR_cD_mn = thread_t2r.partition_D(flat_divide(cD_mn, EpilogueTile{})); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (CTA_M,CTA_N) Tensor tTR_cD = make_coord_tensor(tTR_cD_mn.layout()); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = make_coord(M,N) - cD_mn(_0{}); // (m,n) auto residue_tTR_cD = make_coord(M,N) - tTR_cD_mn(_0{}); // (m,n)
// Arguments for the fusion callbacks for the consumer store warps constexpr bool RefSrc = false; // Register tensors reference T2R copy dst layout auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tiled_mma, EpilogueTile{}, tiled_t2r, cD, residue_cD, tTR_cD, residue_tTR_cD, tTR_rC, thread_idx };
// Thread synchronizer for previously issued waits or fences // to ensure visibility of smem reads/writes to threads or TMA unit auto synchronize = [] () { cutlass::arch::NamedBarrier::sync(ThreadCount, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// Predication for sub-128 thread T2R tiled copy Layout tmem_warp_layout = typename decltype(make_tmem_warp_partitioner(tAcc_epi(_,_,0,0)))::TiledLayout_TV{}; constexpr bool predicate_tmem_load = size(tmem_warp_layout) != cosize(tmem_warp_layout); bool issue_tmem_load = true;
// If tmem doesn't have enough capacity to support double buffering, a portion of tmem (a column of epilogue tiles) // is overlapped between 2 pseudo-buffers. The shared tmem portion corresponds to the last epilogue tile column of // tmem accumulator buffer 0, and the first epilogue tile column of tmem accumulator 1. // Thus, whenever we are processing tmem accumulator buffer 0, we process the epilogue tiles with reversed column order. // Once the last epilogue tile column is loaded from tmem, the acc_pipeline is released. // Then, the next accumulation stage for buffer 1 can start. [[maybe_unused]] bool reverse_epi_n = ReuseTmem && acc_pipe_consumer_state.phase() == 0; static_assert(not (ReuseTmem && AccumulatorPipeline::Stages != 1), "Tmem reuse requires 1 accumulator stage");
// Predication for TMA store (one warp issues TMA store) bool issue_tma_store = warp_idx == 0;
// In the reuse smem configuration we have StagesC smem buffers and at most StagesD committed TMA stores in flight. // The TMA store pipeline producer acquire returns when at most StagesD-1 committed stores are in-flight, so we can // only guarantee store completion after StagesD iterations, then we can begin issuing releases on the smem buffer locks. // store_pipe_producer_state tracks the acquire and load_pipe_consumer_state tracks the release, in circular buffer fashion. // If TMA store supported async transaction mbarriers we would not need this synchronous release behavior. LoadPipelineState load_wait_state = load_pipe_consumer_state; if constexpr (ReuseSmemC) { load_wait_state = store_pipe_producer_state; load_wait_state.phase_ ^= 1; }
// We can delay issue of TMA store by one iteration to achieve better interleaving of non-TMA instructions // Sync requirements of smem reuse may preclude this optimization // Delayed stores cause delayed stage releases which causes deadlock when StagesC == StagesD [[maybe_unused]] int epi_m_prev = 0; [[maybe_unused]] int epi_n_prev = 0; static_assert(not (DelayTmaStore and ReuseSmemC and StagesC <= StagesD), "This TMA epilogue configuration will deadlock");
// The Epilogue Loop auto epi_loop_fn = [&] (auto& cst_callbacks) CUTLASS_LAMBDA_FUNC_INLINE { bool is_producer_load_needed = fusion_callbacks.is_producer_load_needed(); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// The TMA store sequence for one epilogue loop iteration auto tma_store_fn = [&] (int epi_m, int epi_n) CUTLASS_LAMBDA_FUNC_INLINE { // Write the tile from smem to gmem with TMA cutlass::arch::fence_view_async_shared(); // ensure smem writes are visible to TMA synchronize(); // ensure all threads have issued their async fence if (issue_tma_store) { copy(params.tma_store_d, bSG_sD(_,_,_,store_pipe_producer_state.index()), bSG_gD(_,_,_,epi_m,epi_n)); } // Post async fence, pre TMA commit callback entry point cst_callbacks.tma_store(epi_m, epi_n, store_pipe_producer_state.count(), issue_tma_store); // Commit the TMA stores for this stage if (issue_tma_store) { store_pipeline.producer_commit(store_pipe_producer_state); } ++store_pipe_producer_state; // Wait for the next smem buffer to be available if (issue_tma_store) { store_pipeline.producer_acquire(store_pipe_producer_state); } synchronize(); if constexpr (ReuseSmemC) { // producer_acquire returns when at most StagesD-1 committed stores are pending bool store_finished = store_pipe_producer_state.count() > StorePipeline::UnacquiredStages; // Let dma warp know earliest smem buffer is consumed and empty after StagesD producer commits if (store_finished) { if (is_producer_load_needed) { load_pipeline.consumer_release(load_pipe_consumer_state); } ++load_pipe_consumer_state; } } }; // tma_store_fn
cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// Begin the wait for the producer load results ConsumerToken load_wait_token{BarrierStatus::WaitDone}; if (is_producer_load_needed) { load_wait_token = load_pipeline.consumer_try_wait(load_wait_state); } // Begin the wait for the accumulator results ConsumerToken acc_wait_token = acc_pipeline.consumer_try_wait(acc_pipe_consumer_state);
// For each epilogue subtile within the CTA tile constexpr int NumEpiSubtilesN = CUTE_STATIC_V(size<3>(gD_epi)); constexpr int NumEpiSubtilesM = CUTE_STATIC_V(size<2>(gD_epi)); #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesN : 1) for (int iter_n = 0; iter_n < NumEpiSubtilesN; ++iter_n) { #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesM : 1) for (int iter_m = 0; iter_m < NumEpiSubtilesM; ++iter_m) { int epi_m = iter_m, epi_n = iter_n; bool is_first_iteration = iter_m == 0 && iter_n == 0; bool is_last_iteration = iter_m == size<2>(gD_epi)-1 && iter_n == size<3>(gD_epi)-1; bool do_acc_release = is_last_iteration;
// Reverse subtile order for tmem reuse if necessary if constexpr (ReuseTmem) { if (reverse_epi_n) { epi_n = size<3>(gD_epi) - 1 - iter_n; } do_acc_release = iter_m == size<2>(gD_epi)-1 && iter_n == 0; }
cst_callbacks.begin_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Wait for the producer load to fill smem load_pipeline.consumer_wait(load_wait_state, load_wait_token);
if (is_C_load_needed) { // Copy source tile from smem to register copy(tiled_s2r, tSR_sC(_,_,_,load_wait_state.index()), tSR_rC); // Ensure smem loads are complete before reusing smem for mixed types/layouts if constexpr (ReuseSmemC && not (SmemLayoutC{} == SmemLayoutD{})) { synchronize(); } } }
// First loop fusion callback entry point cst_callbacks.previsit(epi_m, epi_n, load_wait_state.count(), is_producer_load_needed);
if (is_producer_load_needed) { // Let producer load warp know smem buffers are consumed and empty if constexpr (not ReuseSmemC) { cutlass::arch::fence_view_async_shared(); load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } ++load_wait_state; }
if (is_first_iteration) { // Wait for mma warp to fill tmem buffer with accumulator results acc_pipeline.consumer_wait(acc_pipe_consumer_state, acc_wait_token); }
// The current tile in tmem Tensor tTR_tAcc_mn = tTR_tAcc(_,_,_,epi_m,epi_n);
// Compute tmem load predication if necessary if constexpr (predicate_tmem_load) { // Issue tmem load if this tile's tmem subpartition is accessible by this warp int subpart_idx = (tTR_tAcc_mn.data().dp_ / 32) % 4; issue_tmem_load = warp_idx == subpart_idx; } bool issue_smem_store = issue_tmem_load;
// Copy accumulator tile from tmem to register if (issue_tmem_load) { copy(tiled_t2r, tTR_tAcc_mn, tTR_rAcc); }
// After the last tmem load, signal that tmem buffer is consumed and empty if (do_acc_release) { cutlass::arch::fence_view_async_tmem_load(); acc_pipeline.consumer_release(acc_pipe_consumer_state); ++acc_pipe_consumer_state; }
// Vectorized fragment loop with visitor callback entry point CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tTR_rD_frg); ++epi_v) { tTR_rD_frg(epi_v) = cst_callbacks.visit(tTR_rAcc_frg(epi_v), epi_v, epi_m, epi_n); }
// The latest we can delay the TMA store is right before the smem store of the next iteration // since the current TMA store needs to be committed before we can acquire the next smem buffer if constexpr (DelayTmaStore) { // Issue TMA stores for the previous subtile if (not is_first_iteration) { tma_store_fn(epi_m_prev, epi_n_prev); } epi_m_prev = epi_m; epi_n_prev = epi_n; }
if constexpr (!IsDirectR2S) { // At present, only FP4 col output with scalefactor generation fusion would go into these branch copy(tiled_r2r, tRR_rD_src, tRR_rD_dst); } tRS_rD_frg(_0{}) = cutlass::NumericArrayConverter<SmemElementD, RegisterElementD, FragmentSize>{}(tRR_rD_dst_frg(_0{}));
// Smem reduction callback entry point using current store buffer for workspace Tensor reduction_buffer = make_tensor(raw_pointer_cast(sD_epi(_,_,store_pipe_producer_state.index()).data()), make_layout(stride<2>(get_nonswizzle_portion(SmemLayoutD{})), _1{})); cst_callbacks.reduce(reduction_buffer, synchronize, epi_m, epi_n, is_last_iteration, tRS_rD_frg);
// Copy output tile from register to smem if (issue_smem_store) { copy(tiled_r2s, tRS_rD, tRS_sD(_,_,_,store_pipe_producer_state.index())); }
// Post reduction, pre TMA store callback entry point cst_callbacks.postreduce(epi_m, epi_n, store_pipe_producer_state.count(), issue_smem_store);
if constexpr (not DelayTmaStore) { // Issue TMA stores for this subtile tma_store_fn(epi_m, epi_n); }
cst_callbacks.end_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Begin the wait for the next subtile producer load load_wait_token = load_pipeline.consumer_try_wait(load_wait_state, is_last_iteration); } } // for epi_m } // for epi_n
if constexpr (DelayTmaStore) { // Issue TMA stores for the last subtile tma_store_fn(epi_m_prev, epi_n_prev); }
cst_callbacks.end(); }; // epi_loop_fn
// // BEGIN EPILOGUE // auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); epi_loop_fn(cst_callbacks); return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state, acc_pipe_consumer_state); }
// API with Global Accumulator in registers for FastFP32 (emulated MMA) kernels. // The accumulator in TMEM periodically loaded into the registers so that the MMA can clear out the TMEM accumulator // values for better accuracy. This epilogue accepts the accumulator in registers and take TiledCopy for the // TMEM->Reg as a parameter to be used in partitioning GMEM tensors C and D. template< class ProblemShapeMNKL, class CtaTileMNK, class CtaCoordMNKL, class MmaTileMNK, class TiledMma, class AccEngine, class AccLayout, class TiledCopyT2R > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, CtaTileMNK cta_tile_mnk, CtaCoordMNKL cta_coord_mnkl, MmaTileMNK mma_tile_mnk, TiledMma tiled_mma, cute::Tensor<AccEngine, AccLayout>& tTR_rAcc, // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) TensorStorage& shared_tensors, TiledCopyT2R tiled_t2r ) { using namespace cute; using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
static_assert(is_rmem<AccEngine>::value, "Accumulator must be Register resident."); static_assert(rank(AccLayout{}) == 5, "Accumulators must be copy-partitioned: (T2R,T2R_M,T2R_N,EPI_M,EPI_N)"); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(rank(CtaCoordMNKL{}) == 4, "CoordMNKL must be rank 4");
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = cta_coord_mnkl; int thread_idx = threadIdx.x % ThreadCount; int warp_idx = thread_idx / NumThreadsPerWarp; [[maybe_unused]] int lane_idx = thread_idx % NumThreadsPerWarp;
// The tma tensor D under im2col mode only has two modes (M, N) which // should be local tiled with only (m_coord, n_coord). auto coord_shape = conditional_return<is_im2col_D>(make_coord(m_coord, n_coord), make_coord(m_coord, n_coord, l_coord));
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mD_mn = params.tma_store_d.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mD = coalesce(mD_mn, take<0,2>(cta_tile_mnk)); Tensor gD = local_tile(mD, take<0,2>(cta_tile_mnk), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtiling Tensor gD_epi = flat_divide( gD, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
// Construct the corresponding pipelined smem tensors auto ptr_sC = shared_tensors.collective.smem_C.begin(); auto ptr_sD = shared_tensors.collective.smem_D.begin(); Tensor sC_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_C) Tensor sD_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sD), SmemLayoutD{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_D)
// (t)hread-partition for (t)mem to (r)egister copy (tTR_) ThrCopy thread_t2r = tiled_t2r.get_slice(thread_idx); Tensor tTR_sD = thread_t2r.partition_D(sD_epi(_,_,_0{})); // (T2R,T2R_M,T2R_N)
// Allocate D and accumulator registers Tensor tTR_rD = make_tensor<SmemElementD>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N)
// Vectorized fragment view constexpr int FragmentSize = DispatchPolicy::FragmentSize; Tensor tTR_rD_frg = recast<Array<SmemElementD, FragmentSize>>(coalesce(tTR_rD)); // (EPI_V)
// (t)hread-partition for (s)mem to (r)egister copy (tSR_) TiledCopy tiled_s2r = make_tiled_copy_D(Copy_Atom<CopyOpS2R, SmemElementC>{}, tiled_t2r); ThrCopy thread_s2r = tiled_s2r.get_slice(thread_idx); Tensor tSR_sC = thread_s2r.partition_S(sC_epi); // (S2R,S2R_M,S2R_N,PIPE_C) Layout tSR_rC_layout = thread_s2r.retile_D(tTR_rD).layout(); // (S2R,S2R_M,S2R_N)
// Allocate C registers // If C smem load is a non-vectorized dst(i) = src(i) then we can allocate C registers directly in the compute type // to eliminate some redundant pack+unpack instruction sequences for sub-word types constexpr bool IsDirectS2R = cute::is_same_v<CopyOpS2R, AutoVectorizingCopyWithAssumedAlignment<128>> && decltype(max_common_vector(tSR_rC_layout, tSR_sC.layout()))::value <= 1; using RegisterElementC = cute::conditional_t<IsDirectS2R, ElementCompute, SmemElementC>; Tensor tTR_rC = make_tensor<RegisterElementC>(shape(tTR_sD)); // (T2R,T2R_M,T2R_N) Tensor tSR_rC = thread_s2r.retile_D(tTR_rC); // (S2R,S2R_M,S2R_N)
// (t)hread-partition for (r)egister to (s)mem copy (tRS_) TiledCopy tiled_r2s = make_tiled_copy_D(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_t2r); ThrCopy thread_r2s = tiled_r2s.get_slice(thread_idx); Tensor tRS_rD = thread_r2s.retile_S(tTR_rD); // (R2S,R2S_M,R2S_N) Tensor tRS_sD = thread_r2s.partition_D(sD_epi); // (R2S,R2S_M,R2S_N,PIPE_D)
// thread(b)lock-partition for (s)mem to (g)mem copy (bSG_) ThrCopy thrblk_s2g = params.tma_store_d.get_slice(Int<0>{}); Tensor bSG_sD = thrblk_s2g.partition_S(sD_epi); // (S2G,S2G_M,S2G_N,PIPE_D) Tensor bSG_gD = thrblk_s2g.partition_D(gD_epi); // (S2G,S2G_M,S2G_N,EPI_M,EPI_N)
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(cta_tile_mnk), make_coord(m_coord, n_coord)); // (CTA_M,CTA_N) Tensor tTR_cD_mn = thread_t2r.partition_D(flat_divide(cD_mn, EpilogueTile{})); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (CTA_M,CTA_N) Tensor tTR_cD = make_coord_tensor(tTR_cD_mn.layout()); // (T2R,T2R_M,T2R_N,EPI_M,EPI_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = make_coord(M,N) - cD_mn(_0{}); // (m,n) auto residue_tTR_cD = make_coord(M,N) - tTR_cD_mn(_0{}); // (m,n)
// Get the fusion callbacks for the consumer store warps constexpr bool RefSrc = false; // Register tensors reference T2R copy dst layout auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, cta_tile_mnk, cta_coord_mnkl, tiled_mma, EpilogueTile{}, tiled_t2r, cD, residue_cD, tTR_cD, residue_tTR_cD, tTR_rC, thread_idx };
auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); bool is_producer_load_needed = fusion_callbacks.is_producer_load_needed(); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// Thread synchronizer for previously issued waits or fences // to ensure visibility of smem reads/writes to threads or TMA unit auto synchronize = [] () { cutlass::arch::NamedBarrier::sync(ThreadCount, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// Predication for TMA store (one warp issues TMA store) bool issue_tma_store = warp_idx == 0;
// In the reuse smem configuration we have StagesC smem buffers and at most StagesD committed TMA stores in flight. // The TMA store pipeline producer acquire returns when at most StagesD-1 committed stores are in-flight, so we can // only guarantee store completion after StagesD iterations, then we can begin issuing releases on the smem buffer locks. // store_pipe_producer_state tracks the acquire and load_pipe_consumer_state tracks the release, in circular buffer fashion. // If TMA store supported async transaction mbarriers we would not need this synchronous release behavior. LoadPipelineState load_wait_state = load_pipe_consumer_state; if constexpr (ReuseSmemC) { load_wait_state = store_pipe_producer_state; load_wait_state.phase_ ^= 1; }
// We can delay issue of TMA store by one iteration to achieve better interleaving of non-TMA instructions // Sync requirements of smem reuse may preclude this optimization // Delayed stores cause delayed stage releases which causes deadlock when StagesC == StagesD int epi_m_prev = 0, epi_n_prev = 0; static_assert(not (DelayTmaStore and ReuseSmemC and StagesC <= StagesD), "This TMA epilogue configuration will deadlock");
// The TMA store sequence for one subtile iteration auto tma_store_fn = [&] (int epi_m, int epi_n) CUTLASS_LAMBDA_FUNC_INLINE { // Write the tile from smem to gmem with TMA cutlass::arch::fence_view_async_shared(); // ensure smem writes are visible to TMA synchronize(); // ensure all threads have issued their async fence if (issue_tma_store) { copy(params.tma_store_d, bSG_sD(_,_,_,store_pipe_producer_state.index()), bSG_gD(_,_,_,epi_m,epi_n)); }
// Post async fence, pre TMA commit callback entry point cst_callbacks.tma_store(epi_m, epi_n, store_pipe_producer_state.count(), issue_tma_store);
// Commit the TMA stores for this stage if (issue_tma_store) { store_pipeline.producer_commit(store_pipe_producer_state); } ++store_pipe_producer_state;
// Wait for the next smem buffer to be available if (issue_tma_store) { store_pipeline.producer_acquire(store_pipe_producer_state); } synchronize();
if constexpr (ReuseSmemC) { // producer_acquire returns when at most StagesD-1 committed stores are pending bool store_finished = store_pipe_producer_state.count() > StorePipeline::UnacquiredStages; // Let dma warp know earliest smem buffer is consumed and empty after StagesD producer commits if (store_finished) { if (is_producer_load_needed) { load_pipeline.consumer_release(load_pipe_consumer_state); } ++load_pipe_consumer_state; } } };
// // BEGIN EPILOGUE //
cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// Begin the wait for the producer load results ConsumerToken load_wait_token{BarrierStatus::WaitDone}; if (is_producer_load_needed) { load_wait_token = load_pipeline.consumer_try_wait(load_wait_state); }
// For each epilogue subtile within the CTA tile constexpr int NumEpiSubtilesN = CUTE_STATIC_V(size<3>(gD_epi)); constexpr int NumEpiSubtilesM = CUTE_STATIC_V(size<2>(gD_epi)); #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesN : 1) for (int iter_n = 0; iter_n < NumEpiSubtilesN; ++iter_n) { #pragma unroll(UnrollEpiLoop ? NumEpiSubtilesM : 1) for (int iter_m = 0; iter_m < NumEpiSubtilesM; ++iter_m) { int epi_m = iter_m, epi_n = iter_n; bool is_first_iteration = iter_m == 0 && iter_n == 0; bool is_last_iteration = iter_m == size<2>(gD_epi)-1 && iter_n == size<3>(gD_epi)-1;
cst_callbacks.begin_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Wait for the producer load to fill smem load_pipeline.consumer_wait(load_wait_state, load_wait_token);
if (is_C_load_needed) { // Copy source tile from smem to register copy(tiled_s2r, tSR_sC(_,_,_,load_wait_state.index()), tSR_rC); // Ensure smem loads are complete before reusing smem for mixed types/layouts if constexpr (ReuseSmemC && not (SmemLayoutC{} == SmemLayoutD{})) { synchronize(); } } }
// First loop fusion callback entry point cst_callbacks.previsit(epi_m, epi_n, load_wait_state.count(), is_producer_load_needed);
if (is_producer_load_needed) { // Let producer load warp know smem buffers are consumed and empty if constexpr (not ReuseSmemC) { cutlass::arch::fence_view_async_shared(); load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } ++load_wait_state; }
Tensor tTR_rAcc_epi_tile = tTR_rAcc(_,_,_,epi_m,epi_n); Tensor tTR_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(coalesce(tTR_rAcc_epi_tile)); // (EPI_V)
// Vectorized fragment loop with visitor callback entry point CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tTR_rD_frg); ++epi_v) { tTR_rD_frg(epi_v) = cst_callbacks.visit(tTR_rAcc_frg(epi_v), epi_v, epi_m, epi_n); }
// The latest we can delay the TMA store is right before the smem store of the next iteration // since the current TMA store needs to be committed before we can acquire the next smem buffer if constexpr (DelayTmaStore) { // Issue TMA stores for the previous subtile if (not is_first_iteration) { tma_store_fn(epi_m_prev, epi_n_prev); } epi_m_prev = epi_m; epi_n_prev = epi_n; }
// Smem reduction callback entry point using current store buffer for workspace Tensor reduction_buffer = make_tensor(raw_pointer_cast(sD_epi(_,_,store_pipe_producer_state.index()).data()), make_layout(stride<2>(get_nonswizzle_portion(SmemLayoutD{})), _1{})); cst_callbacks.reduce(reduction_buffer, synchronize, epi_m, epi_n, is_last_iteration, tTR_rD_frg);
// Copy output tile from register to smem bool issue_smem_store = true; if (issue_smem_store) { copy(tiled_r2s, tRS_rD, tRS_sD(_,_,_,store_pipe_producer_state.index())); }
// Post reduction, pre TMA store callback entry point cst_callbacks.postreduce(epi_m, epi_n, store_pipe_producer_state.count(), issue_smem_store);
if constexpr (not DelayTmaStore) { // Issue TMA stores for this subtile tma_store_fn(epi_m, epi_n); }
cst_callbacks.end_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Begin the wait for the next subtile producer load load_wait_token = load_pipeline.consumer_try_wait(load_wait_state, is_last_iteration); } } // for epi_m } // for epi_n
if constexpr (DelayTmaStore) { // Issue TMA stores for the last subtile tma_store_fn(epi_m_prev, epi_n_prev); }
cst_callbacks.end();
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
template <class CtaTileMNK> CUTLASS_DEVICE void store_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, CtaTileMNK cta_tile_mnk) { if constexpr (ReuseSmemC) { if (fusion_callbacks.is_producer_load_needed()) { // wait for all TMA stores to complete store_pipeline.producer_tail(store_pipe_producer_state);
// Issue releases on up to StagesD-1 previously issued TMA stores constexpr int release_stages = cute::min(StorePipeline::UnacquiredStages, get_load_pipe_increment(cta_tile_mnk)); CUTLASS_PRAGMA_UNROLL for (int stage = 0; stage < release_stages; ++stage) { load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } } } }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::collective
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"
#include "cute/tensor.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < class StrideC, class StrideD, class ThreadEpilogueOp, class SmemLayout, class CopyAtomR2S, class TiledCopyS2R, class CopyAtomR2G, class EpilogueScheduleType = EpilogueSimtVectorized, class Enable = void>class Epilogue { static_assert(cute::is_same_v<EpilogueScheduleType, EpilogueSimtVectorized> || cute::is_same_v<EpilogueScheduleType, EpiloguePtrArraySimtVectorized>, "Could not find an epilogue specialization.");};
//////////////////////////////////////////////////////////////////////////////////////////////////// Epilogue Vectorized/// Applies an element wise operation to all elements within the fragment/// and writes it out to destination storage.////// Ways to generalize this:/// - CTA tile shape/// - vectorization requirements (GMEM)/// - vectoriz(able) transform()///template < class StrideC_, class StrideD_, class ThreadEpilogueOp_, class SmemLayout_, class CopyAtomR2S_, class TiledCopyS2R_, class CopyAtomR2G_, class EpilogueScheduleType_>class Epilogue< StrideC_, StrideD_, ThreadEpilogueOp_, SmemLayout_, CopyAtomR2S_, TiledCopyS2R_, CopyAtomR2G_, EpilogueScheduleType_, cute::enable_if_t< cute::is_same_v<EpilogueScheduleType_, EpilogueSimtVectorized> > > {public: // // Type Aliases // // derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementC = typename ThreadEpilogueOp::ElementC; using StrideC = StrideC_; using ElementD = typename ThreadEpilogueOp::ElementD; using StrideD = StrideD_; using ElementBias = typename detail::IsThreadEpilogueOpWithBias<ThreadEpilogueOp>::type; using SmemLayout = SmemLayout_; using CopyAtomR2S = CopyAtomR2S_; using TiledCopyS2R = TiledCopyS2R_; using CopyAtomR2G = CopyAtomR2G_;
using GmemTiledCopyC = void; using GmemTiledCopyD = CopyAtomR2G;
static constexpr bool IsEpilogueBiasSupported = detail::IsThreadEpilogueOpWithBias<ThreadEpilogueOp>::value; using StrideBias = cute::conditional_t<detail::is_m_major<StrideD>(), Stride<_1,_0,int64_t>, Stride<_0,_1,int64_t>>;
static_assert(cute::rank(StrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]"); static_assert(cute::rank(StrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");
struct SharedStorage { cute::array_aligned<ElementAccumulator, cute::cosize_v<SmemLayout>> smem_epilogue; };
static constexpr bool IsActHasArgs = detail::IsThreadEpilogueOpWithElementwiseArguments<ThreadEpilogueOp>::value;
// Host side epilogue arguments template<class ThreadEpiOp, class = void> struct ThreadEpilogueOpArguments { ElementScalar alpha{0}; ElementScalar beta{0}; ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBias const* bias_ptr = nullptr; StrideBias dBias{}; };
template<class ThreadEpiOp> struct ThreadEpilogueOpArguments< ThreadEpiOp, cute::enable_if_t<detail::IsThreadEpilogueOpWithElementwiseArguments<ThreadEpiOp>::value>> { ElementScalar alpha{0}; ElementScalar beta{0}; ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBias const* bias_ptr = nullptr; StrideBias dBias{}; typename ThreadEpiOp::ElementwiseArguments activation{}; };
struct Arguments { ThreadEpilogueOpArguments<ThreadEpilogueOp> thread{}; using StrideBias = decltype(thread.dBias); ElementC const* ptr_C = nullptr; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params template<class ThreadEpiOp, class = void> struct ParamsType { typename ThreadEpiOp::Params thread{}; ElementC const* ptr_C = nullptr; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; ElementBias const* ptr_Bias = nullptr; StrideBias dBias{}; };
template<class ThreadEpiOp> struct ParamsType< ThreadEpiOp, cute::enable_if_t<detail::IsThreadEpilogueOpWithElementwiseArguments<ThreadEpiOp>::value>> { typename ThreadEpiOp::Params thread{}; typename ThreadEpiOp::ElementwiseArguments activation{}; ElementC const* ptr_C = nullptr; StrideC dC{}; ElementD* ptr_D = nullptr; StrideD dD{}; ElementBias const* ptr_Bias = nullptr; StrideBias dBias{}; };
using Params = ParamsType<ThreadEpilogueOp>;
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( [[maybe_unused]] ProblemShape const& _, Arguments const& args, [[maybe_unused]] void* workspace) { typename ThreadEpilogueOp::Params thread_op_args; thread_op_args.alpha = args.thread.alpha; thread_op_args.beta = args.thread.beta; thread_op_args.alpha_ptr = args.thread.alpha_ptr; thread_op_args.beta_ptr = args.thread.beta_ptr;
if constexpr (IsActHasArgs) { return { thread_op_args, args.thread.activation, args.ptr_C, args.dC, args.ptr_D, args.dD, args.thread.bias_ptr, args.thread.dBias }; } else { return { thread_op_args, args.ptr_C, args.dC, args.ptr_D, args.dD, args.thread.bias_ptr, args.thread.dBias }; } }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { return true; }
CUTLASS_HOST_DEVICE Epilogue(Params const& params_) : params(params_), epilogue_op(params_.thread) { }
CUTLASS_DEVICE bool is_source_needed() { return epilogue_op.is_source_needed(); }
template< class ProblemShapeMNKL, class BlockShapeMNK, class BlockCoordMNKL, class FrgEngine, class FrgLayout, class TiledMma, class ResidueMNK > CUTLASS_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, BlockShapeMNK blk_shape_MNK, BlockCoordMNKL blk_coord_mnkl, cute::Tensor<FrgEngine,FrgLayout> const& accumulators, // (MMA,MMA_M,MMA_N) TiledMma tiled_mma, ResidueMNK residue_mnk, int thread_idx, char* smem_buf) { using namespace cute; using X = Underscore;
static_assert(cute::rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<BlockShapeMNK>::value, "ThreadBlock tile shape must be static"); static_assert(cute::rank(BlockShapeMNK{}) == 3, "BlockShapeMNK must be rank 3"); static_assert(cute::rank(BlockCoordMNKL{}) == 4, "BlockCoordMNKL must be rank 3");
// synchronizing function for smem reads/writes#if CUDA_BARRIER_ENABLED auto synchronize = [] () { cutlass::arch::NamedBarrier::sync(typename TiledCopyS2R::TiledNumThr{}, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };#else auto synchronize = [] () { __syncthreads(); };#endif
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl);
// Represent the full output tensor Tensor mC_mnl = make_tensor(make_gmem_ptr(params.ptr_C), make_shape(M,N,L), params.dC); // (m,n,l) Tensor mD_mnl = make_tensor(make_gmem_ptr(params.ptr_D), make_shape(M,N,L), params.dD); // (m,n,l) Tensor mBias_mnl = make_tensor(make_gmem_ptr(params.ptr_Bias), make_shape(M,N,L), params.dBias); // (m,n,l)
Tensor gC_mnl = local_tile(mC_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gD_mnl = local_tile(mD_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gBias_mnl = local_tile(mBias_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l)
// Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = blk_coord_mnkl; Tensor gC = gC_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N) Tensor gD = gD_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N) Tensor gBias = gBias_mnl(_,_,m_coord,n_coord,l_coord); // (BLK_M,BLK_N)
// Construct a tensor in SMEM that we can partition for rearranging data SharedStorage& storage = *reinterpret_cast<SharedStorage*>(smem_buf); Tensor sAcc = make_tensor(make_smem_ptr(storage.smem_epilogue.data()), SmemLayout{}); // (SMEM_M,SMEM_N)
// Partition sAcc to match the accumulator partitioning auto tiled_r2s = make_tiled_copy_C(CopyAtomR2S{}, tiled_mma); auto thread_r2s = tiled_r2s.get_thread_slice(thread_idx); Tensor tRS_rAcc = thread_r2s.retile_S(accumulators); // ((Atom,AtomNum), MMA_M, MMA_N) Tensor tRS_sAcc = thread_r2s.partition_D(sAcc); // ((Atom,AtomNum),PIPE_M,PIPE_N)
// Tile gD and gC by the shape of SmemLayout first auto tile = make_shape(size<0>(sAcc), size<1>(sAcc)); Tensor gCt = flat_divide(gC, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N) Tensor gDt = flat_divide(gD, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N) Tensor gBiast = flat_divide(gBias, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N)
// Partition sAcc, gC, and gD for the output auto tiled_s2r = TiledCopyS2R{}; auto thread_s2r = tiled_s2r.get_thread_slice(thread_idx); Tensor tSR_sAcc = thread_s2r.partition_S(sAcc); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tSR_gC = thread_s2r.partition_D(gCt); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N) Tensor tSR_gD = thread_s2r.partition_D(gDt); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N) Tensor tSR_gBias = thread_s2r.partition_D(gBiast); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N)
// Allocate intermediate registers on the dst tensors Tensor tSR_rAcc = make_tensor<ElementAccumulator>(take<0,3>(shape(tSR_gC))); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tSR_rC = make_tensor<ElementC>(shape(tSR_rAcc)); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tSR_rD = make_tensor<ElementD>(shape(tSR_rAcc)); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tSR_rBias = make_tensor_like(tSR_gBias); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N)
// Repeat the D-partitioning for coordinates and predication Tensor cD = make_identity_tensor(make_shape(size<0>(gD),size<1>(gD))); // (BLK_M,BLK_N) -> (blk_m,blk_n) Tensor cDt = flat_divide(cD, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N) Tensor tSR_cD = thread_s2r.partition_D(cDt); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N)
CUTE_STATIC_ASSERT(size<1>(tRS_rAcc) % size<3>(tSR_gC) == 0); // TILE_M divides MMA_M CUTE_STATIC_ASSERT(size<2>(tRS_rAcc) % size<4>(tSR_gC) == 0); // TILE_N divides MMA_N
#if 0 if (thread_idx == 0 && m_coord == 0 && n_coord == 0) { print("aC : "); print(accumulators.layout()); print("\n"); print("gC : "); print(gC.layout()); print("\n"); print("gD : "); print(gD.layout()); print("\n"); print("gBias : "); print(gBias.layout()); print("\n"); print("sAcc : "); print(sAcc.layout()); print("\n"); print("\n"); print("tRS_sAcc : "); print(tRS_sAcc.layout()); print("\n"); print("tRS_rAcc : "); print(tRS_rAcc.layout()); print("\n"); print("\n"); print("gDt : "); print(gDt.layout()); print("\n"); print("tSR_sAcc : "); print(tSR_sAcc.layout()); print("\n"); print("tSR_rAcc : "); print(tSR_rAcc.layout()); print("\n"); print("\n"); print("tSR_rC : "); print(tSR_rC.layout()); print("\n"); print("tSR_rD : "); print(tSR_rD.layout()); print("\n"); print("tSR_gC : "); print(tSR_gC.layout()); print("\n"); print("tSR_gD : "); print(tSR_gD.layout()); print("\n"); print("\n"); print("gBiast : "); print(gBiast.layout()); print("\n"); print("tSR_gBias : "); print(tSR_gBias.layout()); print("\n"); print("tSR_rBias : "); print(tSR_rBias.layout()); print("\n"); }#endif
if constexpr (IsEpilogueBiasSupported) { if (params.ptr_Bias) { // Filter so we don't issue redundant copies over stride-0 modes // (only works if 0-strides are in same location, which is by construction) Tensor tSR_gBias_flt = filter_zeros(tSR_gBias); Tensor tSR_rBias_flt = filter_zeros(tSR_rBias); Tensor tSR_cD_flt = filter_zeros(tSR_cD, tSR_gBias.stride()); Tensor tSR_pD_flt = cute::lazy::transform(tSR_cD_flt, [&](auto const& c){ return elem_less(c, take<0,2>(residue_mnk)); });
// Step 0. Copy Bias from GMEM to fragment copy_if(tSR_pD_flt, tSR_gBias_flt, tSR_rBias_flt); } }
// For each tiling needed for SmemLayout to cover shape(gD) CUTLASS_PRAGMA_UNROLL for (int step_m = 0; step_m < size<2>(cDt); ++step_m) { CUTLASS_PRAGMA_UNROLL for (int step_n = 0; step_n < size<3>(cDt); ++step_n) { // Step 1. Copy to SMEM CUTLASS_PRAGMA_UNROLL for (int pipe_m = 0; pipe_m < size<1>(tRS_sAcc); ++pipe_m) { CUTLASS_PRAGMA_UNROLL for (int pipe_n = 0; pipe_n < size<2>(tRS_sAcc); ++pipe_n) { int mma_m = step_m * size<1>(tRS_sAcc) + pipe_m; int mma_n = step_n * size<2>(tRS_sAcc) + pipe_n;
copy(tiled_r2s, tRS_rAcc(_,mma_m,mma_n), tRS_sAcc(_,pipe_m,pipe_n)); } }
// Step 2. Wait for SMEM writes to complete synchronize();
// Step 3. Copy from SMEM into a fragment copy(tiled_s2r, tSR_sAcc, tSR_rAcc);
// Step 4. Wait for SMEM reads to complete synchronize();
Tensor tSR_gDmn = tSR_gD(_,_,_,step_m,step_n); Tensor tSR_cDmn = tSR_cD(_,_,_,step_m,step_n);
if constexpr (IsEpilogueBiasSupported) { Tensor tSR_rBiasmn = tSR_rBias(_,_,_,step_m,step_n);
if (epilogue_op.is_source_needed()) { // source is needed Tensor tSR_gCmn = tSR_gC(_,_,_,step_m,step_n);
// Step 5. Copy C from GMEM to a fragment CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size<0>(tSR_rAcc); ++i) { tSR_rC(i,m,n) = tSR_gCmn(i,m,n); } } } }
// Step 6. Elementwise operation with conversion CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tSR_rAcc); ++i) { if constexpr (IsActHasArgs) { epilogue_op(tSR_rD(i), tSR_rD(i), tSR_rAcc(i), tSR_rC(i), tSR_rBiasmn(i), params.activation); } else { epilogue_op(tSR_rD(i), tSR_rD(i), tSR_rAcc(i), tSR_rC(i), tSR_rBiasmn(i)); } } } else { // source is not needed, avoid load and lift compute
// Step 5. Elementwise operation with conversion CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tSR_rAcc); ++i) { if constexpr (IsActHasArgs) { epilogue_op(tSR_rD(i), tSR_rD(i), tSR_rAcc(i), tSR_rBiasmn(i), params.activation); } else { epilogue_op(tSR_rD(i), tSR_rD(i), tSR_rAcc(i), tSR_rBiasmn(i)); } } }
CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { // The Last Step. Copy to GMEM copy(CopyAtomR2G{}, tSR_rD(_,m,n), tSR_gDmn(_,m,n)); } } } } else { if (epilogue_op.is_source_needed()) { // source is needed Tensor tSR_gCmn = tSR_gC(_,_,_,step_m,step_n);
// Step 5. Copy C from GMEM to a fragment CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size<0>(tSR_rAcc); ++i) { tSR_rC(i,m,n) = tSR_gCmn(i,m,n); } } } }
// Step 6. Elementwise operation with conversion CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tSR_rAcc); ++i) { tSR_rD(i) = epilogue_op(tSR_rAcc(i), tSR_rC(i)); } } else { // source is not needed, avoid load and lift compute
// Step 5. Elementwise operation with conversion CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tSR_rAcc); ++i) { tSR_rD(i) = epilogue_op(tSR_rAcc(i)); } }
CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { // The Last Step. Copy to GMEM copy(CopyAtomR2G{}, tSR_rD(_,m,n), tSR_gDmn(_,m,n)); } } } } } } }
private: Params params; ThreadEpilogueOp epilogue_op;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412/*************************************************************************************************** * Copyright (c) 2024 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/epilogue/collective/sm70_epilogue_vectorized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
//////////////////////////////////////////////////////////////////////////////////////////////////// Ptr Array Epilogue Vectorized/// Applies an element wise operation to all elements within the fragment/// and writes it out to destination storage.////// Ways to generalize this:/// - CTA tile shape/// - vectorization requirements (GMEM)/// - vectoriz(able) transform()///template < class StrideC_, class StrideD_, class ThreadEpilogueOp_, class SmemLayout_, class CopyAtomR2S_, class TiledCopyS2R_, class CopyAtomR2G_, class EpilogueScheduleType_>class Epilogue< StrideC_, StrideD_, ThreadEpilogueOp_, SmemLayout_, CopyAtomR2S_, TiledCopyS2R_, CopyAtomR2G_, EpilogueScheduleType_, cute::enable_if_t< cute::is_same_v<EpilogueScheduleType_, EpiloguePtrArraySimtVectorized> > > {public: // // Type Aliases // // derived types of output thread level operator using ThreadEpilogueOp = ThreadEpilogueOp_; using ElementAccumulator = typename ThreadEpilogueOp::ElementAccumulator; using ElementCompute = typename ThreadEpilogueOp::ElementCompute; using ElementScalar = ElementCompute; using ElementOutput = typename ThreadEpilogueOp::ElementOutput; using ElementC = typename ThreadEpilogueOp::ElementC; using StrideC = StrideC_; using InternalStrideC = cute::remove_pointer_t<StrideC>; using ElementD = typename ThreadEpilogueOp::ElementD; using StrideD = StrideD_; using InternalStrideD = cute::remove_pointer_t<StrideD>;
using SmemLayout = SmemLayout_; using CopyAtomR2S = CopyAtomR2S_; using TiledCopyS2R = TiledCopyS2R_; using CopyAtomR2G = CopyAtomR2G_;
using GmemTiledCopyC = TiledCopyS2R; using GmemTiledCopyD = TiledCopyS2R;
static const int kOutputAlignment = ThreadEpilogueOp::kCount;
using AlignmentType = typename cute::uint_bit<sizeof_bits<ElementOutput>::value * kOutputAlignment>::type;
static_assert(cute::rank(InternalStrideC{}) == 3, "StrideCD must be rank-3: [M, N, L]"); static_assert(cute::rank(InternalStrideD{}) == 3, "StrideCD must be rank-3: [M, N, L]");
struct SharedStorage { cute::array_aligned<ElementAccumulator, cute::cosize_v<SmemLayout>> smem_epilogue; };
using TensorMapStorage = SharedStorage;
// Host side epilogue arguments struct Arguments { typename ThreadEpilogueOp::Params thread{}; ElementC const** ptr_C = nullptr; StrideC dC{}; ElementD** ptr_D = nullptr; StrideD dD{}; };
// Device side epilogue params using Params = Arguments;
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( ProblemShape const&, Arguments const& args, [[maybe_unused]] void* workspace) { return args; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int sm_count) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
template <class ProblemShape> static bool can_implement( [[maybe_unused]] ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { return true; }
CUTLASS_HOST_DEVICE Epilogue(Params const& params_) : params(params_) { }
CUTLASS_DEVICE bool is_source_needed() { // For Ptr-Array or Grouped Gemm we cannot determine if source is needed based on first beta. return true; }
template< class ProblemShapeMNKL, class BlockShapeMNK, class BlockCoordMNKL, class FrgEngine, class FrgLayout, class TiledMma, class ResidueMNK > CUTLASS_DEVICE void operator()( ProblemShapeMNKL problem_shape_mnkl, BlockShapeMNK blk_shape_MNK, BlockCoordMNKL blk_coord_mnkl, cute::Tensor<FrgEngine,FrgLayout> const& accumulators, // (MMA,MMA_M,MMA_N) TiledMma tiled_mma, ResidueMNK residue_mnk, int thread_idx, char* smem_buf) { using namespace cute; using X = Underscore;
static_assert(cute::rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<BlockShapeMNK>::value, "ThreadBlock tile shape must be static"); static_assert(cute::rank(BlockShapeMNK{}) == 3, "BlockShapeMNK must be rank 3"); static_assert(cute::rank(BlockCoordMNKL{}) == 4, "BlockCoordMNKL must be rank 3");
// synchronizing function for smem reads/writes#if CUDA_BARRIER_ENABLED auto synchronize = [] () { cutlass::arch::NamedBarrier::sync(typename TiledCopyS2R::TiledNumThr{}, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };#else auto synchronize = [] () { __syncthreads(); };#endif
// Separate out problem shape for convenience auto M = get<0>(problem_shape_mnkl); auto N = get<1>(problem_shape_mnkl); auto L = get<3>(problem_shape_mnkl); // Batches are managed by using appropriate pointers to C and D matrices const int32_t mock_L = 1; const int32_t mock_l_coord = 0; // Slice to get the tile this CTA is responsible for auto [m_coord, n_coord, k_coord, l_coord] = blk_coord_mnkl;
// If scalar alpha/beta are provided, i.e., same alpha/beta applies to all batches/groups. // If pointers to alpha/beta are provided, i.e., alpha/beta can differ between batches/groups, // we get the correct alpha/beta values for the current batch/group using group index. ThreadEpilogueOp epilogue_op = ThreadEpilogueOp(params.thread, l_coord);
if (epilogue_op.is_source_needed() && params.dC == nullptr) { // Beta value is non-zero while pointer to C is a nullptr assert(0); }
InternalStrideC stride_c; InternalStrideD stride_d; if constexpr (!cute::is_same_v<InternalStrideC, StrideC>) { // If grouped gemm if (epilogue_op.is_source_needed()) { stride_c = params.dC[l_coord]; } stride_d = params.dD[l_coord]; } else { stride_c = params.dC; stride_d = params.dD; }
// Represent the full output tensor ElementC const* ptr_C_l = nullptr; if (epilogue_op.is_source_needed()) { ptr_C_l = params.ptr_C[l_coord]; } Tensor mC_mnl = make_tensor(make_gmem_ptr(ptr_C_l), make_shape(M,N,mock_L), stride_c); // (m,n,l) Tensor mD_mnl = make_tensor(make_gmem_ptr(params.ptr_D[l_coord]), make_shape(M,N,mock_L), stride_d); // (m,n,l) Tensor gC_mnl = local_tile(mC_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l) Tensor gD_mnl = local_tile(mD_mnl, blk_shape_MNK, make_coord(_,_,_), Step<_1,_1, X>{}); // (BLK_M,BLK_N,m,n,l)
Tensor gC = gC_mnl(_,_,m_coord,n_coord,mock_l_coord); // (BLK_M,BLK_N) Tensor gD = gD_mnl(_,_,m_coord,n_coord,mock_l_coord); // (BLK_M,BLK_N)
// Construct a tensor in SMEM that we can partition for rearranging data SharedStorage& storage = *reinterpret_cast<SharedStorage*>(smem_buf); Tensor sAcc = make_tensor(make_smem_ptr(storage.smem_epilogue.data()), SmemLayout{}); // (SMEM_M,SMEM_N)
// Partition sAcc to match the accumulator partitioning auto tiled_r2s = make_tiled_copy_C(CopyAtomR2S{}, tiled_mma); auto thread_r2s = tiled_r2s.get_thread_slice(thread_idx); Tensor tRS_rAcc = thread_r2s.retile_S(accumulators); // ((Atom,AtomNum), MMA_M, MMA_N) Tensor tRS_sAcc = thread_r2s.partition_D(sAcc); // ((Atom,AtomNum),PIPE_M,PIPE_N)
// Tile gD and gC by the shape of SmemLayout first auto tile = make_shape(size<0>(sAcc), size<1>(sAcc)); Tensor gCt = flat_divide(gC, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N) Tensor gDt = flat_divide(gD, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N)
// Partition sAcc, gC, and gD for the output auto tiled_s2r = TiledCopyS2R{}; auto thread_s2r = tiled_s2r.get_thread_slice(thread_idx); Tensor tSR_sAcc = thread_s2r.partition_S(sAcc); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tSR_gC = thread_s2r.partition_D(gCt); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N) Tensor tSR_gD = thread_s2r.partition_D(gDt); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N)
// Allocate intermediate registers on the dst tensors Tensor tSR_rAcc = make_tensor<ElementAccumulator>(take<0,3>(shape(tSR_gC))); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tSR_rD = make_tensor<ElementOutput>(shape(tSR_rAcc)); // ((Atom,AtomNum),ATOM_M,ATOM_N)
// Repeat the D-partitioning for coordinates and predication Tensor cD = make_identity_tensor(make_shape(size<0>(gD),size<1>(gD))); // (BLK_M,BLK_N) -> (blk_m,blk_n) Tensor cDt = flat_divide(cD, tile); // (SMEM_M,SMEM_N,TILE_M,TILE_N) Tensor tSR_cD = thread_s2r.partition_D(cDt); // ((Atom,AtomNum),ATOM_M,ATOM_N,TILE_M,TILE_N)
CUTE_STATIC_ASSERT(size<1>(tRS_rAcc) % size<3>(tSR_gC) == 0); // TILE_M divides MMA_M CUTE_STATIC_ASSERT(size<2>(tRS_rAcc) % size<4>(tSR_gC) == 0); // TILE_N divides MMA_N
#if 0 if (thread_idx == 0 && m_coord == 0 && n_coord == 0) { print("aC : "); print(accumulators.layout()); print("\n"); print("gC : "); print(gC.layout()); print("\n"); print("gD : "); print(gD.layout()); print("\n"); print("sAcc : "); print(sAcc.layout()); print("\n"); print("\n"); print("tRS_sAcc : "); print(tRS_sAcc.layout()); print("\n"); print("tRS_rAcc : "); print(tRS_rAcc.layout()); print("\n"); print("\n"); print("gDt : "); print(gDt.layout()); print("\n"); print("tSR_sAcc : "); print(tSR_sAcc.layout()); print("\n"); print("tSR_rAcc : "); print(tSR_rAcc.layout()); print("\n"); print("\n"); print("tSR_rD : "); print(tSR_rD.layout()); print("\n"); print("tSR_gC : "); print(tSR_gC.layout()); print("\n"); print("tSR_gD : "); print(tSR_gD.layout()); print("\n"); print("\n"); }#endif
// For each tiling needed for SmemLayout to cover shape(gD) CUTLASS_PRAGMA_UNROLL for (int step_m = 0; step_m < size<2>(cDt); ++step_m) { CUTLASS_PRAGMA_UNROLL for (int step_n = 0; step_n < size<3>(cDt); ++step_n) { // Step 1. Copy to SMEM CUTLASS_PRAGMA_UNROLL for (int pipe_m = 0; pipe_m < size<1>(tRS_sAcc); ++pipe_m) { CUTLASS_PRAGMA_UNROLL for (int pipe_n = 0; pipe_n < size<2>(tRS_sAcc); ++pipe_n) { int mma_m = step_m * size<1>(tRS_sAcc) + pipe_m; int mma_n = step_n * size<2>(tRS_sAcc) + pipe_n;
copy(tiled_r2s, tRS_rAcc(_,mma_m,mma_n), tRS_sAcc(_,pipe_m,pipe_n)); } }
// Step 2. Wait for SMEM writes to complete synchronize();
// Step 3. Copy from SMEM into a fragment copy(tiled_s2r, tSR_sAcc, tSR_rAcc);
// Step 4. Wait for SMEM reads to complete synchronize();
Tensor tSR_gDmn = tSR_gD(_,_,_,step_m,step_n); Tensor tSR_cDmn = tSR_cD(_,_,_,step_m,step_n);
if (epilogue_op.is_source_needed()) { // source is needed Tensor tSR_gCmn = tSR_gC(_,_,_,step_m,step_n);
Tensor tSR_rCmn = make_tensor<ElementC>(shape(tSR_gCmn)); // ((Atom,AtomNum),ATOM_M,ATOM_N)
// Step 5. Copy C from GMEM to a fragment CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size<0>(tSR_rAcc); ++i) { tSR_rCmn(i,m,n) = tSR_gCmn(i,m,n); } } } }
CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { // Step 6. Elementwise operation with conversion CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size<0>(tSR_rAcc); ++i) { tSR_rD(i,m,n) = epilogue_op(tSR_rAcc(i,m,n), tSR_rCmn(i,m,n)); } // Step 7. Copy to GMEM copy(CopyAtomR2G{}, tSR_rD(_,m,n), tSR_gDmn(_,m,n)); } } } } else { // source is not needed, avoid load and lift compute
// Step 5. Elementwise operation with conversion CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tSR_rAcc); ++i) { tSR_rD(i) = epilogue_op(tSR_rAcc(i)); }
CUTLASS_PRAGMA_UNROLL for (int m = 0; m < size<1>(tSR_gDmn); ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < size<2>(tSR_gDmn); ++n) { // Predication if (elem_less(tSR_cDmn(0,m,n), take<0,2>(residue_mnk))) { // Step 6. Copy to GMEM copy(CopyAtomR2G{}, tSR_rD(_,m,n), tSR_gDmn(_,m,n)); } } } } } } }
private: Params params;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/arch/barrier.h"#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/collective/detail.hpp"#include "cutlass/epilogue/thread/scale_type.h"#include "cutlass/epilogue/fusion/callbacks.hpp"#include "cutlass/epilogue/fusion/sm90_callbacks_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm120_callbacks_tma_warpspecialized.hpp"#include "cutlass/detail/collective.hpp"#include "cutlass/detail/layout.hpp"#include "cutlass/trace.h"#include "cutlass/cuda_host_adapter.hpp"
#include "cute/tensor.hpp"#include "cute/atom/copy_traits_sm90_tma.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_, int NumEpilogueWarpGroups_, class CtaTileMNK_, // (CTA_M,CTA_N,CTA_K) class EpilogueTile_, // (EPI_TILE_M,EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpG2S_, class SmemLayoutAtomC_, class CopyOpS2R_, class CopyOpS2G_, class SmemLayoutAtomD_, class CopyOpR2S_, class CopyAtomC_, class CopyOpR2R_>class CollectiveEpilogue< Sm90PtrArrayTmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, ReuseSmemC_, DelayTmaStore_, NumEpilogueWarpGroups_ >, CtaTileMNK_, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpG2S_, SmemLayoutAtomC_, CopyOpS2R_, CopyOpS2G_, SmemLayoutAtomD_, CopyOpR2S_, CopyAtomC_, CopyOpR2R_> {public: // // Type Aliases // using DispatchPolicy = Sm90PtrArrayTmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, ReuseSmemC_, DelayTmaStore_, NumEpilogueWarpGroups_ >; using CtaTileMNK = CtaTileMNK_; using EpilogueTile = EpilogueTile_; using FusionCallbacks = FusionCallbacks_; using ElementC = ElementC_; using StrideC = StrideC_; using InternalStrideC = cute::remove_pointer_t<StrideC>; using ElementD = ElementD_; using StrideD = StrideD_; using InternalStrideD = cute::remove_pointer_t<StrideD>; using CopyOpG2S = CopyOpG2S_; using SmemLayoutAtomC = SmemLayoutAtomC_; using CopyOpS2R = CopyOpS2R_; using CopyOpS2G = CopyOpS2G_; using SmemLayoutAtomD = SmemLayoutAtomD_; using CopyOpR2S = CopyOpR2S_; using CopyAtomC = CopyAtomC_; using CopyOpR2R = CopyOpR2R_;
using ThreadEpilogueOp = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::Operation; using GmemTiledCopyC = CopyOpG2S; using GmemTiledCopyD = CopyOpS2G;
static_assert(!is_layout<EpilogueTile>::value && is_tuple<EpilogueTile>::value, "EpilogueTile must be a cute::Tile or cute::Shape"); static_assert(cute::rank(CtaTileMNK{}) == 3, "CtaTileMNK must be rank-3: [CTA_M, CTA_N, CTA_K]"); static_assert(cute::rank(EpilogueTile{}) == 2, "EpilogueTile must be rank-2: [EPI_TILE_M, EPI_TILE_N]"); static_assert(size<0>(CtaTileMNK{}) % size<0>(shape(EpilogueTile{})) == 0, "EPI_TILE_M must divide CTA_M"); static_assert(size<1>(CtaTileMNK{}) % size<1>(shape(EpilogueTile{})) == 0, "EPI_TILE_N must divide CTA_N"); static_assert(cute::rank(InternalStrideC{}) == 3, "StrideC must be rank-3: [M, N, L]"); static_assert(cute::rank(InternalStrideD{}) == 3, "StrideD must be rank-3: [M, N, L]");
private: constexpr static bool is_source_supported = not cute::is_void_v<ElementC>; constexpr static bool is_destination_supported = not cute::is_void_v<ElementD>; using NonVoidElementD = cute::conditional_t<not is_destination_supported,fusion::get_element_aux_t<FusionCallbacks>, ElementD>; static_assert(not cute::is_void_v<NonVoidElementD>, "SmemElementD is void"); using NonVoidElementC = cute::conditional_t<not is_source_supported,NonVoidElementD,ElementC>; // prevents void ref breakages
using SmemElementC = typename cutlass::detail::get_unpacked_element_type<NonVoidElementC>::type; using SmemElementD = typename cutlass::detail::get_unpacked_element_type<NonVoidElementD>::type;
constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static bool ReuseSmemC = ReuseSmemC_ and is_destination_supported; constexpr static bool DelayTmaStore = DelayTmaStore_;
constexpr static bool is_m_major_C = detail::is_m_major<InternalStrideC>(); constexpr static bool is_m_major_D = detail::is_m_major<InternalStrideD>();
constexpr static bool is_im2col_C = cute::is_same_v<CopyOpG2S, SM90_TMA_LOAD_IM2COL>; constexpr static bool is_im2col_D = cute::is_same_v<CopyOpS2G, SM90_TMA_STORE_IM2COL>;
// Check if register transformation is needed before copying register to shared memory. constexpr static bool IsUseR2R = !cute::is_void_v<CopyOpR2R>;
using SmemLayoutC = decltype(tile_to_shape( SmemLayoutAtomC{}, make_shape(size<0>(EpilogueTile{}), size<1>(EpilogueTile{}), Int<StagesC>{}), cute::conditional_t<is_m_major_C, Step<_2,_1,_3>, Step<_1,_2,_3>>{} )); using SmemLayoutD = decltype(tile_to_shape( SmemLayoutAtomD{}, make_shape(size<0>(EpilogueTile{}), size<1>(EpilogueTile{}), Int<ReuseSmemC ? StagesC : StagesD>{}), cute::conditional_t<is_m_major_D, Step<_2,_1,_3>, Step<_1,_2,_3>>{} ));
constexpr static bool support_smem_reuse = is_source_supported && is_destination_supported && StagesD <= StagesC && cosize(take<0,2>(SmemLayoutC{})) == cosize(take<0,2>(SmemLayoutD{})); static_assert(not (ReuseSmemC && not support_smem_reuse), "Smem reuse requirements not met");
constexpr static size_t SmemAlignmentD = cutlass::detail::alignment_for_swizzle(SmemLayoutD{}); constexpr static size_t SmemAlignmentC = cutlass::detail::alignment_for_swizzle(SmemLayoutC{}); constexpr static size_t MaxSmemAlignment = cute::max(SmemAlignmentC, SmemAlignmentD);
using SmemArrayTypeC = cute::ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>>; using SmemArrayTypeD = cute::ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>>;
using EmptyType = cute::tuple<>; using SmemCStorage = cute::conditional_t<is_source_supported and (not ReuseSmemC), SmemArrayTypeC, EmptyType>; using SmemDStorage = cute::conditional_t<is_destination_supported, SmemArrayTypeD, EmptyType>;
struct CollectiveStorageWithC { alignas(SmemAlignmentC) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageWithoutC { cute::array<SmemElementC, 0> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageReuseC { alignas(MaxSmemAlignment) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(MaxSmemAlignment) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
public: // TMA pipeline for loading C using LoadPipeline = cutlass::PipelineTransactionAsync<StagesC>; using LoadPipelineState = cutlass::PipelineState<StagesC>; constexpr static uint32_t TmaTransactionBytes = (size(take<0,2>(SmemLayoutC{})) * static_cast<uint32_t>(sizeof_bits<SmemElementC>::value)) / 8; constexpr static bool RequiresTransactionBytes = true;
constexpr static int NumEpilogueWarpGroups = NumEpilogueWarpGroups_; constexpr static uint32_t MinTensorMapWorkspaceAlignment = 64;
// TMA pipeline for storing D using StorePipeline = cute::conditional_t<ReuseSmemC, cutlass::PipelineTmaStore<StagesC, StagesD-1>, cutlass::PipelineTmaStore<StagesD>>; using StorePipelineState = cutlass::PipelineState<ReuseSmemC ? StagesC : StagesD>;
struct SharedStorage { struct TensorStorage { using CollectiveStorage = cute::conditional_t<not is_source_supported, CollectiveStorageWithoutC, cute::conditional_t<ReuseSmemC, CollectiveStorageReuseC, CollectiveStorageWithC>>; CollectiveStorage collective;
using FusionStorage = typename FusionCallbacks::SharedStorage; FusionStorage thread; } tensors;
struct TensorMapStorage : cute::aligned_struct<128, _0> { cute::TmaDescriptor smem_tensormap_C; cute::array<cute::TmaDescriptor, NumEpilogueWarpGroups> smem_tensormap_D; } tensormaps;
using PipelineStorage = typename LoadPipeline::SharedStorage; PipelineStorage pipeline; }; using TensorStorage = typename SharedStorage::TensorStorage; using TensorMapStorage = typename SharedStorage::TensorMapStorage; using PipelineStorage = typename SharedStorage::PipelineStorage;
static constexpr bool IsGroupedGemmKernel = !cute::is_same_v<InternalStrideC, StrideC>;
// Host side epilogue arguments struct Arguments { typename FusionCallbacks::Arguments thread{}; ElementC const** ptr_C = nullptr; StrideC dC; ElementD ** ptr_D = nullptr; StrideD dD; };
// Device side epilogue params struct Params { using TMA_C = decltype(make_tma_copy( CopyOpG2S{}, make_tensor(make_gmem_ptr(static_cast<NonVoidElementC const*>(nullptr)), repeat_like(InternalStrideC{}, int32_t(0)), InternalStrideC{}), take<0,2>(SmemLayoutC{}), EpilogueTile{}, _1{}));
using TMA_D = decltype(make_tma_copy( CopyOpS2G{}, make_tensor(make_gmem_ptr(static_cast<NonVoidElementD const*>(nullptr)), repeat_like(InternalStrideD{}, int32_t(0)), InternalStrideD{}), take<0,2>(SmemLayoutD{}), EpilogueTile{}, _1{}));
typename FusionCallbacks::Params thread{}; TMA_C tma_load_c; TMA_D tma_store_d; cute::TmaDescriptor* tensormaps; ElementC const** ptr_C; StrideC dC; ElementD** ptr_D; StrideD dD; uint32_t tma_transaction_bytes = TmaTransactionBytes; };
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { // These tensor shapes (only applicable for grouped gemm) and pointers are only used to create tensormap/tma desc. // These will be replaced with correct values before the initial tma load. auto init_M = int32_t(size<0>(CtaTileMNK{})); auto init_N = int32_t(size<1>(CtaTileMNK{})); auto init_L = 1;
static_assert(!is_im2col_C and !is_im2col_D, "Im2Col not supported on C or D");
InternalStrideC stride_c; InternalStrideD stride_d; if constexpr (IsGroupedGemmKernel) { // Strides for Grouped Gemm will be replaced prior to the first access regardless. stride_c = InternalStrideC{}; stride_d = InternalStrideD{}; } else { // Tensor shapes for Ptr-Array are initialized correctly only here. auto problem_shape_MNKL = append<4>(problem_shape.get_host_problem_shape(0), 1); init_M = get<0>(problem_shape_MNKL); init_N = get<1>(problem_shape_MNKL); stride_c = args.dC; stride_d = args.dD; }
uint32_t transaction_bytes = TmaTransactionBytes; typename Params::TMA_C tma_load_c{}; if constexpr (is_source_supported) { // NOTE: Since TMA desc creation with nullptr not possible until 12.6, we use an initial address even when tensor addresses are on device. This address is never used. ElementC const* ptr_C_first_batch = reinterpret_cast<ElementC const*>(reinterpret_cast<uint64_t>(args.ptr_C) & 0xFFFFFFFFFFFFFFF0); // Address must be 16B-aligned Tensor tensor_c = make_tensor(ptr_C_first_batch, make_layout(make_shape(init_M,init_N,init_L), append<3>(stride_c, _0{}))); tma_load_c = make_tma_copy( CopyOpG2S{}, tensor_c, take<0,2>(SmemLayoutC{}), EpilogueTile{}, _1{}); }
typename Params::TMA_D tma_store_d{}; if constexpr (is_destination_supported) { // NOTE: Since TMA desc creation with nullptr not possible until 12.6, we use an initial address even when tensor addresses are on device. This address is never used. ElementD const* ptr_D_first_batch = reinterpret_cast<ElementD const*>(reinterpret_cast<uint64_t>(args.ptr_D) & 0xFFFFFFFFFFFFFFF0); // Address must be 16B-aligned Tensor tensor_d = make_tensor(ptr_D_first_batch, make_layout(make_shape(init_M,init_N,init_L), append<3>(stride_d, _0{}))); tma_store_d = make_tma_copy( CopyOpS2G{}, tensor_d, take<0,2>(SmemLayoutD{}), EpilogueTile{}, _1{}); }
auto fusion_workspace = static_cast<char*>(workspace); auto fusion_workspace_size = round_nearest(FusionCallbacks::get_workspace_size(problem_shape, args.thread), MinTensorMapWorkspaceAlignment); auto tma_descriptor_workspace = reinterpret_cast<cute::TmaDescriptor*>( static_cast<char*>(workspace) + fusion_workspace_size);
return { FusionCallbacks::to_underlying_arguments(problem_shape, args.thread, fusion_workspace), tma_load_c, tma_store_d, tma_descriptor_workspace, args.ptr_C, args.dC, args.ptr_D, args.dD, transaction_bytes, }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args, int sm_count) { constexpr uint32_t NumInputTensors = NumEpilogueWarpGroups + (cute::is_void_v<ElementC> ? 0 : 1); auto descriptors_shape = cute::make_shape(sm_count, Int<NumInputTensors>{}); constexpr size_t SizeOfCuTensorMap = sizeof(cute::TmaDescriptor); // Allocate gmem space for input tensormaps per each SM, A tensormap copies followed by B tensormap copies return (size(descriptors_shape) * SizeOfCuTensorMap) + (round_nearest(FusionCallbacks::get_workspace_size(problem_shape, args.thread), MinTensorMapWorkspaceAlignment)); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return FusionCallbacks::initialize_workspace(problem_shape, args.thread, workspace, stream, cuda_adapter); }
template <class ProblemShape> static bool can_implement( ProblemShape problem_shape, [[maybe_unused]] Arguments const& args) {
bool implementable = true; bool fusion_implementable = true;
if (problem_shape.is_host_problem_shape_available()) { for (int i = 0; i < problem_shape.groups(); ++i) { auto problem_shape_MNKL = append<4>(problem_shape.get_host_problem_shape(i), 1); auto [M,N,K,L] = problem_shape_MNKL;
if constexpr (is_destination_supported) { constexpr int tma_alignment_bits_D = cutlass::detail::get_output_alignment_bits<ElementD>(); constexpr int min_tma_aligned_elements_D = tma_alignment_bits_D / cutlass::sizeof_bits<ElementD>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_D>(cute::make_shape(M,N,L), InternalStrideD{}); }
if constexpr (is_source_supported) { constexpr int tma_alignment_bits_C = cutlass::detail::get_input_alignment_bits<ElementC>(); constexpr int min_tma_aligned_elements_C = tma_alignment_bits_C / cutlass::sizeof_bits<ElementC>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_C>(cute::make_shape(M,N,L), InternalStrideC{}); }
fusion_implementable = fusion_implementable && FusionCallbacks::can_implement(problem_shape_MNKL, args.thread); } } else { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Ignoring check to can implement because host problem shape is not available.\n"); }
if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); }
if (!fusion_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum requirements for FusionCallbacks.\n"); }
bool beta_implementable = true;
if (cute::is_void_v<ElementC> || args.ptr_C == nullptr) { if constexpr (detail::has_beta<Arguments>::value) { beta_implementable = args.thread.beta == 0.0; } if constexpr (detail::has_beta_ptr<Arguments>::value) { beta_implementable = beta_implementable && args.thread.beta_ptr == nullptr; } if constexpr (detail::has_beta_ptr_array<Arguments>::value) { beta_implementable = beta_implementable && args.thread.beta_ptr_array == nullptr; } }
if (!beta_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Beta/beta pointer was set, but epilogue is sourceless (void-C).\n"); }
return implementable && fusion_implementable && beta_implementable; }
template<class TileShapeMNK> CUTLASS_HOST_DEVICE static constexpr int get_load_pipe_increment(TileShapeMNK tile_shape_MNK) { // Compute number of epilogue subtiles return size<1>(zipped_divide(make_layout(take<0,2>(tile_shape_MNK)), EpilogueTile{})); }
template<class TileShapeMNK> CUTLASS_HOST_DEVICE static constexpr int get_store_pipe_increment(TileShapeMNK tile_shape_MNK) { return get_load_pipe_increment(tile_shape_MNK); }
CUTLASS_HOST_DEVICE CollectiveEpilogue(Params const& params_, TensorStorage& shared_tensors) : params(params_), fusion_callbacks(params_.thread, shared_tensors.thread) {}
CUTLASS_DEVICE bool is_producer_load_needed() const { return fusion_callbacks.is_producer_load_needed(); }
CUTLASS_DEVICE auto load_init( Params const& params, TensorMapStorage& shared_tensormaps, int32_t sm_count, int32_t sm_idx) { // Initialize tma for loading constexpr bool IsLoad = true; auto load_tensormaps = tensormaps_init<IsLoad>(params, shared_tensormaps, sm_count, sm_idx, 0); return load_tensormaps; }
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class TiledMma, class TensorMapC, __CUTE_REQUIRES(std::is_pointer_v<TensorMapC>) > CUTLASS_DEVICE auto load( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_MNK, TileCoordMNKL tile_coord_mnkl, TiledMma tiled_mma, int thread_idx, TensorStorage& shared_tensors, TensorMapC const& load_tensormap, int subtile_idx=-1) { using namespace cute;
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = tile_coord_mnkl;
static_assert(!is_im2col_D, "Do not support im2col");
auto coord_shape = append<3>(make_shape(m_coord, n_coord), Int<0>{});
// Represent the full source tensor, slice to get the tile this CTA is currently responsible for Tensor mC_mn = params.tma_load_c.get_tma_tensor(append<3>(make_shape(M,N), Int<1>{})); // (M,N,L) Tensor mC = coalesce(mC_mn, take<0,2>(CtaTileMNK{})); Tensor gC = local_tile(mC, take<0,2>(CtaTileMNK{}), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtile, get matching smem tensor auto ptr_sC = shared_tensors.collective.smem_C.begin(); Tensor gC_epi = flat_divide(gC, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor sC_epi = make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{}); // (EPI_TILE_M,EPI_TILE_N,PIPE_C)
// Prepare the thread(b)lock's (G)mem to (S)mem TMA tiled copy (bGS_) ThrCopy thrblk_g2s = params.tma_load_c.get_slice(Int<0>{}); Tensor bGS_gC = thrblk_g2s.partition_S(gC_epi); // (G2S,G2S_M,G2S_N,EPI_M,EPI_N) Tensor bGS_sC = thrblk_g2s.partition_D(sC_epi); // (G2S,G2S_M,G2S_N,PIPE_C)
// Get the fusion callbacks for the producer load warp auto pld_args = cutlass::epilogue::fusion::detail::ProducerLoadArgs{ problem_shape_mnkl, CtaTileMNK{}, tile_coord_mnkl, tiled_mma, EpilogueTile{}, thread_idx }; auto pld_callbacks = fusion_callbacks.get_producer_load_callbacks(pld_args); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
LoadPipelineState last_load_producer_state = load_pipe_producer_state;
// Predication for TMA load (one thread issues TMA load) bool issue_tma_load = cute::elect_one_sync();
// Pre-loop fusion callback entry point pld_callbacks.begin();
LoadPipelineState prior_state = load_pipe_producer_state;
bool did_load = false;
CUTLASS_PRAGMA_UNROLL for (int epi_n = 0; epi_n < size<3>(gC_epi); ++epi_n) { CUTLASS_PRAGMA_UNROLL for (int epi_m = 0; epi_m < size<2>(gC_epi); ++epi_m) { if (subtile_idx != -1 && (epi_n * static_cast<int>(size<2>(gC_epi)) + epi_m) != subtile_idx) { continue; }
// Acquire the lock for this stage constexpr uint16_t mcast_mask = 0; uint64_t* tma_barrier = load_pipeline.producer_get_barrier(load_pipe_producer_state);
load_pipeline.producer_acquire(load_pipe_producer_state);
// Loop fusion callback entry point pld_callbacks.step(tma_barrier, epi_m, epi_n, load_pipe_producer_state.count(), issue_tma_load);
// Execute the TMA load for C if needed if (is_C_load_needed) { if (issue_tma_load) { copy(params.tma_load_c.with(load_tensormap, *tma_barrier, mcast_mask), bGS_gC(_,_,_,epi_m,epi_n), bGS_sC(_,_,_,load_pipe_producer_state.index())); load_pipeline.producer_expect_transaction(load_pipe_producer_state); } last_load_producer_state = load_pipe_producer_state; did_load = true; }
// Commit TMA loads for this stage and release the lock load_pipeline.producer_commit(load_pipe_producer_state); ++load_pipe_producer_state; } }
// Post-loop fusion callback entry point pld_callbacks.end();
return load_pipe_producer_state; }
CUTLASS_DEVICE auto load_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state) {
if (!fusion_callbacks.is_producer_load_needed()) { return load_pipe_producer_state; }
bool issue_tma_load = cute::elect_one_sync(); if (issue_tma_load) { load_pipeline.producer_tail(load_pipe_producer_state); }
return load_pipe_producer_state; }
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout, class TiledMma, class TensorMapD > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_MNK, TileCoordMNKL tile_coord_mnkl, cute::Tensor<AccEngine,AccLayout> accumulators, TiledMma tiled_mma, int thread_idx, TensorStorage& shared_tensors, TensorMapD const& store_tensormap, int subtile_idx=-1) {
using namespace cute; using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
static_assert(is_rmem<AccEngine>::value, "Accumulator must be RF resident."); static_assert(rank(AccLayout{}) == 3, "Accumulator must be MMA-partitioned: (MMA,MMA_M,MMA_N)"); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<TileShapeMNK>::value, "TileShapeMNK must be static"); static_assert(rank(TileShapeMNK{}) == 3, "TileShapeMNK must be rank 3"); static_assert(rank(TileCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4");
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = tile_coord_mnkl;
static_assert(!is_im2col_D, "Do not support im2col");
auto coord_shape = append<3>(make_shape(m_coord, n_coord), Int<0>{});
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mD_mn = params.tma_store_d.get_tma_tensor(append<3>(make_shape(M,N), Int<1>{})); // (M,N,L)
Tensor mD = coalesce(mD_mn, take<0,2>(CtaTileMNK{})); Tensor gD = local_tile(mD, take<0,2>(CtaTileMNK{}), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtiling Tensor gD_epi = flat_divide(gD, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
// Construct the corresponding pipelined smem tensors auto ptr_sC = shared_tensors.collective.smem_C.begin(); auto ptr_sD = shared_tensors.collective.smem_D.begin(); Tensor sC_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_C) Tensor sD_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sD), SmemLayoutD{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_D)
TiledCopy tiled_copy_C_atom = make_tiled_copy_C_atom(CopyAtomC{}, tiled_mma);
// (t)hread-partition for (r)egister to (r)egister copy (tRR_) TiledCopy tiled_r2r = [&]() { if constexpr (IsUseR2R) { return make_tiled_copy_S(Copy_Atom<CopyOpR2R, ElementCompute>{}, tiled_copy_C_atom); } else { return make_tiled_copy_S(Copy_Atom<AutoVectorizingCopyWithAssumedAlignment<128>, ElementCompute>{}, tiled_copy_C_atom); } }(); ThrCopy thread_r2r = tiled_r2r.get_slice(thread_idx);
// (t)hread-partition for (r)egister to (s)mem copy (tRS_) TiledCopy tiled_r2s = [&]() { if constexpr (IsUseR2R) { return make_tiled_copy_D(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_r2r); } else { return make_tiled_copy_S(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_copy_C_atom); } }(); ThrCopy thread_r2s = tiled_r2s.get_slice(thread_idx); Tensor tRS_rAcc = thread_r2s.retile_S(accumulators); // ((R2S,R2S_V),MMA_M,MMA_N) Tensor tRS_sD = thread_r2s.partition_D(sD_epi); // (R2S,R2S_M,R2S_N,PIPE_D)
auto mma_tile_m = size<0>(TileShapeMNK{}) / size<1>(tRS_rAcc); auto mma_tile_n = size<1>(TileShapeMNK{}) / size<2>(tRS_rAcc); auto epi_tile_m = size<0>(EpilogueTile{}); auto epi_tile_n = size<1>(EpilogueTile{});
// Allocate D registers Layout tRS_rD_layout = make_layout(take<0,3>(shape(thread_r2s.partition_S(sD_epi)))); Tensor tRS_rD = make_tensor<SmemElementD>(tRS_rD_layout); // (R2S,R2S_M,R2S_N)
// Vectorized fragment view constexpr int FragmentSize = DispatchPolicy::FragmentSize; Tensor tRS_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(tRS_rAcc); Tensor tRS_rD_frg = recast<Array<SmemElementD , FragmentSize>>(tRS_rD); CUTE_STATIC_ASSERT(size<0>(tRS_rAcc) % FragmentSize == 0, "Fragment size does not vectorize properly");
// (t)hread-partition for (s)mem to (r)egister copy (tSR_) TiledCopy tiled_s2r = make_tiled_copy_S(Copy_Atom<CopyOpS2R, SmemElementC>{}, tiled_copy_C_atom); ThrCopy thread_s2r = tiled_s2r.get_slice(thread_idx); Tensor tSR_sC = thread_s2r.partition_S(sC_epi); // (S2R,S2R_M,S2R_N,PIPE_C) Layout tSR_rC_layout = thread_s2r.retile_D(tRS_rD).layout(); // (S2R,S2R_M,S2R_N)
// Allocate C registers // If C smem load is a non-vectorized dst(i) = src(i) then we can allocate C registers directly in the compute type // to eliminate some redundant pack+unpack instruction sequences for sub-word types constexpr bool IsDirectS2R = cute::is_same_v<CopyOpS2R, AutoVectorizingCopyWithAssumedAlignment<128>> && decltype(max_common_vector(tSR_rC_layout, tSR_sC.layout()))::value <= 1; using RegisterElementC = cute::conditional_t<IsDirectS2R, ElementCompute, SmemElementC>; Tensor tRS_rC = make_tensor<RegisterElementC>(tRS_rD_layout); // (R2S,R2S_M,R2S_N) Tensor tSR_rC = thread_s2r.retile_D(tRS_rC); // (S2R,S2R_M,S2R_N)
// thread(b)lock-partition for (s)mem to (g)mem copy (bSG_) ThrCopy thrblk_s2g = params.tma_store_d.get_slice(Int<0>{}); Tensor bSG_sD = thrblk_s2g.partition_S(sD_epi); // (S2G,S2G_M,S2G_N,PIPE_D) Tensor bSG_gD = thrblk_s2g.partition_D(gD_epi); // (S2G,S2G_M,S2G_N,EPI_M,EPI_N)
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(CtaTileMNK{}), make_coord(m_coord, n_coord)); // (CTA_M,CTA_N) Tensor tRS_cD_mn = thread_r2s.partition_S(flat_divide(cD_mn, EpilogueTile{})); // (R2S,R2S_M,R2S_N,EPI_M,EPI_N) // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (CTA_M,CTA_N) Tensor tRS_cD = make_coord_tensor(tRS_cD_mn.layout()); // (R2S,R2S_M,R2S_N,EPI_M,EPI_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = make_coord(M,N) - cD_mn(_0{}); // (m,n) auto residue_tRS_cD = make_coord(M,N) - tRS_cD_mn(_0{}); // (m,n)
CUTE_STATIC_ASSERT(epi_tile_m % mma_tile_m == 0, "MMA_TILE_M must divide EPI_TILE_M");
if constexpr (epi_tile_m * epi_tile_n > mma_tile_m * mma_tile_n) { // When the epilogue subtile is larger than the MMA tiles, loop over multiple MMA tiles CUTE_STATIC_ASSERT(epi_tile_n % mma_tile_n == 0, "MMA_TILE_N must divide EPI_TILE_N"); } else { CUTE_STATIC_ASSERT(mma_tile_n % epi_tile_n == 0, "EPI_TILE_N must divide MMA_TILE_N"); }
// Get TiledCopy for partition reference when consumer store. TiledCopy tiled_copy_partition_ref = make_tiled_copy_S(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_copy_C_atom); // Get the fusion callbacks for the consumer store warps constexpr bool RefSrc = true; // Register tensors reference R2S copy src layout auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs{ problem_shape_mnkl, CtaTileMNK{}, tile_coord_mnkl, tiled_mma, EpilogueTile{}, tiled_copy_partition_ref, cD, residue_cD, tRS_cD, residue_tRS_cD, tRS_rC, thread_idx }; auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); bool is_producer_load_needed = fusion_callbacks.is_producer_load_needed(); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
using FragmentVisit = decltype(cst_callbacks.visit(tRS_rAcc_frg(0), 0, 0, 0)); constexpr bool IsDirectR2S = cute::is_same_v<FragmentVisit, Array<SmemElementD, FragmentSize>>; using RegisterElementD = cute::conditional_t<!IsDirectR2S, ElementCompute, SmemElementD>; Tensor tRS_rCompute = make_tensor<RegisterElementD>(tRS_rD_layout); // (R2S,R2S_M,R2S_N) Tensor tRS_rCompute_frg = recast<Array<RegisterElementD, FragmentSize>>(tRS_rCompute);
// Thread synchronizer for previously issued waits or fences // to ensure visibility of smem reads/writes to threads or TMA unit auto synchronize = [&] () { cutlass::arch::NamedBarrier::sync(size(TiledMma{}), cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// Predication for TMA store (a single thread from one warp issues TMA store) bool issue_tma_store = ((thread_idx / NumThreadsPerWarp) == 0) && cute::elect_one_sync();
// In the reuse smem configuration we have StagesC smem buffers and at most StagesD committed TMA stores in flight. // The TMA store pipeline producer acquire returns when at most StagesD-1 committed stores are in-flight, so we can // only guarantee store completion after StagesD iterations, then we can begin issuing releases on the smem buffer locks. // store_pipe_producer_state tracks the acquire and load_pipe_consumer_state tracks the release, in circular buffer fashion. LoadPipelineState load_wait_state = load_pipe_consumer_state; if constexpr (ReuseSmemC) { load_wait_state = store_pipe_producer_state; load_wait_state.phase_ ^= 1; }
// We can delay issue of TMA store by one iteration to achieve better interleaving of non-TMA instructions // Sync requirements of smem reuse may preclude this optimization // Delayed stores cause delayed stage releases which causes deadlock when StagesC == StagesD int epi_m_prev = 0, epi_n_prev = 0; static_assert(not (DelayTmaStore and ReuseSmemC and StagesC <= StagesD), "This TMA epilogue configuration will deadlock");
// The TMA store sequence for one subtile iteration auto tma_store_fn = [&] (int epi_m, int epi_n) { // Write the tile from smem to gmem with TMA cutlass::arch::fence_view_async_shared(); // ensure smem writes are visible to TMA synchronize(); // ensure all threads have issued their async fence if constexpr (is_destination_supported) { if (issue_tma_store) { copy(params.tma_store_d.with(store_tensormap), bSG_sD(_,_,_,store_pipe_producer_state.index()), bSG_gD(_,_,_,epi_m,epi_n)); } }
// Post async fence, pre TMA commit callback entry point cst_callbacks.tma_store(epi_m, epi_n, store_pipe_producer_state.count(), issue_tma_store);
// Commit the TMA stores for this stage if (issue_tma_store) { store_pipeline.producer_commit(store_pipe_producer_state); } ++store_pipe_producer_state; ++issued_stores;
// Wait for the next smem buffer to be available if (issue_tma_store) { store_pipeline.producer_acquire(store_pipe_producer_state); } synchronize();
if constexpr (ReuseSmemC) { // producer_acquire returns when at most StagesD-1 committed stores are pending bool store_finished = issued_stores > StorePipeline::UnacquiredStages; // Let dma warp know earliest smem buffer is consumed and empty after StagesD producer commits if (store_finished) { if (is_producer_load_needed) { load_pipeline.consumer_release(load_pipe_consumer_state); } ++load_pipe_consumer_state; } } };
// // BEGIN EPILOGUE //
// Pre-loop fusion callback entry point cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// For each output tile CUTLASS_PRAGMA_UNROLL for (int epi_n = 0; epi_n < size<3>(gD_epi); ++epi_n) { CUTLASS_PRAGMA_UNROLL for (int epi_m = 0; epi_m < size<2>(gD_epi); ++epi_m) { bool is_first_iteration = epi_m == 0 && epi_n == 0; bool is_last_iteration = epi_m == size<2>(gD_epi)-1 && epi_n == size<3>(gD_epi)-1;
if (subtile_idx != -1 && (epi_n * static_cast<int>(size<2>(gD_epi)) + epi_m) != subtile_idx) { continue; }
cst_callbacks.begin_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Wait for the producer load to fill smem load_pipeline.consumer_wait(load_wait_state);
if (is_C_load_needed) { // Copy source tile from smem to register copy(tiled_s2r, tSR_sC(_,_,_,load_wait_state.index()), tSR_rC); } }
// First loop fusion callback entry point cst_callbacks.previsit(epi_m, epi_n, load_wait_state.count(), is_producer_load_needed);
if (is_producer_load_needed) { if constexpr (not ReuseSmemC) { // Let producer load warp know smem buffers are consumed and empty cutlass::arch::fence_view_async_shared(); load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } ++load_wait_state; }
if constexpr (epi_tile_m * epi_tile_n > mma_tile_m * mma_tile_n) { // When the epilogue subtile is larger than the MMA tiles, loop over multiple // MMA tiles static constexpr int MmaMPerEpiM = epi_tile_m / mma_tile_m; static constexpr int MmaNPerEpiN = epi_tile_n / mma_tile_n;
CUTLASS_PRAGMA_UNROLL for (int mma_n_in_epi = 0; mma_n_in_epi < MmaNPerEpiN; ++mma_n_in_epi) { int mma_n = (epi_n * MmaNPerEpiN) + mma_n_in_epi;
CUTLASS_PRAGMA_UNROLL for (int mma_m_in_epi = 0; mma_m_in_epi < MmaMPerEpiM; ++mma_m_in_epi) { int mma_m = (epi_m * MmaMPerEpiM) + mma_m_in_epi; Tensor tRS_rAcc_frg_mn = tRS_rAcc_frg(_,mma_m,mma_n); int idx_in_epi_subtile = (mma_n_in_epi * MmaMPerEpiM + mma_m_in_epi);
tRS_rCompute_frg(idx_in_epi_subtile) = cst_callbacks.visit( tRS_rAcc_frg_mn(0), idx_in_epi_subtile, epi_m, epi_n); } } } else { int mma_m = epi_m; int mma_n = (epi_n * size<1>(EpilogueTile{})) / mma_tile_n; Tensor tRS_rAcc_frg_mn = tRS_rAcc_frg(_,mma_m,mma_n);
// Vectorized fragment loop with visitor callback entry point int epi_n_in_mma = epi_n % (mma_tile_n / epi_tile_n); int r2s_v = epi_n_in_mma * size(tRS_rCompute_frg); CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tRS_rCompute_frg); ++epi_v) { tRS_rCompute_frg(epi_v) = cst_callbacks.visit(tRS_rAcc_frg_mn(r2s_v + epi_v), epi_v, epi_m, epi_n); } }
// The latest we can delay the TMA store is right before the smem store of the next iteration // since the current TMA store needs to be committed before we can acquire the next smem buffer if constexpr (DelayTmaStore) { // Issue TMA stores for the previous subtile if (not is_first_iteration and subtile_idx == -1) { tma_store_fn(epi_m_prev, epi_n_prev); } epi_m_prev = epi_m; epi_n_prev = epi_n; }
// Smem reduction callback entry point using current store buffer for workspace cst_callbacks.reduce(sD_epi(_,_,store_pipe_producer_state.index()), synchronize, epi_m, epi_n, is_last_iteration, tRS_rCompute_frg);
// Copy tile from register to regiser if needed if constexpr (IsUseR2R) { // retile source and destination for tiled_r2r Tensor tRR_rD_src = thread_r2r.retile_S(tRS_rD); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N) Tensor tRR_rD_dst = thread_r2r.retile_D(tRS_rD); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N)
// Output needs register shuffling before copying to shared memory. copy(tiled_r2r, tRR_rD_src, tRR_rD_dst); }
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tRS_rD_frg); ++i) { tRS_rD_frg(i) = cutlass::NumericArrayConverter<SmemElementD, RegisterElementD, FragmentSize>{}(tRS_rCompute_frg(i)); } // Copy tile from register to smem if constexpr (is_destination_supported) { copy(tiled_r2s, tRS_rD, tRS_sD(_,_,_,store_pipe_producer_state.index())); }
// Post reduction, pre TMA store callback entry point constexpr bool issue_smem_store = true; // No smem store predication cst_callbacks.postreduce(epi_m, epi_n, store_pipe_producer_state.count(), issue_smem_store);
if constexpr (not DelayTmaStore) { // Issue TMA stores for this subtile tma_store_fn(epi_m, epi_n); }
cst_callbacks.end_loop(epi_m, epi_n);
} // for epi_m } // for epi_n
if constexpr (DelayTmaStore) { // Issue TMA stores for the last subtile tma_store_fn(epi_m_prev, epi_n_prev); }
// Post-loop fusion callback entry point cst_callbacks.end();
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
CUTLASS_DEVICE auto store_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state) { // wait for all TMA stores to complete store_pipeline.producer_tail(store_pipe_producer_state); // reset store counter issued_stores = 0;
if constexpr (ReuseSmemC) { if (fusion_callbacks.is_producer_load_needed()) { // Issue releases on up to StagesD-1 previously issued TMA stores constexpr int release_stages = cute::min(StorePipeline::UnacquiredStages, get_load_pipe_increment(CtaTileMNK{})); CUTLASS_PRAGMA_UNROLL for (int stage = 0; stage < release_stages; ++stage) { load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } } }
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
CUTLASS_DEVICE auto store_init( Params const& params, TensorMapStorage& shared_tensormaps, int32_t sm_count, int32_t sm_idx, int32_t warp_group_idx) { int warp_idx_in_warp_group = canonical_warp_idx_sync() % NumWarpsPerWarpGroup; // Since only one warp issues TMA store, we only need that one warp to initialize tensormaps if (warp_idx_in_warp_group == 0) { // Initialize tma constexpr bool IsLoad = false; auto store_tensormaps = tensormaps_init<IsLoad>(params, shared_tensormaps, sm_count, sm_idx, warp_group_idx); return store_tensormaps; } TmaDescriptor* null_tma_desc = nullptr; return cute::make_tuple(null_tma_desc); }
// // Methods to perform different parts of TMA/Tensormap modifications //
template <bool IsLoad> CUTLASS_DEVICE auto tensormaps_init( Params const& params, TensorMapStorage& shared_tensormaps, int32_t sm_count, int32_t sm_idx, int32_t warp_group_idx) {
constexpr uint32_t NumInputTensors = NumEpilogueWarpGroups + (cute::is_void_v<ElementC> ? 0 : 1); Layout desc_layout = make_layout(make_shape(sm_count, Int<NumInputTensors>{}));
Tensor gmem_tensormap = make_tensor(params.tensormaps, desc_layout); // (SMs, NumInputTensors)
if constexpr (IsLoad) { if (is_source_supported) { constexpr int C_tensormap_index = NumEpilogueWarpGroups; Tensor pC_tensormap = make_tensor(params.tma_load_c.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sC_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_C), Int<1>{}, Int<1>{});
if (cute::elect_one_sync()) { // Bringing tensormaps from params to smem for modification later copy(recast<uint128_t>(pC_tensormap), recast<uint128_t>(sC_tensormap)); } __syncwarp(); return cute::make_tuple(&gmem_tensormap(sm_idx, C_tensormap_index));
} TmaDescriptor* null_tma_desc = nullptr; return cute::make_tuple(null_tma_desc); } else { Tensor pD_tensormap = make_tensor(params.tma_store_d.get_tma_descriptor(), Int<1>{}, Int<1>{}); Tensor sD_tensormap = make_tensor(make_smem_ptr(&shared_tensormaps.smem_tensormap_D[warp_group_idx]), Int<1>{}, Int<1>{});
if (cute::elect_one_sync()) { // Bringing tensormaps from params to smem for modification later copy(recast<uint128_t>(pD_tensormap), recast<uint128_t>(sD_tensormap)); } __syncwarp(); return cute::make_tuple(&gmem_tensormap(sm_idx, warp_group_idx)); } }
// Replace address for the global tensor (to be done by single thread) template <bool IsLoad> CUTLASS_DEVICE void tensormaps_replace_global_address( TensorMapStorage& shared_tensormaps, Params const& params, int32_t next_batch, int32_t warp_group_idx) { // Replacing global_address for the next batch if constexpr (IsLoad) { if constexpr (is_source_supported) { if (params.ptr_C != nullptr) { cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_C, params.ptr_C[next_batch]); } } } else if constexpr (is_destination_supported) { cute::tma_descriptor_replace_addr_in_shared_mem(shared_tensormaps.smem_tensormap_D[warp_group_idx], params.ptr_D[next_batch]); } }
// Replace dim and strides for the global tensor - used only for Grouped GEMM (to be done by single thread) template <bool IsLoad, class ProblemShape_MNKL> CUTLASS_DEVICE void tensormaps_replace_global_tensor_properties( TensorMapStorage& shared_tensormaps, Params const& params, int32_t next_group, ProblemShape_MNKL problem_shape_mnkl, int32_t warp_group_idx) { const uint32_t M = get<0>(problem_shape_mnkl); const uint32_t N = get<1>(problem_shape_mnkl); // Replace all dims for consistency constexpr int MaxTensorRank = 5; cute::array<uint32_t, MaxTensorRank> prob_shape = {1,1,1,1,1}; cute::array<uint64_t, MaxTensorRank> prob_stride = {0,0,0,0,0};
if constexpr (IsLoad) { if constexpr (is_source_supported) { if (params.dC != nullptr) { ElementC const* ptr_C = nullptr; Tensor tensor_c = make_tensor(ptr_C, make_layout(make_shape(M,N,Int<1>{}), params.dC[next_group]));
cute::detail::fill_tma_gmem_shape_stride(params.tma_load_c, tensor_c, prob_shape, prob_stride); // Convert strides to byte strides for (uint64_t& stride : prob_stride) { stride = (stride * sizeof_bits_v<ElementC>) / 8; } cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_C, prob_shape, prob_stride); } } } else if constexpr (is_destination_supported) { ElementD const* ptr_D = nullptr; Tensor tensor_d = make_tensor(ptr_D, make_layout(make_shape(M,N,Int<1>{}), params.dD[next_group]));
cute::detail::fill_tma_gmem_shape_stride(params.tma_store_d, tensor_d, prob_shape, prob_stride); // Convert strides to byte strides for (uint64_t& stride : prob_stride) { stride = (stride * sizeof_bits_v<ElementD>) / 8; }
cute::tma_descriptor_replace_dims_strides_in_shared_mem(shared_tensormaps.smem_tensormap_D[warp_group_idx], prob_shape, prob_stride); } }
template <bool IsLoad, class ProblemShape_MNKL> CUTLASS_DEVICE void tensormaps_perform_update( TensorMapStorage& shared_tensormaps, Params const& params, cute::TmaDescriptor const* tensormap, ProblemShape_MNKL problem_shape_mnkl, int32_t next_batch, int32_t warp_group_idx) { if (cute::elect_one_sync()) { // Replacing global_address for the next batch tensormaps_replace_global_address<IsLoad>(shared_tensormaps, params, next_batch, warp_group_idx);
if constexpr (IsGroupedGemmKernel) { // Replacing global dims and strides for the next batch tensormaps_replace_global_tensor_properties<IsLoad>( shared_tensormaps, params, next_batch, problem_shape_mnkl, warp_group_idx); }
} }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_cp_fence_release( TensorMapStorage& shared_tensormaps, cute::TmaDescriptor const* tensormap, const int32_t warp_group_idx = 0) { // Commit and wait for all TMA load/store instructions before updating the tensormap in gmem. // This operation only happens when the group/batch changes between consecutive tiles. // If there are no uncommitted instructions then tma_desc_commit_group results in an empty bulk async-group. auto tma_desc_wait_all_fn = [] () CUTLASS_LAMBDA_FUNC_INLINE { if (cute::elect_one_sync()) { cute::tma_desc_commit_group(); cute::tma_desc_wait_group(); } }; // Entire warp must do this (ie its aligned) if constexpr (IsLoad) { if constexpr (is_source_supported) { tma_desc_wait_all_fn(); tma_descriptor_cp_fence_release(tensormap, shared_tensormaps.smem_tensormap_C); } } else if constexpr (is_destination_supported) { tma_desc_wait_all_fn(); tma_descriptor_cp_fence_release(tensormap, shared_tensormaps.smem_tensormap_D[warp_group_idx]); } }
template <bool IsLoad> CUTLASS_DEVICE void tensormaps_fence_acquire(cute::TmaDescriptor const* tensormap) { if constexpr (IsLoad) { if constexpr (is_source_supported) { cute::tma_descriptor_fence_acquire(tensormap); } } else { cute::tma_descriptor_fence_acquire(tensormap); } }
private: Params const& params; FusionCallbacks fusion_callbacks; int issued_stores = 0;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing elementwise operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/arch/barrier.h"#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/collective/detail.hpp"#include "cutlass/epilogue/thread/scale_type.h"#include "cutlass/epilogue/fusion/callbacks.hpp"#include "cutlass/epilogue/fusion/sm90_callbacks_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm120_callbacks_tma_warpspecialized.hpp"#include "cutlass/detail/collective.hpp"#include "cutlass/detail/layout.hpp"#include "cutlass/detail/helper_macros.hpp"#include "cutlass/trace.h"
#include "cute/tensor.hpp"#include "cutlass/cuda_host_adapter.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_, class CtaTileMNK_, // (CTA_M,CTA_N,CTA_K) class EpilogueTile_, // (EPI_TILE_M,EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpG2S_, class SmemLayoutAtomC_, class CopyOpS2R_, class CopyOpS2G_, class SmemLayoutAtomD_, class CopyOpR2S_, class CopyAtomC_, class CopyOpR2R_>class CollectiveEpilogue< Sm90TmaWarpSpecialized<StagesC_,StagesD_,FragmentSize_,ReuseSmemC_,DelayTmaStore_>, CtaTileMNK_, EpilogueTile_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpG2S_, SmemLayoutAtomC_, CopyOpS2R_, CopyOpS2G_, SmemLayoutAtomD_, CopyOpR2S_, CopyAtomC_, CopyOpR2R_> {public: // // Type Aliases // using DispatchPolicy = Sm90TmaWarpSpecialized<StagesC_,StagesD_,FragmentSize_,ReuseSmemC_,DelayTmaStore_>; using CtaTileMNK = CtaTileMNK_; using EpilogueTile = EpilogueTile_; using FusionCallbacks = FusionCallbacks_; using ElementC = ElementC_; using StrideC = StrideC_; using ElementD = ElementD_; using StrideD = StrideD_; using CopyOpG2S = CopyOpG2S_; using SmemLayoutAtomC = SmemLayoutAtomC_; using CopyOpS2R = CopyOpS2R_; using CopyOpS2G = CopyOpS2G_; using SmemLayoutAtomD = SmemLayoutAtomD_; using CopyOpR2S = CopyOpR2S_; using CopyAtomC = CopyAtomC_; using CopyOpR2R = CopyOpR2R_;
using ThreadEpilogueOp = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::Operation; using GmemTiledCopyC = CopyOpG2S; using GmemTiledCopyD = CopyOpS2G;
static_assert(!is_layout<EpilogueTile>::value && is_tuple<EpilogueTile>::value, "EpilogueTile must be a cute::Tile or cute::Shape"); static_assert(cute::rank(CtaTileMNK{}) == 3, "CtaTileMNK must be rank-3: [CTA_M, CTA_N, CTA_K]"); static_assert(cute::rank(EpilogueTile{}) == 2, "EpilogueTile must be rank-2: [EPI_TILE_M, EPI_TILE_N]"); static_assert(size<0>(CtaTileMNK{}) % size<0>(shape(EpilogueTile{})) == 0, "EPI_TILE_M must divide CTA_M"); static_assert(size<1>(CtaTileMNK{}) % size<1>(shape(EpilogueTile{})) == 0, "EPI_TILE_N must divide CTA_N"); static_assert(cute::rank(StrideC{}) == 3, "StrideC must be rank-3: [M, N, L]"); static_assert(cute::rank(StrideD{}) == 3, "StrideD must be rank-3: [M, N, L]");
private: constexpr static bool is_source_supported = not cute::is_void_v<ElementC>; constexpr static bool is_destination_supported = not cute::is_void_v<ElementD>; using NonVoidElementD = cute::conditional_t<not is_destination_supported,fusion::get_element_aux_t<FusionCallbacks>, ElementD>; static_assert(not cute::is_void_v<NonVoidElementD>, "SmemElementD is void"); using NonVoidElementC = cute::conditional_t<not is_source_supported,NonVoidElementD,ElementC>; // prevents void ref breakages
using TmaElementD = cute::conditional_t<cute::is_same_v<NonVoidElementD, cutlass::complex<float>>, uint64_t, NonVoidElementD>; using TmaElementC = cute::conditional_t<cute::is_same_v<NonVoidElementC, cutlass::complex<float>>, uint64_t, NonVoidElementC>;
using SmemElementC = typename cutlass::detail::get_unpacked_element_type<NonVoidElementC>::type; using SmemElementD = typename cutlass::detail::get_unpacked_element_type<NonVoidElementD>::type;
constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static bool ReuseSmemC = ReuseSmemC_ and is_destination_supported; constexpr static bool DelayTmaStore = DelayTmaStore_;
constexpr static bool is_m_major_C = detail::is_m_major<StrideC>(); constexpr static bool is_m_major_D = detail::is_m_major<StrideD>();
constexpr static bool is_im2col_C = cute::is_same_v<CopyOpG2S, SM90_TMA_LOAD_IM2COL>; constexpr static bool is_im2col_D = cute::is_same_v<CopyOpS2G, SM90_TMA_STORE_IM2COL>;
// Check if register transformation is needed before copying register to shared memory. constexpr static bool IsUseR2R = !cute::is_void_v<CopyOpR2R>;
using SmemLayoutC = decltype(tile_to_shape( SmemLayoutAtomC{}, make_shape(size<0>(EpilogueTile{}), size<1>(EpilogueTile{}), Int<StagesC>{}), cute::conditional_t<is_m_major_C, Step<_2,_1,_3>, Step<_1,_2,_3>>{} )); using SmemLayoutD = decltype(tile_to_shape( SmemLayoutAtomD{}, make_shape(size<0>(EpilogueTile{}), size<1>(EpilogueTile{}), Int<ReuseSmemC ? StagesC : StagesD>{}), cute::conditional_t<is_m_major_D, Step<_2,_1,_3>, Step<_1,_2,_3>>{} ));
constexpr static bool support_smem_reuse = is_source_supported && is_destination_supported && StagesD <= StagesC && cosize(take<0,2>(SmemLayoutC{})) == cosize(take<0,2>(SmemLayoutD{})); static_assert(not (ReuseSmemC && not support_smem_reuse), "Smem reuse requirements not met");
constexpr static size_t SmemAlignmentD = cutlass::detail::alignment_for_swizzle(SmemLayoutD{}); constexpr static size_t SmemAlignmentC = cutlass::detail::alignment_for_swizzle(SmemLayoutC{}); constexpr static size_t MaxSmemAlignment = cute::max(SmemAlignmentC, SmemAlignmentD);
using SmemArrayTypeC = cute::ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>>; using SmemArrayTypeD = cute::ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>>;
using EmptyType = cute::tuple<>; using SmemCStorage = cute::conditional_t<is_source_supported and (not ReuseSmemC), SmemArrayTypeC, EmptyType>; using SmemDStorage = cute::conditional_t<is_destination_supported, SmemArrayTypeD, EmptyType>;
struct CollectiveStorageWithC { alignas(SmemAlignmentC) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageWithoutC { cute::array<SmemElementC, 0> smem_C; alignas(SmemAlignmentD) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
union CollectiveStorageReuseC { alignas(MaxSmemAlignment) ArrayEngine<SmemElementC, cosize_v<SmemLayoutC>> smem_C; alignas(MaxSmemAlignment) ArrayEngine<SmemElementD, cosize_v<SmemLayoutD>> smem_D; };
public: // TMA pipeline for loading C using LoadPipeline = cutlass::PipelineTransactionAsync<StagesC>; using LoadPipelineState = cutlass::PipelineState<StagesC>; constexpr static uint32_t TmaTransactionBytes = (size(take<0,2>(SmemLayoutC{})) * static_cast<uint32_t>(sizeof_bits<SmemElementC>::value)) / 8; constexpr static bool RequiresTransactionBytes = true;
// TMA pipeline for storing D using StorePipeline = cute::conditional_t<ReuseSmemC, cutlass::PipelineTmaStore<StagesC, StagesD-1>, cutlass::PipelineTmaStore<StagesD>>; using StorePipelineState = cutlass::PipelineState<ReuseSmemC ? StagesC : StagesD>;
struct SharedStorage { struct TensorStorage { using CollectiveStorage = cute::conditional_t<not is_source_supported, CollectiveStorageWithoutC, cute::conditional_t<ReuseSmemC, CollectiveStorageReuseC, CollectiveStorageWithC>>; CollectiveStorage collective;
using FusionStorage = typename FusionCallbacks::SharedStorage; FusionStorage thread; } tensors;
using PipelineStorage = typename LoadPipeline::SharedStorage; PipelineStorage pipeline; }; using TensorStorage = typename SharedStorage::TensorStorage; using PipelineStorage = typename SharedStorage::PipelineStorage;
// Host side epilogue arguments struct Arguments { typename FusionCallbacks::Arguments thread{}; ElementC const* ptr_C; StrideC dC; ElementD const* ptr_D; StrideD dD; };
// Device side epilogue params struct Params { using TMA_C = decltype(make_tma_copy( CopyOpG2S{}, make_tensor(make_gmem_ptr<TmaElementC const>(nullptr), repeat_like(StrideC{}, int32_t(0)), StrideC{}), take<0,2>(SmemLayoutC{}), EpilogueTile{}, _1{})); using TMA_D = decltype(make_tma_copy( CopyOpS2G{}, make_tensor(make_gmem_ptr<TmaElementD>(nullptr), repeat_like(StrideD{}, int32_t(0)), StrideD{}), take<0,2>(SmemLayoutD{}), EpilogueTile{}, _1{}));
typename FusionCallbacks::Params thread{}; TMA_C tma_load_c; TMA_D tma_store_d; uint32_t tma_transaction_bytes = TmaTransactionBytes; };
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments( ProblemShape const& problem_shape, Arguments const& args, [[maybe_unused]] void* workspace) { // Optionally append 1s until problem shape is rank-4 in case its is only rank-3 (MNK) auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_MNKL;
uint32_t transaction_bytes = TmaTransactionBytes; typename Params::TMA_C tma_load_c{}; if constexpr (is_source_supported) { Tensor tensor_c = make_tensor(make_gmem_ptr<TmaElementC const>(args.ptr_C), make_layout(make_shape(M,N,L), args.dC)); tma_load_c = make_tma_copy_C_sm90( CopyOpG2S{}, tensor_c, take<0,2>(SmemLayoutC{}), EpilogueTile{}); }
typename Params::TMA_D tma_store_d{}; if constexpr (is_destination_supported) { Tensor tensor_d = make_tensor(make_gmem_ptr<TmaElementD>(args.ptr_D), make_layout(make_shape(M,N,L), args.dD)); tma_store_d = make_tma_copy_C_sm90( CopyOpS2G{}, tensor_d, take<0,2>(SmemLayoutD{}), EpilogueTile{}); }
return { FusionCallbacks::to_underlying_arguments(problem_shape, args.thread, workspace), tma_load_c, tma_store_d, transaction_bytes }; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return FusionCallbacks::get_workspace_size(problem_shape, args.thread); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return FusionCallbacks::initialize_workspace(problem_shape, args.thread, workspace, stream, cuda_adapter); }
template <class ProblemShape> static bool can_implement( ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; auto shape = cute::make_shape(M,N,L);
bool implementable = true; if constexpr (is_destination_supported) { constexpr int tma_alignment_bits_D = cutlass::detail::get_output_alignment_bits<ElementD>(); constexpr int min_tma_aligned_elements_D = tma_alignment_bits_D / cutlass::sizeof_bits<ElementD>::value; if constexpr (cute::is_same_v<CopyOpS2G, SM90_TMA_STORE_IM2COL>) { // ignore L stride for implicit gemm implementable = cutlass::detail::check_alignment<min_tma_aligned_elements_D>(take<0,2>(shape), take<0,2>(StrideD{})); } else { implementable = cutlass::detail::check_alignment<min_tma_aligned_elements_D>(shape, StrideD{}); } }
if constexpr (not cute::is_void_v<ElementC>) { constexpr int tma_alignment_bits_C = cutlass::detail::get_input_alignment_bits<ElementC>(); constexpr int min_tma_aligned_elements_C = tma_alignment_bits_C / cutlass::sizeof_bits<ElementC>::value; if constexpr (cute::is_same_v<CopyOpG2S, SM90_TMA_LOAD_IM2COL>) { // ignore L stride for implicit gemm implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_C>(take<0,2>(shape), take<0,2>(StrideC{})); } else { implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_C>(shape, StrideC{}); } }
if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); }
bool fusion_implementable = FusionCallbacks::can_implement(problem_shape, args.thread);
if (!fusion_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum requirements for FusionCallbacks.\n"); }
bool beta_implementable = true;
if constexpr (cute::is_void_v<ElementC>) { if constexpr (detail::has_beta<Arguments>::value) { beta_implementable = args.thread.beta == 0.0; } if constexpr (detail::has_beta_ptr<Arguments>::value) { beta_implementable = beta_implementable && args.thread.beta_ptr == nullptr; } }
if (!beta_implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Beta/beta pointer was set, but epilogue is sourceless (void-C).\n"); }
return implementable && fusion_implementable && beta_implementable; }
template<class TileShapeMNK> CUTLASS_HOST_DEVICE static constexpr int get_load_pipe_increment(TileShapeMNK tile_shape_MNK) { // Compute number of epilogue subtiles return size<1>(zipped_divide(make_layout(take<0,2>(tile_shape_MNK)), EpilogueTile{})); }
template<class TileShapeMNK> CUTLASS_HOST_DEVICE static constexpr int get_store_pipe_increment(TileShapeMNK tile_shape_MNK) { return get_load_pipe_increment(tile_shape_MNK); }
/// Issue Tma Descriptor Prefetch -- ideally from a single thread for best performance CUTLASS_DEVICE static void prefetch_tma_descriptors(Params const& epilogue_params) { if constexpr (is_source_supported) { cute::prefetch_tma_descriptor(epilogue_params.tma_load_c.get_tma_descriptor()); } if constexpr (is_destination_supported) { cute::prefetch_tma_descriptor(epilogue_params.tma_store_d.get_tma_descriptor()); } }
CUTLASS_HOST_DEVICE CollectiveEpilogue(Params const& params_, TensorStorage& shared_tensors) : params(params_), fusion_callbacks(params_.thread, shared_tensors.thread) {}
CUTLASS_DEVICE bool is_producer_load_needed() const { return fusion_callbacks.is_producer_load_needed(); }
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class TiledMma > CUTLASS_DEVICE auto load( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_MNK, TileCoordMNKL tile_coord_mnkl, TiledMma tiled_mma, int thread_idx, TensorStorage& shared_tensors, int subtile_idx=-1) { using namespace cute;
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = tile_coord_mnkl;
// The tma tensor C under im2col mode only has two modes (M, N) which // should be local tiled with only (m_coord, n_coord). auto coord_shape = conditional_return<is_im2col_C>( make_coord(m_coord, n_coord), make_coord(m_coord, n_coord, l_coord));
// Represent the full source tensor, slice to get the tile this CTA is currently responsible for Tensor mC_mn = params.tma_load_c.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mC = coalesce(mC_mn, take<0,2>(CtaTileMNK{})); Tensor gC = local_tile(mC, take<0,2>(CtaTileMNK{}), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtile, get matching smem tensor auto ptr_sC = shared_tensors.collective.smem_C.begin(); Tensor gC_epi = flat_divide(gC, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor sC_epi = make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{}); // (EPI_TILE_M,EPI_TILE_N,PIPE_C)
// Prepare the thread(b)lock's (G)mem to (S)mem TMA tiled copy (bGS_) ThrCopy thrblk_g2s = params.tma_load_c.get_slice(Int<0>{}); Tensor bGS_gC = thrblk_g2s.partition_S(gC_epi); // (G2S,G2S_M,G2S_N,EPI_M,EPI_N) Tensor bGS_sC = thrblk_g2s.partition_D(sC_epi); // (G2S,G2S_M,G2S_N,PIPE_C)
// Get the fusion callbacks for the producer load warp auto pld_args = cutlass::epilogue::fusion::detail::ProducerLoadArgs( problem_shape_mnkl, CtaTileMNK{}, tile_coord_mnkl, tiled_mma, EpilogueTile{}, thread_idx ); auto pld_callbacks = fusion_callbacks.get_producer_load_callbacks(pld_args); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
// Predication for TMA load (one thread issues TMA load) bool issue_tma_load = cute::elect_one_sync();
// Pre-loop fusion callback entry point pld_callbacks.begin();
CUTLASS_PRAGMA_UNROLL for (int epi_n = 0; epi_n < size<3>(gC_epi); ++epi_n) { CUTLASS_PRAGMA_UNROLL for (int epi_m = 0; epi_m < size<2>(gC_epi); ++epi_m) { if (subtile_idx != -1 && (epi_n * static_cast<int>(size<2>(gC_epi)) + epi_m) != subtile_idx) { continue; } // Acquire the lock for this stage constexpr uint16_t mcast_mask = 0; uint64_t* tma_barrier = load_pipeline.producer_get_barrier(load_pipe_producer_state); load_pipeline.producer_acquire(load_pipe_producer_state);
// Loop fusion callback entry point pld_callbacks.step(tma_barrier, epi_m, epi_n, load_pipe_producer_state.count(), issue_tma_load);
// Execute the TMA load for C if needed if (issue_tma_load && is_C_load_needed) { copy(params.tma_load_c.with(*tma_barrier, mcast_mask), bGS_gC(_,_,_,epi_m,epi_n), bGS_sC(_,_,_,load_pipe_producer_state.index())); load_pipeline.producer_expect_transaction(load_pipe_producer_state); }
// Commit TMA loads for this stage and release the lock load_pipeline.producer_commit(load_pipe_producer_state); ++load_pipe_producer_state; } }
// Post-loop fusion callback entry point pld_callbacks.end();
return load_pipe_producer_state; }
CUTLASS_DEVICE auto load_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_producer_state) { bool issue_tma_load = cute::elect_one_sync(); if (issue_tma_load) { load_pipeline.producer_tail(load_pipe_producer_state); }
return load_pipe_producer_state; }
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class AccEngine, class AccLayout, class TiledMma > CUTLASS_DEVICE auto store( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state, ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_MNK, TileCoordMNKL tile_coord_mnkl, cute::Tensor<AccEngine,AccLayout> accumulators, TiledMma tiled_mma, int thread_idx, TensorStorage& shared_tensors, int subtile_idx=-1) { using namespace cute; using ElementAccumulator = typename AccEngine::value_type; using ElementCompute_ = typename epilogue::fusion::FusionCallbacksTraits<FusionCallbacks>::ElementCompute; using ElementCompute = cute::conditional_t<cute::is_void_v<ElementCompute_>,ElementAccumulator,ElementCompute_>;
static_assert(is_rmem<AccEngine>::value, "Accumulator must be RF resident."); static_assert(rank(AccLayout{}) == 3, "Accumulator must be MMA-partitioned: (MMA,MMA_M,MMA_N)"); static_assert(rank(ProblemShapeMNKL{}) == 4, "ProblemShapeMNKL must be rank 4"); static_assert(is_static<TileShapeMNK>::value, "TileShapeMNK must be static"); static_assert(rank(TileShapeMNK{}) == 3, "TileShapeMNK must be rank 3"); static_assert(rank(TileCoordMNKL{}) == 4, "TileCoordMNKL must be rank 4");
// Indexing variables auto [M, N, K, L] = problem_shape_mnkl; auto [m_coord, n_coord, k_coord, l_coord] = tile_coord_mnkl;
// The tma tensor D under im2col mode only has two modes (M, N) which // should be local tiled with only (m_coord, n_coord). auto coord_shape = conditional_return<is_im2col_D>( make_coord(m_coord, n_coord), make_coord(m_coord, n_coord, l_coord));
// Represent the full output tensor, slice to get the tile this CTA is responsible for Tensor mD_mn = params.tma_store_d.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mD = coalesce(mD_mn, take<0,2>(CtaTileMNK{})); Tensor gD = local_tile(mD, take<0,2>(CtaTileMNK{}), coord_shape); // (CTA_M,CTA_N)
// Apply epilogue subtiling Tensor gD_epi = flat_divide(gD, EpilogueTile{}); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
// Construct the corresponding pipelined smem tensors auto ptr_sC = shared_tensors.collective.smem_C.begin(); auto ptr_sD = shared_tensors.collective.smem_D.begin(); Tensor sC_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sC), SmemLayoutC{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_C) Tensor sD_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(ptr_sD), SmemLayoutD{})); // (EPI_TILE_M,EPI_TILE_N,PIPE_D)
TiledCopy tiled_copy_C_atom = make_tiled_copy_C_atom(CopyAtomC{}, tiled_mma);
// (t)hread-partition for (r)egister to (r)egister copy (tRR_) TiledCopy tiled_r2r = [&]() CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (IsUseR2R) { return make_tiled_copy_S(Copy_Atom<CopyOpR2R, ElementCompute>{}, tiled_copy_C_atom); } else { return make_tiled_copy_S(Copy_Atom<AutoVectorizingCopyWithAssumedAlignment<128>, ElementCompute>{}, tiled_copy_C_atom); } }(); ThrCopy thread_r2r = tiled_r2r.get_slice(thread_idx);
// (t)hread-partition for (r)egister to (s)mem copy (tRS_) TiledCopy tiled_r2s = [&]() CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (IsUseR2R) { return make_tiled_copy_D(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_r2r); } else { return make_tiled_copy_S(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_copy_C_atom); } }(); ThrCopy thread_r2s = tiled_r2s.get_slice(thread_idx); Tensor tRS_rAcc = thread_r2s.retile_S(accumulators); // ((R2S,R2S_V),MMA_M,MMA_N) Tensor tRS_sD = thread_r2s.partition_D(sD_epi); // (R2S,R2S_M,R2S_N,PIPE_D)
auto mma_tile_m = size<0>(TileShapeMNK{}) / size<1>(tRS_rAcc); auto mma_tile_n = size<1>(TileShapeMNK{}) / size<2>(tRS_rAcc); auto epi_tile_m = size<0>(EpilogueTile{}); auto epi_tile_n = size<1>(EpilogueTile{});
// Allocate D registers Layout tRS_rD_layout = make_layout(take<0,3>(shape(thread_r2s.partition_S(sD_epi)))); Tensor tRS_rD = make_tensor<SmemElementD>(tRS_rD_layout); // (R2S,R2S_M,R2S_N)
// Vectorized fragment view constexpr int FragmentSize = DispatchPolicy::FragmentSize; Tensor tRS_rAcc_frg = recast<Array<ElementAccumulator, FragmentSize>>(tRS_rAcc); Tensor tRS_rD_frg = recast<Array<SmemElementD , FragmentSize>>(tRS_rD); CUTE_STATIC_ASSERT(size<0>(tRS_rAcc) % FragmentSize == 0, "Fragment size does not vectorize properly");
// (t)hread-partition for (s)mem to (r)egister copy (tSR_) TiledCopy tiled_s2r = make_tiled_copy_S(Copy_Atom<CopyOpS2R, SmemElementC>{}, tiled_copy_C_atom); ThrCopy thread_s2r = tiled_s2r.get_slice(thread_idx); Tensor tSR_sC = thread_s2r.partition_S(sC_epi); // (S2R,S2R_M,S2R_N,PIPE_C) Layout tSR_rC_layout = thread_s2r.retile_D(tRS_rD).layout(); // (S2R,S2R_M,S2R_N)
// Allocate C registers // If C smem load is a non-vectorized dst(i) = src(i) then we can allocate C registers directly in the compute type // to eliminate some redundant pack+unpack instruction sequences for sub-word types constexpr bool IsDirectS2R = cute::is_same_v<CopyOpS2R, AutoVectorizingCopyWithAssumedAlignment<128>> && decltype(max_common_vector(tSR_rC_layout, tSR_sC.layout()))::value <= 1; using RegisterElementC = cute::conditional_t<IsDirectS2R, ElementCompute, SmemElementC>; Tensor tRS_rC = make_tensor<RegisterElementC>(tRS_rD_layout); // (R2S,R2S_M,R2S_N) Tensor tSR_rC = thread_s2r.retile_D(tRS_rC); // (S2R,S2R_M,S2R_N)
// thread(b)lock-partition for (s)mem to (g)mem copy (bSG_) ThrCopy thrblk_s2g = params.tma_store_d.get_slice(Int<0>{}); Tensor bSG_sD = thrblk_s2g.partition_S(sD_epi); // (S2G,S2G_M,S2G_N,PIPE_D) Tensor bSG_gD = thrblk_s2g.partition_D(gD_epi); // (S2G,S2G_M,S2G_N,EPI_M,EPI_N)
// OOB predication for tile quantization "residue" // Absolute coordinate tensors (dynamic) Tensor mD_crd = make_identity_tensor(make_shape(M,N)); // (M,N) Tensor cD_mn = local_tile(mD_crd, take<0,2>(CtaTileMNK{}), make_coord(m_coord, n_coord)); // (CTA_M,CTA_N) Tensor tRS_cD_mn = [&]() CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (IsUseR2R) { // (t)hread-partition for ConsumerStoreCallbacks. TiledCopy tiled_cst = make_tiled_copy_S(Copy_Atom<CopyOpR2S,SmemElementC>{}, tiled_copy_C_atom); ThrCopy thread_cst = tiled_cst.get_slice(thread_idx);
return thread_cst.partition_S(flat_divide(cD_mn, EpilogueTile{})); // (R2S,R2S_M,R2S_N,EPI_M,EPI_N) } else { return thread_r2s.partition_S(flat_divide(cD_mn, EpilogueTile{})); // (R2S,R2S_M,R2S_N,EPI_M,EPI_N) } }(); // Relative coordinate tensors (static) Tensor cD = make_coord_tensor(cD_mn.layout()); // (CTA_M,CTA_N) Tensor tRS_cD = make_coord_tensor(tRS_cD_mn.layout()); // (R2S,R2S_M,R2S_N,EPI_M,EPI_N) // Subtract the global "bottom right" corner from the local "top left" corner to get the max relative coordinate auto residue_cD = make_coord(M,N) - cD_mn(_0{}); // (m,n) auto residue_tRS_cD = make_coord(M,N) - tRS_cD_mn(_0{}); // (m,n)
CUTE_STATIC_ASSERT(epi_tile_m % mma_tile_m == 0, "MMA_TILE_M must divide EPI_TILE_M");
if constexpr (epi_tile_m * epi_tile_n > mma_tile_m * mma_tile_n) { // When the epilogue subtile is larger than the MMA tiles, loop over multiple MMA tiles CUTE_STATIC_ASSERT(epi_tile_n % mma_tile_n == 0, "MMA_TILE_N must divide EPI_TILE_N"); } else { CUTE_STATIC_ASSERT(mma_tile_n % epi_tile_n == 0, "EPI_TILE_N must divide MMA_TILE_N"); }
// Get TiledCopy for partition reference when consumer store. TiledCopy tiled_copy_partition_ref = make_tiled_copy_S(Copy_Atom<CopyOpR2S,SmemElementD>{}, tiled_copy_C_atom); // Get the fusion callbacks for the consumer store warps constexpr bool RefSrc = true; // Register tensors reference tiled copy src layout auto cst_args = cutlass::epilogue::fusion::detail::ConsumerStoreArgs( problem_shape_mnkl, CtaTileMNK{}, tile_coord_mnkl, tiled_mma, EpilogueTile{}, tiled_copy_partition_ref, cD, residue_cD, tRS_cD, residue_tRS_cD, tRS_rC, thread_idx ); auto cst_callbacks = fusion_callbacks.template get_consumer_store_callbacks<RefSrc>(cst_args); bool is_producer_load_needed = fusion_callbacks.is_producer_load_needed(); bool is_C_load_needed = is_source_supported && fusion_callbacks.is_C_load_needed();
using FragmentVisit = decltype(cst_callbacks.visit(tRS_rAcc_frg(0), 0, 0, 0)); constexpr bool IsDirectR2S = cute::is_same_v<FragmentVisit, Array<SmemElementD, FragmentSize>>; using RegisterElementD = cute::conditional_t<!IsDirectR2S, ElementCompute, SmemElementD>; Tensor tRS_rCompute = make_tensor<RegisterElementD>(tRS_rD_layout); // (R2S,R2S_M,R2S_N) Tensor tRS_rCompute_frg = recast<Array<RegisterElementD, FragmentSize>>(tRS_rCompute);
// Thread synchronizer for previously issued waits or fences // to ensure visibility of smem reads/writes to threads or TMA unit auto synchronize = [&] () CUTLASS_LAMBDA_FUNC_INLINE { cutlass::arch::NamedBarrier::sync(size(TiledMma{}), cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
// Predication for TMA store (one warp issues TMA store) bool issue_tma_store = (thread_idx / NumThreadsPerWarp) == 0;
// In the reuse smem configuration we have StagesC smem buffers and at most StagesD committed TMA stores in flight. // The TMA store pipeline producer acquire returns when at most StagesD-1 committed stores are in-flight, so we can // only guarantee store completion after StagesD iterations, then we can begin issuing releases on the smem buffer locks. // store_pipe_producer_state tracks the acquire and load_pipe_consumer_state tracks the release, in circular buffer fashion. LoadPipelineState load_wait_state = load_pipe_consumer_state; if constexpr (ReuseSmemC) { load_wait_state = store_pipe_producer_state; load_wait_state.phase_ ^= 1; }
// We can delay issue of TMA store by one iteration to achieve better interleaving of non-TMA instructions // Sync requirements of smem reuse may preclude this optimization // Delayed stores cause delayed stage releases which causes deadlock when StagesC == StagesD [[maybe_unused]] int epi_m_prev = 0; [[maybe_unused]] int epi_n_prev = 0; static_assert(not (DelayTmaStore and ReuseSmemC and StagesC <= StagesD), "This TMA epilogue configuration will deadlock");
// The TMA store sequence for one subtile iteration auto tma_store_fn = [&] (int epi_m, int epi_n) CUTLASS_LAMBDA_FUNC_INLINE { // Write the tile from smem to gmem with TMA cutlass::arch::fence_view_async_shared(); // ensure smem writes are visible to TMA synchronize(); // ensure all threads have issued their async fence if constexpr (is_destination_supported) { if (issue_tma_store) { copy(params.tma_store_d, bSG_sD(_,_,_,store_pipe_producer_state.index()), bSG_gD(_,_,_,epi_m,epi_n)); } }
// Post async fence, pre TMA commit callback entry point cst_callbacks.tma_store(epi_m, epi_n, store_pipe_producer_state.count(), issue_tma_store);
// Commit the TMA stores for this stage if (issue_tma_store) { store_pipeline.producer_commit(store_pipe_producer_state); } ++store_pipe_producer_state; ++issued_stores;
// Wait for the next smem buffer to be available if (issue_tma_store) { store_pipeline.producer_acquire(store_pipe_producer_state); } synchronize();
if constexpr (ReuseSmemC) { // producer_acquire returns when at most StagesD-1 committed stores are pending bool store_finished = issued_stores > StorePipeline::UnacquiredStages; // Let dma warp know earliest smem buffer is consumed and empty after StagesD producer commits if (store_finished) { if (is_producer_load_needed) { load_pipeline.consumer_release(load_pipe_consumer_state); } ++load_pipe_consumer_state; } } };
// // BEGIN EPILOGUE //
// Pre-loop fusion callback entry point cst_callbacks.begin(); if (cst_callbacks.begin_sync_needed()) { synchronize(); }
// For each output tile CUTLASS_PRAGMA_UNROLL for (int epi_n = 0; epi_n < size<3>(gD_epi); ++epi_n) { CUTLASS_PRAGMA_UNROLL for (int epi_m = 0; epi_m < size<2>(gD_epi); ++epi_m) { [[maybe_unused]] bool is_first_iteration = epi_m == 0 && epi_n == 0; bool is_last_iteration = epi_m == size<2>(gD_epi)-1 && epi_n == size<3>(gD_epi)-1;
if (subtile_idx != -1 && (epi_n * static_cast<int>(size<2>(gD_epi)) + epi_m) != subtile_idx) { continue; }
cst_callbacks.begin_loop(epi_m, epi_n);
if (is_producer_load_needed) { // Wait for the producer load to fill smem load_pipeline.consumer_wait(load_wait_state);
if (is_C_load_needed) { // Copy source tile from smem to register copy(tiled_s2r, tSR_sC(_,_,_,load_wait_state.index()), tSR_rC); // Ensure smem loads are complete before reusing smem for mixed types/layouts if constexpr (ReuseSmemC && not (SmemLayoutC{} == SmemLayoutD{})) { synchronize(); } } }
// First loop fusion callback entry point cst_callbacks.previsit(epi_m, epi_n, load_wait_state.count(), is_producer_load_needed);
if (is_producer_load_needed) { if constexpr (not ReuseSmemC) { // Let producer load warp know smem buffers are consumed and empty cutlass::arch::fence_view_async_shared(); load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } ++load_wait_state; }
if constexpr (epi_tile_m * epi_tile_n > mma_tile_m * mma_tile_n) { // When the epilogue subtile is larger than the MMA tiles, loop over multiple // MMA tiles static constexpr int MmaMPerEpiM = epi_tile_m / mma_tile_m; static constexpr int MmaNPerEpiN = epi_tile_n / mma_tile_n;
CUTLASS_PRAGMA_UNROLL for (int mma_n_in_epi = 0; mma_n_in_epi < MmaNPerEpiN; ++mma_n_in_epi) { int mma_n = (epi_n * MmaNPerEpiN) + mma_n_in_epi;
CUTLASS_PRAGMA_UNROLL for (int mma_m_in_epi = 0; mma_m_in_epi < MmaMPerEpiM; ++mma_m_in_epi) { int mma_m = (epi_m * MmaMPerEpiM) + mma_m_in_epi; Tensor tRS_rAcc_frg_mn = tRS_rAcc_frg(_,mma_m,mma_n); int idx_in_epi_subtile = (mma_n_in_epi * MmaMPerEpiM + mma_m_in_epi);
tRS_rCompute_frg(idx_in_epi_subtile) = cst_callbacks.visit( tRS_rAcc_frg_mn(0), idx_in_epi_subtile, epi_m, epi_n); } } } else { int mma_m = epi_m; int mma_n = (epi_n * size<1>(EpilogueTile{})) / mma_tile_n; Tensor tRS_rAcc_frg_mn = tRS_rAcc_frg(_,mma_m,mma_n);
// Vectorized fragment loop with visitor callback entry point int epi_n_in_mma = epi_n % (mma_tile_n / epi_tile_n); int r2s_v = epi_n_in_mma * size(tRS_rCompute_frg); CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(tRS_rCompute_frg); ++epi_v) { tRS_rCompute_frg(epi_v) = cst_callbacks.visit(tRS_rAcc_frg_mn(r2s_v + epi_v), epi_v, epi_m, epi_n); } }
// The latest we can delay the TMA store is right before the smem store of the next iteration // since the current TMA store needs to be committed before we can acquire the next smem buffer if constexpr (DelayTmaStore) { // Issue TMA stores for the previous subtile if (not is_first_iteration and subtile_idx == -1) { tma_store_fn(epi_m_prev, epi_n_prev); } epi_m_prev = epi_m; epi_n_prev = epi_n; }
// Smem reduction callback entry point using current store buffer for workspace cst_callbacks.reduce(sD_epi(_,_,store_pipe_producer_state.index()), synchronize, epi_m, epi_n, is_last_iteration, tRS_rCompute_frg);
// Copy tile from register to regiser if needed if constexpr (IsUseR2R) { // retile source and destination for tiled_r2r Tensor tRR_rD_src = thread_r2r.retile_S(tRS_rCompute); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N) Tensor tRR_rD_dst = thread_r2r.retile_D(tRS_rCompute); // (R2R,R2R_M,R2R_N,EPI_M,EPI_N)
// Output register transformation before copying to shared memory. copy(tiled_r2r, tRR_rD_src, tRR_rD_dst); }
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tRS_rD_frg); ++i) { tRS_rD_frg(i) = cutlass::NumericArrayConverter<SmemElementD, RegisterElementD, FragmentSize>{}(tRS_rCompute_frg(i)); }
// Copy tile from register to smem if constexpr (is_destination_supported) { copy(tiled_r2s, tRS_rD, tRS_sD(_,_,_,store_pipe_producer_state.index())); }
// Post reduction, pre TMA store callback entry point constexpr bool issue_smem_store = true; // No smem store predication cst_callbacks.postreduce(epi_m, epi_n, store_pipe_producer_state.count(), issue_smem_store);
if constexpr (not DelayTmaStore) { // Issue TMA stores for this subtile tma_store_fn(epi_m, epi_n); }
cst_callbacks.end_loop(epi_m, epi_n);
} // for epi_m } // for epi_n
if constexpr (DelayTmaStore) { // Issue TMA stores for the last subtile tma_store_fn(epi_m_prev, epi_n_prev); }
// Post-loop fusion callback entry point cst_callbacks.end();
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
CUTLASS_DEVICE auto store_tail( LoadPipeline load_pipeline, LoadPipelineState load_pipe_consumer_state, StorePipeline store_pipeline, StorePipelineState store_pipe_producer_state) { // wait for all TMA stores to complete store_pipeline.producer_tail(store_pipe_producer_state); // reset store counter issued_stores = 0;
if constexpr (ReuseSmemC) { if (fusion_callbacks.is_producer_load_needed()) { // Issue releases on up to StagesD-1 previously issued TMA stores constexpr int release_stages = cute::min(StorePipeline::UnacquiredStages, get_load_pipe_increment(CtaTileMNK{})); CUTLASS_PRAGMA_UNROLL for (int stage = 0; stage < release_stages; ++stage) { load_pipeline.consumer_release(load_pipe_consumer_state); ++load_pipe_consumer_state; } } }
return cute::make_tuple(load_pipe_consumer_state, store_pipe_producer_state); }
private: Params const& params; FusionCallbacks fusion_callbacks; int issued_stores = 0;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing pipelined epilogues with bias add and elementwise activation functions. This collective is now DEPRECATED, will be removed in the next release. Use EVT instead.*/
#pragma once
#include "sm90_epilogue_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int StagesC_, int StagesD_, int FragmentSize_, class BlockTileShape_, // (BLK_M,BLK_N,BLK_K) class EpilogueTileShape_, // (EPI_TILE_M,EPI_TILE_N) class ElementC_, class StrideC_, class ElementD_, class StrideD_, class FusionCallbacks_, class CopyOpG2S_, class SmemLayoutAtomC_, class CopyOpS2R_, class CopyOpS2G_, class SmemLayoutAtomD_, class CopyOpR2S_, class CopyAtomC_, class CopyOpR2R_>class Sm90EpilogueTmaWarpSpecializedBiasElementwise : public CollectiveEpilogue< Sm90TmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, false, false>, BlockTileShape_, EpilogueTileShape_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpG2S_, SmemLayoutAtomC_, CopyOpS2R_, CopyOpS2G_, SmemLayoutAtomD_, CopyOpR2S_, CopyAtomC_, CopyOpR2R_> {private: using Impl = CollectiveEpilogue< Sm90TmaWarpSpecialized<StagesC_, StagesD_, FragmentSize_, false, false>, BlockTileShape_, EpilogueTileShape_, ElementC_, StrideC_, ElementD_, StrideD_, FusionCallbacks_, CopyOpG2S_, SmemLayoutAtomC_, CopyOpS2R_, CopyOpS2G_, SmemLayoutAtomD_, CopyOpR2S_, CopyAtomC_, CopyOpR2R_ >;public: using DispatchPolicy = Sm90TmaWarpSpecializedBiasElementwise<StagesC_, StagesD_, FragmentSize_>; using ElementCompute = typename Impl::ThreadEpilogueOp::ElementCompute; using ElementBias = typename Impl::ThreadEpilogueOp::ElementBias; using ElementT = typename Impl::ThreadEpilogueOp::ElementAux;
// Constructor inheritance using Impl::Impl;
// Host side epilogue arguments struct [[deprecated("use Sm90TmaWarpSpecialized Arguments instead")]] Arguments { struct ThreadArgs { ElementCompute alpha{1}; ElementCompute beta{0}; ElementCompute const *alpha_ptr{nullptr}; ElementCompute const *beta_ptr{nullptr}; } thread; ElementC_ const* ptr_C{nullptr}; StrideC_ dC{}; ElementD_* ptr_D{nullptr}; StrideD_ dD{}; ElementBias const* ptr_Bias{nullptr}; ElementT* ptr_T{nullptr};
CUTLASS_HOST_DEVICE operator typename Impl::Arguments() const { typename Impl::Arguments arguments; arguments.thread.alpha = thread.alpha; arguments.thread.beta = thread.beta; arguments.thread.alpha_ptr = thread.alpha_ptr; arguments.thread.beta_ptr = thread.beta_ptr; if constexpr (not cute::is_void_v<ElementBias>) { arguments.thread.bias_ptr = ptr_Bias; } if constexpr (not cute::is_void_v<ElementT>) { arguments.thread.aux_ptr = ptr_T; arguments.thread.dAux = dD; } arguments.ptr_C = ptr_C; arguments.dC = dC; arguments.ptr_D = ptr_D; arguments.dD = dD;
return arguments; } };
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace collective} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/#pragma once
#include "cutlass/numeric_conversion.h"#include "cutlass/epilogue/thread/scale_type.h"
//////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue {
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// Builder Epilogue Schedules////////////////////////////////////////////////////////////////////////////////// Pre-Hopper schedulesstruct PtrArrayDefault {};struct EpilogueSimtVectorized {};struct EpiloguePtrArraySimtVectorized {};// Hopper direct store schedulesstruct NoSmemWarpSpecialized {};struct PtrArrayNoSmemWarpSpecialized {};struct PtrArrayNoSmemWarpSpecializedTransposed {};// Hopper TMA schedulesstruct TmaWarpSpecialized {};struct TmaWarpSpecializedCooperative {};struct PtrArrayTmaWarpSpecialized { static constexpr int NumEpilogueWarpGroups = 1; };struct PtrArrayTmaWarpSpecializedPingpong { static constexpr int NumEpilogueWarpGroups = 2; };struct PtrArrayTmaWarpSpecializedCooperative { static constexpr int NumEpilogueWarpGroups = 2; };// Blackwell direct store schedulesstruct NoSmemWarpSpecialized1Sm {};struct NoSmemWarpSpecialized2Sm {};struct FastF32NoSmemWarpSpecialized1Sm : NoSmemWarpSpecialized1Sm {};struct FastF32NoSmemWarpSpecialized2Sm : NoSmemWarpSpecialized2Sm {};struct BlockwiseNoSmemWarpSpecialized1Sm : NoSmemWarpSpecialized1Sm {};struct BlockwiseNoSmemWarpSpecialized2Sm : NoSmemWarpSpecialized2Sm {};struct PtrArrayNoSmemWarpSpecialized1Sm : NoSmemWarpSpecialized1Sm {};struct PtrArrayNoSmemWarpSpecialized2Sm : NoSmemWarpSpecialized2Sm {};struct PtrArrayFastF32NoSmemWarpSpecialized1Sm : PtrArrayNoSmemWarpSpecialized1Sm {};struct PtrArrayFastF32NoSmemWarpSpecialized2Sm : PtrArrayNoSmemWarpSpecialized2Sm {};struct PtrArrayBlockwiseNoSmemWarpSpecialized1Sm : PtrArrayNoSmemWarpSpecialized1Sm {};struct PtrArrayBlockwiseNoSmemWarpSpecialized2Sm : PtrArrayNoSmemWarpSpecialized2Sm {};// Blackwell TMA schedules struct TmaWarpSpecialized1Sm {};struct TmaWarpSpecialized2Sm {};struct PtrArrayTmaWarpSpecialized1Sm : TmaWarpSpecialized1Sm {};struct PtrArrayTmaWarpSpecialized2Sm : TmaWarpSpecialized2Sm {};struct TmaWarpSpecialized1SmNvf4 final : TmaWarpSpecialized1Sm {};struct TmaWarpSpecialized2SmNvf4 final : TmaWarpSpecialized2Sm {};struct TmaWarpSpecialized1SmMxf4 final : TmaWarpSpecialized1Sm {};struct TmaWarpSpecialized2SmMxf4 final : TmaWarpSpecialized2Sm {};struct TmaWarpSpecialized1SmMxf8f6f4 final : TmaWarpSpecialized1Sm {};struct TmaWarpSpecialized2SmMxf8f6f4 final : TmaWarpSpecialized2Sm {};// Cooperative epilogue schedule for sm120 sparse kernelsstruct SparseTmaWarpSpecializedCooperativeSm120 : public TmaWarpSpecializedCooperative {};
// DEPRECATED schedules, will be removed in next releasestruct TmaWarpSpecializedElementwiseBase : public TmaWarpSpecialized {};struct TmaWarpSpecializedCooperativeElementwiseBase : public TmaWarpSpecializedCooperative {};template < template <class T> class ActivationFunctor_, thread::ScaleType::Kind Scale_ = thread::ScaleType::Default, FloatRoundStyle Round_ = FloatRoundStyle::round_to_nearest>struct [[deprecated("Use TmaWarpSpecialized with fusion::LinCombEltAct instead")]]TmaWarpSpecializedElementwise : public TmaWarpSpecializedElementwiseBase { template <class T> using ActivationFunctor = ActivationFunctor_<T>; static constexpr thread::ScaleType::Kind Scale = Scale_; static constexpr FloatRoundStyle Round = Round_;};
template < template <class T> class ActivationFunctor_, thread::ScaleType::Kind Scale_ = thread::ScaleType::Default, FloatRoundStyle Round_ = FloatRoundStyle::round_to_nearest>struct [[deprecated("Use TmaWarpSpecializedCooperative with fusion::LinCombEltAct instead")]]TmaWarpSpecializedCooperativeElementwise : public TmaWarpSpecializedCooperativeElementwiseBase { template <class T> using ActivationFunctor = ActivationFunctor_<T>; static constexpr thread::ScaleType::Kind Scale = Scale_; static constexpr FloatRoundStyle Round = Round_;};
struct TmaWarpSpecializedBiasElementwiseBase : public TmaWarpSpecialized{};struct TmaWarpSpecializedCooperativeBiasElementwiseBase : public TmaWarpSpecializedCooperative {};
template < template <class T> class ActivationFunctor_, class ElementT_, template <class T> class BiasOp_, bool StoreT_, class ElementBias_>struct [[deprecated("Use TmaWarpSpecialized with fusion::LinCombPerRowBiasEltActAux instead")]]TmaWarpSpecializedBiasElementwise : public TmaWarpSpecializedBiasElementwiseBase { template <class T> using ActivationFunctor = ActivationFunctor_<T>; using ElementT = ElementT_;
template <class T> using BiasOp = BiasOp_<T>;
static constexpr bool StoreT = StoreT_; using ElementBias = ElementBias_;};
template < template <class T> class ActivationFunctor_, class ElementT_, template <class T> class BiasOp_, bool StoreT_, class ElementBias_>struct [[deprecated("Use TmaWarpSpecializedCooperative with fusion::LinCombPerRowBiasEltActAux instead")]]TmaWarpSpecializedCooperativeBiasElementwise : public TmaWarpSpecializedCooperativeBiasElementwiseBase { template <class T> using ActivationFunctor = ActivationFunctor_<T>;
using ElementT = ElementT_;
template <class T> using BiasOp = BiasOp_<T>;
static constexpr bool StoreT = StoreT_; using ElementBias = ElementBias_;};
////////////////////////////////////////////////////////////////////////////////// Collective Dispatch Policies////////////////////////////////////////////////////////////////////////////////
template< int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_>struct Sm90TmaWarpSpecialized { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_; constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool DelayTmaStore = DelayTmaStore_;};
template< int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_, int NumEpilogueWarpGroups_>struct Sm90PtrArrayTmaWarpSpecialized { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_; constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool DelayTmaStore = DelayTmaStore_; constexpr static int NumEpilogueWarpGroups = NumEpilogueWarpGroups_;};
// DEPRECATED policies, will be removed in next releasetemplate< int StagesC_, int StagesD_, int FragmentSize_ = 2>struct Sm90TmaWarpSpecializedBiasElementwise { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_;};
template< int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_>struct Sm100TmaWarpSpecialized { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_; constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool DelayTmaStore = DelayTmaStore_;};
template< int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_>struct Sm100PtrArrayTmaWarpSpecialized { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_; constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool DelayTmaStore = DelayTmaStore_;
static_assert(StagesC >= 1, "StagesC must be >= 1"); static_assert(StagesD >= 1, "StagesD must be >= 1");};
struct Sm100NoSmem { constexpr static int StagesC = 1; constexpr static int StagesD = 1; constexpr static int FragmentSize = 1;};
struct Sm100NoSmemWarpSpecialized { constexpr static int StagesC = 1; constexpr static int StagesD = 1; constexpr static int FragmentSize = 1;};
struct Sm100PtrArrayNoSmem { constexpr static int StagesC = 1; constexpr static int StagesD = 1; constexpr static int FragmentSize = 1;};
struct Sm100PtrArrayNoSmemWarpSpecialized { constexpr static int StagesC = 1; constexpr static int StagesD = 1; constexpr static int FragmentSize = 1;};template< int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_>struct Sm120TmaWarpSpecialized { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_; constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool DelayTmaStore = DelayTmaStore_;};
template< int StagesC_, int StagesD_, int FragmentSize_, bool ReuseSmemC_, bool DelayTmaStore_, int NumEpilogueWarpGroups_>struct Sm120PtrArrayTmaWarpSpecialized { constexpr static int StagesC = StagesC_; constexpr static int StagesD = StagesD_; constexpr static int FragmentSize = FragmentSize_; constexpr static bool ReuseSmemC = ReuseSmemC_; constexpr static bool DelayTmaStore = DelayTmaStore_; constexpr static int NumEpilogueWarpGroups = NumEpilogueWarpGroups_;};
//////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
#pragma once
#include "cutlass/detail/dependent_false.hpp"#include "cutlass/epilogue/fusion/operations.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Dispatch interface for epilogue fusion callbacks// For visitor fusions, this is just a convenience wrapper to provide metadata and non-nested args.// It is also valid to just pass visitor callbacks directly to the collective, e.g. fusion::Sm90LinearCombination,// provided the collective supports a visitor callbacks interface. This is useful for implementing custom fusions.template < class DispatchPolicy, // specialize on collective's dispatch policy since callbacks API will depend on collective's algorithm class Operation, // the fusion operation being performed, e.g. fusion::LinearCombination class CtaTile_MNK, // computed tile per CTA class EpilogueTile_MN, // epilogue subtile size class... Args // callbacks implementation dependent args (e.g. copy atoms, smem layouts)>struct FusionCallbacks { static_assert(cutlass::detail::dependent_false<DispatchPolicy, Operation>, "Could not find a callbacks specialization.");};
// Metadata helper to handle custom EVTs or other non-FusionCallbacks typestemplate <class T>struct FusionCallbacksTraits { using DispatchPolicy = void; using Callbacks = T; using Operation = FusionOperation; using CtaTile_MNK = void; using EpilogueTile_MN = void; using ElementCompute = void;};
template < class DispatchPolicy_, class Operation_, class CtaTile_MNK_, class EpilogueTile_MN_, class... Args>struct FusionCallbacksTraits< FusionCallbacks<DispatchPolicy_, Operation_, CtaTile_MNK_, EpilogueTile_MN_, Args...>> { using DispatchPolicy = DispatchPolicy_; using Callbacks = FusionCallbacks<DispatchPolicy_, Operation_, CtaTile_MNK_, EpilogueTile_MN_, Args...>; using Operation = Operation_; using CtaTile_MNK = CtaTile_MNK_; using EpilogueTile_MN = EpilogueTile_MN_; using ElementCompute = typename Operation::ElementCompute;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
#pragma once
#include <cutlass/numeric_conversion.h>#include <cutlass/layout/matrix.h>#include <cute/numeric/numeric_types.hpp>#include <cute/numeric/integral_constant.hpp> // cute::false_type
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// Fusion Operations// Template args must not be implementation dependent///////////////////////////////////////////////////////////////////////////////////////////////////
struct FusionOperation { // metadata types/queries that can be overrided using ElementOutput = void; using ElementCompute = void; FloatRoundStyle RoundStyle = FloatRoundStyle::round_indeterminate;
using ElementSource = void; static constexpr bool IsSourceSupported = false; static constexpr bool IsResidualSupported = false; // Source is added after activation
using ElementScalar = void; static constexpr int AlignmentScalar = 0; static constexpr bool IsScaleFactorSupported = false; static constexpr bool IsPerRowScaleSupported = false; static constexpr bool IsPerColScaleSupported = false;
using ElementBias = void; static constexpr int AlignmentBias = 0; static constexpr bool IsPerRowBiasSupported = false; static constexpr bool IsPerColBiasSupported = false; static constexpr bool IsDePerRowBiasSupported = false;
using ActivationFn = void; static constexpr bool IsEltActSupported = false; static constexpr bool IsDeEltActSupported = false;
using ElementAux = void; using GmemLayoutTagAux = void; static constexpr int AlignmentAux = 0; static constexpr bool IsAuxOutSupported = false; static constexpr bool IsAuxInSupported = false;
using ElementAmax = void; static constexpr bool IsAbsMaxSupported = false;
using ElementBlockScaleFactor = void; static constexpr int SFVecSize = 0; static constexpr bool IsBlockScaleSupported = false; // Umbrella variable to check BlockScaling support in the epilogues using GmemLayoutTagScalefactor = void;};
// D = alpha * acctemplate< class ElementOutput_, class ElementCompute_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct ScaledAcc : FusionOperation { using ElementOutput = ElementOutput_; using ElementCompute = ElementCompute_; using ElementScalar = ElementScalar_; static constexpr int AlignmentScalar = 1; static constexpr auto RoundStyle = RoundStyle_;};
// D = alpha * acc + beta * Ctemplate< class ElementOutput_, class ElementCompute_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinearCombination : ScaledAcc<ElementOutput_, ElementCompute_, ElementScalar_, RoundStyle_> { using ElementSource = ElementSource_; static constexpr bool IsSourceSupported = true;};
// D = activation(alpha * acc + beta * C)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombEltAct : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using ActivationFn = ActivationFn_<ElementCompute_>; static constexpr bool IsEltActSupported = true;};
// D = softmax(top_k(alpha * acc + beta * C))template< int TopK, class ElementOutput_, class ElementCompute_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombTopKSoftmaxCol : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> {};
// D = alpha * acc + beta * C + per-row biastemplate< class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerRowBias : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using ElementBias = ElementBias_; static constexpr int AlignmentBias = AlignmentBias_; static constexpr bool IsPerRowBiasSupported = true;};
// D = alpha * acc + beta * C + per-column biastemplate< class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerColBias : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using ElementBias = ElementBias_; static constexpr int AlignmentBias = AlignmentBias_; static constexpr bool IsPerColBiasSupported = true;};
// D = activation(alpha * acc + beta * C + per-row bias)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerRowBiasEltAct : LinCombPerRowBias<ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ActivationFn = ActivationFn_<ElementCompute_>; static constexpr bool IsEltActSupported = true;};
// Grouped Wgrad's D = alpha * acc + beta * C with special AccFetch.template< class GroupsPerTile_, class ElementOutput_, class ElementCompute_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinearCombinationGroupedWgrad : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using GroupsPerTile = GroupsPerTile_;};
// D = activation(alpha * acc + beta * C + per-column bias)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerColBiasEltAct : LinCombPerColBias<ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ActivationFn = ActivationFn_<ElementCompute_>; static constexpr bool IsEltActSupported = true;};
// D = activation(alpha * acc + beta * C + per-row bias)// aux = alpha * acc + beta * C + per-row biastemplate< class GmemLayoutTagAux_, template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementAux_ = ElementOutput_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentAux_ = 128 / cute::sizeof_bits_v<ElementAux_>, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerRowBiasEltActAux : LinCombPerRowBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementAux = ElementAux_; using GmemLayoutTagAux = GmemLayoutTagAux_; static constexpr int AlignmentAux = AlignmentAux_; static constexpr bool IsAuxOutSupported = true;};
// D = activation(alpha * acc + beta * C + per-col bias)// aux = alpha * acc + beta * C + per-col biastemplate< class GmemLayoutTagAux_, template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementAux_ = ElementOutput_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentAux_ = 128 / cute::sizeof_bits_v<ElementAux_>, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerColBiasEltActAux : LinCombPerColBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementAux = ElementAux_; using GmemLayoutTagAux = GmemLayoutTagAux_; static constexpr int AlignmentAux = AlignmentAux_; static constexpr bool IsAuxOutSupported = true;};
// D = activation(per-row alpha * acc + per-row beta * C + per-row bias)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, // per-row alpha/beta int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, int AlignmentScalar_ = 128 / cute::sizeof_bits_v<ElementScalar_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct PerRowLinCombPerRowBiasEltAct : LinCombPerRowBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { static constexpr int AlignmentScalar = AlignmentScalar_; static constexpr bool IsPerRowScaleSupported = true;};
// D = activation(per-col alpha * acc + per-col beta * C + per-column bias)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, // per-row alpha/beta int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, int AlignmentScalar_ = 128 / cute::sizeof_bits_v<ElementScalar_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct PerColLinCombPerColBiasEltAct : LinCombPerColBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { static constexpr int AlignmentScalar = AlignmentScalar_; static constexpr bool IsPerColScaleSupported = true;};
// D = activation(per-col alpha * acc + per-column bias) + per-col beta * Ctemplate< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, // per-row alpha/beta int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, int AlignmentScalar_ = 128 / cute::sizeof_bits_v<ElementScalar_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct PerColResAddPerColBiasEltAct : PerColLinCombPerColBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, AlignmentScalar_, RoundStyle_> { static constexpr bool IsResidualSupported = true;};
// Z = scale_a * scale_b * alpha * acc + beta * scale_c * C + per-row bias// if D is fp8 // D = scale_d * activation(Z)// else// D = activation(Z)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct ScaledLinCombPerRowBiasEltAct : LinCombPerRowBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { static constexpr bool IsScaleFactorSupported = true;};
// Z = scale_a * scale_b * alpha * acc + beta * scale_c * C + per-col bias// if D is fp8 // D = scale_d * activation(Z)// else// D = activation(Z)template< template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct ScaledLinCombPerColBiasEltAct : LinCombPerColBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { static constexpr bool IsScaleFactorSupported = true;};
// Z = scale_a * scale_b * alpha * acc + scale_c * beta * C + per-row bias// if D is fp8 // amax_d = max(abs(elements in activation(Z)))// D = scale_d * activation(Z)// else// D = activation(Z)// if Aux is fp8 // amax_aux = max(abs(elements in Z))// Aux = scale_aux * Z// else// Aux = Ztemplate< class GmemLayoutTagAux_, template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementAux_ = ElementOutput_, class ElementAmax_ = ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentAux_ = 128 / cute::sizeof_bits_v<ElementAux_>, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct ScaledLinCombPerRowBiasEltActAmaxAux : ScaledLinCombPerRowBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementAmax = ElementAmax_; static constexpr bool IsAbsMaxSupported = true;
using ElementAux = ElementAux_; using GmemLayoutTagAux = GmemLayoutTagAux_; static constexpr int AlignmentAux = AlignmentAux_; static constexpr bool IsAuxOutSupported = true;};
// Z = scale_a * scale_b * alpha * acc + scale_c * beta * C + per-col bias// if D is fp8 // amax_d = max(abs(elements in activation(Z)))// D = scale_d * activation(Z)// else// D = activation(Z)// if Aux is fp8 // amax_aux = max(abs(elements in Z))// Aux = scale_aux * Z// else// Aux = Ztemplate< class GmemLayoutTagAux_, template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementAux_ = ElementOutput_, class ElementAmax_ = ElementCompute_, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentAux_ = 128 / cute::sizeof_bits_v<ElementAux_>, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct ScaledLinCombPerColBiasEltActAmaxAux : ScaledLinCombPerColBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementAmax = ElementAmax_; static constexpr bool IsAbsMaxSupported = true;
using ElementAux = ElementAux_; using GmemLayoutTagAux = GmemLayoutTagAux_; static constexpr int AlignmentAux = AlignmentAux_; static constexpr bool IsAuxOutSupported = true;};
// Z = Aux// dY = alpha * acc + beta * C// D = d_activation(dY, Z)template< class GmemLayoutTagAux_, template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementAux_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentAux_ = 128 / cute::sizeof_bits_v<ElementAux_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombDeEltAct : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using ActivationFn = ActivationFn_<ElementCompute_>; static constexpr bool IsDeEltActSupported = true;
using ElementAux = ElementAux_; using GmemLayoutTagAux = GmemLayoutTagAux_; static constexpr int AlignmentAux = AlignmentAux_; static constexpr bool IsAuxInSupported = true;};
// Z = Aux// dY = alpha * acc + beta * C// D = d_activation(dY, Z)// dBias = sum of columns of Dtemplate< class GmemLayoutTagAux_, template <class> class ActivationFn_, class ElementOutput_, class ElementCompute_, class ElementAux_ = ElementOutput_, class ElementBias_ = ElementCompute_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentAux_ = 128 / cute::sizeof_bits_v<ElementAux_>, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombDeEltActDePerRowBias : LinCombDeEltAct<GmemLayoutTagAux_, ActivationFn_, ElementOutput_, ElementCompute_, ElementAux_, ElementSource_, ElementScalar_, AlignmentAux_, RoundStyle_> { using ElementBias = ElementBias_; static constexpr int AlignmentBias = AlignmentBias_; static constexpr bool IsDePerRowBiasSupported = true;};
template< int SFVecSize_, class ElementOutput_, class ElementCompute_, class ElementBlockScaleFactor_, class GmemLayoutTagScalefactor_ = cutlass::layout::RowMajor, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombBlockScaleFactor : LinearCombination<ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using ElementBlockScaleFactor = ElementBlockScaleFactor_; static constexpr int SFVecSize = SFVecSize_; static constexpr bool IsBlockScaleSupported = true; using GmemLayoutTagScalefactor = GmemLayoutTagScalefactor_;};
// D = activation(alpha * acc + beta * C)// With BlockScaleFactor generation (same recipe as LinCombBlockScaleFactor).template< template <class> class ActivationFn_, int SFVecSize_, class ElementOutput_, class ElementCompute_, class ElementBlockScaleFactor_, class GmemLayoutTagScalefactor_ = cutlass::layout::RowMajor, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombEltActBlockScaleFactor : LinCombEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementSource_, ElementScalar_, RoundStyle_> { using ElementBlockScaleFactor = ElementBlockScaleFactor_; static constexpr int SFVecSize = SFVecSize_; static constexpr bool IsBlockScaleSupported = true; using GmemLayoutTagScalefactor = GmemLayoutTagScalefactor_;};
// D = alpha * acc + beta * C + per-row bias// With BlockScaleFactor generationtemplate< int SFVecSize_, class ElementOutput_, class ElementCompute_, class ElementBlockScaleFactor_, class GmemLayoutTagScalefactor_ = cutlass::layout::RowMajor, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerRowBiasBlockScaleFactor : LinCombPerRowBias<ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementBlockScaleFactor = ElementBlockScaleFactor_; static constexpr int SFVecSize = SFVecSize_; static constexpr bool IsBlockScaleSupported = true; using GmemLayoutTagScalefactor = GmemLayoutTagScalefactor_;};
// D = alpha * acc + beta * C + per-col bias// With BlockScaleFactor generation.template< int SFVecSize_, class ElementOutput_, class ElementCompute_, class ElementBlockScaleFactor_, class GmemLayoutTagScalefactor_ = cutlass::layout::RowMajor, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerColBiasBlockScaleFactor : LinCombPerColBias<ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementBlockScaleFactor = ElementBlockScaleFactor_; static constexpr int SFVecSize = SFVecSize_; static constexpr bool IsBlockScaleSupported = true; using GmemLayoutTagScalefactor = GmemLayoutTagScalefactor_;};
// D = activation(alpha * acc + beta * C + per-row bias)// With BlockScaleFactor generation.template< template <class> class ActivationFn_, int SFVecSize_, class ElementOutput_, class ElementCompute_, class ElementBlockScaleFactor_, class GmemLayoutTagScalefactor_ = cutlass::layout::RowMajor, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerRowBiasEltActBlockScaleFactor : LinCombPerRowBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementBlockScaleFactor = ElementBlockScaleFactor_; static constexpr int SFVecSize = SFVecSize_; static constexpr bool IsBlockScaleSupported = true; using GmemLayoutTagScalefactor = GmemLayoutTagScalefactor_;};
// D = activation(alpha * acc + beta * C + per-col bias)// With BlockScaleFactor generation.template< template <class> class ActivationFn_, int SFVecSize_, class ElementOutput_, class ElementCompute_, class ElementBlockScaleFactor_, class GmemLayoutTagScalefactor_ = cutlass::layout::RowMajor, class ElementBias_ = ElementOutput_, class ElementSource_ = ElementOutput_, class ElementScalar_ = ElementCompute_, int AlignmentBias_ = 128 / cute::sizeof_bits_v<ElementBias_>, FloatRoundStyle RoundStyle_ = FloatRoundStyle::round_to_nearest>struct LinCombPerColBiasEltActBlockScaleFactor : LinCombPerColBiasEltAct<ActivationFn_, ElementOutput_, ElementCompute_, ElementBias_, ElementSource_, ElementScalar_, AlignmentBias_, RoundStyle_> { using ElementBlockScaleFactor = ElementBlockScaleFactor_; static constexpr int SFVecSize = SFVecSize_; static constexpr bool IsBlockScaleSupported = true; using GmemLayoutTagScalefactor = GmemLayoutTagScalefactor_;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Fusion callbacks specializations for the sm100 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"
#include "cute/tensor.hpp"
#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/fusion/callbacks.hpp"#include "cutlass/epilogue/fusion/sm90_callbacks_tma_warpspecialized.hpp"
#include "cutlass/epilogue/fusion/sm100_visitor_compute_tma_warpspecialized.hpp" #include "cutlass/epilogue/fusion/sm100_visitor_store_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Sm100 Tma warp specialized callbacks just alias to their sm90 counterparttemplate < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class Operation, class CtaTile_MNK, class EpilogueTile_MN, class... Args>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> : FusionCallbacks< epilogue::Sm90TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args... > { using FusionCallbacks< epilogue::Sm90TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...>::FusionCallbacks;};
// Sm100 direct store callbacks alias to sm100 tma callbacks with 0 stages// Additional copy atom args will be ignored in the 0-stage specializations of aux load/store nodestemplate < class Operation, class CtaTile_MNK, class EpilogueTile_MN, class... Args>struct FusionCallbacks< epilogue::Sm100NoSmemWarpSpecialized, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> : FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<0, 0, 0, false, false>, Operation, CtaTile_MNK, EpilogueTile_MN, Args... > { using FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<0, 0, 0, false, false>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...>::FusionCallbacks;};
// Sm100 Ptr array tma warp specialized callbacks just alias to their sm90 counterparttemplate < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class Operation, class CtaTile_MNK, class EpilogueTile_MN, class... Args>struct FusionCallbacks< epilogue::Sm100PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> : FusionCallbacks< epilogue::Sm90PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, 1>, Operation, CtaTile_MNK, EpilogueTile_MN, Args... > { using FusionCallbacks< epilogue::Sm90PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, 1>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...>::FusionCallbacks;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = alpha * acc + beta * C// With Row BlockScaleFactor Generation.template< int SFVecsize, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinearCombRowBlockScaleFactor = Sm90EVT<Sm100BlockScaleFactorRowStore<SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle>, // gen scalefactor Sm90LinearCombination<ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle> // beta * C + (alpha * acc) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile> : Sm100LinearCombRowBlockScaleFactor<SFVecSize, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle> {
using Impl = Sm100LinearCombRowBlockScaleFactor<SFVecSize, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle>; using Operation = fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // binary op : alpha * acc {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // binary args : multiplies }, // end binary op {} // ternary args : multiply_add }, {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } }; // Ctor inheritance using Impl::Impl;};
// D = alpha * acc + beta * C// With Col BlockScaleFactor Generation.template< int SFVecsize, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinearCombColBlockScaleFactor = Sm90EVT<Sm100BlockScaleFactorColStore<SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle>, // gen scalefactor Sm90LinearCombination<ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle> // beta * C + (alpha * acc) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile> : Sm100LinearCombColBlockScaleFactor<SFVecSize, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle> {
using Impl = Sm100LinearCombColBlockScaleFactor<SFVecSize, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle>; using Operation = fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementSource, ElementScalar, RoundStyle>;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // binary op : alpha * acc {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // binary args : multiplies }, // end binary op {} // ternary args : multiply_add }, {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// For Ptr-Array and Grouped GEMM// D = alpha * acc + beta * C, where alpha and beta can be vectors for each batch/group// With Row BlockScaleFactor Generation, separate tensors per batch/group.template< int SFVecsize, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinearCombRowBlockScaleFactorPtrArray = Sm90EVT<Sm100BlockScaleFactorRowStore<SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor *, RoundStyle>, // gen scalefactor Sm90LinearCombinationPtrArray<ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle> // beta * C + (alpha * acc) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile> : Sm100LinearCombRowBlockScaleFactorPtrArray<SFVecSize, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle> {
using Impl = Sm100LinearCombRowBlockScaleFactorPtrArray<SFVecSize, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle>; using Operation = fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementScalar const* const* alpha_ptr_array = nullptr; ElementScalar const* const* beta_ptr_array = nullptr; ElementBlockScaleFactor ** block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. // NormConst is a single device-side constant value, its not per-batch or per-group using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc) {{beta}, {beta_ptr}, {beta_ptr_array}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // binary op : alpha * acc {{alpha}, {alpha_ptr}, {alpha_ptr_array}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // binary args : multiplies }, // end binary op {} // ternary args : multiply_add }, {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } }; // Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// For Ptr-Array and Grouped GEMM// D = activation(alpha * acc + beta * C), where alpha and beta can be vectors for each batch/group// With Row BlockScaleFactor Generation, separate tensors per batch/group.template< int SFVecsize, class EpilogueTile, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombEltActRowBlockScaleFactorPtrArray = Sm90EVT<Sm100BlockScaleFactorRowStore<SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor *, RoundStyle>, // gen scalefactor Sm90LinCombEltActPtrArray<ActivationFn, ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle> // activation(beta * C + (alpha * acc)) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombEltActBlockScaleFactor<ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombEltActRowBlockScaleFactorPtrArray<SFVecSize, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle> {
using Impl = Sm100LinCombEltActRowBlockScaleFactorPtrArray<SFVecSize, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle>; using Operation = fusion::LinCombEltActBlockScaleFactor<ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementScalar const* const* alpha_ptr_array = nullptr; ElementScalar const* const* beta_ptr_array = nullptr; ElementBlockScaleFactor ** block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op: activation(beta * C + (alpha * acc)) { // ternary op : beta * C + (alpha * acc) {{beta}, {beta_ptr}, {beta_ptr_array}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // binary op : alpha * acc {{alpha}, {alpha_ptr}, {alpha_ptr_array}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // binary args : multiplies }, // end binary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = alpha * acc + beta * C + per-row bias// with row blockScaled generationtemplate< int SFVecsize, class CtaTileShapeMNK, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombPerRowBiasRowBlockScaleFactor = Sm90EVT< Sm100BlockScaleFactorRowStore< SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerRowBias< CtaTileShapeMNK, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombPerRowBiasRowBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm100LinCombPerRowBiasRowBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////// D = alpha * acc + beta * C + per-row bias// with col blockScaled generationtemplate< int SFVecsize, class CtaTileShapeMNK, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombPerRowBiasColBlockScaleFactor = Sm90EVT< Sm100BlockScaleFactorColStore< SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerRowBias< CtaTileShapeMNK, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombPerRowBiasColBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm100LinCombPerRowBiasColBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = alpha * acc + beta * C + per_col bias// with row blockScaled generationtemplate< int StagesC, int SFVecsize, class CtaTileShapeMNK, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombPerColBiasRowBlockScaleFactor = Sm90EVT< Sm100BlockScaleFactorRowStore< SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerColBias< StagesC, CtaTileShapeMNK, EpilogueTile, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerColBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombPerColBiasRowBlockScaleFactor< StagesC, SFVecSize, CtaTileShapeMNK, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm100LinCombPerColBiasRowBlockScaleFactor< StagesC, SFVecSize, CtaTileShapeMNK, EpilogueTile, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerColBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_0,_1,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = activation(alpha * acc + beta * C + per-row bias) // with row blockScaled generationtemplate< int SFVecsize, class CtaTileShapeMNK, class EpilogueTile, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombPerRowBiasEltActRowBlockScaleFactor = Sm90EVT< Sm100BlockScaleFactorRowStore< SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerRowBiasEltAct< CtaTileShapeMNK, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombPerRowBiasEltActRowBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm100LinCombPerRowBiasEltActRowBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {}; using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = activation(alpha * acc + beta * C + per-row bias) // with col blockScaled generationtemplate< int SFVecsize, class CtaTileShapeMNK, class EpilogueTile, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombPerRowBiasEltActColBlockScaleFactor = Sm90EVT< Sm100BlockScaleFactorColStore< SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerRowBiasEltAct< CtaTileShapeMNK, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombPerRowBiasEltActColBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm100LinCombPerRowBiasEltActColBlockScaleFactor< SFVecSize, CtaTileShapeMNK, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {}; using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = activation(alpha * acc + beta * C + per_col bias) // with row blockScaled generationtemplate< int StagesC, int SFVecsize, class CtaTileShapeMNK, class EpilogueTile, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm100LinCombPerColBiasEltActRowBlockScaleFactor = Sm90EVT< Sm100BlockScaleFactorRowStore< SFVecsize, EpilogueTile, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerColBiasEltAct< StagesC, CtaTileShapeMNK, EpilogueTile, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerColBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm100LinCombPerColBiasEltActRowBlockScaleFactor< StagesC, SFVecSize, CtaTileShapeMNK, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm100LinCombPerColBiasEltActRowBlockScaleFactor< StagesC, SFVecSize, CtaTileShapeMNK, EpilogueTile, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerColBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_0,_1,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {}; using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// --------------------------------------------------------------------// Sm100PtrArrayNoSmemWarpSpecialized (direct-store, grouped GEMM)// --------------------------------------------------------------------template < class Operation, class CtaTile_MNK, class EpilogueTile_MN, class... Args>struct FusionCallbacks< epilogue::Sm100PtrArrayNoSmemWarpSpecialized, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> : FusionCallbacks< // reuse the ptr-array *TMA* callbacks with 0 stages epilogue::Sm100PtrArrayTmaWarpSpecialized<0,0,0,false,false>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> {
using Base = FusionCallbacks< epilogue::Sm100PtrArrayTmaWarpSpecialized<0,0,0,false,false>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...>;
// bring ctors into scope using Base::Base;};
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500/*************************************************************************************************** * Copyright (c) 2024 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree compute operations for the sm100 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/detail/sm100_blockscaled_layout.hpp" #include "cutlass/epilogue/thread/activation.h"#include "cute/tensor.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_compute_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm100_visitor_store_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
///////////////////////////////////////////////////////////////////////////////////////////////////// BatchNormApply//// This node aims to do the batch norm apply. The procedure is described as follows://// output = (input - mean) * inv_stddev * alpha + bias//// while: (1) input & output are 2 matrices with shape (M, N),// which are frg_input & return value of the visit function//// (2) mean, inv_stddev, alpha & bias are 4 vectors with shape (N).// which are loaded by ProducerLoadCallbacks//// To avoid redundant calculations in EVT, this node simplify the procedure as follows://// output = input * alpha' + bias'//// while alpha' & bias' are 2 vectors with shape (N) calculated by mean, inv_stddev, alpha & bias//// The calculation among vectors is described as follows://// alpha' = alpha * inv_stddev// bias' = bias - mean * alpha'///////////////////////////////////////////////////////////////////////////////////////////////////
template < // reuses the mbarriers from the epilogue subtile load pipeline, so this must be at least // this should just match CLC stage count int Stages, class CtaTileShapeMNK, class ElementScalar, class ElementCompute, class ElementOutput, class StrideMNL = Stride<_0,_1,_0>, int Alignment = 128 / sizeof_bits_v<ElementScalar>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>struct Sm100BatchNormApply { static_assert(Alignment * sizeof_bits_v<ElementScalar> % 128 == 0, "sub-16B alignment not supported yet"); static_assert(cute::is_same_v<StrideMNL, Stride<_0,_1,_0>>); // row vector broadcast for alpha, bias, mean & inv_stddev
using SmemLayout = decltype(make_layout(make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{}))));
using ElementCol = cute::conditional_t<(sizeof(ElementCompute) > sizeof(ElementScalar)), ElementCompute, ElementScalar>;
struct SharedStorage { alignas(16) array_aligned<ElementCol, size<1>(CtaTileShapeMNK{}) * Stages> smem_alpha; alignas(16) array_aligned<ElementCol, size<1>(CtaTileShapeMNK{}) * Stages> smem_bias; alignas(16) array_aligned<ElementScalar, size<1>(CtaTileShapeMNK{}) * Stages> smem_mean; alignas(16) array_aligned<ElementScalar, size<1>(CtaTileShapeMNK{}) * Stages> smem_inv_stddev; };
struct Arguments { ElementScalar const* alpha_ptr = nullptr; ElementScalar const* bias_ptr = nullptr; ElementScalar const* mean_ptr = nullptr; ElementScalar const* inv_stddev_ptr = nullptr; StrideMNL dVec = {}; };
struct Params { using TMA_Vec = decltype(make_tma_atom( SM90_TMA_LOAD{}, make_tensor(make_gmem_ptr<ElementScalar const>(nullptr), repeat_like(StrideMNL{}, int32_t(0)), append<3>(StrideMNL{}, _0{})), take<0,2>(SmemLayout{}), take<0,2>(CtaTileShapeMNK{})));
TMA_Vec tma_load_alpha; TMA_Vec tma_load_bias; TMA_Vec tma_load_mean; TMA_Vec tma_load_inv_stddev; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { // Optionally append 1s until problem shape is rank-4 in case its is only rank-3 (MNK) auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl;
Tensor tensor_alpha = make_tensor(make_gmem_ptr(args.alpha_ptr), make_layout(make_shape(size(M),N,size(L)), append<3>(args.dVec, _0{}))); Tensor tensor_bias = make_tensor(make_gmem_ptr(args.bias_ptr), make_layout(make_shape(size(M),N,size(L)), append<3>(args.dVec, _0{}))); Tensor tensor_mean = make_tensor(make_gmem_ptr(args.mean_ptr), make_layout(make_shape(size(M),N,size(L)), append<3>(args.dVec, _0{}))); Tensor tensor_inv_stddev = make_tensor(make_gmem_ptr(args.inv_stddev_ptr), make_layout(make_shape(size(M),N,size(L)), append<3>(args.dVec, _0{})));
typename Params::TMA_Vec tma_load_alpha = make_tma_atom(SM90_TMA_LOAD{}, tensor_alpha, take<0,2>(SmemLayout{}), take<0,2>(CtaTileShapeMNK{})); typename Params::TMA_Vec tma_load_bias = make_tma_atom(SM90_TMA_LOAD{}, tensor_bias, take<0,2>(SmemLayout{}), take<0,2>(CtaTileShapeMNK{})); typename Params::TMA_Vec tma_load_mean = make_tma_atom(SM90_TMA_LOAD{}, tensor_mean, take<0,2>(SmemLayout{}), take<0,2>(CtaTileShapeMNK{})); typename Params::TMA_Vec tma_load_inv_stddev = make_tma_atom(SM90_TMA_LOAD{}, tensor_inv_stddev, take<0,2>(SmemLayout{}), take<0,2>(CtaTileShapeMNK{}));
return Params{tma_load_alpha, tma_load_bias, tma_load_mean, tma_load_inv_stddev}; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm100BatchNormApply() { }
CUTLASS_HOST_DEVICE Sm100BatchNormApply(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms), smem_alpha(const_cast<ElementScalar*>(shared_storage.smem_alpha.data())), smem_bias(const_cast<ElementScalar*>(shared_storage.smem_bias.data())), smem_mean(const_cast<ElementScalar*>(shared_storage.smem_mean.data())), smem_inv_stddev(const_cast<ElementScalar*>(shared_storage.smem_inv_stddev.data())), smem_col_alpha(const_cast<ElementCompute*>(shared_storage.smem_alpha.data())), smem_col_bias(const_cast<ElementCompute*>(shared_storage.smem_bias.data())) { }
Params const* params_ptr; ElementScalar* smem_alpha; ElementScalar* smem_bias; ElementScalar* smem_mean; ElementScalar* smem_inv_stddev; ElementCompute* smem_col_alpha; ElementCompute* smem_col_bias;
CUTLASS_DEVICE bool is_producer_load_needed() const { return true; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <int EpiTiles, class GTensor, class STensor> struct ProducerLoadCallbacks : EmptyProducerLoadCallbacks { CUTLASS_DEVICE ProducerLoadCallbacks(GTensor&& gAlpha, GTensor&& gBias, GTensor&& gMean, GTensor&& gInvStddev, STensor&& sAlpha, STensor&& sBias, STensor&& sMean, STensor&& sInvStddev, Params const* params_ptr) : gAlpha(cute::forward<GTensor>(gAlpha)), gBias(cute::forward<GTensor>(gBias)), gMean(cute::forward<GTensor>(gMean)), gInvStddev(cute::forward<GTensor>(gInvStddev)), sAlpha(cute::forward<STensor>(sAlpha)), sBias(cute::forward<STensor>(sBias)), sMean(cute::forward<STensor>(sMean)), sInvStddev(cute::forward<STensor>(sInvStddev)), params_ptr(params_ptr) {}
GTensor gAlpha; GTensor gBias; GTensor gMean; GTensor gInvStddev;
STensor sAlpha; STensor sBias; STensor sMean; STensor sInvStddev;
Params const* params_ptr;
CUTLASS_DEVICE void step(uint64_t* full_mbarrier_ptr, int epi_m, int epi_n, int load_iteration, bool issue_tma_load) { if (epi_m == 0 && epi_n == 0 && issue_tma_load) { // Increment the expect-tx count of the first subtile's mbarrier by the row vector's byte-size constexpr uint32_t copy_bytes = size<1>(CtaTileShapeMNK{}) * bits_to_bytes(sizeof_bits_v<ElementScalar>) * 4; cutlass::arch::ClusterTransactionBarrier::expect_transaction(full_mbarrier_ptr, copy_bytes); // Issue the TMA bulk copy int pipe_index = (load_iteration / EpiTiles) % Stages; copy(params_ptr->tma_load_alpha.with(*full_mbarrier_ptr), gAlpha, sAlpha(_,pipe_index)); copy(params_ptr->tma_load_bias.with(*full_mbarrier_ptr), gBias, sBias(_,pipe_index)); copy(params_ptr->tma_load_mean.with(*full_mbarrier_ptr), gMean, sMean(_,pipe_index)); copy(params_ptr->tma_load_inv_stddev.with(*full_mbarrier_ptr), gInvStddev, sInvStddev(_,pipe_index)); } } };
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl;
Tensor mAlpha = params_ptr->tma_load_alpha.get_tma_tensor(make_shape(size(M),N,size(L))); Tensor mBias = params_ptr->tma_load_bias.get_tma_tensor(make_shape(size(M),N,size(L))); Tensor mMean = params_ptr->tma_load_mean.get_tma_tensor(make_shape(size(M),N,size(L))); Tensor mInvStddev = params_ptr->tma_load_inv_stddev.get_tma_tensor(make_shape(size(M),N,size(L)));
Tensor gAlpha = local_tile(mAlpha, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N) Tensor gBias = local_tile(mBias, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N) Tensor gMean = local_tile(mMean, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N) Tensor gInvStddev = local_tile(mInvStddev, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N)
Tensor sAlpha = make_tensor(make_smem_ptr(smem_alpha), SmemLayout{}); // (CTA_M,CTA_N,PIPE) Tensor sBias = make_tensor(make_smem_ptr(smem_bias), SmemLayout{}); // (CTA_M,CTA_N,PIPE) Tensor sMean = make_tensor(make_smem_ptr(smem_mean), SmemLayout{}); // (CTA_M,CTA_N,PIPE) Tensor sInvStddev = make_tensor(make_smem_ptr(smem_inv_stddev), SmemLayout{}); // (CTA_M,CTA_N,PIPE)
auto [tCgAlpha, tCsAlpha] = tma_partition(params_ptr->tma_load_alpha, group_modes<0,2>(sAlpha), group_modes<0,2>(gAlpha)); auto [tCgBias, tCsBias] = tma_partition(params_ptr->tma_load_bias, group_modes<0,2>(sBias), group_modes<0,2>(gBias)); auto [tCgMean, tCsMean] = tma_partition(params_ptr->tma_load_mean, group_modes<0,2>(sMean), group_modes<0,2>(gMean)); auto [tCgInvStddev, tCsInvStddev] = tma_partition(params_ptr->tma_load_inv_stddev, group_modes<0,2>(sInvStddev), group_modes<0,2>(gInvStddev));
constexpr int EpiTiles = decltype(size(ceil_div(shape(take<0,2>(args.tile_shape_mnk)), args.epi_tile)))::value; return ProducerLoadCallbacks<EpiTiles, decltype(tCgAlpha), decltype(tCsAlpha)>( cute::move(tCgAlpha), cute::move(tCgBias), cute::move(tCgMean), cute::move(tCgInvStddev), cute::move(tCsAlpha), cute::move(tCsBias), cute::move(tCsMean), cute::move(tCsInvStddev), params_ptr); }
template <int EpiTiles, class SR_RTensor, class SR_STensor, class SR_CTensor, class SR_SCTensor, class RTensor, class STensor, class ThrNum> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( SR_RTensor&& tSR_rAlpha, SR_RTensor&& tSR_rBias, SR_RTensor&& tSR_rMean, SR_RTensor&& tSR_rInvStddev, SR_STensor&& tSR_sAlpha, SR_STensor&& tSR_sBias, SR_STensor&& tSR_sMean, SR_STensor&& tSR_sInvStddev, SR_CTensor&& tSR_cAlpha, SR_SCTensor&& tSR_sColAlpha, SR_SCTensor&& tSR_sColBias, RTensor&& tCrAlpha, RTensor&& tCrBias, STensor&& tCsAlpha, STensor&& tCsBias, ThrNum thr_num, Params const* params_ptr) : tSR_rAlpha(cute::forward<SR_RTensor>(tSR_rAlpha)), tSR_rBias(cute::forward<SR_RTensor>(tSR_rBias)), tSR_rMean(cute::forward<SR_RTensor>(tSR_rMean)), tSR_rInvStddev(cute::forward<SR_RTensor>(tSR_rInvStddev)), tSR_sAlpha(cute::forward<SR_STensor>(tSR_sAlpha)), tSR_sBias(cute::forward<SR_STensor>(tSR_sBias)), tSR_sMean(cute::forward<SR_STensor>(tSR_sMean)), tSR_sInvStddev(cute::forward<SR_STensor>(tSR_sInvStddev)), tSR_cAlpha(cute::forward<SR_CTensor>(tSR_cAlpha)), tSR_sColAlpha(cute::forward<SR_SCTensor>(tSR_sColAlpha)), tSR_sColBias(cute::forward<SR_SCTensor>(tSR_sColBias)), tCrAlpha(cute::forward<RTensor>(tCrAlpha)), tCrBias(cute::forward<RTensor>(tCrBias)), tCsAlpha(cute::forward<STensor>(tCsAlpha)), tCsBias(cute::forward<STensor>(tCsBias)), thr_num(thr_num), params_ptr(params_ptr) {}
SR_RTensor tSR_rAlpha; SR_RTensor tSR_rBias; SR_RTensor tSR_rMean; SR_RTensor tSR_rInvStddev; SR_STensor tSR_sAlpha; SR_STensor tSR_sBias; SR_STensor tSR_sMean; SR_STensor tSR_sInvStddev; SR_CTensor tSR_cAlpha; SR_SCTensor tSR_sColAlpha; SR_SCTensor tSR_sColBias;
ThrNum thr_num;
RTensor tCrAlpha; // (CPY,CPY_M,CPY_N) RTensor tCrBias; // (CPY,CPY_M,CPY_N)
STensor tCsAlpha; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,PIPE) STensor tCsBias; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,PIPE)
Params const* params_ptr;
CUTLASS_DEVICE void previsit(int epi_m, int epi_n, int load_iteration, bool is_producer_load_needed) { if (epi_m == 0 && epi_n == 0) { // Assumes M-major subtile loop // Filter so we don't issue redundant copies over stride-0 modes // (only works if 0-strides are in same location, which is by construction) auto synchronize = [&] () { cutlass::arch::NamedBarrier::sync(thr_num, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); }; int pipe_index = (load_iteration / EpiTiles) % Stages;
Tensor tSR_rAlpha_flt = filter_zeros(tSR_rAlpha); Tensor tSR_rBias_flt = filter_zeros(tSR_rBias); Tensor tSR_rMean_flt = filter_zeros(tSR_rMean); Tensor tSR_rInvStddev_flt = filter_zeros(tSR_rInvStddev); Tensor tSR_sAlpha_flt = filter_zeros(tSR_sAlpha(_,_,_,pipe_index)); Tensor tSR_sBias_flt = filter_zeros(tSR_sBias(_,_,_,pipe_index)); Tensor tSR_sMean_flt = filter_zeros(tSR_sMean(_,_,_,pipe_index)); Tensor tSR_sInvStddev_flt = filter_zeros(tSR_sInvStddev(_,_,_,pipe_index)); Tensor tSR_cAlpha_flt = filter_zeros(tSR_cAlpha, tSR_rAlpha.stride());
for (int i = 0; i < size(tSR_rAlpha_flt); ++i) { if (get<1>(tSR_cAlpha_flt(i)) >= size<1>(CtaTileShapeMNK{})) { // OOB of SMEM continue; } tSR_rAlpha_flt(i) = tSR_sAlpha_flt(i); tSR_rBias_flt(i) = tSR_sBias_flt(i); tSR_rMean_flt(i) = tSR_sMean_flt(i); tSR_rInvStddev_flt(i) = tSR_sInvStddev_flt(i); }
constexpr int RegFragSize = cute::min(size(tSR_rAlpha_flt), cute::max(1, static_cast<int>(sizeof(uint32_t) / sizeof(ElementCompute)))); Tensor tSR_rAlpha_frg = recast<Array<ElementCompute, RegFragSize>>(tSR_rAlpha_flt); // (FRG_V) Tensor tSR_rBias_frg = recast<Array<ElementCompute, RegFragSize>>(tSR_rBias_flt); // (FRG_V) Tensor tSR_rMean_frg = recast<Array<ElementCompute, RegFragSize>>(tSR_rMean_flt); // (FRG_V) Tensor tSR_rInvStddev_frg = recast<Array<ElementCompute, RegFragSize>>(tSR_rInvStddev_flt); // (FRG_V)
cutlass::multiplies<Array<ElementCompute, RegFragSize>> mul; cutlass::negate<Array<ElementCompute, RegFragSize>> negate; cutlass::multiply_add<Array<ElementCompute, RegFragSize>> mul_add;
// We do computation among vectors before computation among matrices // alpha' = alpha * inv_stddev // bias' = bias - alpha' * mean CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tSR_rAlpha_frg); ++i) { tSR_rAlpha_frg(i) = mul(tSR_rAlpha_frg(i), tSR_rInvStddev_frg(i)); tSR_rBias_frg(i) = mul_add(tSR_rAlpha_frg(i), negate(tSR_rMean_frg(i)), tSR_rBias_frg(i)); }
Tensor tSR_sColAlpha_flt = filter_zeros(tSR_sColAlpha(_,_,_,pipe_index)); Tensor tSR_sColBias_flt = filter_zeros(tSR_sColBias(_,_,_,pipe_index)); // After computation, 4 vectors -> 2 vectors for (int i = 0; i < size(tSR_rAlpha_flt); ++i) { if (get<1>(tSR_cAlpha_flt(i)) >= size<1>(CtaTileShapeMNK{})) { // OOB of SMEM continue; } tSR_sColAlpha_flt(i) = tSR_rAlpha_flt(i); tSR_sColBias_flt(i) = tSR_rBias_flt(i); }
synchronize();
// To do bn_apply with Acc, reload these 2 vectors with the consistent shape copy_aligned(tCsAlpha(_,_,_,_,_,pipe_index), tCrAlpha); copy_aligned(tCsBias(_,_,_,_,_,pipe_index), tCrBias); } }
template <typename ElementAccumulator, typename ElementInput, int FragmentSize> CUTLASS_DEVICE Array<ElementOutput, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_inputs) { constexpr int RegFragSize = cute::max(1, static_cast<int>(sizeof(uint32_t) / sizeof(ElementCompute))); cutlass::multiply_add<Array<ElementCompute, RegFragSize>> mul_add;
Array<ElementCompute, FragmentSize> frg_apply;
using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; using ConvertOutput = NumericArrayConverter<ElementOutput, ElementCompute, FragmentSize, RoundStyle>;
ConvertInput convert_input{}; ConvertOutput convert_output{};
Array frg_I = convert_input(frg_inputs);
Tensor tCrAlpha_frg = recast<Array<ElementCompute, RegFragSize>>(tCrAlpha(_,_,_,epi_m,epi_n)); Tensor tCrBias_frg = recast<Array<ElementCompute, RegFragSize>>(tCrBias(_,_,_,epi_m,epi_n));
constexpr int RegFragArraySize = FragmentSize / RegFragSize; using RegFragArr = Array<Array<ElementCompute, RegFragSize>, RegFragArraySize>; RegFragArr& frg_I_ = reinterpret_cast<RegFragArr&>(frg_I); RegFragArr& frg_apply_ = reinterpret_cast<RegFragArr&>(frg_apply);
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < RegFragArraySize; ++i) { frg_apply_[i] = mul_add(tCrAlpha_frg(epi_v * RegFragArraySize + i), frg_I_[i], tCrBias_frg(epi_v * RegFragArraySize + i)); }
return convert_output(frg_apply); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { using ThreadCount = decltype(size(args.tiled_copy));
Tensor sAlpha = make_tensor(make_smem_ptr(smem_alpha), // (CTA_M,CTA_N,PIPE) make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{}))); Tensor sBias = make_tensor(make_smem_ptr(smem_bias), // (CTA_M,CTA_N,PIPE) make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{}))); Tensor sColAlpha = make_tensor(make_smem_ptr(smem_col_alpha), // (CTA_M,CTA_N,PIPE) make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{}))); Tensor sColBias = make_tensor(make_smem_ptr(smem_col_bias), // (CTA_M,CTA_N,PIPE) make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{}))); Tensor sMean = make_tensor(make_smem_ptr(smem_mean), // (CTA_M,CTA_N,PIPE) make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{}))); Tensor sInvStddev = make_tensor(make_smem_ptr(smem_inv_stddev), // (CTA_M,CTA_N,PIPE) make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}), Stages), make_stride(_0{},_1{},size<1>(CtaTileShapeMNK{})));
// S2R: Smem to Reg auto tiled_s2r = make_tiled_copy(Copy_Atom<DefaultCopy, ElementScalar>{}, Layout< Shape<_1, ThreadCount>, Stride<_0, _1>>{}, Layout<_1>{}); auto thr_s2r = tiled_s2r.get_slice(args.thread_idx); Tensor tSR_sAlpha = thr_s2r.partition_S(sAlpha); Tensor tSR_sBias = thr_s2r.partition_S(sBias); Tensor tSR_sMean = thr_s2r.partition_S(sMean); Tensor tSR_sInvStddev = thr_s2r.partition_S(sInvStddev); Tensor tSR_sColAlpha = thr_s2r.partition_S(sColAlpha); Tensor tSR_sColBias = thr_s2r.partition_S(sColBias); Tensor tSR_cAlpha = thr_s2r.partition_S(args.cD);
Tensor tSR_rAlpha = make_tensor_like<ElementCompute>(take<0,3>(tSR_sAlpha)); // need to check Tensor tSR_rBias = make_tensor_like<ElementCompute>(take<0,3>(tSR_sBias)); Tensor tSR_rMean = make_tensor_like<ElementCompute>(take<0,3>(tSR_sMean)); Tensor tSR_rInvStddev = make_tensor_like<ElementCompute>(take<0,3>(tSR_sInvStddev));
Tensor tCsAlpha = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,PIPE) sColAlpha, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCsBias = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,PIPE) sColBias, args.epi_tile, args.tiled_copy, args.thread_idx);
Tensor tCrAlpha = make_tensor_like<ElementCompute>(take<0,5>(tCsAlpha)); // (CPY,CPY_M,CPY_N) Tensor tCrBias = make_tensor_like<ElementCompute>(take<0,5>(tCsBias)); // (CPY,CPY_M,CPY_N)
constexpr int EpiTiles = decltype(size<1>(zipped_divide(make_layout(take<0,2>(args.tile_shape_mnk)), args.epi_tile)))::value; return ConsumerStoreCallbacks<EpiTiles , decltype(tSR_rAlpha), decltype(tSR_sAlpha), decltype(tSR_cAlpha), decltype(tSR_sColAlpha), decltype(tCrAlpha), decltype(tCsAlpha), ThreadCount >( cute::move(tSR_rAlpha), cute::move(tSR_rBias), cute::move(tSR_rMean), cute::move(tSR_rInvStddev), cute::move(tSR_sAlpha), cute::move(tSR_sBias), cute::move(tSR_sMean), cute::move(tSR_sInvStddev), cute::move(tSR_cAlpha), cute::move(tSR_sColAlpha), cute::move(tSR_sColBias), cute::move(tCrAlpha), cute::move(tCrBias), cute::move(tCsAlpha), cute::move(tCsBias), ThreadCount{}, params_ptr); }};
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree store operations for the sm100 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/detail/sm100_blockscaled_layout.hpp" #include "cute/tensor.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp"#include "cutlass/detail/helper_macros.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
namespace detail { template <int SFVecSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int FragmentSize, int NumVecs> CUTLASS_DEVICE auto compute_quantized_with_row_scalefactor( Array<ElementCompute, FragmentSize>& frg_compute, Array<ElementBlockScaleFactor, NumVecs>& frg_sf, ElementCompute norm_constant) { cutlass::multiplies<ElementCompute> mul; cutlass::multiplies<Array<ElementCompute, SFVecSize>> mul_array;
Array<ElementOutput, FragmentSize> frg_output; auto output_frgs = reinterpret_cast<Array<ElementOutput, SFVecSize> *>(frg_output.data()); auto compute_frgs = reinterpret_cast<Array< ElementCompute, SFVecSize> *>(frg_compute.data());
Array<ElementCompute, NumVecs> qpvscale_rcps = [&]() CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (cute::is_same_v<ElementBlockScaleFactor, float_ue8m0_t>) { // UE8M0: Use integer subtraction to do the fast rcp in ue8m0 and then convert to float. auto e8m0_qpvscale_rcp = cutlass::reciprocal_approximate<Array<ElementBlockScaleFactor, NumVecs>>{}(frg_sf); return cutlass::NumericArrayConverter<ElementCompute, ElementBlockScaleFactor, NumVecs>{}(e8m0_qpvscale_rcp); } else { // UE4M3: Do the rcp in fp32 data type. auto qpvscale_ups = cutlass::NumericArrayConverter<ElementCompute, ElementBlockScaleFactor, NumVecs>{}(frg_sf); return cutlass::reciprocal_approximate_ftz<decltype(qpvscale_ups)>{}(qpvscale_ups); } }();
// norm_constant and qpvscale_rcps are all positive numbers. auto acc_scales = cutlass::multiplies<Array<ElementCompute, NumVecs>>{}(norm_constant, qpvscale_rcps);
CUTLASS_PRAGMA_UNROLL for (int sf_v = 0; sf_v < NumVecs; ++sf_v) { // Map INF to fp32::max auto acc_scale = minimum_with_nan_propagation<ElementCompute>{}(acc_scales[sf_v], cutlass::platform::numeric_limits<ElementCompute>::max()); // Convert to output type output_frgs[sf_v] = cutlass::NumericArrayConverter<ElementOutput, ElementCompute, SFVecSize>{}(mul_array(compute_frgs[sf_v], acc_scale)); } return frg_output; }}/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// BlockScaleFactor Generation Operations///////////////////////////////////////////////////////////////////////////////////////////////////
template < int SFVecSize, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>struct Sm100BlockScaleFactorRowStore { static_assert(size<1>(EpilogueTile{}) % SFVecSize == 0, "EpilogueTileN should be divisible by SFVecSize"); static_assert(size<1>(EpilogueTile{}) / SFVecSize == 1 or size<1>(EpilogueTile{}) / SFVecSize == 2 or size<1>(EpilogueTile{}) / SFVecSize == 4 or size<1>(EpilogueTile{}) / SFVecSize == 8, "Possible store in interleaved 4B aligned format"); using NormalConstStrideMNL = Stride<_0,_0,int64_t>; struct SharedStorage { };
struct Arguments { ElementBlockScaleFactor* ptr_scale_factor = nullptr; ElementCompute const* norm_constant_ptr = nullptr; NormalConstStrideMNL norm_constant_stride = {}; };
using Params = Arguments;
using UnderlyingElementBlockScaleFactor = cute::remove_pointer_t<ElementBlockScaleFactor>;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; bool implementable = (N % SFVecSize == 0); if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: [EVT Sm100BlockScaleFactorRowStore] N-dim should be divisible by SFVecSize.\n"); } return implementable; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm100BlockScaleFactorRowStore() { }
CUTLASS_HOST_DEVICE Sm100BlockScaleFactorRowStore(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) { }
Params const* params_ptr = nullptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template < class RTensor, class GTensor, class CoordGTensor, class ThrResidue, class EpiTileCoordMN, class ElementType > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( RTensor&& tC_rSFD_, // (CPY,CPY_M,CPY_N) GTensor&& tC_gSFD_, // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,#EPI_Ms, #EPI_Ns) CoordGTensor tC_cSFD_, // (m,n) ThrResidue residue_tC_cSFD_, // (m,n) Params const* params_ptr_, EpiTileCoordMN epi_tile_coord_mn_, // (epi_tile_coord_m, epi_tile_coord_n) ElementType norm_constant_, ElementType norm_constant_scaled_down_) : tC_rSFD(cute::forward<RTensor>(tC_rSFD_)) , tC_gSFD(cute::forward<GTensor>(tC_gSFD_)) , tC_cSFD(tC_cSFD_) , residue_tC_cSFD(residue_tC_cSFD_) , params_ptr(params_ptr_) , norm_constant(norm_constant_) , norm_constant_scaled_down(norm_constant_scaled_down_) , epi_tile_coord_mn(epi_tile_coord_mn_){}
static_assert(is_same_v<ElementType, ElementCompute>); RTensor tC_rSFD; GTensor tC_gSFD; CoordGTensor tC_cSFD; ThrResidue residue_tC_cSFD; Params const* params_ptr; ElementCompute norm_constant; ElementCompute norm_constant_scaled_down; EpiTileCoordMN epi_tile_coord_mn;
template <class ElementAccumulator, class ElementInput, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { static_assert(FragmentSize % SFVecSize == 0, "Scale factor vector size should divide FragmentSize"); constexpr int NumVecs = FragmentSize / SFVecSize; Array<ElementCompute, FragmentSize> frg_compute;
auto input_frgs = reinterpret_cast<Array< ElementInput, SFVecSize> const*>(frg_input.data()); auto compute_frgs = reinterpret_cast<Array< ElementCompute, SFVecSize> *>(frg_compute.data());
Tensor tC_rSFD_frg = recast<cutlass::Array<UnderlyingElementBlockScaleFactor, NumVecs>>(coalesce(filter(tC_rSFD))); // (EPI_V)
cutlass::multiplies<ElementCompute> mul; cutlass::maximum_absolute_value_reduction<Array<ElementCompute, SFVecSize>, true> amax_reduction;
cutlass::Array<ElementCompute, NumVecs> vec_maxs; cutlass::Array<ElementCompute, NumVecs> pvscales; // SF generation CUTLASS_PRAGMA_UNROLL for (int sf_v = 0; sf_v < NumVecs; ++sf_v) { compute_frgs[sf_v] = NumericArrayConverter<ElementCompute, ElementInput, SFVecSize>{}(input_frgs[sf_v]); /// Step1: get max across a vector vec_maxs[sf_v] = amax_reduction(ElementCompute(0), compute_frgs[sf_v]); }
/// Step2: Compute Scale pvscales = cutlass::multiplies<Array<ElementCompute, NumVecs>>{}(vec_maxs, norm_constant_scaled_down);
tC_rSFD_frg(_0{}) = cutlass::NumericArrayConverter<UnderlyingElementBlockScaleFactor, ElementCompute, NumVecs>{}(pvscales);
Tensor tCgSFD_flt = filter_zeros(tC_gSFD(_,_,_,_0{},_0{},get<0>(epi_tile_coord_mn) + epi_m, get<1>(epi_tile_coord_mn) + epi_n)); Tensor tCrSFD_flt = filter_zeros(tC_rSFD); constexpr auto MCL = decltype(max_common_layout(tCgSFD_flt, tCrSFD_flt)){}; constexpr int V = cute::min(4, size(MCL)); using VecType = uint_bit_t<V * sizeof_bits_v<UnderlyingElementBlockScaleFactor>>; Tensor tCgSFD_vec = recast<VecType>(coalesce(tCgSFD_flt)); Tensor tCrSFD_vec = recast<VecType>(coalesce(tCrSFD_flt)); Tensor tCcSFD_pred = tC_cSFD(_,_,_, epi_m, epi_n); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrSFD_vec); i++){ if (elem_less(tCcSFD_pred(i * SFVecSize * V), residue_tC_cSFD)) { tCgSFD_vec(i) = tCrSFD_vec(i); } } /// Step3: Compute quantized output values return detail::compute_quantized_with_row_scalefactor<SFVecSize, ElementOutput>(frg_compute, tC_rSFD_frg(_0{}), norm_constant); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [tile_coord_m, tile_coord_n, tile_coord_k, tile_coord_l] = args.tile_coord_mnkl; using Sm1xxBlockScaledOutputConfig= cutlass::detail::Sm1xxBlockScaledOutputConfig<SFVecSize>; UnderlyingElementBlockScaleFactor* ptr_scale_factor = nullptr; // If Ptr-Array/Grouped GEMM with BlockScaleFactor per batch/group if constexpr (!cute::is_same_v<UnderlyingElementBlockScaleFactor, ElementBlockScaleFactor>) { ptr_scale_factor = params_ptr->ptr_scale_factor[tile_coord_l]; tile_coord_l = 0; } else { ptr_scale_factor = params_ptr->ptr_scale_factor; }
auto epi_tile_mn = shape<1>(zipped_divide(make_layout(take<0,2>(args.tile_shape_mnk)), args.epi_tile)); Tensor mSFD = make_tensor(make_gmem_ptr(ptr_scale_factor), Sm1xxBlockScaledOutputConfig::tile_atom_to_shape_SFD(args.problem_shape_mnkl)); static_assert(size<1>(EpilogueTile{}) && ((size<1>(EpilogueTile{}) & (size<1>(EpilogueTile{}) - 1)) == 0), "Epilogue Tile N should be pow of 2"); Tensor gSFD = local_tile(mSFD, args.epi_tile, make_coord(_,_,tile_coord_l)); // (EPI_M,EPI_N, #EPI_Ms, #EPI_Ns) Tensor tCgSFD = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,#EPI_Ms, #EPI_Ns) gSFD, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrSFD = make_tensor_like<UnderlyingElementBlockScaleFactor>(take<0,3>(cute::layout(tCgSFD))); // (CPY,CPY_M,CPY_N)
auto epi_tile_coord_mn = make_coord(tile_coord_m * size<0>(epi_tile_mn), tile_coord_n * size<1>(epi_tile_mn));
// Fetch and compute these during initialization Tensor mNormConst= make_tensor(make_gmem_ptr(params_ptr->norm_constant_ptr), make_layout(make_shape(M, N, L), params_ptr->norm_constant_stride)); ElementCompute norm_constant = mNormConst(_0{},_0{},tile_coord_l); ElementCompute fp_max = ElementCompute(cutlass::platform::numeric_limits<ElementOutput>::max()); ElementCompute scale_down_factor = cutlass::reciprocal_approximate_ftz<ElementCompute>{}(fp_max); ElementCompute norm_constant_scaled_down = cutlass::multiplies<ElementCompute>{}(norm_constant, scale_down_factor);#if 0 if(threadIdx.x == 128 && blockIdx.x == 0 && blockIdx.y == 0){ print("epi_tile ");print(args.epi_tile); print("\n"); print("mSFD ");print(mSFD); print("\n"); print("gSFD ");print(gSFD); print("\n"); print("tCgSFD ");print(tCgSFD); print("\n"); print("tCrSFD ");print(tCrSFD); print("\n"); print("filter(tCrSFD) ");print(filter(tCrSFD)); print("\n"); print("filter(tCgSFD) ");print(filter(tCgSFD)); print("\n"); }#endif
return ConsumerStoreCallbacks( cute::move(tCrSFD), cute::move(tCgSFD), args.tCcD, args.residue_tCcD, params_ptr, epi_tile_coord_mn, norm_constant, norm_constant_scaled_down);
}};
template < int SFVecSize, class EpilogueTile, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>struct Sm100BlockScaleFactorColStore {
static_assert(size<0>(EpilogueTile{}) % SFVecSize == 0, "EpilogueTileN should be divisible by SFVecSize"); static_assert(size<0>(EpilogueTile{}) / SFVecSize == 1 or size<0>(EpilogueTile{}) / SFVecSize == 2 or size<0>(EpilogueTile{}) / SFVecSize == 4 or size<0>(EpilogueTile{}) / SFVecSize == 8, "Possible store in interleaved 4B aligned format"); using NormalConstStrideMNL = Stride<_0,_0,int64_t>; static constexpr int NumSyncWarps = SFVecSize == 64 ? 4 : 0; static constexpr int NumSyncThreads = NumSyncWarps * NumThreadsPerWarp; struct SharedStorage { array_aligned<ElementCompute, NumSyncWarps> smem_aux; };
struct Arguments { ElementBlockScaleFactor* ptr_scale_factor = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. ElementCompute const* norm_constant_ptr = nullptr; NormalConstStrideMNL norm_constant_stride = {}; };
using Params = Arguments;
// BlockScaleFactor generation is per batch or group // For Ptr-Array GEMM and Grouped GEMM, ElementBlockScaleFactor is ElementType* using UnderlyingElementBlockScaleFactor = cute::remove_pointer_t<ElementBlockScaleFactor>;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; bool implementable = (M % SFVecSize == 0); if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: [EVT Sm100BlockScaleFactorColStore] M-dim should be divisible by SFVecSize.\n"); } return implementable; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm100BlockScaleFactorColStore() { }
CUTLASS_HOST_DEVICE Sm100BlockScaleFactorColStore(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) , smem_aux(const_cast<ElementCompute*>(shared_storage.smem_aux.data())) { }
Params const* params_ptr = nullptr; ElementCompute *smem_aux = nullptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template < class RTensor, class GTensor, class STensor, class CoordGTensor, class ThrResidue, class EpiTileCoordMN, class ElementType > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { // Normally, we should use tile_shape_mnk to tile the gtensor. // However, the SF gtensor could not be divisible by non-pow2 cta tile, so we use epi tile (pow2) to do tiling. CUTLASS_DEVICE ConsumerStoreCallbacks( RTensor&& tC_rSFD_, // (CPY,CPY_M,CPY_N) GTensor&& tC_gSFD_, // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,#EPI_Ms, #EPI_Ns) STensor&& sAmaxs_, // (NumSyncWarps) CoordGTensor tC_cSFD_, // (m,n) ThrResidue residue_tC_cSFD_, // (m,n) Params const* params_ptr_, EpiTileCoordMN epi_tile_coord_mn_, // (epi_tile_coord_m, epi_tile_coord_n) ElementType norm_constant_, ElementType norm_constant_scaled_down_) : tC_rSFD(cute::forward<RTensor>(tC_rSFD_)) , tC_gSFD(cute::forward<GTensor>(tC_gSFD_)) , sAmaxs(cute::forward<STensor>(sAmaxs_)) , tC_cSFD(tC_cSFD_) , residue_tC_cSFD(residue_tC_cSFD_) , params_ptr(params_ptr_) , norm_constant(norm_constant_) , norm_constant_scaled_down(norm_constant_scaled_down_) , epi_tile_coord_mn(epi_tile_coord_mn_) {}
static_assert(is_same_v<ElementType, ElementCompute>); RTensor tC_rSFD; GTensor tC_gSFD; STensor sAmaxs; CoordGTensor tC_cSFD; ThrResidue residue_tC_cSFD; Params const* params_ptr; ElementCompute norm_constant; ElementCompute norm_constant_scaled_down; EpiTileCoordMN epi_tile_coord_mn;
CUTLASS_DEVICE ElementCompute find_amax(ElementCompute max) { // Overall idea: after TMEM_LOAD.32DP32bit pattern, each thread in the warp can load adjacent elements of a column into its private RF. // Here we are using shuffle instructons to the amax value of the adjacent column elements. // For VS16, t0~t15 would generate an amax, and t16~t31 would generate another one. // For VS32, t0~t31 should generate an amax. // For VS64, t0~t63 should generate an amax. We would first do the reduciton within a warp, // and then use smem to do inter-warp reduction. if constexpr (SFVecSize == 32) { return cutlass::redux_abs_max_nan_propagation_sync_warp<ElementCompute>{}(max); } else if constexpr (SFVecSize == 16) { return cutlass::redux_abs_max_nan_propagation_sync_warp_t0t15_t16t31<ElementCompute>{}(max); } else if constexpr (SFVecSize == 64) { // Get abs_max per warp auto abs_max = cutlass::redux_abs_max_nan_propagation_sync_warp<ElementCompute>{}(max);
// Switch the amax of adjacent warps const bool leading_thread = (threadIdx.x % NumThreadsPerWarp) == 0; const int warp_idx = threadIdx.x / NumThreadsPerWarp % 4; auto synchronize = [] () CUTLASS_LAMBDA_FUNC_INLINE { cutlass::arch::NamedBarrier::sync(NumSyncThreads, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); }; // Inter-warp reduction for VS=64 // Only 4 * FP32 = 16 bytes smem is needed as we have 4 warps. if (leading_thread) { sAmaxs(warp_idx) = abs_max; } synchronize(); // Switch data between two adjacent warps to do reduction float tmp = sAmaxs(warp_idx^1); synchronize(); abs_max = cutlass::maximum_with_nan_propagation<ElementCompute>{}(abs_max,tmp); return abs_max; } else { static_assert(cutlass::detail::dependent_false<ElementCompute>, "Unsupported VecSize"); } }
template <int FragmentSize> CUTLASS_DEVICE auto compute_quantized_value(Array<ElementCompute, FragmentSize> compute, Array<UnderlyingElementBlockScaleFactor, FragmentSize> sf) { cutlass::multiplies<Array<ElementCompute, FragmentSize>> mul_array; auto qpvscale_rcp = [&]() CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (cute::is_same_v<UnderlyingElementBlockScaleFactor, float_ue8m0_t>) { // UE8M0: Use integer subtraction to do the fast rcp in ue8m0 and then convert to float. auto e8m0_qpvscale_rcps = cutlass::reciprocal_approximate<Array<UnderlyingElementBlockScaleFactor, FragmentSize>>{}(sf); return cutlass::NumericArrayConverter<ElementCompute, UnderlyingElementBlockScaleFactor, FragmentSize>{}(e8m0_qpvscale_rcps); } else { // UE4M3: Do the rcp in fp32 data type. auto qpvscale_up = cutlass::NumericArrayConverter<ElementCompute, UnderlyingElementBlockScaleFactor, FragmentSize>{}(sf); return cutlass::reciprocal_approximate_ftz<decltype(qpvscale_up)>{}(qpvscale_up); } }(); // norm_constant and qpvscale_rcps[sf_v] are all positive numbers. auto acc_scale = mul_array(norm_constant, qpvscale_rcp); // Map INF to fp32::max acc_scale = minimum_with_nan_propagation<decltype(acc_scale)>{}(acc_scale, cutlass::platform::numeric_limits<ElementCompute>::max()); return mul_array(compute, acc_scale); }
template <class ElementAccumulator, class ElementInput, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { constexpr int NumVecs = 1; // each thread only compute 1 col scalefactors Array<ElementCompute, FragmentSize> frg_compute; Array<ElementOutput, FragmentSize> frg_output; Array<ElementCompute, FragmentSize> frg_scale_float; Array<ElementCompute, FragmentSize> frg_amax; Array<UnderlyingElementBlockScaleFactor, FragmentSize> frg_scale;
Tensor tC_rSFD_frg = recast<cutlass::Array<UnderlyingElementBlockScaleFactor, NumVecs>>(coalesce(filter(tC_rSFD))); // (EPI_V)
cutlass::multiplies<ElementCompute> mul; cutlass::multiplies<Array<ElementCompute, FragmentSize>> mul_array; /// convert acc to Element Compute auto compute_frgs = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize>{}(frg_input);
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { /// Step1: get max across a vector frg_amax[i] = find_amax(compute_frgs[i]); } frg_scale_float = mul_array(frg_amax, norm_constant_scaled_down); frg_scale = cutlass::NumericArrayConverter<UnderlyingElementBlockScaleFactor, ElementCompute, FragmentSize>{}(frg_scale_float); auto tC_cSFD_pred = tC_cSFD(_,_,_,epi_m,epi_n); auto tC_gSFD_store = tC_gSFD(_,_,_,_,_,get<0>(epi_tile_coord_mn) + epi_m, get<1>(epi_tile_coord_mn) + epi_n); for (int i=0; i < cute::ceil_div(FragmentSize, SFVecSize); i++) { int idx = i * SFVecSize + threadIdx.x % SFVecSize; if (idx < FragmentSize && elem_less(tC_cSFD_pred(idx), residue_tC_cSFD)) { UnderlyingElementBlockScaleFactor tmp = frg_scale[idx]; // Store the (EpilogueTile / SFVecSize) elements. tC_gSFD_store(idx) = tmp; } }
/// Step3: Compute quantized output values if constexpr (cute::sizeof_bits_v<ElementOutput> == 4) { return compute_quantized_value(compute_frgs, frg_scale); // ElementCompute } else { // 6bits or 8bits output. compute_frgs = compute_quantized_value(compute_frgs, frg_scale); frg_output = cutlass::NumericArrayConverter<ElementOutput, ElementCompute, FragmentSize>{}(compute_frgs); return frg_output; // ElementOutput }
} };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [tile_coord_m, tile_coord_n, tile_coord_k, tile_coord_l] = args.tile_coord_mnkl; using Sm1xxBlockScaledOutputConfig = cutlass::detail::Sm1xxBlockScaledOutputConfig<SFVecSize, UMMA::Major::MN>; UnderlyingElementBlockScaleFactor* ptr_scale_factor = nullptr; // If Ptr-Array/Grouped GEMM with BlockScaleFactor per batch/group if constexpr (!cute::is_same_v<UnderlyingElementBlockScaleFactor, ElementBlockScaleFactor>) { ptr_scale_factor = params_ptr->ptr_scale_factor[tile_coord_l]; tile_coord_l = 0; } else { ptr_scale_factor = params_ptr->ptr_scale_factor; }
auto epi_tile_mn = shape<1>(zipped_divide(make_layout(take<0,2>(args.tile_shape_mnk)), args.epi_tile)); Tensor mSFD = make_tensor(make_gmem_ptr(ptr_scale_factor), Sm1xxBlockScaledOutputConfig::tile_atom_to_shape_SFD(args.problem_shape_mnkl)); //Tensor gSFD = local_tile(mSFD, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // Normally, we should use tile_shape_mnk to tile the mSFD tensor. However, we could not do it for non-pow2 cta tile with vectorsize = 32. // For scale factor, 128x4 elements are stored in a basic block, and the layout of mSFD is ((_32,_4,int),(_32,_4,int),int):((_16,_4,int),(_0,_1, int),int) // If we tiled it using tile_shape_mnk(128, 192), the N mode would encounter shape_div failure because (32, 4) could not be divisible by 192. // Therefore, switching to using pow2 epilogue tile. static_assert(size<1>(EpilogueTile{}) && ((size<1>(EpilogueTile{}) & (size<1>(EpilogueTile{}) - 1)) == 0), "Epilogue Tile N should be pow of 2"); Tensor gSFD = local_tile(mSFD, args.epi_tile, make_coord(_,_,tile_coord_l)); // (EPI_M,EPI_N, #EPI_Ms, #EPI_Ns) Tensor tCgSFD = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,#EPI_Ms, #EPI_Ns) gSFD, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrSFD = make_tensor_like<UnderlyingElementBlockScaleFactor>(take<0,3>(cute::layout(tCgSFD))); // (CPY,CPY_M,CPY_N)
auto epi_tile_coord_mn = make_coord(tile_coord_m * size<0>(epi_tile_mn), tile_coord_n * size<1>(epi_tile_mn));
// Fetch and compute these during initialization Tensor mNormConst= make_tensor(make_gmem_ptr(params_ptr->norm_constant_ptr), make_layout(make_shape(M, N, L), params_ptr->norm_constant_stride)); ElementCompute norm_constant = mNormConst(_0{},_0{},tile_coord_l); ElementCompute fp_max = ElementCompute(cutlass::platform::numeric_limits<ElementOutput>::max()); ElementCompute scale_down_factor = cutlass::reciprocal_approximate_ftz<ElementCompute>{}(fp_max); ElementCompute norm_constant_scaled_down = cutlass::multiplies<ElementCompute>{}(norm_constant, scale_down_factor);
Tensor sAmaxs = make_tensor(make_smem_ptr(smem_aux), make_layout(_4{}));#if 0 if(threadIdx.x == 128 && blockIdx.x == 0 && blockIdx.y == 0){ print("mSFD ");print(mSFD); print("\n"); print("gSFD ");print(gSFD); print("\n"); print("tCgSFD ");print(tCgSFD); print("\n"); print("tCrSFD ");print(tCrSFD); print("\n"); print("args.tCcD ");print(args.tCcD); print("\n"); print("args.residue_tCcD ");print(args.residue_tCcD); print("\n"); print("filter(tCrSFD) ");print(filter(tCrSFD)); print("\n"); print("filter(tCgSFD) ");print(filter(tCgSFD)); print("\n"); }#endif
return ConsumerStoreCallbacks( cute::move(tCrSFD), cute::move(tCgSFD), cute::move(sAmaxs), args.tCcD, args.residue_tCcD, params_ptr, epi_tile_coord_mn, norm_constant, norm_constant_scaled_down); }};
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593/*************************************************************************************************** * Copyright (c) 2025 - 2025 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. * **************************************************************************************************/
/*! \file \brief Fusion callbacks specializations for the SM120 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"
#include "cute/tensor.hpp"
#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/fusion/callbacks.hpp"#include "cutlass/epilogue/fusion/sm90_callbacks_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm100_callbacks_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm120_visitor_store_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Sm120 Tma warp specialized callbacks just alias to their sm90 counterparttemplate < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class Operation, class CtaTile_MNK, class EpilogueTile_MN, class... Args>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> : FusionCallbacks< epilogue::Sm90TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args... > { using FusionCallbacks< epilogue::Sm90TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...>::FusionCallbacks;};
// D = alpha * acc + beta * C// With BlockScaleFactor Generation.// 1. Find max of 32 F32 elements// 2. Convert the max to UE8 (or UE4M3) and store the result.// 3. Convert the UE8 (or UE4M3) back to F32 scale.// 4. Reciprocal of F32 scale with MUFU.// 5. Multiply each F32 element with the above reciprocal, then convert to ElementDtemplate< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinearCombRowBlockScaleFactor = Sm90EVT<Sm120BlockScaleFactorRowStore<SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput,ElementCompute, ElementBlockScaleFactor, RoundStyle>, // gen scalefactor Sm90LinearCombination<ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle> // beta * C + (alpha * acc) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute,ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile> : Sm120LinearCombRowBlockScaleFactor<SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type,ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle> {
using Impl = Sm120LinearCombRowBlockScaleFactor<SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type,ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle>;
using Sm100Fusion = FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute,ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile >; using Operation = typename Sm100Fusion::Operation;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // binary op : alpha * acc {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // binary args : multiplies }, // end binary op {} // ternary args : multiply_add }, {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } }; // Ctor inheritance using Impl::Impl;};
// D = alpha * acc + beta * C + per-row bias// with row blockScaled generationtemplate< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerRowBiasRowBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorRowStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, // gen scalefactor Sm90LinCombPerRowBias< CtaTileShapeMNK, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerRowBiasRowBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerRowBiasRowBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// D = activation(alpha * acc + beta * C + per-row bias) // with row blockScaled generationtemplate< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerRowBiasEltActRowBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorRowStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, // gen scalefactor Sm90LinCombPerRowBiasEltAct< CtaTileShapeMNK, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerRowBiasEltActRowBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerRowBiasEltActRowBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {}; using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// D = alpha * acc + beta * C + per_col bias// with row blockScaled generationtemplate< int StagesC, int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerColBiasRowBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorRowStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, // gen scalefactor Sm90LinCombPerColBias< StagesC, CtaTileShapeMNK, EpilogueTile, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerColBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerColBiasRowBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerColBiasRowBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerColBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_0,_1,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// D = activation(alpha * acc + beta * C + per_col bias) // with row blockScaled generationtemplate< int StagesC, int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerColBiasEltActRowBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorRowStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, // gen scalefactor Sm90LinCombPerColBiasEltAct< StagesC, CtaTileShapeMNK, EpilogueTile, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerColBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerColBiasEltActRowBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerColBiasEltActRowBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerColBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_0,_1,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {}; using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// D = alpha * acc + beta * C// with per column blockScaled generation// 1. Find max of 32 F32 elements// 2. Convert the max to UE8 (or UE4M3) and store the result.// 3. Convert the UE8 (or UE4M3) back to F32 scale.// 4. Reciprocal of F32 scale with MUFU.// 5. Multiply each F32 element with the above reciprocal, then convert to ElementDtemplate< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinearCombColBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorColStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle>, Sm90LinearCombination< ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle> >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized< StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute,ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile> : Sm120LinearCombColBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle > {
using Impl = Sm120LinearCombColBlockScaleFactor<SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type,ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle>;
using Sm100Fusion = FusionCallbacks< epilogue::Sm100TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombBlockScaleFactor<SFVecSize, ElementOutput, ElementCompute,ElementBlockScaleFactor, cutlass::layout::ColumnMajor,ElementSource, ElementScalar, RoundStyle>, CtaTileShapeMNK, EpilogueTile >; using Operation = typename Sm100Fusion::Operation;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // binary op : alpha * acc {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // binary args : multiplies }, // end binary op {} // ternary args : multiply_add }, {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } }; // Ctor inheritance using Impl::Impl;};
// D = alpha * acc + beta * C + per-Col bias// with per column blockScaled generationtemplate< int StagesC, int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerColBiasColBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorColStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerColBias< StagesC, CtaTileShapeMNK, EpilogueTile, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerColBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerColBiasColBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >{
using Impl = Sm120LinCombPerColBiasColBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerColBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_0,_1,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// D = activation(alpha * acc + beta * C + per_col bias)// with per column blockScaled generationtemplate< int StagesC, int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerColBiasEltActColBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorColStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerColBiasEltAct< StagesC, CtaTileShapeMNK, EpilogueTile, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerColBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerColBiasEltActColBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerColBiasEltActColBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerColBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_0,_1,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// D = activation(alpha * acc + beta * C + per-row bias)// with per column blockScaled generationtemplate< int StagesC, int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerRowBiasEltActColBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorColStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, Sm90LinCombPerRowBiasEltAct< CtaTileShapeMNK, ActivationFn, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerRowBiasEltActColBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerRowBiasEltActColBlockScaleFactor< StagesC, SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias,ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// D = alpha * acc + beta * C + per-row bias// with per column blockScaled generationtemplate< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementBias = ElementOutput, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, int AlignmentBias = 128 / sizeof_bits_v<ElementBias>, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombPerRowBiasColBlockScaleFactor = Sm90EVT< Sm120BlockScaleFactorColStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, RoundStyle >, // gen scalefactor Sm90LinCombPerRowBias< CtaTileShapeMNK, ElementCompute, ElementCompute, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementBias, class ElementSource, class ElementScalar, int AlignmentBias, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120TmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore>, fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombPerRowBiasColBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle > {
using Impl = Sm120LinCombPerRowBiasColBlockScaleFactor< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementBias, ElementSource, ElementScalar, AlignmentBias, RoundStyle >;
using Operation = fusion::LinCombPerRowBiasBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::ColumnMajor, ElementBias, ElementSource, ElementScalar,AlignmentBias, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementBlockScaleFactor * block_scale_factor_ptr = nullptr; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using StrideBias = Stride<_1,_0,int64_t>; ElementBias const* bias_ptr = nullptr; StrideBias dBias = {};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {bias_ptr, ElementBias(0), dBias}, // leaf args : bias {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// Sm120 Ptr array tma warp specialized callbacks just alias to their sm90 counterparttemplate < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, int NumEpilogueWarpGroups, class Operation, class CtaTile_MNK, class EpilogueTile_MN, class... Args>struct FusionCallbacks< epilogue::Sm120PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...> : FusionCallbacks< epilogue::Sm90PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>, Operation, CtaTile_MNK, EpilogueTile_MN, Args... > { using FusionCallbacks< epilogue::Sm90PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>, Operation, CtaTile_MNK, EpilogueTile_MN, Args...>::FusionCallbacks;};
// For Ptr-Array and Grouped GEMM// D = alpha * acc + beta * C, where alpha and beta can be vectors for each batch/group// With Row BlockScaleFactor Generation, separate tensors per batch/group.template< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinearCombRowBlockScaleFactorPtrArray = Sm90EVT< Sm120BlockScaleFactorRowStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor *, RoundStyle >, // gen scalefactor Sm90LinearCombinationPtrArray< ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle > // beta * C + (alpha * acc) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, int NumEpilogueWarpGroups, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>, fusion::LinCombBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinearCombRowBlockScaleFactorPtrArray< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle > {
using Impl = Sm120LinearCombRowBlockScaleFactorPtrArray< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle >;
using Operation = fusion::LinCombBlockScaleFactor< SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementScalar const* const* alpha_ptr_array = nullptr; ElementScalar const* const* beta_ptr_array = nullptr; ElementBlockScaleFactor ** block_scale_factor_ptr = nullptr;
// A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
operator typename Impl::Arguments() const { return { { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {beta_ptr_array}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {alpha_ptr_array}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};
// For Ptr-Array and Grouped GEMM// D = activation(alpha * acc + beta * C), where alpha and beta can be vectors for each batch/group// With Row BlockScaleFactor Generation, separate tensors per batch/group.template< int SFVecsize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, class ElementSource = ElementOutput, class ElementScalar = ElementCompute, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>using Sm120LinCombEltActRowBlockScaleFactorPtrArray = Sm90EVT< Sm120BlockScaleFactorRowStore< SFVecsize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ElementOutput, ElementCompute, ElementBlockScaleFactor *, RoundStyle >, // gen scalefactor Sm90LinCombEltActPtrArray<ActivationFn, ElementCompute, ElementCompute, ElementSource, ElementScalar, RoundStyle > // activation(beta * C + (alpha * acc)) >;
template < int StagesC, int StagesD, int FragmentSize, bool ReuseSmemC, bool DelayTmaStore, int NumEpilogueWarpGroups, template <class> class ActivationFn, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, int SFVecSize, class ElementSource, class ElementScalar, FloatRoundStyle RoundStyle, class CtaTileShapeMNK, class EpilogueTile>struct FusionCallbacks< epilogue::Sm120PtrArrayTmaWarpSpecialized<StagesC, StagesD, FragmentSize, ReuseSmemC, DelayTmaStore, NumEpilogueWarpGroups>, fusion::LinCombEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle >, CtaTileShapeMNK, EpilogueTile> : Sm120LinCombEltActRowBlockScaleFactorPtrArray< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle > {
using Impl = Sm120LinCombEltActRowBlockScaleFactorPtrArray< SFVecSize, EpilogueTile, CtaTileShapeMNK, FragmentSize, ActivationFn, typename cutlass::detail::get_unpacked_element_type<ElementOutput>::type, ElementCompute, ElementBlockScaleFactor, ElementSource, ElementScalar, RoundStyle >;
using Operation = fusion::LinCombEltActBlockScaleFactor< ActivationFn, SFVecSize, ElementOutput, ElementCompute, ElementBlockScaleFactor, cutlass::layout::RowMajor, ElementSource, ElementScalar, RoundStyle >;
struct Arguments { ElementScalar alpha = ElementScalar(1); ElementScalar beta = ElementScalar(0); ElementScalar const* alpha_ptr = nullptr; ElementScalar const* beta_ptr = nullptr; ElementScalar const* const* alpha_ptr_array = nullptr; ElementScalar const* const* beta_ptr_array = nullptr; ElementBlockScaleFactor ** block_scale_factor_ptr = nullptr;
// A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. using StrideNormConst = Stride<_0,_0,int64_t>; ElementCompute const* norm_constant_ptr = nullptr; StrideNormConst dNormConst = {_0{}, _0{}, 0};
using StrideAlpha = Stride<_0,_0,int64_t>; using StrideBeta = Stride<_0,_0,int64_t>; StrideAlpha dAlpha = {_0{}, _0{}, 0}; StrideBeta dBeta = {_0{}, _0{}, 0};
using ActivationArguments = typename Sm90Compute<ActivationFn, ElementOutput, ElementCompute, RoundStyle>::Arguments; ActivationArguments activation = ActivationArguments();
operator typename Impl::Arguments() const { return { { // unary op : activation(beta * C + (alpha * acc + bias)) { // ternary op : beta * C + (alpha * acc + bias) {{beta}, {beta_ptr}, {beta_ptr_array}, {dBeta}}, // leaf args : beta {}, // leaf args : C { // ternary op : alpha * acc + bias {{alpha}, {alpha_ptr}, {alpha_ptr_array}, {dAlpha}}, // leaf args : alpha {}, // leaf args : acc {} // ternary args : multiply_add }, // end ternary op {} // ternary args : multiply_add }, // end ternary op activation // unary args : activation }, // end unary op {block_scale_factor_ptr, norm_constant_ptr, dNormConst} // BlockScaleFactor args }; // end ternary op } };
// Ctor inheritance using Impl::Impl;};} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899/*************************************************************************************************** * Copyright (c) 2025 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree store operations for the SM120 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/detail/sm100_blockscaled_layout.hpp"#include "cute/tensor.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// BlockScaleFactor Generation Operations///////////////////////////////////////////////////////////////////////////////////////////////////
template < int SFVecSize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>struct Sm120BlockScaleFactorRowStore {
static_assert(size<1>(EpilogueTile{}) % SFVecSize == 0, "EpilogueTileN should be divisible by SFVecSize"); static_assert(size<1>(EpilogueTile{}) / SFVecSize == 1 or size<1>(EpilogueTile{}) / SFVecSize == 2 or size<1>(EpilogueTile{}) / SFVecSize == 4 or size<1>(EpilogueTile{}) / SFVecSize == 8, "Possible store in interleaved 4B aligned format");
static constexpr int NumWarpgroups = 2; static constexpr int NumSyncWarps = NumWarpsPerWarpGroup * NumWarpgroups; static constexpr int NumQuadsPerWarp = 8; static constexpr int NumSyncQuads = NumSyncWarps * NumQuadsPerWarp; struct SharedStorage { array_aligned<ElementCompute, NumSyncQuads> smem_aux; }; using NormalConstStrideMNL = Stride<_0,_0,int64_t>; struct Arguments { ElementBlockScaleFactor* ptr_scale_factor = {}; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. ElementCompute const* norm_constant_ptr = {}; NormalConstStrideMNL norm_constant_stride = {}; };
using Params = Arguments;
using UnderlyingElementBlockScaleFactor = cute::remove_pointer_t<ElementBlockScaleFactor>;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; bool implementable = (N % SFVecSize == 0); if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: [EVT Sm120BlockScaleFactorRowStore] N-dim should be divisible by SFVecSize.\n"); } return implementable; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm120BlockScaleFactorRowStore() { }
CUTLASS_HOST_DEVICE Sm120BlockScaleFactorRowStore(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) , smem_aux(const_cast<ElementCompute*>(shared_storage.smem_aux.data())) { }
Params const* params_ptr = nullptr; ElementCompute *smem_aux = nullptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template < class RTensor, class GTensor, class STensor, class CoordGTensor, class ThrResidue, class TileCoordMN, class ElementType, class TiledCopy_ > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( RTensor&& tC_rSFD_, GTensor&& tC_gSFD_, STensor&& sAmaxs_, CoordGTensor tC_cSFD_, ThrResidue residue_tC_cSFD_, Params const* params_ptr_, TileCoordMN tile_coord_mn_, ElementType norm_constant_, ElementType norm_constant_scaled_down_, int thread_idx_, TiledCopy_ const&) : tC_rSFD(cute::forward<RTensor>(tC_rSFD_)) , tC_gSFD(cute::forward<GTensor>(tC_gSFD_)) , sAmaxs(cute::forward<STensor>(sAmaxs_)) , tC_cSFD(tC_cSFD_) , residue_tC_cSFD(residue_tC_cSFD_) , params_ptr(params_ptr_) , norm_constant(norm_constant_) , norm_constant_scaled_down(norm_constant_scaled_down_) , tile_coord_mn(tile_coord_mn_) , thread_idx(thread_idx_) {}
static_assert(is_same_v<ElementType, ElementCompute>); RTensor tC_rSFD; GTensor tC_gSFD; STensor sAmaxs; CoordGTensor tC_cSFD; ThrResidue residue_tC_cSFD; Params const* params_ptr; ElementCompute norm_constant; ElementCompute norm_constant_scaled_down; TileCoordMN tile_coord_mn; int thread_idx; static constexpr int NumCollaboratingThreads = decltype(size(TiledCopy_{}))::value; static_assert(NumCollaboratingThreads % NumThreadsPerWarpGroup == 0); static constexpr int NumCollaboratingWarpGroups = NumCollaboratingThreads / NumThreadsPerWarpGroup; static_assert(NumCollaboratingWarpGroups == 1 || NumCollaboratingWarpGroups == 2, "SM120 epilogue currently only supports one or two warp groups collaborating.");
template <class ElementAccumulator, class ElementInput> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { return frg_input; }
template <class SmemTensor, class SyncFn, class VTensor> CUTLASS_DEVICE void reduce(SmemTensor&& smem_buffer, SyncFn const& sync_fn, int epi_m, int epi_n, bool is_last_iteration, VTensor visit_results) { /* Accumulator fragments are distributed across quads in different warps. For SFVector = 16, we have:
8 elements 8 elements 8 elements 8 elements <----------------><-----------------><-----------------><-----------------> Warp 0 Quad 0 Warp 0 Quad 0 Warp 4 Quad 0 Warp 4 Quad 0 Warp 0 Quad 1 Warp 0 Quad 1 Warp 4 Quad 1 Warp 4 Quad 1 ... ... ... ... Warp 0 Quad 7 Warp 0 Quad 7 Warp 4 Quad 7 Warp 4 Quad 7 Warp 0 Quad 0 Warp 0 Quad 0 Warp 4 Quad 0 Warp 4 Quad 0 Warp 0 Quad 1 Warp 0 Quad 1 Warp 4 Quad 1 Warp 4 Quad 1 ... ... ... ... Warp 0 Quad 7 Warp 0 Quad 7 Warp 4 Quad 7 Warp 4 Quad 7
<same pattern for warps 1 and 5 for the next set of 16 rows> <same pattern for warps 2 and 6 for the next set of 16 rows> <same pattern for warps 3 and 7 for the next set of 16 rows>
In this case, row-wise scale factors are cooperatively reduced across 4 threads from 1 quad in 1 warp. Each quad computes its own, local absolute maximum without communicating with other warps through shared memory.
For SFVector = 32, we have: 8 elements 8 elements 8 elements 8 elements <----------------><-----------------><-----------------><-----------------> Warp 0 Quad 0 Warp 4 Quad 0 Warp 0 Quad 0 Warp 4 Quad 0 Warp 0 Quad 1 Warp 4 Quad 1 Warp 0 Quad 1 Warp 4 Quad 1 ... ... ... ... Warp 0 Quad 7 Warp 4 Quad 7 Warp 0 Quad 7 Warp 4 Quad 7 Warp 0 Quad 0 Warp 4 Quad 0 Warp 0 Quad 0 Warp 4 Quad 0 Warp 0 Quad 1 Warp 4 Quad 1 Warp 0 Quad 1 Warp 4 Quad 1 ... ... ... ... Warp 0 Quad 7 Warp 4 Quad 7 Warp 0 Quad 7 Warp 4 Quad 7
<same pattern for warps 1 and 5 for the next set of 16 rows> <same pattern for warps 2 and 6 for the next set of 16 rows> <same pattern for warps 3 and 7 for the next set of 16 rows>
For SFVector = 64, we have: 8 elements 8 elements 8 elements 8 elements <----------------><-----------------><-----------------><-----------------> Warp 0 Quad 0 Warp 2 Quad 0 Warp 4 Quad 0 Warp 6 Quad 0 Warp 0 Quad 1 Warp 2 Quad 1 Warp 4 Quad 1 Warp 6 Quad 1 ... ... ... ... Warp 0 Quad 7 Warp 2 Quad 7 Warp 4 Quad 7 Warp 6 Quad 7 Warp 0 Quad 0 Warp 2 Quad 0 Warp 4 Quad 0 Warp 6 Quad 0 Warp 0 Quad 1 Warp 2 Quad 1 Warp 4 Quad 1 Warp 6 Quad 1 ... ... ... ... Warp 0 Quad 7 Warp 2 Quad 7 Warp 4 Quad 7 Warp 6 Quad 7
<same pattern for warps 1, 3, 5 and 7 for the next set of 16 rows>
Thus, rowwise scale factors are cooperatively reduced across 8 threads from two quads in two warps. Each quad first computes its own, local absolute maximum and then shares this with the corresponding quad in the other warp. In this case, a reduction through shared memory is needed.
For a non-cooperative epilogue (in which each warpgroup computes a separate tile), the pattern is the same as that above, except that warps 0 and 2 are in the same row, and 1 and 3 are in the same row, and warps 4-7 are not included. */
// Accumulator fragments consist of two elements from two different rows of a 16x8 MMA output static constexpr int ColsPerThreadAccFrag = 2; static constexpr int RowsPerThreadAccFrag = 2; static_assert(FragmentSize == (ColsPerThreadAccFrag * RowsPerThreadAccFrag));
static constexpr int NumThreadsPerQuad = 4; static_assert(SFVecSize == 16 || SFVecSize == 32 || SFVecSize == 64, "SF vector size must be either 16, 32 or 64."); // A quad from two or four warps participate in computing each scale factor. constexpr int WarpsPerSF = SFVecSize / 16; static_assert(WarpsPerSF == 1 || WarpsPerSF == 2 || WarpsPerSF == 4, "Only one, two or four warps are allowed in reduction.");
constexpr bool IsInterWarpReductionNeeded = (WarpsPerSF != 1);
// Number of fragments for each thread that are needed for computing a scale factor static constexpr int AccFragsPerSF = SFVecSize / (ColsPerThreadAccFrag * NumThreadsPerQuad * WarpsPerSF); static_assert(size<2>(visit_results) % AccFragsPerSF == 0, "Fragments along N mode must be a multiple of the number of accumulator fragments needed per SF");
auto warp_idx = thread_idx / NumThreadsPerWarp; auto warpgroup_idx = thread_idx / NumThreadsPerWarpGroup; auto quad_idx_in_warp = (thread_idx % NumThreadsPerWarp) / NumThreadsPerQuad; auto thread_idx_in_quad = thread_idx % NumThreadsPerQuad;
cutlass::maximum_absolute_value_reduction<ElementCompute, true> amax_op; cutlass::multiplies<ElementCompute> mul; Tensor tC_rSFD_flt = filter_zeros(tC_rSFD);
auto synchronize = [&] () { cutlass::arch::NamedBarrier::sync(NumCollaboratingThreads, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
CUTLASS_PRAGMA_UNROLL for (int sf_id = 0; sf_id < size(tC_rSFD_flt); ++sf_id) {
auto coord = idx2crd(sf_id, tC_rSFD_flt.shape()); auto row_in_acc = get<0,1,1>(coord); auto row = crd2idx(get<1>(coord), get<1>(tC_rSFD_flt.shape())); auto sf = crd2idx(get<2>(coord), get<2>(tC_rSFD_flt.shape()));
// // Compute amax for this scale factor // ElementCompute amax{0};
// Compute amax among vals owned by this thread for this vector auto acc_frag_row = row_in_acc * RowsPerThreadAccFrag; auto acc_frag_start_for_sf = sf * AccFragsPerSF; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < AccFragsPerSF; ++i) { auto acc_frg = visit_results(0, row, acc_frag_start_for_sf + i); amax = amax_op(amax, acc_frg[acc_frag_row]); amax = amax_op(amax, acc_frg[acc_frag_row + 1]); }
// At this point, each thread has computed the amax of the values that it owns for this SF vector. // We now need to compute the amax across threads. Because the TiledMMA uses an MmaThrLayout of <4,1,1>, // we know that all fragments in this row will belong to threads in this warp. Furthermore, because // SM120 narrow-precision MMAs have 16x8 output size with a quad owning two rows, we know that a quad // will own all of the elements to be reduced via amax. Therefore, we can use warp shuffle intrinsics // among threads in one quad to compute the amax. CUTLASS_PRAGMA_UNROLL for (int i = 1; i < 3; ++i) { auto amax_other = __shfl_xor_sync(0xffffffff, amax, i); amax = amax_op(amax, amax_other); }
if constexpr (IsInterWarpReductionNeeded) { // At this point, all threads in the quad have the amax for the elements of the accumulator owned by its quad // that should be used in computing the amax for this SF. Threads 0 in each quad of warps 0 and 2 // (similarly, 1 and 3) now exchange amaxes to compute the final amax. if (thread_idx_in_quad == 0) { sAmaxs(quad_idx_in_warp, warp_idx) = amax; } synchronize();
// Get the amax broadcasted by the warp with which we share. // Work on 4 warps per SFD generation if constexpr (WarpsPerSF == 4) { if constexpr (NumCollaboratingWarpGroups == 2) { // This implementation assumes warp layout 2 x 4. // For cooperative kernels (NumCollaboratingWarpGroups=2), // warp 0 shares with 2 / 4 / 6, warp 1 shares with 3 / 5/ 7. auto amax_other2 = sAmaxs(quad_idx_in_warp, warp_idx ^ 2); auto amax_other4 = sAmaxs(quad_idx_in_warp, warp_idx ^ 4); auto amax_other6 = sAmaxs(quad_idx_in_warp, warp_idx ^ 6); synchronize(); amax = amax_op(amax, amax_other2); amax = amax_op(amax, amax_other4); amax = amax_op(amax, amax_other6); } else { static_assert(cutlass::detail::dependent_false<TiledCopy_>, "Unsupported warp layout."); } } // Work on 2 warps per SFD generation else if constexpr(WarpsPerSF == 2) { // For cooperative kernels (NumCollaboratingWarpGroups=2), 0 shares // with 4, 1 shares with 5, etc. For non-cooperative kernels // (NumCollaboratingWarpGroups=1), 0 shares with 2, 1 shares with 3. auto amax_other = sAmaxs( quad_idx_in_warp, warp_idx ^ (1 << NumCollaboratingWarpGroups)); synchronize(); amax = amax_op(amax, amax_other); } }
ElementCompute pvscale = mul(amax, norm_constant_scaled_down); UnderlyingElementBlockScaleFactor qpvscale = NumericConverter<UnderlyingElementBlockScaleFactor, ElementCompute>{}(pvscale); tC_rSFD_flt(coord) = qpvscale;
// // Apply the scale factor to the output // ElementCompute qpvscale_rcp = [&]() { if constexpr (cute::is_same_v<UnderlyingElementBlockScaleFactor, float_ue8m0_t>) { // UE8M0: Use integer subtraction to do the fast rcp in ue8m0 and then convert to float. auto e8m0_qpvscale_rcp = cutlass::reciprocal_approximate<UnderlyingElementBlockScaleFactor>{}(qpvscale); return cutlass::NumericConverter<ElementCompute, UnderlyingElementBlockScaleFactor>{}(e8m0_qpvscale_rcp); } else { // UE4M3: Do the rcp in fp32 data type. auto qpvscale_up = cutlass::NumericConverter<ElementCompute, UnderlyingElementBlockScaleFactor>{}(qpvscale); return cutlass::reciprocal_approximate_ftz<decltype(qpvscale_up)>{}(qpvscale_up); } }();
ElementCompute acc_scale = mul(norm_constant, qpvscale_rcp); acc_scale = cutlass::minimum_with_nan_propagation<ElementCompute>{}(acc_scale, cutlass::platform::numeric_limits<ElementCompute>::max());
// Compute quantized output values CUTLASS_PRAGMA_UNROLL for (int i = 0; i < AccFragsPerSF; ++i) { auto acc_frag = visit_results(0, row, acc_frag_start_for_sf + i); visit_results(0, row, acc_frag_start_for_sf + i)[acc_frag_row ] = mul(acc_frag[acc_frag_row], acc_scale); visit_results(0, row, acc_frag_start_for_sf + i)[acc_frag_row + 1] = mul(acc_frag[acc_frag_row + 1], acc_scale); } } // sf
// Since scale factors are computed cooperatively across two quads from two warps, we only need one thread from the // set of 8 cooperating threads to write out the data. We do this with thread 0 in each quad of the first warp that collaborates. bool write_sf = (thread_idx_in_quad == 0); if constexpr (NumCollaboratingWarpGroups == 2) { // For cooperative kernels (NumCollaboratingWarpGroups=2), 0 shares with 4, 1 shares with 5, etc. // Thus, only the warps in the first warpgroup need to write out scale factors. if constexpr (IsInterWarpReductionNeeded) { write_sf &= warp_idx < NumWarpsPerWarpGroup; } } else { if constexpr (IsInterWarpReductionNeeded) { // When non-cooperative kernels apply inter warp reduce, they are with // SF output rule as below : // 1. warp 0 shares with 2 and 1 shares with 3 within each warpgroup. // 2. warps 0 and 1 of the first warpgroup and 4 and 5 of the second // warpgroup need to write output sf. write_sf &= ((warp_idx < 2) || (warpgroup_idx == 1 && warp_idx < 6)); } }
if (write_sf && elem_less(tC_cSFD(_0{}, _0{}, _0{}, epi_m, epi_n), residue_tC_cSFD)) { copy_aligned(tC_rSFD, tC_gSFD(_, _, _, _0{}, _0{}, get<0>(tile_coord_mn) + epi_m, get<1>(tile_coord_mn) + epi_n)); } } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; using Sm1xxBlockScaledOutputConfig = cutlass::detail::Sm1xxBlockScaledOutputConfig<SFVecSize>; UnderlyingElementBlockScaleFactor* ptr_scale_factor = nullptr; // If Ptr-Array/Grouped GEMM with BlockScaleFactor per batch/group if constexpr (!cute::is_same_v<UnderlyingElementBlockScaleFactor, ElementBlockScaleFactor>) { ptr_scale_factor = params_ptr->ptr_scale_factor[l]; l = 0; } else { ptr_scale_factor = params_ptr->ptr_scale_factor; }
auto epi_tile_mn = shape<1>(zipped_divide(make_layout(take<0,2>(args.tile_shape_mnk)), args.epi_tile)); Tensor mSFD = make_tensor(make_gmem_ptr(ptr_scale_factor), Sm1xxBlockScaledOutputConfig::tile_atom_to_shape_SFD(args.problem_shape_mnkl));
static_assert(size<1>(EpilogueTile{}) && ((size<1>(EpilogueTile{}) & (size<1>(EpilogueTile{}) - 1)) == 0), "Epilogue Tile N should be pow of 2"); Tensor gSFD = local_tile(mSFD, args.epi_tile, make_coord(_, _,l)); // (EPI_M,EPI_N, #EPI_Ms, #EPI_Ns) Tensor tCgSFD = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,#EPI_Ms, #EPI_Ns) gSFD, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrSFD = make_tensor_like<UnderlyingElementBlockScaleFactor>(take<0,3>(cute::layout(tCgSFD))); // (CPY,CPY_M,CPY_N)
auto tile_coord_mn = make_coord(m * size<0>(epi_tile_mn), n * size<1>(epi_tile_mn));
// Fetch and compute these during initialization Tensor mNormConst= make_tensor(make_gmem_ptr(params_ptr->norm_constant_ptr), make_layout(make_shape(M, N, L), params_ptr->norm_constant_stride)); ElementCompute norm_constant = mNormConst(_0{},_0{},l); ElementCompute fp_max = ElementCompute(cutlass::platform::numeric_limits<ElementOutput>::max()); ElementCompute scale_down_factor = cutlass::reciprocal_approximate_ftz<ElementCompute>{}(fp_max); ElementCompute norm_constant_scaled_down = cutlass::multiplies<ElementCompute>{}(norm_constant, scale_down_factor);
Tensor sAmaxs = make_tensor( make_smem_ptr(smem_aux), make_layout(make_shape(Int<NumQuadsPerWarp>{}, Int<NumSyncWarps>{})) );
return ConsumerStoreCallbacks( cute::move(tCrSFD), cute::move(tCgSFD), cute::move(sAmaxs), args.tCcD, args.residue_tCcD, params_ptr, tile_coord_mn, norm_constant, norm_constant_scaled_down, args.thread_idx, args.tiled_copy);
}};
/////////////////////////////////////////////////////////////////////////////////////////////////
template < int SFVecSize, class EpilogueTile, class CtaTileShapeMNK, int FragmentSize, class ElementOutput, class ElementCompute, class ElementBlockScaleFactor, FloatRoundStyle RoundStyle = FloatRoundStyle::round_to_nearest>struct Sm120BlockScaleFactorColStore {
static_assert(size<0>(EpilogueTile{}) % SFVecSize == 0, "EpilogueTileN should be divisible by SFVecSize"); static_assert(size<0>(EpilogueTile{}) / SFVecSize == 1 or size<0>(EpilogueTile{}) / SFVecSize == 2 or size<0>(EpilogueTile{}) / SFVecSize == 4, "Possible store in interleaved 4B aligned format");
static constexpr int NumWarpgroups = 2; static constexpr int NumSyncWarps = NumWarpsPerWarpGroup * NumWarpgroups; static constexpr int NumThreadsPerQuad = 4; static constexpr int NumSyncElementsCrossWarp = NumSyncWarps * NumThreadsPerQuad; struct SharedStorage { array_aligned<ElementCompute, NumSyncElementsCrossWarp> smem_aux; };
using NormalConstStrideMNL = Stride<_0,_0,int64_t>;
struct Arguments { ElementBlockScaleFactor* ptr_scale_factor = {}; // A matrix wide constant value to scale the output matrix // Avoids generating small FP4 values. ElementCompute const* norm_constant_ptr = {}; NormalConstStrideMNL norm_constant_stride = {}; }; using Params = Arguments;
using UnderlyingElementBlockScaleFactor = cute::remove_pointer_t<ElementBlockScaleFactor>;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; bool implementable = (M % SFVecSize == 0); if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: [EVT Sm120BlockScaleFactorColStore] N-dim should be divisible by SFVecSize.\n"); } return implementable; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm120BlockScaleFactorColStore() { }
CUTLASS_HOST_DEVICE Sm120BlockScaleFactorColStore(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) , smem_aux(const_cast<ElementCompute*>(shared_storage.smem_aux.data())) { }
Params const* params_ptr = nullptr; ElementCompute *smem_aux = nullptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template < class RTensor, class GTensor, class STensor, class CoordGTensor, class ThrResidue, class TileCoordMN, class ElementType, class TiledCopy_ > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( RTensor&& tC_rSFD_, GTensor&& tC_gSFD_, STensor&& sAmaxs_, CoordGTensor tC_cSFD_, ThrResidue residue_tC_cSFD_, Params const* params_ptr_, TileCoordMN tile_coord_mn_, ElementType norm_constant_, ElementType norm_constant_scaled_down_, int thread_idx_, TiledCopy_ const&) : tC_rSFD(cute::forward<RTensor>(tC_rSFD_)) , tC_gSFD(cute::forward<GTensor>(tC_gSFD_)) , sAmaxs(cute::forward<STensor>(sAmaxs_)) , tC_cSFD(tC_cSFD_) , residue_tC_cSFD(residue_tC_cSFD_) , params_ptr(params_ptr_) , norm_constant(norm_constant_) , norm_constant_scaled_down(norm_constant_scaled_down_) , tile_coord_mn(tile_coord_mn_) , thread_idx(thread_idx_) {}
static_assert(is_same_v<ElementType, ElementCompute>); RTensor tC_rSFD; GTensor tC_gSFD; STensor sAmaxs; CoordGTensor tC_cSFD; ThrResidue residue_tC_cSFD; Params const* params_ptr; ElementCompute norm_constant; ElementCompute norm_constant_scaled_down; TileCoordMN tile_coord_mn; int thread_idx; static constexpr int NumCollaboratingThreads = decltype(size(TiledCopy_{}))::value; static_assert(NumCollaboratingThreads % NumThreadsPerWarpGroup == 0); static constexpr int NumCollaboratingWarpGroups = NumCollaboratingThreads / NumThreadsPerWarpGroup; static_assert(NumCollaboratingWarpGroups == 2, "SM120 epilogue currently only supports two warp groups collaborating."); static_assert(SFVecSize == 16 || SFVecSize == 32 || SFVecSize == 64, "SF vector size must be either 16, 32 or 64.");
template <class ElementAccumulator, class ElementInput> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { return frg_input; }
template <class SmemTensor, class SyncFn, class VTensor> CUTLASS_DEVICE void reduce(SmemTensor&& smem_buffer, SyncFn const& sync_fn, int epi_m, int epi_n, bool is_last_iteration, VTensor visit_results) { /* Accumulator fragments are distributed across threads/quads in different warps. For column major, the reduction happens along M dimension. For SFVector = 32, we have:
8 elements 8 elements 8 elements 8 elements + <----------------------><----------------------><----------------------><----------------------> | Warp 0 Quad 0 Warp 4 Quad 0 Warp 0 Quad 0 Warp 4 Quad 0 | Warp 0 Quad 1 Warp 4 Quad 1 Warp 0 Quad 1 Warp 4 Quad 1 | ... ... ... ... 1 | Warp 0 Quad 7 Warp 4 Quad 7 Warp 0 Quad 7 Warp 4 Quad 7 6 | Warp 0 Quad 0 Warp 4 Quad 0 Warp 0 Quad 0 Warp 4 Quad 0 | Warp 0 Quad 1 Warp 4 Quad 1 Warp 0 Quad 1 Warp 4 Quad 1 | ... ... ... ... + Warp 0 Quad 7 Warp 4 Quad 7 Warp 0 Quad 7 Warp 4 Quad 7 | Warp 1 Quad 0 Warp 5 Quad 0 Warp 1 Quad 0 Warp 5 Quad 0 | Warp 1 Quad 1 Warp 5 Quad 1 Warp 1 Quad 1 Warp 5 Quad 1 1 | ... ... ... ... 6 | Warp 1 Quad 7 Warp 5 Quad 7 Warp 1 Quad 7 Warp 5 Quad 7 | Warp 1 Quad 0 Warp 5 Quad 0 Warp 1 Quad 0 Warp 5 Quad 0 | Warp 1 Quad 1 Warp 5 Quad 1 Warp 1 Quad 1 Warp 5 Quad 1 | ... ... ... ... | Warp 1 Quad 7 Warp 5 Quad 7 Warp 1 Quad 7 Warp 5 Quad 7
<same pattern for warps 2/3 and 6/7 for the next set of 32 rows>
In this case, colum-wise scale factors are cooperatively reduced across 8 threads from 2 warps. Each column first computes its own, local absolute maximum and then shares this with the corresponding threads in the other warp. In this case, a reduction through shared memory is needed.
For SFVector = 64, the reduction happens inside 4 warps: warp 0/1/2/3 and warp 4/5/6/7. */
// Accumulator fragments consist of two elements from two different columns of a 16x8 MMA output static constexpr int RowsPerThreadAccFrag = 2; static constexpr int ColsPerThreadAccFrag = 2; static_assert(FragmentSize == (ColsPerThreadAccFrag * RowsPerThreadAccFrag));
static constexpr int NumThreadsPerCol = NumThreadsPerWarp / NumThreadsPerQuad; constexpr int WarpsPerSF = SFVecSize / NumThreadsPerCol / ColsPerThreadAccFrag; static_assert(WarpsPerSF == 1 || WarpsPerSF == 2 || WarpsPerSF == 4, "Only one, two or four warps are allowed in reduction.");
auto warp_idx = thread_idx / NumThreadsPerWarp; auto thread_idx_in_warp = thread_idx % NumThreadsPerWarp;
cutlass::maximum_absolute_value_reduction<ElementCompute, true> amax_op; cutlass::multiplies<ElementCompute> mul;
auto synchronize = [&] () { // When WarpsPerSF equals 1, data processing is inside warp, there is no needs to have the sync. static constexpr bool NoSyncNeeded = (WarpsPerSF == 1); if(NoSyncNeeded) return; cutlass::arch::NamedBarrier::sync(NumCollaboratingThreads, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); };
CUTLASS_PRAGMA_UNROLL for(int mma_in_epi = 0; mma_in_epi < size<1>(tC_rSFD)*size<2>(tC_rSFD); ++mma_in_epi) {
CUTLASS_PRAGMA_UNROLL for (int sf_id = 0; sf_id < ColsPerThreadAccFrag; ++sf_id) {
// // Compute amax for this scale factor // ElementCompute amax{0};
// Compute amax among vals owned by this thread for this vector auto acc_frg = visit_results(mma_in_epi); amax = amax_op(amax, acc_frg[sf_id]); amax = amax_op(amax, acc_frg[sf_id + ColsPerThreadAccFrag]);
// At this point, each thread has computed the amax of the values that it owns for this SF vector. // We now need to compute the amax across threads. Because SM120 narrow-precision MMAs have 16x8 output // size with a quad owning two rows, we know that 8 threads in one column will own all of the 16 elements // to be reduced via amax. Therefore, we can use warp shuffle intrinsics among threads to compute the amax. CUTLASS_PRAGMA_UNROLL for (int i = 1; i < NumThreadsPerCol; ++i) { auto amax_other = __shfl_xor_sync(0xffffffff, amax, (i * NumThreadsPerQuad)); amax = amax_op(amax, amax_other); }
// At this point, all threads in the quad have the amax for the elements of the accumulator owned by its // threads that should be used in computing the amax for this SF. if (thread_idx_in_warp < NumThreadsPerQuad && WarpsPerSF != 1) { sAmaxs(thread_idx_in_warp, warp_idx) = amax; }
synchronize();
// Get the amax broadcasted by the warp with which we share. // For cooperative kernels, when scale factor vector size is 32 (WarpsPerSF equals 2), // warp 0 shares with 1, warp2 shares with 2, etc. // When vector size is 64 (WarpsPerSF equals 4), warp 0 shares with 1/2/3, and 4 shares with 5/6/7. // When vector size is 16, no needs to swap between warps. if constexpr (2 == WarpsPerSF) { auto amax_other = sAmaxs(thread_idx % NumThreadsPerQuad, warp_idx ^ 1); amax = amax_op(amax, amax_other); } else if constexpr (4 == WarpsPerSF) { auto amax_other1 = sAmaxs(thread_idx % NumThreadsPerQuad, warp_idx ^ 1); auto amax_other2 = sAmaxs(thread_idx % NumThreadsPerQuad, warp_idx ^ 2); auto amax_other3 = sAmaxs(thread_idx % NumThreadsPerQuad, warp_idx ^ 3); amax = amax_op(amax, amax_other1); amax_other2 = amax_op(amax_other2, amax_other3); amax = amax_op(amax, amax_other2); } synchronize();
ElementCompute pvscale = mul(amax, norm_constant_scaled_down); UnderlyingElementBlockScaleFactor qpvscale = NumericConverter<UnderlyingElementBlockScaleFactor, ElementCompute>{}(pvscale); filter(tC_rSFD)(sf_id + mma_in_epi*ColsPerThreadAccFrag) = qpvscale;
// // Apply the scale factor to the output // ElementCompute qpvscale_rcp = [&]() { if constexpr (cute::is_same_v<UnderlyingElementBlockScaleFactor, float_ue8m0_t>) { // UE8M0: Use integer subtraction to do the fast rcp in ue8m0 and then convert to float. auto e8m0_qpvscale_rcp = cutlass::reciprocal_approximate<UnderlyingElementBlockScaleFactor>{}(qpvscale); return cutlass::NumericConverter<ElementCompute, UnderlyingElementBlockScaleFactor>{}(e8m0_qpvscale_rcp); } else { // UE4M3: Do the rcp in fp32 data type. auto qpvscale_up = cutlass::NumericConverter<ElementCompute, UnderlyingElementBlockScaleFactor>{}(qpvscale); return cutlass::reciprocal_approximate_ftz<decltype(qpvscale_up)>{}(qpvscale_up); } }();
ElementCompute acc_scale = mul(norm_constant, qpvscale_rcp); acc_scale = cutlass::minimum_with_nan_propagation<ElementCompute>{}(acc_scale, cutlass::platform::numeric_limits<ElementCompute>::max());
// Compute quantized output values visit_results(mma_in_epi)[sf_id ] = mul(acc_frg[sf_id ], acc_scale); visit_results(mma_in_epi)[sf_id + ColsPerThreadAccFrag] = mul(acc_frg[sf_id + ColsPerThreadAccFrag], acc_scale); } // end for sf_id } // end for mma_in_epi
// Since scale factors are computed cooperatively across two or four warps, we only need one thread from the // cooperating column threads group to write out the data. bool write_sf = (thread_idx_in_warp < NumThreadsPerQuad); if constexpr (2 == WarpsPerSF) { // Output warp {0, 2, 4, 6}. write_sf &= ((warp_idx & 0x1) == 0); } else if constexpr (4 == WarpsPerSF) { // Output warp {0, 4}. write_sf &= ((warp_idx & 0x3) == 0); } else if constexpr (1 == WarpsPerSF) { // Output warp {0, 1, ..., 7}. Keep write_sf as is. }
if (write_sf && elem_less(tC_cSFD(_0{}, _0{}, _0{}, epi_m, epi_n), residue_tC_cSFD)) { copy_aligned(tC_rSFD, tC_gSFD(_, _, _, _0{}, _0{}, get<0>(tile_coord_mn) + epi_m, get<1>(tile_coord_mn) + epi_n)); } } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; using Sm1xxBlockScaledOutputConfig= cutlass::detail::Sm1xxBlockScaledOutputConfig<SFVecSize, UMMA::Major::MN>; UnderlyingElementBlockScaleFactor* ptr_scale_factor = nullptr; // If Ptr-Array/Grouped GEMM with BlockScaleFactor per batch/group if constexpr (!cute::is_same_v<UnderlyingElementBlockScaleFactor, ElementBlockScaleFactor>) { ptr_scale_factor = params_ptr->ptr_scale_factor[l]; l = 0; } else { ptr_scale_factor = params_ptr->ptr_scale_factor; }
static_assert(size<0>(EpilogueTile{}) && ((size<0>(EpilogueTile{}) & (size<1>(EpilogueTile{}) - 1)) == 0), "Epilogue Tile N should be pow of 2");
auto epi_tile_mn = shape<1>(zipped_divide(make_layout(take<0,2>(args.tile_shape_mnk)), args.epi_tile)); Tensor mSFD = make_tensor(make_gmem_ptr(ptr_scale_factor), Sm1xxBlockScaledOutputConfig::tile_atom_to_shape_SFD(args.problem_shape_mnkl));
Tensor gSFD = local_tile(mSFD, args.epi_tile, make_coord(_, _,l)); // (EPI_M,EPI_N, #EPI_Ms, #EPI_Ns) Tensor tCgSFD = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,#EPI_Ms, #EPI_Ns) gSFD, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrSFD = make_tensor_like<UnderlyingElementBlockScaleFactor>(take<0,3>(cute::layout(tCgSFD))); // (CPY,CPY_M,CPY_N)
auto tile_coord_mn = make_coord(m * size<0>(epi_tile_mn), n * size<1>(epi_tile_mn));
// Fetch and compute these during initialization Tensor mNormConst= make_tensor(make_gmem_ptr(params_ptr->norm_constant_ptr), make_layout(make_shape(M, N, L), params_ptr->norm_constant_stride)); ElementCompute norm_constant = mNormConst(_0{},_0{},l); ElementCompute fp_max = ElementCompute(cutlass::platform::numeric_limits<ElementOutput>::max()); ElementCompute scale_down_factor = cutlass::reciprocal_approximate_ftz<ElementCompute>{}(fp_max); ElementCompute norm_constant_scaled_down = cutlass::multiplies<ElementCompute>{}(norm_constant, scale_down_factor);
Tensor sAmaxs = make_tensor( make_smem_ptr(smem_aux), make_layout(make_shape(Int<NumThreadsPerQuad>{}, Int<NumSyncWarps>{})) );
return ConsumerStoreCallbacks( cute::move(tCrSFD), cute::move(tCgSFD), cute::move(sAmaxs), args.tCcD, args.residue_tCcD, params_ptr, tile_coord_mn, norm_constant, norm_constant_scaled_down, args.thread_idx, args.tiled_copy);
}};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree compute operations for the sm90 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/array.h"#include "cutlass/numeric_conversion.h"#include "cutlass/epilogue/thread/activation.h"#include "cutlass/detail/helper_macros.hpp"
#include "cute/tensor.hpp"
#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_load_tma_warpspecialized.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_store_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// N-nary Elementwise Compute Operation///////////////////////////////////////////////////////////////////////////////////////////////////
// The template argument provided for ComputeFn must be able to accept// exactly one template parameter. In Standard C++, it's OK for// ComputeFn to have other template parameters, as long as those have// defaults. For example, the following struct Foo would work.//// template<class A, class B = A>// struct Foo {// CUTLASS_HOST_DEVICE auto operator() (A a, B b);// };//// However, some compilers, such as Clang, require that the argument// take _exactly_ one template parameter. This is nonstandard C++// behavior. One work-around for this case is to create a subclass// with exactly one template parameter, and then use that subclass as// the template argument.//// template<class A>// struct FooHomogeneous : public Foo<A, A> {};//template< template <class> class ComputeFn, class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, class = void>struct Sm90Compute {private: using EmptyArguments = typename Sm90VisitorImpl<>::Arguments;
template <class Fn, class = void> struct ComputeArguments { using type = EmptyArguments; };
// partial specialization for compute fns that define an Arguments member, e.g. activation hyperparameters template <class Fn> struct ComputeArguments<Fn, platform::void_t<typename Fn::Arguments>> { using type = typename Fn::Arguments; };
public: struct SharedStorage { };
using Arguments = typename ComputeArguments<ComputeFn<ElementCompute>>::type;
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const&, Arguments const& args, void*) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const&, Arguments const&) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_HOST_DEVICE Sm90Compute() : params() {}
CUTLASS_HOST_DEVICE Sm90Compute(Params const& params, SharedStorage const& shared_storage) : params(params) {}
Params const params;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(Params const& params) : params(params) {}
Params const& params;
template <typename ElementAccumulator, typename... ElementInputs, int FragmentSize> CUTLASS_DEVICE Array<ElementOutput, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInputs, FragmentSize> const&... frg_inputs) { return transform_apply(cute::make_tuple(frg_inputs...), [&] (auto&& frg_input) CUTLASS_LAMBDA_FUNC_INLINE { using ElementInput = typename cute::remove_cvref_t<decltype(frg_input)>::Element; using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; ConvertInput convert_input{};
return convert_input(frg_input); }, [&] (auto&&... cvt_frg_inputs) CUTLASS_LAMBDA_FUNC_INLINE { using ComputeOutput = ComputeFn<Array<ElementCompute, FragmentSize>>; ComputeOutput compute_output{};
if constexpr (cute::is_same_v<Arguments, EmptyArguments>) { using ElementComputeOutput = typename cute::remove_cvref_t<decltype(compute_output(cvt_frg_inputs...))>::Element; using ConvertOutput = NumericArrayConverter<ElementOutput, ElementComputeOutput, FragmentSize, RoundStyle>; ConvertOutput convert_output{}; return convert_output(compute_output(cvt_frg_inputs...)); } else { using ElementComputeOutput = typename cute::remove_cvref_t<decltype(compute_output(cvt_frg_inputs..., params))>::Element; using ConvertOutput = NumericArrayConverter<ElementOutput, ElementComputeOutput, FragmentSize, RoundStyle>; ConvertOutput convert_output{}; return convert_output(compute_output(cvt_frg_inputs..., params)); } } ); }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { return ConsumerStoreCallbacks(params); }
};
///////////////////////////////////////////////////////////////////////////////////////////////////// Performance Optimized Specializations///////////////////////////////////////////////////////////////////////////////////////////////////
// beta * C + Ztemplate < class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, class InputScaleOp, // beta class ElementSource, // C class InputAddOp // Z>struct Sm90TreeVisitor< Sm90Compute<homogeneous_multiply_add, ElementOutput, ElementCompute, RoundStyle, cute::void_t<decltype(declval<InputScaleOp>().is_zero())>>, InputScaleOp, Sm90SrcFetch<ElementSource>, InputAddOp> : Sm90VisitorImpl< InputScaleOp, Sm90SrcFetch<ElementSource>, InputAddOp, Sm90Compute<homogeneous_multiply_add, ElementOutput, ElementCompute, RoundStyle> >{ using Impl = Sm90VisitorImpl< InputScaleOp, Sm90SrcFetch<ElementSource>, InputAddOp, Sm90Compute<homogeneous_multiply_add, ElementOutput, ElementCompute, RoundStyle> >; using Params = typename Impl::Params; using SharedStorage = typename Impl::SharedStorage;
CUTLASS_HOST_DEVICE Sm90TreeVisitor() {}
CUTLASS_HOST_DEVICE Sm90TreeVisitor( Params const& params, SharedStorage const& shared_storage) : Impl(params, shared_storage) {}
CUTLASS_DEVICE bool is_producer_load_needed() const { auto const& scale_op = get<0>(Impl::ops); auto const& added_op = get<2>(Impl::ops); if constexpr (detail::IsScalarBroadcast<InputScaleOp>::value && not is_void_v<ElementSource>) { return (get<2>(scale_op.params_ptr->dScalar[0]) != 0 && scale_op.params_ptr->scalar_ptrs[0] != nullptr) || is_C_load_needed() || added_op.is_producer_load_needed(); } else { return is_C_load_needed() || added_op.is_producer_load_needed(); } }
CUTLASS_DEVICE bool is_C_load_needed() const { auto const& scale_op = get<0>(Impl::ops); auto const& src_op = get<1>(Impl::ops); auto const& added_op = get<2>(Impl::ops); return (not scale_op.is_zero() && src_op.is_C_load_needed()) || added_op.is_C_load_needed(); }
template <class CallbacksImpl> struct ConsumerStoreCallbacks : CallbacksImpl { CUTLASS_DEVICE ConsumerStoreCallbacks(bool is_C_load_needed, CallbacksImpl&& impl) : is_C_load_needed(is_C_load_needed), CallbacksImpl(cute::forward<CallbacksImpl>(impl)) { }
bool is_C_load_needed;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<ElementOutput, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Array frg_added = get<2>(CallbacksImpl::callbacks_tuple).visit(frg_acc, epi_v, epi_m, epi_n);
using ElementZ = typename decltype(frg_added)::Element; using ConvertZ = NumericArrayConverter<ElementCompute, ElementZ, FragmentSize, RoundStyle>; using ConvertI = NumericArrayConverter<ElementOutput, ElementCompute, FragmentSize, RoundStyle>; ConvertZ convert_Z{}; ConvertI convert_I{};
Array frg_I = convert_Z(frg_added);
if constexpr (!is_void_v<ElementSource>) { Array frg_scalar = get<0>(CallbacksImpl::callbacks_tuple).visit(frg_acc, epi_v, epi_m, epi_n); Array frg_source = get<1>(CallbacksImpl::callbacks_tuple).visit(frg_acc, epi_v, epi_m, epi_n);
using ElementX = typename decltype(frg_scalar)::Element; using ElementY = typename decltype(frg_source)::Element; using ConvertX = NumericArrayConverter<ElementCompute, ElementX, FragmentSize, RoundStyle>; using ConvertY = NumericArrayConverter<ElementCompute, ElementY, FragmentSize, RoundStyle>; using ComputeI = multiply_add<Array<ElementCompute, FragmentSize>>; ConvertX convert_X{}; ConvertY convert_Y{}; ComputeI compute_I{};
frg_I = compute_I(convert_X(frg_scalar), convert_Y(frg_source), frg_I); }
return convert_I(frg_I); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto callbacks_tuple = Impl::template get_consumer_store_callbacks<ReferenceSrc>(args); bool is_C_load_needed = this->is_C_load_needed(); if (not is_C_load_needed) { cute::clear(args.tCrC); } return ConsumerStoreCallbacks<decltype(callbacks_tuple)>( is_C_load_needed, std::move(callbacks_tuple)); }};
// ReLU with aux bit tensor dReLU/dZ// Aux(i) = Z(i) >= 0 ? 1 : 0namespace detail {// Placeholder node so we can retain standard EVT structuretemplate <class StrideMNL>struct Sm90ReLUAuxStore : Sm90VisitorImpl<> { struct SharedStorage {};
struct Arguments { cutlass::uint1b_t* ptr_aux = nullptr; StrideMNL dAux = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90ReLUAuxStore() { }
CUTLASS_HOST_DEVICE Sm90ReLUAuxStore(Params const& params, SharedStorage const& shared_storage) { }};} // namespace detail
// Specialization on the generic compute+aux EVTtemplate < // Compute node template <class> class Activation, class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, // Aux node int Stages, class EpilogueTile, class StrideMNL, class SmemLayoutAtom, class CopyOpR2S, int Alignment, bool EnableNullptr, // Input node class InputOp>struct Sm90TreeVisitor< Sm90Compute<Activation, ElementOutput, ElementCompute, RoundStyle, cute::enable_if_t<cute::is_same_v<Activation<ElementCompute>, cutlass::epilogue::thread::ReLu<ElementCompute>> || cute::is_same_v<Activation<ElementCompute>, cutlass::epilogue::thread::Clamp<ElementCompute>> || cute::is_same_v<Activation<ElementCompute>, cutlass::epilogue::thread::ThresholdReLU<ElementCompute>> >>, Sm90TreeVisitor< Sm90AuxStore< Stages, EpilogueTile, cutlass::uint1b_t, RoundStyle, StrideMNL, SmemLayoutAtom, CopyOpR2S, Alignment, EnableNullptr >, InputOp >> : Sm90VisitorImpl< Sm90VisitorImpl< InputOp, detail::Sm90ReLUAuxStore<StrideMNL> >, Sm90Compute<Activation, ElementOutput, ElementCompute, RoundStyle> >{ using Impl = Sm90VisitorImpl< Sm90VisitorImpl< InputOp, detail::Sm90ReLUAuxStore<StrideMNL> >, Sm90Compute<Activation, ElementOutput, ElementCompute, RoundStyle> >; using Params = typename Impl::Params; using SharedStorage = typename Impl::SharedStorage;
CUTLASS_HOST_DEVICE Sm90TreeVisitor() {}
CUTLASS_HOST_DEVICE Sm90TreeVisitor(Params const& params_, SharedStorage const& shared_storage) : params(params_), Impl(params_, shared_storage) {}
Params const& params;
template <class RTensor, class GTensor, class CTensor, class ThrResidue, class CallbacksImpl> struct ConsumerStoreCallbacks : CallbacksImpl { CUTLASS_DEVICE ConsumerStoreCallbacks( RTensor&& tC_rAux, GTensor&& tC_gAux, CTensor tC_cAux, ThrResidue residue_tC_cAux, Params const& params, CallbacksImpl&& impl) : tC_rAux(cute::forward<RTensor>(tC_rAux)), tC_gAux(cute::forward<GTensor>(tC_gAux)), tC_cAux(tC_cAux), residue_tC_cAux(residue_tC_cAux), params(params), CallbacksImpl(cute::forward<CallbacksImpl>(impl)) {}
RTensor tC_rAux; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) GTensor tC_gAux; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) CTensor tC_cAux; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) ThrResidue residue_tC_cAux; Params const& params;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<ElementOutput, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { // Unpack callbacks + params auto& [callbacks_input_aux, callbacks_compute] = CallbacksImpl::callbacks_tuple; auto& [callbacks_input, callbacks_aux] = callbacks_input_aux.callbacks_tuple; auto const& [params_input_aux, params_compute] = params; auto const& [params_input, params_aux] = params_input_aux;
// Visit the input node Array frg_input = callbacks_input.visit(frg_acc, epi_v, epi_m, epi_n);
// Compute activation + aux using ElementInput = typename decltype(frg_input)::Element; using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; using ConvertAux = PackPredicates<FragmentSize>; using ComputeOutput = Activation<ElementCompute>; using ConvertOutput = NumericArrayConverter<ElementOutput, ElementCompute, FragmentSize, RoundStyle>; ConvertInput convert_input{}; ComputeOutput relu{}; ConvertAux convert_aux{}; ConvertOutput convert_output{};
Array frg_compute = convert_input(frg_input); bool frg_aux[FragmentSize]; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { ElementCompute pre_relu = frg_compute[i]; if constexpr (cute::is_same_v<Activation<ElementCompute>, cutlass::epilogue::thread::Clamp<ElementCompute>> || cute::is_same_v<Activation<ElementCompute>, cutlass::epilogue::thread::ThresholdReLU<ElementCompute>>) { frg_compute[i] = relu(frg_compute[i], params_compute); } else { frg_compute[i] = relu(frg_compute[i]); } if constexpr (cute::is_same_v<ElementCompute, float>) { uint32_t aux; asm volatile("set.equ.u32.f32 %0, %1, %2;\n" : "=r"(aux) : "f"(frg_compute[i]), "f"(pre_relu)); // NaN outputs 1 in Aux frg_aux[i] = static_cast<bool>(aux); } else if constexpr (cute::is_same_v<ElementCompute, cutlass::half_t>) { uint32_t aux; cutlass::half_t compute = frg_compute[i]; asm volatile("set.equ.u32.f16 %0, %1, %2;\n" : "=r"(aux) : "h"(compute.raw()), "h"(pre_relu.raw())); // NaN outputs 1 in Aux frg_aux[i] = static_cast<bool>(aux); } else { frg_aux[i] = frg_compute[i] == pre_relu; } }
static_assert(FragmentSize % 8 == 0, "Predicate vector must be byte-aligned"); Tensor tC_rAux_frg = recast<typename ConvertAux::result_type>(coalesce(tC_rAux(_,_,_,epi_m,epi_n))); // (EPI_V) tC_rAux_frg(epi_v) = convert_aux(frg_aux);
return convert_output(frg_compute); }
CUTLASS_DEVICE void end() { // Unpack callbacks + params auto& [callbacks_input_aux, callbacks_compute] = CallbacksImpl::callbacks_tuple; auto& [callbacks_input, callbacks_aux] = callbacks_input_aux.callbacks_tuple; auto const& [params_input_aux, params_compute] = params; auto const& [params_input, params_aux] = params_input_aux;
// Visit the input node callbacks_input.end();
// Nullptr is no-op if constexpr (EnableNullptr) { if (params_aux.ptr_aux == nullptr) { return; } }
// Compute vectorization constexpr auto MCL = decltype(max_common_layout(tC_rAux, tC_gAux)){}; constexpr int V = cute::min(Alignment, size(MCL)); // Copy vectorizes into byte-aligned stores if constexpr (V > 1 && V % 8 == 0) { using VecType = uint_bit_t<V>; Tensor tC_rAux_vec = recast<VecType>(tC_rAux); Tensor tC_gAux_vec = recast<VecType>(tC_gAux); Tensor tC_cAux_vec = tensor<1>(zipped_divide(tC_cAux, MCL.compose(Int<V>{}))); Tensor tC_pAux_vec = cute::lazy::transform(tC_cAux_vec, [&](auto const& c){ return elem_less(c, residue_tC_cAux); }); copy_if(tC_pAux_vec, tC_rAux_vec, tC_gAux_vec); } // sub-byte vectorization, must serialize threads else { // Assumes no inter-warp sharing of bytes (most copy layouts should satisfy this) int lane_idx = canonical_lane_idx(); Tensor tC_pAux = cute::lazy::transform(tC_cAux, [&](auto const& c){ return elem_less(c, residue_tC_cAux); }); CUTLASS_PRAGMA_NO_UNROLL for (int i = 0; i < NumThreadsPerWarp; ++i) { if (lane_idx == i) { copy_if(tC_pAux, tC_rAux, tC_gAux); } __syncwarp(); } } } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { // Unpack params auto const& [params_input_aux, params_compute] = params; auto const& [params_input, params_aux] = params_input_aux;
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; gmem_ptr ptr_aux = make_gmem_ptr<cutlass::uint1b_t>(params_aux.ptr_aux); Tensor mAux = make_tensor(ptr_aux, make_layout(make_shape(M,N,L), params_aux.dAux)); // (M,N,L) Tensor gAux = local_tile(mAux, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N)
Tensor tC_gAux = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) gAux, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tC_rAux = make_tensor<cutlass::uint1b_t>(shape(tC_gAux)); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N)
auto callbacks_impl = Impl::template get_consumer_store_callbacks<ReferenceSrc>(args); return ConsumerStoreCallbacks<decltype(tC_rAux), decltype(tC_gAux), decltype(args.tCcD), decltype(args.residue_tCcD), decltype(callbacks_impl)>( cute::move(tC_rAux), cute::move(tC_gAux), args.tCcD, args.residue_tCcD, params, cute::move(callbacks_impl)); }};
// Aux load for uint1b_ttemplate < int Stages, class EpilogueTile, class StrideMNL, class SmemLayoutAtom, class CopyOpS2R, int Alignment, bool EnableNullptr>struct Sm90AuxLoad< Stages, EpilogueTile, cutlass::uint1b_t, StrideMNL, SmemLayoutAtom, CopyOpS2R, Alignment, EnableNullptr> { static_assert(Alignment % 128 == 0, "sub-16B alignment not supported yet");
struct SharedStorage {};
struct Arguments { cutlass::uint1b_t const* ptr_aux = nullptr; cutlass::uint1b_t null_default = cutlass::uint1b_t(0); StrideMNL dAux = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90AuxLoad() { }
CUTLASS_HOST_DEVICE Sm90AuxLoad(Params const& params, SharedStorage const&) : params(params) { }
Params const params;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template <class RTensor, class GTensor, class CTensor, class ThrResidue> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(RTensor&& tC_rAux_, GTensor&& tC_gAux_, CTensor tC_cAux_, ThrResidue residue_tC_cAux_, Params const& params_) : tC_rAux(cute::forward<RTensor>(tC_rAux_)), tC_gAux(cute::forward<GTensor>(tC_gAux_)), tC_cAux(tC_cAux_), residue_tC_cAux(residue_tC_cAux_), params(params_) {}
RTensor tC_rAux; // (CPY,CPY_M,CPY_N,{EPI_M,EPI_N}) GTensor tC_gAux; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) CTensor tC_cAux; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) ThrResidue residue_tC_cAux; Params const& params;
CUTLASS_DEVICE void begin() { if constexpr (decltype(cute::rank(tC_rAux))::value == 5) { if constexpr (EnableNullptr) { if (params.ptr_aux == nullptr) { return; } }
constexpr auto MCL = decltype(max_common_layout(tC_rAux, tC_gAux)){}; constexpr int V = cute::min(Alignment, size(MCL)); if constexpr (V > 1) { using VecType = uint_bit_t<V>; Tensor tC_gAux_vec = recast<VecType>(tC_gAux); Tensor tC_rAux_vec = recast<VecType>(tC_rAux); Tensor tC_cAux_vec = tensor<1>(zipped_divide(tC_cAux, MCL.compose(Int<V>{}))); Tensor tC_pAux_vec = cute::lazy::transform(tC_cAux_vec, [&](auto const& c){ return elem_less(c, residue_tC_cAux); }); copy_if(tC_pAux_vec, tC_gAux_vec, tC_rAux_vec); } else { Tensor tC_pAux = cute::lazy::transform(tC_cAux, [&](auto const& c){ return elem_less(c, residue_tC_cAux); }); copy_if(tC_pAux, tC_gAux, tC_rAux); } } }
CUTLASS_DEVICE void begin_loop(int epi_m, int epi_n) { if constexpr (decltype(cute::rank(tC_rAux))::value == 3) { if constexpr (EnableNullptr) { if (params.ptr_aux == nullptr) { return; } }
Tensor tC_pAux = cute::lazy::transform(tC_cAux(_,_,_,epi_m,epi_n), [&](auto const& c){ return elem_less(c, residue_tC_cAux); }); copy_if(tC_pAux, tC_gAux(_,_,_,epi_m,epi_n), tC_rAux); } }
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { using ElementRegister = typename remove_cvref_t<RTensor>::value_type; if constexpr (decltype(cute::rank(tC_rAux))::value == 3) { return recast<Array<ElementRegister, FragmentSize>>(coalesce(tC_rAux))(epi_v); } else { return recast<Array<ElementRegister, FragmentSize>>(coalesce(tC_rAux(_,_,_,epi_m,epi_n)))(epi_v); } } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; gmem_ptr ptr_aux = make_gmem_ptr<cutlass::uint1b_t const>(params.ptr_aux); Tensor mAux = make_tensor(ptr_aux, make_layout(make_shape(M,N,L), params.dAux)); // (M,N,L) Tensor gAux = local_tile(mAux, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N)
Tensor tC_gAux = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) gAux, args.epi_tile, args.tiled_copy, args.thread_idx);
// If byte-unaligned vectorization, store in registers as uint32_t to reduce redundant pack+unpack instruction sequences constexpr int V = decltype(max_common_vector(tC_gAux.layout(), make_layout(tC_gAux.shape())))::value; Tensor tC_rAux = [&] () CUTLASS_LAMBDA_FUNC_INLINE { if constexpr (V % 8 != 0) { return make_tensor<uint32_t>(take<0,3>(shape(tC_gAux))); // (CPY,CPY_M,CPY_N) } else { return make_tensor<cutlass::uint1b_t>(shape(tC_gAux)); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) } }();
if constexpr (EnableNullptr) { if (params.ptr_aux == nullptr) { fill(tC_rAux, params.null_default); } }
return ConsumerStoreCallbacks<decltype(tC_rAux), decltype(tC_gAux), decltype(args.tCcD), decltype(args.residue_tCcD)>( cute::move(tC_rAux), cute::move(tC_gAux), args.tCcD, args.residue_tCcD, params); }};
// dReLU specializationtemplate< class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle>struct Sm90Compute< cutlass::epilogue::thread::dReLU, ElementOutput, ElementCompute, RoundStyle> : Sm90VisitorImpl<> {
using Sm90VisitorImpl<>::Sm90VisitorImpl;
struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { template <typename ElementAccumulator, typename ElementInput, typename ElementAux, int FragmentSize> CUTLASS_DEVICE Array<ElementOutput, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput , FragmentSize> const& frg_input, Array<ElementAux , FragmentSize> const& frg_aux) { using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; using ComputeOutput = cutlass::epilogue::thread::dReLU<Array<ElementCompute, FragmentSize>>; using ConvertOutput = NumericArrayConverter<ElementOutput, ElementCompute, FragmentSize, RoundStyle>; ConvertInput convert_input{}; ComputeOutput compute_output{}; ConvertOutput convert_output{};
return convert_output(compute_output(convert_input(frg_input), frg_aux)); // don't convert frg_aux for dReLU } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { return ConsumerStoreCallbacks(); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree load operations for the sm90 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/arch/barrier.h"#include "cutlass/epilogue/collective/detail.hpp"#include "cutlass/detail/helper_macros.hpp"
#include "cute/tensor.hpp"#include "sm90_visitor_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// Elementwise Fetch Operations///////////////////////////////////////////////////////////////////////////////////////////////////
// returns accumulatorstruct Sm90AccFetch : Sm90VisitorImpl<> {
using Sm90VisitorImpl<>::Sm90VisitorImpl;
struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<ElementAccumulator, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { return frg_acc; } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { return ConsumerStoreCallbacks{}; }};
// Split tree visitor fetches intermediate results from temporary accumulatorsusing Sm90SplitTreeFetch = Sm90AccFetch;
/////////////////////////////////////////////////////////////////////////////////////////////////
// returns Ctemplate <class Element>struct Sm90SrcFetch : Sm90VisitorImpl<> {
CUTLASS_DEVICE bool is_producer_load_needed() const { return is_C_load_needed(); }
CUTLASS_DEVICE bool is_C_load_needed() const { return not is_void_v<Element>; }
CUTLASS_DEVICE bool is_zero() const { return is_void_v<Element>; }
using Sm90VisitorImpl<>::Sm90VisitorImpl;
template<class SrcTensor> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(SrcTensor const& tCrC) : tCrC(tCrC) {}
SrcTensor const& tCrC; // (CPY,CPY_M,CPY_N)
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<typename SrcTensor::value_type, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { return recast<Array<typename SrcTensor::value_type, FragmentSize>>(tCrC)(epi_v); }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { // register type may differ from logical type so we can't assert matching types here return ConsumerStoreCallbacks(args.tCrC); }};
// returns accumulator in Grouped Conv Wgradtemplate <class GroupsPerTile_>struct Sm90AccFetchGroupedWgrad : Sm90VisitorImpl<> {
using Sm90VisitorImpl<>::Sm90VisitorImpl; using GroupsPerTile = GroupsPerTile_; struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(int32_t thread_idx) : thread_idx(thread_idx) { }
int32_t thread_idx;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<ElementAccumulator, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) {
Array<ElementAccumulator, FragmentSize> frg_acc_rst; int warp_id = thread_idx / 32;
// In Grouped Wgrad, only diagonal block data is valid and the others is wrong and useless. // One block size is C/G x C/G. Note that C/G = Tile_N / GroupsPerTile. // Copy diagonal block ACC into the first block Col which is the output tensor size Tile_M * C/G. // Then we can store the valid output tensor tile directly. if constexpr ( cute::is_same_v<GroupsPerTile, _1> ) { frg_acc_rst = frg_acc; } else if constexpr ( cute::is_same_v<GroupsPerTile, _2> ) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < 16; i++) { frg_acc_rst[i] = frg_acc[i + warp_id / 2 * 16]; } } else if constexpr ( cute::is_same_v<GroupsPerTile, _4> ) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < 8; i++) { frg_acc_rst[i] = frg_acc[i + warp_id * 8]; } } else if constexpr ( cute::is_same_v<GroupsPerTile, _8> ) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < 4; i++) { frg_acc_rst[i] = frg_acc[i + warp_id * 8 + i / 2 * 4]; } }
return frg_acc_rst; } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { return ConsumerStoreCallbacks(args.thread_idx); }};
///////////////////////////////////////////////////////////////////////////////////////////////////// Elementwise Load Operations///////////////////////////////////////////////////////////////////////////////////////////////////
template < int Stages, class EpilogueTile, class Element, class StrideMNL, class SmemLayoutAtom, class CopyOpS2R, int Alignment = 128 / sizeof_bits_v<Element>, bool EnableNullptr = true // Fallback scalar broadcast for nullptr params>struct Sm90AuxLoad { static_assert(Alignment * sizeof_bits_v<Element> % 128 == 0, "sub-16B alignment not supported yet");
constexpr static bool is_m_major = epilogue::collective::detail::is_m_major<StrideMNL>(); // Find the max contiguous layout usable by TMA (if EpilogueTile is a non-compact tiler) using SmemShapeTma = decltype(make_shape( max_common_vector(make_layout(get<0>(EpilogueTile{})),make_layout(get<0>(EpilogueTile{}))), max_common_vector(make_layout(get<1>(EpilogueTile{})),make_layout(get<1>(EpilogueTile{}))))); using SmemLayoutTma = decltype(tile_to_shape( SmemLayoutAtom{}, SmemShapeTma{}, cute::conditional_t<is_m_major, Step<_2,_1>, Step<_1,_2>>{} )); using SmemLayout = decltype(tile_to_shape( SmemLayoutTma{}, make_shape(size<0>(shape(EpilogueTile{})), size<1>(shape(EpilogueTile{})), Int<Stages>{}), cute::conditional_t<is_m_major, Step<_2,_1,_3>, Step<_1,_2,_3>>{} )); using CopyOpG2S = SM90_TMA_LOAD ;
struct SharedStorage { alignas(cutlass::detail::alignment_for_swizzle(SmemLayout{})) array_aligned<Element, size(SmemLayout{})> smem_aux; };
struct Arguments { Element const* ptr_aux = nullptr; Element null_default = Element(0); StrideMNL dAux = {}; };
struct Params { using TMA_Aux = decltype(make_tma_copy( CopyOpG2S{}, make_tensor(make_gmem_ptr(static_cast<Element const*>(nullptr)), repeat_like(StrideMNL{}, int32_t(0)), append<3>(StrideMNL{}, _0{})), take<0,2>(SmemLayoutTma{}))); TMA_Aux tma_load_aux; Element null_default = Element(0); bool use_default = false; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { // Optionally append 1s until problem shape is rank-4 in case its is only rank-3 (MNK) auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto M_AUX = size(M) ; Tensor tensor_aux = make_tensor(make_gmem_ptr(args.ptr_aux), make_layout(make_shape(M_AUX,N,L), append<3>(args.dAux, _0{}))); typename Params::TMA_Aux tma_load_aux = make_tma_copy(CopyOpG2S{}, tensor_aux, take<0,2>(SmemLayoutTma{}));
bool use_default = false; if constexpr (EnableNullptr) { use_default = args.ptr_aux == nullptr; }
return Params{tma_load_aux, args.null_default, use_default}; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90AuxLoad() { }
CUTLASS_HOST_DEVICE Sm90AuxLoad(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms), smem_aux(const_cast<Element*>(shared_storage.smem_aux.data())) { }
Params const* params_ptr; Element* smem_aux;
CUTLASS_DEVICE bool is_producer_load_needed() const { return true; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_DEVICE bool is_zero() const { return (params_ptr->use_default && params_ptr->null_default == Element(0)); }
template <class GTensor, class STensor> struct ProducerLoadCallbacks : EmptyProducerLoadCallbacks { CUTLASS_DEVICE ProducerLoadCallbacks(GTensor&& bGS_gAux, STensor&& bGS_sAux, Params const* params_ptr) : bGS_gAux(cute::forward<GTensor>(bGS_gAux)), bGS_sAux(cute::forward<STensor>(bGS_sAux)), params_ptr(params_ptr) {}
GTensor bGS_gAux; // (TMA,TMA_M,TMA_N,EPI_M,EPI_N) STensor bGS_sAux; // (TMA,TMA_M,TMA_N,PIPE) Params const* params_ptr;
CUTLASS_DEVICE void step(uint64_t* full_mbarrier_ptr, int epi_m, int epi_n, int load_iteration, bool issue_tma_load) { if constexpr (EnableNullptr) { if (params_ptr->use_default) { return; } }
if (issue_tma_load) { // Increment the expected transaction bytes of the current stage's mbarrier by the subtile's byte-size constexpr uint32_t copy_bytes = size(take<0,2>(SmemLayout{})) * sizeof_bits_v<Element> / 8; cutlass::arch::ClusterTransactionBarrier::expect_transaction(full_mbarrier_ptr, copy_bytes); // Issue the TMA load constexpr uint16_t mcast_mask = 0; int load_pipe_index = load_iteration % Stages; copy(params_ptr->tma_load_aux.with(*full_mbarrier_ptr, mcast_mask), bGS_gAux(_,_,_,epi_m,epi_n), bGS_sAux(_,_,_,load_pipe_index)); } } };
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; auto coord_shape = make_coord(m, n, l) ; Tensor mAux_mn = params_ptr->tma_load_aux.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mAux = coalesce(mAux_mn, take<0,2>(args.tile_shape_mnk)); Tensor gAux = local_tile(mAux, take<0,2>(args.tile_shape_mnk), coord_shape); // (CTA_M,CTA_N)
Tensor gAux_epi = flat_divide(gAux, args.epi_tile); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N) Tensor sAux_epi = make_tensor(make_smem_ptr(smem_aux), SmemLayout{}); // (EPI_TILE_M,EPI_TILE_N,PIPE)
ThrCopy thrblk_g2s = params_ptr->tma_load_aux.get_slice(_0{}); Tensor bGS_gAux = thrblk_g2s.partition_S(gAux_epi); // (TMA,TMA_M,TMA_N,EPI_M,EPI_N) Tensor bGS_sAux = thrblk_g2s.partition_D(sAux_epi); // (TMA,TMA_M,TMA_N,PIPE)
return ProducerLoadCallbacks<decltype(bGS_gAux), decltype(bGS_sAux)>( cute::move(bGS_gAux), cute::move(bGS_sAux), params_ptr); }
template <class RTensor, class TiledS2R, class STensorS2R> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(RTensor&& tC_rAux, TiledS2R tiled_s2r, STensorS2R&& tSR_sAux, Params const* params_ptr) : tC_rAux(cute::forward<RTensor>(tC_rAux)), tiled_s2r(tiled_s2r), tSR_sAux(cute::forward<STensorS2R>(tSR_sAux)), params_ptr(params_ptr) { }
TiledS2R tiled_s2r; RTensor tC_rAux; // (CPY,CPY_M,CPY_N) STensorS2R tSR_sAux; // (S2R,S2R_M,S2R_N,PIPE) Params const* params_ptr;
CUTLASS_DEVICE void previsit(int epi_m, int epi_n, int load_iteration, bool is_producer_load_needed) { if constexpr (EnableNullptr) { if (params_ptr->use_default) { fill(tC_rAux, params_ptr->null_default); return; } }
using RLayoutS2R = decltype(cute::layout(TiledS2R{}.get_slice(0).retile_S(RTensor{}))); Tensor tSR_rAux = make_tensor(tC_rAux.data(), RLayoutS2R{}); // (S2R,S2R_M,S2R_N)
int load_pipe_index = load_iteration % Stages; copy(tiled_s2r, tSR_sAux(_,_,_,load_pipe_index), tSR_rAux); }
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<Element, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Tensor tC_rAux_frg = recast<Array<Element, FragmentSize>>(coalesce(tC_rAux)); // (EPI_V)
return tC_rAux_frg(epi_v); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl;
Tensor mAux_mn = params_ptr->tma_load_aux.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor mAux = coalesce(mAux_mn, take<0,2>(args.tile_shape_mnk)); Tensor tC_gAux = sm90_partition_for_epilogue<ReferenceSrc // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) >(mAux, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tC_rAux = make_tensor<Element>(take<0,3>(shape(tC_gAux))); // (CPY,CPY_M,CPY_N)
auto tiled_s2r = conditional_return<ReferenceSrc>( make_tiled_copy_S(Copy_Atom<CopyOpS2R,Element>{}, args.tiled_copy), make_tiled_copy_D(Copy_Atom<CopyOpS2R,Element>{}, args.tiled_copy) ); Tensor sAux_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(smem_aux), SmemLayout{})); // (EPI_TILE_M,EPI_TILE_N,PIPE) auto tSR_sAux = tiled_s2r.get_slice(args.thread_idx).partition_S(sAux_epi); // (S2R,S2R_M,S2R_N,PIPE)
return ConsumerStoreCallbacks<decltype(tC_rAux), decltype(tiled_s2r), decltype(tSR_sAux)>( cute::move(tC_rAux), tiled_s2r, cute::move(tSR_sAux), params_ptr); }};
template < class Element, class EpilogueTile, // Unused class LayoutOrStrideMNL, class SmemLayoutAtom, // Unused class CopyOpS2R, // Unused int Alignment, bool EnableNullptr>struct Sm90AuxLoad< 0, EpilogueTile, Element, LayoutOrStrideMNL, SmemLayoutAtom, CopyOpS2R, Alignment, EnableNullptr> { using ElementAux = Element; using StrideMNL = cutlass::gemm::TagToStrideC_t<LayoutOrStrideMNL>;
struct SharedStorage { };
struct Arguments { Element const* ptr_aux = nullptr; Element null_default = Element(0); StrideMNL dAux = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90AuxLoad() { }
CUTLASS_HOST_DEVICE Sm90AuxLoad(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) { }
Params const* params_ptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template< class GTensorG2R, class RTensor, class CTensorG2R, class ProblemShapeMNL > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(GTensorG2R&& tC_gAux, RTensor&& tC_rAux, CTensorG2R&& tC_cAux, ProblemShapeMNL problem_shape_mnl, Params const* params_ptr) : tC_gAux(cute::forward<GTensorG2R>(tC_gAux)), tC_rAux(cute::forward<RTensor>(tC_rAux)), tC_cAux(cute::forward<CTensorG2R>(tC_cAux)), problem_shape_mnl(problem_shape_mnl), params_ptr(params_ptr) {}
GTensorG2R tC_gAux; RTensor tC_rAux; CTensorG2R tC_cAux; ProblemShapeMNL problem_shape_mnl; Params const* params_ptr;
CUTLASS_DEVICE void begin_loop(int epi_m, int epi_n) { if constexpr (EnableNullptr) { if (params_ptr->ptr_aux == nullptr) { fill(tC_rAux, params_ptr->null_default); return; } } constexpr auto MCL = decltype(max_common_layout(tC_gAux(_,_,_,_0{},_0{}), tC_rAux)){}; constexpr int V = cute::min(Alignment, size(MCL));
Tensor tC_gAux_vec = recast<Array<Element, V>>(coalesce(tC_gAux(_,_,_,epi_m,epi_n))); Tensor tC_rAux_vec = recast<Array<Element, V>>(coalesce(tC_rAux));
Tensor tC_cAux_vec = tensor<1>(zipped_divide(coalesce(tC_cAux(_,_,_,epi_m,epi_n)), MCL.compose(Int<V>{}))); Tensor tC_pAux_vec = cute::lazy::transform(tC_cAux_vec, [&](auto const& c){ return elem_less(c, problem_shape_mnl); });
copy_if(tC_pAux_vec, tC_gAux_vec, tC_rAux_vec); }
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<Element, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { return recast<Array<Element, FragmentSize>>(tC_rAux)(epi_v); } };
template < bool ReferenceSrc, class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl;
auto problem_shape_mnl = make_shape(M,N,L);
// Gmem Tensor Tensor mAux = make_tensor( make_gmem_ptr(params_ptr->ptr_aux), make_shape(M,N,L), params_ptr->dAux ); Tensor tC_gAux = sm90_partition_for_epilogue<ReferenceSrc>( mAux, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx);
// Register Tensor Tensor tC_rAux = make_tensor<Element>(take<0,3>(shape(tC_gAux)));
// Predication support Tensor coordAux = make_identity_tensor(shape(mAux)); Tensor tC_cAux = sm90_partition_for_epilogue<ReferenceSrc>( coordAux, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx);
return ConsumerStoreCallbacks<decltype(tC_gAux), decltype(tC_rAux), decltype(tC_cAux), decltype(problem_shape_mnl)>( cute::move(tC_gAux), cute::move(tC_rAux), cute::move(tC_cAux), problem_shape_mnl, params_ptr ); }};
///////////////////////////////////////////////////////////////////////////////////////////////////// Broadcast Load Operations///////////////////////////////////////////////////////////////////////////////////////////////////
// Scalar broadcast// Supports reduction over multiple broadcasts to support fusions such as fp8 scaling factorstemplate< class Element, class StrideMNL_ = Stride<_0,_0,_0>, int BroadcastCount = 1, template <class> class ReductionFn = multiplies>struct Sm90ScalarBroadcast { using StrideMNL = StrideMNL_; static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))>); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_0,_0>{});
struct SharedStorage { };
struct Arguments { Element scalars[BroadcastCount] = {}; Element const* scalar_ptrs[BroadcastCount] = {}; StrideMNL dScalar[BroadcastCount] = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter *cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
// This must be called after update_scalar is called CUTLASS_DEVICE bool is_zero() const { if (get<2>(params_ptr->dScalar[0]) == 0) { // Only 1 batch return scalar == Element(0); } else { // multiple batch if (valid_scalar == false) { // for stridedBatch kernel, if ptr has a valid address, we need to enable the epi_load warps. return params_ptr->scalar_ptrs[0] == nullptr; } else { // Check whether each batch is ZERO or not. return scalar == Element(0); } } }
CUTLASS_HOST_DEVICE Sm90ScalarBroadcast() { }
CUTLASS_HOST_DEVICE Sm90ScalarBroadcast(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) { // Get the scalar for non-batched broadcast if (size<2>(params_ptr->dScalar[0]) == 0) { update_scalar(); } }
Element scalar; bool valid_scalar = false; Params const* params_ptr;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { // Get the scalar for batched broadcast if (size<2>(params_ptr->dScalar[0]) != 0) { auto [m_coord, n_coord, k_coord, l_coord] = args.tile_coord_mnkl; update_scalar(l_coord); }
return EmptyProducerLoadCallbacks{}; }
struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(Element scalar) : scalar(scalar) {}
Element scalar;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<Element, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Array<Element, FragmentSize> frg_scalar; frg_scalar.fill(scalar);
return frg_scalar; }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
// Get the scalar for batched broadcast if (get<2>(params_ptr->dScalar[0]) != 0) { auto [m_coord, n_coord, k_coord, l_coord] = args.tile_coord_mnkl; update_scalar(l_coord); }
return ConsumerStoreCallbacks(scalar); }
private: CUTLASS_DEVICE void update_scalar(int l_coord = 0) { valid_scalar = true; int l_offset = l_coord * size<2>(params_ptr->dScalar[0]);
if (params_ptr->scalar_ptrs[0] != nullptr) { scalar = params_ptr->scalar_ptrs[0][l_offset]; } else { // batch stride is ignored for nullptr fallback scalar = params_ptr->scalars[0]; }
// Do reduction over multiple broadcasts if necessary ReductionFn<Element> reduction_fn; CUTLASS_PRAGMA_UNROLL for (int i = 1; i < BroadcastCount; ++i) { if (params_ptr->scalar_ptrs[i] != nullptr) { int rest_l_offset = l_coord * size<2>(params_ptr->dScalar[i]); scalar = reduction_fn(scalar, params_ptr->scalar_ptrs[i][rest_l_offset]); } else { // batch stride is ignored for nullptr fallback scalar = reduction_fn(scalar, params_ptr->scalars[i]); } } }
template<class... Xs> CUTLASS_DEVICE void update_scalar(cute::tuple<Xs...>) { // Only support multiple L-modes with fully-broadcast scalar scalar = params_ptr->scalars[0]; valid_scalar = true; }};
// Scalar broadcast// Supports reduction over multiple broadcasts to support fusions such as fp8 scaling factorstemplate< class Element, class StrideMNL_ = Stride<_0,_0,_0>, int BroadcastCount = 1, template <class> class ReductionFn = multiplies>struct Sm90ScalarBroadcastPtrArray { using StrideMNL = StrideMNL_; static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))>); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_0,_0>{});
struct SharedStorage { };
struct Arguments { Element scalars[BroadcastCount] = {}; Element const* scalar_ptrs[BroadcastCount] = {}; Element const* const* scalar_ptr_arrays[BroadcastCount] = {}; StrideMNL dScalar[BroadcastCount] = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter *cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_DEVICE bool is_producer_load_needed() const { // producer load is needed if Element is not void return !cute::is_void_v<Element>; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
// This must be called after update_scalar is called CUTLASS_DEVICE bool is_zero() const { return scalar == Element(0); }
CUTLASS_HOST_DEVICE Sm90ScalarBroadcastPtrArray() { }
CUTLASS_HOST_DEVICE Sm90ScalarBroadcastPtrArray(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) { // Get the scalar for non-batched broadcast if (size<2>(params_ptr->dScalar[0]) == 0) { update_scalar(); } }
Element scalar; Params const* params_ptr;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { // Always refresh scalar with the current group index so per-group // alpha/beta values (provided through pointer arrays) are loaded // correctly even when the L-stride is zero. auto [m_coord, n_coord, k_coord, l_coord] = args.tile_coord_mnkl; update_scalar(l_coord);
return EmptyProducerLoadCallbacks{}; }
struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(Element scalar) : scalar(scalar) {}
Element scalar;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<Element, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Array<Element, FragmentSize> frg_scalar; frg_scalar.fill(scalar);
return frg_scalar; }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto [m_coord, n_coord, k_coord, l_coord] = args.tile_coord_mnkl; update_scalar(l_coord);
return ConsumerStoreCallbacks(scalar); }
private: CUTLASS_DEVICE void update_scalar(int l_coord = 0) { int l_offset = l_coord * size<2>(params_ptr->dScalar[0]);
if (params_ptr->scalar_ptr_arrays[0] != nullptr) { // Pointer-array variant: each entry already points to the scalar of a group. scalar = *(params_ptr->scalar_ptr_arrays[0][l_coord]); } else if (params_ptr->scalar_ptrs[0] != nullptr) { // Strided pointer variant. scalar = params_ptr->scalar_ptrs[0][l_offset]; } else { // Literal fallback. scalar = params_ptr->scalars[0]; }
// Do reduction over multiple broadcasts if necessary ReductionFn<Element> reduction_fn; CUTLASS_PRAGMA_UNROLL for (int i = 1; i < BroadcastCount; ++i) {
if (params_ptr->scalar_ptr_arrays[i] != nullptr) { scalar = reduction_fn(scalar, *(params_ptr->scalar_ptr_arrays[i][l_coord])); } else if (params_ptr->scalar_ptrs[i] != nullptr) { int rest_l_offset = l_coord * size<2>(params_ptr->dScalar[i]); scalar = reduction_fn(scalar, params_ptr->scalar_ptrs[i][rest_l_offset]); } else { scalar = reduction_fn(scalar, params_ptr->scalars[i]); } } }};
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace detail {
template <int StagesC, class CtaTileShapeMNK, class EpilogueTile>[[deprecated("row broadcast only uses 0 stages")]] constexpr intcompute_row_broadcast_stages() { return ceil_div(StagesC, size<1>(zipped_divide(make_layout(take<0,2>(CtaTileShapeMNK{})), EpilogueTile{}))) + 1;}
}
// Row vector broadcasttemplate< int Stages, class CtaTileShapeMNK, class ElementInput_, class ElementCompute = cute::remove_pointer_t<ElementInput_>, class StrideMNL_ = Stride<_0,_1,_0>, int Alignment = 128 / sizeof_bits_v<cute::remove_pointer_t<ElementInput_>>, bool EnableNullptr = true // Fallback scalar broadcast for nullptr params>struct Sm90RowBroadcast { using StrideMNL = StrideMNL_; // Get base element input type. using ElementInput = cute::remove_pointer_t<ElementInput_>; // Check if input is an array of pointers. static constexpr bool IsArrayOfPointers = is_same_v<ElementInput*, ElementInput_>; using PtrRowType = cute::conditional_t<IsArrayOfPointers, ElementInput const* const*, ElementInput const*>;
static_assert(Stages == 0, "Row broadcast doesn't support smem pipelining");
static constexpr bool IsDynamicBroadcast = is_same_v<remove_cvref_t<decltype(get<1>(StrideMNL{}))>, bool>; // row vector or scalar broadcast static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))> || IsDynamicBroadcast); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_0,_1>{} || IsDynamicBroadcast);
struct SharedStorage { array_aligned<ElementInput, size<1>(CtaTileShapeMNK{})> smem; };
struct Arguments { PtrRowType ptr_row = nullptr; ElementInput null_default = ElementInput(0); StrideMNL dRow = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90RowBroadcast() { }
CUTLASS_HOST_DEVICE Sm90RowBroadcast(Params const& params, SharedStorage const& shared_storage) : params(params), is_zero_(false), smem(const_cast<ElementInput*>(shared_storage.smem.data())) { auto const& [stride_M, stride_N, stride_L] = params.dRow; // Nullptr default if (EnableNullptr && params.ptr_row == nullptr) { is_zero_ = params.null_default == ElementCompute(0); } // Dynamic non-batched scalar broadcast else if (IsDynamicBroadcast && stride_N == bool(0) && stride_L == repeat_like(stride_L, 0)) { if constexpr (!IsArrayOfPointers) { is_zero_ = params.ptr_row[0] == ElementInput(0); } } }
Params params; bool is_zero_ = false; ElementInput *smem = nullptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_DEVICE bool is_zero() const { return is_zero_; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template <class GS_GTensor, class GS_STensor, class GS_CTensor, class Tiled_G2S, class SR_STensor, class SR_RTensor, class Residue> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( GS_GTensor tGS_gRow_, GS_STensor tGS_sRow_, GS_CTensor tGS_cRow_, Tiled_G2S tiled_g2s_, SR_STensor tSR_sRow_, SR_RTensor tSR_rRow_, Residue residue_cRow_, Params const& params_) : tGS_gRow(tGS_gRow_) , tGS_sRow(tGS_sRow_) , tGS_cRow(tGS_cRow_) , tiled_G2S(tiled_g2s_) , tSR_sRow(tSR_sRow_) , tSR_rRow(tSR_rRow_) , residue_cRow(residue_cRow_) , params(params_) { }
GS_GTensor tGS_gRow; // (CPY,CPY_M,CPY_N) GS_STensor tGS_sRow; // (CPY,CPY_M,CPY_N) GS_CTensor tGS_cRow; // (CPY,CPY_M,CPY_N) Tiled_G2S tiled_G2S;
SR_STensor tSR_sRow; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) SR_RTensor tSR_rRow; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N)
Residue residue_cRow; // (m, n) Params const& params;
CUTLASS_DEVICE void begin() { bool is_nullptr = EnableNullptr && params.ptr_row == nullptr;
Tensor tGS_gRow_flt = filter_zeros(tGS_gRow); Tensor tGS_sRow_flt = filter_zeros(tGS_sRow); Tensor tGS_cRow_flt = filter_zeros(tGS_cRow, tGS_gRow.stride());
for (int i = 0; i < size(tGS_gRow_flt); ++i) { if (get<1>(tGS_cRow_flt(i)) >= size<1>(CtaTileShapeMNK{})) { continue; // OOB of SMEM, } if (not is_nullptr && elem_less(tGS_cRow_flt(i), residue_cRow)) { tGS_sRow_flt(i) = tGS_gRow_flt(i); // issue async gmem to smem load } else { tGS_sRow_flt(i) = params.null_default; // fill OOB values so smem to RF load can issue without predication } } }
CUTLASS_DEVICE bool begin_sync_needed() const { return true; // Ensure visibility of async gmem to smem loads }
CUTLASS_DEVICE void begin_loop(int epi_m, int epi_n) { if (epi_m == 0) { // Assumes M-major subtile loop Tensor tSR_sRow_flt = filter_zeros(tSR_sRow(_,_,_,epi_m,epi_n)); Tensor tSR_rRow_flt = make_tensor_like<ElementInput>(tSR_sRow_flt); copy_aligned(tSR_sRow_flt, tSR_rRow_flt);
constexpr int FrgSize = size(tSR_rRow_flt); using FrgInput = Array<ElementInput, FrgSize>; using FrgCompute = Array<ElementCompute, FrgSize>; using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FrgSize>;
Tensor tSR_rRow_input_frg = recast<FrgInput>(coalesce(tSR_rRow_flt)); Tensor tSR_rRow_compute_frg = recast<FrgCompute>(filter(tSR_rRow)); ConvertInput convert_input{};
tSR_rRow_compute_frg(_0{}) = convert_input(tSR_rRow_input_frg(_0{})); } }
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<ElementCompute, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Array<ElementCompute, FragmentSize> frg_row;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { frg_row[i] = tSR_rRow(epi_v * FragmentSize + i); }
return frg_row; } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; using ThreadCount = decltype(size(args.tiled_copy));
auto layout_N = [&] () CUTLASS_LAMBDA_FUNC_INLINE { auto shape_N = get<1>(args.problem_shape_mnkl); if constexpr (IsDynamicBroadcast) { auto stride_N = repeat_like(shape_N, int(0)); if (get<1>(params.dRow) == bool(1)) { stride_N = transform_leaf(compact_major<LayoutLeft>(shape_N), [] (auto const& stride) { return static_cast<int>(stride); } ); } return make_layout(shape_N, stride_N); } else { return make_layout(shape_N); } }();
auto layout_M = make_layout(M, repeat_like(M, _0{})); auto layout_L = make_layout(L, get<2>(params.dRow)); ElementInput const* ptr_row = nullptr; if constexpr(IsArrayOfPointers) { if (!(EnableNullptr && params.ptr_row == nullptr)) { ptr_row = params.ptr_row[l]; } } else { ptr_row = params.ptr_row; } Tensor mRow = make_tensor(make_gmem_ptr(ptr_row), make_layout(layout_M,layout_N,layout_L)); Tensor gRow = local_tile(mRow(_,_,l), take<0,2>(args.tile_shape_mnk), make_coord(m, n)); // (CTA_M, CTA_N) Tensor sRow = make_tensor(make_smem_ptr(smem), make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{})), make_shape(_0{}, _1{})); // (CTA_M, CTA_N) //// G2S: Gmem to Smem auto tiled_g2s = make_tiled_copy(Copy_Atom<DefaultCopy, ElementInput>{}, Layout< Shape<_1, ThreadCount>, Stride<_0, _1>>{}, Layout<_1>{}); auto thr_g2s = tiled_g2s.get_slice(args.thread_idx); Tensor tGS_gRow = thr_g2s.partition_S(gRow); Tensor tGS_sRow = thr_g2s.partition_D(sRow);
//// G2S: Coord Tensor tGS_cRow = thr_g2s.partition_S(args.cD);
//// S2R: Smem to Reg Tensor tSR_sRow = sm90_partition_for_epilogue<ReferenceSrc>(sRow, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tSR_rRow = make_tensor_like<ElementCompute>(take<0,3>(tSR_sRow)); // (CPY,CPY_M,CPY_N)
return ConsumerStoreCallbacks( tGS_gRow, tGS_sRow, tGS_cRow, tiled_g2s, tSR_sRow, tSR_rRow, args.residue_cD, params); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Column vector broadcasttemplate< int Stages, class CtaTileShapeMNK, class ElementInput_, class ElementCompute = cute::remove_pointer_t<ElementInput_>, class StrideMNL_ = Stride<_1,_0,_0>, int Alignment = 128 / sizeof_bits_v<cute::remove_pointer_t<ElementInput_>>, bool EnableNullptr = true // Fallback scalar broadcast for nullptr params>struct Sm90ColBroadcast { using StrideMNL = StrideMNL_; // Get base element input type. using ElementInput = cute::remove_pointer_t<ElementInput_>; // Check if input is an array of pointers. static constexpr bool IsArrayOfPointers = is_same_v<ElementInput*, ElementInput_>; using PtrColType = cute::conditional_t<IsArrayOfPointers, ElementInput const* const*, ElementInput const*>;
static_assert(Stages == 0, "Column broadcast doesn't support smem pipelining");
static constexpr bool IsDynamicBroadcast = is_same_v<remove_cvref_t<decltype(get<0>(StrideMNL{}))>, bool>; // Column vector or scalar broadcast static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))> || IsDynamicBroadcast); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_1,_0>{} || IsDynamicBroadcast);
// Accumulator distributes col elements evenly amongst threads so we can just directly load from gmem struct SharedStorage { };
struct Arguments { PtrColType ptr_col = nullptr; ElementInput null_default = ElementInput(0); StrideMNL dCol = {}; };
struct Params { PtrColType ptr_col = nullptr; ElementCompute null_default = ElementCompute(0); StrideMNL dCol = {}; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return {args.ptr_col, ElementCompute(args.null_default), args.dCol}; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_DEVICE bool is_zero() const { return is_zero_; }
CUTLASS_HOST_DEVICE Sm90ColBroadcast() { }
CUTLASS_HOST_DEVICE Sm90ColBroadcast(Params const& params, SharedStorage const& shared_storage) : params(params), is_zero_(false) { auto const& [stride_M, stride_N, stride_L] = params.dCol; // Nullptr default if (EnableNullptr && params.ptr_col == nullptr) { is_zero_ = params.null_default == ElementCompute(0); } // Dynamic non-batched scalar broadcast else if (IsDynamicBroadcast && stride_M == bool(0) && stride_L == repeat_like(stride_L, 0)) { if constexpr (!IsArrayOfPointers) { is_zero_ = params.ptr_col[0] == ElementInput(0); } } }
Params params; bool is_zero_;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template<class GTensor, class RTensor, class CTensor, class ThrResidue> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(GTensor tCgCol_, RTensor tCrCol_, CTensor tCcCol_, ThrResidue residue_tCcCol_, Params const& params_) : tCgCol(tCgCol_), tCrCol(tCrCol_), tCcCol(tCcCol_), residue_tCcCol(residue_tCcCol_), params(params_) { if (EnableNullptr && params.ptr_col == nullptr) { fill(tCrCol, params.null_default); } }
GTensor tCgCol; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) RTensor tCrCol; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) CTensor tCcCol; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) ThrResidue residue_tCcCol; Params const& params;
CUTLASS_DEVICE void begin() { if (EnableNullptr && params.ptr_col == nullptr) { return; }
// Filter so we don't issue redundant copies over stride-0 modes // (only works if 0-strides are in same location, which is by construction) Tensor tCgCol_flt = filter_zeros(tCgCol); Tensor tCrCol_flt = make_tensor_like<ElementInput>(filter_zeros(tCrCol)); Tensor tCcCol_flt = filter_zeros(tCcCol, tCgCol.stride());
constexpr auto MCL = decltype(max_common_layout(tCgCol_flt, tCrCol_flt)){}; constexpr int V = cute::min(Alignment, size(MCL)); if constexpr (V > 1) { using VecType = uint_bit_t<V * sizeof_bits_v<ElementInput>>; Tensor tCgCol_vec = recast<VecType>(coalesce(tCgCol_flt)); Tensor tCrCol_vec = recast<VecType>(coalesce(tCrCol_flt)); Tensor tCcCol_vec = tensor<1>(zipped_divide(tCcCol_flt, MCL.compose(Int<V>{}))); Tensor tCpCol_vec = cute::lazy::transform(tCcCol_vec, [&](auto const& c){ return elem_less(c, residue_tCcCol); }); copy_if(tCpCol_vec, tCgCol_vec, tCrCol_vec); } else { Tensor tCpCol_flt = cute::lazy::transform(tCcCol_flt, [&](auto const& c){ return elem_less(c, residue_tCcCol); }); copy_if(tCpCol_flt, tCgCol_flt, tCrCol_flt); }
constexpr int FrgSize = size(tCrCol_flt); using FrgInput = Array<ElementInput, FrgSize>; using FrgCompute = Array<ElementCompute, FrgSize>; using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FrgSize>;
Tensor tCrCol_input_frg = recast<FrgInput>(coalesce(tCrCol_flt)); Tensor tCrCol_compute_frg = recast<FrgCompute>(filter(tCrCol)); ConvertInput convert_input{};
tCrCol_compute_frg(_0{}) = convert_input(tCrCol_input_frg(_0{})); }
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE Array<ElementCompute, FragmentSize> visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Array<ElementCompute, FragmentSize> frg_col; Tensor tCrCol_mn = tCrCol(_,_,_,epi_m,epi_n);
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { frg_col[i] = tCrCol_mn(epi_v * FragmentSize + i); }
return frg_col; }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; auto layout_M = [&] () CUTLASS_LAMBDA_FUNC_INLINE { auto shape_M = get<0>(args.problem_shape_mnkl); if constexpr (IsDynamicBroadcast) { auto stride_M = repeat_like(shape_M, int(0)); if (get<0>(params.dCol) == bool(1)) { stride_M = transform_leaf(compact_major<LayoutLeft>(shape_M), [] (auto const& stride) { return static_cast<int>(stride); } ); } return make_layout(shape_M, stride_M); } else { return make_layout(shape_M); } }();
auto layout_N = make_layout(N, repeat_like(N, _0{})); auto layout_L = make_layout(L, get<2>(params.dCol)); ElementInput const* ptr_col = nullptr; if constexpr(IsArrayOfPointers) { if (!(EnableNullptr && params.ptr_col == nullptr)) { ptr_col = params.ptr_col[l]; } } else { ptr_col = params.ptr_col; } Tensor mCol = make_tensor(make_gmem_ptr(ptr_col), make_layout(layout_M,layout_N,layout_L)); Tensor tCgCol = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) mCol, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx);
Tensor mCol_static = make_tensor(make_gmem_ptr(ptr_col), make_layout(make_layout(M),layout_N,layout_L)); Tensor tCgCol_static = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) mCol_static, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrCol = make_tensor_like<ElementCompute>(tCgCol_static); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N)
return ConsumerStoreCallbacks(tCgCol, tCrCol, args.tCcD, args.residue_tCcD, params); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Batch matrix broadcast// Only need to redefine this if we can multicast across cluster Ltemplate < int Stages, class EpilogueTile, class Element, class StrideMNL, class SmemLayoutAtom, class CopyOpS2R, int Alignment = 128 / sizeof_bits_v<Element>, bool EnableNullptr = true // Fallback scalar broadcast for nullptr params>using Sm90MatrixBroadcast = Sm90AuxLoad<Stages, EpilogueTile, Element, StrideMNL, SmemLayoutAtom, CopyOpS2R, EnableNullptr>;
namespace detail {
template <typename Operation, typename = void>struct IsScalarBroadcast { static constexpr bool value = false;};
template <typename Operation>struct IsScalarBroadcast<Operation, cute::enable_if_t<is_same_v<decltype(take<0,2>(typename Operation::StrideMNL{})), Stride<_0,_0>>>> { static constexpr bool value = true;};
}
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree store operations for the sm90 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/workspace.h"
#include "cute/tensor.hpp"#include "sm90_visitor_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// Elementwise Store Operations///////////////////////////////////////////////////////////////////////////////////////////////////
template < int Stages, class EpilogueTile, class Element, FloatRoundStyle RoundStyle, class StrideMNL, class SmemLayoutAtom, class CopyOpR2S, int Alignment = 128 / sizeof_bits_v<Element>, bool EnableNullptr = true // Noop on nullptr params>struct Sm90AuxStore { using ElementAux = Element; static_assert(Alignment * sizeof_bits_v<Element> % 128 == 0, "sub-16B alignment not supported yet");
constexpr static bool is_m_major = epilogue::collective::detail::is_m_major<StrideMNL>(); // Find the max contiguous layout usable by TMA (if EpilogueTile is a non-compact tiler) using SmemShapeTma = decltype(make_shape( max_common_vector(make_layout(get<0>(EpilogueTile{})),make_layout(get<0>(EpilogueTile{}))), max_common_vector(make_layout(get<1>(EpilogueTile{})),make_layout(get<1>(EpilogueTile{}))))); using SmemLayoutTma = decltype(tile_to_shape( SmemLayoutAtom{}, SmemShapeTma{}, cute::conditional_t<is_m_major, Step<_2,_1>, Step<_1,_2>>{} )); using SmemLayout = decltype(tile_to_shape( SmemLayoutTma{}, make_shape(size<0>(shape(EpilogueTile{})), size<1>(shape(EpilogueTile{})), Int<Stages>{}), cute::conditional_t<is_m_major, Step<_2,_1,_3>, Step<_1,_2,_3>>{} ));
struct SharedStorage { alignas(cutlass::detail::alignment_for_swizzle(SmemLayout{})) array_aligned<Element, size(SmemLayout{})> smem_aux; };
struct Arguments { Element* ptr_aux = nullptr; StrideMNL dAux = {}; };
struct Params { using TMA_Aux = decltype(make_tma_copy( SM90_TMA_STORE{}, make_tensor(static_cast<Element*>(nullptr), repeat_like(StrideMNL{}, int32_t(0)), StrideMNL{}), SmemLayoutTma{})); TMA_Aux tma_store_aux; bool is_nullptr = false; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { // Optionally append 1s until problem shape is rank-4 in case its is only rank-3 (MNK) auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl;
bool is_nullptr = false; if constexpr (EnableNullptr) { is_nullptr = args.ptr_aux == nullptr; }
typename Params::TMA_Aux tma_store_aux; if (not is_nullptr) { Tensor tensor_aux = make_tensor(args.ptr_aux, make_layout(make_shape(M,N,L), args.dAux)); tma_store_aux = make_tma_copy(SM90_TMA_STORE{}, tensor_aux, SmemLayoutTma{}); }
return {tma_store_aux, is_nullptr}; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90AuxStore() { }
CUTLASS_HOST_DEVICE Sm90AuxStore(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms), smem_aux(const_cast<Element*>(shared_storage.smem_aux.data())) { }
Params const* params_ptr; Element* smem_aux;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template < class RTensor, class TiledR2S, class STensorR2S, class STensorS2G, class GTensorS2G > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( RTensor&& tC_rAux, TiledR2S tiled_r2s, STensorR2S&& tRS_sAux, STensorS2G&& bSG_sAux, GTensorS2G&& bSG_gAux, Params const* params_ptr) : tiled_r2s(tiled_r2s), tC_rAux(cute::forward<RTensor>(tC_rAux)), tRS_sAux(cute::forward<STensorR2S>(tRS_sAux)), bSG_sAux(cute::forward<STensorS2G>(bSG_sAux)), bSG_gAux(cute::forward<GTensorS2G>(bSG_gAux)), params_ptr(params_ptr) {}
TiledR2S tiled_r2s; RTensor tC_rAux; // (CPY,CPY_M,CPY_N) STensorR2S tRS_sAux; // (R2S,R2S_M,R2S_N,PIPE) STensorS2G bSG_sAux; // (S2G,S2G_M,S2G_N,PIPE) GTensorS2G bSG_gAux; // (S2G,S2G_M,S2G_N,EPI_M,EPI_N) Params const* params_ptr;
template <typename ElementAccumulator, typename ElementInput, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { using ConvertInput = NumericArrayConverter<Element, ElementInput, FragmentSize, RoundStyle>; ConvertInput convert_input{};
Tensor tC_rAux_frg = recast<Array<Element, FragmentSize>>(coalesce(tC_rAux)); // (EPI_V) tC_rAux_frg(epi_v) = convert_input(frg_input);
return frg_input; }
CUTLASS_DEVICE void postreduce(int epi_m, int epi_n, int store_iteration, bool issue_smem_store) { if constexpr (EnableNullptr) { if (params_ptr->is_nullptr) { return; } }
using RLayoutR2S = decltype(cute::layout(TiledR2S{}.get_slice(0).retile_S(RTensor{}))); Tensor tRS_rAux = make_tensor(tC_rAux.data(), RLayoutR2S{}); // (R2S,R2S_M,R2S_N)
if (issue_smem_store) { int store_pipe_index = store_iteration % Stages; copy(tiled_r2s, tRS_rAux, tRS_sAux(_,_,_,store_pipe_index)); } }
CUTLASS_DEVICE void tma_store(int epi_m, int epi_n, int store_iteration, bool issue_tma_store) { if constexpr (EnableNullptr) { if (params_ptr->is_nullptr) { return; } }
if (issue_tma_store) { // Issue the TMA store int store_pipe_index = store_iteration % Stages; copy(params_ptr->tma_store_aux, bSG_sAux(_,_,_,store_pipe_index), bSG_gAux(_,_,_,epi_m,epi_n)); } } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl; Tensor mAux = params_ptr->tma_store_aux.get_tma_tensor(make_shape(M,N,L)); // (M,N,L) Tensor gAux = local_tile(mAux, take<0,2>(args.tile_shape_mnk), make_coord(m,n,l)); // (CTA_M,CTA_N)
Tensor tC_gAux = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) gAux, args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tC_rAux = make_tensor<Element>(take<0,3>(shape(tC_gAux))); // (CPY,CPY_M,CPY_N)
Tensor sAux_epi = cute::as_position_independent_swizzle_tensor( make_tensor(make_smem_ptr(smem_aux), SmemLayout{})); // (EPI_TILE_M,EPI_TILE_N,PIPE) Tensor gAux_epi = flat_divide(gAux, args.epi_tile); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N)
auto tiled_r2s = conditional_return<ReferenceSrc>( make_tiled_copy_S(Copy_Atom<CopyOpR2S,Element>{}, args.tiled_copy), make_tiled_copy_D(Copy_Atom<CopyOpR2S,Element>{}, args.tiled_copy) ); auto tRS_sAux = tiled_r2s.get_slice(args.thread_idx).partition_D(sAux_epi); // (R2S,R2S_M,R2S_N,PIPE)
ThrCopy thrblk_s2g = params_ptr->tma_store_aux.get_slice(_0{}); Tensor bSG_sAux = thrblk_s2g.partition_S(sAux_epi); // (TMA,TMA_M,TMA_N,PIPE) Tensor bSG_gAux = thrblk_s2g.partition_D(gAux_epi); // (TMA,TMA_M,TMA_N,EPI_M,EPI_N)
return ConsumerStoreCallbacks<decltype(tC_rAux), decltype(tiled_r2s), decltype(tRS_sAux), decltype(bSG_sAux), decltype(bSG_gAux)>( cute::move(tC_rAux), tiled_r2s, cute::move(tRS_sAux), cute::move(bSG_sAux), cute::move(bSG_gAux), params_ptr); }};
template < class Element, class EpilogueTile, // Unused FloatRoundStyle RoundStyle, class LayoutOrStrideMNL, class SmemLayoutAtom, // Unused class CopyOpR2S, // Unused int Alignment, bool EnableNullptr>struct Sm90AuxStore< 0, EpilogueTile, Element, RoundStyle, LayoutOrStrideMNL, SmemLayoutAtom, CopyOpR2S, Alignment, EnableNullptr> { using ElementAux = Element; using StrideMNL = cutlass::gemm::TagToStrideC_t<LayoutOrStrideMNL>;
struct SharedStorage { };
struct Arguments { Element* ptr_aux = nullptr; StrideMNL dAux = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return cutlass::Status::kSuccess; }
CUTLASS_HOST_DEVICE Sm90AuxStore() { }
CUTLASS_HOST_DEVICE Sm90AuxStore(Params const& params, SharedStorage const& shared_storage) : params_ptr(¶ms) { }
Params const* params_ptr;
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template< class GTensorR2G, class RTensor, class CTensorR2G, class ProblemShapeMNL > struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( GTensorR2G&& tC_gAux, RTensor&& tC_rAux, CTensorR2G&& tC_cAux, ProblemShapeMNL problem_shape_mnl, Params const* params_ptr) : tC_gAux(cute::forward<GTensorR2G>(tC_gAux)), tC_rAux(cute::forward<RTensor>(tC_rAux)), tC_cAux(cute::forward<CTensorR2G>(tC_cAux)), problem_shape_mnl(problem_shape_mnl), params_ptr(params_ptr) {}
GTensorR2G tC_gAux; RTensor tC_rAux; CTensorR2G tC_cAux; ProblemShapeMNL problem_shape_mnl; Params const* params_ptr;
template <typename ElementAccumulator, typename ElementInput, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { using ConvertInput = NumericArrayConverter<Element, ElementInput, FragmentSize, RoundStyle>; ConvertInput convert_input{};
Tensor tC_rAux_frg = recast<Array<Element, FragmentSize>>(coalesce(tC_rAux)); tC_rAux_frg(epi_v) = convert_input(frg_input);
return frg_input; }
CUTLASS_DEVICE void end_loop(int epi_m, int epi_n) { if constexpr (EnableNullptr) { if (params_ptr->ptr_aux == nullptr) { return; } }
constexpr auto MCL = decltype(max_common_layout(tC_gAux(_,_,_,_0{},_0{}), tC_rAux)){}; constexpr int V = cute::min(Alignment, size(MCL));
Tensor tC_gAux_vec = recast<Array<Element, V>>(coalesce(tC_gAux(_,_,_,epi_m,epi_n))); Tensor tC_rAux_vec = recast<Array<Element, V>>(coalesce(tC_rAux));
Tensor tC_cAux_vec = tensor<1>(zipped_divide(coalesce(tC_cAux(_,_,_,epi_m,epi_n)), MCL.compose(Int<V>{}))); Tensor tC_pAux_vec = cute::lazy::transform(tC_cAux_vec, [&](auto const& c){ return elem_less(c, problem_shape_mnl); });
copy_if(tC_pAux_vec, tC_rAux_vec, tC_gAux_vec); } };
template < bool ReferenceSrc, class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) {
auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl;
auto problem_shape_mnl = make_shape(M,N,L);
// Gmem Tensor Tensor mAux = make_tensor( make_gmem_ptr(params_ptr->ptr_aux), make_shape(M,N,L), params_ptr->dAux ); Tensor tC_gAux = sm90_partition_for_epilogue<ReferenceSrc>( mAux, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx);
// Register Tensor Tensor tC_rAux = make_tensor<Element>(take<0,3>(shape(tC_gAux)));
// Predication support Tensor coordAux = make_identity_tensor(shape(mAux)); Tensor tC_cAux = sm90_partition_for_epilogue<ReferenceSrc>( coordAux, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx);
return ConsumerStoreCallbacks<decltype(tC_gAux), decltype(tC_rAux), decltype(tC_cAux), decltype(problem_shape_mnl)>( cute::move(tC_gAux), cute::move(tC_rAux), cute::move(tC_cAux), problem_shape_mnl, params_ptr );
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////// Reduction Store Operations///////////////////////////////////////////////////////////////////////////////////////////////////
// Scalar reductiontemplate < template <class> class RegReduceFn, template <class> class GmemReduceFn, class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, class StrideMNL = Stride<_0,_0,_0>, bool EnableNullptr = true // Noop on nullptr params>struct Sm90ScalarReduction {private: static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))>); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_0,_0>{}); static constexpr bool IsAtomic = is_atomic<GmemReduceFn<ElementCompute>>::value; static_assert(IsAtomic, "non-atomic scalar reduction not supported yet");
public: struct SharedStorage { };
struct Arguments { ElementOutput* ptr_scalar = nullptr; ElementCompute reduction_identity = ElementCompute(0); StrideMNL dScalar = {}; };
using Params = Arguments;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return args; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { #if !defined(CUTLASS_SKIP_REDUCTION_INIT) if constexpr (IsAtomic) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; Layout mScalar_layout = make_layout(make_shape(M,N,L), args.dScalar); if (args.ptr_scalar != nullptr) { return fill_workspace(args.ptr_scalar, ElementOutput(args.reduction_identity), cosize(mScalar_layout), stream, cuda_adapter); } } #endif
return cutlass::Status::kSuccess; }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_HOST_DEVICE Sm90ScalarReduction() { }
CUTLASS_HOST_DEVICE Sm90ScalarReduction(Params const& params, SharedStorage const& shared_storage) : params(params) { }
Params const params;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template<class CTensor, class ThrResidue> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( int l_coord, CTensor tCcScalar, ThrResidue residue_tCcScalar, Params const& params) : scalar(params.reduction_identity), l_coord(l_coord), tCcScalar(tCcScalar), residue_tCcScalar(residue_tCcScalar), params(params) {}
ElementCompute scalar; int l_coord; CTensor tCcScalar; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) ThrResidue residue_tCcScalar; Params params;
template <typename ElementAccumulator, typename ElementInput, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { if constexpr (EnableNullptr) { if (params.ptr_scalar == nullptr) { return frg_input; } }
using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; using ReduceInput = RegReduceFn<ElementCompute>; ConvertInput convert_input{}; ReduceInput reduce_input{};
Array frg_I = convert_input(frg_input); Tensor tCcScalar_mn = tCcScalar(_,_,_,epi_m,epi_n);
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { if (elem_less(tCcScalar_mn(epi_v * FragmentSize + i), residue_tCcScalar)) { scalar = reduce_input(scalar, frg_I[i]); } }
return frg_input; }
CUTLASS_DEVICE void end() { if constexpr (EnableNullptr) { if (params.ptr_scalar == nullptr) { return; } }
using ConvertI = NumericConverter<ElementOutput, ElementCompute, RoundStyle>; using ReduceInput = GmemReduceFn<ElementOutput>;
ConvertI convert_I{}; ReduceInput reduce_input{};
ElementOutput* ptr_scalar = params.ptr_scalar + l_coord * get<2>(params.dScalar); reduce_input(ptr_scalar, convert_I(scalar)); }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { return ConsumerStoreCallbacks<decltype(args.tCcD), decltype(args.residue_tCcD)>( get<3>(args.tile_coord_mnkl), args.tCcD, args.residue_tCcD, params); }
};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Row vector reductiontemplate < template <class> class RegReduceFn, template <class> class ShuffleReduceFn, template <class> class GmemReduceFn, int Stages, class CtaTileShapeMNK, class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, class StrideMNL = Stride<_0,_1,_0>, int Alignment = 128 / sizeof_bits_v<ElementOutput>, bool EnableNullptr = true, // Noop on nullptr params // If this is false, ptr_row is assumed to point to a compact n-major (ceil_div(M,CTA_M), round_nearest(N,CTA_N), L) // tensor of ElementCompute. It is the user's responsibility to reduce this to a (N, L) tensor of ElementOutput bool FinalReduction = true, // False means skip OOB predication if OOB inputs are known to be the reduction identity bool VisitCheckOOB = true, // Indicate the parameter order when calling RegReduceFn // Seq length equals the number of RegReduceFn parameters // No.0 represents tCrRow; No.1 and subsequent numbers sequentially represent frg_inputs in `visit` class RegReduceSeq = cute::seq<0, 1>>struct Sm90RowReduction {private: static_assert(Stages == 0, "Smem usage not supported yet"); static_assert(Alignment * sizeof_bits_v<ElementOutput> % 128 == 0, "sub-16B alignment not supported yet"); static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))>); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_0,_1>{}); static constexpr bool IsAtomic = is_atomic<GmemReduceFn<ElementCompute>>::value; static_assert(not (IsAtomic && not FinalReduction), "atomic reduction must be final");
public: struct SharedStorage { };
struct Arguments { void* ptr_row = nullptr; // ElementOutput* if FinalReduction, else ElementCompute* ElementCompute reduction_identity = ElementCompute(0); StrideMNL dRow = {}; };
struct Params { void* ptr_row = nullptr; ElementCompute reduction_identity = ElementCompute(0); StrideMNL dRow = {}; ElementCompute* reduction_buffer = nullptr; int* tile_counters = nullptr; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { ElementCompute* reduction_buffer; int* tile_counters = nullptr; if constexpr (IsAtomic) { reduction_buffer = nullptr; } else if constexpr (FinalReduction) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{}; size_t tile_counters_offset = product(ceil_div(make_shape(size<>(M), size<>(N), L), make_shape(tile_M, tile_N))) * tile_N * sizeof(ElementCompute); tile_counters_offset = round_nearest(tile_counters_offset, MinWorkspaceAlignment);
reduction_buffer = reinterpret_cast<ElementCompute*>(workspace); tile_counters = reinterpret_cast<int*>(reinterpret_cast<uint8_t*>(workspace) + tile_counters_offset); } else { reduction_buffer = reinterpret_cast<ElementCompute*>(args.ptr_row); }
return { args.ptr_row, args.reduction_identity, args.dRow, reduction_buffer, tile_counters }; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { if constexpr (IsAtomic || not FinalReduction) { return 0; }
size_t workspace_size = 0; auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{}; // Increment by size of reduction buffer workspace_size += product(ceil_div(make_shape(size<>(M),size<>(N),L), make_shape(tile_M, tile_N))) * tile_N * sizeof(ElementCompute); // Align and increment by size of tile counters workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment); workspace_size += cute::ceil_div(size<>(N), tile_N) * sizeof(int); return workspace_size; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { if constexpr (IsAtomic) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; Layout mRow_layout = make_layout(make_shape(size<>(M),size<>(N),size<>(L)), args.dRow); if (args.ptr_row != nullptr) { return fill_workspace(args.ptr_row, ElementOutput(args.reduction_identity), cosize(mRow_layout), stream, cuda_adapter); } return Status::kSuccess; } else if constexpr (FinalReduction) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{}; size_t tile_counters_offset = product(ceil_div(make_shape(size<>(M),size<>(N),L), make_shape(tile_M, tile_N))) * tile_N * sizeof(ElementCompute); tile_counters_offset = round_nearest(tile_counters_offset, MinWorkspaceAlignment);
int* tile_counters = reinterpret_cast<int*>(reinterpret_cast<uint8_t*>(workspace) + tile_counters_offset); size_t tile_counters_size = cute::ceil_div(size<>(N), tile_N) * sizeof(int); return zero_workspace(tile_counters, tile_counters_size, stream, cuda_adapter); } else { return Status::kSuccess; } }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_HOST_DEVICE Sm90RowReduction() { }
CUTLASS_HOST_DEVICE Sm90RowReduction(Params const& params, SharedStorage const& shared_storage) : params(params) { }
Params params;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template<class ArgsTuple> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(ArgsTuple&& args_tuple, Params const& params) : args_tuple(cute::forward<ArgsTuple>(args_tuple)), params(params) {}
ArgsTuple args_tuple; Params const& params; bool do_final_reduction = false;
template <typename ElementAccumulator, typename... ElementInputs, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInputs, FragmentSize> const&... frg_inputs) { if constexpr (EnableNullptr) { if (params.ptr_row == nullptr) { return cute::get<0>(cute::make_tuple(frg_inputs...)); } }
auto& [ref_src, tCrRow, tCcRow, gRow_l, cRow, gBuf_ml, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, tile_coord_mnkl, residue_cRow, residue_tCcRow, epi_tile, tiled_copy, thread_idx] = args_tuple; Tensor tCrRow_mn = tCrRow(_,_,_,epi_m,epi_n); Tensor tCcRow_mn = tCcRow(_,_,_,epi_m,epi_n);
if constexpr (VisitCheckOOB) { using ReduceInput = RegReduceFn<ElementCompute>; ReduceInput reduce_input{};
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { if (elem_less(tCcRow_mn(epi_v * FragmentSize + i), residue_tCcRow)) { ElementCompute& tCrRow_vmn = tCrRow_mn(epi_v * FragmentSize + i); tCrRow_vmn = transform_apply(cute::make_tuple(frg_inputs...), [&] (auto&& frg_input) { return ElementCompute(frg_input[i]); }, [&] (auto&&... cvt_frg_inputs) { auto frg_compute_tuple = cute::make_tuple(tCrRow_vmn, cvt_frg_inputs...); return cute::detail::apply(frg_compute_tuple, reduce_input, RegReduceSeq{}); }); } } } else { constexpr int RegFragSize = cute::max(1, static_cast<int>(sizeof(uint32_t) / sizeof(ElementCompute))); using ReduceInput = RegReduceFn<Array<ElementCompute, RegFragSize>>; ReduceInput reduce_input{}; Tensor tCrRow_mn_frg = recast<Array<ElementCompute, RegFragSize>>(tCrRow_mn);
constexpr int RegFragArraySize = FragmentSize / RegFragSize; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < RegFragArraySize; ++i) { Array<ElementCompute, RegFragSize>& tCrRow_vmn_frg = tCrRow_mn_frg(epi_v * RegFragArraySize + i); tCrRow_vmn_frg = transform_apply(cute::make_tuple(frg_inputs...), [&] (auto&& frg_input) { using ElementInput = typename cute::remove_cvref_t<decltype(frg_input)>::Element; using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, RegFragSize, RoundStyle>; using RegFragArr = Array<Array<ElementCompute, RegFragSize>, RegFragArraySize>; ConvertInput convert_input{}; return convert_input(reinterpret_cast<RegFragArr&>(frg_input)[i]); }, [&] (auto&&... cvt_frg_inputs) { auto frg_compute_tuple = cute::make_tuple(tCrRow_vmn_frg, cvt_frg_inputs...); return cute::detail::apply(frg_compute_tuple, reduce_input, RegReduceSeq{}); }); } } return cute::get<0>(cute::make_tuple(frg_inputs...)); }
template <class STensor, class SyncFn, class VTensor> CUTLASS_DEVICE void reduce(STensor&& smem_buffer, SyncFn const& sync_fn, int epi_m, int epi_n, bool is_last_iteration, VTensor visit_results) { if (not is_last_iteration) { return; }
auto& [ref_src, tCrRow, tCcRow, gRow_l, cRow, gBuf_ml, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, tile_coord_mnkl, residue_cRow, residue_tCcRow, epi_tile, tiled_copy, thread_idx] = args_tuple; auto [m, n, k, l] = tile_coord_mnkl; constexpr bool ReferenceSrc = decltype(ref_src)::value; if constexpr (EnableNullptr) { if (params.ptr_row == nullptr) { return; } }
// fully OOB CTA in partially OOB cluster if (not elem_less(cRow(_0{},_0{}), residue_cRow)) { return; }
int lane_m = get<0>(lane_mn); [[maybe_unused]] bool is_reduced_lane = lane_m == 0;
// // 1. Warp shuffle reduction // using FragmentShuffle = Array<ElementCompute, sizeof(uint64_t) / sizeof(ElementCompute)>; Tensor tCrRow_frg = recast<FragmentShuffle>(filter(tCrRow)); using ReduceShuffle = ShuffleReduceFn<FragmentShuffle>; ReduceShuffle reduce_shuffle{};
auto FrgSizePerLaneM = size(tCrRow_frg) / size<0>(lane_layout_MN); constexpr bool SwapShuffle = FrgSizePerLaneM > 0;
// // Swap Shuffle // // The normal way to reduction among threads: // use shuffle to let *** the first half of threads *** have *** whole data *** from the second half of threads. // After each step of reduction, a half of threads won't work in the following steps. // That is, as the reduction progresses, the efficiency of shuffle & reduction instructions gradually change from 1/2, 1/4 to 1/32 (the worst case). // // To overcome this shortcoming, for a NxN matrix to be reduced among N threads as a 1XN vectors, // we use swap & shuffle aiming to let *** each half of threads *** have *** a half of data *** from the other half of threads. // After reduction, each half of threads should deal with a (N/2)x(N/2) sub-matrix independently in the following step. // We can recursively do this until the problem size is 1. // if constexpr (SwapShuffle) { // for a NxN matrix to be reduced among N threads as a 1XN vectors Tensor tCrRow_frg_ = logical_divide(tCrRow_frg, FrgSizePerLaneM); // (FrgSizePerLaneM, M) CUTLASS_PRAGMA_UNROLL for (int m = size<1>(tCrRow_frg_) / 2; m > 0; m /= 2) { CUTLASS_PRAGMA_UNROLL for (int r = 0; r < m; ++r) { auto frg_A = tCrRow_frg_(_,r); auto frg_B = tCrRow_frg_(_,r + m); CUTLASS_PRAGMA_UNROLL for (int v = 0; v < size(frg_A); ++v) { // Step1: swap if (not (lane_m & m)) { // the first half of threads swap fragments from the first half of data to the second cutlass::swap(frg_A(v), frg_B(v)); }
// Step2: shuffle uint64_t frg_shfl = reinterpret_cast<uint64_t&>(frg_A(v)); // each half of threads get a half of data from the other half of threads frg_shfl = __shfl_xor_sync(0xFFFFFFFF, frg_shfl, lane_layout_MN(m, _0{}));
// Step3: reduction frg_A(v) = reduce_shuffle(frg_B(v), reinterpret_cast<FragmentShuffle&>(frg_shfl)); } } } } else { CUTLASS_PRAGMA_UNROLL for (int reduction_rows = size<0>(lane_layout_MN) / 2; reduction_rows > 0; reduction_rows /= 2) { CUTLASS_PRAGMA_UNROLL for (int frg_idx = 0; frg_idx < size(tCrRow_frg); ++frg_idx) { uint64_t frg_shfl = reinterpret_cast<uint64_t&>(tCrRow_frg(frg_idx)); frg_shfl = __shfl_down_sync(0xFFFFFFFF, frg_shfl, lane_layout_MN(reduction_rows, _0{})); tCrRow_frg(frg_idx) = reduce_shuffle(tCrRow_frg(frg_idx), reinterpret_cast<FragmentShuffle&>(frg_shfl)); } } }
// // 2. Atomic reduction // if constexpr (IsAtomic) { // Filter so we don't issue redunant copies over stride-0 modes Tensor tCrRow_flt = filter_zeros(tCrRow); Tensor tCcRow_flt = make_tensor(tCcRow.data(), make_layout(tCrRow_flt.shape(), tCcRow.stride())); auto FltFrgSizePerLaneM = size(tCrRow_flt) / size<0>(lane_layout_MN);
Tensor tCgRow = sm90_partition_for_epilogue<ReferenceSrc>(gRow_l(_,_,l), epi_tile, tiled_copy, thread_idx); Tensor tCgRow_flt = filter_zeros(tCgRow); // NOTE: atomic reduction is performed in the output type using ConvertOutput = NumericConverter<ElementOutput, ElementCompute, RoundStyle>; using ReduceOutput = GmemReduceFn<ElementOutput>; ConvertOutput convert_output{}; ReduceOutput reduce_output{};
if constexpr (SwapShuffle) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FltFrgSizePerLaneM; ++i) { int idx = lane_m * FltFrgSizePerLaneM + i; // Only care about OOB for N mode if (get<1>(tCcRow_flt(idx)) < get<1>(residue_tCcRow)) { reduce_output(&tCgRow_flt(idx), convert_output(tCrRow_flt(i))); } } } else { if (is_reduced_lane) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrRow_flt); ++i) { if (elem_less(tCcRow_flt(i), residue_tCcRow)) { reduce_output(&tCgRow_flt(i), convert_output(tCrRow_flt(i))); } } } } sync_fn(); }
// // 2. One warp in M, skip threadblock smem reduction // else if constexpr (decltype(size<0>(warp_layout_MN))::value <= 1) { // Dump warp reduction to gmem workspace using ElementGmem = cute::conditional_t<FinalReduction, ElementCompute volatile, ElementCompute>; Tensor tCgBuf = sm90_partition_for_epilogue<ReferenceSrc>(gBuf_ml(_,_,m,l), epi_tile, tiled_copy, thread_idx);
if constexpr (SwapShuffle) { Tensor tCrRow_flt = filter(tCrRow); Tensor tCgBuf_flt = recast<ElementGmem>(filter(tCgBuf)); auto FltFrgSizePerLaneM = size(tCrRow_flt) / size<0>(lane_layout_MN); Tensor tCgBuf_flt_ = logical_divide(tCgBuf_flt, FltFrgSizePerLaneM); // (FltFrgSizePerLaneM, M) Tensor tCrRow_flt_ = logical_divide(tCrRow_flt, FltFrgSizePerLaneM); // (FltFrgSizePerLaneM, M) copy_aligned(tCrRow_flt_(_,_0{}), tCgBuf_flt_(_,lane_m)); } else { if (is_reduced_lane) { copy_aligned(tCrRow, recast<ElementGmem>(tCgBuf)); } } sync_fn(); }
// // 2. Multiple warps in M, do threadblock smem reduction // else { Tensor sBuf = make_tensor(make_smem_ptr<ElementCompute>(raw_pointer_cast(smem_buffer.data())), sBuf_layout); static_assert(decltype(cosize(sBuf.layout()))::value * sizeof(ElementCompute) <= decltype(cosize(smem_buffer.layout()))::value * sizeof(typename remove_cvref_t<STensor>::value_type), "smem reduction buffer not large enough, use a larger epilogue tile"); sync_fn();
// Dump warp reduction to smem workspace Tensor tCsBuf = sm90_partition_for_epilogue<ReferenceSrc>(sBuf(_,_,get<0>(warp_mn)), epi_tile, tiled_copy, thread_idx);
if constexpr (SwapShuffle) { Tensor tCrRow_flt = filter(tCrRow); Tensor tCsBuf_flt = filter(tCsBuf); auto FltFrgSizePerLaneM = size(tCrRow_flt) / size<0>(lane_layout_MN); Tensor tCsBuf_flt_ = logical_divide(tCsBuf_flt, FltFrgSizePerLaneM); // (FltFrgSizePerLaneM, M) Tensor tCrRow_flt_ = logical_divide(tCrRow_flt, FltFrgSizePerLaneM); // (FltFrgSizePerLaneM, M) copy_aligned(tCrRow_flt_(_,_0{}), tCsBuf_flt_(_,lane_m)); } else { if (is_reduced_lane) { copy_aligned(tCrRow, tCsBuf); } } sync_fn();
constexpr int SmemFragSize = cute::max(size_t{1}, sizeof(uint32_t) / sizeof(ElementCompute)); using FragmentSmem = Array<ElementCompute, SmemFragSize>; using VectorSmem = uint_bit_t<sizeof_bits_v<FragmentSmem>>; using ReduceSmem = GmemReduceFn<FragmentSmem>; ReduceSmem reduce_smem{};
Tensor sBuf_frg = recast<FragmentSmem>(filter_zeros(sBuf)); Tensor sBuf_vec = recast<VectorSmem>(filter_zeros(sBuf)); constexpr int FragsPerRow = decltype(size<1>(sBuf_frg))::value;
constexpr int RowNum = decltype(size<0>(warp_layout_MN))::value; using FragmentSmemArray = Array<FragmentSmem, RowNum>;
// Do the threadblock smem reduction using VectorGmem = cute::conditional_t<FinalReduction, VectorSmem volatile, VectorSmem>; Tensor gBuf_vec = recast<VectorGmem>(filter(gBuf_ml(_,_,m,l))); CUTLASS_PRAGMA_UNROLL for (int frg_idx = thread_idx; frg_idx < FragsPerRow; frg_idx += size(tiled_copy)) { FragmentSmemArray frg_smem;
CUTLASS_PRAGMA_UNROLL for (int reduction_rows = 0; reduction_rows < RowNum; ++reduction_rows) { int FragsCurrRows = reduction_rows * FragsPerRow; frg_smem[reduction_rows] = sBuf_frg(FragsCurrRows + frg_idx); }
CUTLASS_PRAGMA_UNROLL for (int reduction_rows = RowNum / 2; reduction_rows > 0; reduction_rows /= 2) { CUTLASS_PRAGMA_UNROLL for (int row_idx = 0; row_idx < reduction_rows; ++row_idx) { frg_smem[row_idx] = reduce_smem(frg_smem[row_idx], frg_smem[row_idx + reduction_rows]); } } gBuf_vec(frg_idx) = reinterpret_cast<VectorSmem&>(frg_smem[0]); } sync_fn(); }
// // 3. Increment atomic counters to signal final gmem reduction // if constexpr (not IsAtomic && FinalReduction) { // Ensure gmem writes are visible to other threads before incrementing counter __threadfence(); sync_fn(); // Collective thread 0 increments atomic tile counter and copies value to smem int* prev_tile_count = reinterpret_cast<int*>(raw_pointer_cast(smem_buffer.data())); if (thread_idx == 0) { *prev_tile_count = atomicAdd(¶ms.tile_counters[n], 1); } sync_fn(); // Broadcast tile count to other threads in CTA and determine final reduction status do_final_reduction = *prev_tile_count == size<2>(gBuf_ml) * size<3>(gBuf_ml) - 1; sync_fn(); } }
CUTLASS_DEVICE void end() { // // 4. Do final gmem reduction if necessary // if constexpr (not IsAtomic && FinalReduction) { if (not do_final_reduction) { return; }
auto& [ref_src, tCrRow, tCcRow, gRow_l, cRow, gBuf_ml, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, tile_coord_mnkl, residue_cRow, residue_tCcRow, epi_tile, tiled_copy, thread_idx] = args_tuple;
using ReduceOutput = GmemReduceFn<ElementCompute>; using ConvertOutput = NumericConverter<ElementOutput, ElementCompute, RoundStyle>; ReduceOutput reduce_output{}; ConvertOutput convert_output{};
// Reduction over batches if (size<2>(stride(gRow_l)) == 0) { CUTLASS_PRAGMA_NO_UNROLL for (int n = thread_idx; n < size<1>(gBuf_ml); n += size(tiled_copy)) { Tensor tRgBuf_ml = gBuf_ml(_0{},n,_,_); ElementCompute output = tRgBuf_ml(_0{}); CUTLASS_PRAGMA_NO_UNROLL for (int ml = 1; ml < size(tRgBuf_ml); ++ml) { output = reduce_output(output, tRgBuf_ml(ml)); } if (elem_less(cRow(_0{},n), residue_cRow)) { gRow_l(_0{},n,_0{}) = convert_output(output); } } } // No reduction over batches else { CUTLASS_PRAGMA_NO_UNROLL for (int n = thread_idx; n < size<1>(gBuf_ml); n += size(tiled_copy)) { bool do_store = elem_less(cRow(_0{},n), residue_cRow); CUTLASS_PRAGMA_NO_UNROLL for (int l = 0; l < size<3>(gBuf_ml); ++l) { Tensor tRgBuf_m = gBuf_ml(_0{},n,_,l); ElementCompute output = tRgBuf_m(_0{}); CUTLASS_PRAGMA_NO_UNROLL for (int m = 1; m < size(tRgBuf_m); ++m) { output = reduce_output(output, tRgBuf_m(m)); } if (do_store) { gRow_l(_0{},n,l) = convert_output(output); } } } }
} } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { Layout ref_layout_MN = [&] () { auto mn_shape = shape(typename decltype(args.tiled_copy)::Tiler_MN{}); if constexpr (ReferenceSrc) { return right_inverse(args.tiled_copy.get_layoutS_TV()).with_shape(mn_shape); } else { return right_inverse(args.tiled_copy.get_layoutD_TV()).with_shape(mn_shape); } }(); // tile_mn -> tv_idx
// Get the MN layout + coord of lanes to determine shuffle reduction iterations using _W = Int<decltype(args.tiled_copy)::TiledNumThr::value / NumThreadsPerWarp>; Layout tv2lane = Layout<Shape<Int<NumThreadsPerWarp>,_W,_1>,Stride<_1,_0,_0>>{}; // tv_idx -> lane_idx Layout ref2lane = composition(tv2lane, ref_layout_MN); // tile_mn -> lane_idx Layout lane_layout_MN = make_layout(filter(get<0>(ref2lane)), filter(get<1>(ref2lane))); // lane_mn -> lane_idx Layout inv_lane_layout_MN = right_inverse(lane_layout_MN); // lane_idx -> lane_mn int lane_idx = canonical_lane_idx(); auto lane_mn = idx2crd(inv_lane_layout_MN(lane_idx), shape(lane_layout_MN));
// Get the MN layout + coord of warps to determine smem reduction iterations Layout tv2warp = Layout<Shape<Int<NumThreadsPerWarp>,_W,_1>,Stride<_0,_1,_0>>{}; // tv_idx -> warp_idx Layout ref2warp = composition(tv2warp, ref_layout_MN); // tile_mn -> warp_idx Layout warp_layout_MN = make_layout(filter(get<0>(ref2warp)), filter(get<1>(ref2warp))); // warp_mn -> warp_idx Layout inv_warp_layout_MN = right_inverse(warp_layout_MN); // warp_idx -> warp_mn
int warp_idx = args.thread_idx / NumThreadsPerWarp; auto warp_mn = idx2crd(inv_warp_layout_MN(warp_idx), shape(warp_layout_MN));
// Partition output gmem and register tensors auto [tile_M, tile_N, tile_K] = args.tile_shape_mnk; auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl;
Tensor mRow = make_tensor(make_gmem_ptr<ElementOutput>(params.ptr_row), make_shape(M,N,L), params.dRow); // (M,N,L) Tensor gRow_l = local_tile(mRow, take<0,2>(args.tile_shape_mnk), make_coord(m,n,_)); // (CTA_M,CTA_N,L) Tensor tCgRow = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) gRow_l(_,_,l), args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrRow = make_tensor_like<ElementCompute>(tCgRow); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N)
fill(tCrRow, params.reduction_identity);
// Partition gmem+smem reduction buffer tensors Layout gBuf_layout = make_layout(take<0,2>(args.tile_shape_mnk), make_stride(_0{}, _1{})); auto block_shape = ceil_div(make_shape(M,N,L), shape(gBuf_layout)); // (M_CNT, N_CNT, L_CNT)
// Let the M_CNT (the num of partial reduction results) become the outer mode Layout block_layout = make_layout(block_shape, make_stride(get<1>(block_shape), _1{}, get<0>(block_shape) * get<1>(block_shape))); Layout mBuf_layout = blocked_product(gBuf_layout, block_layout); Tensor mBuf = make_tensor(make_gmem_ptr(params.reduction_buffer), mBuf_layout); // (ceil_M,ceil_N,L) Tensor gBuf_ml = local_tile(mBuf, take<0,2>(args.tile_shape_mnk), make_coord(_,n,_)); // (CTA_M,CTA_N,REST_M,L) Layout sBuf_layout = blocked_product(gBuf_layout, // (CTA_M,CTA_N,WARPS_M) make_layout(make_shape(_1{},_1{},size<0>(warp_layout_MN))));
auto args_tuple = make_tuple( bool_constant<ReferenceSrc>{}, cute::move(tCrRow), args.tCcD, gRow_l, args.cD, gBuf_ml, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, args.tile_coord_mnkl, args.residue_cD, args.residue_tCcD, args.epi_tile, args.tiled_copy, args.thread_idx); return ConsumerStoreCallbacks<decltype(args_tuple)>(cute::move(args_tuple), params); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Col vector reductiontemplate < template <class> class RegReduceFn, template <class> class ShuffleReduceFn, template <class> class GmemReduceFn, int Stages, class CtaTileShapeMNK, class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, class StrideMNL = Stride<_1,_0,_0>, int Alignment = 128 / sizeof_bits_v<ElementOutput>, bool EnableNullptr = true, // Noop on nullptr params // If this is false, ptr_col is assumed to point to a compact m-major (round_nearest(M,CTA_M), ceil_div(N,CTA_N), L) // tensor of ElementCompute. It is the user's responsibility to reduce this to a (M, L) tensor of ElementOutput bool FinalReduction = true, // False means skip OOB predication if OOB inputs are known to be the reduction identity bool VisitCheckOOB = true>struct Sm90ColReduction {private: static_assert(Stages == 0, "Smem usage not supported yet"); static_assert(Alignment * sizeof_bits_v<ElementOutput> % 128 == 0, "sub-16B alignment not supported yet"); static_assert(is_static_v<decltype(take<0,2>(StrideMNL{}))>); // batch stride can be dynamic or static static_assert(take<0,2>(StrideMNL{}) == Stride<_1,_0>{}); static constexpr bool IsAtomic = is_atomic<GmemReduceFn<ElementCompute>>::value; static_assert(not (IsAtomic && not FinalReduction), "atomic reduction must be final");
public: struct SharedStorage { };
struct Arguments { void* ptr_col = nullptr; // ElementOutput* if FinalReduction, else ElementCompute* ElementCompute reduction_identity = ElementCompute(0); StrideMNL dCol = {}; };
struct Params { void* ptr_col = nullptr; ElementCompute reduction_identity = ElementCompute(0); StrideMNL dCol = {}; ElementCompute* reduction_buffer = nullptr; int* tile_counters = nullptr; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { ElementCompute* reduction_buffer; int* tile_counters = nullptr; if constexpr (IsAtomic) { reduction_buffer = nullptr; } else if constexpr (FinalReduction) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{}; size_t tile_counters_offset = product(ceil_div(make_shape(M,N,L), make_shape(tile_M, tile_N))) * tile_M * sizeof(ElementCompute); tile_counters_offset = round_nearest(tile_counters_offset, MinWorkspaceAlignment);
reduction_buffer = reinterpret_cast<ElementCompute*>(workspace); tile_counters = reinterpret_cast<int*>(reinterpret_cast<uint8_t*>(workspace) + tile_counters_offset); } else { reduction_buffer = reinterpret_cast<ElementCompute*>(args.ptr_col); }
return { args.ptr_col, args.reduction_identity, args.dCol, reduction_buffer, tile_counters }; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return true; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { if constexpr (IsAtomic || not FinalReduction) { return 0; }
size_t workspace_size = 0; auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{};
// Increment by size of reduction buffer workspace_size += product(ceil_div(make_shape(M,N,L), make_shape(tile_M, tile_N))) * tile_M * sizeof(ElementCompute); // Align and increment by size of tile counters workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment); workspace_size += cute::ceil_div(M, tile_M) * sizeof(int);
return workspace_size; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { if constexpr (IsAtomic) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; Layout mCol_layout = make_layout(make_shape(size<>(M),size<>(N),size<>(L)), args.dCol); if (args.ptr_col != nullptr) { return fill_workspace(args.ptr_col, ElementOutput(args.reduction_identity), cosize(mCol_layout), stream, cuda_adapter); } return Status::kSuccess; } else if constexpr (FinalReduction) { auto problem_shape_mnkl = append<4>(problem_shape, 1); auto [M, N, K, L] = problem_shape_mnkl; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{}; size_t tile_counters_offset = product(ceil_div(make_shape(M,N,L), make_shape(tile_M, tile_N))) * tile_M * sizeof(ElementCompute); tile_counters_offset = round_nearest(tile_counters_offset, MinWorkspaceAlignment);
int* tile_counters = reinterpret_cast<int*>(reinterpret_cast<uint8_t*>(workspace) + tile_counters_offset); size_t tile_counters_size = cute::ceil_div(M, tile_M) * sizeof(int); return zero_workspace(tile_counters, tile_counters_size, stream, cuda_adapter); } else { return Status::kSuccess; } }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_HOST_DEVICE Sm90ColReduction() { }
CUTLASS_HOST_DEVICE Sm90ColReduction(Params const& params, SharedStorage const& shared_storage) : params(params) { }
Params params;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template<class ArgsTuple> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(ArgsTuple&& args_tuple, Params const& params) : args_tuple(cute::forward<ArgsTuple>(args_tuple)), params(params) {}
ArgsTuple args_tuple; Params const& params; bool do_final_reduction = false;
template <typename ElementAccumulator, typename ElementInput, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) { if constexpr (EnableNullptr) { if (params.ptr_col == nullptr) { return frg_input; } }
auto& [ref_src, tCrCol, tCcCol, gCol_l, cCol, gBuf_nl, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, tile_coord_mnkl, residue_cCol, residue_tCcCol, epi_tile, tiled_copy, thread_idx] = args_tuple; Tensor tCrCol_mn = tCrCol(_,_,_,epi_m,epi_n); Tensor tCcCol_mn = tCcCol(_,_,_,epi_m,epi_n);
using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; using ReduceInput = RegReduceFn<ElementCompute>; ConvertInput convert_input{}; ReduceInput reduce_input{};
Array frg_I = convert_input(frg_input); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { if (!VisitCheckOOB || elem_less(tCcCol_mn(epi_v * FragmentSize + i), residue_tCcCol)) { ElementCompute& tCrCol_vmn = tCrCol_mn(epi_v * FragmentSize + i); tCrCol_vmn = reduce_input(tCrCol_vmn, frg_I[i]); } }
return frg_input; }
template <class STensor, class SyncFn, class VTensor> CUTLASS_DEVICE void reduce(STensor&& smem_buffer, SyncFn const& sync_fn, int epi_m, int epi_n, bool is_last_iteration, VTensor visit_results) { if (not is_last_iteration) { return; }
auto& [ref_src, tCrCol, tCcCol, gCol_l, cCol, gBuf_nl, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, tile_coord_mnkl, residue_cCol, residue_tCcCol, epi_tile, tiled_copy, thread_idx] = args_tuple; auto [m, n, k, l] = tile_coord_mnkl; constexpr bool ReferenceSrc = decltype(ref_src)::value;
// Runtime nullptr is noop if constexpr (EnableNullptr) { if (params.ptr_col == nullptr) { return; } }
// fully OOB CTA in partially OOB cluster if (not elem_less(cCol(_0{},_0{}), residue_cCol)) { return; }
// // 1. Warp shuffle reduction // using FragmentShuffle = Array<ElementCompute, sizeof(uint64_t) / sizeof(ElementCompute)>; using ReduceShuffle = ShuffleReduceFn<FragmentShuffle>; ReduceShuffle reduce_shuffle{}; Tensor tCrCol_frg = recast<FragmentShuffle>(filter(tCrCol)); CUTLASS_PRAGMA_UNROLL for (int reduction_cols = size<1>(lane_layout_MN) / 2; reduction_cols > 0; reduction_cols /= 2) { CUTLASS_PRAGMA_UNROLL for (int frg_idx = 0; frg_idx < size(tCrCol_frg); ++frg_idx) { uint64_t frg_shfl = reinterpret_cast<uint64_t&>(tCrCol_frg(frg_idx)); frg_shfl = __shfl_down_sync(0xFFFFFFFF, frg_shfl, lane_layout_MN(_0{},reduction_cols)); tCrCol_frg(frg_idx) = reduce_shuffle(tCrCol_frg(frg_idx), reinterpret_cast<FragmentShuffle&>(frg_shfl)); } } bool is_reduced_lane = get<1>(lane_mn) == 0;
// // 2. Atomic reduction // if constexpr (IsAtomic) { // Filter so we don't issue redunant copies over stride-0 modes Tensor tCrCol_flt = filter_zeros(tCrCol); Tensor tCcCol_flt = make_tensor(tCcCol.data(), make_layout(tCrCol_flt.shape(), tCcCol.stride()));
Tensor tCgCol = sm90_partition_for_epilogue<ReferenceSrc>(gCol_l(_,_,l), epi_tile, tiled_copy, thread_idx); Tensor tCgCol_flt = filter_zeros(tCgCol);
// NOTE: atomic reduction is performed in the output type using ConvertOutput = NumericConverter<ElementOutput, ElementCompute, RoundStyle>; using ReduceOutput = GmemReduceFn<ElementOutput>; ConvertOutput convert_output{}; ReduceOutput reduce_output{};
if (is_reduced_lane) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrCol_flt); ++i) { if (elem_less(tCcCol_flt(i), residue_tCcCol)) { reduce_output(&tCgCol_flt(i), convert_output(tCrCol_flt(i))); } } } sync_fn(); }
// // 2. One warp in N, skip threadblock smem reduction // else if constexpr (decltype(size<1>(warp_layout_MN))::value <= 1) { // Dump warp reduction to gmem workspace using ElementGmem = cute::conditional_t<FinalReduction, ElementCompute volatile, ElementCompute>; Tensor tCgBuf = sm90_partition_for_epilogue<ReferenceSrc>(gBuf_nl(_,_,n,l), epi_tile, tiled_copy, thread_idx); if (is_reduced_lane) { copy_aligned(tCrCol, recast<ElementGmem>(tCgBuf)); } sync_fn(); }
// // 2. Multiple warps in N, do threadblock smem reduction // else { Tensor sBuf = make_tensor(make_smem_ptr<ElementCompute>(raw_pointer_cast(smem_buffer.data())), sBuf_layout); static_assert(decltype(cosize(sBuf.layout()))::value * sizeof(ElementCompute) <= decltype(cosize(smem_buffer.layout()))::value * sizeof(typename remove_cvref_t<STensor>::value_type), "smem reduction buffer not large enough, use a larger epilogue tile"); sync_fn();
// Dump warp reduction to smem workspace Tensor tCsBuf = sm90_partition_for_epilogue<ReferenceSrc>(sBuf(_,_,get<1>(warp_mn)), epi_tile, tiled_copy, thread_idx); if (is_reduced_lane) { copy_aligned(tCrCol, tCsBuf); } sync_fn();
constexpr int SmemFragSize = cute::max(size_t{1}, sizeof(uint32_t) / sizeof(ElementCompute)); using FragmentSmem = Array<ElementCompute, SmemFragSize>; using VectorSmem = uint_bit_t<sizeof_bits_v<FragmentSmem>>; using ReduceSmem = GmemReduceFn<FragmentSmem>; ReduceSmem reduce_smem{};
Tensor sBuf_frg = recast<FragmentSmem>(filter_zeros(sBuf)); Tensor sBuf_vec = recast<VectorSmem>(filter_zeros(sBuf)); constexpr int FragsPerCol = decltype(size<0>(sBuf_frg))::value;
// Do the threadblock smem reduction CUTLASS_PRAGMA_UNROLL for (int reduction_cols = size<1>(warp_layout_MN) / 2; reduction_cols > 1; reduction_cols /= 2) { int FragsPerReduction = reduction_cols * FragsPerCol; CUTLASS_PRAGMA_NO_UNROLL for (int frg_idx = thread_idx; frg_idx < FragsPerReduction; frg_idx += size(tiled_copy)) { FragmentSmem frg_smem = reduce_smem(sBuf_frg(frg_idx), sBuf_frg(frg_idx + FragsPerReduction)); sBuf_vec(frg_idx) = reinterpret_cast<VectorSmem&>(frg_smem); } sync_fn(); }
// Do final smem reduction and dump to gmem workspace using VectorGmem = cute::conditional_t<FinalReduction, VectorSmem volatile, VectorSmem>; Tensor gBuf_vec = recast<VectorGmem>(filter(gBuf_nl(_,_,n,l))); CUTLASS_PRAGMA_NO_UNROLL for (int frg_idx = thread_idx; frg_idx < FragsPerCol; frg_idx += size(tiled_copy)) { FragmentSmem frg_smem = reduce_smem(sBuf_frg(frg_idx), sBuf_frg(frg_idx + FragsPerCol)); gBuf_vec(frg_idx) = reinterpret_cast<VectorSmem&>(frg_smem); } sync_fn(); }
// // 3. Increment atomic counters to signal final gmem reduction // if constexpr (not IsAtomic && FinalReduction) { // Ensure gmem writes are visible to other threads before incrementing counter __threadfence(); sync_fn(); // Collective thread 0 increments atomic tile counter and copies value to smem int* prev_tile_count = reinterpret_cast<int*>(raw_pointer_cast(smem_buffer.data())); if (thread_idx == 0) { *prev_tile_count = atomicAdd(¶ms.tile_counters[m], 1); } sync_fn(); // Broadcast tile count to other threads in CTA and determine final reduction status do_final_reduction = *prev_tile_count == size<2>(gBuf_nl) * size<3>(gBuf_nl) - 1; sync_fn(); } }
CUTLASS_DEVICE void end() { // // 4. Do final gmem reduction if necessary // if constexpr (not IsAtomic && FinalReduction) { if (not do_final_reduction) { return; }
auto& [ref_src, tCrCol, tCcCol, gCol_l, cCol, gBuf_nl, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, tile_coord_mnkl, residue_cCol, residue_tCcCol, epi_tile, tiled_copy, thread_idx] = args_tuple;
using ReduceOutput = GmemReduceFn<ElementCompute>; using ConvertOutput = NumericConverter<ElementOutput, ElementCompute, RoundStyle>; ReduceOutput reduce_output{}; ConvertOutput convert_output{};
// Reduction over batches if (size<2>(stride(gCol_l)) == 0) { CUTLASS_PRAGMA_NO_UNROLL for (int m = thread_idx; m < size<0>(gBuf_nl); m += size(tiled_copy)) { Tensor tRgBuf_nl = gBuf_nl(m,_0{},_,_); ElementCompute output = tRgBuf_nl(_0{}); CUTLASS_PRAGMA_NO_UNROLL for (int nl = 1; nl < size(tRgBuf_nl); ++nl) { output = reduce_output(output, tRgBuf_nl(nl)); } if (elem_less(cCol(m,_0{}), residue_cCol)) { gCol_l(m,_0{},_0{}) = convert_output(output); } } } // No reduction over batches else { CUTLASS_PRAGMA_NO_UNROLL for (int m = thread_idx; m < size<0>(gBuf_nl); m += size(tiled_copy)) { bool do_store = elem_less(cCol(m,_0{}), residue_cCol); CUTLASS_PRAGMA_NO_UNROLL for (int l = 0; l < size<3>(gBuf_nl); ++l) { Tensor tRgBuf_n = gBuf_nl(m,_0{},_,l); ElementCompute output = tRgBuf_n(_0{}); CUTLASS_PRAGMA_NO_UNROLL for (int n = 1; n < size(tRgBuf_n); ++n) { output = reduce_output(output, tRgBuf_n(n)); } if (do_store) { gCol_l(m,_0{},l) = convert_output(output); } } } }
} }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { Layout ref_layout_MN = [&] () { auto mn_shape = shape(typename decltype(args.tiled_copy)::Tiler_MN{}); if constexpr (ReferenceSrc) { return right_inverse(args.tiled_copy.get_layoutS_TV()).with_shape(mn_shape); } else { return right_inverse(args.tiled_copy.get_layoutD_TV()).with_shape(mn_shape); } }(); // tile_mn -> tv_idx
// Get the MN layout + coord of lanes to determine shuffle reduction iterations using _W = Int<decltype(args.tiled_copy)::TiledNumThr::value / NumThreadsPerWarp>; Layout tv2lane = Layout<Shape<Int<NumThreadsPerWarp>,_W,_1>,Stride<_1,_0,_0>>{}; // tv_idx -> lane_idx Layout ref2lane = composition(tv2lane, ref_layout_MN); // tile_mn -> lane_idx Layout lane_layout_MN = make_layout(filter(get<0>(ref2lane)), filter(get<1>(ref2lane))); // lane_mn -> lane_idx Layout inv_lane_layout_MN = right_inverse(lane_layout_MN); // lane_idx -> lane_mn int lane_idx = canonical_lane_idx(); auto lane_mn = idx2crd(inv_lane_layout_MN(lane_idx), shape(lane_layout_MN));
// Get the MN layout + coord of warps to determine smem reduction iterations Layout tv2warp = Layout<Shape<Int<NumThreadsPerWarp>,_W,_1>,Stride<_0,_1,_0>>{}; // tv_idx -> warp_idx Layout ref2warp = composition(tv2warp, ref_layout_MN); // tile_mn -> warp_idx Layout warp_layout_MN = make_layout(filter(get<0>(ref2warp)), filter(get<1>(ref2warp))); // warp_mn -> warp_idx Layout inv_warp_layout_MN = right_inverse(warp_layout_MN); // warp_idx -> warp_mn int warp_idx = args.thread_idx / NumThreadsPerWarp; auto warp_mn = idx2crd(inv_warp_layout_MN(warp_idx), shape(warp_layout_MN));
// Partition output gmem and register tensors auto [tile_M, tile_N, tile_K] = args.tile_shape_mnk; auto [M, N, K, L] = args.problem_shape_mnkl; auto [m, n, k, l] = args.tile_coord_mnkl;
Tensor mCol = make_tensor(make_gmem_ptr<ElementOutput>(params.ptr_col), make_shape(M,N,L), params.dCol); // (M,N,L) Tensor gCol_l = local_tile(mCol, take<0,2>(args.tile_shape_mnk), make_coord(m,n,_)); // (CTA_M,CTA_N,L) Tensor tCgCol = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) gCol_l(_,_,l), args.epi_tile, args.tiled_copy, args.thread_idx); Tensor tCrCol = make_tensor_like<ElementCompute>(tCgCol); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) fill(tCrCol, params.reduction_identity);
// Partition gmem+smem reduction buffer tensors Layout gBuf_layout = make_layout(take<0,2>(args.tile_shape_mnk), make_stride(_1{}, _0{})); Layout mBuf_layout = blocked_product(gBuf_layout, make_layout(ceil_div(make_shape(M,N,L), shape(gBuf_layout)))); Tensor mBuf = make_tensor(make_gmem_ptr(params.reduction_buffer), mBuf_layout); // (ceil_M,ceil_N,L) Tensor gBuf_nl = local_tile(mBuf, take<0,2>(args.tile_shape_mnk), make_coord(m,_,_)); // (CTA_M,CTA_N,REST_N,L) Layout sBuf_layout = blocked_product(gBuf_layout,make_layout(make_shape(_1{},_1{},size<1>(warp_layout_MN)))); // (CTA_M,CTA_N,WARPS_N)
auto args_tuple = make_tuple( bool_constant<ReferenceSrc>{}, cute::move(tCrCol), args.tCcD, gCol_l, args.cD, gBuf_nl, sBuf_layout, lane_layout_MN, lane_mn, warp_layout_MN, warp_mn, args.tile_coord_mnkl, args.residue_cD, args.residue_tCcD, args.epi_tile, args.tiled_copy, args.thread_idx); return ConsumerStoreCallbacks<decltype(args_tuple)>(std::move(args_tuple), params); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Batch matrix reductiontemplate < int Stages, class EpilogueTile, class Element, class StrideMNL, class CopyOpR2S, class SmemLayoutAtom, int Alignment = 128 / sizeof_bits_v<Element>, bool EnableNullptr = true // Noop on nullptr params>struct Sm90MatrixReduction;
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree operation base implementation to enable composable fusions for the sm90 TMA warp-specialized (ws) epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/workspace.h"#include "cutlass/detail/helper_macros.hpp"
#include "cute/tensor.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
using namespace cute;using cute::tuple;
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace detail {
///////////////////////////////////////////////////////////////////////////////////////////////////// Partitioning Helpers///////////////////////////////////////////////////////////////////////////////////////////////////
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class CtaTileMN, class EpilogueTile, class TiledCopy>CUTLASS_HOST_DEVICEconstexpr autosm90_partition_for_epilogue( CtaTileMN cT, // (CTA_M,CTA_N,...) EpilogueTile epi_tile, // (EPI_TILE_M,EPI_TILE_N) TiledCopy tiled_copy, int thread_idx) { ThrCopy thread_copy = tiled_copy.get_thread_slice(thread_idx); Tensor cT_epi = flat_divide(cT, epi_tile); // (EPI_TILE_M,EPI_TILE_N,EPI_M,EPI_N,...) if constexpr (ReferenceSrc) { return thread_copy.partition_S(cT_epi); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,...) } else { return thread_copy.partition_D(cT_epi); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N,...) }}
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class Engine, class LayoutMNL, class TileShapeMNK, class TileCoordMNKL, class EpilogueTile, class TiledCopy>CUTLASS_HOST_DEVICEconstexpr autosm90_partition_for_epilogue( Tensor<Engine, LayoutMNL> mT, // (M,N,L) TileShapeMNK tile_shape_mnk, // (CTA_M,CTA_N,CTA_K) TileCoordMNKL tile_coord_mnkl, // (m,n,k,l) EpilogueTile epi_tile, // (EPI_TILE_M,EPI_TILE_N) TiledCopy tiled_copy, int thread_idx) { auto [m, n, k, l] = tile_coord_mnkl; auto coord_shape = make_coord(m, n, l) ; Tensor cT = local_tile(mT, take<0,2>(tile_shape_mnk), coord_shape); // (CTA_M,CTA_N) Tensor tCcT = sm90_partition_for_epilogue<ReferenceSrc>(cT, epi_tile, tiled_copy, thread_idx); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N)
return tCcT;}
///////////////////////////////////////////////////////////////////////////////////////////////////// Visitor Implementation///////////////////////////////////////////////////////////////////////////////////////////////////
//// Producer load callbacks, called by the epilogue load warp.// Operations usually only define this if TMA load is needed. Most operations will reuse this empy implementation// Load callbacks are responsible for issuing corresponding mbarrier expect-tx ops for any TMA loads issued, but// are not responsible for issuing the producer_commit barrier arrival, which is issued by the collective instead// If this is non-empty, is_producer_load_needed must be true.//template <class CallbacksTuple>struct ProducerLoadCallbacksImpl { // Callbacks can store non-persistent variables (e.g. tensors) or copies of persistent variables CallbacksTuple callbacks_tuple;
// Before entry of the subtile load loop CUTLASS_DEVICE void begin() { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.begin(); } ); }
// Entry of the subtile load loop. Aux loads usually performed here // Upon entry the producer acquire of the current subtile lock has completed. // Upon exit all TMA loads for this subtile must have been issued, with corresponding expect-tx operations CUTLASS_DEVICE void step(uint64_t* full_mbarrier_ptr, int epi_m, int epi_n, int load_iteration, bool issue_tma_load) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.step(full_mbarrier_ptr, epi_m, epi_n, load_iteration, issue_tma_load); } ); }
// Exit of the subtile load loop. CUTLASS_DEVICE void end() { for_each(callbacks_tuple, [] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.end(); } ); }};
//// Consumer store callbacks, called by the epilogue store warps.// All operations must redefine this, with optional inheritance from this empty implementation.//template <class CallbacksTuple>struct ConsumerStoreCallbacksImpl { // Callbacks can store non-persistent variables (e.g. tensors) or copies of persistent variables CallbacksTuple callbacks_tuple;
// Before entry of subtile store loop. Gmem broadcasts usually performed here. CUTLASS_DEVICE void begin() { for_each(callbacks_tuple, [] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.begin(); } ); }
// Is a thread sync needed after begin(). Allows chaining async copies across multiple nodes CUTLASS_DEVICE bool begin_sync_needed() const { return cute::apply(callbacks_tuple, [] (auto const&... callbacks) { return (false || ... || callbacks.begin_sync_needed()); } ); }
// Start of subtile store iteration CUTLASS_DEVICE void begin_loop(int epi_m, int epi_n) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.begin_loop(epi_m, epi_n); } ); }
// Before visit callback. Smem broadcasts usually performed here. // Upon entry, all producer loads for this subtile are completed and visible. CUTLASS_DEVICE void previsit(int epi_m, int epi_n, int load_iteration, bool is_producer_load_needed) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.previsit(epi_m, epi_n, load_iteration, is_producer_load_needed); } ); }
// Perform the fused elementwise computation template <typename ElementAccumulator, typename... ElementInputs, int FragmentSize> CUTLASS_DEVICE auto // returns an Array visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInputs, FragmentSize> const&... frg_inputs) // depends on the N-naryness of the op = delete; // Must be implemented for each operation
// After visit call. Smem reductions usually performed here // reduction_buffer is an arbitrary smem tensor that can be used for workspace // It is each nodes reponsibility to assert that this buffer is sufficiently sized // and to ensure that this buffer is no longer needed upon callback exit // i.e. results are synchronized and no longer in the reduction buffer // // visit_results is a rmem tensor that contains the results of visit() for an entire // on the current epilogue subtile template <class STensor, class SyncFn, class VTensor> CUTLASS_DEVICE void reduce(STensor&& reduction_buffer, SyncFn const& sync_fn, int epi_m, int epi_n, bool is_last_iteration, VTensor visit_results) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.reduce(reduction_buffer, sync_fn, epi_m, epi_n, is_last_iteration, visit_results); } ); }
// After reduce call, before smem async fence. Smem stores usually performed here. // Upon exit, all smem stores for TMA must have been issued CUTLASS_DEVICE void postreduce(int epi_m, int epi_n, int store_iteration, bool issue_smem_store) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.postreduce(epi_m, epi_n, store_iteration, issue_smem_store); } ); }
// After smem async fence, before TMA store commit. Aux stores usually performed here // Upon exit, all TMA stores for this subtile must have been issued // Because of the TMA store delay optimization, this entry point must ONLY be used for TMA stores // other gmem stores can be placed in the reduce or postreduce entry points CUTLASS_DEVICE void tma_store(int epi_m, int epi_n, int store_iteration, bool issue_tma_store) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.tma_store(epi_m, epi_n, store_iteration, issue_tma_store); } ); }
// End of subtile store iteration CUTLASS_DEVICE void end_loop(int epi_m, int epi_n) { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.end_loop(epi_m, epi_n); } ); }
// Exit of subtile store loop. Gmem reductions usually performed here. CUTLASS_DEVICE void end() { for_each(callbacks_tuple, [&] (auto& callbacks) CUTLASS_LAMBDA_FUNC_INLINE { callbacks.end(); } ); }};
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class TiledMma, class EpilogueTile>struct ProducerLoadArgs { ProblemShapeMNKL problem_shape_mnkl; TileShapeMNK tile_shape_mnk; TileCoordMNKL tile_coord_mnkl; TiledMma tiled_mma; EpilogueTile epi_tile; int thread_idx;
CUTLASS_DEVICE ProducerLoadArgs( ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_mnk, TileCoordMNKL tile_coord_mnkl, TiledMma tiled_mma, EpilogueTile epi_tile, int thread_idx) : problem_shape_mnkl(problem_shape_mnkl), tile_shape_mnk(tile_shape_mnk), tile_coord_mnkl(tile_coord_mnkl), tiled_mma(tiled_mma), epi_tile(epi_tile), thread_idx(thread_idx) {}};
template< class ProblemShapeMNKL, class TileShapeMNK, class TileCoordMNKL, class TiledMma, class EpilogueTile, class TiledCopy, class CoordTensor, class Residue, class ThrCoordTensor, class ThrResidue, class ThrSrcTensor>struct ConsumerStoreArgs { ProblemShapeMNKL problem_shape_mnkl; TileShapeMNK tile_shape_mnk; TileCoordMNKL tile_coord_mnkl; TiledMma tiled_mma; EpilogueTile epi_tile; TiledCopy tiled_copy; CoordTensor cD; Residue residue_cD; ThrCoordTensor tCcD; ThrResidue residue_tCcD; ThrSrcTensor & tCrC; int thread_idx;
CUTLASS_DEVICE ConsumerStoreArgs( ProblemShapeMNKL problem_shape_mnkl, TileShapeMNK tile_shape_mnk, TileCoordMNKL tile_coord_mnkl, TiledMma tiled_mma, EpilogueTile epi_tile, TiledCopy tiled_copy, CoordTensor cD, Residue residue_cD, ThrCoordTensor tCcD, ThrResidue residue_tCcD, ThrSrcTensor & tCrC, int thread_idx) : problem_shape_mnkl(problem_shape_mnkl), tile_shape_mnk(tile_shape_mnk), tile_coord_mnkl(tile_coord_mnkl), tiled_mma(tiled_mma), epi_tile(epi_tile), tiled_copy(tiled_copy), cD(cD), residue_cD(residue_cD), tCcD(tCcD), residue_tCcD(residue_tCcD), tCrC(tCrC), thread_idx(thread_idx) {}};
template <class... Ops>struct Sm90VisitorImplBase { // Shared memory allocation using SharedStorage = tuple<typename Ops::SharedStorage...>; // Host side fusion arguments using Arguments = tuple<typename Ops::Arguments...>; // Device side fusion params (Kernel-entry API) using Params = tuple<typename Ops::Params...>;
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { uint8_t* op_workspace = reinterpret_cast<uint8_t*>(workspace); return transform_apply(tuple<Ops...>{}, args, [&] (auto&& op, auto const& op_args) CUTLASS_LAMBDA_FUNC_INLINE { using Op = cute::remove_cvref_t<decltype(op)>; auto ret = Op::to_underlying_arguments(problem_shape, op_args, op_workspace); if (op_workspace != nullptr) { size_t op_workspace_size = Op::get_workspace_size(problem_shape, op_args); op_workspace += round_nearest(op_workspace_size, MinWorkspaceAlignment); } return ret; }, [] (auto&&... op_params) CUTLASS_LAMBDA_FUNC_INLINE { return cute::make_tuple(op_params...); } ); }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return transform_apply(tuple<Ops...>{}, args, [&] (auto&& op, auto const& op_args) CUTLASS_LAMBDA_FUNC_INLINE { using Op = cute::remove_cvref_t<decltype(op)>; return Op::can_implement(problem_shape, op_args); }, [&] (auto&&... implementable) CUTLASS_LAMBDA_FUNC_INLINE { return (true && ... && implementable); } ); }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return transform_apply(tuple<Ops...>{}, args, [&] (auto&& op, auto const& op_args) CUTLASS_LAMBDA_FUNC_INLINE { using Op = cute::remove_cvref_t<decltype(op)>; size_t op_workspace_size = Op::get_workspace_size(problem_shape, op_args); return round_nearest(op_workspace_size, MinWorkspaceAlignment); }, [&] (auto&&... op_workspace_size) CUTLASS_LAMBDA_FUNC_INLINE { return (0 + ... + op_workspace_size); } ); }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { Status status = Status::kSuccess; uint8_t* op_workspace = reinterpret_cast<uint8_t*>(workspace); return transform_apply(tuple<Ops...>{}, args, // Initialize each operation's workspace, stopping at the first error [&] (auto&& op, auto const& op_args) CUTLASS_LAMBDA_FUNC_INLINE { if (status != Status::kSuccess) { return status; }
using Op = cute::remove_cvref_t<decltype(op)>; status = Op::initialize_workspace(problem_shape, op_args, op_workspace, stream, cuda_adapter); if (op_workspace != nullptr) { size_t op_workspace_size = Op::get_workspace_size(problem_shape, op_args); op_workspace += round_nearest(op_workspace_size, MinWorkspaceAlignment); } return status; }, // Return the final status [&] (auto const&...ops) CUTLASS_LAMBDA_FUNC_INLINE { return status; } ); }
CUTLASS_HOST_DEVICE Sm90VisitorImplBase() {}
CUTLASS_HOST_DEVICE Sm90VisitorImplBase(Params const& params, SharedStorage const& shared_storage) : ops(transform_apply(tuple<Ops...>{}, params, shared_storage, [] (auto&& op, auto const& op_params, auto&& op_storage) CUTLASS_LAMBDA_FUNC_INLINE { using Op = cute::remove_cvref_t<decltype(op)>; return Op(op_params, op_storage); }, [] (auto&&... ops) CUTLASS_LAMBDA_FUNC_INLINE { return cute::make_tuple(ops...); } )) {}
// Ops can store kernel persistent variables (e.g. descriptors, scalars, wave counters) tuple<Ops...> ops;};
template <class... Ops>struct Sm90VisitorImpl : Sm90VisitorImplBase<Ops...> {
using Impl = Sm90VisitorImplBase<Ops...>; using Params = typename Impl::Params; using SharedStorage = typename Impl::SharedStorage;
CUTLASS_HOST_DEVICE Sm90VisitorImpl() {}
CUTLASS_HOST_DEVICE Sm90VisitorImpl(Params const& params, SharedStorage const& shared_storage) : Impl(params, shared_storage) {}
using Impl::ops;
// // Queries for kernel runtime //
// Is a specialized warp for producer TMA loads needed // e.g. Aux tensor loads, broadcasts using TMA bulk copy // This condition cannot change between work tiles because it is used // to determine whether the load warp should exit early or not // e.g. for batched beta this must always be true regardless of current batch idx CUTLASS_DEVICE bool is_producer_load_needed() const { return cute::apply(ops, [] (auto const&... op) CUTLASS_LAMBDA_FUNC_INLINE { return (false || ... || op.is_producer_load_needed()); } ); }
// Is a producer TMA load specifically for C needed // If this is true then is_producer_load_needed must also be true // This condition can change between work tiles because it is only used // to determine whether the TMA and smem loads for C of a given tile should happen // e.g. for batched beta this can be false depending on current batch idx CUTLASS_DEVICE bool is_C_load_needed() const { return cute::apply(ops, [] (auto const&... op) CUTLASS_LAMBDA_FUNC_INLINE { return (false || ... || op.is_C_load_needed()); } ); }
// Producer load callbacks factory // All operations must redefine this, but most can just dispatch to the base impl template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return transform_apply(ops, [&] (auto& op) CUTLASS_LAMBDA_FUNC_INLINE { return op.get_producer_load_callbacks(args); }, [] (auto&&... callbacks) CUTLASS_LAMBDA_FUNC_INLINE { auto callbacks_tuple = cute::make_tuple(callbacks...); return ProducerLoadCallbacksImpl<decltype(callbacks_tuple)>{callbacks_tuple}; } ); }
// Consumer store callbacks factory // All operations must redefine this template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { return transform_apply(ops, [&] (auto& op) CUTLASS_LAMBDA_FUNC_INLINE { return op.template get_consumer_store_callbacks<ReferenceSrc>(args); }, [] (auto&&... callbacks) CUTLASS_LAMBDA_FUNC_INLINE { auto callbacks_tuple = cute::make_tuple(callbacks...); return ConsumerStoreCallbacksImpl<decltype(callbacks_tuple)>{callbacks_tuple}; } ); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Convenience aliasesusing EmptyProducerLoadCallbacks = ProducerLoadCallbacksImpl<cute::tuple<>>;using EmptyConsumerStoreCallbacks = ConsumerStoreCallbacksImpl<cute::tuple<>>;
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace detail
using namespace detail;
///////////////////////////////////////////////////////////////////////////////////////////////////// Tree visitor///////////////////////////////////////////////////////////////////////////////////////////////////
template <class NodeOp, class... ChildOps>struct Sm90TreeVisitor : Sm90VisitorImpl<ChildOps..., NodeOp> {
using Impl = Sm90VisitorImpl<ChildOps..., NodeOp>; using Params = typename Impl::Params; using SharedStorage = typename Impl::SharedStorage;
CUTLASS_HOST_DEVICE Sm90TreeVisitor() {}
CUTLASS_HOST_DEVICE Sm90TreeVisitor( Params const& params, SharedStorage const& shared_storage) : Impl(params, shared_storage) {}
template<class CallbacksImpl> struct ConsumerStoreCallbacks : CallbacksImpl { CUTLASS_DEVICE ConsumerStoreCallbacks(CallbacksImpl&& impl) : CallbacksImpl(cute::forward<CallbacksImpl>(impl)) {}
using CallbacksImpl::callbacks_tuple;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { constexpr int Rm1 = sizeof...(ChildOps); return cute::detail::tapply(callbacks_tuple, [&] (auto& child_callbacks) CUTLASS_LAMBDA_FUNC_INLINE { return child_callbacks.visit(frg_acc, epi_v, epi_m, epi_n); // child ops must be nullary (e.g. loads, trees) }, [&] (auto&&... frg_inputs) CUTLASS_LAMBDA_FUNC_INLINE { return get<Rm1>(callbacks_tuple).visit(frg_acc, epi_v, epi_m, epi_n, frg_inputs...); }, make_seq<Rm1>{} // restrict the transform to R-1 child ops, apply is for node op ); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto callbacks_impl = Sm90VisitorImpl<ChildOps..., NodeOp>:: template get_consumer_store_callbacks<ReferenceSrc>(args); return ConsumerStoreCallbacks<decltype(callbacks_impl)>(cute::move(callbacks_impl)); }};
///////////////////////////////////////////////////////////////////////////////////////////////////// DAG visitors///////////////////////////////////////////////////////////////////////////////////////////////////
// Most DAG fusions can be represented as a set of output trees with a common input tree// The common input is first evaluated, then the result is passed as the acc fragment to the output treestemplate <class InputTree, class OutputTree, class... AuxOutTrees>struct Sm90SplitTreeVisitor : Sm90VisitorImpl<InputTree, AuxOutTrees..., OutputTree> {
using Sm90VisitorImpl<InputTree, AuxOutTrees..., OutputTree>::Sm90VisitorImpl;
template<class CallbacksImpl> struct ConsumerStoreCallbacks : CallbacksImpl { CUTLASS_DEVICE ConsumerStoreCallbacks(CallbacksImpl&& impl) : CallbacksImpl(cute::forward<CallbacksImpl>(impl)) {}
using CallbacksImpl::callbacks_tuple;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { Array frg_input = get<0>(callbacks_tuple).visit(frg_acc, epi_v, epi_m, epi_n);
constexpr int Rm2 = sizeof...(AuxOutTrees); cute::for_each(make_seq<Rm2>{}, // restrict the sequence to aux out trees [&] (auto I) CUTLASS_LAMBDA_FUNC_INLINE { get<I+1>(callbacks_tuple).visit(frg_input, epi_v, epi_m, epi_n); } );
return get<Rm2+1>(callbacks_tuple).visit(frg_input, epi_v, epi_m, epi_n); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto callbacks_impl = Sm90VisitorImpl<InputTree, AuxOutTrees..., OutputTree>:: template get_consumer_store_callbacks<ReferenceSrc>(args); return ConsumerStoreCallbacks<decltype(callbacks_impl)>(cute::move(callbacks_impl)); }};/////////////////////////////////////////////////////////////////////////////////////////////////
template< // deducing the output type for all the nodes is tricky so we just convert them all to a common type // if multiple compute types are needed then split into multiple subgraphs grouped by type class ElementCompute, class EdgeTuple, // tuple of int_sequence, each sequence is the children indices (indexed by topological order) for each node class... Ops // in topological order, last op is the output. EdgeTuple must match this order>struct Sm90TopologicalVisitor : Sm90VisitorImpl<Ops...> { static_assert(is_static_v<EdgeTuple>); static_assert(cute::rank(EdgeTuple{}) == sizeof...(Ops)); static_assert(sizeof...(Ops) > 1);
using Sm90VisitorImpl<Ops...>::Sm90VisitorImpl;
template<class CallbacksImpl> struct ConsumerStoreCallbacks : CallbacksImpl { CUTLASS_DEVICE ConsumerStoreCallbacks(CallbacksImpl&& impl) : CallbacksImpl(cute::forward<CallbacksImpl>(impl)) {}
using CallbacksImpl::callbacks_tuple;
template <typename ElementAccumulator, int FragmentSize> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n) { constexpr int Rm1 = sizeof...(Ops) - 1; auto frg_compute_tuple = cute::repeat<Rm1>(Array<ElementCompute, FragmentSize>{});
return cute::detail::tapply(EdgeTuple{}, callbacks_tuple, frg_compute_tuple, // Visit the first R-1 ops in topological order [&] (auto&& edge_seq, auto& callbacks, auto& frg_compute) CUTLASS_LAMBDA_FUNC_INLINE { frg_compute = cute::detail::apply(frg_compute_tuple, // Compute the current op with children inputs [&] (auto const&... frg_inputs) CUTLASS_LAMBDA_FUNC_INLINE { auto frg_output = callbacks.visit(frg_acc, epi_v, epi_m, epi_n, frg_inputs...); using ElementOutput = typename decltype(frg_output)::Element; using ConvertOutput = NumericArrayConverter<ElementCompute, ElementOutput, FragmentSize>; ConvertOutput convert_output{};
return convert_output(frg_output); }, // Get inputs in the sequence given by the children indices of the current op edge_seq ); return frg_compute; // unused }, // Visit the last op [&] (auto const&...ops) CUTLASS_LAMBDA_FUNC_INLINE { return cute::detail::apply(frg_compute_tuple, // Compute the last op with children inputs [&] (auto const&... frg_inputs) CUTLASS_LAMBDA_FUNC_INLINE { return get<Rm1>(callbacks_tuple).visit(frg_acc, epi_v, epi_m, epi_n, frg_inputs...); }, // Get inputs in the sequence given by the children indices of the last op get<Rm1>(EdgeTuple{}) ); }, // Transform to visit R-1 ops, apply to visit last op make_seq<Rm1>{} ); } };
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { auto callbacks_impl = Sm90VisitorImpl<Ops...>:: template get_consumer_store_callbacks<ReferenceSrc>(args); return ConsumerStoreCallbacks<decltype(callbacks_impl)>(cute::move(callbacks_impl)); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Base specializations so we can have standard layout params and simple aggregate initializersnamespace detail {
template <class Op0>struct Sm90VisitorImplBase<Op0> {
// Retain tuple for SharedStorage because empty structs have 1B alignment // tuples use multiple inheritance, avoids this problem using SharedStorage = tuple< typename Op0::SharedStorage >;
struct Arguments { typename Op0::Arguments op_0; };
struct Params { typename Op0::Params op_0; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return Params{ Op0::to_underlying_arguments(problem_shape, args.op_0, workspace) }; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return Op0::can_implement(problem_shape, args.op_0); }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { size_t workspace_size = 0; workspace_size += Op0::get_workspace_size(problem_shape, args.op_0); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
return workspace_size; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { Status status = Status::kSuccess; uint8_t* workspace_ptr = reinterpret_cast<uint8_t*>(workspace); size_t workspace_offset = 0;
status = Op0::initialize_workspace(problem_shape, args.op_0, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op0::get_workspace_size(problem_shape, args.op_0); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
return status; }
CUTLASS_HOST_DEVICE Sm90VisitorImplBase() {}
CUTLASS_HOST_DEVICE Sm90VisitorImplBase(Params const& params, SharedStorage const& shared_storage) : ops({ Op0(params.op_0, get<0>(shared_storage)) }) {}
tuple<Op0> ops;};
template <class Op0, class Op1>struct Sm90VisitorImplBase<Op0, Op1> {
using SharedStorage = tuple< typename Op0::SharedStorage, typename Op1::SharedStorage >;
struct Arguments { typename Op0::Arguments op_0; typename Op1::Arguments op_1; };
struct Params { typename Op0::Params op_0; typename Op1::Params op_1; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { size_t op_0_workspace_size = Op0::get_workspace_size(problem_shape, args.op_0); uint8_t* op_0_workspace = reinterpret_cast<uint8_t*>(workspace); uint8_t* op_1_workspace = op_0_workspace + op_0_workspace_size; return Params{ Op0::to_underlying_arguments(problem_shape, args.op_0, op_0_workspace), Op1::to_underlying_arguments(problem_shape, args.op_1, op_1_workspace) }; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return Op0::can_implement(problem_shape, args.op_0) && Op1::can_implement(problem_shape, args.op_1); }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { size_t workspace_size = 0; workspace_size += Op0::get_workspace_size(problem_shape, args.op_0); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
workspace_size += Op1::get_workspace_size(problem_shape, args.op_1); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
return workspace_size; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { Status status = Status::kSuccess; uint8_t* workspace_ptr = reinterpret_cast<uint8_t*>(workspace); size_t workspace_offset = 0;
status = Op0::initialize_workspace(problem_shape, args.op_0, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op0::get_workspace_size(problem_shape, args.op_0); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
status = Op1::initialize_workspace(problem_shape, args.op_1, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op1::get_workspace_size(problem_shape, args.op_1); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
return status; }
CUTLASS_HOST_DEVICE Sm90VisitorImplBase() {}
CUTLASS_HOST_DEVICE Sm90VisitorImplBase(Params const& params, SharedStorage const& shared_storage) : ops({ Op0(params.op_0, get<0>(shared_storage)), Op1(params.op_1, get<1>(shared_storage)) }) {}
tuple<Op0, Op1> ops;};
template <class Op0, class Op1, class Op2>struct Sm90VisitorImplBase<Op0, Op1, Op2> {
using SharedStorage = tuple< typename Op0::SharedStorage, typename Op1::SharedStorage, typename Op2::SharedStorage >;
struct Arguments { typename Op0::Arguments op_0; typename Op1::Arguments op_1; typename Op2::Arguments op_2; };
struct Params { typename Op0::Params op_0; typename Op1::Params op_1; typename Op2::Params op_2; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { size_t op_0_workspace_size = Op0::get_workspace_size(problem_shape, args.op_0); size_t op_1_workspace_size = Op1::get_workspace_size(problem_shape, args.op_1); uint8_t* op_0_workspace = reinterpret_cast<uint8_t*>(workspace); uint8_t* op_1_workspace = op_0_workspace + op_0_workspace_size; uint8_t* op_2_workspace = op_1_workspace + op_1_workspace_size; return Params{ Op0::to_underlying_arguments(problem_shape, args.op_0, op_0_workspace), Op1::to_underlying_arguments(problem_shape, args.op_1, op_1_workspace), Op2::to_underlying_arguments(problem_shape, args.op_2, op_2_workspace) }; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return Op0::can_implement(problem_shape, args.op_0) && Op1::can_implement(problem_shape, args.op_1) && Op2::can_implement(problem_shape, args.op_2); }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { size_t workspace_size = 0; workspace_size += Op0::get_workspace_size(problem_shape, args.op_0); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
workspace_size += Op1::get_workspace_size(problem_shape, args.op_1); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
workspace_size += Op2::get_workspace_size(problem_shape, args.op_2); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
return workspace_size; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { Status status = Status::kSuccess; uint8_t* workspace_ptr = reinterpret_cast<uint8_t*>(workspace); size_t workspace_offset = 0;
status = Op0::initialize_workspace(problem_shape, args.op_0, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op0::get_workspace_size(problem_shape, args.op_0); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
status = Op1::initialize_workspace(problem_shape, args.op_1, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op1::get_workspace_size(problem_shape, args.op_1); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
status = Op2::initialize_workspace(problem_shape, args.op_2, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op2::get_workspace_size(problem_shape, args.op_2); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
return status; }
CUTLASS_HOST_DEVICE Sm90VisitorImplBase() {}
CUTLASS_HOST_DEVICE Sm90VisitorImplBase(Params const& params, SharedStorage const& shared_storage) : ops({ Op0(params.op_0, get<0>(shared_storage)), Op1(params.op_1, get<1>(shared_storage)), Op2(params.op_2, get<2>(shared_storage)) }) {}
tuple<Op0, Op1, Op2> ops;};
template <class Op0, class Op1, class Op2, class Op3>struct Sm90VisitorImplBase<Op0, Op1, Op2, Op3> {
using SharedStorage = tuple< typename Op0::SharedStorage, typename Op1::SharedStorage, typename Op2::SharedStorage, typename Op3::SharedStorage >;
struct Arguments { typename Op0::Arguments op_0; typename Op1::Arguments op_1; typename Op2::Arguments op_2; typename Op3::Arguments op_3; };
struct Params { typename Op0::Params op_0; typename Op1::Params op_1; typename Op2::Params op_2; typename Op3::Params op_3; };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { size_t op_0_workspace_size = Op0::get_workspace_size(problem_shape, args.op_0); size_t op_1_workspace_size = Op1::get_workspace_size(problem_shape, args.op_1); size_t op_2_workspace_size = Op2::get_workspace_size(problem_shape, args.op_2); uint8_t* op_0_workspace = reinterpret_cast<uint8_t*>(workspace); uint8_t* op_1_workspace = op_0_workspace + op_0_workspace_size; uint8_t* op_2_workspace = op_1_workspace + op_1_workspace_size; uint8_t* op_3_workspace = op_2_workspace + op_2_workspace_size; return Params{ Op0::to_underlying_arguments(problem_shape, args.op_0, op_0_workspace), Op1::to_underlying_arguments(problem_shape, args.op_1, op_1_workspace), Op2::to_underlying_arguments(problem_shape, args.op_2, op_2_workspace), Op3::to_underlying_arguments(problem_shape, args.op_3, op_3_workspace) }; } template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { return Op0::can_implement(problem_shape, args.op_0) && Op1::can_implement(problem_shape, args.op_1) && Op2::can_implement(problem_shape, args.op_2) && Op3::can_implement(problem_shape, args.op_3); }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { size_t workspace_size = 0; workspace_size += Op0::get_workspace_size(problem_shape, args.op_0); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
workspace_size += Op1::get_workspace_size(problem_shape, args.op_1); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
workspace_size += Op2::get_workspace_size(problem_shape, args.op_2); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
workspace_size += Op3::get_workspace_size(problem_shape, args.op_3); workspace_size = round_nearest(workspace_size, MinWorkspaceAlignment);
return workspace_size; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { Status status = Status::kSuccess; uint8_t* workspace_ptr = reinterpret_cast<uint8_t*>(workspace); size_t workspace_offset = 0;
status = Op0::initialize_workspace(problem_shape, args.op_0, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op0::get_workspace_size(problem_shape, args.op_0); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
status = Op1::initialize_workspace(problem_shape, args.op_1, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op1::get_workspace_size(problem_shape, args.op_1); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
status = Op2::initialize_workspace(problem_shape, args.op_2, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op2::get_workspace_size(problem_shape, args.op_2); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
status = Op3::initialize_workspace(problem_shape, args.op_3, workspace_ptr + workspace_offset, stream, cuda_adapter); workspace_offset += Op3::get_workspace_size(problem_shape, args.op_3); workspace_offset = round_nearest(workspace_offset, MinWorkspaceAlignment); if (status != Status::kSuccess) { return status; }
return status; }
CUTLASS_HOST_DEVICE Sm90VisitorImplBase() {}
CUTLASS_HOST_DEVICE Sm90VisitorImplBase(Params const& params, SharedStorage const& shared_storage) : ops({ Op0(params.op_0, get<0>(shared_storage)), Op1(params.op_1, get<1>(shared_storage)), Op2(params.op_2, get<2>(shared_storage)), Op3(params.op_3, get<3>(shared_storage)) }) {}
tuple<Op0, Op1, Op2, Op3> ops;};
} // namespace detail
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763/*************************************************************************************************** * Copyright (c) 2024 - 2025 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. * **************************************************************************************************/
/*! \file \brief Visitor tree Top-K + Softmax fusion operation for sm90 TMA warp-specialized epilogue*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/workspace.h"
#include "cute/tensor.hpp"#include "sm90_visitor_tma_warpspecialized.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::epilogue::fusion {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Top-K + Softmax reduction across columns// Performs a reduction of top-K values across N, and finally performs a softmax on them,// and sets values not in the top-K to 0.//// Assumptions:// 1. CTA_N >= N (single tile across N, the mode which is reduced)// 2. EPI_N >= N (single epilogue tile across N, because we can reduce and revisit one// epilogue tile at a time.)// 3. Top-K value is either 2 or 4.//
namespace detail {
// Implementations for add to sorted list and merging sorted lists,// with fast paths for lists of size 2 and 4 (Top-2 and Top-4).// Generic implementations may result in greater register use and branching,// and should be avoided.// Fast paths for Top-2 and Top-4 are written in inline PTX directly.
CUTLASS_DEVICEArray<float, 2> top_2_reduce_scalar(Array<float, 2> a, float scalar) { Array<float, 2> out; asm volatile( "{\n" " .reg .f32 mx;\n" " .reg .pred p;\n" " max.f32 mx, %3, %4;\n" " setp.gtu.f32 p, %2, %4;\n" " selp.f32 %1, mx, %2, p;\n" " selp.f32 %0, %2, %4, p;\n" "}\n" : "=f"(out[0]), "=f"(out[1]) : "f"(a[0]), "f"(a[1]), "f"(scalar)); return out;}
CUTLASS_DEVICEArray<float, 2> top_2_reduce(Array<float, 2> a, Array<float, 2> b) { Array<float, 2> out; asm volatile( "{\n" " .reg .v2 .f32 mx;\n" " .reg .pred p;\n" " max.f32 mx.x, %3, %4;\n" // max(a1, b0) " max.f32 mx.y, %2, %5;\n" // max(a0, b1) " setp.gtu.f32 p, %2, %4;\n" // a0 > b0 " selp.f32 %1, mx.x, mx.y, p;\n" // a0 > b0 ? max(a1, b0) : max(a0, b1) " selp.f32 %0, %2, %4, p;\n" // a0 > b0 ? a0 : b0 "}\n" : "=f"(out[0]), "=f"(out[1]) : "f"(a[0]), "f"(a[1]), "f"(b[0]), "f"(b[1])); return out;}
CUTLASS_DEVICEArray<float, 4> top_4_reduce_scalar(Array<float, 4> a, float scalar) { Array<float, 4> out; asm volatile( "{\n" " .reg .f32 mx;\n" // max(a3, b) " .reg .pred p0;\n" // a0 > b " .reg .pred p1;\n" // a1 > b " .reg .pred p2;\n" // a2 > b " max.f32 mx, %7, %8;\n" // max(a3, b) " setp.gtu.f32 p0, %4, %8;\n" // a0 > b " setp.gtu.f32 p1, %5, %8;\n" // a1 > b " setp.gtu.f32 p2, %6, %8;\n" // a2 > b " selp.f32 %3, mx, %6, p2;\n" // a2 > b ? max(a3, b) : a2 " selp.f32 %2, %6, %8, p2;\n" // a1 = a2 > b ? a2 : b " selp.f32 %2, %2, %5, p1;\n" // a1 > b ? max(a2, b) : a1 == a1 > b ? a1 : old_a1 " selp.f32 %1, %5, %8, p1;\n" // a0 = a1 > b ? a1 : b " selp.f32 %1, %1, %4, p0;\n" // a0 > b ? max(a1, b) : a0 == a0 > b ? a0 : old_a0 " selp.f32 %0, %4, %8, p0;\n" // a0 = a0 > b ? a0 : b "}\n" : "=f"(out[0]), "=f"(out[1]), "=f"(out[2]), "=f"(out[3]) : "f"(a[0]), "f"(a[1]), "f"(a[2]), "f"(a[3]), "f"(scalar)); return out;}
CUTLASS_DEVICEArray<float, 4> top_4_reduce(Array<float, 4> a, Array<float, 4> b) { Array<float, 4> out; asm volatile( "{\n" " .reg .f32 mxa0b1;\n" // max(a0, b1) " .reg .f32 mxa1b0;\n" // max(a1, b0)
" .reg .f32 mxa2b0;\n" // max(a2, b0) " .reg .f32 mxa1b1;\n" // max(a1, b1) " .reg .f32 mxa0b2;\n" // max(a1, b1)
" .reg .f32 mxa1b2;\n" // max(a1, b2) " .reg .f32 mxa2b1;\n" // max(a2, b1) " max.f32 mxa1b2, %5, %10;\n" " max.f32 mxa2b1, %6, %9;\n"
" .reg .f32 mxa3b0;\n" // max(a1, b2) " .reg .f32 mxa0b3;\n" // max(a2, b1) " max.f32 mxa3b0, %7, %8;\n" " max.f32 mxa0b3, %4, %11;\n"
" .reg .pred pa0b0;\n" // a0 > b0 " .reg .pred pa1b0;\n" // a1 > b0 " .reg .pred pa2b0;\n" // a2 > b0 " .reg .pred pa0b1;\n" // a0 > b1 " .reg .pred pa1b1;\n" // a1 > b1 " .reg .pred pa0b2;\n" // a0 > b2 " .reg .pred pb2a0;\n" // b1 > a0 " .reg .pred pb1a0;\n" // b1 > a0
" setp.gtu.f32 pa0b0, %4, %8;\n" // a0 > b0 " setp.gtu.f32 pa1b0, %5, %8;\n" // a1 > b0 " setp.gtu.f32 pa2b0, %6, %8;\n" // a2 > b0 " setp.gtu.f32 pa0b1, %4, %9;\n" // a0 > b1 " setp.gtu.f32 pa1b1, %5, %9;\n" // a1 > b1 " setp.gtu.f32 pa0b2, %4, %10;\n" // a0 > b2
" not.pred pb2a0, pa0b2;\n" " not.pred pb1a0, pa0b1;\n"
" selp.f32 mxa1b0, %5, %8, pa1b0;\n" // max(a1, b0) " selp.f32 mxa0b1, %4, %9, pa0b1;\n" // max(a0, b1)
" selp.f32 mxa1b1, %5, %9, pa1b1;\n" // max(a1, b1) " selp.f32 mxa2b0, %6, %8, pa2b0;\n" // max(a2, b0) " selp.f32 mxa0b2, %4, %10, pa0b2;\n" // max(a0, b2)
// a0 " selp.f32 %0, %4, %8, pa0b0;\n" // a0 = a0 > b0 ? a0 : b0
// a1 " selp.f32 %1, mxa1b0, mxa0b1, pa0b0;\n" // a1 = a0 > b0 ? max(a1, b0) : max(a0, b1)
// a2 " mov.f32 %2, mxa1b1;\n" // a2 = max(a1, b1) ** most likely case " selp.f32 %2, mxa2b0, %2, pa1b0;\n" // a0 > a1 > b0 " selp.f32 %2, mxa0b2, %2, pb1a0;\n" // b0 > b1 > a0
// a3 " mov.f32 %3, mxa1b2;\n" // a3 = max(a1, b2) ** one of the most likely cases " selp.f32 %3, mxa2b1, %3, pa1b1;\n" // a3 = a1 > b1 ? max(a2, b1) ** second most likely case " selp.f32 %3, mxa3b0, %3, pa2b0;\n" // a0 > a1 > a2 > b0 " selp.f32 %3, mxa0b3, %3, pb2a0;\n" // b0 > b1 > b2 > a0 "}\n" : "=f"(out[0]), "=f"(out[1]), "=f"(out[2]), "=f"(out[3]) : "f"(a[0]), "f"(a[1]), "f"(a[2]), "f"(a[3]), "f"(b[0]), "f"(b[1]), "f"(b[2]), "f"(b[3])); return out;}
// Assumption: array elements are sorted in descending order// (a[0] is the largest element in a[].)template <typename Element, int N>CUTLASS_DEVICEvoid add_element_to_desc_sorted_array(cutlass::Array<Element, N>& a, Element b) { if constexpr (N == 2 && is_same_v<Element, float>) { a = top_2_reduce_scalar(a, b); } else if constexpr (N == 4 && is_same_v<Element, float>) { a = top_4_reduce_scalar(a, b); } else { // slower generic path with branching, slower, and can cause register spill CUTLASS_PRAGMA_UNROLL for (int k = 0; k < N; ++k) { if (a[k] < b) { // Shift down CUTLASS_PRAGMA_UNROLL for (int l = N - 1; l > k; --l) { a[l] = a[l-1]; } a[k] = b; break; } } }}
// Assumption: array elements are sorted in descending order// (a[0] and b[0] are the largest elements in a[] and b[].)template <typename Element, int N>CUTLASS_DEVICEvoid merge_desc_sorted_arrays(cutlass::Array<Element, N>& a, const cutlass::Array<Element, N>& b) { if constexpr (N == 2 && is_same_v<Element, float>) { a = top_2_reduce(a, b); } else if constexpr (N == 4 && is_same_v<Element, float>) { a = top_4_reduce(a, b); } else { // slower generic path with branching, slower, and can cause register spill int j = 0; CUTLASS_PRAGMA_UNROLL for (int k = 0; k < N; ++k) { if (a[k] < b[j]) { // Shift down CUTLASS_PRAGMA_UNROLL for (int l = N - 1; l > k; --l) { a[l] = a[l-1]; } a[k] = b[j]; ++j; } } }}
// Assumption: array elements are sorted in descending order// (a[0] is the largest element in a[].)template <typename Element, int N>CUTLASS_DEVICEElement topk_logsumexp(cutlass::Array<Element, N> a) { // Do one less `exp`, because we know what its result will be. // Assume x is a set of `x_i`s, and `x_m` is the maximum of that set. // logsumexp(x) = log(sum(x_i)) = m + log(sum(x_i - m)) = m + log(1 + sum_{i != m}(x_i - x_m)) // Compute m + log(1 + sum_{i != m}(x_i - x_m)) Element sum = Element(1.0); CUTLASS_PRAGMA_UNROLL for (int i = 1; i < N; ++i) { sum += fast_exp(a[i] - a[0]); } return a[0] + fast_log(sum);}
CUTLASS_DEVICEfloat fast_masked_softmax(float value, float minimum, float logsumexp) { float new_value; asm volatile( "{\n" " .reg .pred p0;\n" // value >= minimum " setp.geu.f32 p0, %1, %2;\n"
" .reg .f32 x_lse;\n" " .reg .f32 %%f<11>;\n" " .reg .b32 %%r<3>;\n"
// x_lse = value - minimum " sub.rn.f32 x_lse, %1, %3;\n"
// exp(x_lse) // The following is derived from a ptx dump of expf. // exp requires a base conversion from exp2. " fma.rn.f32 %%f1, x_lse, 0f3BBB989D, 0f3F000000;\n" " cvt.sat.f32.f32 %%f2, %%f1;\n" " fma.rm.f32 %%f3, %%f2, 0f437C0000, 0f4B400001;\n" " add.f32 %%f4, %%f3, 0fCB40007F;\n" " neg.f32 %%f5, %%f4;\n" " fma.rn.f32 %%f6, x_lse, 0f3FB8AA3B, %%f5;\n" " fma.rn.f32 %%f7, x_lse, 0f32A57060, %%f6;\n" " mov.b32 %%r1, %%f3;\n" " shl.b32 %%r2, %%r1, 23;\n" " mov.b32 %%f8, %%r2;\n" " ex2.approx.ftz.f32 %%f9, %%f7;\n" " mul.f32 %%f10, %%f9, %%f8;\n"
// Mask or softmax " selp.f32 %0, %%f10, 0f00000000, p0;\n" "}\n" : "=f"(new_value) : "f"(value), "f"(minimum), "f"(logsumexp)); return new_value;}
template <typename Element>CUTLASS_DEVICEElement masked_softmax(Element value, Element minimum, Element logsumexp) { if constexpr (is_same_v<Element, float>) { // Inline PTX implementation // Significantly reduces register requirements return fast_masked_softmax(value, minimum, logsumexp); } else { return value < minimum ? Element(0.0) : fast_exp(value - logsumexp); }}
} // namespace detail
template < int TopK, int FragmentSize, class CtaTileShapeMNK, class EpilogueTile, class ElementOutput, class ElementCompute, FloatRoundStyle RoundStyle, int Alignment = 128 / sizeof_bits_v<ElementOutput>, bool UseButterflyReduce = true>struct Sm90TopKSoftmaxColReduction {private: static_assert(is_same_v<ElementCompute, float>, "Fused Top-K + Softmax reduction requires FP32 accumulation."); static_assert(TopK == 2 || TopK == 4, "Fused Top-K + Softmax reduction only allows K=2 and K=4, because those cases have been performance-optimized. Other values of K can be enabled by removing this assertion, but they may come with serious performance implications." ); static_assert(Alignment * sizeof_bits_v<ElementOutput> % 128 == 0, "sub-16B alignment not supported yet");
// Reduction tensors // We have two tensors for this EVT node: a reduction tensor and a tensor holding // final reduction values (tCrSoftmax). The reason for this is that Top-K and Softmax // require different reductions, but those luckily overlap. Top-K obviously needs at least // two values (K >= 2), and softmax needs one value: logsumexp. Logsumexp is simply the log // of sum of exponents over the set, and is equivalent to m + sum(exp(x_i - m)), where m is the // maximum of all x_i elements. Since safe softmax for any element x_i is computed as // softmax(x_i) = exp(x_i - m) / sum_j(exp(x_j - max)) // we can track logsumexp instead of tracking two variables (sum of exps and the max). // In addition, subtracting logsumexp from any element and taking its exp is equivalent to // computing its softmax. // // The overlap between softmax and top-K is that we don't need to reduce logsumexp along the // way at all, because any element not in the top-K is going to be masked out and set to 0. // Therefore, we only reduce the top-K elements, and when done, compute their logsumexp and // keep it, and the smallest element in the top-K for masking out non-top-K elements. // // This means that our final reduction result will always be 2 elements, regardless of the value // of K: minimum of top-K, and logsumexp. // // For each reduction tensor, we define a new struct for readability.
struct ReductionResult { ElementCompute min_; ElementCompute logsumexp_;
CUTLASS_DEVICE ReductionResult() { }
CUTLASS_DEVICE ReductionResult(ElementCompute min, ElementCompute logsumexp): logsumexp_(logsumexp), min_(min) { }
// Warp shuffle broadcast CUTLASS_DEVICE void shuffle_up_sync(uint32_t delta, int lane_id) { static_assert(sizeof(ReductionResult) == sizeof(uint64_t)); uint64_t r = reinterpret_cast<uint64_t&>(*this); r = __shfl_up_sync(0xFFFFFFFF, r, delta); *this = (lane_id - static_cast<int>(delta) >= 0) ? reinterpret_cast<ReductionResult&>(r) : *this; } };
struct TopKResult { Array<ElementCompute, TopK> top_k_;
CUTLASS_DEVICE TopKResult() { top_k_.fill(-cutlass::platform::numeric_limits<ElementCompute>::infinity()); }
// This is where we do the "final" reduction, where we compute // the logsumexp for softmax, keep the smallest value in top-K, // and discard the rest. CUTLASS_DEVICE ReductionResult reduce_final() const { return ReductionResult(top_k_[TopK - 1], topk_logsumexp(top_k_)); }
// Butterfly reduction CUTLASS_DEVICE void shuffle_xor_sync(int laneMask) { if constexpr (TopK == 2) { static_assert(sizeof(TopKResult) == sizeof(uint64_t)); uint64_t top_k = reinterpret_cast<uint64_t&>(*this); top_k = __shfl_xor_sync(0xFFFFFFFF, top_k, laneMask); auto synced_v = reinterpret_cast<TopKResult&>(top_k); detail::merge_desc_sorted_arrays(top_k_, synced_v.top_k_); } else if constexpr (TopK == 4) { static_assert(sizeof(TopKResult) == 2 * sizeof(uint64_t)); uint64_t* top_k_ptr = reinterpret_cast<uint64_t*>(this); uint64_t top_k_arr[2]; top_k_arr[0] = top_k_ptr[0]; top_k_arr[1] = top_k_ptr[1]; top_k_arr[0] = __shfl_xor_sync(0xFFFFFFFF, top_k_arr[0], laneMask); top_k_arr[1] = __shfl_xor_sync(0xFFFFFFFF, top_k_arr[1], laneMask); auto synced_v = reinterpret_cast<TopKResult&>(top_k_arr); detail::merge_desc_sorted_arrays(top_k_, synced_v.top_k_); } else { TopKResult synced_v; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < TopK; ++i) { synced_v.top_k_[i] = __shfl_xor_sync(0xFFFFFFFF, top_k_[i], laneMask); } detail::merge_desc_sorted_arrays(top_k_, synced_v.top_k_); } }
// Warp shuffle reduction CUTLASS_DEVICE void shuffle_down_sync(uint32_t delta) { if constexpr (TopK == 2) { static_assert(sizeof(TopKResult) == sizeof(uint64_t)); uint64_t top_k = reinterpret_cast<uint64_t&>(*this); top_k = __shfl_down_sync(0xFFFFFFFF, top_k, delta); auto synced_v = reinterpret_cast<TopKResult&>(top_k); detail::merge_desc_sorted_arrays(top_k_, synced_v.top_k_); } else if constexpr (TopK == 4) { static_assert(sizeof(TopKResult) == 2 * sizeof(uint64_t)); uint64_t* top_k_ptr = reinterpret_cast<uint64_t*>(this); uint64_t top_k_arr[2]; top_k_arr[0] = top_k_ptr[0]; top_k_arr[1] = top_k_ptr[1]; top_k_arr[0] = __shfl_down_sync(0xFFFFFFFF, top_k_arr[0], delta); top_k_arr[1] = __shfl_down_sync(0xFFFFFFFF, top_k_arr[1], delta); auto synced_v = reinterpret_cast<TopKResult&>(top_k_arr); detail::merge_desc_sorted_arrays(top_k_, synced_v.top_k_); } else { TopKResult synced_v; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < TopK; ++i) { synced_v.top_k_[i] = __shfl_down_sync(0xFFFFFFFF, top_k_[i], delta); } detail::merge_desc_sorted_arrays(top_k_, synced_v.top_k_); } } };
public: struct SharedStorage { };
struct Arguments { };
struct Params { };
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { return {}; }
template <class ProblemShape> static bool can_implement(ProblemShape const& problem_shape, Arguments const& args) { auto [M, N, K, L] = problem_shape; auto [tile_M, tile_N, tile_K] = CtaTileShapeMNK{}; // Cross CTA reduction is not possible because there is no guarantee that all CTAs run // concurrently. // Cross epilogue tile reduction is possible, but re-visiting and applying reduction // to accumulators is only possible for the current epilogue tile. auto [epi_M, epi_N] = EpilogueTile{}; return N <= tile_N && N <= epi_N && N >= TopK; }
template <class ProblemShape> static size_t get_workspace_size(ProblemShape const& problem_shape, Arguments const& args) { return 0; }
template <class ProblemShape> static cutlass::Status initialize_workspace(ProblemShape const& problem_shape, Arguments const& args, void* workspace, cudaStream_t stream, CudaHostAdapter* cuda_adapter = nullptr) { return Status::kSuccess; }
CUTLASS_DEVICE bool is_producer_load_needed() const { return false; }
CUTLASS_DEVICE bool is_C_load_needed() const { return false; }
CUTLASS_HOST_DEVICE Sm90TopKSoftmaxColReduction() { }
CUTLASS_HOST_DEVICE Sm90TopKSoftmaxColReduction(Params const& params, SharedStorage const& shared_storage) : params(params) { }
Params params;
template <class... Args> CUTLASS_DEVICE auto get_producer_load_callbacks(ProducerLoadArgs<Args...> const& args) { return EmptyProducerLoadCallbacks{}; }
template<class ArgsTuple> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks(ArgsTuple&& args_tuple, Params const& params) : args_tuple(cute::forward<ArgsTuple>(args_tuple)), params(params) {}
ArgsTuple args_tuple; Params const& params;
template <typename ElementAccumulator, typename ElementInput> CUTLASS_DEVICE auto visit(Array<ElementAccumulator, FragmentSize> const& frg_acc, int epi_v, int epi_m, int epi_n, Array<ElementInput, FragmentSize> const& frg_input) {
auto& [tCrTopK, tCrSoftmax, tCcCol, cCol, lane_layout_MN, lane_mn, residue_cCol, residue_tCcCol] = args_tuple; Tensor tCcCol_mn = tCcCol(_,_,_,epi_m,epi_n);
using ConvertInput = NumericArrayConverter<ElementCompute, ElementInput, FragmentSize, RoundStyle>; ConvertInput convert_input{};
Array frg_I = convert_input(frg_input); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { auto thread_crd = tCcCol_mn(epi_v * FragmentSize + i); if (elem_less(thread_crd, residue_tCcCol)) { TopKResult& tCrCol_vmn = tCrTopK(epi_v * FragmentSize + i); detail::add_element_to_desc_sorted_array(tCrCol_vmn.top_k_, frg_I[i]); } }
return frg_input; }
template <class STensor, class SyncFn, class VTensor> CUTLASS_DEVICE void reduce(STensor&& smem_buffer, SyncFn const& sync_fn, int epi_m, int epi_n, bool is_last_iteration, VTensor visit_results) {
auto& [tCrTopK, tCrSoftmax, tCcCol, cCol, lane_layout_MN, lane_mn, residue_cCol, residue_tCcCol] = args_tuple;
// fully OOB CTA in partially OOB cluster if (not elem_less(cCol(_0{},_0{}), residue_cCol)) { return; } Tensor tCcCol_mn = tCcCol(_,_,_,epi_m,epi_n);
// `tCrTopK` and `tCrSoftmax` have 0-strides along modes that correspond to N, // in order to reduce along modes in the `R2S` sublayout that correspond to N. // This means we should modify and warp-reduce them according to their co-domain instead of // their domain. Therefore we keep a filtered view of both and use them as necessary. auto tCrTopK_f = filter(tCrTopK); auto tCrSoftmax_f = filter(tCrSoftmax);
// The pattern here is: reduce Top-K first, then compute logsumexp, keep it and the // last element of Top-K, use the latter to mask the visited results, and the former // to apply softmax. // // This gives us two options: reduce the Top-K with warp shuffles, have the reduced // lanes compute logsumexp and pair it with the last Top-K element, and broadcast // the result back using warp shuffles. // // Alternatively, we can do a butterfly reduction over Top-K, and have all lanes // compute their own logsumexp and skip the broadcast. if constexpr (UseButterflyReduce) { // // 1. Butterfly reduction // CUTLASS_PRAGMA_UNROLL for (int j = 1; j < size<1>(lane_layout_MN); j *= 2) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrTopK_f); ++i) { tCrTopK_f(i).shuffle_xor_sync(j); } }
// // 2. Strip down reduced value and compute sum of exps // CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrSoftmax_f); ++i) { tCrSoftmax_f(i) = tCrTopK_f(i).reduce_final(); } } else { // // 1. Warp shuffle reduction // CUTLASS_PRAGMA_UNROLL for (int reduction_cols = size<1>(lane_layout_MN) / 2; reduction_cols > 0; reduction_cols /= 2) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrTopK_f); ++i) { tCrTopK_f(i).shuffle_down_sync(lane_layout_MN(_0{},reduction_cols)); } }
// // 2. Strip down reduced value and compute sum of exps // bool is_reduced_lane = get<1>(lane_mn) == 0; if (is_reduced_lane) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrSoftmax_f); ++i) { tCrSoftmax_f(i) = tCrTopK_f(i).reduce_final(); } }
// // 3. Broadcast reduced values to all participants // CUTLASS_PRAGMA_UNROLL for (int broadcast_cols = 1; broadcast_cols <= size<1>(lane_layout_MN) / 2; broadcast_cols *= 2) { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(tCrSoftmax_f); ++i) { tCrSoftmax_f(i).shuffle_up_sync(lane_layout_MN(_0{},broadcast_cols), get<1>(lane_mn)); } } }
// // 4. Re-visit and apply top-K and softmax // CUTLASS_PRAGMA_UNROLL for (int epi_v = 0; epi_v < size(visit_results); ++epi_v) { auto& visit_frag = visit_results(epi_v); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < FragmentSize; ++i) { visit_frag[i] = detail::masked_softmax( visit_frag[i], tCrSoftmax(epi_v * FragmentSize + i).min_, tCrSoftmax(epi_v * FragmentSize + i).logsumexp_ ); } }
}
CUTLASS_DEVICE void end_loop(int epi_m, int epi_n) { auto& [tCrTopK, tCrSoftmax, tCcCol, cCol, lane_layout_MN, lane_mn, residue_cCol, residue_tCcCol] = args_tuple;
// Reset reduced top-K values for next tile // This must be done because we only assume a single epilogue tile across N, // but not M. fill(tCrTopK, TopKResult()); }
CUTLASS_DEVICE void end() { }
};
template < bool ReferenceSrc, // do register tensors reference the src or dst layout of the tiled copy class... Args > CUTLASS_DEVICE auto get_consumer_store_callbacks(ConsumerStoreArgs<Args...> const& args) { Layout ref_layout_MN = [&] () { auto mn_shape = shape(typename decltype(args.tiled_copy)::Tiler_MN{}); if constexpr (ReferenceSrc) { return right_inverse(args.tiled_copy.get_layoutS_TV()).with_shape(mn_shape); } else { return right_inverse(args.tiled_copy.get_layoutD_TV()).with_shape(mn_shape); } }(); // tile_mn -> tv_idx
// Get the MN layout + coord of lanes to determine shuffle reduction iterations using _W = Int<decltype(args.tiled_copy)::TiledNumThr::value / NumThreadsPerWarp>; Layout tv2lane = Layout<Shape<Int<NumThreadsPerWarp>,_W,_1>,Stride<_1,_0,_0>>{}; // tv_idx -> lane_idx Layout ref2lane = composition(tv2lane, ref_layout_MN); // tile_mn -> lane_idx Layout lane_layout_MN = make_layout(filter(get<0>(ref2lane)), filter(get<1>(ref2lane))); // lane_mn -> lane_idx Layout inv_lane_layout_MN = right_inverse(lane_layout_MN); // lane_idx -> lane_mn int lane_idx = canonical_lane_idx(); auto lane_mn = idx2crd(inv_lane_layout_MN(lane_idx), shape(lane_layout_MN));
// Get the MN layout + coord of warps to determine smem reduction iterations Layout tv2warp = Layout<Shape<Int<NumThreadsPerWarp>,_W,_1>,Stride<_0,_1,_0>>{}; // tv_idx -> warp_idx Layout ref2warp = composition(tv2warp, ref_layout_MN); // tile_mn -> warp_idx Layout warp_layout_MN = make_layout(filter(get<0>(ref2warp)), filter(get<1>(ref2warp))); // warp_mn -> warp_idx
// Make sure there's only one warp across N so we can use warp shuffle intrinsics for reduction. static_assert(decltype(size<1>(warp_layout_MN))::value <= 1);
// Reduction layout // We're assuming all elements in a row (over which we're performing the reduction) are // visited in the same corresponding epilogue tile, and this is what allows us to apply the // top-K + softmax operation within `reduce()`, by re-visiting the accumulated results. // // This presents a challenge, because the layout of the accumulated results is typically in // in the register to shared memory shape, or: (R2S,R2S_M,R2S_N). // This means that we still need to reduce this tensor along N. // // The solution is simple: we need to flatten the layout, identify modes that correspond to // N and set their strides to 0, in order to map fragment indices corresponding to the same // row back to the same element in the tensor. // // This requires some extra layout manipulation, which is as follows.
// Create new accumulator layout with column broadcast auto [M, N, K] = args.tile_shape_mnk; auto thr_mma = args.tiled_mma.get_thread_slice(args.thread_idx); auto gColReduce = make_tensor<ElementCompute>( make_layout(make_shape(M, N), make_stride(_1{}, 0_c))); // (M,N) auto tCrColReduce = make_tensor_like<ElementCompute>( // (FrgV, MMA_M, MMA_N) thr_mma.partition_C(gColReduce).layout());
// Tile the new accumulator tensor according to R2S ThrCopy thread_r2s = args.tiled_copy.get_slice(args.thread_idx); Tensor tRS_rSoftmax = thread_r2s.retile_S(tCrColReduce); // ((R2S,R2S_V),MMA_M,MMA_N) auto tCrC_layout = args.tCrC.layout(); // (R2S,R2S_M,R2S_N)
// Compose the new accumulator R2S layout with the expected tCrC layout to get final // reduction tensor layout. auto tCrSoftmax_layout = take<0, 3>(tRS_rSoftmax.layout()).compose(tCrC_layout); // (R2S,R2S_V) o (R2S,R2S_M,R2S_N)
Tensor tCrTopK = make_tensor<TopKResult>(tCrSoftmax_layout); // (R2S,R2S_M,R2S_N) Tensor tCrSoftmax = make_tensor<ReductionResult>(tCrSoftmax_layout); // (R2S,R2S_M,R2S_N) fill(tCrTopK, TopKResult());
auto args_tuple = make_tuple( cute::move(tCrTopK), cute::move(tCrSoftmax), args.tCcD, args.cD, lane_layout_MN, lane_mn, args.residue_cD, args.residue_tCcD); return ConsumerStoreCallbacks<decltype(args_tuple)>(std::move(args_tuple), params); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::epilogue::fusion
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914/*************************************************************************************************** * Copyright (c) 2017 - 2025 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. * **************************************************************************************************//*! \file \brief This extends the contents of cutlass/functional.h with frequently used activation functions.
*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/numeric_types.h"#include "cutlass/numeric_conversion.h"#include "cutlass/constants.h"#include "cutlass/complex.h"#include "cutlass/array.h"#include "cutlass/half.h"#include "cutlass/functional.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace thread {
/////////////////////////////////////////////////////////////////////////////////////////////////
// If kIsHeavy is a member, use it. Otherwise, assume that it's false.template<class Op, class Enable = void>struct kIsHeavy_member_or_false { static constexpr bool value = false;};template<class Op>struct kIsHeavy_member_or_false<Op, typename cutlass::platform::enable_if<Op::kIsHeavy>::type> { static constexpr bool value = Op::kIsHeavy;};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Identity operatortemplate <typename T>struct Identity { static const bool kIsHeavy = false;
CUTLASS_HOST_DEVICE T operator()(T value) const { return value; }};
template <typename T, int N>struct Identity<Array<T, N> > { CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> value) const { return value; }};
/// Scale operatortemplate <typename T>struct Scale { struct Arguments { using scale_type = T; T scale = T(1); };
CUTLASS_HOST_DEVICE T operator()(T value, T scale) const { multiplies<T> mul; return mul(scale, value); }
CUTLASS_HOST_DEVICE T operator()(T value, Arguments args = Arguments()) const { return this->operator()(value, args.scale); }};
template <typename T, int N>struct Scale<Array<T, N>> { using Arguments = typename Scale<T>::Arguments;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> values, T scale) const { multiplies<Array<T, N>> mul; return mul(scale, values); }
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> values, Arguments args = Arguments()) const { return this->operator()(values, args.scale); }};
/// Specialization to compose other activations with a defined unary operator/// e.g. Scale<Identity<T>>template <template <class> class Activation, typename T>struct Scale<Activation<T>> { using Arguments = typename Scale<T>::Arguments;
static const bool kIsHeavy = Activation<T>::kIsHeavy;
CUTLASS_HOST_DEVICE T operator()(T value, typename Arguments::scale_type scale) const { multiplies<T> mul; Activation<T> act; return mul(scale, act(value)); }
CUTLASS_HOST_DEVICE T operator()(T value, Arguments args = Arguments()) const { return this->operator()(value, args.scale); }};
/// ReLu operator - propagates NaNstemplate <typename T>struct ReLu { static const bool kIsHeavy = false;
CUTLASS_HOST_DEVICE T operator()(T threshold, T value) const { constexpr bool PropagateNaN = true; maximum<T, PropagateNaN> mx;
return mx(value, threshold); }
CUTLASS_HOST_DEVICE T operator()(T value) const { constexpr bool PropagateNaN = true; maximum<T, PropagateNaN> mx;
return mx(value, T(0)); }};
template <typename T>using ReLU = ReLu<T>;
template <typename T, int N>struct ReLu<Array<T, N>> { static const bool kIsHeavy = false;
CUTLASS_HOST_DEVICE Array<T, N> operator()(T const & threshold, Array<T, N> const &frag) const { constexpr bool PropagateNaN = true; maximum<Array<T, N>, PropagateNaN> mx;
return mx(frag, threshold); }
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &frag) const { constexpr bool PropagateNaN = true; maximum<Array<T, N>, PropagateNaN> mx; return mx(frag, T(0)); }};
// Generic clamptemplate <typename T>struct Clamp { struct Arguments { T lower_bound = CUTLASS_STL_NAMESPACE::numeric_limits<T>::lowest(); T upper_bound = CUTLASS_STL_NAMESPACE::numeric_limits<T>::max(); };
CUTLASS_HOST_DEVICE T operator()(T const& value, T const& lower_bound, T const& upper_bound) const { constexpr bool PropagateNaN = true; maximum<T, PropagateNaN> mx; minimum<T, PropagateNaN> mn;
return mn(mx(value, lower_bound), upper_bound); }
CUTLASS_HOST_DEVICE T operator()(T const& value, Arguments const& args = Arguments()) const { return this->operator()(value, args.lower_bound, args.upper_bound); }};
template <typename T, int N>struct Clamp<Array<T,N>> { using Arguments = typename Clamp<T>::Arguments;
CUTLASS_HOST_DEVICE Array<T,N> operator()(Array<T,N> const& values, T const& lower_bound, T const& upper_bound) const { constexpr bool PropagateNaN = true; maximum<Array<T,N>, PropagateNaN> mx; minimum<Array<T,N>, PropagateNaN> mn;
return mn(mx(values, lower_bound), upper_bound); }
CUTLASS_HOST_DEVICE Array<T,N> operator()(Array<T,N> const& values, Arguments const& args = Arguments()) const { return this->operator()(values, args.lower_bound, args.upper_bound); }};
// Lower Boundtemplate <typename T>struct LowerBound { struct Arguments { T lower_bound; };
CUTLASS_HOST_DEVICE T operator()(T const& value, T const& lower_bound) const { constexpr bool PropagateNaN = true; maximum<T, PropagateNaN> mx;
return mx(value, lower_bound); }
CUTLASS_HOST_DEVICE T operator()(T const& value, Arguments const& args = Arguments()) const { return this->operator()(value, args.lower_bound); }};
template <typename T, int N>struct LowerBound<Array<T,N>> { using Arguments = typename LowerBound<T>::Arguments;
CUTLASS_HOST_DEVICE Array<T,N> operator()(Array<T,N> const& values, T const& lower_bound) const { constexpr bool PropagateNaN = true; maximum<Array<T,N>, PropagateNaN> mx;
return mx(values, lower_bound); }
CUTLASS_HOST_DEVICE Array<T,N> operator()(Array<T,N> const& values, Arguments const& args = Arguments()) const { return this->operator()(values, args.lower_bound); }};
// Leaky Relu operatortemplate <typename T>struct LeakyReLU {
static const bool kIsHeavy = false;
struct Arguments { T leaky_alpha = T(0); };
CUTLASS_HOST_DEVICE T operator()(T const& value, T const& leaky_alpha) const { T res = value > T(0) ? value : value * leaky_alpha; return res; }
CUTLASS_HOST_DEVICE T operator()(T const& value, Arguments const& args = Arguments()) const { return this->operator()(value, args.leaky_alpha); }};
template <typename T, int N>struct LeakyReLU<Array<T, N> > {
static const bool kIsHeavy = false;
using Arguments = typename LeakyReLU<T>::Arguments;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& values, T const& leaky_alpha) const { Array<T, N> y; LeakyReLU<T> leaky_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < int(values.size()); ++i) { y[i] = leaky_op(values[i], leaky_alpha); }
return y; }
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& values, Arguments const& args = Arguments()) const { return this->operator()(values, args.leaky_alpha); }};
// Y = min((X <= threshold ? 0 : X), upper_bound)template <typename T>struct ThresholdReLU { static constexpr bool kIsHeavy = false;
struct Arguments { T threshold = T(0); T upper_bound = CUTLASS_STL_NAMESPACE::numeric_limits<T>::max(); };
CUTLASS_HOST_DEVICE T operator()(T value, T threshold, T upper_bound) const { minimum_with_nan_propagation<T> mn; return mn((value <= threshold ? T(0) : value), upper_bound); }
CUTLASS_HOST_DEVICE T operator()(T value, Arguments const& args = Arguments()) const { return operator()(value, args.threshold, args.upper_bound); }};
template <typename T, int N>struct ThresholdReLU<Array<T,N>> { static constexpr bool kIsHeavy = false;
using Arguments = typename ThresholdReLU<T>::Arguments;
CUTLASS_HOST_DEVICE Array<T,N> operator()(Array<T,N> const& values, T threshold, T upper_bound) const { ThresholdReLU<T> relu;
Array<T,N> retvals; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { retvals[i] = relu(values[i], threshold, upper_bound); }
return retvals; }
CUTLASS_HOST_DEVICE Array<T,N> operator()(Array<T,N> const& values, Arguments const& args = Arguments()) const { return operator()(values, args.threshold, args.upper_bound); }};
// Tanh operatortemplate <typename T>struct Tanh { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE T operator()(T const &value) const { return fast_tanh(value); }};
template <typename T, int N>struct Tanh<Array<T, N> > { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &value) const { Array<T, N> y; Tanh<T> tanh_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = tanh_op(value[i]); }
return y; }};
template <int N>struct Tanh<Array<half_t, N>> { using T = half_t; static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& z) const { fast_tanh_op<Array<T, N>> tanh; return tanh(z); }};
// Sigmoid operatortemplate <typename T>struct Sigmoid { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE T operator()(T const &value) const {#if defined(CUTLASS_USE_TANH_FOR_SIGMOID) return fast_tanh(value * T(0.5)) * T(0.5) + T(0.5);#else return T(1) / (T(1) + fast_exp(-value));#endif }};
template <typename T, int N>struct Sigmoid<Array<T, N>> { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& z) const {#if defined(CUTLASS_USE_TANH_FOR_SIGMOID) multiplies<Array<T, N>> mul; multiply_add<Array<T, N>> fma; fast_tanh_op<Array<T, N>> tanh; return fma(tanh(mul(z, cutlass::constants::half<T>())), cutlass::constants::half<T>(), cutlass::constants::half<T>());#else plus<Array<T, N>> add; divides<Array<T, N>> div; negate<Array<T, N>> neg; fast_exp_op<Array<T, N>> fast_exp; return div(cutlass::constants::one<T>(), add(cutlass::constants::one<T>(), fast_exp(neg(z))));#endif }};
// SiLu (swish) operator introduced by Elfwing et al. in the following paper// "Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning" (2017)// https://arxiv.org/pdf/1702.03118.pdf// It is used in EfficientNet and YOLOv5, for example.// Reference: https://pytorch.org/docs/stable/generated/torch.nn.SiLU.htmltemplate <typename T>struct SiLu { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE T operator()(T const &value) const { Sigmoid<T> sigmoid; return value * sigmoid(value); }};
template <typename T, int N>struct SiLu<Array<T, N>> { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &value) const { Sigmoid<Array<T, N>> sigmoid_op; multiplies<Array<T, N>> mul; return mul(value, sigmoid_op(value)); }};
template <typename T>using ScaledSiLu = Scale<SiLu<T>>;
// Hardswish operator introduced by Howard et al. in the following paper// "Searching for MobileNetV3" (2019)// https://arxiv.org/pdf/1905.02244.pdf// It is used in models based on MobilenetNetV3.// Reference: https://pytorch.org/docs/stable/generated/torch.nn.Hardswish.htmltemplate <typename T>struct HardSwish { static const bool kIsHeavy = false;
CUTLASS_HOST_DEVICE T operator()(T const &x) const { minimum<T> mn; maximum<T> mx; T relu6 = mn(mx(x + T(3), T(0)), T(6)); return x * relu6 / T(6); }};
template <>struct HardSwish<float> { using T = float; static const bool kIsHeavy = false; static constexpr float kOneSixth = 0.16666667f;
CUTLASS_HOST_DEVICE T operator()(T const &x) const { minimum<T> mn; maximum<T> mx; T relu6 = mn(mx(x + T(3), T(0)), T(6)); return x * relu6 * kOneSixth; }};
template <>struct HardSwish<cutlass::half_t> { using T = cutlass::half_t; static const bool kIsHeavy = false; static constexpr float kOneSixth = 0.16666667f;
CUTLASS_HOST_DEVICE T operator()(T const &x) const { minimum<T> mn; maximum<T> mx; T relu6 = mn(mx(x + T(3), T(0)), T(6)); return x * relu6 * T(kOneSixth); }};
template <typename T, int N>struct HardSwish<Array<T, N> > { static const bool kIsHeavy = false;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &value) const { Array<T, N> y; HardSwish<T> hardswish_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = hardswish_op(value[i]); }
return y; }};
template <int N>struct HardSwish<Array<half_t, N> > { using T = half_t; static const bool kIsHeavy = false; static constexpr float kOneSixth = 0.16666667f;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &value) const { minimum<Array<T, N> > mn; maximum<Array<T, N> > mx; multiplies<Array<T, N> > mul; plus<Array<T, N> > add;
return mul(mul(mn(mx(add(value, T(3)), T(0)), T(6)), value), T(kOneSixth)); }};
template <typename T>using ScaledHardSwish = Scale<HardSwish<T>>;
//// GELU function definitions implemented as described by// Hendrycks, D., and Gimpel, K. in// "Gaussian Error Linear Units (GELUs)." (2020)// https://arxiv.org/pdf/1606.08415.pdf//// Floating-point constants are Taylor coefficients described in the paper.//
// GELU operatortemplate <typename T>struct GELU { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE T operator()(T const &value) const { return T(cutlass::constants::half<T>() * value * (cutlass::constants::one<T>() + (T)erff((float)(value * cutlass::constants::half_root_two<T>())))); }};
template <>struct GELU<float> { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE float operator()(float const &value) const { return cutlass::constants::half<float>() * value * (cutlass::constants::one<float>() + erff(value * cutlass::constants::half_root_two<float>() )); }};
template <>struct GELU<double> { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE double operator()(double const &value) const { return cutlass::constants::half<double>() * value * (cutlass::constants::one<double>() + erf( value * cutlass::constants::half_root_two<double>() )); }};
template <typename T, int N>struct GELU<Array<T, N> > { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &value) const { Array<T, N> y; GELU<T> gelu_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = gelu_op(value[i]); }
return y; }};
template <typename T>using ScaledGELU = Scale<GELU<T>>;
// GELU operator implemented using the Taylor series approximationtemplate <typename T>struct GELU_taylor { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE T operator()(T const &z) const {
T k0 = T(0.7978845608028654); T k1 = T(0.044715);
return T(cutlass::constants::half<T>() * z * (cutlass::constants::one<T>() + fast_tanh(k0 * z * (cutlass::constants::one<T>() + k1 * z * z)))); }};
template <>struct GELU_taylor <float>{ static const bool kIsHeavy = true; using T = float; CUTLASS_HOST_DEVICE T operator()(T const &z) const { // 0.5f * (x + x * tanh(x * (0.797885f + 0.0356774f * x * x))); T k0 = T(0.7978845608028654); T tmp = T(0.044715); T k1 = T(k0*tmp); multiply_add<T> fma; multiplies<T> mul; T v0 = mul(k1, z); T v1 = fma(v0, z, k0); T v2 = mul(z, v1); T v3 = fast_tanh(v2); T v4 = fma(z, v3, z); T v5 = mul(cutlass::constants::half<T>(), v4); return v5; }};
template <int N>struct GELU_taylor<Array<half_t, N> > { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<half_t, N> operator()(Array<half_t, N> const &z) const {
using T = half_t; Array<half_t, N> y;
half_t k0 = half_t(0.7978845608028654); half_t k1 = half_t(0.044715);
multiply_add<Array<half_t, N>> fma; multiplies<Array<half_t, N>> mul; plus<Array<half_t, N>> add;
fast_tanh_op<Array<half_t, N>> tanh;
Array<half_t, N> u = mul(mul(k0, z), fma(mul(k1, z), z, cutlass::constants::one<T>()));
y = mul(mul(z, cutlass::constants::half<T>()), add(cutlass::constants::one<T>(), tanh(u)));
return y; }};
template <int N>struct GELU_taylor<Array<float, N> > { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<float, N> operator()(Array<float, N> const &value) const { multiply_add<Array<float, N>> fma; multiplies<Array<float, N>> mul; fast_tanh_op<Array<float, N>> tanh; // 0.5f * (x + x * tanh(x * (0.797885f + 0.0356774f * x * x))); float k0 = float(0.7978845608028654); float tmp = float(0.044715); float k1 = float(k0*tmp);
Array<float, N> v0 = mul(k1, value); Array<float, N> v1 = fma(v0, value, k0); Array<float, N> v2 = mul(value, v1); Array<float, N> v3 = tanh(v2); Array<float, N> v4 = fma(value, v3, value); Array<float, N> v5 = mul(cutlass::constants::half<float>(), v4); return v5; }};
template <typename T, int N>struct GELU_taylor<Array<T, N> > { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &value) const { Array<T, N> y; GELU_taylor<T> gelu_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = gelu_op(value[i]); }
return y; }};
template <typename T>using ScaledGELU_taylor = Scale<GELU_taylor<T>>;
/// Computes backwards pass for GELU operator assuming d_t is the layer gradient and/// z is computed from the forward pass.template <typename T>struct dGELU { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE T operator()(T const &d_t, T const &z) const {
T k0 = T(0.7978845608028654); T k1 = T(0.044715); T k2 = T(0.1070322243);
T tanh_out = fast_tanh(k0 * z * (1 + k1 * z * z));
T ff = constants::half<T>() * z * ((1 - tanh_out * tanh_out) * (k0 + k2 * z * z)) + constants::half<T>() * (1 + tanh_out);
return ff * d_t; }};
template <typename T, int N>struct dGELU<Array<T, N> > { static const bool kIsHeavy = true;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const &d_t, Array<T, N> const &z) const { Array<T, N> y; dGELU<T> gelu_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = gelu_op(d_t[i], z[i]); }
return y; }};
template <typename T>struct dReLU { CUTLASS_HOST_DEVICE T operator()(T d_t, bool d_relu) const { return d_relu ? d_t : T(0); }
template <typename U> CUTLASS_HOST_DEVICE T operator()(T d_t, U d_relu) const { return operator()(d_t, static_cast<bool>(d_relu)); }};
template <typename T, int N>struct dReLU<Array<T, N>> { CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& d_t, bool const (&d_relu)[N]) const { Array<T, N> y; dReLU<T> relu_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = relu_op(d_t[i], d_relu[i]); }
return y; }
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& d_t, Array<uint1b_t, N> const& d_relu) const { UnpackPredicates<N> unpack_op;
bool preds[N]; unpack_op(preds, d_relu);
return operator()(d_t, preds); }
template <typename U> CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& d_t, Array<U, N> const& d_relu) const { Array<T, N> y; dReLU<T> relu_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = relu_op(d_t[i], d_relu[i]); }
return y; }};
/// Computes backwards pass for ReLU operator assuming d_t is the layer gradient and/// z is computed from the forward pass.template <typename T>struct dReLU_Z { CUTLASS_HOST_DEVICE T operator()(T d_t, T z) const { return z < 0 ? T(0) : d_t; }};
template <typename T, int N>struct dReLU_Z<Array<T, N>> { CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& d_t, Array<T, N> const& z) const { Array<T, N> y; dReLU_Z<T> relu_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < N; ++i) { y[i] = relu_op(d_t[i], z[i]); }
return y; }};
// ElementwiseFilter operator// Filters by a specific value and maps it to 0.0// Used in GEMM + commtemplate <typename T>struct ElementwiseFilter {
static const bool kIsHeavy = false;
struct Arguments { T value_to_filter = T(-0.0); T filtered_value = T(0.0); };
CUTLASS_HOST_DEVICE T operator()(T const& value, T const& value_to_filter, T const& filtered_value) const { T res = value == value_to_filter ? filtered_value : value; return res; }
CUTLASS_HOST_DEVICE T operator()(T const& value, Arguments const& args = Arguments()) const { return this->operator()(value, args.value_to_filter, args.filtered_value); }};
template <typename T, int N>struct ElementwiseFilter<Array<T, N> > {
static const bool kIsHeavy = false;
using Arguments = typename ElementwiseFilter<T>::Arguments;
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& values, T const& value_to_filter, T const& filtered_value) const { Array<T, N> y; ElementwiseFilter<T> filter_op;
CUTLASS_PRAGMA_UNROLL for (int i = 0; i < int(values.size()); ++i) { y[i] = filter_op(values[i], value_to_filter, filtered_value); }
return y; }
CUTLASS_HOST_DEVICE Array<T, N> operator()(Array<T, N> const& values, Arguments const& args = Arguments()) const { return this->operator()(values, args.value_to_filter, args.filtered_value); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace thread} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148/*************************************************************************************************** * Copyright (c) 2017 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing conversion operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/numeric_types.h"#include "cutlass/array.h"#include "cutlass/functional.h"#include "cutlass/numeric_conversion.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace thread {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Converts the result without other operations///template < typename ElementOutput_, ///< Data type used to load and store tensors int Count, ///< Number of elements computed per operation typename ElementAccumulator_ = ElementOutput_, ///< Accumulator data type FloatRoundStyle Round = FloatRoundStyle::round_to_nearest>class Convert {public:
using ElementOutput = ElementOutput_; using ElementAccumulator = ElementAccumulator_; using ElementCompute = ElementAccumulator_; using ElementD = ElementOutput; // for use with cute::collective::DefaultEpilogue
static int const kCount = Count;
using FragmentOutput = Array<ElementOutput, kCount>; using FragmentAccumulator = Array<ElementAccumulator, kCount>; using ComputeFragment = FragmentAccumulator;
static FloatRoundStyle const kRound = Round;
static bool const kIsHeavy = false;
/// Host-constructable parameters structure struct Params {
// // Methods //
CUTLASS_HOST_DEVICE Params() {} };
public:
/// Constructs the function object, possibly loading from pointers in host memory CUTLASS_HOST_DEVICE Convert(Params const ¶ms = Params()) {
}
/// Functionally required for serial reduction in the epilogue CUTLASS_HOST_DEVICE void set_k_partition(int k_partition, int k_partition_count) {
}
/// Returns true if source is needed based on state of runtime arguments CUTLASS_HOST_DEVICE constexpr bool is_source_needed() const { return false; }
/// Constexpr function to enable the compiler to optimize away the source loading if it is /// never needed. CUTLASS_HOST_DEVICE constexpr bool is_source_ever_needed() const { return false; }
/// Computes linear scaling: D = alpha * accumulator + beta * source CUTLASS_HOST_DEVICE FragmentOutput operator()( FragmentAccumulator const &accumulator, FragmentOutput const &source = FragmentOutput(), ElementCompute uniform = ElementCompute(0)) const {
// Convert to destination numeric type NumericArrayConverter<ElementOutput, ElementAccumulator, kCount, Round> destination_converter;
return destination_converter(accumulator); }
// // Specializations for scalar (for use with cute::collective::DefaultEpilogue) // CUTLASS_HOST_DEVICE ElementD operator()(ElementAccumulator const accumulator, ElementAccumulator const source) const { NumericConverter<ElementD, ElementAccumulator, Round> destination_converter; return destination_converter(source); }
CUTLASS_HOST_DEVICE ElementD operator()(ElementAccumulator const accumulator) const { NumericConverter<ElementD, ElementAccumulator, Round> destination_converter; return destination_converter(accumulator); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace thread} // namespace epilogue} // namespace cutlass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/*************************************************************************************************** * Copyright (c) 2023 - 2025 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. * **************************************************************************************************//*! \file \brief Utilities for thread-level epilogues*/
#pragma once
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace thread {
namespace detail {
/// Class used to identify cases in which no operation is performedtemplate <typename T_>struct NoOp {};
} // namespace detail} // namespace thread} // namespace epilogue} // namespace cutlass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527/*************************************************************************************************** * Copyright (c) 2017 - 2025 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. * **************************************************************************************************//*! \file \brief Functor performing linear combination operations used by epilogues.*/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/numeric_types.h"#include "cutlass/array.h"#include "cutlass/functional.h"#include "cutlass/numeric_conversion.h"#include "cutlass/epilogue/thread/scale_type.h"#include "cutlass/epilogue/thread/linear_combination_params.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {namespace epilogue {namespace thread {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Applies a linear combination operator to an array of elements.////// D = alpha * accumulator + beta * source///template < typename ElementOutput_, ///< Data type used to load and store tensors int Count, ///< Number of elements computed per operation. ///< Usually it is 128/sizeof_bits<ElementOutput_>, ///< but we use 64 or 32 sometimes when there are not enough data to store typename ElementAccumulator_ = ElementOutput_, ///< Accumulator data type typename ElementCompute_ = ElementOutput_, ///< Data type used to compute linear combination ScaleType::Kind Scale = ScaleType::Default, ///< Control Alpha and Beta scaling FloatRoundStyle Round = FloatRoundStyle::round_to_nearest, typename ElementSource_ = ElementOutput_>class LinearCombination {public:
using ElementOutput = ElementOutput_; using ElementSource = ElementSource_; using ElementAccumulator = ElementAccumulator_; using ElementCompute = ElementCompute_; using ElementScalar = ElementCompute; using ElementC = ElementSource_; using ElementD = ElementOutput_;
static int const kCount = Count; static const ScaleType::Kind kScale = Scale; using FragmentOutput = Array<ElementOutput, kCount>; using FragmentSource = Array<ElementSource, kCount>; using FragmentAccumulator = Array<ElementAccumulator, kCount>; using FragmentCompute = Array<ElementCompute, kCount>;
static FloatRoundStyle const kRound = Round;
/// Host-constructable parameters structure struct Params { ElementCompute alpha; ///< scales accumulators ElementCompute beta; ///< scales source tensor ElementCompute const *alpha_ptr; ///< pointer to accumulator scalar - if not null, loads it from memory ElementCompute const *beta_ptr; ///< pointer to source scalar - if not null, loads it from memory ElementCompute const* const* alpha_ptr_array; ///< array of pointers to accumulator scalar per group/batch ElementCompute const* const* beta_ptr_array; ///< array of pointers to source scalar per group/batch
CUTLASS_HOST_DEVICE Params(): alpha(ElementCompute(1)), beta(ElementCompute(0)), alpha_ptr(nullptr), beta_ptr(nullptr), alpha_ptr_array(nullptr), beta_ptr_array(nullptr) { }
CUTLASS_HOST_DEVICE Params( ElementCompute alpha, ElementCompute beta ): alpha(alpha), beta(beta), alpha_ptr(nullptr), beta_ptr(nullptr), alpha_ptr_array(nullptr), beta_ptr_array(nullptr) { }
CUTLASS_HOST_DEVICE Params( ElementCompute alpha ): alpha(alpha), beta(0), alpha_ptr(nullptr), beta_ptr(nullptr), alpha_ptr_array(nullptr), beta_ptr_array(nullptr) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const *alpha_ptr, ElementCompute const *beta_ptr ): alpha(0), beta(0), alpha_ptr(alpha_ptr), beta_ptr(beta_ptr), alpha_ptr_array(nullptr), beta_ptr_array(nullptr) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const *alpha_ptr ): alpha(0), beta(0), alpha_ptr(alpha_ptr), beta_ptr(nullptr), alpha_ptr_array(nullptr), beta_ptr_array(nullptr) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const* const* alpha_ptr_array, ElementCompute const* const* beta_ptr_array ): alpha(0), beta(0), alpha_ptr(nullptr), beta_ptr(nullptr), alpha_ptr_array(alpha_ptr_array), beta_ptr_array(beta_ptr_array) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const* const* alpha_ptr_array ): alpha(0), beta(0), alpha_ptr(nullptr), beta_ptr(nullptr), alpha_ptr_array(alpha_ptr_array), beta_ptr_array(nullptr) { } };
private:
// // Data members //
ElementCompute alpha_; ElementCompute beta_;
public:
/// Constructs the function object, possibly loading from pointers in host memory CUTLASS_HOST_DEVICE explicit LinearCombination(Params const ¶ms, int group_idx) { if (params.alpha_ptr_array != nullptr && params.alpha_ptr_array[group_idx] != nullptr) { alpha_ = *(params.alpha_ptr_array[group_idx]); } else if (params.alpha_ptr != nullptr) { alpha_ = *params.alpha_ptr; } else { alpha_ = params.alpha; } if (params.beta_ptr_array != nullptr && params.beta_ptr_array[group_idx] != nullptr) { beta_ = *(params.beta_ptr_array[group_idx]); } else if (params.beta_ptr != nullptr) { beta_ = *params.beta_ptr; } else { beta_ = params.beta; } }
CUTLASS_HOST_DEVICE explicit LinearCombination(const Params & params) : LinearCombination(params, /* group_idx */ 0) { }
/// Returns true if source is needed CUTLASS_HOST_DEVICE bool is_source_needed() const { if (Scale == ScaleType::NoBetaScaling) return true;
if (Scale == ScaleType::OnlyAlphaScaling) return false;
if (Scale == ScaleType::Nothing) return false;
return beta_ != ElementCompute(0); }
/// Functionally required for serial reduction in the epilogue CUTLASS_HOST_DEVICE void set_k_partition(int k_partition, int k_partition_count) { if (k_partition) { beta_ = ElementCompute(1); } }
/// Computes linear scaling with source: D = alpha * accumulator + beta * source CUTLASS_HOST_DEVICE FragmentOutput operator()( FragmentAccumulator const &accumulator, FragmentSource const &source) const {
// Convert source to internal compute numeric type NumericArrayConverter<ElementCompute, ElementSource, kCount, Round> source_converter; NumericArrayConverter<ElementCompute, ElementAccumulator, kCount, Round> accumulator_converter;
// Convert to destination numeric type NumericArrayConverter<ElementOutput, ElementCompute, kCount, Round> destination_converter;
FragmentCompute converted_source = source_converter(source); FragmentCompute converted_accumulator = accumulator_converter(accumulator);
if (Scale == ScaleType::Nothing) return destination_converter(converted_accumulator);
// Perform binary operations FragmentCompute intermediate;
multiplies<FragmentCompute> mul_add_source; multiply_add<FragmentCompute> mul_add_accumulator;
if (Scale == ScaleType::NoBetaScaling) intermediate = converted_source; else intermediate = mul_add_source(beta_, converted_source); // X = beta * C + uniform
intermediate = mul_add_accumulator(alpha_, converted_accumulator, intermediate); // D = alpha * Accum + X
return destination_converter(intermediate); }
/// Computes linear scaling: D = alpha * accumulator CUTLASS_HOST_DEVICE FragmentOutput operator()( FragmentAccumulator const &accumulator) const {
// Convert source to interal compute numeric type NumericArrayConverter<ElementCompute, ElementAccumulator, kCount, Round> accumulator_converter;
// Convert to destination numeric type NumericArrayConverter<ElementOutput, ElementCompute, kCount, Round> destination_converter;
FragmentCompute converted_accumulator = accumulator_converter(accumulator);
if (Scale == ScaleType::Nothing) return destination_converter(converted_accumulator);
// Perform binary operations FragmentCompute intermediate; multiplies<FragmentCompute> mul_accumulator;
intermediate = mul_accumulator(alpha_, converted_accumulator); // D = alpha * Accum
return destination_converter(intermediate); }
// // Specializations for scalar (for use with cute::collective::DefaultEpilogue) // CUTLASS_HOST_DEVICE ElementD operator()(ElementAccumulator const accumulator, ElementC const source) const { // Convert everything to Compute type, do compute, and then store to output type NumericConverter<ElementCompute, ElementAccumulator, Round> accumulator_converter; [[maybe_unused]] NumericConverter<ElementCompute, ElementC, Round> source_converter; NumericConverter<ElementD, ElementCompute, Round> destination_converter;
// Convert to destination numeric type
ElementCompute converted_accumulator = accumulator_converter(accumulator); if constexpr (Scale == ScaleType::Nothing) { return destination_converter(converted_accumulator); }
// Perform binary operations ElementCompute intermediate; multiplies<ElementCompute> multiply; multiply_add<ElementCompute> madd;
if constexpr (Scale == ScaleType::NoBetaScaling) { intermediate = source_converter(source); } else { intermediate = multiply(beta_, source); // X = beta * C + uniform }
intermediate = madd(alpha_, converted_accumulator, intermediate); // D = alpha * Accum + X return destination_converter(intermediate); }
CUTLASS_HOST_DEVICE ElementD operator()(ElementAccumulator const accumulator) const { // Convert everything to Compute type, do compute, and then store to output type NumericConverter<ElementCompute, ElementAccumulator, Round> accumulator_converter; NumericConverter<ElementD, ElementCompute, Round> destination_converter; ElementCompute converted_accumulator = accumulator_converter(accumulator);
// Convert to destination numeric type if constexpr (Scale == ScaleType::Nothing) { return destination_converter(converted_accumulator); }
// Perform binary operations ElementCompute intermediate; multiplies<ElementCompute> multiply;
intermediate = multiply(alpha_, accumulator); // D = alpha * Accum return destination_converter(intermediate); }};
/// Applies a linear combination operator to an array of elements.////// D = vector_alpha * accumulator + (optional) vector_beta/scalar_beta * source///template < typename ElementOutput_, ///< Data type used to load and store tensors int Count, ///< Number of elements computed per operation. typename ElementAccumulator_, ///< Accumulator data type typename ElementCompute_, ///< Data type used to compute linear combination FloatRoundStyle Round, typename ElementSource_>class LinearCombination<ElementOutput_, Count, ElementAccumulator_, ElementCompute_, ScaleType::PerChannelScaling, Round, ElementSource_> {public: using ElementOutput = ElementOutput_; using ElementSource = ElementSource_; using ElementAccumulator = ElementAccumulator_; using ElementCompute = ElementCompute_; using ElementC = ElementSource_; using ElementD = ElementOutput_;
static int const kCount = Count; static const ScaleType::Kind kScale = ScaleType::PerChannelScaling; static constexpr bool IsPerChannelScalingSupported = true;
using FragmentOutput = Array<ElementOutput, kCount>; using FragmentSource = Array<ElementSource, kCount>; using FragmentAccumulator = Array<ElementAccumulator, kCount>; using FragmentCompute = Array<ElementCompute, kCount>;
static FloatRoundStyle const kRound = Round;
/// Host-constructable parameters structure struct Params { ElementCompute const *alpha_ptr; ///< pointer to accumulator vector ElementCompute const *beta_ptr; ///< pointer to source vector ElementCompute beta; ///< scales source tensor
CUTLASS_HOST_DEVICE Params(): alpha_ptr(nullptr), beta_ptr(nullptr), beta(ElementCompute(0)) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const *alpha_ptr, ElementCompute const *beta_ptr ): alpha_ptr(alpha_ptr), beta_ptr(beta_ptr), beta(ElementCompute(0)) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const *alpha_ptr ): alpha_ptr(alpha_ptr), beta_ptr(nullptr), beta(ElementCompute(0)) { }
CUTLASS_HOST_DEVICE Params( ElementCompute const *alpha_ptr, ElementCompute beta ): alpha_ptr(alpha_ptr), beta_ptr(nullptr), beta(beta) { }
};
private:
// // Data members //
ElementCompute const* beta_ptr_ = nullptr; ElementCompute beta_ = 0;
public:
/// Constructs the function object CUTLASS_HOST_DEVICE LinearCombination(Params const& params) { if (params.beta_ptr) { beta_ptr_ = params.beta_ptr; } else { beta_ = params.beta; } }
/// Returns true if source is needed CUTLASS_HOST_DEVICE bool is_source_needed() const { return beta_ptr_ != nullptr || beta_ != ElementCompute(0); }
CUTLASS_HOST_DEVICE bool is_beta_vector() const { return beta_ptr_ != nullptr; }
/// Computes linear scaling with source: D = vector_alpha * accumulator + vector_beta * source CUTLASS_HOST_DEVICE FragmentOutput operator()( FragmentAccumulator const& accumulator, FragmentSource const& source, FragmentCompute const& valpha, FragmentCompute const& vbeta) const { // Convert source to internal compute numeric type NumericArrayConverter<ElementCompute, ElementSource, kCount, Round> source_converter; NumericArrayConverter<ElementCompute, ElementAccumulator, kCount, Round> accumulator_converter;
// Convert to destination numeric type NumericArrayConverter<ElementOutput, ElementCompute, kCount, Round> destination_converter;
FragmentCompute converted_source = source_converter(source); FragmentCompute converted_accumulator = accumulator_converter(accumulator);
// Perform binary operations FragmentCompute intermediate;
multiplies<FragmentCompute> mul_add_source; multiply_add<FragmentCompute> mul_add_accumulator;
intermediate = mul_add_source(vbeta, converted_source); // X = vector_beta * C + uniform
intermediate = mul_add_accumulator(valpha, converted_accumulator, intermediate); // D = vector_alpha * Accum + X
return destination_converter(intermediate); }
/// Computes linear scaling with source: D = vector_alpha * accumulator + scalar_beta(from host) * source CUTLASS_HOST_DEVICE FragmentOutput operator()( FragmentAccumulator const& accumulator, FragmentSource const& source, FragmentCompute const& valpha) const { // Convert source to internal compute numeric type NumericArrayConverter<ElementCompute, ElementSource, kCount, Round> source_converter; NumericArrayConverter<ElementCompute, ElementAccumulator, kCount, Round> accumulator_converter;
// Convert to destination numeric type NumericArrayConverter<ElementOutput, ElementCompute, kCount, Round> destination_converter;
FragmentCompute converted_source = source_converter(source); FragmentCompute converted_accumulator = accumulator_converter(accumulator);
// Perform binary operations FragmentCompute intermediate;
multiplies<FragmentCompute> mul_add_source; multiply_add<FragmentCompute> mul_add_accumulator;
intermediate = mul_add_source(beta_, converted_source); // X = scalar_beta * C + uniform
intermediate = mul_add_accumulator(valpha, converted_accumulator, intermediate); // D = vector_alpha * Accum + X
return destination_converter(intermediate); }
/// Computes linear scaling: D = vector_alpha * accumulator CUTLASS_HOST_DEVICE FragmentOutput operator()( FragmentAccumulator const& accumulator, FragmentCompute const& valpha) const { // Convert source to interal compute numeric type NumericArrayConverter<ElementCompute, ElementAccumulator, kCount, Round> accumulator_converter;
// Convert to destination numeric type NumericArrayConverter<ElementOutput, ElementCompute, kCount, Round> destination_converter;
FragmentCompute converted_accumulator = accumulator_converter(accumulator);
// Perform binary operations FragmentCompute intermediate; multiplies<FragmentCompute> mul_accumulator;
intermediate = mul_accumulator(valpha, converted_accumulator); // D = vector_alpha * Accum
return destination_converter(intermediate); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace thread} // namespace epilogue} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////.gitattributes+1
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/detail/sm103_blockscaled_layout.hppAdded+107
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/device_kernel.hAdded+129
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/collective_builder.hppAdded+126
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/collective_epilogue.hppAdded+75
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/default_epilogue.hppAdded+265
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/default_epilogue_array.hppAdded+287
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/detail.hppAdded+887
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/epilogue_tensor_broadcast.hppAdded+271
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_array_nosmem.hppAdded+937
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_array_tma_warpspecialized.hppAdded+1526
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_nosmem.hppAdded+856
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm100_epilogue_tma_warpspecialized.hppAdded+1299
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm70_epilogue_vectorized.hppAdded+549
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm70_epilogue_vectorized_array.hppAdded+412
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm90_epilogue_array_tma_warpspecialized.hppAdded+1245
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm90_epilogue_tma_warpspecialized.hppAdded+958
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/collective/sm90_epilogue_tma_warpspecialized_bias_elementwise.hppAdded+164
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/dispatch_policy.hppAdded+302
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/callbacks.hppAdded+91
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/operations.hppAdded+645
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm100_callbacks_tma_warpspecialized.hppAdded+1322
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm100_visitor_compute_tma_warpspecialized.hppAdded+500
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm100_visitor_store_tma_warpspecialized.hppAdded+666
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm120_callbacks_tma_warpspecialized.hppAdded+1593
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm120_visitor_store_tma_warpspecialized.hppAdded+899
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_callbacks_tma_warpspecialized.hppAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_compute_tma_warpspecialized.hppAdded+842
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_load_tma_warpspecialized.hppAdded+1492
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_store_tma_warpspecialized.hppAdded+1722
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hppAdded+1149
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/fusion/sm90_visitor_topk_softmax.hppAdded+763
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/activation.hAdded+914
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/conversion_op.hAdded+148
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/detail.hppAdded+52
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination.hAdded+527
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_bias_elementwise.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_bias_relu.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_clamp.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_dgelu.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_drelu.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_gelu.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_generic.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_generic_with_scaling.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_hardswish.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_leaky_relu.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_params.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_planar_complex.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_relu.hAdded
build/torch215-cu132-aarch64-linux/include/third-party/cutlass/include/cutlass/epilogue/thread/linear_combination_relu0.hAdded