//===----------------------------------------------------------------------===// // // Part of the DirectXShaderCompiler, under the Apache License v2.0 with LLVM // Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // DirectX Shader Model 6.10 Linear Algebra objects and APIs. //===----------------------------------------------------------------------===// #ifndef _HLSL_DX_LINALG_H_ #define _HLSL_DX_LINALG_H_ #include #include #if ((__SHADER_TARGET_MAJOR > 6) || \ (__SHADER_TARGET_MAJOR == 6 && __SHADER_TARGET_MINOR >= 10)) && \ (__HLSL_VERSION >= 2021) #pragma dxc diagnostic push #pragma dxc diagnostic ignored "-Whlsl-groupshared-202x" namespace dxil { // This enum must _exactly_ match the DXIL constants. enum class ComponentType : uint32_t { Invalid = 0, I1 = 1, I16 = 2, U16 = 3, I32 = 4, U32 = 5, I64 = 6, U64 = 7, F16 = 8, F32 = 9, F64 = 10, SNormF16 = 11, UNormF16 = 12, SNormF32 = 13, UNormF32 = 14, SNormF64 = 15, UNormF64 = 16, PackedS8x32 = 17, PackedU8x32 = 18, // BEGIN NEW FOR SM 6.9 I8 = 19, U8 = 20, F8_E4M3FN = 21, F8_E5M2 = 22, // END // BEGIN NEW FOR SM 6.10 BFloat16 = 23, // END LastEntry }; } // namespace dxil namespace dx { namespace linalg { #define __COMPONENT_TYPE(type) type = (uint)dxil::ComponentType::type // This enum only defines values that are valid for Matrix component types. // Each enumeration's value matches the cooresponding DXIL constant. struct ComponentType { enum ComponentEnum { // Signed integers. __COMPONENT_TYPE(I8), __COMPONENT_TYPE(I16), __COMPONENT_TYPE(I32), __COMPONENT_TYPE(I64), // Unsigned integers. __COMPONENT_TYPE(U8), __COMPONENT_TYPE(U16), __COMPONENT_TYPE(U32), __COMPONENT_TYPE(U64), // Floating point types. __COMPONENT_TYPE(F8_E4M3FN), __COMPONENT_TYPE(F8_E5M2), __COMPONENT_TYPE(F16), __COMPONENT_TYPE(F32), __COMPONENT_TYPE(F64), __COMPONENT_TYPE(BFloat16), }; }; #undef __COMPONENT_TYPE using ComponentEnum = ComponentType::ComponentEnum; struct MatrixUse { enum MatrixUseEnum { A = 0, B = 1, Accumulator = 2, }; }; using MatrixUseEnum = MatrixUse::MatrixUseEnum; struct MatrixScope { enum MatrixScopeEnum { Thread = 0, Wave = 1, ThreadGroup = 2, }; }; using MatrixScopeEnum = MatrixScope::MatrixScopeEnum; struct MatrixLayout { enum MatrixLayoutEnum { RowMajor = 0, ColMajor = 1, MulOptimal = 2, MulOptimalTranspose = 3, OuterProductOptimal = 4, OuterProductOptimalTranspose = 5, }; }; using MatrixLayoutEnum = MatrixLayout::MatrixLayoutEnum; namespace __detail { template struct ComponentTypeTraits { using Type = uint; static const bool IsNativeScalar = false; static const uint ElementsPerScalar = 4; }; template struct TypeTraits { static const ComponentEnum CompType = (ComponentEnum)dxil::ComponentType::Invalid; }; template struct IsComponentTypeAvailable { static const bool value = true; }; #if !__HLSL_ENABLE_16_BIT template <> struct IsComponentTypeAvailable { static const bool value = false; }; template <> struct IsComponentTypeAvailable { static const bool value = false; }; template <> struct IsComponentTypeAvailable { static const bool value = false; }; #endif template struct IsCompatibleVectorElement { static const bool IsPackedCarrier = hlsl::is_same::value || hlsl::is_same::value; static const bool value = IsComponentTypeAvailable::value && (hlsl::is_same::Type>::value || (!ComponentTypeTraits::IsNativeScalar && IsPackedCarrier)); }; template <> struct ComponentTypeTraits { using Type = uint; static const bool IsNativeScalar = false; static const uint ElementsPerScalar = 2; }; #define __MATRIX_SCALAR_COMPONENT_MAPPING(enum_val, type) \ template <> struct ComponentTypeTraits { \ using Type = type; \ static const bool IsNativeScalar = true; \ static const uint ElementsPerScalar = 1; \ }; \ template <> struct TypeTraits { \ static const ComponentEnum CompType = enum_val; \ }; #if __HLSL_ENABLE_16_BIT __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I16, int16_t) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U16, uint16_t) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F16, float16_t) #endif __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I32, int32_t) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U32, uint32_t) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F32, float) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::I64, int64_t) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::U64, uint64_t) __MATRIX_SCALAR_COMPONENT_MAPPING(ComponentType::F64, double) template struct DstN { // Make sure to round up in case SrcN isn't an even multiple of the number of // elements per scalar static const int Value = (SrcN * ComponentTypeTraits::ElementsPerScalar + ComponentTypeTraits::ElementsPerScalar - 1) / ComponentTypeTraits::ElementsPerScalar; }; template struct DimMN { static const SIZE_TYPE M = MVal; static const SIZE_TYPE N = NVal; }; template struct DimMN { static const SIZE_TYPE M = NVal; static const SIZE_TYPE N = MVal; }; template struct ScalarCountFromPackedComponents { static const SIZE_TYPE ElementsPerScalar = ComponentTypeTraits::ElementsPerScalar; static const SIZE_TYPE Value = (PackedComponentCount + ElementsPerScalar - 1) / ElementsPerScalar; }; template struct DefaultAlign { enum { MinDim = M < N ? M : N, ScalarCount = ScalarCountFromPackedComponents::Value, ByteAlign = ScalarCount * 4, MinByteAlign = ByteAlign < 4 ? 4 : ByteAlign, Value = MinByteAlign < 16 ? MinByteAlign : 16 }; }; } // namespace __detail template struct VectorRef { ByteAddressBuffer Buf; uint Offset; }; template struct InterpretedVector { vector Data; static const ComponentEnum Interpretation = CT; static const SIZE_TYPE Size = __detail::ComponentTypeTraits::ElementsPerScalar * N; }; template typename hlsl::enable_if< __detail::IsCompatibleVectorElement::value, InterpretedVector >::type MakeInterpretedVector(vector Vec) { InterpretedVector IV = {Vec}; return IV; } template typename hlsl::enable_if< DestCT != OriginCT && __detail::IsComponentTypeAvailable::value && __detail::IsCompatibleVectorElement::value, InterpretedVector::Type, __detail::DstN::Value, DestCT> >::type Convert(vector Vec) { vector::Type, __detail::DstN::Value> Result; dx::__builtin_LinAlg_Convert(Result, Vec, OriginCT, DestCT); return MakeInterpretedVector(Result); } template typename hlsl::enable_if< DestCT == OriginCT && __detail::IsCompatibleVectorElement::value, InterpretedVector >::type Convert(vector Vec) { return MakeInterpretedVector(Vec); } template class Matrix { using ElementType = typename __detail::ComponentTypeTraits::Type; // If this isn't a native scalar, we have a type that may pack more than 1 // element in each scalar value. (Ex. 8bit => 4elems, 16bit => 2elems) static const uint ElementsPerScalar = __detail::ComponentTypeTraits::ElementsPerScalar; static const bool IsNativeScalar = __detail::ComponentTypeTraits::IsNativeScalar; using HandleT = __builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(CT, M, N, Use, Scope)]]; HandleT __handle; template [[nodiscard]] Matrix::M, __detail::DimMN::N, NewUse, Scope> Cast() { Matrix::M, __detail::DimMN::N, NewUse, Scope> Result; dx::__builtin_LinAlg_CopyConvertMatrix(Result.__handle, __handle, Transpose); return Result; } template [[nodiscard]] static typename hlsl::enable_if::value, Matrix>::type Splat(Ty Val) { Matrix Result; dx::__builtin_LinAlg_FillMatrix(Result.__handle, hlsl::is_signed::value, Val); return Result; } template ::Value> [[nodiscard]] static Matrix Load(ByteAddressBuffer Res, uint StartOffset, uint Stride, MatrixLayoutEnum Layout) { Matrix Result; dx::__builtin_LinAlg_MatrixLoadFromDescriptor( Result.__handle, Res, StartOffset, Stride, Layout, Align); return Result; } template ::Value> [[nodiscard]] static Matrix Load(RWByteAddressBuffer Res, uint StartOffset, uint Stride, MatrixLayoutEnum Layout) { Matrix Result; dx::__builtin_LinAlg_MatrixLoadFromDescriptor( Result.__handle, Res, StartOffset, Stride, Layout, Align); return Result; } template [[nodiscard]] static typename hlsl::enable_if< (hlsl::is_same::type, ElementType>::value || hlsl::is_integral_or_packed_integral< typename hlsl::strip_vector_type::type>::value), Matrix>::type Load(groupshared Ty Arr[Size], uint StartIdx, uint Stride, MatrixLayoutEnum Layout) { Matrix Result; dx::__builtin_LinAlg_MatrixLoadFromMemory(Result.__handle, Arr, StartIdx, Stride, Layout); return Result; } template typename hlsl::enable_if::type Length() { return dx::__builtin_LinAlg_MatrixLength(__handle); } template typename hlsl::enable_if::type GetCoordinate(uint Index) { return dx::__builtin_LinAlg_MatrixGetCoordinate(__handle, Index); } template typename hlsl::enable_if::type Get(uint Index) { ElementType Result; dx::__builtin_LinAlg_MatrixGetElement(Result, __handle, Index); return Result; } template typename hlsl::enable_if::type Set(uint Index, ElementType Value) { dx::__builtin_LinAlg_MatrixSetElement(__handle, __handle, Index, Value); } template ::Value> void Store(RWByteAddressBuffer Res, uint StartOffset, uint Stride, MatrixLayoutEnum Layout) { dx::__builtin_LinAlg_MatrixStoreToDescriptor(__handle, Res, StartOffset, Stride, Layout, Align); } template typename hlsl::enable_if< (hlsl::is_same::type, ElementType>::value || hlsl::is_integral_or_packed_integral< typename hlsl::strip_vector_type::type>::value), void>::type Store(groupshared Ty Arr[Size], uint StartIdx, uint Stride, MatrixLayoutEnum Layout) { dx::__builtin_LinAlg_MatrixStoreToMemory(__handle, Arr, StartIdx, Stride, Layout); } // Accumulate methods template ::Value, MatrixUseEnum UseLocal = Use> typename hlsl::enable_if::type InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset, uint Stride, MatrixLayoutEnum Layout) { dx::__builtin_LinAlg_MatrixAccumulateToDescriptor( __handle, Res, StartOffset, Stride, Layout, Align); } template typename hlsl::enable_if< hlsl::is_same::type, ElementType>::value && hlsl::is_arithmetic_vector::value && Use == MatrixUse::Accumulator && UseLocal == Use, void>::type InterlockedAccumulate(groupshared Ty Arr[Size], uint StartIdx, uint Stride, MatrixLayoutEnum Layout) { dx::__builtin_LinAlg_MatrixAccumulateToMemory(__handle, Arr, StartIdx, Stride, Layout); } template typename hlsl::enable_if< hlsl::is_same::type, uint8_t4_packed>::value && Use == MatrixUse::Accumulator && UseLocal == Use, void>::type InterlockedAccumulate(groupshared Ty Arr[Size], uint StartIdx, uint Stride, MatrixLayoutEnum Layout) { dx::__builtin_LinAlg_MatrixAccumulateToMemory(__handle, Arr, StartIdx, Stride, Layout); } template typename hlsl::enable_if::type Accumulate(const Matrix MatrixA) { dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixA.__handle); } template typename hlsl::enable_if::type Accumulate(const Matrix MatrixB) { dx::__builtin_LinAlg_MatrixAccumulate(__handle, __handle, MatrixB.__handle); } template typename hlsl::enable_if::type MultiplyAccumulate(const Matrix MatrixA, const Matrix MatrixB) { dx::__builtin_LinAlg_MatrixMatrixMultiplyAccumulate( __handle, MatrixA.__handle, MatrixB.__handle, __handle); } }; // Thread-scope Matrices are read-only. Using a template partial // specialization for this simplifies the SFINAE-foo above. template class Matrix { using ElementType = typename __detail::ComponentTypeTraits::Type; using HandleT = __builtin_LinAlgMatrix [[__LinAlgMatrix_Attributes(CT, M, N, Use, MatrixScope::Thread)]]; HandleT __handle; template [[nodiscard]] static typename hlsl::enable_if::type Load(ByteAddressBuffer Res, uint StartOffset, uint Stride) { Matrix Result; dx::__builtin_LinAlg_MatrixLoadFromDescriptor( Result.__handle, Res, StartOffset, Stride, Layout, Align); return Result; } template typename hlsl::enable_if::type InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset) { dx::__builtin_LinAlg_MatrixAccumulateToDescriptor( __handle, Res, StartOffset, 0, MatrixLayout::OuterProductOptimal, Align); } }; MatrixUseEnum AccumulatorLayout() { return (MatrixUseEnum)(dx::__builtin_LinAlg_MatrixQueryAccumulatorLayout()); } template [[nodiscard]] Matrix Multiply(const Matrix MatrixA, const Matrix MatrixB) { Matrix Result; dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, MatrixB.__handle); return Result; } template [[nodiscard]] Matrix Multiply(const Matrix MatrixA, const Matrix MatrixB) { Matrix Result; dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, MatrixB.__handle); return Result; } template [[nodiscard]] Matrix Multiply( const Matrix MatrixA, const Matrix MatrixB) { Matrix Result; dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, MatrixB.__handle); return Result; } template [[nodiscard]] Matrix Multiply( const Matrix MatrixA, const Matrix MatrixB) { Matrix Result; dx::__builtin_LinAlg_MatrixMatrixMultiply(Result.__handle, MatrixA.__handle, MatrixB.__handle); return Result; } // Cooperative Vector Replacement API // Cooperative Vector operates on per-thread vectors multiplying against B // matrices with thread scope. template typename hlsl::enable_if::value, vector >::type Multiply(Matrix MatrixA, vector Vec) { vector Result; dx::__builtin_LinAlg_MatrixVectorMultiply( Result, MatrixA.__handle, hlsl::is_signed::value, Vec, __detail::TypeTraits::CompType); return Result; } template typename hlsl::enable_if< InterpretedVector::Size == K && __detail::IsCompatibleVectorElement::value, vector >::type Multiply(Matrix MatrixA, InterpretedVector InterpVec) { vector Result; dx::__builtin_LinAlg_MatrixVectorMultiply( Result, MatrixA.__handle, hlsl::is_signed::value, InterpVec.Data, InterpVec.Interpretation); return Result; } template typename hlsl::enable_if::value && hlsl::is_arithmetic::value, vector >::type MultiplyAdd(Matrix MatrixA, vector Vec, vector Bias) { InterpretedVector::CompType> BiasConvInterp = Convert<__detail::TypeTraits::CompType, __detail::TypeTraits::CompType>(Bias); vector Result; dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( Result, MatrixA.__handle, hlsl::is_signed::value, Vec, __detail::TypeTraits::CompType, BiasConvInterp.Data); return Result; } template typename hlsl::enable_if< VecK == __detail::ScalarCountFromPackedComponents::Value && __detail::IsCompatibleVectorElement::value && hlsl::is_arithmetic::value, vector >::type MultiplyAdd(Matrix MatrixA, InterpretedVector InterpVec, vector Bias) { InterpretedVector::CompType> BiasConvInterp = Convert<__detail::TypeTraits::CompType, __detail::TypeTraits::CompType>(Bias); vector Result; dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( Result, MatrixA.__handle, hlsl::is_signed::value, InterpVec.Data, InterpVec.Interpretation, BiasConvInterp.Data); return Result; } template typename hlsl::enable_if::value, vector >::type MultiplyAdd(Matrix MatrixA, vector Vec, VectorRef BiasRef) { using BiasVecTy = vector::Type, __detail::ScalarCountFromPackedComponents::Value>; BiasVecTy Bias = BiasRef.Buf.template Load(BiasRef.Offset); // Convert currently does not support packed type vector sizes that // are not a multiple of the number of elements per scalar, so we // need to do an extra conversion here to get it into the right shape. // For example, if BiasRef is F8_E4M3FN and M is 7, it gets loaded into // vector, and if OutputTy is half, Convert will return // vector instead of vector. // https://github.com/microsoft/DirectXShaderCompiler/issues/8418 // // Convert to OutputTy vector with padding using BiasConvInterpPaddedTy = InterpretedVector< OutputTy, __detail::DstN< __detail::TypeTraits::CompType, BiasCT, __detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value, __detail::TypeTraits::CompType>; BiasConvInterpPaddedTy BiasConvInterpPadded = Convert<__detail::TypeTraits::CompType, BiasCT>(Bias); // Truncate the vector to the correct size M vector BiasConv = (vector)BiasConvInterpPadded.Data; vector Result; dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( Result, MatrixA.__handle, hlsl::is_signed::value, Vec, __detail::TypeTraits::CompType, BiasConv); return Result; } template typename hlsl::enable_if< VecK == __detail::ScalarCountFromPackedComponents::Value && __detail::IsCompatibleVectorElement::value, vector >::type MultiplyAdd(Matrix MatrixA, InterpretedVector InterpVec, VectorRef BiasRef) { using BiasVecTy = vector::Type, __detail::ScalarCountFromPackedComponents::Value>; BiasVecTy Bias = BiasRef.Buf.template Load(BiasRef.Offset); // Convert currently does not support packed type vector sizes that // are not a multiple of the number of elements per scalar, so we // need to do an extra conversion here to get it into the right shape. // For example, if BiasRef is F8_E4M3FN and M is 7, it gets loaded into // vector, and if OutputTy is half, Convert will return // vector instead of vector. // https://github.com/microsoft/DirectXShaderCompiler/issues/8418 // // Convert to OutputTy vector with padding using BiasConvInterpPaddedTy = InterpretedVector< OutputTy, __detail::DstN< __detail::TypeTraits::CompType, BiasCT, __detail::ScalarCountFromPackedComponents< BiasCT, M>::Value>::Value, __detail::TypeTraits::CompType>; BiasConvInterpPaddedTy BiasConvInterpPadded = Convert<__detail::TypeTraits::CompType, BiasCT>(Bias); // Truncate the vector to the correct size M vector BiasConv = (vector)BiasConvInterpPadded.Data; vector Result; dx::__builtin_LinAlg_MatrixVectorMultiplyAdd( Result, MatrixA.__handle, hlsl::is_signed::value, InterpVec.Data, InterpVec.Interpretation, BiasConv); return Result; } // Outer product functions template [[nodiscard]] typename hlsl::enable_if< hlsl::is_arithmetic::value, Matrix >::type OuterProduct(vector VecA, vector VecB) { Matrix Result; dx::__builtin_LinAlg_MatrixOuterProduct( Result.__handle, hlsl::is_signed::value, VecA, VecB); return Result; } template typename hlsl::enable_if::value, void>::type InterlockedAccumulate(RWByteAddressBuffer Res, uint StartOffset, vector Vec) { dx::__builtin_LinAlg_VectorAccumulateToDescriptor(Res, StartOffset, Align, Vec); } } // namespace linalg } // namespace dx #pragma dxc diagnostic pop #endif // SM 6.10 check and HV version check #endif // _HLSL_DX_LINALG_H_