Sync on vLLM 20240402
Browse filesFiles changed (22)
- cuda_utils.hAdded+41
- cutlass_extensions/epilogue/broadcast_load_epilogue_array_c3x.hppAdded+457
- cutlass_extensions/gemm/collective/collective_builder.hppAdded+123
- cutlass_extensions/gemm/collective/fp8_accumulation.hppAdded+183
- cutlass_extensions/gemm/collective/sm90_mma_tma_gmma_ss_warpspecialized_fp8_blockwise_scaling.hppAdded+730
- cutlass_extensions/gemm/dispatch_policy.hppAdded+39
- cutlass_w8a8/c3x/cutlass_gemm_caller.cuhAdded+107
- cutlass_w8a8/c3x/scaled_mm.cuhAdded+147
- cutlass_w8a8/c3x/scaled_mm_azp_sm90_int8.cuAdded+24
- cutlass_w8a8/c3x/scaled_mm_blockwise_sm90_fp8.cuAdded+24
- cutlass_w8a8/c3x/scaled_mm_blockwise_sm90_fp8_dispatch.cuhAdded+194
- cutlass_w8a8/c3x/scaled_mm_kernels.hppAdded+39
- cutlass_w8a8/c3x/scaled_mm_sm100_fp8.cuAdded+24
- cutlass_w8a8/c3x/scaled_mm_sm100_fp8_dispatch.cuhAdded+67
- cutlass_w8a8/c3x/scaled_mm_sm90_fp8.cuAdded+24
- cutlass_w8a8/c3x/scaled_mm_sm90_fp8_dispatch.cuhAdded+120
- cutlass_w8a8/c3x/scaled_mm_sm90_int8.cuAdded+24
- cutlass_w8a8/c3x/scaled_mm_sm90_int8_dispatch.cuhAdded+163
- cutlass_w8a8/scaled_mm_c3x_sm100.cuAdded+34
- cutlass_w8a8/scaled_mm_c3x_sm90.cuAdded+77
- torch-ext/quantization/platforms.pyAdded+69
- utils.cuhAdded+59
1234567891011121314151617181920212223242526272829303132333435363738394041#pragma once
#include <stdio.h>
#if defined(__HIPCC__) #define HOST_DEVICE_INLINE __host__ __device__ #define DEVICE_INLINE __device__ #define HOST_INLINE __host__#elif defined(__CUDACC__) || defined(_NVHPC_CUDA) #define HOST_DEVICE_INLINE __host__ __device__ __forceinline__ #define DEVICE_INLINE __device__ __forceinline__ #define HOST_INLINE __host__ __forceinline__#else #define HOST_DEVICE_INLINE inline #define DEVICE_INLINE inline #define HOST_INLINE inline#endif
#define CUDA_CHECK(cmd) \ do { \ cudaError_t e = cmd; \ if (e != cudaSuccess) { \ printf("Failed: Cuda error %s:%d '%s'\n", __FILE__, __LINE__, \ cudaGetErrorString(e)); \ exit(EXIT_FAILURE); \ } \ } while (0)
int64_t get_device_attribute(int64_t attribute, int64_t device_id);
int64_t get_max_shared_memory_per_block_device_attribute(int64_t device_id);
namespace cuda_utils {
template <typename T>HOST_DEVICE_INLINE constexpr std::enable_if_t<std::is_integral_v<T>, T>ceil_div(T a, T b) { return (a + b - 1) / b;}
}; // namespace cuda_utils123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457/*************************************************************************************************** * Copyright (c) 2023 - 2024 NVIDIA CORPORATION & AFFILIATES. All rights *reserved. SPDX-License-Identifier: BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, *this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE *LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/
//// This file is a modified excerpt of// include/cutlass/epilogue/fusion/sm90_visitor_load_tma_warpspecialized.hpp// from https://github.com/NVIDIA/cutlass v3.5.0// It has been modified to support either row/column or scalar broadcasting// where the tensor being loaded from is always passed in via a device pointer.// This lets one compiled kernel handle all cases of per-tensor or// per-channel/per-token quantization.//// This interface also allows the scales to be passed in as tensors that// consistently reside on the device, which avoids an issue with a previous// implementation where scalars needed to be on the CPU since they// were passed in via float values. This created a potential performance hazard// if scales were initially on the device, and caused torch.compile graphs// breaks when moving scales to the CPU.//#pragma once
// Turn off clang-format for the entire file to keep it close to upstream// clang-format off
#include "cutlass/cutlass.h"#include "cutlass/arch/barrier.h"
#include "cute/tensor.hpp"#include "cutlass/epilogue/fusion/sm90_visitor_tma_warpspecialized.hpp"
namespace cutlass::epilogue::fusion {
using namespace cute;using namespace detail;
// Row vector broadcasttemplate< int Stages, class CtaTileShapeMNK, class Element, class StrideMNL = Stride<_0,_1,_0>, int Alignment = 128 / sizeof_bits_v<Element>>struct Sm90RowOrScalarBroadcastArray { static_assert(Stages == 0, "Row broadcast doesn't support smem usage"); 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>{});
struct SharedStorage { array_aligned<Element, size<1>(CtaTileShapeMNK{})> smem; };
// This struct has been modified to have a bool indicating that ptr_row is a // scalar that must be broadcast, instead of containing a scalar that is // valid if ptr_row is null. struct Arguments { const Element* const* ptr_row_array = nullptr; bool row_broadcast = true; 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 Sm90RowOrScalarBroadcastArray() { }
CUTLASS_HOST_DEVICE Sm90RowOrScalarBroadcastArray(Params const& params, SharedStorage const& shared_storage) : params(params) , smem(const_cast<Element*>(shared_storage.smem.data())) { }
Params params; Element *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 (!params.row_broadcast && *(params.ptr_row_array[group]) == Element(0)); }
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 CTensor, class ThrResidue, class ThrNum> 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_, CTensor tCcRow_, ThrResidue residue_tCcRow_, ThrNum thr_num_, int group, 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_) , tCcRow(tCcRow_) , residue_tCcRow(residue_tCcRow_) , group(group) , 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) CTensor tCcRow; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) ThrResidue residue_tCcRow; // (m, n) ThrNum thr_num; int group; Params const& params;
CUTLASS_DEVICE void begin() { if (!params.row_broadcast) { fill(tSR_rRow, *(params.ptr_row_array[group])); return; }
auto synchronize = [&] () { cutlass::arch::NamedBarrier::sync(thr_num, cutlass::arch::ReservedNamedBarriers::EpilogueBarrier); }; Tensor tGS_gRow_flt = filter_zeros(tGS_gRow); Tensor tGS_sRow_flt = filter_zeros(tGS_sRow); Tensor tGS_cRow_flt = make_tensor(tGS_cRow.data(), make_layout(tGS_gRow_flt.shape(), tGS_cRow.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 (elem_less(tGS_cRow_flt(i), make_coord(get<0>(residue_tCcRow), get<1>(residue_tCcRow)))) { tGS_sRow_flt(i) = tGS_gRow_flt(i); } else { tGS_sRow_flt(i) = Element(0); // Set to Zero when OOB so LDS could be issue without any preds. } } synchronize(); }
CUTLASS_DEVICE void begin_loop(int epi_m, int epi_n) { if (epi_m == 0) { // Assumes M-major subtile loop if (!params.row_broadcast) return; // Do not issue LDS when row is scalar Tensor tSR_sRow_flt = filter_zeros(tSR_sRow(_,_,_,epi_m,epi_n)); Tensor tSR_rRow_flt = filter_zeros(tSR_rRow); copy(tSR_sRow_flt, tSR_rRow_flt); } }
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_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));
Tensor mRow = make_tensor(make_gmem_ptr(params.ptr_row_array[l]), make_shape(M,N,1), params.dRow); 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, Element>{}, 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 auto cRow = make_identity_tensor(make_shape(size<0>(CtaTileShapeMNK{}), size<1>(CtaTileShapeMNK{}))); Tensor tGS_cRow = thr_g2s.partition_S(cRow);
//// 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(take<0,3>(tSR_sRow)); // (CPY,CPY_M,CPY_N)
return ConsumerStoreCallbacks<decltype(tGS_gRow), decltype(tGS_sRow), decltype(tGS_cRow), decltype(tiled_g2s), decltype(tSR_sRow), decltype(tSR_rRow), decltype(args.tCcD), decltype(args.residue_cD), ThreadCount>( tGS_gRow, tGS_sRow, tGS_cRow, tiled_g2s, tSR_sRow, tSR_rRow, args.tCcD, args.residue_cD, ThreadCount{}, l, params); }};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Column vector broadcasttemplate< int Stages, class CtaTileShapeMNK, class Element, class StrideMNL = Stride<_1,_0,_0>, int Alignment = 128 / sizeof_bits_v<Element>>struct Sm90ColOrScalarBroadcastArray { static_assert(Stages == 0, "Column broadcast doesn't support smem usage yet"); static_assert(Alignment * sizeof_bits_v<Element> % 128 == 0, "sub-16B alignment not supported yet"); static_assert( (cute::is_same_v<StrideMNL, Stride<_1,_0, _0>>) || // col vector broadcast, e.g. per-row alpha/bias (cute::is_same_v<StrideMNL, Stride<_1,_0,int>>)); // batched col vector broadcast, e.g. batched per-row bias
// Accumulator distributes col elements evenly amongst threads so we can just directly load from gmem struct SharedStorage { };
// This struct has been modified to have a bool indicating that ptr_col is a // scalar that must be broadcast, instead of containing a scalar that is // valid if ptr_col is null. struct Arguments { const Element* const* ptr_col_array = nullptr; bool col_broadcast = true; StrideMNL dCol = {}; };
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; }
CUTLASS_DEVICE bool is_zero() const { return (!params.col_broadcast && *(params.ptr_col_array[group]) == Element(0)); }
CUTLASS_HOST_DEVICE Sm90ColOrScalarBroadcastArray() { }
CUTLASS_HOST_DEVICE Sm90ColOrScalarBroadcastArray(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 GTensor, class RTensor, class CTensor, class ProblemShape> struct ConsumerStoreCallbacks : EmptyConsumerStoreCallbacks { CUTLASS_DEVICE ConsumerStoreCallbacks( GTensor&& tCgCol, RTensor&& tCrCol, CTensor&& tCcCol, ProblemShape problem_shape, int group, Params const& params ): tCgCol(cute::forward<GTensor>(tCgCol)), tCrCol(cute::forward<RTensor>(tCrCol)), tCcCol(cute::forward<CTensor>(tCcCol)), m(get<0>(problem_shape)), group(group), params(params) {}
GTensor tCgCol; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) RTensor tCrCol; CTensor tCcCol; // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) Params const& params; int m; int group;
CUTLASS_DEVICE void begin() { Tensor pred = make_tensor<bool>(shape(tCgCol)); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(pred); ++i) { pred(i) = get<0>(tCcCol(i)) < m; }
if (!params.col_broadcast) { fill(tCrCol, *(params.ptr_col_array[group])); 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) copy_if(pred, filter(tCgCol), filter(tCrCol)); }
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_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;
Tensor mCol = make_tensor(make_gmem_ptr(params.ptr_col_array[l]), make_shape(M,N,1), params.dCol); 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 tCrCol = make_tensor_like(tCgCol); // (CPY,CPY_M,CPY_N,EPI_M,EPI_N)
// Generate an identity tensor matching the shape of the global tensor and // partition the same way, this will be used to generate the predicate // tensor for loading Tensor cCol = make_identity_tensor(mCol.shape()); Tensor tCcCol = sm90_partition_for_epilogue<ReferenceSrc>( // (CPY,CPY_M,CPY_N,EPI_M,EPI_N) cCol, args.tile_shape_mnk, args.tile_coord_mnkl, args.epi_tile, args.tiled_copy, args.thread_idx);
return ConsumerStoreCallbacks( cute::move(tCgCol), cute::move(tCrCol), cute::move(tCcCol), args.problem_shape_mnkl, l, params ); }};
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123// Modified from: cutlass/gemm/collective/builders/sm90_gmma_builder.inl// clang-format off#pragma once
#include "cutlass/gemm/collective/builders/sm90_gmma_builder.inl"
#include "cutlass_extensions/gemm/collective/sm90_mma_tma_gmma_ss_warpspecialized_fp8_blockwise_scaling.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::gemm::collective {
/////////////////////////////////////////////////////////////////////////////////////////////////
// GMMA_TMA_WS_SS (BlockScaled Builders)template < class ElementA, class GmemLayoutATag, int AlignmentA, class ElementB, class GmemLayoutBTag, int AlignmentB, class ElementAccumulator, class TileShape_MNK, class ClusterShape_MNK, class StageCountType, int ScaleGranularityM>struct CollectiveBuilder< arch::Sm90, arch::OpClassTensorOp, ElementA, GmemLayoutATag, AlignmentA, ElementB, GmemLayoutBTag, AlignmentB, ElementAccumulator, TileShape_MNK, ClusterShape_MNK, StageCountType, KernelTmaWarpSpecializedCooperativeFP8BlockScaledSubGroupMAccum<ScaleGranularityM>, cute::enable_if_t< not detail::is_use_rmem_A<ElementA, GmemLayoutATag, ElementB, GmemLayoutBTag>()>> { using KernelScheduleType = KernelTmaWarpSpecializedCooperativeFP8BlockScaledSubGroupMAccum<ScaleGranularityM>;
static_assert(is_static<TileShape_MNK>::value); static_assert(is_static<ClusterShape_MNK>::value);#ifndef CUTLASS_SM90_COLLECTIVE_BUILDER_SUPPORTED static_assert(cutlass::detail::dependent_false<ElementA>, "Unsupported Toolkit for SM90 Collective Builder\n");#endif static_assert(detail::is_aligned<ElementA, AlignmentA, ElementB, AlignmentB, detail::tma_alignment_bytes>(), "Should meet TMA alignment requirement\n");
static constexpr bool IsArrayOfPointersGemm = (cute::is_any_of_v<KernelScheduleType, KernelPtrArrayTmaWarpSpecializedCooperative, KernelPtrArrayTmaWarpSpecializedPingpong>); static constexpr bool IsFP8Input = detail::is_input_fp8<ElementA, ElementB>(); static_assert((!IsFP8Input || !IsArrayOfPointersGemm), "KernelTmaWarpSpecializedCooperativeFP8BlockScaledAccum is only compatible with FP8 Blocked Scaled version right now.");
// For fp32 types, map to tf32 MMA value type using ElementAMma = cute::conditional_t<cute::is_same_v<ElementA, float>, tfloat32_t, ElementA>; using ElementBMma = cute::conditional_t<cute::is_same_v<ElementB, float>, tfloat32_t, ElementB>;
static constexpr cute::GMMA::Major GmmaMajorA = detail::gmma_ss_tag_to_major_A<ElementAMma, GmemLayoutATag>(); static constexpr cute::GMMA::Major GmmaMajorB = detail::gmma_ss_tag_to_major_B<ElementBMma, GmemLayoutBTag>();
static constexpr bool IsCooperative = cute::is_any_of_v<KernelScheduleType, KernelTmaWarpSpecializedCooperative, KernelPtrArrayTmaWarpSpecializedCooperative, KernelTmaWarpSpecializedCooperativeFP8BlockScaledSubGroupMAccum<ScaleGranularityM>>; using AtomLayoutMNK = cute::conditional_t<IsCooperative, Layout<Shape<_2,_1,_1>>, Layout<Shape<_1,_1,_1>>>;
using TiledMma = decltype(cute::make_tiled_mma(cute::GMMA::ss_op_selector< ElementAMma, ElementBMma, ElementAccumulator, TileShape_MNK, GmmaMajorA, GmmaMajorB>(), AtomLayoutMNK{}));
using GmemTiledCopyA = decltype(detail::sm90_cluster_shape_to_tma_atom(shape<1>(ClusterShape_MNK{}))); using GmemTiledCopyB = decltype(detail::sm90_cluster_shape_to_tma_atom(shape<0>(ClusterShape_MNK{})));
using SmemLayoutAtomA = decltype(detail::ss_smem_selector< GmmaMajorA, ElementAMma, decltype(cute::get<0>(TileShape_MNK{})), decltype(cute::get<2>(TileShape_MNK{}))>()); using SmemLayoutAtomB = decltype(detail::ss_smem_selector< GmmaMajorB, ElementBMma, decltype(cute::get<1>(TileShape_MNK{})), decltype(cute::get<2>(TileShape_MNK{}))>());
static constexpr size_t TensorMapStorage = IsArrayOfPointersGemm ? sizeof(cute::TmaDescriptor) * 2 /* for A and B */ : 0; static constexpr int KernelSmemCarveout = static_cast<int>(TensorMapStorage);
static constexpr int PipelineStages = detail::compute_stage_count_or_override<detail::sm90_smem_capacity_bytes - KernelSmemCarveout, ElementAMma, ElementBMma, TileShape_MNK>(StageCountType{}); using DispatchPolicy = MainloopSm90TmaGmmaWarpSpecializedBlockScalingSubGroupMFP8<PipelineStages, ClusterShape_MNK, KernelScheduleType, ScaleGranularityM>;
using SmemCopyAtomA = void; using SmemCopyAtomB = void;
using CollectiveOp = CollectiveMma< DispatchPolicy, TileShape_MNK, ElementA, TagToStrideA_t<GmemLayoutATag>, ElementB, TagToStrideB_t<GmemLayoutBTag>, TiledMma, GmemTiledCopyA, SmemLayoutAtomA, SmemCopyAtomA, cute::identity, GmemTiledCopyB, SmemLayoutAtomB, SmemCopyAtomB, cute::identity >;};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::gemm::collective
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183// clang-format off// adapted from: https://github.com/soundOfDestiny/cutlass/blob/a4208aa6958864923505cade9c63eb2a6daf16e5/include/cutlass/gemm/collective/fp8_accumulation.hpp
/*************************************************************************************************** * Copyright (c) 2023 - 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/
#pragma once
#include "cute/algorithm/clear.hpp"#include "cute/tensor.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////FP8 Accumulation//////////////////////////////////////////////////////////////////////////////////////////////////////////// This class provides API to promote (add) or scale (multiply_add) the results/// from the tensor core accumulators to the main accumulators when the number /// of MMAs reaches the max number of MMA interval specified by user, after that/// the tensor core accumulators are zeroed.//////////////////////////////////////////////////////////////////////////////
namespace cutlass::gemm::collective {
template < class EngineAccum, class LayoutAccum>struct GmmaFP8AccumulationWithScale { using TensorAccum = cute::Tensor<EngineAccum, LayoutAccum>; using ElementAccumulator = typename EngineAccum::value_type;
static_assert(is_static<LayoutAccum>::value, "Accumulator Layout should be static"); static_assert(is_rmem<TensorAccum>::value , "Accumulator tensor must be rmem resident.");
private: TensorAccum& accum_; TensorAccum accum_temp_;
uint32_t accum_promotion_interval_; // defines the max num of executed MMAs after which accum should be promoted. uint32_t mma_count_per_mainloop_iteration_; // num of MMAs per k_tile of mainloop uint32_t mma_count_; // current executed MMAs uint32_t reset_accum_flag_; // accum needs to be zeroed or not.
// promote or `add` the partial accumulators to main accumulator (FADD). CUTLASS_DEVICE void promote_core() { warpgroup_wait<0>(); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accum_); ++i) { accum_(i) += accum_temp_(i); } }
// `multiply` scale the partial accumulators and `add` to main accumulator (FFMA). template < class EngineScale, class LayoutScale> CUTLASS_DEVICE void scale_core(const cute::Tensor<EngineScale, LayoutScale> &scale) { using TensorScale = cute::Tensor<EngineScale, LayoutScale>;
static_assert(is_static<LayoutScale>::value, "Scale Layout should be static"); static_assert(is_rmem<TensorScale>::value , "Scale tensor must be rmem resident.");
static_assert(LayoutAccum{}.shape() == LayoutScale{}.shape(), "Accumulator and scale must have same shape.");
warpgroup_wait<0>(); CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(accum_); ++i) { accum_(i) += accum_temp_(i) * scale(i); } }
public: CUTLASS_DEVICE GmmaFP8AccumulationWithScale( TensorAccum &accum, uint32_t accum_promotion_interval, uint32_t mma_count_per_mainloop_iteration) : accum_(accum), accum_promotion_interval_(accum_promotion_interval), mma_count_per_mainloop_iteration_(mma_count_per_mainloop_iteration), mma_count_(0), reset_accum_flag_(0) { accum_temp_ = cute::make_fragment_like(accum); }
// // Methods (Common) //
CUTLASS_DEVICE TensorAccum& operator()() { return accum_temp_; }
/// prepare the MMA accumulators when initialization or zeroing is required. CUTLASS_DEVICE bool prepare_if_needed() { return reset_accum_flag_; }
// // Methods (for FADD version) //
/// promote (add) the results from the MMA accumulators to main accumulator if needed. CUTLASS_DEVICE void promote_if_needed() { mma_count_ += mma_count_per_mainloop_iteration_; reset_accum_flag_ = __shfl_sync(0xffffffff, mma_count_ == accum_promotion_interval_, 0); if (reset_accum_flag_) { promote_core(); mma_count_ = 0; } }
/// promote (add) the residue results from the MMA accumulators to main accumulator if needed. CUTLASS_DEVICE void promote_residue_if_needed() { if (__shfl_sync(0xffffffff, mma_count_ > 0, 0)) { promote_core(); } }
// // Methods (for FFMA version) //
/// scale (multiply_add) the results from the MMA accumulators to main accumulator if needed. template < class EngineScale, class LayoutScale> CUTLASS_DEVICE void scale_if_needed(const cute::Tensor<EngineScale, LayoutScale> &scale) { mma_count_ += mma_count_per_mainloop_iteration_; reset_accum_flag_ = __shfl_sync(0xffffffff, mma_count_ == accum_promotion_interval_, 0); if (reset_accum_flag_) { scale_core(scale); mma_count_ = 0; } }
/// scale (multiply_add) the residue results from the MMA accumulators to main accumulator if needed. template < class EngineScale, class LayoutScale> CUTLASS_DEVICE void scale_residue_if_needed(const cute::Tensor<EngineScale, LayoutScale> &scale) { if (__shfl_sync(0xffffffff, mma_count_ > 0, 0)) { scale_core(scale); } }};
} // namespace cutlass::gemm::collective123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730// clang-format off// Adapted (Heavily) from: https://github.com/soundOfDestiny/cutlass/blob/9d997ce0dea4c5fa1a617db6b7ff29aa9235822c/include/cutlass/gemm/collective/sm90_mma_tma_gmma_ss_warpspecialized_fp8_blockwise_scaling.hpp
/*************************************************************************************************** * Copyright (c) 2023 - 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/
#pragma once
#include "cutlass/cutlass.h"#include "cutlass/gemm/dispatch_policy.hpp"#include "cutlass/trace.h"#include "cutlass/numeric_types.h"
#include "cute/arch/cluster_sm90.hpp"#include "cute/arch/copy_sm80.hpp"#include "cute/arch/copy_sm90.hpp"#include "cute/algorithm/functional.hpp"#include "cute/atom/mma_atom.hpp"#include "cute/algorithm/gemm.hpp"#include "cute/tensor_predicate.hpp"#include "cute/numeric/arithmetic_tuple.hpp"
#include "cutlass_extensions/gemm/dispatch_policy.hpp"#include "cutlass_extensions/gemm/collective/fp8_accumulation.hpp"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass::gemm::collective {using namespace cute;
/////////////////////////////////////////////////////////////////////////////////////////////////
// WarpSpecialized Mainlooptemplate < int Stages, class ClusterShape, class KernelSchedule, int ScaleGranularityM_, class TileShape_, class ElementA_, class StrideA_, class ElementB_, class StrideB_, class TiledMma_, class GmemTiledCopyA_, class SmemLayoutAtomA_, class SmemCopyAtomA_, class TransformA_, class GmemTiledCopyB_, class SmemLayoutAtomB_, class SmemCopyAtomB_, class TransformB_>struct CollectiveMma< MainloopSm90TmaGmmaWarpSpecializedBlockScalingSubGroupMFP8<Stages, ClusterShape, KernelSchedule, ScaleGranularityM_>, TileShape_, ElementA_, StrideA_, ElementB_, StrideB_, TiledMma_, GmemTiledCopyA_, SmemLayoutAtomA_, SmemCopyAtomA_, TransformA_, GmemTiledCopyB_, SmemLayoutAtomB_, SmemCopyAtomB_, TransformB_>{ // // Type Aliases // using DispatchPolicy = MainloopSm90TmaGmmaWarpSpecializedBlockScalingSubGroupMFP8<Stages, ClusterShape, KernelSchedule, ScaleGranularityM_>; using TileShape = TileShape_; using ElementA = ElementA_; using StrideA = StrideA_; using ElementB = ElementB_; using StrideB = StrideB_; using TiledMma = TiledMma_; using ElementAccumulator = typename TiledMma::ValTypeC; using ElementBlockScale = ElementAccumulator; using GmemTiledCopyA = GmemTiledCopyA_; using GmemTiledCopyB = GmemTiledCopyB_; using SmemLayoutAtomA = SmemLayoutAtomA_; using SmemLayoutAtomB = SmemLayoutAtomB_; using SmemCopyAtomA = SmemCopyAtomA_; using SmemCopyAtomB = SmemCopyAtomB_; using TransformA = TransformA_; using TransformB = TransformB_; using ArchTag = typename DispatchPolicy::ArchTag;
using CtaShape_MNK = decltype(shape_div(TileShape{}, ClusterShape{})); using MainloopPipeline = cutlass::PipelineTmaAsync<DispatchPolicy::Stages>; using PipelineState = cutlass::PipelineState<DispatchPolicy::Stages>; using PipelineParams = typename MainloopPipeline::Params;
// Two threads per CTA are producers (1 for operand tile and 32 for scales) static constexpr int NumProducerThreadEvents = 33;
static constexpr int ScaleGranularityM = ScaleGranularityM_ == 0 ? size<0>(TileShape{}) : ScaleGranularityM_; static constexpr int ScaleMsPerTile = size<0>(TileShape{}) / ScaleGranularityM;
static_assert(cute::rank(SmemLayoutAtomA{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); static_assert((size<0>(TileShape{}) % size<0>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtom must evenly divide tile shape."); static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomA{})) == 0, "SmemLayoutAtom must evenly divide tile shape.");
static_assert(cute::rank(SmemLayoutAtomB{}) == 2, "SmemLayoutAtom must be rank 2 (M/N, K)"); static_assert((size<1>(TileShape{}) % size<0>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtom must evenly divide tile shape."); static_assert((size<2>(TileShape{}) % size<1>(SmemLayoutAtomB{})) == 0, "SmemLayoutAtom must evenly divide tile shape.");
static_assert((size<0>(TileShape{}) % ScaleGranularityM) == 0, "FP8 scaling granularity must evenly divide tile shape along M.");
// Tile along modes in a way that maximizes the TMA box size. using SmemLayoutA = decltype(tile_to_shape( SmemLayoutAtomA{}, make_shape(shape<0>(TileShape{}), shape<2>(TileShape{}), Int<DispatchPolicy::Stages>{}), cute::conditional_t< ::cutlass::gemm::detail::is_major<0,StrideA>(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); using SmemLayoutB = decltype(tile_to_shape( SmemLayoutAtomB{}, make_shape(shape<1>(TileShape{}), shape<2>(TileShape{}), Int<DispatchPolicy::Stages>{}), cute::conditional_t< ::cutlass::gemm::detail::is_major<0,StrideB>(), Step<_2,_1,_3>, Step<_1,_2,_3>>{})); // Block scaling gmem-to-smem copy atom using SmemBlockScalingCopyAtomA = Copy_Atom<SM80_CP_ASYNC_CACHEALWAYS<ElementBlockScale>, ElementBlockScale>; using SmemBlockScalingCopyAtomB = Copy_Atom<SM80_CP_ASYNC_CACHEALWAYS<ElementBlockScale>, ElementBlockScale>; // Block scaling smem layout using SmemLayoutScaleA = Layout<Shape<Int<ScaleMsPerTile>, Int<DispatchPolicy::Stages>>>; using SmemLayoutScaleB = Layout<Shape<Int<DispatchPolicy::Stages>>, Stride<_1>>; // `ScaleNsPerTile` is always 1.
static_assert(DispatchPolicy::Stages >= 2, "Specialization requires Stages set to value 1 or more."); static_assert(cute::is_base_of<cute::GMMA::DescriptorIterator, typename TiledMma::FrgTypeA>::value && cute::is_base_of<cute::GMMA::DescriptorIterator, typename TiledMma::FrgTypeB>::value, "MMA atom must source both A and B operand from smem_desc for this mainloop."); static_assert(cute::is_same_v<GmemTiledCopyA, SM90_TMA_LOAD> || cute::is_same_v<GmemTiledCopyA, SM90_TMA_LOAD_MULTICAST>, "GmemTiledCopy - invalid SM90 TMA copy atom specified."); static_assert(cute::is_same_v<GmemTiledCopyB, SM90_TMA_LOAD> || cute::is_same_v<GmemTiledCopyB, SM90_TMA_LOAD_MULTICAST>, "GmemTiledCopy - invalid SM90 TMA copy atom specified."); static_assert(cute::is_same_v<ElementAccumulator, ElementBlockScale>, "ElementAccumulator and ElementBlockScale should be same datatype");
struct SharedStorage { struct TensorStorage : cute::aligned_struct<128> { cute::array_aligned<typename TiledMma::ValTypeA, cute::cosize_v<SmemLayoutA>> smem_A; // mxk cute::array_aligned<typename TiledMma::ValTypeB, cute::cosize_v<SmemLayoutB>> smem_B; // nxk cute::array_aligned<ElementBlockScale, cute::cosize_v<SmemLayoutScaleA>> smem_scale_A; // ScaleMsPerTile x k cute::array_aligned<ElementBlockScale, cute::cosize_v<SmemLayoutScaleB>> smem_scale_B; // 1xk } tensors;
using PipelineStorage = typename MainloopPipeline::SharedStorage; PipelineStorage pipeline; }; using TensorStorage = typename SharedStorage::TensorStorage; using PipelineStorage = typename SharedStorage::PipelineStorage;
// Host side kernel arguments struct Arguments { ElementA const* ptr_A; StrideA dA; ElementB const* ptr_B; StrideB dB; ElementBlockScale const* ptr_scale_A; ElementBlockScale const* ptr_scale_B; };
// Device side kernel params struct Params { // Assumption: StrideA is congruent with Problem_MK using TMA_A = decltype(make_tma_copy_A_sm90( GmemTiledCopyA{}, make_tensor(static_cast<ElementA const*>(nullptr), repeat_like(StrideA{}, int32_t(0)), StrideA{}), SmemLayoutA{}(_,_,0), TileShape{}, ClusterShape{})); // Assumption: StrideB is congruent with Problem_NK using TMA_B = decltype(make_tma_copy_B_sm90( GmemTiledCopyB{}, make_tensor(static_cast<ElementB const*>(nullptr), repeat_like(StrideB{}, int32_t(0)), StrideB{}), SmemLayoutB{}(_,_,0), TileShape{}, ClusterShape{})); TMA_A tma_load_a; TMA_B tma_load_b; uint32_t tma_transaction_bytes = TmaTransactionBytes; uint32_t tma_transaction_bytes_mk = TmaTransactionBytesMK; uint32_t tma_transaction_bytes_nk = TmaTransactionBytesNK; // Block scaling factors for A and B ElementBlockScale const* ptr_scale_A; ElementBlockScale const* ptr_scale_B; };
// // Methods //
template <class ProblemShape> static constexpr Params to_underlying_arguments(ProblemShape const& problem_shape, Arguments const& args, void* workspace) { (void) workspace;
// Optionally append 1s until problem shape is rank-4 (MNKL), in case it is only rank-3 (MNK) auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL;
auto ptr_A = reinterpret_cast<ElementA const*>(args.ptr_A); auto ptr_B = reinterpret_cast<ElementB const*>(args.ptr_B);
Tensor tensor_a = make_tensor(ptr_A, make_layout(make_shape(M,K,L), args.dA)); Tensor tensor_b = make_tensor(ptr_B, make_layout(make_shape(N,K,L), args.dB)); typename Params::TMA_A tma_load_a = make_tma_copy_A_sm90( GmemTiledCopyA{}, tensor_a, SmemLayoutA{}(_,_,cute::Int<0>{}), TileShape{}, ClusterShape{}); typename Params::TMA_B tma_load_b = make_tma_copy_B_sm90( GmemTiledCopyB{}, tensor_b, SmemLayoutB{}(_,_,cute::Int<0>{}), TileShape{}, ClusterShape{}); uint32_t transaction_bytes_mk = TmaTransactionBytesMK; uint32_t transaction_bytes_nk = TmaTransactionBytesNK; uint32_t transaction_bytes = transaction_bytes_mk + transaction_bytes_nk;
return { tma_load_a, tma_load_b, transaction_bytes, transaction_bytes_mk, transaction_bytes_nk, args.ptr_scale_A, args.ptr_scale_B }; }
template<class ProblemShape> static bool can_implement( ProblemShape const& problem_shape, [[maybe_unused]] Arguments const& args) { constexpr int tma_alignment_bits = 128; auto problem_shape_MNKL = append<4>(problem_shape, 1); auto [M,N,K,L] = problem_shape_MNKL; bool implementable = true; constexpr int min_tma_aligned_elements_A = tma_alignment_bits / cutlass::sizeof_bits<ElementA>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_A>(cute::make_shape(M,K,L), StrideA{}); constexpr int min_tma_aligned_elements_B = tma_alignment_bits / cutlass::sizeof_bits<ElementB>::value; implementable = implementable && cutlass::detail::check_alignment<min_tma_aligned_elements_B>(cute::make_shape(N,K,L), StrideB{});
if (!implementable) { CUTLASS_TRACE_HOST(" CAN IMPLEMENT: Problem Size doesn't meet the minimum alignment requirements for TMA.\n"); } return implementable; }
static constexpr int K_PIPE_MAX = DispatchPolicy::Stages; static constexpr int K_PIPE_MMAS = 1; static constexpr uint32_t TmaTransactionBytesMK = cutlass::bits_to_bytes(size<0>(SmemLayoutA{}) * size<1>(SmemLayoutA{}) * static_cast<uint32_t>(sizeof_bits<ElementA>::value)); static constexpr uint32_t TmaTransactionBytesNK = cutlass::bits_to_bytes(size<0>(SmemLayoutB{}) * size<1>(SmemLayoutB{}) * static_cast<uint32_t>(sizeof_bits<ElementB>::value)); static constexpr uint32_t TmaTransactionBytes = TmaTransactionBytesMK + TmaTransactionBytesNK;
/// Issue Tma Descriptor Prefetch -- ideally from a single thread for best performance CUTLASS_DEVICE static void prefetch_tma_descriptors(Params const& mainloop_params) { cute::prefetch_tma_descriptor(mainloop_params.tma_load_a.get_tma_descriptor()); cute::prefetch_tma_descriptor(mainloop_params.tma_load_b.get_tma_descriptor()); }
/// Set up the data needed by this collective for load and mma. /// Returns a tuple of tensors. The collective and the kernel layer have the contract /// Returned tuple must contain at least two elements, with the first two elements being: /// gA_mkl - The tma tensor, A after a local tile so it has shape (BLK_M,BLK_K,m,k,l) /// gB_nkl - The tma tensor, B after a local tile so it has shape (BLK_N,BLK_K,n,k,l) template <class ProblemShape_MNKL> CUTLASS_DEVICE auto load_init(ProblemShape_MNKL const& problem_shape_MNKL, Params const& mainloop_params) const { using X = Underscore; // Separate out problem shape for convenience auto [M,N,K,L] = problem_shape_MNKL;
// TMA requires special handling of strides to deal with coord codomain mapping // Represent the full tensors -- get these from TMA Tensor mA_mkl = mainloop_params.tma_load_a.get_tma_tensor(make_shape(M,K,L)); // (m,k,l) Tensor mB_nkl = mainloop_params.tma_load_b.get_tma_tensor(make_shape(N,K,L)); // (n,k,l)
// Make tiled views, defer the slice Tensor gA_mkl = local_tile(mA_mkl, TileShape{}, make_coord(_,_,_), Step<_1, X,_1>{}); // (BLK_M,BLK_K,m,k,l) Tensor gB_nkl = local_tile(mB_nkl, TileShape{}, make_coord(_,_,_), Step< X,_1,_1>{}); // (BLK_N,BLK_K,n,k,l)
constexpr auto scales_m = Int<ScaleMsPerTile>{}; auto tM = get<2>(gA_mkl.shape()); auto tN = get<2>(gB_nkl.shape()); auto tK = get<3>(gA_mkl.shape());
// Make the tiled views of scale tensors auto scaleA_shape = make_shape(M / ScaleGranularityM, tK, L); // (scale_m,k,l) auto scaleA_layout = make_ordered_layout(scaleA_shape, Step<_0, _1, _2>{}); auto scaleB_shape = make_shape(tN, tK, L); // (n,k,l) auto scaleB_layout = make_ordered_layout(scaleB_shape, Step<_1, _0, _2>{});
// Note that mScaleA_mkl and mScaleB_nkl are already blocked tiled in the `m` host and // gScaleA_mkl and gScaleB_nkl in `g` global memory are same as mScaleA_mkl and mScaleB_nkl. Tensor mScaleA_mkl = make_tensor(make_gmem_ptr(mainloop_params.ptr_scale_A), scaleA_layout); // (scale_m,k,l) Tensor mScaleB_nkl = make_tensor(make_gmem_ptr(mainloop_params.ptr_scale_B), scaleB_layout); // (n,k,l)
return cute::make_tuple(gA_mkl, gB_nkl, mScaleA_mkl, mScaleB_nkl); }
/// Perform a collective-scoped matrix multiply-accumulate /// Producer Perspective template < class TensorA, class TensorB, class TensorScaleA, class TensorScaleB, class KTileIterator, class BlockCoord > CUTLASS_DEVICE void load( Params const& mainloop_params, MainloopPipeline pipeline, PipelineState smem_pipe_write, cute::tuple<TensorA, TensorB, TensorScaleA, TensorScaleB> const& load_inputs, BlockCoord const& blk_coord, KTileIterator k_tile_iter, int k_tile_count, int thread_idx, uint32_t block_rank_in_cluster, TensorStorage& shared_tensors) { int lane_predicate = cute::elect_one_sync();
// Blockscaling: Tma loads for load_input and CpAsync for load_scale Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.data()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.data()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) Tensor sScaleA = make_tensor(cute::make_smem_ptr(shared_tensors.smem_scale_A.data()), SmemLayoutScaleA{}); // (ScaleMsPerTile,k) Tensor sScaleB = make_tensor(cute::make_smem_ptr(shared_tensors.smem_scale_B.data()), SmemLayoutScaleB{}); // (k)
// // Prepare the TMA loads for A and B //
constexpr uint32_t cluster_shape_x = get<0>(ClusterShape()); uint2 cluster_local_block_id = {block_rank_in_cluster % cluster_shape_x, block_rank_in_cluster / cluster_shape_x};
Tensor gA_mkl = get<0>(load_inputs); Tensor gB_nkl = get<1>(load_inputs);
auto block_tma_a = mainloop_params.tma_load_a.get_slice(cluster_local_block_id.y); auto block_tma_b = mainloop_params.tma_load_b.get_slice(cluster_local_block_id.x);
// Partition the inputs based on the current block coordinates. auto [m_coord, n_coord, k_coord, l_coord] = blk_coord; Tensor gA = gA_mkl(_,_,m_coord,_,l_coord); // (BLK_M,BLK_K,k) Tensor gB = gB_nkl(_,_,n_coord,_,l_coord); // (BLK_N,BLK_K,k)
// Block scaling: load_scale has scaling tensors in global memory which are not tiled Tensor mScaleA_mkl = get<2>(load_inputs); Tensor mScaleB_nkl = get<3>(load_inputs); auto scales_m = get<0>(mScaleA_mkl.shape());
Tensor cScaleA_mkl = make_identity_tensor(mScaleA_mkl.shape());
Tensor gScaleA = local_tile( mScaleA_mkl, make_tile(Int<ScaleMsPerTile>{}), make_coord(m_coord,_,l_coord)); // (ScaleMsPerTile,k,1) Tensor cScaleA = local_tile( cScaleA_mkl, make_tile(Int<ScaleMsPerTile>{}), make_coord(m_coord,_,l_coord)); Tensor gScaleB = mScaleB_nkl(n_coord,_,l_coord); // (1,k,1)
// TODO: test `scale_copy_a` with `ScaleMsPerTile` < 128 TiledCopy scale_copy_a = make_tiled_copy(SmemBlockScalingCopyAtomA{}, Layout<Shape<_32>>{}, Layout<Shape<_1>>{}); // (1,1,1) TiledCopy scale_copy_b = make_tiled_copy(SmemBlockScalingCopyAtomB{}, Layout<Shape<_1>>{}, Layout<Shape<_1>>{}); // (1,1,1) ThrCopy thr_scale_copy_a = scale_copy_a.get_slice(threadIdx.x); ThrCopy thr_scale_copy_b = scale_copy_b.get_slice(threadIdx.x); Tensor tAgA_ScaleA = thr_scale_copy_a.partition_S(gScaleA); Tensor tAcA_ScaleA = thr_scale_copy_a.partition_S(cScaleA); Tensor tAsA_ScaleA = thr_scale_copy_a.partition_D(sScaleA); Tensor tBgB_ScaleB = thr_scale_copy_b.partition_S(gScaleB); Tensor tBsB_ScaleB = thr_scale_copy_b.partition_D(sScaleB);
// Applies the mapping from block_tma_a Tensor tAgA = block_tma_a.partition_S(gA); // (TMA,TMA_M,TMA_K,k) Tensor tAsA = block_tma_a.partition_D(sA); // (TMA,TMA_M,TMA_K,PIPE)
Tensor tBgB = block_tma_b.partition_S(gB); // (TMA,TMA_N,TMA_K,k) Tensor tBsB = block_tma_b.partition_D(sB); // (TMA,TMA_N,TMA_K,PIPE)
uint16_t mcast_mask_a = 0; uint16_t mcast_mask_b = 0;
// Issue TmaLoads for GEMM operands A/B and CpAsync for scale tensors // Maps the tile -> block, value if constexpr (cute::is_same_v<GmemTiledCopyA, SM90_TMA_LOAD_MULTICAST>) { auto block_layout = Layout<typename DispatchPolicy::ClusterShape>{}; // (m,n) -> block_id for (int n = 0; n < size<1>(block_layout); ++n) { mcast_mask_a |= (uint16_t(1) << block_layout(cluster_local_block_id.x,n,Int<0>{})); } }
if constexpr (cute::is_same_v<GmemTiledCopyB, SM90_TMA_LOAD_MULTICAST>) { auto block_layout = Layout<typename DispatchPolicy::ClusterShape>{}; // (m,n) -> block_id for (int m = 0; m < size<0>(block_layout); ++m) { mcast_mask_b |= (uint16_t(1) << block_layout(m,cluster_local_block_id.y,Int<0>{})); } }
// Allocate predicate tensors for a_scales (since we can't guarantee that // all scales are valid, since we could have a partial tiles along M) Tensor tApA_ScaleA = make_tensor<bool>(shape(tAsA_ScaleA(_,_,0))); #pragma unroll for (int i = 0; i < size(tApA_ScaleA); ++i) { tApA_ScaleA(i) = get<0>(tAcA_ScaleA(i)) < scales_m; }
// Mainloop CUTLASS_PRAGMA_NO_UNROLL for ( ; k_tile_count > 0; --k_tile_count) { // LOCK smem_pipe_write for _writing_ pipeline.producer_acquire(smem_pipe_write);
// // Copy gmem to smem for *k_tile_iter // int write_stage = smem_pipe_write.index(); using BarrierType = typename MainloopPipeline::ProducerBarrierType; BarrierType* tma_barrier = pipeline.producer_get_barrier(smem_pipe_write);
// Copy operands A and B from global memory to shared memory if (lane_predicate) copy(mainloop_params.tma_load_a.with(*tma_barrier, mcast_mask_a), tAgA(_,_,_,*k_tile_iter), tAsA(_,_,_,write_stage)); if (lane_predicate) copy(mainloop_params.tma_load_b.with(*tma_barrier, mcast_mask_b), tBgB(_,_,_,*k_tile_iter), tBsB(_,_,_,write_stage));
// Copy scale tensors from global memory to shared memory copy_if(scale_copy_a, tApA_ScaleA, tAgA_ScaleA(_,_,*k_tile_iter), tAsA_ScaleA(_,_,write_stage)); copy(scale_copy_b, tBgB_ScaleB(_,*k_tile_iter), tBsB_ScaleB(_,write_stage)); pipeline.producer_commit(smem_pipe_write, cutlass::arch::cpasync_barrier_arrive_noinc);
++k_tile_iter;
// Advance smem_pipe_write ++smem_pipe_write; } }
/// Perform a Producer Epilogue to prevent early exit of blocks in a Cluster CUTLASS_DEVICE void load_tail( MainloopPipeline pipeline, PipelineState smem_pipe_write) { int lane_predicate = cute::elect_one_sync();
// Issue the epilogue waits if (lane_predicate) { /* This helps avoid early exit of blocks in Cluster * Waits for all stages to either be released (all * Consumer UNLOCKs), or if the stage was never used * then would just be acquired since the phase was * still inverted from make_producer_start_state */ pipeline.producer_tail(smem_pipe_write); } }
/// Perform a collective-scoped matrix multiply-accumulate /// Consumer Perspective template < class FrgTensorC > CUTLASS_DEVICE void mma(MainloopPipeline pipeline, PipelineState smem_pipe_read, FrgTensorC& accum, int k_tile_count, int thread_idx, TensorStorage& shared_tensors, Params const& mainloop_params) {
static_assert(is_rmem<FrgTensorC>::value, "C tensor must be rmem resident."); static_assert(cute::rank(SmemLayoutA{}) == 3, "Smem layout must be rank 3."); static_assert(cute::rank(SmemLayoutB{}) == 3, "Smem layout must be rank 3."); static_assert(cute::is_void_v<SmemCopyAtomA>, "SM90 GMMA mainloops cannot have a non-void copy atom for smem sourced instructions."); static_assert(cute::is_void_v<SmemCopyAtomB>, "SM90 GMMA mainloops cannot have a non-void copy atom for smem sourced instructions.");
Tensor sA = make_tensor(make_smem_ptr(shared_tensors.smem_A.data()), SmemLayoutA{}); // (BLK_M,BLK_K,PIPE) Tensor sB = make_tensor(make_smem_ptr(shared_tensors.smem_B.data()), SmemLayoutB{}); // (BLK_N,BLK_K,PIPE) // Block scaling Tensor sScaleAViewAsC = make_tensor(cute::make_smem_ptr(shared_tensors.smem_scale_A.data()), Layout< Shape<Shape<Int<ScaleGranularityM>, Int<ScaleMsPerTile>>, cute::tuple_element_t<1, TileShape>, Int<DispatchPolicy::Stages>>, Stride<Stride<_0, _1>, _0, Int<ScaleMsPerTile>> >{}); // ((ScaleGranularityM,ScaleMsPerTile),n,k) Tensor sScaleB = make_tensor(cute::make_smem_ptr(shared_tensors.smem_scale_B.data()), SmemLayoutScaleB{}); // (k)
// // Define C accumulators and A/B partitioning // // Layout of warp group to thread mapping
static_assert(stride<0>(typename TiledMma::ALayout{}) == 0 and stride<0>(typename TiledMma::BLayout{}) == 0 and size<0>(typename TiledMma::ALayout{}) == NumThreadsPerWarpGroup and size<0>(typename TiledMma::BLayout{}) == NumThreadsPerWarpGroup, "Stride of the first mode must be 0 and the size of the mode must be NumThreadsPerWarpGroup");
constexpr int MmaWarpGroups = size(TiledMma{}) / NumThreadsPerWarpGroup; Layout warp_group_thread_layout = make_layout(Int<MmaWarpGroups>{}, Int<NumThreadsPerWarpGroup>{});
int warp_group_idx = __shfl_sync(0xFFFFFFFF, thread_idx / NumThreadsPerWarpGroup, 0);
TiledMma tiled_mma; auto thread_mma = tiled_mma.get_slice(warp_group_thread_layout(warp_group_idx));
Tensor tCsScaleAViewAsC = tiled_mma.get_slice(thread_idx).partition_C(sScaleAViewAsC); // (MMA,MMA_M,MMA_N,PIPE), `thread_mma` above is correct when partitioning A and B, but it is not correct when partitioning C.
Tensor tCsA = thread_mma.partition_A(sA); // (MMA,MMA_M,MMA_K,PIPE) Tensor tCsB = thread_mma.partition_B(sB); // (MMA,MMA_N,MMA_K,PIPE)
// Allocate "fragments/descriptors" Tensor tCrA = thread_mma.make_fragment_A(tCsA); // (MMA,MMA_M,MMA_K,PIPE) Tensor tCrB = thread_mma.make_fragment_B(tCsB); // (MMA,MMA_N,MMA_K,PIPE)
CUTE_STATIC_ASSERT_V(size<1>(tCsA) == size<1>(accum)); // M CUTE_STATIC_ASSERT_V(size<1>(tCsB) == size<2>(accum)); // N CUTE_STATIC_ASSERT_V(size<2>(tCsA) == size<2>(tCsB)); // K CUTE_STATIC_ASSERT_V(size<3>(tCsA) == size<3>(tCsB)); // PIPE CUTE_STATIC_ASSERT_V(Int<DispatchPolicy::Stages>{} == size<2>(sA)); // PIPE CUTE_STATIC_ASSERT_V(Int<DispatchPolicy::Stages>{} == size<2>(sB)); // PIPE
// // PIPELINED MAIN LOOP // static_assert((0 <= K_PIPE_MMAS) && (K_PIPE_MMAS < K_PIPE_MAX), "ERROR : Incorrect number of MMAs in flight");
// We release buffers to producer warps(dma load) with some mmas in flight PipelineState smem_pipe_release = smem_pipe_read; // Per block scale values for operand A and B
using RegLayoutScaleAViewAsC = decltype(make_layout_like(tCsScaleAViewAsC(_, _, _, 0).layout())); // `make_layout_like` makes a compact layout. using RegLayoutScaleAEssential = decltype(filter_zeros(RegLayoutScaleAViewAsC{}.stride(), RegLayoutScaleAViewAsC{}.shape())); // an interface to traverse the underlying storage for the compact layout mentioned above
Tensor tCrScaleAViewAsC = make_tensor<ElementBlockScale>(RegLayoutScaleAViewAsC{}); // (MMA,MMA_M,MMA_N) ElementBlockScale scale_b;
// Prologue GMMAs int prologue_mma_count = min(K_PIPE_MMAS, k_tile_count);
tiled_mma.accumulate_ = GMMA::ScaleOut::Zero;
GmmaFP8AccumulationWithScale accumulation(accum, size<2>(TileShape{}) / size<2>(typename TiledMma::AtomShape_MNK{}), size<2>(tCrA)); warpgroup_fence_operand(accumulation()); CUTLASS_PRAGMA_UNROLL for (int k_tile_prologue = prologue_mma_count; k_tile_prologue > 0; --k_tile_prologue) { // WAIT on smem_pipe_read until its data are available (phase bit flips from rdPhaseBit value) auto barrier_token = pipeline.consumer_try_wait(smem_pipe_read); pipeline.consumer_wait(smem_pipe_read, barrier_token);
if (accumulation.prepare_if_needed()) { tiled_mma.accumulate_ = GMMA::ScaleOut::Zero; }
int read_stage = smem_pipe_read.index(); // Load per block scale values from shared memory to registers. scale_b = sScaleB[read_stage]; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(RegLayoutScaleAEssential{}); i++) { tCrScaleAViewAsC.data()[i] = tCsScaleAViewAsC(_, _, _, read_stage)(idx2crd(i, RegLayoutScaleAEssential{})); } if constexpr (ScaleMsPerTile == 1) { static_assert(size(RegLayoutScaleAEssential{}) == 1); tCrScaleAViewAsC.data()[0] = __shfl_sync(0xffffffff, tCrScaleAViewAsC.data()[0] * scale_b, 0); // `tCrScaleAViewAsC.data()[0]` are all same in a warp group when `ScaleMsPerTile == 1`. } else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(RegLayoutScaleAEssential{}); i++) { tCrScaleAViewAsC.data()[i] = tCrScaleAViewAsC.data()[i] * scale_b; } }
warpgroup_arrive(); // Unroll the K mode manually to set scale D to 1 CUTLASS_PRAGMA_UNROLL for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { // (V,M,K) x (V,N,K) => (V,M,N) cute::gemm(tiled_mma, tCrA(_,_,k_block,read_stage), tCrB(_,_,k_block,read_stage), accumulation()); tiled_mma.accumulate_ = GMMA::ScaleOut::One; } warpgroup_commit_batch();
// Block scale the accumulators with reg tensor `tCrScaleAViewAsC` accumulation.scale_if_needed(tCrScaleAViewAsC);
++smem_pipe_read; }
warpgroup_fence_operand(accumulation()); // Mainloop GMMAs k_tile_count -= prologue_mma_count;
CUTLASS_PRAGMA_NO_UNROLL for ( ; k_tile_count > 0; --k_tile_count) { // WAIT on smem_pipe_read until its data are available (phase bit flips from rdPhaseBit value) auto barrier_token = pipeline.consumer_try_wait(smem_pipe_read); pipeline.consumer_wait(smem_pipe_read, barrier_token);
// // Compute on k_tile //
int read_stage = smem_pipe_read.index();
// Load per block scale values from shared memory to registers (at most twice per block along M and exactly once per block along N) scale_b = sScaleB[read_stage]; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(RegLayoutScaleAEssential{}); i++) { tCrScaleAViewAsC.data()[i] = tCsScaleAViewAsC(_, _, _, read_stage)(idx2crd(i, RegLayoutScaleAEssential{})); } if constexpr (ScaleMsPerTile == 1) { static_assert(size(RegLayoutScaleAEssential{}) == 1); tCrScaleAViewAsC.data()[0] = __shfl_sync(0xffffffff, tCrScaleAViewAsC.data()[0] * scale_b, 0); // `tCrScaleAViewAsC.data()[0]` are all same in a warp group when `ScaleMsPerTile == 1`. } else { CUTLASS_PRAGMA_UNROLL for (int i = 0; i < size(RegLayoutScaleAEssential{}); i++) { tCrScaleAViewAsC.data()[i] = tCrScaleAViewAsC.data()[i] * scale_b; } }
if (accumulation.prepare_if_needed()) { tiled_mma.accumulate_ = GMMA::ScaleOut::Zero; }
warpgroup_fence_operand(accumulation()); warpgroup_arrive(); // Unroll the K mode manually to set scale D to 1 CUTLASS_PRAGMA_UNROLL for (int k_block = 0; k_block < size<2>(tCrA); ++k_block) { // (V,M,K) x (V,N,K) => (V,M,N) cute::gemm(tiled_mma, tCrA(_,_,k_block,read_stage), tCrB(_,_,k_block,read_stage), accumulation()); tiled_mma.accumulate_ = GMMA::ScaleOut::One; } warpgroup_commit_batch();
/// Wait on the GMMA barrier for K_PIPE_MMAS (or fewer) outstanding to ensure smem_pipe_write is consumed warpgroup_wait<K_PIPE_MMAS>(); warpgroup_fence_operand(accumulation());
// Block scale the accumulators with reg tensor `tCrScaleAViewAsC` accumulation.scale_if_needed(tCrScaleAViewAsC);
pipeline.consumer_release(smem_pipe_release); // UNLOCK smem_pipe_release, done _computing_ on it
// Advance smem_pipe_read and smem_pipe_release ++smem_pipe_read; ++smem_pipe_release; } accumulation.scale_residue_if_needed(tCrScaleAViewAsC);
warpgroup_fence_operand(accumulation()); }
/// Perform a Consumer Epilogue to release all buffers CUTLASS_DEVICE void mma_tail(MainloopPipeline pipeline, PipelineState smem_pipe_release, int k_tile_count) { // Prologue GMMAs int prologue_mma_count = min(K_PIPE_MMAS, k_tile_count); k_tile_count -= prologue_mma_count;
smem_pipe_release.advance(k_tile_count);
// Wait on all GMMAs to complete warpgroup_wait<0>();
for (int count = 0; count < prologue_mma_count; ++count) { pipeline.consumer_release(smem_pipe_release); // UNLOCK smem_pipe_release, done _computing_ on it ++smem_pipe_release; } }};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::gemm::collective
/////////////////////////////////////////////////////////////////////////////////////////////////123456789101112131415161718192021222324252627282930313233343536373839#pragma once
#include "cutlass/gemm/dispatch_policy.hpp"
namespace cutlass::gemm {
//////////////////////////////////////////////////////////////////////////////
// FP8 related policies (including Blocked Scaled Accumulation)// `ScaleGranularityM` specifies scaling granularity along M, while zero-value// `ScaleGranularityM` indicates that scaling granularity is// `size<0>(TileShape_MNK{})` along M.template <int ScaleGranularityM = 0>struct KernelTmaWarpSpecializedCooperativeFP8BlockScaledSubGroupMAccum : KernelTmaWarpSpecializedCooperative {};
// n-buffer in smem (Hopper TMA), pipelined with Hopper GMMA and TMA, Warp// specialized dynamic schedule For FP8 kernels with Block Scalingtemplate <int Stages_, class ClusterShape_ = Shape<_1, _1, _1>, class KernelSchedule = KernelTmaWarpSpecialized, int ScaleGranularityM = 0 // `ScaleGranularityM` specifies scaling granularity along M, // while zero-value `ScaleGranularityM` indicates that scaling // granularity is `size<0>(TileShape_MNK{})` along M. >struct MainloopSm90TmaGmmaWarpSpecializedBlockScalingSubGroupMFP8 : MainloopSm90TmaGmmaWarpSpecialized<Stages_, ClusterShape_, KernelSchedule> { static_assert( cute::is_same_v< KernelSchedule, KernelTmaWarpSpecializedCooperativeFP8BlockScaledSubGroupMAccum< ScaleGranularityM>>, "KernelSchedule must be one of the warp specialized policies");};
//////////////////////////////////////////////////////////////////////////////
} // namespace cutlass::gemm123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107#pragma once
// clang-format will break include orders// clang-format off#include <torch/all.h>
#include <ATen/cuda/CUDAContext.h>
#include "cutlass/cutlass.h"
#include "cute/tensor.hpp"#include "cute/atom/mma_atom.hpp"#include "cutlass/numeric_types.h"
#include "cutlass/gemm/device/gemm_universal_adapter.h"#include "cutlass/gemm/kernel/gemm_universal.hpp"#include "cutlass/epilogue/collective/collective_builder.hpp"#include "cutlass/gemm/collective/collective_builder.hpp"#include "cutlass/util/packed_stride.hpp"
#include "core/math.hpp"#include "cutlass_extensions/common.hpp"// clang-format on
namespace vllm::c3x {
static inline cute::Shape<int, int, int, int> get_problem_shape( torch::Tensor const& a, torch::Tensor const& b) { int32_t m = a.size(0), n = b.size(1), k = a.size(1); return {m, n, k, 1};}
template <typename GemmKernel>void cutlass_gemm_caller( torch::Device device, cute::Shape<int, int, int, int> prob_shape, typename GemmKernel::MainloopArguments mainloop_args, typename GemmKernel::EpilogueArguments epilogue_args, typename GemmKernel::TileSchedulerArguments scheduler = {}) { cutlass::KernelHardwareInfo hw_info; typename GemmKernel::Arguments args{cutlass::gemm::GemmUniversalMode::kGemm, prob_shape, mainloop_args, epilogue_args, hw_info, scheduler};
// Launch the CUTLASS GEMM kernel. using GemmOp = cutlass::gemm::device::GemmUniversalAdapter<GemmKernel>; GemmOp gemm_op; CUTLASS_CHECK(gemm_op.can_implement(args));
size_t workspace_size = gemm_op.get_workspace_size(args); auto const workspace_options = torch::TensorOptions().dtype(torch::kUInt8).device(device); auto workspace = torch::empty(workspace_size, workspace_options);
auto stream = at::cuda::getCurrentCUDAStream(device.index());
cutlass::Status status = gemm_op.run(args, workspace.data_ptr(), stream); CUTLASS_CHECK(status);}
template <typename Gemm, typename... EpilogueArgs>void cutlass_gemm_caller(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... epilogue_params) { using ElementAB = typename Gemm::ElementAB; using ElementC = typename Gemm::ElementC; using ElementD = typename Gemm::ElementD; using GemmKernel = typename Gemm::GemmKernel;
using StrideA = typename Gemm::GemmKernel::StrideA; using StrideB = typename Gemm::GemmKernel::StrideB; using StrideC = typename Gemm::GemmKernel::StrideC; using StrideD = StrideC; using StrideAux = StrideC;
typename GemmKernel::ProblemShape prob_shape = get_problem_shape(a, b); auto [M, N, K, L] = prob_shape;
StrideA a_stride = cutlass::make_cute_packed_stride(StrideA{}, cute::make_shape(M, K, L)); StrideB b_stride = cutlass::make_cute_packed_stride(StrideB{}, cute::make_shape(N, K, L)); StrideC c_stride = cutlass::make_cute_packed_stride(StrideC{}, cute::make_shape(M, N, L)); StrideD d_stride = cutlass::make_cute_packed_stride(StrideD{}, cute::make_shape(M, N, L)); StrideAux aux_stride = d_stride;
auto a_ptr = static_cast<ElementAB*>(a.data_ptr()); auto b_ptr = static_cast<ElementAB*>(b.data_ptr()); typename GemmKernel::MainloopArguments mainloop_args{a_ptr, a_stride, b_ptr, b_stride};
auto c_ptr = static_cast<ElementD*>(out.data_ptr()); // auto d_ptr = static_cast<ElementC*>(out.data_ptr()); typename GemmKernel::EpilogueArguments epilogue_args{ Gemm::Epilogue::prepare_args( std::forward<EpilogueArgs>(epilogue_params)...), c_ptr, c_stride, c_ptr, d_stride};
cutlass_gemm_caller<GemmKernel>(a.device(), prob_shape, mainloop_args, epilogue_args);}
} // namespace vllm::c3x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147#pragma once
// clang-format will break include orders// clang-format off
#include "cutlass/cutlass.h"
#include "cute/tensor.hpp"#include "cute/atom/mma_atom.hpp"#include "cutlass/numeric_types.h"
#include "cutlass/gemm/device/gemm_universal_adapter.h"#include "cutlass/gemm/kernel/gemm_universal.hpp"#include "cutlass/epilogue/collective/collective_builder.hpp"#include "cutlass/gemm/collective/collective_builder.hpp"
#include "core/math.hpp"#include "cutlass_extensions/common.hpp"// clang-format on
/* Epilogues defined in, csrc/cutlass_extensions/epilogue/scaled_mm_epilogues_c3x.hpp, must contain a public type named EVTCompute of type Sm90EVT, as well as a static prepare_args function that constructs an EVTCompute::Arguments struct.*/
using namespace cute;
namespace vllm {
template <typename ElementAB_, typename ElementD_, template <typename, typename, typename> typename Epilogue_, typename TileShape, typename ClusterShape, typename KernelSchedule, typename EpilogueSchedule>struct cutlass_3x_gemm { using ElementAB = ElementAB_; using ElementD = ElementD_; using ElementAcc = typename std::conditional<std::is_same_v<ElementAB, int8_t>, int32_t, float>::type;
using Epilogue = Epilogue_<ElementAcc, ElementD, TileShape>;
using StrideD = Stride<int64_t, Int<1>, Int<0>>; using ElementC = void; using StrideC = StrideD;
using EVTCompute = typename Epilogue::EVTCompute;
// These are the minimum alignments needed for the kernels to compile static constexpr int AlignmentAB = 128 / cutlass::sizeof_bits<ElementAB>::value; static constexpr int AlignmentCD = 4;
using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< cutlass::arch::Sm90, cutlass::arch::OpClassTensorOp, TileShape, ClusterShape, cutlass::epilogue::collective::EpilogueTileAuto, ElementAcc, float, ElementC, StrideC, AlignmentCD, ElementD, StrideD, AlignmentCD, EpilogueSchedule, EVTCompute>::CollectiveOp;
static constexpr size_t CEStorageSize = sizeof(typename CollectiveEpilogue::SharedStorage); using Stages = typename cutlass::gemm::collective::StageCountAutoCarveout< static_cast<int>(CEStorageSize)>;
// clang-format off using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< cutlass::arch::Sm90, cutlass::arch::OpClassTensorOp, ElementAB, cutlass::layout::RowMajor, AlignmentAB, ElementAB, cutlass::layout::ColumnMajor, AlignmentAB, ElementAcc, TileShape, ClusterShape, Stages, KernelSchedule>::CollectiveOp; // clang-format on
using KernelType = enable_sm90_or_later<cutlass::gemm::kernel::GemmUniversal< cute::Shape<int, int, int, int>, CollectiveMainloop, CollectiveEpilogue, cutlass::gemm::PersistentScheduler>>;
struct GemmKernel : public KernelType {};};
template <typename ElementAB_, typename ElementD_, template <typename, typename, typename> typename Epilogue_, typename TileShape, typename ClusterShape, typename KernelSchedule, typename EpilogueSchedule>struct cutlass_3x_gemm_sm100 { using ElementAB = ElementAB_; using LayoutA = cutlass::layout::RowMajor; static constexpr int AlignmentA = 128 / cutlass::sizeof_bits<ElementAB>::value;
using LayoutB = cutlass::layout::ColumnMajor; static constexpr int AlignmentB = 128 / cutlass::sizeof_bits<ElementAB>::value;
using ElementC = void; using LayoutC = cutlass::layout::RowMajor; static constexpr int AlignmentC = 128 / cutlass::sizeof_bits<ElementD_>::value;
using ElementD = ElementD_; using LayoutD = cutlass::layout::RowMajor; static constexpr int AlignmentD = AlignmentC;
using ElementAcc = typename std::conditional<std::is_same_v<ElementAB, int8_t>, int32_t, float>::type; using Epilogue = Epilogue_<ElementAcc, ElementD, TileShape>;
// MMA type using ElementAccumulator = float;
// Epilogue types using ElementBias = cutlass::half_t; using ElementCompute = float; using ElementAux = ElementD; using LayoutAux = LayoutD; using ElementAmax = float;
using EVTCompute = typename Epilogue::EVTCompute;
using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, TileShape, ClusterShape, cutlass::epilogue::collective::EpilogueTileAuto, ElementAccumulator, ElementCompute, ElementC, LayoutC, AlignmentC, ElementD, LayoutD, AlignmentD, EpilogueSchedule, EVTCompute>::CollectiveOp;
using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< cutlass::arch::Sm100, cutlass::arch::OpClassTensorOp, ElementAB, LayoutA, AlignmentA, ElementAB, LayoutB, AlignmentB, ElementAccumulator, TileShape, ClusterShape, cutlass::gemm::collective::StageCountAutoCarveout<static_cast<int>( sizeof(typename CollectiveEpilogue::SharedStorage))>, KernelSchedule>::CollectiveOp;
using GemmKernel = cutlass::gemm::kernel::GemmUniversal< Shape<int, int, int, int>, CollectiveMainloop, CollectiveEpilogue, void>;};
} // namespace vllm123456789101112131415161718192021222324#include "scaled_mm_kernels.hpp"#include "scaled_mm_sm90_int8_dispatch.cuh"#include "cutlass_extensions/epilogue/scaled_mm_epilogues_c3x.hpp"
namespace vllm {
void cutlass_scaled_mm_azp_sm90_int8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, torch::Tensor const& azp_adj, std::optional<torch::Tensor> const& azp, std::optional<torch::Tensor> const& bias) { if (azp) { return cutlass_scaled_mm_sm90_int8_epilogue< c3x::ScaledEpilogueBiasAzpToken>(out, a, b, a_scales, b_scales, azp_adj, *azp, bias); } else { return cutlass_scaled_mm_sm90_int8_epilogue<c3x::ScaledEpilogueBiasAzp>( out, a, b, a_scales, b_scales, azp_adj, bias); }}
} // namespace vllm123456789101112131415161718192021222324
#include "scaled_mm_kernels.hpp"#include "scaled_mm_blockwise_sm90_fp8_dispatch.cuh"#include "cutlass_extensions/epilogue/scaled_mm_epilogues_c3x.hpp"
namespace vllm {
void cutlass_scaled_mm_blockwise_sm90_fp8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales) { if (out.dtype() == torch::kBFloat16) { cutlass_gemm_blockwise_sm90_fp8_dispatch<cutlass::bfloat16_t>( out, a, b, a_scales, b_scales);
} else { TORCH_CHECK(out.dtype() == torch::kFloat16); cutlass_gemm_blockwise_sm90_fp8_dispatch<cutlass::half_t>( out, a, b, a_scales, b_scales); }}
} // namespace vllm123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194#pragma once
#include "cutlass/cutlass.h"#include "cutlass/numeric_types.h"
#include "cute/tensor.hpp"#include "cutlass/tensor_ref.h"#include "cutlass/gemm/dispatch_policy.hpp"#include "cutlass/gemm/collective/collective_builder.hpp"#include "cutlass/gemm/device/gemm_universal_adapter.h"#include "cutlass/gemm/kernel/gemm_universal.hpp"#include "cutlass/gemm/kernel/tile_scheduler_params.h"#include "cutlass/epilogue/dispatch_policy.hpp"#include "cutlass/epilogue/collective/collective_builder.hpp"
#include "cutlass_extensions/gemm/dispatch_policy.hpp"#include "cutlass_extensions/gemm/collective/collective_builder.hpp"
#include "cutlass_gemm_caller.cuh"
namespace vllm {
using namespace cute;
template <typename SchedulerType, typename OutType, int GroupSizeM_, int GroupSizeN_, int GroupSizeK_, int TileSizeM_ = 128, class ClusterShape = Shape<_1, _2, _1>>struct cutlass_3x_gemm_fp8_blockwise { using GroupSizeM = Int<GroupSizeM_>; using GroupSizeN = Int<GroupSizeN_>; using GroupSizeK = Int<GroupSizeK_>; using TileSizeM = Int<TileSizeM_>;
static_assert(TileSizeM_ % GroupSizeM_ == 0, "TileSizeM must be a multiple of GroupSizeM");
using ElementAB = cutlass::float_e4m3_t;
using ElementA = ElementAB; using LayoutA = cutlass::layout::RowMajor; static constexpr int AlignmentA = 128 / cutlass::sizeof_bits<ElementA>::value;
using ElementB = ElementAB; using LayoutB = cutlass::layout::ColumnMajor; static constexpr int AlignmentB = 128 / cutlass::sizeof_bits<ElementB>::value;
using ElementD = OutType; using StrideD = Stride<int64_t, Int<1>, Int<0>>; static constexpr int AlignmentD = 128 / cutlass::sizeof_bits<ElementD>::value;
using ElementC = void; using StrideC = StrideD; static constexpr int AlignmentC = AlignmentD;
using ElementAccumulator = float; using ElementBlockScale = float; using ElementCompute = float; using ArchTag = cutlass::arch::Sm90; using OperatorClass = cutlass::arch::OpClassTensorOp; using TileShape = Shape<TileSizeM, GroupSizeN, GroupSizeK>;
using KernelSchedule = cutlass::gemm:: KernelTmaWarpSpecializedCooperativeFP8BlockScaledSubGroupMAccum< GroupSizeM_>; using EpilogueSchedule = cutlass::epilogue::TmaWarpSpecializedCooperative; using EpilogueTileType = cutlass::epilogue::collective::EpilogueTileAuto;
using StoreEpilogueCompute = typename cutlass::epilogue::fusion::Sm90EVT< cutlass::epilogue::fusion::Sm90AccFetch>;
using CollectiveEpilogue = typename cutlass::epilogue::collective::CollectiveBuilder< ArchTag, OperatorClass, TileShape, ClusterShape, EpilogueTileType, ElementAccumulator, ElementCompute, ElementC, StrideC, AlignmentC, ElementD, StrideD, AlignmentD, EpilogueSchedule, StoreEpilogueCompute>::CollectiveOp;
using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< ArchTag, OperatorClass, ElementA, LayoutA, AlignmentA, ElementB, LayoutB, AlignmentB, ElementAccumulator, TileShape, ClusterShape, cutlass::gemm::collective::StageCountAutoCarveout<static_cast<int>( sizeof(typename CollectiveEpilogue::SharedStorage))>, KernelSchedule>::CollectiveOp;
using KernelType = enable_sm90_or_later<cutlass::gemm::kernel::GemmUniversal< Shape<int, int, int, int>, CollectiveMainloop, CollectiveEpilogue, SchedulerType>>;
struct GemmKernel : public KernelType {};
using StrideA = typename GemmKernel::StrideA; using StrideB = typename GemmKernel::StrideB;};
template <typename Gemm>void cutlass_gemm_caller_blockwise(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales) { using GemmKernel = typename Gemm::GemmKernel;
using ElementAB = typename Gemm::ElementAB; using ElementD = typename Gemm::ElementD;
auto prob_shape = c3x::get_problem_shape(a, b); int32_t m = get<0>(prob_shape), n = get<1>(prob_shape), k = get<2>(prob_shape);
int64_t lda = a.stride(0); int64_t ldb = b.stride(1); int64_t ldc = out.stride(0);
using StrideA = Stride<int64_t, Int<1>, int64_t>; using StrideB = Stride<int64_t, Int<1>, int64_t>; using StrideC = typename Gemm::StrideC;
StrideA a_stride{lda, Int<1>{}, 0}; StrideB b_stride{ldb, Int<1>{}, 0}; StrideC c_stride{ldc, Int<1>{}, Int<0>{}};
auto a_ptr = static_cast<ElementAB*>(a.data_ptr()); auto b_ptr = static_cast<ElementAB*>(b.data_ptr()); auto a_scales_ptr = static_cast<float*>(a_scales.data_ptr()); auto b_scales_ptr = static_cast<float*>(b_scales.data_ptr());
// Check is the t is contiguous and is 1D or 2D with one of the dimensions // being 1 (i.e. a row or column vector) auto is_contiguous_vector = [](const torch::Tensor& t) { auto t_sizes = t.sizes(); return t.is_contiguous() && (t.dim() == 1 || (t.dim() == 2 && *std::min_element(t_sizes.begin(), t_sizes.end()) == 1)); };
// TODO(lucas): lets clean-up the kernel so that we pass in Strides so // we don't have to deal with enforcing implicit layouts TORCH_CHECK(a_scales.size(0) == m / Gemm::GroupSizeM::value); TORCH_CHECK(a_scales.size(1) == k / Gemm::GroupSizeK::value); TORCH_CHECK(a_scales.stride(0) == 1 || is_contiguous_vector(a_scales), "a_scales must be M major"); TORCH_CHECK(b_scales.size(0) == k / Gemm::GroupSizeK::value); TORCH_CHECK(b_scales.size(1) == n / Gemm::GroupSizeN::value); TORCH_CHECK(b_scales.stride(0) == 1 || is_contiguous_vector(b_scales), "b_scales must be K major"); typename GemmKernel::MainloopArguments mainloop_args{ a_ptr, a_stride, b_ptr, b_stride, a_scales_ptr, b_scales_ptr};
auto c_ptr = static_cast<ElementD*>(out.data_ptr()); typename GemmKernel::EpilogueArguments epilogue_args{ {}, c_ptr, c_stride, c_ptr, c_stride};
typename GemmKernel::TileSchedulerArguments scheduler;
static constexpr bool UsesStreamKScheduler = cute::is_same_v<typename GemmKernel::TileSchedulerTag, cutlass::gemm::StreamKScheduler>;
if constexpr (UsesStreamKScheduler) { using DecompositionMode = typename cutlass::gemm::kernel::detail:: PersistentTileSchedulerSm90StreamKParams::DecompositionMode; using ReductionMode = typename cutlass::gemm::kernel::detail:: PersistentTileSchedulerSm90StreamKParams::ReductionMode;
scheduler.decomposition_mode = DecompositionMode::StreamK; scheduler.reduction_mode = ReductionMode::Nondeterministic; }
c3x::cutlass_gemm_caller<GemmKernel>(a.device(), prob_shape, mainloop_args, epilogue_args, scheduler);}
template <typename OutType>void cutlass_gemm_blockwise_sm90_fp8_dispatch(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales) { auto k = a.size(1); auto n = b.size(1);
if (k > 3 * n) { cutlass_gemm_caller_blockwise<cutlass_3x_gemm_fp8_blockwise< cutlass::gemm::StreamKScheduler, OutType, 1, 128, 128>>( out, a, b, a_scales, b_scales); } else { cutlass_gemm_caller_blockwise<cutlass_3x_gemm_fp8_blockwise< cutlass::gemm::PersistentScheduler, OutType, 1, 128, 128>>( out, a, b, a_scales, b_scales); }}
} // namespace vllm123456789101112131415161718192021222324252627282930313233343536373839#pragma once
#include <torch/all.h>
namespace vllm {
void cutlass_scaled_mm_sm90_fp8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias);
void cutlass_scaled_mm_sm90_int8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias);
void cutlass_scaled_mm_azp_sm90_int8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, torch::Tensor const& azp_adj, std::optional<torch::Tensor> const& azp, std::optional<torch::Tensor> const& bias);
void cutlass_scaled_mm_blockwise_sm90_fp8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales);
void cutlass_scaled_mm_sm100_fp8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias);
} // namespace vllm123456789101112131415161718192021222324#include "scaled_mm_kernels.hpp"#include "scaled_mm_sm100_fp8_dispatch.cuh"#include "cutlass_extensions/epilogue/scaled_mm_epilogues_c3x.hpp"
namespace vllm {
void cutlass_scaled_mm_sm100_fp8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias) { TORCH_CHECK(a_scales.is_contiguous() && b_scales.is_contiguous()); if (bias) { TORCH_CHECK(bias->dtype() == out.dtype(), "currently bias dtype must match output dtype ", out.dtype()); return cutlass_scaled_mm_sm100_fp8_epilogue<c3x::ScaledEpilogueBias>( out, a, b, a_scales, b_scales, *bias); } else { return cutlass_scaled_mm_sm100_fp8_epilogue<c3x::ScaledEpilogue>( out, a, b, a_scales, b_scales); }}
} // namespace vllm12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#pragma once
#include "scaled_mm.cuh"#include "cutlass_gemm_caller.cuh"
/** * This file defines Gemm kernel configurations for SM100 (fp8) based on the * Gemm shape. */
namespace vllm {
using c3x::cutlass_gemm_caller;
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm100_fp8_config_default { static_assert(std::is_same<InType, cutlass::float_e4m3_t>()); using KernelSchedule = cutlass::gemm::collective::KernelScheduleAuto; using EpilogueSchedule = cutlass::epilogue::collective::EpilogueScheduleAuto; using TileShape = Shape<_256, _128, _64>; using ClusterShape = Shape<_2, _2, _1>; using Cutlass3xGemm = cutlass_3x_gemm_sm100<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue, typename... EpilogueArgs>inline void cutlass_gemm_sm100_fp8_dispatch(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... args) { static_assert(std::is_same<InType, cutlass::float_e4m3_t>()); TORCH_CHECK(a.dtype() == torch::kFloat8_e4m3fn); TORCH_CHECK(b.dtype() == torch::kFloat8_e4m3fn);
using Cutlass3xGemmDefault = typename sm100_fp8_config_default<InType, OutType, Epilogue>::Cutlass3xGemm; return cutlass_gemm_caller<Cutlass3xGemmDefault>( out, a, b, std::forward<EpilogueArgs>(args)...);}
template <template <typename, typename, typename> typename Epilogue, typename... EpilogueArgs>void cutlass_scaled_mm_sm100_fp8_epilogue(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... epilogue_args) { TORCH_CHECK(a.dtype() == torch::kFloat8_e4m3fn); TORCH_CHECK(b.dtype() == torch::kFloat8_e4m3fn);
if (out.dtype() == torch::kBFloat16) { return cutlass_gemm_sm100_fp8_dispatch<cutlass::float_e4m3_t, cutlass::bfloat16_t, Epilogue>( out, a, b, std::forward<EpilogueArgs>(epilogue_args)...); } else { TORCH_CHECK(out.dtype() == torch::kFloat16); return cutlass_gemm_sm100_fp8_dispatch<cutlass::float_e4m3_t, cutlass::half_t, Epilogue>( out, a, b, std::forward<EpilogueArgs>(epilogue_args)...); }}
} // namespace vllm123456789101112131415161718192021222324#include "scaled_mm_kernels.hpp"#include "scaled_mm_sm90_fp8_dispatch.cuh"#include "cutlass_extensions/epilogue/scaled_mm_epilogues_c3x.hpp"
namespace vllm {
void cutlass_scaled_mm_sm90_fp8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias) { TORCH_CHECK(a_scales.is_contiguous() && b_scales.is_contiguous()); if (bias) { TORCH_CHECK(bias->dtype() == out.dtype(), "currently bias dtype must match output dtype ", out.dtype()); return cutlass_scaled_mm_sm90_fp8_epilogue<c3x::ScaledEpilogueBias>( out, a, b, a_scales, b_scales, *bias); } else { return cutlass_scaled_mm_sm90_fp8_epilogue<c3x::ScaledEpilogue>( out, a, b, a_scales, b_scales); }}
} // namespace vllm123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120#pragma once
#include "scaled_mm.cuh"#include "cutlass_gemm_caller.cuh"
/** * This file defines Gemm kernel configurations for SM90 (fp8) based on the Gemm * shape. */
namespace vllm {
using c3x::cutlass_gemm_caller;
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_fp8_config_default { // M in (128, inf) static_assert(std::is_same<InType, cutlass::float_e4m3_t>()); using KernelSchedule = cutlass::gemm::KernelTmaWarpSpecializedPingpongFP8FastAccum; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_128, _128, _128>; using ClusterShape = Shape<_2, _1, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_fp8_config_M128 { // M in (64, 128] static_assert(std::is_same<InType, cutlass::float_e4m3_t>()); using KernelSchedule = cutlass::gemm::KernelTmaWarpSpecializedPingpongFP8FastAccum; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_64, _128, _128>; using ClusterShape = Shape<_2, _1, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_fp8_config_M64 { // M in [1, 64] static_assert(std::is_same<InType, cutlass::float_e4m3_t>()); using KernelSchedule = cutlass::gemm::KernelTmaWarpSpecializedPingpongFP8FastAccum; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_64, _64, _128>; using ClusterShape = Shape<_1, _8, _1>;
using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue, typename... EpilogueArgs>inline void cutlass_gemm_sm90_fp8_dispatch(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... args) { static_assert(std::is_same<InType, cutlass::float_e4m3_t>()); TORCH_CHECK(a.dtype() == torch::kFloat8_e4m3fn); TORCH_CHECK(b.dtype() == torch::kFloat8_e4m3fn);
using Cutlass3xGemmDefault = typename sm90_fp8_config_default<InType, OutType, Epilogue>::Cutlass3xGemm; using Cutlass3xGemmM64 = typename sm90_fp8_config_M64<InType, OutType, Epilogue>::Cutlass3xGemm; using Cutlass3xGemmM128 = typename sm90_fp8_config_M128<InType, OutType, Epilogue>::Cutlass3xGemm;
uint32_t const m = a.size(0); uint32_t const mp2 = std::max(static_cast<uint32_t>(64), next_pow_2(m)); // next power of 2
if (mp2 <= 64) { // m in [1, 64] return cutlass_gemm_caller<Cutlass3xGemmM64>( out, a, b, std::forward<EpilogueArgs>(args)...); } else if (mp2 <= 128) { // m in (64, 128] return cutlass_gemm_caller<Cutlass3xGemmM128>( out, a, b, std::forward<EpilogueArgs>(args)...); } else { // m in (128, inf) return cutlass_gemm_caller<Cutlass3xGemmDefault>( out, a, b, std::forward<EpilogueArgs>(args)...); }}
template <template <typename, typename, typename> typename Epilogue, typename... EpilogueArgs>void cutlass_scaled_mm_sm90_fp8_epilogue(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... epilogue_args) { TORCH_CHECK(a.dtype() == torch::kFloat8_e4m3fn); TORCH_CHECK(b.dtype() == torch::kFloat8_e4m3fn);
if (out.dtype() == torch::kBFloat16) { return cutlass_gemm_sm90_fp8_dispatch<cutlass::float_e4m3_t, cutlass::bfloat16_t, Epilogue>( out, a, b, std::forward<EpilogueArgs>(epilogue_args)...); } else { TORCH_CHECK(out.dtype() == torch::kFloat16); return cutlass_gemm_sm90_fp8_dispatch<cutlass::float_e4m3_t, cutlass::half_t, Epilogue>( out, a, b, std::forward<EpilogueArgs>(epilogue_args)...); }}
} // namespace vllm123456789101112131415161718192021222324#include "scaled_mm_kernels.hpp"#include "scaled_mm_sm90_int8_dispatch.cuh"#include "cutlass_extensions/epilogue/scaled_mm_epilogues_c3x.hpp"
namespace vllm {
void cutlass_scaled_mm_sm90_int8(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias) { TORCH_CHECK(a_scales.is_contiguous() && b_scales.is_contiguous()); if (bias) { TORCH_CHECK(bias->dtype() == out.dtype(), "currently bias dtype must match output dtype ", out.dtype()); return cutlass_scaled_mm_sm90_int8_epilogue<c3x::ScaledEpilogueBias>( out, a, b, a_scales, b_scales, *bias); } else { return cutlass_scaled_mm_sm90_int8_epilogue<c3x::ScaledEpilogue>( out, a, b, a_scales, b_scales); }}
} // namespace vllm123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163#pragma once
#include "scaled_mm.cuh"#include "cutlass_gemm_caller.cuh"
/** * This file defines Gemm kernel configurations for SM90 (int8) based on the * Gemm shape. */
namespace vllm {
using c3x::cutlass_gemm_caller;
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_int8_config_default { // For M > 128 and any N static_assert(std::is_same<InType, int8_t>()); using KernelSchedule = typename cutlass::gemm::KernelTmaWarpSpecializedPingpong; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_128, _128, _128>; using ClusterShape = Shape<_2, _1, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_int8_config_M128 { // For M in (64, 128] and any N static_assert(std::is_same<InType, int8_t>()); using KernelSchedule = typename cutlass::gemm::KernelTmaWarpSpecializedPingpong; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_64, _128, _128>; using ClusterShape = Shape<_2, _1, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_int8_config_M64 { // For M in (32, 64] and any N static_assert(std::is_same<InType, int8_t>()); using KernelSchedule = typename cutlass::gemm::KernelTmaWarpSpecialized; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_64, _64, _256>; using ClusterShape = Shape<_1, _1, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_int8_config_M32_NBig { // For M in [1, 32] and N >= 8192 static_assert(std::is_same<InType, int8_t>()); using KernelSchedule = typename cutlass::gemm::KernelTmaWarpSpecialized; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_64, _128, _256>; using ClusterShape = Shape<_1, _4, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue>struct sm90_int8_config_M32_NSmall { // For M in [1, 32] and N < 8192 static_assert(std::is_same<InType, int8_t>()); using KernelSchedule = typename cutlass::gemm::KernelTmaWarpSpecialized; using EpilogueSchedule = typename cutlass::epilogue::TmaWarpSpecialized; using TileShape = Shape<_64, _64, _256>; using ClusterShape = Shape<_1, _8, _1>; using Cutlass3xGemm = cutlass_3x_gemm<InType, OutType, Epilogue, TileShape, ClusterShape, KernelSchedule, EpilogueSchedule>;};
template <typename InType, typename OutType, template <typename, typename, typename> typename Epilogue, typename... EpilogueArgs>inline void cutlass_gemm_sm90_int8_dispatch(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... args) { static_assert(std::is_same<InType, int8_t>()); TORCH_CHECK(a.dtype() == torch::kInt8); TORCH_CHECK(b.dtype() == torch::kInt8);
using Cutlass3xGemmDefault = typename sm90_int8_config_default<InType, OutType, Epilogue>::Cutlass3xGemm; using Cutlass3xGemmM128 = typename sm90_int8_config_M128<InType, OutType, Epilogue>::Cutlass3xGemm; using Cutlass3xGemmM64 = typename sm90_int8_config_M64<InType, OutType, Epilogue>::Cutlass3xGemm; using Cutlass3xGemmM32NBig = typename sm90_int8_config_M32_NBig<InType, OutType, Epilogue>::Cutlass3xGemm; using Cutlass3xGemmM32NSmall = typename sm90_int8_config_M32_NSmall<InType, OutType, Epilogue>::Cutlass3xGemm;
uint32_t const n = out.size(1); bool const is_small_n = n < 8192;
uint32_t const m = a.size(0); uint32_t const mp2 = std::max(static_cast<uint32_t>(32), next_pow_2(m)); // next power of 2
if (mp2 <= 32) { // m in [1, 32] if (is_small_n) { return cutlass_gemm_caller<Cutlass3xGemmM32NSmall>( out, a, b, std::forward<EpilogueArgs>(args)...); } else { return cutlass_gemm_caller<Cutlass3xGemmM32NBig>( out, a, b, std::forward<EpilogueArgs>(args)...); } } else if (mp2 <= 64) { // m in (32, 64] return cutlass_gemm_caller<Cutlass3xGemmM64>( out, a, b, std::forward<EpilogueArgs>(args)...); } else if (mp2 <= 128) { // m in (64, 128] return cutlass_gemm_caller<Cutlass3xGemmM128>( out, a, b, std::forward<EpilogueArgs>(args)...); } else { // m in (128, inf) return cutlass_gemm_caller<Cutlass3xGemmDefault>( out, a, b, std::forward<EpilogueArgs>(args)...); }}
template <template <typename, typename, typename> typename Epilogue, typename... EpilogueArgs>void cutlass_scaled_mm_sm90_int8_epilogue(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, EpilogueArgs&&... epilogue_args) { TORCH_CHECK(a.dtype() == torch::kInt8); TORCH_CHECK(b.dtype() == torch::kInt8);
if (out.dtype() == torch::kBFloat16) { return cutlass_gemm_sm90_int8_dispatch<int8_t, cutlass::bfloat16_t, Epilogue>( out, a, b, std::forward<EpilogueArgs>(epilogue_args)...); } else { TORCH_CHECK(out.dtype() == torch::kFloat16); return cutlass_gemm_sm90_int8_dispatch<int8_t, cutlass::half_t, Epilogue>( out, a, b, std::forward<EpilogueArgs>(epilogue_args)...); }}
} // namespace vllm12345678910111213141516171819202122232425262728293031323334#include <cudaTypedefs.h>#include "c3x/scaled_mm_kernels.hpp"
#include "cuda_utils.h"
/* This file defines quantized GEMM operations using the CUTLASS 3.x API, for NVIDIA GPUs with sm100 (Blackwell).*/
#if defined CUDA_VERSION && CUDA_VERSION >= 12800
void cutlass_scaled_mm_sm100(torch::Tensor& c, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias) { TORCH_CHECK(a_scales.dtype() == torch::kFloat32); TORCH_CHECK(b_scales.dtype() == torch::kFloat32);
int M = a.size(0), N = b.size(1), K = a.size(1); TORCH_CHECK( (a_scales.numel() == 1 || a_scales.numel() == a.size(0)) && (b_scales.numel() == 1 || b_scales.numel() == b.size(1)), "Currently, block scaled fp8 gemm is not implemented for Blackwell");
// Standard per-tensor/per-token/per-channel scaling TORCH_CHECK(a_scales.is_contiguous() && b_scales.is_contiguous()); TORCH_CHECK(a.dtype() == torch::kFloat8_e4m3fn, "Currently, only fp8 gemm is implemented for Blackwell"); vllm::cutlass_scaled_mm_sm100_fp8(c, a, b, a_scales, b_scales, bias);}
#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#include <cudaTypedefs.h>#include "c3x/scaled_mm_kernels.hpp"
#include "cuda_utils.h"
/* This file defines quantized GEMM operations using the CUTLASS 3.x API, for NVIDIA GPUs with sm90a (Hopper).*/
#if defined CUDA_VERSION && CUDA_VERSION >= 12000
void cutlass_scaled_mm_sm90(torch::Tensor& c, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, std::optional<torch::Tensor> const& bias) { TORCH_CHECK(a_scales.dtype() == torch::kFloat32); TORCH_CHECK(b_scales.dtype() == torch::kFloat32);
int M = a.size(0), N = b.size(1), K = a.size(1);
if ((a_scales.numel() == 1 || a_scales.numel() == a.size(0)) && (b_scales.numel() == 1 || b_scales.numel() == b.size(1))) { // Standard per-tensor/per-token/per-channel scaling TORCH_CHECK(a_scales.is_contiguous() && b_scales.is_contiguous()); if (a.dtype() == torch::kFloat8_e4m3fn) { vllm::cutlass_scaled_mm_sm90_fp8(c, a, b, a_scales, b_scales, bias); } else { TORCH_CHECK(a.dtype() == torch::kInt8); vllm::cutlass_scaled_mm_sm90_int8(c, a, b, a_scales, b_scales, bias); } } else { using GroupShape = std::array<int64_t, 2>; auto make_group_shape = [](torch::Tensor const& x, torch::Tensor const& s) -> GroupShape { TORCH_CHECK(s.dim() == 2, "cutlass_scaled_mm group scales must be 2D"); return {cuda_utils::ceil_div(x.size(0), s.size(0)), cuda_utils::ceil_div(x.size(1), s.size(1))}; };
GroupShape a_scale_group_shape = make_group_shape(a, a_scales); GroupShape b_scale_group_shape = make_group_shape(b, b_scales);
// 1x128 per-token group scales for activations // 128x128 blockwise scales for weights TORCH_CHECK((a_scale_group_shape == GroupShape{1, 128} && b_scale_group_shape == GroupShape{128, 128} && a.dtype() == torch::kFloat8_e4m3fn && b.dtype() == torch::kFloat8_e4m3fn), "cutlass_scaled_mm only supports datatype float8_e4m3fn.\n" "a_scale_group_shape must be [1, 128]. Got: [", a_scale_group_shape[0], ", ", a_scale_group_shape[1], "]\n" "b_scale_group_shape must be [128, 128]. Got: [", b_scale_group_shape[0], ", ", b_scale_group_shape[1], "]"); TORCH_CHECK(!bias, "Bias not yet supported blockwise scaled_mm");
vllm::cutlass_scaled_mm_blockwise_sm90_fp8(c, a, b, a_scales, b_scales); }}
void cutlass_scaled_mm_azp_sm90(torch::Tensor& out, torch::Tensor const& a, torch::Tensor const& b, torch::Tensor const& a_scales, torch::Tensor const& b_scales, torch::Tensor const& azp_adj, std::optional<torch::Tensor> const& azp, std::optional<torch::Tensor> const& bias) { TORCH_CHECK(a_scales.dtype() == torch::kFloat32); TORCH_CHECK(b_scales.dtype() == torch::kFloat32);
vllm::cutlass_scaled_mm_azp_sm90_int8(out, a, b, a_scales, b_scales, azp_adj, azp, bias);}
#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869from abc import ABC, abstractmethodfrom functools import lru_cachefrom typing import NamedTuple
import torch
IS_ROCM = torch.version.hip is not None
class DeviceCapability(NamedTuple): major: int minor: int
def as_version_str(self) -> str: return f"{self.major}.{self.minor}"
def to_int(self) -> int: """ Express device capability as an integer ``<major><minor>``.
It is assumed that the minor version is always a single digit. """ assert 0 <= self.minor < 10 return self.major * 10 + self.minor
class Platform(ABC): simple_compile_backend: str = "inductor"
@classmethod @abstractmethod def get_device_name(cls, device_id: int = 0) -> str: ...
@abstractmethod def is_rocm(self): ...
class CudaPlatform(Platform): @classmethod def get_device_capability(cls, device_id: int = 0) -> DeviceCapability: major, minor = torch.cuda.get_device_capability(device_id) return DeviceCapability(major=major, minor=minor)
@classmethod @lru_cache(maxsize=8) def get_device_name(cls, device_id: int = 0) -> str: return torch.cuda.get_device_name(0)
def is_rocm(self): return False
class RocmPlatform(Platform): @classmethod @lru_cache(maxsize=8) def get_device_capability(cls, device_id: int = 0) -> DeviceCapability: major, minor = torch.cuda.get_device_capability(device_id) return DeviceCapability(major=major, minor=minor)
@classmethod @lru_cache(maxsize=8) def get_device_name(cls, device_id: int = 0) -> str: return torch.cuda.get_device_name(device_id)
def is_rocm(self): return True
current_platform = RocmPlatform() if IS_ROCM else CudaPlatform()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#pragma once
/** * Quantization utilities including: * Adjusted maximum values for qtypes. * Minimum scaling factors for qtypes. */
#include <cmath>#include <torch/types.h>
#ifndef USE_ROCM #include <c10/util/Float8_e4m3fn.h> #define MAYBE_HOST_DEVICE C10_HOST_DEVICE#else #include <ATen/hip/HIPContext.h> #include <c10/util/Float8_e4m3fn.h> #include <c10/util/Float8_e4m3fnuz.h> // ROCm doesn't seem to need C10_HOST_DEVICE for static constexpr #define MAYBE_HOST_DEVICE#endif
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::Float8_e4m3fn> || std::is_same_v<T, c10::Float8_e4m3fnuz> || std::is_same_v<T, int8_t>>>struct quant_type_max { static constexpr T val() { return std::numeric_limits<T>::max(); }};
// Using the default max value from pytorch (240.0 0x7F) will cause accuracy// issues when running dynamic quantization. Here use 224.0 0x7E for rocm.template <>struct quant_type_max<c10::Float8_e4m3fnuz> { static constexpr c10::Float8_e4m3fnuz val() { return c10::Float8_e4m3fnuz(0x7E, c10::Float8_e4m3fnuz::from_bits()); }};
template <typename T>MAYBE_HOST_DEVICE static constexpr T quant_type_max_v = quant_type_max<T>::val();
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::Float8_e4m3fn> || std::is_same_v<T, c10::Float8_e4m3fnuz> || std::is_same_v<T, int8_t>>>struct min_scaling_factor { C10_DEVICE C10_ALWAYS_INLINE static float val() { return 1.0f / (quant_type_max_v<T> * 512.0f); }};
template <>struct min_scaling_factor<int8_t> { C10_DEVICE C10_ALWAYS_INLINE static float val() { return std::numeric_limits<float>::epsilon(); }};cuda_utils.hAdded+41
cutlass_extensions/epilogue/broadcast_load_epilogue_array_c3x.hppAdded+457
cutlass_extensions/gemm/collective/collective_builder.hppAdded+123
cutlass_extensions/gemm/collective/fp8_accumulation.hppAdded+183
cutlass_extensions/gemm/collective/sm90_mma_tma_gmma_ss_warpspecialized_fp8_blockwise_scaling.hppAdded+730
cutlass_extensions/gemm/dispatch_policy.hppAdded+39
cutlass_w8a8/c3x/cutlass_gemm_caller.cuhAdded+107
cutlass_w8a8/c3x/scaled_mm.cuhAdded+147
cutlass_w8a8/c3x/scaled_mm_azp_sm90_int8.cuAdded+24
cutlass_w8a8/c3x/scaled_mm_blockwise_sm90_fp8.cuAdded+24
cutlass_w8a8/c3x/scaled_mm_blockwise_sm90_fp8_dispatch.cuhAdded+194
cutlass_w8a8/c3x/scaled_mm_kernels.hppAdded+39
cutlass_w8a8/c3x/scaled_mm_sm100_fp8.cuAdded+24
cutlass_w8a8/c3x/scaled_mm_sm100_fp8_dispatch.cuhAdded+67
cutlass_w8a8/c3x/scaled_mm_sm90_fp8.cuAdded+24
cutlass_w8a8/c3x/scaled_mm_sm90_fp8_dispatch.cuhAdded+120
cutlass_w8a8/c3x/scaled_mm_sm90_int8.cuAdded+24
cutlass_w8a8/c3x/scaled_mm_sm90_int8_dispatch.cuhAdded+163
cutlass_w8a8/scaled_mm_c3x_sm100.cuAdded+34
cutlass_w8a8/scaled_mm_c3x_sm90.cuAdded+77
torch-ext/quantization/platforms.pyAdded+69
utils.cuhAdded+59