A high-performance inference engine for AI models
reorganize code
Eugene Bokhan666f1be8b641
diff --git a/Cargo.toml b/Cargo.tomlindex 78ce593fb..46dccc8f4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -5,7 +5,7 @@ resolver = "3"[workspace.package]version = "0.1.7"edition = "2024"-rust-version = "1.91"+rust-version = "1.92"license = "MIT"authors = ["Mirai Tech <https://trymirai.com>"]repository = "https://github.com/trymirai/uzu"diff --git a/crates/uzu/build.rs b/crates/uzu/build.rsindex bd74cd71e..dd4c7d1e3 100644--- a/crates/uzu/build.rs+++ b/crates/uzu/build.rs@@ -40,7 +40,7 @@ fn generate_metal_bindings() {// Only generate types we care about.allowlist_type("GEMMParams").allowlist_type("GEMMAddMMParams")- .allowlist_type("SplitKGEMMParams")+ .allowlist_type("GEMMSpiltKParams")// Use core types.use_core().generate()@@ -82,6 +82,13 @@ fn compile_metal_shaders() {println!("cargo:info=Compiling Metal shaders for SDK: {}", sdk);+ // Re-run build script if the host OS version changes (affects Metal feature availability)+ if cfg!(target_os = "macos") {+ println!(+ "cargo:rerun-if-changed=/System/Library/CoreServices/SystemVersion.plist"+ );+ }+// Gather all .metal files in the project (src directory and subdirs)let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());let src_dir = manifest_dir.join("src");@@ -118,25 +125,59 @@ fn compile_metal_shaders() {let metallib_path =metallib_dir.join(format!("shaders_{}.metallib", platform_suffix));+ let nax_enabled = should_enable_nax(&target_os, sdk);+ if nax_enabled {+ println!("cargo:info=Metal NAX kernels enabled (Metal 4, OS 26+)");+ } else {+ println!("cargo:info=Metal NAX kernels disabled");+ }++ let metal_files_to_compile: Vec<PathBuf> = if nax_enabled {+ metal_files.clone()+ } else {+ metal_files.iter().filter(|p| !is_nax_kernel(p)).cloned().collect()+ };+// Decide whether to compile (if metallib missing or any source changed)- let should_compile =- needs_compilation(&metal_files, &metallib_path, &target);+ let should_compile = needs_compilation(+ &metal_files_to_compile,+ &metallib_path,+ &target,+ nax_enabled,+ );if should_compile {- compile_metal_files(&metal_files, &metallib_dir, sdk, &src_dir);+ compile_metal_files(+ &metal_files_to_compile,+ &metallib_dir,+ sdk,+ &src_dir,+ nax_enabled,+ );// Record the target triple for which we built the metalliblet _ = fs::write(metallib_path.with_extension("target"), &target);+ // Record whether we built with NAX kernels enabled+ let _ = fs::write(+ metallib_path.with_extension("nax"),+ if nax_enabled {+ "1"+ } else {+ "0"+ },+ );} else {println!("cargo:info=Metal shaders are up-to-date; skipping compilation");}- // Read the (new or existing) metallib bytes- let metallib_data = fs::read(&metallib_path)- .or_else(|_| fs::read(metallib_dir.join("shaders.metallib")))- .expect("Failed to read metallib data");- // Write bytes into a Rust source file as a static array- write_metallib_as_bytes(&metallib_data, &out_dir.join("metal_lib.rs"));+ if !metallib_path.exists() {+ panic!("Metal library not found at {}", metallib_path.display());+ }++ // Generate a tiny Rust source file that uses include_bytes! to embed the+ // compiled metallib. This avoids generating a massive Rust file containing+ // a hex-encoded byte array (which is slow to write/compile).+ write_metallib_include(platform_suffix, &out_dir.join("metal_lib.rs"));// Tell Cargo when to re-run this build script: all shader files, plus build.rs and any FFI headerslet mut sorted_files: Vec<&PathBuf> = metal_files.iter().collect();@@ -147,6 +188,43 @@ fn compile_metal_shaders() {println!("cargo:rerun-if-changed=build.rs");}+fn is_nax_kernel(path: &Path) -> bool {+ path.file_name()+ .and_then(|s| s.to_str())+ .map(|s| s.contains("_nax"))+ .unwrap_or(false)+}++const NAX_MIN_OS_MAJOR: u32 = 26;++fn host_macos_major_version() -> Option<u32> {+ if !cfg!(target_os = "macos") {+ return None;+ }+ let output =+ Command::new("sw_vers").arg("-productVersion").output().ok()?;+ if !output.status.success() {+ return None;+ }+ let version = String::from_utf8_lossy(&output.stdout);+ let major = version.trim().split('.').next()?.parse::<u32>().ok()?;+ Some(major)+}++fn should_enable_nax(+ target_os: &str,+ sdk: &str,+) -> bool {+ if target_os != "macos" && target_os != "ios" {+ return false;+ }+ // Conservative: don't enable NAX for simulator builds+ if sdk == "iphonesimulator" {+ return false;+ }+ host_macos_major_version().is_some_and(|major| major >= NAX_MIN_OS_MAJOR)+}+// Recursively find all .metal files in the given directoryfn find_metal_files(dir: &Path) -> Vec<PathBuf> {let mut files = Vec::new();@@ -169,6 +247,7 @@ fn needs_compilation(metal_files: &[PathBuf],metallib_path: &Path,target: &str,+ nax_enabled: bool,) -> bool {// If output metallib doesn't exist, need to compileif !metallib_path.exists() {@@ -186,6 +265,22 @@ fn needs_compilation(return true;}}+ // If the previous NAX mode differs, force a rebuild (affects metallib compatibility)+ let desired_nax = if nax_enabled {+ "1"+ } else {+ "0"+ };+ match fs::read_to_string(metallib_path.with_extension("nax")) {+ Ok(prev_nax) if prev_nax.trim() == desired_nax => {},+ _ => {+ println!(+ "cargo:warning=Metal NAX mode changed; recompiling shaders (nax={})",+ desired_nax+ );+ return true;+ },+ }// If any source file is newer than the metallib, recompilelet metallib_mtime = fs::metadata(metallib_path).and_then(|m| m.modified())@@ -210,6 +305,7 @@ fn compile_metal_files(out_dir: &Path,sdk: &str,src_dir: &Path,+ nax_enabled: bool,) {// Create temp directory for .air fileslet air_dir = out_dir.join("air");@@ -218,9 +314,52 @@ fn compile_metal_files(// Collect include directories (parents of each metal file + src dir)let mut include_dirs = HashSet::new();include_dirs.insert(src_dir.to_path_buf());++ // Add kernel root and common/matmul subdirectories to satisfy kernel includes+ let kernel_dir = src_dir.join("backends/metal/kernel");+ if kernel_dir.exists() {+ include_dirs.insert(kernel_dir.clone());+ let common_dir = kernel_dir.join("common");+ if common_dir.exists() {+ include_dirs.insert(common_dir);+ }++ let matmul_dir = kernel_dir.join("matmul");+ if matmul_dir.exists() {+ include_dirs.insert(matmul_dir.clone());++ let gemv_dir = matmul_dir.join("gemv");+ if gemv_dir.exists() {+ include_dirs.insert(gemv_dir);+ }++ let steel_dir = matmul_dir.join("steel");+ if steel_dir.exists() {+ include_dirs.insert(steel_dir.clone());++ let steel_gemm_dir = steel_dir.join("gemm");+ if steel_gemm_dir.exists() {+ include_dirs.insert(steel_gemm_dir.clone());+ let steel_gemm_kernels_dir = steel_gemm_dir.join("kernels");+ if steel_gemm_kernels_dir.exists() {+ include_dirs.insert(steel_gemm_kernels_dir);+ }+ }++ let steel_utils_dir = steel_dir.join("utils");+ if steel_utils_dir.exists() {+ include_dirs.insert(steel_utils_dir);+ }+ }+ }+ }+for metal_file in metal_files {if let Some(parent) = metal_file.parent() {include_dirs.insert(parent.to_path_buf());+ if let Some(grand) = parent.parent() {+ include_dirs.insert(grand.to_path_buf());+ }}}@@ -232,8 +371,22 @@ fn compile_metal_files(_ => "-O2", // treat levels 2,3,s,z as O2 for metal};- // Platform-specific min version flags (Metal 3.1 requires macOS 14 / iOS 17)- let platform_flags = if sdk == "macosx" || sdk == "maccatalyst" {+ let metal_std = if nax_enabled {+ "metal4.0"+ } else {+ "metal3.1"+ };++ // Platform-specific min version flags.+ // - Metal 3.1 requires macOS 14 / iOS 17+ // - NAX kernels require macOS/iOS 26+ (Metal 4)+ let platform_flags = if nax_enabled {+ if sdk == "macosx" || sdk == "maccatalyst" {+ vec!["-mmacosx-version-min=26.0"]+ } else {+ vec!["-mios-version-min=26.0"]+ }+ } else if sdk == "macosx" || sdk == "maccatalyst" {vec!["-mmacosx-version-min=14.0"]} else {vec!["-mios-version-min=17.0"]@@ -255,7 +408,7 @@ fn compile_metal_files(// Invoke Metal compilerlet mut cmd = Command::new("xcrun");cmd.args(&["-sdk", sdk, "metal", metal_opt_flag]);- cmd.arg(format!("-std={}", "metal3.1")); // target Metal 3.1 shading language+ cmd.arg(format!("-std={}", metal_std));for flag in &platform_flags {cmd.arg(flag);}@@ -325,21 +478,19 @@ fn compile_metal_files();}-fn write_metallib_as_bytes(- metallib_data: &[u8],+fn write_metallib_include(+ platform_suffix: &str,out_path: &Path,) {let mut f = fs::File::create(out_path).expect("Cannot create metal_lib.rs");- writeln!(f, "// AUTO-GENERATED Metal library byte array").unwrap();- writeln!(f, "pub const METAL_LIBRARY_DATA: &[u8] = &[").unwrap();- for chunk in metallib_data.chunks(16) {- write!(f, " ").unwrap();- for byte in chunk {- write!(f, "0x{:02x}, ", byte).unwrap();- }- writeln!(f).unwrap();- }- writeln!(f, "];").unwrap();+ let metallib_file_name = format!("shaders_{}.metallib", platform_suffix);+ writeln!(f, "// AUTO-GENERATED Metal library include").unwrap();+ writeln!(+ f,+ "pub const METAL_LIBRARY_DATA: &[u8] = include_bytes!(concat!(env!(\"OUT_DIR\"), \"/metallib/{}\"));",+ metallib_file_name+ )+ .unwrap();}fn write_empty_metallib() {diff --git a/crates/uzu/src/backends/metal/kernel/common/bf16.h b/crates/uzu/src/backends/metal/kernel/common/bf16.hnew file mode 100644index 000000000..1fafab2b1--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/common/bf16.h@@ -0,0 +1,14 @@+#pragma once++#include <metal_stdlib>++using namespace metal;++typedef bfloat bfloat16_t;+inline uint16_t bfloat16_to_uint16(const bfloat16_t x) {+ return as_type<uint16_t>(x);+}++inline bfloat16_t uint16_to_bfloat16(const uint16_t x) {+ return as_type<bfloat16_t>(x);+}diff --git a/crates/uzu/src/backends/metal/kernel/common/bf16_math.h b/crates/uzu/src/backends/metal/kernel/common/bf16_math.hnew file mode 100644index 000000000..23e3291c3--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/common/bf16_math.h@@ -0,0 +1,378 @@+#pragma once++///////////////////////////////////////////////////////////////////////////////+// Metal math for bfloat16+///////////////////////////////////////////////////////////////////////////////++/*++Following the Metal Shading Language Specification (Metal 3.1)++"bfloat is an extended itypeing point type that only allows implicit conversion+ to a type of greater itypeing point rank. While bfloat can be implicitly+ converted to itype, it cannot be implicitly converted to half, and neither+ itype nor half can be implicitly converted to bfloat."++Further, as far as I can tell, the stdlib math/simd functions are not defined+for bfloat and calling with an argument of type bfloat will result in that+argument getting implicitly converted to itype which then returns an output+that is (likely) a itype which cannot be implicitly converted into a bfloat++This leads to situations where+bfloat a = 5.0bf;+bfloat b = metal::abs(a); // this will throw an error since abs return itype+bfloat c = static_cast<bfloat>(metal::abs(a)); // this is fine++For the moment, I will be adding overloaded instantiations of the math+functions to accordingly automatically handle the casting++*/++#define instantiate_metal_math_funcs(itype, otype, ctype, mfast) \+ \+ METAL_FUNC otype abs(itype x) { \+ return static_cast<otype>(__metal_fabs(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype acos(itype x) { \+ return static_cast<otype>(__metal_acos(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype acosh(itype x) { \+ return static_cast<otype>(__metal_acosh(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype asin(itype x) { \+ return static_cast<otype>(__metal_asin(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype asinh(itype x) { \+ return static_cast<otype>(__metal_asinh(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype atan(itype y_over_x) { \+ return static_cast<otype>( \+ __metal_atan(static_cast<ctype>(y_over_x), mfast)); \+ } \+ METAL_FUNC otype atan2(itype y, itype x) { \+ return static_cast<otype>( \+ __metal_atan2(static_cast<ctype>(y), static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype atanh(itype x) { \+ return static_cast<otype>(__metal_atanh(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype ceil(itype x) { \+ return static_cast<otype>(__metal_ceil(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype cos(itype x) { \+ return static_cast<otype>(__metal_cos(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype cosh(itype x) { \+ return static_cast<otype>(__metal_cosh(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype cospi(itype x) { \+ return static_cast<otype>(__metal_cospi(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype divide(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_divide(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype exp(itype x) { \+ return static_cast<otype>(__metal_exp(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype exp10(itype x) { \+ return static_cast<otype>(__metal_exp10(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype exp2(itype x) { \+ return static_cast<otype>(__metal_exp2(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype fabs(itype x) { \+ return static_cast<otype>(__metal_fabs(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype fdim(itype x, itype y) { \+ ctype t = static_cast<ctype>(x - y); \+ return static_cast<otype>(select(t, ctype(0), t < ctype(0) || x == y)); \+ } \+ METAL_FUNC otype floor(itype x) { \+ return static_cast<otype>(__metal_floor(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype fma(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fma( \+ static_cast<ctype>(x), static_cast<ctype>(y), static_cast<ctype>(z))); \+ } \+ METAL_FUNC otype fmax(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_fmax(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype fmax3(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fmax3( \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z), \+ mfast)); \+ } \+ METAL_FUNC otype fmedian3(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fmedian3( \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z), \+ mfast)); \+ } \+ METAL_FUNC otype fmin(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_fmin(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype fmin3(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fmin3( \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z), \+ mfast)); \+ } \+ METAL_FUNC otype fmod(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_fmod(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype fract(itype x) { \+ return static_cast<otype>(__metal_fract(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype frexp(itype x, thread int& exp) { \+ return static_cast<otype>(__metal_frexp(static_cast<ctype>(x), &exp)); \+ } \+ METAL_FUNC otype ldexp(itype x, int k) { \+ return static_cast<otype>(__metal_ldexp(static_cast<ctype>(x), k, mfast)); \+ } \+ METAL_FUNC otype log(itype x) { \+ return static_cast<otype>(__metal_log(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype log10(itype x) { \+ return static_cast<otype>(__metal_log10(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype log2(itype x) { \+ return static_cast<otype>(__metal_log2(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype max(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_fmax(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype max3(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fmax3( \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z), \+ mfast)); \+ } \+ METAL_FUNC otype median3(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fmedian3( \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z), \+ mfast)); \+ } \+ METAL_FUNC otype min(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_fmin(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype min3(itype x, itype y, itype z) { \+ return static_cast<otype>(__metal_fmin3( \+ static_cast<ctype>(x), \+ static_cast<ctype>(y), \+ static_cast<ctype>(z), \+ mfast)); \+ } \+ METAL_FUNC otype nextafter(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_nextafter(static_cast<ctype>(x), static_cast<ctype>(y))); \+ } \+ METAL_FUNC otype pow(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_pow(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype powr(itype x, itype y) { \+ return static_cast<otype>( \+ __metal_powr(static_cast<ctype>(x), static_cast<ctype>(y), mfast)); \+ } \+ METAL_FUNC otype rint(itype x) { \+ return static_cast<otype>(__metal_rint(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype round(itype x) { \+ return static_cast<otype>(__metal_round(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype rsqrt(itype x) { \+ return static_cast<otype>(__metal_rsqrt(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype sin(itype x) { \+ return static_cast<otype>(__metal_sin(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype sinh(itype x) { \+ return static_cast<otype>(__metal_sinh(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype sinpi(itype x) { \+ return static_cast<otype>(__metal_sinpi(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype sqrt(itype x) { \+ return static_cast<otype>(__metal_sqrt(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype tan(itype x) { \+ return static_cast<otype>(__metal_tan(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype tanh(itype x) { \+ return static_cast<otype>(__metal_tanh(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype tanpi(itype x) { \+ return static_cast<otype>(__metal_tanpi(static_cast<ctype>(x), mfast)); \+ } \+ METAL_FUNC otype trunc(itype x) { \+ return static_cast<otype>(__metal_trunc(static_cast<ctype>(x), mfast)); \+ }++namespace metal {++instantiate_metal_math_funcs(+ bfloat16_t,+ bfloat16_t,+ float,+ __METAL_MAYBE_FAST_MATH__);++namespace fast {++instantiate_metal_math_funcs(+ bfloat16_t,+ bfloat16_t,+ float,+ __METAL_FAST_MATH__);++} // namespace fast++namespace precise {++instantiate_metal_math_funcs(+ bfloat16_t,+ bfloat16_t,+ float,+ __METAL_PRECISE_MATH__);++} // namespace precise++} // namespace metal++///////////////////////////////////////////////////////////////////////////////+// Metal simd for bfloat16+///////////////////////////////////////////////////////////////////////////////++#define instantiate_metal_simd_comm_funcs( \+ itype, otype, ctype, itype_to_ctype, ctype_to_otype) \+ \+ METAL_FUNC otype simd_broadcast(itype data, ushort broadcast_lane_id) { \+ return ctype_to_otype( \+ __metal_simd_broadcast(itype_to_ctype(data), broadcast_lane_id)); \+ } \+ \+ METAL_FUNC otype simd_shuffle(itype data, ushort simd_lane_id) { \+ return ctype_to_otype( \+ __metal_simd_shuffle(itype_to_ctype(data), simd_lane_id)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_and_fill_down( \+ itype data, itype filling_data, ushort delta, ushort modulo) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \+ itype_to_ctype(data), itype_to_ctype(filling_data), delta, modulo)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_and_fill_down( \+ itype data, itype filling_data, ushort delta) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_down( \+ itype_to_ctype(data), \+ itype_to_ctype(filling_data), \+ delta, \+ __metal_get_simdgroup_size(ushort()))); \+ } \+ \+ METAL_FUNC otype simd_shuffle_and_fill_up( \+ itype data, itype filling_data, ushort delta, ushort modulo) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \+ itype_to_ctype(data), itype_to_ctype(filling_data), delta, modulo)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_and_fill_up( \+ itype data, itype filling_data, ushort delta) { \+ return ctype_to_otype(__metal_simd_shuffle_and_fill_up( \+ itype_to_ctype(data), \+ itype_to_ctype(filling_data), \+ delta, \+ __metal_get_simdgroup_size(ushort()))); \+ } \+ \+ METAL_FUNC otype simd_shuffle_down(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_down(itype_to_ctype(data), delta)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_rotate_down(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_rotate_down(itype_to_ctype(data), delta)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_rotate_up(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_rotate_up(itype_to_ctype(data), delta)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_up(itype data, ushort delta) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_up(itype_to_ctype(data), delta)); \+ } \+ \+ METAL_FUNC otype simd_shuffle_xor(itype data, ushort mask) { \+ return ctype_to_otype( \+ __metal_simd_shuffle_xor(itype_to_ctype(data), mask)); \+ }++#define instantiate_metal_simd_reduction_funcs(itype, otype, ctype) \+ \+ METAL_FUNC otype simd_max(itype data) { \+ return static_cast<otype>(__metal_simd_max(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_min(itype data) { \+ return static_cast<otype>(__metal_simd_min(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_prefix_exclusive_product(itype data) { \+ return static_cast<otype>( \+ __metal_simd_prefix_exclusive_product(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_prefix_exclusive_sum(itype data) { \+ return static_cast<otype>( \+ __metal_simd_prefix_exclusive_sum(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_prefix_inclusive_product(itype data) { \+ return static_cast<otype>( \+ __metal_simd_prefix_inclusive_product(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_prefix_inclusive_sum(itype data) { \+ return static_cast<otype>( \+ __metal_simd_prefix_inclusive_sum(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_product(itype data) { \+ return static_cast<otype>(__metal_simd_product(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_sum(itype data) { \+ return static_cast<otype>(__metal_simd_sum(static_cast<ctype>(data))); \+ } \+ \+ METAL_FUNC otype simd_xor(itype data) { \+ return static_cast<otype>(__metal_simd_xor(static_cast<ctype>(data))); \+ }++namespace metal {++instantiate_metal_simd_comm_funcs(+ bfloat16_t,+ bfloat16_t,+ uint16_t,+ bfloat16_to_uint16,+ uint16_to_bfloat16);+instantiate_metal_simd_reduction_funcs(bfloat16_t, bfloat16_t, float);++} // namespace metaldiff --git a/crates/uzu/src/backends/metal/kernel/common/complex.h b/crates/uzu/src/backends/metal/kernel/common/complex.hnew file mode 100644index 000000000..858ecd9e0--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/common/complex.h@@ -0,0 +1,171 @@+#pragma once++#include <metal_stdlib>++using namespace metal;++struct complex64_t;++template <typename T>+static constexpr constant bool can_convert_to_complex64 =+ !is_same_v<T, complex64_t> && is_convertible_v<T, float>;++template <typename T>+static constexpr constant bool can_convert_from_complex64 =+ !is_same_v<T, complex64_t> &&+ (is_convertible_v<float, T> || is_convertible_v<bfloat16_t, T>);++struct complex64_t {+ float real;+ float imag;++ // Constructors+ constexpr complex64_t(float real, float imag) : real(real), imag(imag) {};+ constexpr complex64_t() : real(0), imag(0) {};+ constexpr complex64_t() threadgroup : real(0), imag(0) {};++ // Conversions to complex64_t+ template <+ typename T,+ typename = typename enable_if<can_convert_to_complex64<T>>::type>+ constexpr complex64_t(T x) thread : real(x), imag(0) {}++ template <+ typename T,+ typename = typename enable_if<can_convert_to_complex64<T>>::type>+ constexpr complex64_t(T x) threadgroup : real(x), imag(0) {}++ template <+ typename T,+ typename = typename enable_if<can_convert_to_complex64<T>>::type>+ constexpr complex64_t(T x) device : real(x), imag(0) {}++ template <+ typename T,+ typename = typename enable_if<can_convert_to_complex64<T>>::type>+ constexpr complex64_t(T x) constant : real(x), imag(0) {}++ // Conversions from complex64_t+ template <+ typename T,+ typename = typename enable_if<can_convert_from_complex64<T>>::type>+ constexpr operator T() const thread {+ return static_cast<T>(real);+ }++ template <+ typename T,+ typename = typename enable_if<can_convert_from_complex64<T>>::type>+ constexpr operator T() const threadgroup {+ return static_cast<T>(real);+ }++ template <+ typename T,+ typename = typename enable_if<can_convert_from_complex64<T>>::type>+ constexpr operator T() const device {+ return static_cast<T>(real);+ }++ template <+ typename T,+ typename = typename enable_if<can_convert_from_complex64<T>>::type>+ constexpr operator T() const constant {+ return static_cast<T>(real);+ }+};++constexpr complex64_t operator-(complex64_t x) {+ return {-x.real, -x.imag};+}++constexpr bool operator>=(complex64_t a, complex64_t b) {+ return (a.real > b.real) || (a.real == b.real && a.imag >= b.imag);+}++constexpr bool operator>(complex64_t a, complex64_t b) {+ return (a.real > b.real) || (a.real == b.real && a.imag > b.imag);+}++constexpr bool operator<=(complex64_t a, complex64_t b) {+ return operator>=(b, a);+}++constexpr bool operator<(complex64_t a, complex64_t b) {+ return operator>(b, a);+}++constexpr bool operator==(complex64_t a, complex64_t b) {+ return a.real == b.real && a.imag == b.imag;+}++constexpr complex64_t operator+(complex64_t a, complex64_t b) {+ return {a.real + b.real, a.imag + b.imag};+}++constexpr thread complex64_t& operator+=(thread complex64_t& a, complex64_t b) {+ a.real += b.real;+ a.imag += b.imag;+ return a;+}++constexpr threadgroup complex64_t& operator+=(+ threadgroup complex64_t& a,+ complex64_t b) {+ a.real += b.real;+ a.imag += b.imag;+ return a;+}++constexpr device complex64_t& operator+=(device complex64_t& a, complex64_t b) {+ a.real += b.real;+ a.imag += b.imag;+ return a;+}++constexpr complex64_t operator+(float a, complex64_t b) {+ return {a + b.real, b.imag};+}+constexpr complex64_t operator+(complex64_t a, float b) {+ return {a.real + b, a.imag};+}++constexpr complex64_t operator-(complex64_t a, complex64_t b) {+ return {a.real - b.real, a.imag - b.imag};+}+constexpr complex64_t operator-(float a, complex64_t b) {+ return {a - b.real, -b.imag};+}+constexpr complex64_t operator-(complex64_t a, float b) {+ return {a.real - b, a.imag};+}++constexpr complex64_t operator*(complex64_t a, complex64_t b) {+ return {a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real};+}++constexpr complex64_t operator/(complex64_t a, complex64_t b) {+ auto denom = b.real * b.real + b.imag * b.imag;+ auto x = a.real * b.real + a.imag * b.imag;+ auto y = a.imag * b.real - a.real * b.imag;+ return {x / denom, y / denom};+}++constexpr complex64_t operator/(float a, complex64_t b) {+ auto denom = b.real * b.real + b.imag * b.imag;+ auto x = a * b.real;+ auto y = -a * b.imag;+ return {x / denom, y / denom};+}++constexpr complex64_t operator%(complex64_t a, complex64_t b) {+ auto real = a.real - (b.real * static_cast<int64_t>(a.real / b.real));+ auto imag = a.imag - (b.imag * static_cast<int64_t>(a.imag / b.imag));+ if (real != 0 && (real < 0 != b.real < 0)) {+ real += b.real;+ }+ if (imag != 0 && (imag < 0 != b.imag < 0)) {+ imag += b.imag;+ }+ return {real, imag};+}diff --git a/crates/uzu/src/backends/metal/kernel/common/defines.h b/crates/uzu/src/backends/metal/kernel/common/defines.hnew file mode 100644index 000000000..e77c28855--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/common/defines.h@@ -0,0 +1,22 @@+#pragma once++#if defined __METAL__+#define MTL_CONST constant+#else+#define MTL_CONST+#endif++static MTL_CONST constexpr int MAX_REDUCE_SPECIALIZED_DIMS = 4;+static MTL_CONST constexpr int REDUCE_N_READS = 4;+static MTL_CONST constexpr int REDUCE_N_WRITES = 4;+static MTL_CONST constexpr int SOFTMAX_N_READS = 4;+static MTL_CONST constexpr int RMS_N_READS = 4;+static MTL_CONST constexpr int RMS_LOOPED_LIMIT = 4096;++// Instantiate a templated kernel.+// Extra args are used as template parameters:+// e.g. instantiate_kernel(binary_int, binary, a, b) ->+// [[host_name(binary_int)]] [kernel] binary<a, b>+#define instantiate_kernel(name, func, ...) \+ template [[host_name( \+ name)]] [[kernel]] decltype(func<__VA_ARGS__>) func<__VA_ARGS__>;diff --git a/crates/uzu/src/backends/metal/kernel/common/logging.h b/crates/uzu/src/backends/metal/kernel/common/logging.hnew file mode 100644index 000000000..4d06cd85a--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/common/logging.h@@ -0,0 +1,20 @@+#pragma once++#if defined(__METAL_VERSION__) && (__METAL_VERSION__ >= 320)+#include <metal_logging>++using os_log = metal::os_log;++#else++struct os_log {+ constexpr os_log(constant char*, constant char*) constant {}++ template <typename... Args>+ void log_debug(constant char*, Args...) const {}++ template <typename... Args>+ void log_debug(constant char*, Args...) const constant {}+};++#endif\ No newline at end of filediff --git a/crates/uzu/src/backends/metal/kernel/common/utils.h b/crates/uzu/src/backends/metal/kernel/common/utils.hnew file mode 100644index 000000000..05ff74458--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/common/utils.h@@ -0,0 +1,442 @@+#pragma once++#include <metal_math>++#include "bf16.h"+#include "bf16_math.h"+#include "complex.h"+#include "defines.h"+#include "logging.h"++typedef half float16_t;++// Work per thread values for different types.+template <typename U>+struct WorkPerThread {+ static_assert(sizeof(U) <= 8, "Type too large");+ static constexpr int constant n = 8 / sizeof(U);+};++///////////////////////////////////////////////////////////////////////////////+// Type limits utils+///////////////////////////////////////////////////////////////////////////////++template <typename U>+struct Limits {+ static const constant U max = metal::numeric_limits<U>::max();+ static const constant U min = metal::numeric_limits<U>::min();+ static const constant U finite_max = metal::numeric_limits<U>::max();+ static const constant U finite_min = metal::numeric_limits<U>::min();+};++#define instantiate_default_limit(type) \+ template <> \+ struct Limits<type> { \+ static constexpr constant type max = metal::numeric_limits<type>::max(); \+ static constexpr constant type min = metal::numeric_limits<type>::min(); \+ static constexpr constant type finite_max = \+ metal::numeric_limits<type>::max(); \+ static constexpr constant type finite_min = \+ metal::numeric_limits<type>::min(); \+ };++instantiate_default_limit(uint8_t);+instantiate_default_limit(uint16_t);+instantiate_default_limit(uint32_t);+instantiate_default_limit(uint64_t);+instantiate_default_limit(int8_t);+instantiate_default_limit(int16_t);+instantiate_default_limit(int32_t);+instantiate_default_limit(int64_t);++#define instantiate_float_limit(type) \+ template <> \+ struct Limits<type> { \+ static constexpr constant type max = \+ metal::numeric_limits<type>::infinity(); \+ static constexpr constant type min = \+ -metal::numeric_limits<type>::infinity(); \+ static constexpr constant type finite_max = \+ metal::numeric_limits<type>::max(); \+ static constexpr constant type finite_min = \+ -metal::numeric_limits<type>::max(); \+ };++instantiate_float_limit(half);+instantiate_float_limit(float);+instantiate_float_limit(bfloat16_t);++template <>+struct Limits<bool> {+ static constexpr constant bool max = true;+ static constexpr constant bool min = false;+};++template <>+struct Limits<complex64_t> {+ static constexpr constant complex64_t max = complex64_t(+ metal::numeric_limits<float>::infinity(),+ metal::numeric_limits<float>::infinity());+ static constexpr constant complex64_t min = complex64_t(+ -metal::numeric_limits<float>::infinity(),+ -metal::numeric_limits<float>::infinity());+};++///////////////////////////////////////////////////////////////////////////////+// Indexing utils+///////////////////////////////////////////////////////////////////////////////++#define MTL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)")++///////////////////////////////////////////////////////////////////////////////+// Single Array with generic dims++template <typename IdxT = int64_t>+METAL_FUNC IdxT elem_to_loc(+ IdxT elem,+ constant const int* shape,+ constant const int64_t* strides,+ int ndim) {+ IdxT loc = 0;+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {+ loc += (elem % shape[i]) * IdxT(strides[i]);+ elem /= shape[i];+ }+ return loc;+}++// Non templated version to handle arbitrary dims+template <typename IdxT = int64_t>+METAL_FUNC IdxT elem_to_loc(+ uint3 elem,+ constant const int* shape,+ constant const int64_t* strides,+ int ndim) {+ IdxT loc =+ elem.x * IdxT(strides[ndim - 1]) + elem.y * IdxT(strides[ndim - 2]);+ for (int d = ndim - 3; d >= 0; --d) {+ loc += (elem.z % shape[d]) * IdxT(strides[d]);+ elem.z /= shape[d];+ }+ return loc;+}++///////////////////////////////////////////////////////////////////////////////+// Single Array with fixed N dims++template <typename IdxT = int64_t>+METAL_FUNC IdxT elem_to_loc_1(uint elem, constant const int64_t& stride) {+ return elem * IdxT(stride);+}++template <typename IdxT = int64_t>+METAL_FUNC IdxT elem_to_loc_2(uint2 elem, constant const int64_t strides[2]) {+ return elem.x * IdxT(strides[1]) + elem.y * IdxT(strides[0]);+}++template <typename IdxT = int64_t>+METAL_FUNC IdxT elem_to_loc_3(uint3 elem, constant const int64_t strides[3]) {+ return elem.x * IdxT(strides[2]) + elem.y * IdxT(strides[1]) ++ elem.z * IdxT(strides[0]);+}++///////////////////////////////////////////////////////////////////////////////+// Multiple Arrays with generic dims++template <typename IdxT = int64_t>+METAL_FUNC vec<IdxT, 2> elem_to_loc_2_nd(+ uint3 elem,+ constant const int* shape,+ constant const int64_t* a_strides,+ constant const int64_t* b_strides,+ int ndim) {+ vec<IdxT, 2> loc = {+ IdxT(+ elem.x * IdxT(a_strides[ndim - 1]) ++ IdxT(elem.y) * IdxT(a_strides[ndim - 2])),+ IdxT(+ elem.x * IdxT(b_strides[ndim - 1]) ++ elem.y * IdxT(b_strides[ndim - 2]))};+ for (int d = ndim - 3; d >= 0; --d) {+ uint l = elem.z % shape[d];+ loc.x += l * IdxT(a_strides[d]);+ loc.y += l * IdxT(b_strides[d]);+ elem.z /= shape[d];+ }+ return loc;+}++template <typename IdxT = int64_t>+METAL_FUNC vec<IdxT, 3> elem_to_loc_3_nd(+ uint3 elem,+ constant const int* shape,+ constant const int64_t* a_strides,+ constant const int64_t* b_strides,+ constant const int64_t* c_strides,+ int ndim) {+ vec<IdxT, 3> loc = {+ IdxT(elem.x * IdxT(a_strides[ndim - 1])) ++ IdxT(elem.y * IdxT(a_strides[ndim - 2])),+ IdxT(elem.x * IdxT(b_strides[ndim - 1])) ++ IdxT(elem.y * IdxT(b_strides[ndim - 2])),+ IdxT(elem.x * IdxT(c_strides[ndim - 1])) ++ IdxT(elem.y * IdxT(c_strides[ndim - 2]))};+ for (int d = ndim - 3; d >= 0; --d) {+ uint l = elem.z % shape[d];+ loc.x += l * IdxT(a_strides[d]);+ loc.y += l * IdxT(b_strides[d]);+ loc.z += l * IdxT(c_strides[d]);+ elem.z /= shape[d];+ }+ return loc;+}++///////////////////////////////////////////////////////////////////////////////+// Elem to loc in a loop utils+///////////////////////////////////////////////////////////////////////////////++template <int DIM, typename OffsetT = size_t, bool General = true>+struct LoopedElemToLoc {+ int dim;+ LoopedElemToLoc<DIM - 1, OffsetT, General> inner_looper;+ OffsetT offset{0};+ int index{0};++ LoopedElemToLoc(int dim) : dim(dim), inner_looper(dim - 1) {}++ void next(const constant int* shape, const constant int64_t* strides) {+ if (dim == 0) {+ return;+ }+ index++;+ offset += OffsetT(strides[dim - 1]);+ if (index >= shape[dim - 1]) {+ index = 0;+ inner_looper.next(shape, strides);+ offset = inner_looper.offset;+ }+ }++ void next(int n, const constant int* shape, const constant int64_t* strides) {+ if (dim == 0) {+ return;+ }+ index += n;+ offset += n * OffsetT(strides[dim - 1]);++ if (index >= shape[dim - 1]) {+ int extra = index - shape[dim - 1];+ if (extra >= shape[dim - 1]) {+ inner_looper.next(1 + extra / shape[dim - 1], shape, strides);+ extra = extra % shape[dim - 1];+ } else {+ inner_looper.next(shape, strides);+ }+ index = 0;+ offset = inner_looper.offset;+ if (extra > 0) {+ next(extra, shape, strides);+ }+ }+ }++ OffsetT location() {+ return offset;+ }+};++template <typename OffsetT>+struct LoopedElemToLoc<1, OffsetT, true> {+ int dim;+ OffsetT offset{0};+ uint index{0};++ LoopedElemToLoc(int dim) : dim(dim) {}++ void next(const constant int* shape, const constant int64_t* strides) {+ index++;+ if (dim > 1) {+ offset = elem_to_loc<OffsetT>(index, shape, strides, dim);+ } else {+ offset += OffsetT(strides[0]);+ }+ }++ void next(int n, const constant int* shape, const constant int64_t* strides) {+ index += n;+ if (dim > 1) {+ offset = elem_to_loc<OffsetT>(index, shape, strides, dim);+ } else {+ offset = index * OffsetT(strides[0]);+ }+ }++ OffsetT location() {+ return offset;+ }+};++template <typename OffsetT>+struct LoopedElemToLoc<1, OffsetT, false> {+ OffsetT offset{0};++ LoopedElemToLoc(int) {}++ void next(const constant int*, const constant int64_t* strides) {+ offset += OffsetT(strides[0]);+ }++ void next(int n, const constant int*, const constant int64_t* strides) {+ offset += n * OffsetT(strides[0]);+ }++ OffsetT location() {+ return offset;+ }+};++///////////////////////////////////////////////////////////////////////////////+// Calculation utils+///////////////////////////////////////////////////////////////////////////////++/** Compute ceil((float)N/(float)M) */+template <typename T, typename U>+inline T ceildiv(T N, U M) {+ return (N + M - 1) / M;+}++// https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#1202+inline float log1p(float x) {+ float xp1 = 1.0f + x;+ if (xp1 == Limits<float>::max) {+ return Limits<float>::max;+ }+ if (xp1 == 1.0f) {+ return x;+ }++ return x * (metal::log(xp1) / (xp1 - 1.0f));+}++inline bfloat16_t log1p(bfloat16_t x) {+ float xp1 = 1.0f + static_cast<float>(x);+ if (xp1 == Limits<float>::max) {+ return Limits<bfloat16_t>::max;+ }+ if (xp1 == 1.0f) {+ return x;+ }++ return bfloat16_t(x * (metal::log(xp1) / (xp1 - 1.0f)));+}++inline complex64_t log1p(complex64_t in) {+ float x = in.real;+ float y = in.imag;+ float zabs = metal::precise::sqrt(x * x + y * y);+ float theta = metal::atan2(y, x + 1);+ if (zabs < 0.5f) {+ float r = x * (2 + x) + y * y;+ if (r == 0) { // handle underflow+ return {x, theta};+ }+ return {0.5f * log1p(r), theta};+ } else {+ auto z0 = metal::sqrt((x + 1) * (x + 1) + y * y);+ return {metal::log(z0), theta};+ }+}++///////////////////////////////////////////////////////////////////////////////+// SIMD shuffle ops+///////////////////////////////////////////////////////////////////////////////++inline uint64_t simd_shuffle_down(uint64_t data, uint16_t delta) {+ return as_type<uint64_t>(+ metal::simd_shuffle_down(as_type<uint2>(data), delta));+}++inline int64_t simd_shuffle_down(int64_t data, uint16_t delta) {+ return as_type<int64_t>(+ metal::simd_shuffle_down(as_type<uint2>(data), delta));+}++inline bool simd_shuffle_down(bool data, uint16_t delta) {+ return simd_shuffle_down(static_cast<uint32_t>(data), delta);+}++inline complex64_t simd_shuffle_down(complex64_t data, uint16_t delta) {+ return complex64_t(+ simd_shuffle_down(data.real, delta), simd_shuffle_down(data.imag, delta));+}++inline uint64_t simd_shuffle_up(uint64_t data, uint16_t delta) {+ return as_type<uint64_t>(metal::simd_shuffle_up(as_type<uint2>(data), delta));+}++inline int64_t simd_shuffle_up(int64_t data, uint16_t delta) {+ return as_type<int64_t>(metal::simd_shuffle_up(as_type<uint2>(data), delta));+}++inline bool simd_shuffle_up(bool data, uint16_t delta) {+ return simd_shuffle_up(static_cast<uint32_t>(data), delta);+}++inline complex64_t simd_shuffle_up(complex64_t data, uint16_t delta) {+ return complex64_t(+ simd_shuffle_up(data.real, delta), simd_shuffle_up(data.imag, delta));+}++inline uint64_t+simd_shuffle_and_fill_up(uint64_t data, uint64_t filling, uint16_t delta) {+ return as_type<uint64_t>(metal::simd_shuffle_and_fill_up(+ as_type<uint2>(data), as_type<uint2>(filling), delta));+}++inline int64_t+simd_shuffle_and_fill_up(int64_t data, int64_t filling, uint16_t delta) {+ return as_type<int64_t>(metal::simd_shuffle_and_fill_up(+ as_type<uint2>(data), as_type<uint2>(filling), delta));+}++inline bool simd_shuffle_and_fill_up(bool data, bool filling, uint16_t delta) {+ return simd_shuffle_and_fill_up(+ static_cast<uint32_t>(data), static_cast<uint32_t>(filling), delta);+}++inline complex64_t simd_shuffle_and_fill_up(+ complex64_t data,+ complex64_t filling,+ uint16_t delta) {+ return complex64_t(+ simd_shuffle_and_fill_up(data.real, filling.real, delta),+ simd_shuffle_and_fill_up(data.imag, filling.imag, delta));+}++inline uint64_t simd_shuffle(uint64_t data, uint16_t lane) {+ return as_type<uint64_t>(metal::simd_shuffle(as_type<uint2>(data), lane));+}++inline int64_t simd_shuffle(int64_t data, uint16_t lane) {+ return as_type<int64_t>(metal::simd_shuffle(as_type<uint2>(data), lane));+}++inline bool simd_shuffle(bool data, uint16_t lane) {+ return simd_shuffle(static_cast<uint32_t>(data), lane);+}++inline complex64_t simd_shuffle(complex64_t data, uint16_t lane) {+ return complex64_t(+ simd_shuffle(data.real, lane), simd_shuffle(data.imag, lane));+}++// std::conditional is not included with Metal+template <bool condition, typename T, typename U>+struct ConditionalType {+ using type = U;+};++template <typename T, typename U>+struct ConditionalType<true, T, U> {+ using type = T;+};diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gather.rs b/crates/uzu/src/backends/metal/kernel/matmul/gather.rsnew file mode 100644index 000000000..3f94225bd--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/gather.rs@@ -0,0 +1,586 @@+use std::collections::HashMap;++use metal::{+ Buffer as MTLBuffer, ComputeCommandEncoderRef,+ ComputePipelineState as MTLComputePipelineState, MTLSize,+};++use super::shared_types::GEMMParams;+use crate::{+ DataType,+ backends::metal::{DeviceClass, MTLContext, MTLError},+};++#[derive(Debug, Clone, PartialEq, Eq, Hash)]+struct RhsOnlyPipelineKey {+ name: String,+ align_m: bool,+ align_n: bool,+ align_k: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Hash)]+struct GatherPipelineKey {+ name: String,+ has_batch: bool,+ align_m: bool,+ align_n: bool,+ align_k: bool,+}++#[derive(Debug, Clone)]+pub struct GatherMmRhsArguments<'a> {+ pub a: &'a MTLBuffer,+ pub b: &'a MTLBuffer,+ pub rhs_indices: &'a MTLBuffer,+ pub out: &'a MTLBuffer,+ pub m: i32,+ pub n: i32,+ pub k: i32,+ pub lda: i32,+ pub ldb: i32,+ pub batch_stride_b: i64,+ pub transpose_b: bool,+ /// Number of matrices available on the RHS (E dimension in the reference backend).+ pub rhs_matrix_count: i32,+}++#[derive(Debug, Clone)]+pub struct GatherMmArguments<'a> {+ pub a: &'a MTLBuffer,+ pub b: &'a MTLBuffer,+ pub lhs_indices: &'a MTLBuffer,+ pub rhs_indices: &'a MTLBuffer,+ pub out: &'a MTLBuffer,+ pub m: i32,+ pub n: i32,+ pub k: i32,+ pub lda: i32,+ pub ldb: i32,+ /// Grid Z dimension for the gather kernel (out.size / (M*N) in the reference backend).+ pub batch_size_out: i32,+ /// Number of batch dimensions for the output (out.ndim - 2 in the reference backend).+ pub batch_ndim: i32,++ // LHS/RHS indices layout (used when has_batch=true).+ pub lhs_indices_shape: &'a [i32],+ pub lhs_indices_strides: &'a [i64],+ pub rhs_indices_strides: &'a [i64],++ // A tensor batch layout (for elem_to_loc on selected matrix index).+ pub batch_ndim_a: i32,+ pub a_shape: &'a [i32],+ pub a_strides: &'a [i64],++ // B tensor batch layout (for elem_to_loc on selected matrix index).+ pub batch_ndim_b: i32,+ pub b_shape: &'a [i32],+ pub b_strides: &'a [i64],++ pub transpose_a: bool,+ pub transpose_b: bool,+}++pub struct GatherGemm {+ data_type: DataType,+ rhs_only_pipelines: HashMap<RhsOnlyPipelineKey, MTLComputePipelineState>,+ gather_pipelines: HashMap<GatherPipelineKey, MTLComputePipelineState>,+}++impl GatherGemm {+ pub fn new(data_type: DataType) -> Self {+ Self {+ data_type,+ rhs_only_pipelines: HashMap::new(),+ gather_pipelines: HashMap::new(),+ }+ }++ fn steel_type_name(&self) -> Result<&'static str, MTLError> {+ match self.data_type {+ DataType::F16 => Ok("float16"),+ DataType::BF16 => Ok("bfloat16"),+ DataType::F32 => Ok("float32"),+ other => Err(MTLError::Generic(format!(+ "Unsupported data type for gather GEMM: {other:?}"+ ))),+ }+ }++ fn device_class_code(mtl: &MTLContext) -> char {+ match mtl.architecture.device_class {+ DeviceClass::Desktop => 'd',+ DeviceClass::Integrated => 'g',+ DeviceClass::Phone => 'p',+ DeviceClass::Unknown(_) => 'g',+ }+ }++ fn select_gemm_tparams(+ device_class: char,+ data_type: DataType,+ transpose_a: bool,+ transpose_b: bool,+ m: i32,+ n: i32,+ k: i32,+ batch_size_out: i32,+ ) -> (i32, i32, i32, i32, i32) {+ // Matches the initialization and tparam selection logic used by the+ // reference backend for gather/segmented GEMM kernels.+ let mut bm = 64;+ let mut bn = 64;+ let mut bk = 16;+ let mut wm = 2;+ let mut wn = 2;++ let is_float32 = matches!(data_type, DataType::F32);+ let work_elements = (batch_size_out as i64) * (m as i64) * (n as i64);++ match device_class {+ 'g' | 'p' => {+ if !transpose_a && transpose_b {+ // nt+ bm = 64;+ bn = 32;+ bk = 32;+ wm = 2;+ wn = 2;+ } else if !is_float32 {+ // half and bfloat+ bm = 64;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ }+ },+ 'd' => {+ if work_elements >= (1_i64 << 20) {+ // large matmul+ if !is_float32 {+ if 2 * std::cmp::max(m, n) > k {+ // Reasonable K+ bm = 64;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ } else if !transpose_a && transpose_b {+ // nt with large k+ bm = 64;+ bn = 32;+ bk = 32;+ wm = 2;+ wn = 2;+ } else {+ // nn with large K+ bm = 32;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ }+ }+ } else if !is_float32 {+ // smaller matmul, half and bfloat+ if !transpose_a && transpose_b {+ // nt+ bm = 64;+ bn = 32;+ bk = 32;+ wm = 2;+ wn = 2;+ } else {+ // nn+ bm = 64;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ }+ }+ },+ _ => {},+ }++ (bm, bn, bk, wm, wn)+ }++ fn gather_kernel_name(+ &self,+ prefix: &str,+ transpose_a: bool,+ transpose_b: bool,+ bm: i32,+ bn: i32,+ bk: i32,+ wm: i32,+ wn: i32,+ ) -> Result<String, MTLError> {+ let tname = format!(+ "{}{}",+ if transpose_a {+ 't'+ } else {+ 'n'+ },+ if transpose_b {+ 't'+ } else {+ 'n'+ }+ );+ let dtype = self.steel_type_name()?;+ Ok(format!(+ "{prefix}_{tname}_{dtype}_{dtype}_bm{bm}_bn{bn}_bk{bk}_wm{wm}_wn{wn}",+ ))+ }++ fn set_i32_slice_bytes(+ enc: &ComputeCommandEncoderRef,+ index: u64,+ data: &[i32],+ ) {+ if data.is_empty() {+ let zero = 0_i32;+ enc.set_bytes(+ index,+ std::mem::size_of::<i32>() as u64,+ &zero as *const i32 as *const _,+ );+ } else {+ enc.set_bytes(+ index,+ (data.len() * std::mem::size_of::<i32>()) as u64,+ data.as_ptr() as *const _,+ );+ }+ }++ fn set_i64_slice_bytes(+ enc: &ComputeCommandEncoderRef,+ index: u64,+ data: &[i64],+ ) {+ if data.is_empty() {+ let zero = 0_i64;+ enc.set_bytes(+ index,+ std::mem::size_of::<i64>() as u64,+ &zero as *const i64 as *const _,+ );+ } else {+ enc.set_bytes(+ index,+ (data.len() * std::mem::size_of::<i64>()) as u64,+ data.as_ptr() as *const _,+ );+ }+ }++ fn get_or_compile_rhs_only_pipeline(+ &mut self,+ mtl: &MTLContext,+ name: &str,+ align_m: bool,+ align_n: bool,+ align_k: bool,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ let key = RhsOnlyPipelineKey {+ name: name.to_string(),+ align_m,+ align_n,+ align_k,+ };++ if !self.rhs_only_pipelines.contains_key(&key) {+ let fcv = metal::FunctionConstantValues::new();+ fcv.set_constant_value_at_index(+ &align_m as *const bool as *const _,+ metal::MTLDataType::Bool,+ 200,+ );+ fcv.set_constant_value_at_index(+ &align_n as *const bool as *const _,+ metal::MTLDataType::Bool,+ 201,+ );+ fcv.set_constant_value_at_index(+ &align_k as *const bool as *const _,+ metal::MTLDataType::Bool,+ 202,+ );++ let cache_key = format!(+ "{name}_am{}_an{}_ak{}",+ align_m as u8, align_n as u8, align_k as u8+ );+ let (ps, _) = mtl.compute_pipeline_state_with_reflection_cached(+ &cache_key,+ name,+ Some(&fcv),+ )?;+ self.rhs_only_pipelines.insert(key.clone(), ps);+ }++ Ok(self.rhs_only_pipelines.get(&key).unwrap())+ }++ fn get_or_compile_gather_pipeline(+ &mut self,+ mtl: &MTLContext,+ name: &str,+ has_batch: bool,+ align_m: bool,+ align_n: bool,+ align_k: bool,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ let key = GatherPipelineKey {+ name: name.to_string(),+ has_batch,+ align_m,+ align_n,+ align_k,+ };++ if !self.gather_pipelines.contains_key(&key) {+ let fcv = metal::FunctionConstantValues::new();+ fcv.set_constant_value_at_index(+ &has_batch as *const bool as *const _,+ metal::MTLDataType::Bool,+ 10,+ );+ fcv.set_constant_value_at_index(+ &align_m as *const bool as *const _,+ metal::MTLDataType::Bool,+ 200,+ );+ fcv.set_constant_value_at_index(+ &align_n as *const bool as *const _,+ metal::MTLDataType::Bool,+ 201,+ );+ fcv.set_constant_value_at_index(+ &align_k as *const bool as *const _,+ metal::MTLDataType::Bool,+ 202,+ );++ let cache_key = format!(+ "{name}_hb{}_am{}_an{}_ak{}",+ has_batch as u8, align_m as u8, align_n as u8, align_k as u8+ );+ let (ps, _) = mtl.compute_pipeline_state_with_reflection_cached(+ &cache_key,+ name,+ Some(&fcv),+ )?;+ self.gather_pipelines.insert(key.clone(), ps);+ }++ Ok(self.gather_pipelines.get(&key).unwrap())+ }++ pub fn encode_mm_rhs(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: &GatherMmRhsArguments,+ ) -> Result<(), MTLError> {+ // NAX gather kernels are only instantiated for float16/bfloat16.+ let prefer_nax =+ mtl.is_nax_available() && !matches!(self.data_type, DataType::F32);++ let (bm, bn, bk, wm, wn, use_nax) = if prefer_nax {+ // Mirrors rhs-only NAX gather tile selection.+ let e = std::cmp::max(1, args.rhs_matrix_count);+ let ratio = args.m / e;+ let (bm, wm) = if ratio > 48 {+ (64, 2)+ } else if ratio > 24 {+ (32, 1)+ } else {+ (16, 1)+ };+ (bm, 128, 128, wm, 4, true)+ } else {+ (16, 64, 16, 1, 2, false)+ };++ let align_m = (args.m % bm) == 0;+ let align_n = (args.n % bn) == 0;+ let align_k = (args.k % bk) == 0;++ let prefix = if use_nax {+ "steel_gather_mm_rhs_nax"+ } else {+ "steel_gather_mm_rhs"+ };++ // gather_mm_rhs only supports transpose_a=false (nn/nt instantiations).+ let kname = self.gather_kernel_name(+ prefix,+ /*transpose_a=*/ false,+ args.transpose_b,+ bm,+ bn,+ bk,+ wm,+ wn,+ )?;++ let ps = self.get_or_compile_rhs_only_pipeline(+ mtl, &kname, align_m, align_n, align_k,+ )?;++ enc.set_compute_pipeline_state(ps);+ enc.set_buffer(0, Some(args.a), 0);+ enc.set_buffer(1, Some(args.b), 0);+ enc.set_buffer(2, Some(args.rhs_indices), 0);+ enc.set_buffer(3, Some(args.out), 0);++ let tiles_n = (args.n + bn - 1) / bn;+ let tiles_m = (args.m + bm - 1) / bm;+ let params = GEMMParams {+ M: args.m,+ N: args.n,+ K: args.k,+ lda: args.lda,+ ldb: args.ldb,+ ldd: args.n,+ tiles_n,+ tiles_m,+ batch_stride_a: 0,+ batch_stride_b: args.batch_stride_b,+ batch_stride_d: 0,+ swizzle_log: 0,+ gemm_k_iterations_aligned: args.k / bk,+ batch_ndim: 0,+ };+ enc.set_bytes(+ 4,+ std::mem::size_of::<GEMMParams>() as u64,+ ¶ms as *const GEMMParams as *const _,+ );++ let threads_per_tg = MTLSize::new(32, wn as u64, wm as u64);+ let tgs = MTLSize::new(tiles_n as u64, tiles_m as u64, 1);+ enc.dispatch_thread_groups(tgs, threads_per_tg);+ Ok(())+ }++ pub fn encode_mm(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: &GatherMmArguments,+ ) -> Result<(), MTLError> {+ let device_class = Self::device_class_code(mtl);+ let (bm, bn, bk, wm, wn) = Self::select_gemm_tparams(+ device_class,+ self.data_type,+ args.transpose_a,+ args.transpose_b,+ args.m,+ args.n,+ args.k,+ args.batch_size_out,+ );++ let has_batch = args.batch_ndim > 1;+ let align_m = (args.m % bm) == 0;+ let align_n = (args.n % bn) == 0;+ let align_k = (args.k % bk) == 0;++ let kname = self.gather_kernel_name(+ "steel_gather_mm",+ args.transpose_a,+ args.transpose_b,+ bm,+ bn,+ bk,+ wm,+ wn,+ )?;++ let ps = self.get_or_compile_gather_pipeline(+ mtl, &kname, has_batch, align_m, align_n, align_k,+ )?;++ enc.set_compute_pipeline_state(ps);++ enc.set_buffer(0, Some(args.a), 0);+ enc.set_buffer(1, Some(args.b), 0);+ enc.set_buffer(2, Some(args.lhs_indices), 0);+ enc.set_buffer(3, Some(args.rhs_indices), 0);+ enc.set_buffer(4, Some(args.out), 0);++ let tiles_n = (args.n + bn - 1) / bn;+ let tiles_m = (args.m + bm - 1) / bm;+ let batch_stride_a = if args.batch_ndim > 0 {+ *args.lhs_indices_strides.first().unwrap_or(&0)+ } else {+ 0+ };+ let batch_stride_b = if args.batch_ndim > 0 {+ *args.rhs_indices_strides.first().unwrap_or(&0)+ } else {+ 0+ };++ let params = GEMMParams {+ M: args.m,+ N: args.n,+ K: args.k,+ lda: args.lda,+ ldb: args.ldb,+ ldd: args.n,+ tiles_n,+ tiles_m,+ batch_stride_a,+ batch_stride_b,+ batch_stride_d: (args.m as i64) * (args.n as i64),+ swizzle_log: 0,+ gemm_k_iterations_aligned: args.k / bk,+ batch_ndim: args.batch_ndim,+ };++ enc.set_bytes(+ 5,+ std::mem::size_of::<GEMMParams>() as u64,+ ¶ms as *const GEMMParams as *const _,+ );++ // Note: many of these are only used when has_batch=true, but they are+ // present in the kernel signature unconditionally.+ Self::set_i32_slice_bytes(enc, 6, args.lhs_indices_shape);+ Self::set_i64_slice_bytes(enc, 7, args.lhs_indices_strides);+ Self::set_i64_slice_bytes(enc, 8, args.rhs_indices_strides);++ enc.set_bytes(+ 9,+ std::mem::size_of::<i32>() as u64,+ &args.batch_ndim_a as *const i32 as *const _,+ );+ Self::set_i32_slice_bytes(enc, 10, args.a_shape);+ Self::set_i64_slice_bytes(enc, 11, args.a_strides);++ enc.set_bytes(+ 12,+ std::mem::size_of::<i32>() as u64,+ &args.batch_ndim_b as *const i32 as *const _,+ );+ Self::set_i32_slice_bytes(enc, 13, args.b_shape);+ Self::set_i64_slice_bytes(enc, 14, args.b_strides);++ let threads_per_tg = MTLSize::new(32, wn as u64, wm as u64);+ let tgs = MTLSize::new(+ tiles_n as u64,+ tiles_m as u64,+ args.batch_size_out as u64,+ );+ enc.dispatch_thread_groups(tgs, threads_per_tg);+ Ok(())+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv.metaldeleted file mode 100644index 4494ac79c..000000000--- a/crates/uzu/src/backends/metal/kernel/matmul/gemv.metal+++ /dev/null@@ -1,729 +0,0 @@-// SPDX-License-Identifier: MIT--#include <metal_simdgroup>-#include <metal_stdlib>--using namespace metal;--#define UZU_MTL_CONST static constant constexpr const--template <typename T>-struct DefaultAccumulator {- using type = float;-};--template <typename T>-using AccumulatorType = typename DefaultAccumulator<T>::type;--static METAL_FUNC int64_t linear_offset_for_batch(- uint batch_index,- const constant int* batch_shape,- const constant int64_t* batch_strides,- int batch_ndim-) {- if (batch_ndim <= 1) {- return static_cast<int64_t>(batch_index) * batch_strides[0];- }-- int64_t offset = 0;- uint remaining = batch_index;- for (int dim = batch_ndim - 1; dim >= 0; --dim) {- int dim_size = batch_shape[dim];- if (dim_size <= 0) {- continue;- }- uint coord = remaining % static_cast<uint>(dim_size);- remaining /= static_cast<uint>(dim_size);- offset += coord * batch_strides[dim];- }- return offset;-}--///////////////////////////////////////////////////////////////////////////////-/// Matrix vector multiplication-///////////////////////////////////////////////////////////////////////////////--template <- typename T,- const int BM, /* Threadgroup rows (in simdgroups) */- const int BN, /* Threadgroup cols (in simdgroups) */- const int SM, /* Simdgroup rows (in threads) */- const int SN, /* Simdgroup cols (in threads) */- const int TM, /* Thread rows (in elements) */- const int TN, /* Thread cols (in elements) */- const bool kDoAxpby, /* Do out = alpha * out + beta * bias */- typename AccT = AccumulatorType<T>>-struct GEMVKernel {- using acc_type = AccT;-- UZU_MTL_CONST int threadsM = BM * SM;- UZU_MTL_CONST int threadsN = BN * SN;-- UZU_MTL_CONST int blockM = threadsM * TM;- UZU_MTL_CONST int blockN = threadsN * TN;-- static_assert(SM * SN == 32, "simdgroup can only have 32 threads");- static_assert(- SN == 4 || SN == 8 || SN == 16 || SN == 32,- "gemv block must have a width of 4, 8, 16, or 32"- );-- UZU_MTL_CONST short tgp_mem_size = BN > 1 ? BN*(blockM + TM) : 0;- UZU_MTL_CONST bool needs_tgp_reduction = BN > 1;-- template <typename U = T>- static METAL_FUNC void load_unsafe(- const device T* src,- thread U dst[TN],- const int src_offset = 0- ) {-#pragma unroll- for (int tn = 0; tn < TN; tn++) {- dst[tn] = static_cast<U>(src[src_offset + tn]);- }- }-- template <typename U = T>- static METAL_FUNC void load_safe(- const device T* src,- thread U dst[TN],- const int src_offset = 0,- const int src_size = TN- ) {- if (src_offset + TN <= src_size) {-#pragma unroll- for (int tn = 0; tn < TN; tn++) {- dst[tn] = static_cast<U>(src[src_offset + tn]);- }- } else {-#pragma unroll- for (int tn = 0; tn < TN; tn++) {- dst[tn] = (src_offset + tn) < src_size- ? static_cast<U>(src[src_offset + tn])- : U(0);- }- }- }-- static METAL_FUNC void run(- const device T* mat [[buffer(0)]],- const device T* in_vec [[buffer(1)]],- const device T* bias [[buffer(2)]],- device T* out_vec [[buffer(3)]],- const constant int& in_vec_size [[buffer(4)]],- const constant int& out_vec_size [[buffer(5)]],- const constant int& matrix_ld [[buffer(6)]],- const constant float& alpha [[buffer(7)]],- const constant float& beta [[buffer(8)]],- const constant int& bias_stride [[buffer(14)]],- threadgroup AccT* tgp_memory [[threadgroup(0)]],- uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]],- uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]]- ) {- (void)lid;-- thread AccT result[TM] = {0};- thread T inter[TN];- thread AccT v_coeff[TN];-- const int thrM = SN != 32 ? simd_lid / SN : 0;- const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);-- const int sgN = BN != 1 ? (simd_gid % BN) : 0;-- const int simdM = BN != 1 ? SM * (simd_gid / BN) : int(SM * simd_gid);- const int simdN = BN != 1 ? SN * (simd_gid % BN) : 0;-- int bm = (simdM + thrM) * TM;- int bn = (simdN + thrN) * TN;-- int out_row = tid.x * blockM + bm;-- if (out_row >= out_vec_size) {- return;- }-- out_row = (out_row + TM <= out_vec_size) ? out_row : (out_vec_size - TM);-- mat += out_row * matrix_ld;-- constexpr const uniform<int> loop_stride = make_uniform(blockN);- const uniform<int> in_size = make_uniform(in_vec_size);- const uniform<int> n_iter = in_size / loop_stride;- const uniform<int> last_iter = loop_stride * n_iter;- const uniform<int> leftover = in_size - last_iter;-- for (int i = 0; i < n_iter; ++i) {- load_unsafe<AccT>(in_vec, v_coeff, bn);-- int mat_offset = 0;-#pragma unroll- for (int tm = 0; tm < TM; tm++) {- load_unsafe(mat, inter, mat_offset + bn);--#pragma unroll- for (int tn = 0; tn < TN; tn++) {- result[tm] += inter[tn] * v_coeff[tn];- }-- mat_offset += matrix_ld;- }-- bn += blockN;- }-- if (leftover > 0) {- load_safe<AccT>(in_vec, v_coeff, bn, in_size);--#pragma unroll- for (int tm = 0; tm < TM; tm++) {- load_safe(&mat[tm * matrix_ld], inter, bn, in_size);--#pragma unroll- for (int tn = 0; tn < TN; tn++) {- result[tm] += inter[tn] * v_coeff[tn];- }- }- }--#pragma unroll- for (int tm = 0; tm < TM; tm++) {-#pragma unroll- for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {- result[tm] += simd_shuffle_down(result[tm], sn);- }- }-- if (needs_tgp_reduction) {- threadgroup AccT* tgp_results = tgp_memory + sgN * (blockM + TM) + bm;- if (thrN == 0) {-#pragma unroll- for (int tm = 0; tm < TM; tm++) {- tgp_results[tm] = result[tm];- }-- threadgroup_barrier(mem_flags::mem_none);-- if (sgN == 0) {-#pragma unroll- for (int sgn = 1; sgn < BN; sgn++) {-#pragma unroll- for (int tm = 0; tm < TM; tm++) {- result[tm] += tgp_results[sgn * (blockM + TM) + tm];- }- }- }- }- }-- if (simdN == 0 && thrN == 0) {-#pragma unroll- for (int tm = 0; tm < TM; tm++) {- if (kDoAxpby) {- out_vec[out_row + tm] =- static_cast<T>(alpha) * static_cast<T>(result[tm]) +- static_cast<T>(beta) * bias[(out_row + tm) * bias_stride];- } else {- out_vec[out_row + tm] = static_cast<T>(result[tm]);- }- }- }- }-};--///////////////////////////////////////////////////////////////////////////////-/// Vector matrix multiplication (transposed GEMV)-///////////////////////////////////////////////////////////////////////////////--template <- typename T,- const int BM, /* Threadgroup rows (in simdgroups) */- const int BN, /* Threadgroup cols (in simdgroups) */- const int SM, /* Simdgroup rows (in threads) */- const int SN, /* Simdgroup cols (in threads) */- const int TM, /* Thread rows (in elements) */- const int TN, /* Thread cols (in elements) */- const bool kDoAxpby, /* Do out = alpha * out + beta * bias */- typename AccT = AccumulatorType<T>>-struct GEMVTKernel {- using acc_type = AccT;-- UZU_MTL_CONST int threadsM = BM * SM;- UZU_MTL_CONST int threadsN = BN * SN;-- UZU_MTL_CONST int blockM = threadsM * TM;- UZU_MTL_CONST int blockN = threadsN * TN;-- static_assert(SM * SN == 32, "simdgroup can only have 32 threads");-- UZU_MTL_CONST short tgp_mem_size = BM > 1 ? BM*(blockN + TN) : 0;- UZU_MTL_CONST bool needs_tgp_reduction = BM > 1;-- static METAL_FUNC void run(- const device T* mat [[buffer(0)]],- const device T* in_vec [[buffer(1)]],- const device T* bias [[buffer(2)]],- device T* out_vec [[buffer(3)]],- const constant int& in_vec_size [[buffer(4)]],- const constant int& out_vec_size [[buffer(5)]],- const constant int& matrix_ld [[buffer(6)]],- const constant float& alpha [[buffer(7)]],- const constant float& beta [[buffer(8)]],- const constant int& bias_stride [[buffer(14)]],- threadgroup AccT* tgp_memory [[threadgroup(0)]],- uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]],- uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]]- ) {- (void)lid;-- AccT result[TN] = {0};- T inter[TN];- AccT v_coeff[TM];- const int thrM = SN != 32 ? simd_lid / SN : 0;- const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);-- const int sgM = BN != 1 ? (simd_gid / BN) : int(simd_gid);- const int sgN = BN != 1 ? (simd_gid % BN) : 0;-- const int simdM = SM * sgM;- const int simdN = SN * sgN;-- int cm = (simdM + thrM);- int cn = (simdN + thrN);-- int bm = cm * TM;- int bn = cn * TN;-- int out_col = tid.x * blockN + bn;-- constexpr const uniform<int> loop_stride = make_uniform(blockM);- const uniform<int> in_size = make_uniform(in_vec_size);- const uniform<int> n_iter = in_size / loop_stride;- const uniform<int> last_iter = loop_stride * n_iter;- const uniform<int> leftover = in_size - last_iter;-- if (out_col < out_vec_size) {- out_col = (out_col + TN < out_vec_size) ? out_col : (out_vec_size - TN);-- for (int i = 0; i < n_iter; ++i) {- threadgroup_barrier(mem_flags::mem_none);--#pragma unroll- for (int tm = 0; tm < TM; tm++) {- v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);- }--#pragma unroll- for (int tm = 0; tm < TM; tm++) {- auto vc = static_cast<AccT>(v_coeff[tm]);- for (int tn = 0; tn < TN; tn++) {- inter[tn] = mat[(bm + tm) * matrix_ld + out_col + tn];- }- for (int tn = 0; tn < TN; tn++) {- result[tn] += vc * inter[tn];- }- }-- bm += blockM;- }-- if (leftover > 0) {- for (int tm = 0; tm < TM && bm + tm < in_vec_size; tm++) {- v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);--#pragma unroll- for (int tn = 0; tn < TN; tn++) {- inter[tn] = mat[(bm + tm) * matrix_ld + out_col + tn];- }--#pragma unroll- for (int tn = 0; tn < TN; tn++) {- result[tn] += v_coeff[tm] * inter[tn];- }- }- }- }--#pragma unroll- for (int tn = 0; tn < TN; tn++) {-#pragma unroll- for (ushort sm = (SM / 2); sm >= 1; sm >>= 1) {- result[tn] += simd_shuffle_down(result[tn], SN * sm);- }- }-- if (needs_tgp_reduction) {- threadgroup AccT* tgp_results = tgp_memory + sgM * (blockN + TN) + bn;- if (thrM == 0) {-#pragma unroll- for (int tn = 0; tn < TN; tn++) {- tgp_results[tn] = result[tn];- }-- threadgroup_barrier(mem_flags::mem_none);-- if (sgM == 0) {-#pragma unroll- for (int sgm = 1; sgm < BM; sgm++) {-#pragma unroll- for (int tn = 0; tn < TN; tn++) {- result[tn] += tgp_results[sgm * (blockN + TN) + tn];- }- }- }- }- }-- if (cm == 0 && out_col < out_vec_size) {-#pragma unroll- for (int j = 0; j < TN; j++) {- if (kDoAxpby) {- out_vec[out_col + j] =- static_cast<T>(alpha) * static_cast<T>(result[j]) +- static_cast<T>(beta) * bias[(out_col + j) * bias_stride];- } else {- out_vec[out_col + j] = static_cast<T>(result[j]);- }- }- }- }-};--///////////////////////////////////////////////////////////////////////////////-/// Kernel entry points-///////////////////////////////////////////////////////////////////////////////--template <- typename T,- const int BM, /* Threadgroup rows (in simdgroups) */- const int BN, /* Threadgroup cols (in simdgroups) */- const int SM, /* Simdgroup rows (in threads) */- const int SN, /* Simdgroup cols (in threads) */- const int TM, /* Thread rows (in elements) */- const int TN, /* Thread cols (in elements) */- const bool kDoNCBatch, /* Batch ndim > 1 */- const bool kDoAxpby> /* Do out = alpha * out + beta * bias */-METAL_FUNC void gemv_entry(- const device T* mat [[buffer(0)]],- const device T* in_vec [[buffer(1)]],- const device T* bias [[buffer(2)]],- device T* out_vec [[buffer(3)]],- const constant int& in_vec_size [[buffer(4)]],- const constant int& out_vec_size [[buffer(5)]],- const constant int& matrix_ld [[buffer(6)]],- const constant float& alpha [[buffer(7)]],- const constant float& beta [[buffer(8)]],- const constant int& batch_ndim [[buffer(9)]],- const constant int* batch_shape [[buffer(10)]],- const constant int64_t* vector_batch_stride [[buffer(11)]],- const constant int64_t* matrix_batch_stride [[buffer(12)]],- const constant int64_t* bias_batch_stride [[buffer(13)]],- const constant int& bias_stride [[buffer(14)]],- threadgroup- typename GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>::acc_type*- tgp_memory,- uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]],- uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]]-) {- using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;-- if (kDoNCBatch) {- in_vec += linear_offset_for_batch(- tid.z,- batch_shape,- vector_batch_stride,- batch_ndim- );- mat += linear_offset_for_batch(- tid.z,- batch_shape,- matrix_batch_stride,- batch_ndim- );- if (kDoAxpby) {- bias += linear_offset_for_batch(- tid.z,- batch_shape,- bias_batch_stride,- batch_ndim- );- }- } else {- in_vec += tid.z * vector_batch_stride[0];- mat += tid.z * matrix_batch_stride[0];- if (kDoAxpby) {- bias += tid.z * bias_batch_stride[0];- }- }-- out_vec += tid.z * out_vec_size;-- gemv_kernel::run(- mat,- in_vec,- bias,- out_vec,- in_vec_size,- out_vec_size,- matrix_ld,- alpha,- beta,- bias_stride,- tgp_memory,- tid,- lid,- simd_gid,- simd_lid- );-}--template <- typename T,- const int BM, /* Threadgroup rows (in simdgroups) */- const int BN, /* Threadgroup cols (in simdgroups) */- const int SM, /* Simdgroup rows (in threads) */- const int SN, /* Simdgroup cols (in threads) */- const int TM, /* Thread rows (in elements) */- const int TN, /* Thread cols (in elements) */- const bool kDoNCBatch, /* Batch ndim > 1 */- const bool kDoAxpby> /* Do out = alpha * out + beta * bias */-METAL_FUNC void gemv_t_entry(- const device T* mat [[buffer(0)]],- const device T* in_vec [[buffer(1)]],- const device T* bias [[buffer(2)]],- device T* out_vec [[buffer(3)]],- const constant int& in_vec_size [[buffer(4)]],- const constant int& out_vec_size [[buffer(5)]],- const constant int& matrix_ld [[buffer(6)]],- const constant float& alpha [[buffer(7)]],- const constant float& beta [[buffer(8)]],- const constant int& batch_ndim [[buffer(9)]],- const constant int* batch_shape [[buffer(10)]],- const constant int64_t* vector_batch_stride [[buffer(11)]],- const constant int64_t* matrix_batch_stride [[buffer(12)]],- const constant int64_t* bias_batch_stride [[buffer(13)]],- const constant int& bias_stride [[buffer(14)]],- threadgroup- typename GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>::acc_type*- tgp_memory,- uint3 tid [[threadgroup_position_in_grid]],- uint3 lid [[thread_position_in_threadgroup]],- uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]]-) {- using gemv_kernel = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;-- if (kDoNCBatch) {- in_vec += linear_offset_for_batch(- tid.z,- batch_shape,- vector_batch_stride,- batch_ndim- );- mat += linear_offset_for_batch(- tid.z,- batch_shape,- matrix_batch_stride,- batch_ndim- );- if (kDoAxpby) {- bias += linear_offset_for_batch(- tid.z,- batch_shape,- bias_batch_stride,- batch_ndim- );- }- } else {- in_vec += tid.z * vector_batch_stride[0];- mat += tid.z * matrix_batch_stride[0];- if (kDoAxpby) {- bias += tid.z * bias_batch_stride[0];- }- }-- out_vec += tid.z * out_vec_size;-- gemv_kernel::run(- mat,- in_vec,- bias,- out_vec,- in_vec_size,- out_vec_size,- matrix_ld,- alpha,- beta,- bias_stride,- tgp_memory,- tid,- lid,- simd_gid,- simd_lid- );-}--///////////////////////////////////////////////////////////////////////////////-/// Instantiation helpers-///////////////////////////////////////////////////////////////////////////////--#define instantiate_gemv_helper( \- name, \- itype, \- bm, \- bn, \- sm, \- sn, \- tm, \- tn, \- nc, \- axpby \-) \- [[host_name( \- "gemv_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \- "_tn" #tn "_nc" #nc "_axpby" #axpby \- )]] [[kernel, max_total_threads_per_threadgroup(bm * bn * 32)]] \- void \- gemv_inst_##name##_bm##bm##_bn##bn##_sm##sm##_sn##sn##_tm##tm##_tn##tn##_nc##nc##_axpby##axpby( \- const device itype* mat [[buffer(0)]], \- const device itype* in_vec [[buffer(1)]], \- const device itype* bias [[buffer(2)]], \- device itype* out_vec [[buffer(3)]], \- const constant int& in_vec_size [[buffer(4)]], \- const constant int& out_vec_size [[buffer(5)]], \- const constant int& matrix_ld [[buffer(6)]], \- const constant float& alpha [[buffer(7)]], \- const constant float& beta [[buffer(8)]], \- const constant int& batch_ndim [[buffer(9)]], \- const constant int* batch_shape [[buffer(10)]], \- const constant int64_t* vector_batch_stride [[buffer(11)]], \- const constant int64_t* matrix_batch_stride [[buffer(12)]], \- const constant int64_t* bias_batch_stride [[buffer(13)]], \- const constant int& bias_stride [[buffer(14)]], \- uint3 tid [[threadgroup_position_in_grid]], \- uint3 lid [[thread_position_in_threadgroup]], \- uint simd_gid [[simdgroup_index_in_threadgroup]], \- uint simd_lid [[thread_index_in_simdgroup]] \- ) { \- using gemv_kernel = GEMVKernel<itype, bm, bn, sm, sn, tm, tn, axpby>; \- threadgroup typename gemv_kernel::acc_type tgp_memory \- [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size]; \- gemv_entry<itype, bm, bn, sm, sn, tm, tn, nc, axpby>( \- mat, \- in_vec, \- bias, \- out_vec, \- in_vec_size, \- out_vec_size, \- matrix_ld, \- alpha, \- beta, \- batch_ndim, \- batch_shape, \- vector_batch_stride, \- matrix_batch_stride, \- bias_batch_stride, \- bias_stride, \- gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory, \- tid, \- lid, \- simd_gid, \- simd_lid \- ); \- } \- [[host_name( \- "gemv_t_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \- "_tn" #tn "_nc" #nc "_axpby" #axpby \- )]] [[kernel, max_total_threads_per_threadgroup(bm * bn * 32)]] \- void \- gemv_t_inst_##name##_bm##bm##_bn##bn##_sm##sm##_sn##sn##_tm##tm##_tn##tn##_nc##nc##_axpby##axpby( \- const device itype* mat [[buffer(0)]], \- const device itype* in_vec [[buffer(1)]], \- const device itype* bias [[buffer(2)]], \- device itype* out_vec [[buffer(3)]], \- const constant int& in_vec_size [[buffer(4)]], \- const constant int& out_vec_size [[buffer(5)]], \- const constant int& matrix_ld [[buffer(6)]], \- const constant float& alpha [[buffer(7)]], \- const constant float& beta [[buffer(8)]], \- const constant int& batch_ndim [[buffer(9)]], \- const constant int* batch_shape [[buffer(10)]], \- const constant int64_t* vector_batch_stride [[buffer(11)]], \- const constant int64_t* matrix_batch_stride [[buffer(12)]], \- const constant int64_t* bias_batch_stride [[buffer(13)]], \- const constant int& bias_stride [[buffer(14)]], \- uint3 tid [[threadgroup_position_in_grid]], \- uint3 lid [[thread_position_in_threadgroup]], \- uint simd_gid [[simdgroup_index_in_threadgroup]], \- uint simd_lid [[thread_index_in_simdgroup]] \- ) { \- using gemv_kernel = GEMVTKernel<itype, bm, bn, sm, sn, tm, tn, axpby>; \- threadgroup typename gemv_kernel::acc_type tgp_memory \- [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size]; \- gemv_t_entry<itype, bm, bn, sm, sn, tm, tn, nc, axpby>( \- mat, \- in_vec, \- bias, \- out_vec, \- in_vec_size, \- out_vec_size, \- matrix_ld, \- alpha, \- beta, \- batch_ndim, \- batch_shape, \- vector_batch_stride, \- matrix_batch_stride, \- bias_batch_stride, \- bias_stride, \- gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory, \- tid, \- lid, \- simd_gid, \- simd_lid \- ); \- }--// clang-format off-#define instantiate_gemv(name, itype, bm, bn, sm, sn, tm, tn) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 0) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 1) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1)--#define instantiate_gemv_blocks(name, itype) \- instantiate_gemv(name, itype, 1, 8, 1, 32, 4, 4) \- instantiate_gemv(name, itype, 1, 8, 1, 32, 1, 4) \- instantiate_gemv(name, itype, 1, 1, 8, 4, 4, 4) \- instantiate_gemv(name, itype, 1, 1, 8, 4, 1, 4) \- instantiate_gemv(name, itype, 4, 1, 1, 32, 1, 4) \- instantiate_gemv(name, itype, 4, 1, 1, 32, 4, 4) \- instantiate_gemv(name, itype, 8, 1, 1, 32, 4, 4)--instantiate_gemv_blocks(float32, float);-instantiate_gemv_blocks(float16, half);-instantiate_gemv_blocks(bfloat16, bfloat);--#define instantiate_gemv_t(name, itype, bm, bn, sm, sn, tm, tn) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 0) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 1) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \- instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1)--#define instantiate_gemv_t_blocks(name, itype) \- instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 1) \- instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 4) \- instantiate_gemv_t(name, itype, 1, 4, 8, 4, 4, 4) \- instantiate_gemv_t(name, itype, 1, 16, 8, 4, 4, 4) \- instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4)--instantiate_gemv_t_blocks(float32, float);-instantiate_gemv_t_blocks(float16, half);-instantiate_gemv_t_blocks(bfloat16, bfloat);-// clang-format ondiff --git a/crates/uzu/src/backends/metal/kernel/matmul/gemv/gemv.metal b/crates/uzu/src/backends/metal/kernel/matmul/gemv/gemv.metalnew file mode 100644index 000000000..1c5bf124d--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/gemv/gemv.metal@@ -0,0 +1,866 @@+#include <metal_simdgroup>+#include <metal_stdlib>++#include "../../common/utils.h"++#include "../steel/utils.h"++using namespace metal;++///////////////////////////////////////////////////////////////////////////////+/// Matrix vector multiplication+///////////////////////////////////////////////////////////////////////////////++#define MTL_CONST static constant constexpr const++template <typename U>+struct DefaultAccT {+ using type = float;+};+template <>+struct DefaultAccT<complex64_t> {+ using type = complex64_t;+};++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const int TN, /* Thread cols (in elements) */+ const bool kDoAxpby, /* Do out = alpha * out + beta * bias */+ typename AccT = typename DefaultAccT<T>::type>+struct GEMVKernel {+ using acc_type = AccT;++ MTL_CONST int threadsM = BM * SM;+ MTL_CONST int threadsN = BN * SN;++ MTL_CONST int blockM = threadsM * TM;+ MTL_CONST int blockN = threadsN * TN;++ static_assert(SM * SN == 32, "simdgroup can only have 32 threads");++ static_assert(+ SN == 4 || SN == 8 || SN == 16 || SN == 32,+ "gemv block must have a width of 4, 8, 16, or 32");++ // - The matrix of size (M = out_vec_size, K = in_vec_size) is divided up+ // into blocks of (blockM, blockN) divided among threadgroups+ // - Every thread works on a block of (TM, TN)+ // - We assume each threadgroup has (threadsN, threadsM, 1) threads+ //+ // 1. A thread loads TN elements each from mat along TM rows+ // and the corresponding scalar from the vector+ // 2. The thread then multiplies and adds to accumulate its local result for+ // the block+ // 3. At the end, each thread has accumulated results over all blocks across+ // the rows. These are then summed up across the threadgroup+ // 4. Each threadgroup writes its accumulated blockM outputs+ //+ // Edge case handling:+ // - The threadgroup with the largest tid has blocks that exceed the matrix+ // * The blocks that start outside the matrix are never read (thread results+ // remain zero)+ // * The last thread that partially overlaps with the matrix is shifted+ // inwards such that the thread block fits exactly in the matrix++ MTL_CONST short tgp_mem_size = BN > 1 ? BN*(blockM + TM) : 0;+ MTL_CONST bool needs_tgp_reduction = BN > 1;++ template <typename U = T>+ static METAL_FUNC void+ load_unsafe(const device T* src, thread U dst[TN], const int src_offset = 0) {+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ dst[tn] = static_cast<U>(src[src_offset + tn]);+ }+ }++ template <typename U = T>+ static METAL_FUNC void load_safe(+ const device T* src,+ thread U dst[TN],+ const int src_offset = 0,+ const int src_size = TN) {+ if (src_offset + TN <= src_size) {+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ dst[tn] = static_cast<U>(src[src_offset + tn]);+ }+ } else { // Edgecase+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ dst[tn] = src_offset + tn < src_size+ ? static_cast<U>(src[src_offset + tn])+ : U(0);+ }+ }+ }++ static METAL_FUNC void run(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& matrix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& bias_stride [[buffer(14)]],+ threadgroup AccT* tgp_memory [[threadgroup(0)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]) {+ // Appease compiler+ (void)lid;++ // Thread local accumulation results+ thread AccT result[TM] = {0};+ thread T inter[TN];+ thread AccT v_coeff[TN];++ const int thrM = SN != 32 ? simd_lid / SN : 0;+ const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);++ const int sgN = BN != 1 ? (simd_gid % BN) : 0;++ const int simdM = BN != 1 ? SM * (simd_gid / BN) : int(SM * simd_gid);+ const int simdN = BN != 1 ? SN * (simd_gid % BN) : 0;++ int bm = (simdM + thrM) * TM;+ int bn = (simdN + thrN) * TN;++ // Block position+ int out_row = tid.x * blockM + bm;++ // Exit simdgroup if rows out of bound+ if (out_row >= out_vec_size)+ return;++ // Adjust tail simdgroup to ensure in bound reads+ out_row = out_row + TM <= out_vec_size ? out_row : out_vec_size - TM;++ // Advance matrix+ mat += out_row * matrix_ld;++ constexpr const uniform<int> loop_stride = make_uniform(blockN);+ const uniform<int> in_size = make_uniform(in_vec_size);+ const uniform<int> n_iter = in_size / loop_stride;+ const uniform<int> last_iter = loop_stride * n_iter;+ const uniform<int> leftover = in_size - last_iter;++ // Loop over in_vec in blocks of blockN+ for (int i = 0; i < n_iter; ++i) {+ load_unsafe<AccT>(in_vec, v_coeff, bn);++ // Per thread work loop+ int mat_offset = 0;+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ // Load for the row+ load_unsafe(mat, inter, mat_offset + bn);++ // Accumulate results+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ result[tm] += inter[tn] * v_coeff[tn];+ }++ mat_offset += matrix_ld;+ }++ bn += blockN;+ }++ if (leftover > 0) {+ load_safe<AccT>(in_vec, v_coeff, bn, in_size);++ // Per thread work loop+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ // Load for the row+ load_safe(&mat[tm * matrix_ld], inter, bn, in_size);++ // Accumulate results+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ result[tm] += inter[tn] * v_coeff[tn];+ }+ }+ }++ // Simdgroup accumulations+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ MTL_PRAGMA_UNROLL+ for (ushort sn = (SN / 2); sn >= 1; sn >>= 1) {+ result[tm] += simd_shuffle_down(result[tm], sn);+ }+ }++ // Threadgroup accumulation results+ if (needs_tgp_reduction) {+ threadgroup AccT* tgp_results = tgp_memory + sgN * (blockM + TM) + bm;+ if (thrN == 0) {+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ tgp_results[tm] = result[tm];+ }++ threadgroup_barrier(mem_flags::mem_none);++ if (sgN == 0) {+ MTL_PRAGMA_UNROLL+ for (int sgn = 1; sgn < BN; sgn++) {+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ result[tm] += tgp_results[sgn * (blockM + TM) + tm];+ }+ }+ }+ }+ }++ // Write outputs+ if (simdN == 0 && thrN == 0) {+ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ if (kDoAxpby) {+ out_vec[out_row + tm] =+ static_cast<T>(alpha) * static_cast<T>(result[tm]) ++ static_cast<T>(beta) * bias[(out_row + tm) * bias_stride];+ } else {+ out_vec[out_row + tm] = static_cast<T>(result[tm]);+ }+ }+ }+ }+};++///////////////////////////////////////////////////////////////////////////////+/// Vector matrix multiplication+///////////////////////////////////////////////////////////////////////////////++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const int TN, /* Thread cols (in elements) */+ const bool kDoAxpby, /* Do out = alpha * out + beta * bias */+ typename AccT = typename DefaultAccT<T>::type>+struct GEMVTKernel {+ using acc_type = AccT;++ MTL_CONST int threadsM = BM * SM;+ MTL_CONST int threadsN = BN * SN;++ MTL_CONST int blockM = threadsM * TM;+ MTL_CONST int blockN = threadsN * TN;++ static_assert(SM * SN == 32, "simdgroup can only have 32 threads");++ // - The matrix of size (M = in_vec_size, N = out_vec_size) is divided up+ // into blocks of (blockM, blockN) divided among threadgroups+ // - Every thread works on a block of (TM, TN)+ // - We assume each threadgroup has (threadsN, threadsM, 1) threads+ //+ // 1. A thread loads TN elements each from mat along TM contiguous rows+ // and the corresponding scalar from the vector+ // 2. The thread then accumulates its local result for the block+ // 3. At the end, each thread has accumulated results over all blocks across+ // the rows. These are then summed up across the threadgroup+ // 4. Each threadgroup writes its accumulated BN * TN outputs+ //+ // Edge case handling:+ // - The threadgroup with the largest tid has blocks that exceed the matrix+ // * The blocks that start outside the matrix are never read (thread results+ // remain zero)+ // * The last thread that partially overlaps with the matrix is shifted+ // inwards such that the thread block fits exactly in the matrix++ MTL_CONST short tgp_mem_size = BM > 1 ? BM*(blockN + TN) : 0;+ MTL_CONST bool needs_tgp_reduction = BM > 1;++ static METAL_FUNC void run(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& marix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& bias_stride [[buffer(14)]],+ threadgroup AccT* tgp_memory [[threadgroup(0)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]) {+ // Appease compiler+ (void)lid;++ // Thread local accumulation results+ AccT result[TN] = {0};+ T inter[TN];+ AccT v_coeff[TM];+ const int thrM = SN != 32 ? simd_lid / SN : 0;+ const int thrN = SN != 32 ? simd_lid % SN : int(simd_lid);++ const int sgM = BN != 1 ? (simd_gid / BN) : int(simd_gid);+ const int sgN = BN != 1 ? (simd_gid % BN) : 0;++ const int simdM = SM * sgM;+ const int simdN = SN * sgN;++ int cm = (simdM + thrM);+ int cn = (simdN + thrN);++ int bm = cm * TM;+ int bn = cn * TN;++ int out_col = tid.x * blockN + bn;++ constexpr const uniform<int> loop_stride = make_uniform(blockM);+ const uniform<int> in_size = make_uniform(in_vec_size);+ const uniform<int> n_iter = in_size / loop_stride;+ const uniform<int> last_iter = loop_stride * n_iter;+ const uniform<int> leftover = in_size - last_iter;++ // Edgecase handling+ if (out_col < out_vec_size) {+ out_col = out_col + TN < out_vec_size ? out_col : out_vec_size - TN;++ // Per thread accumulation main loop+ for (int i = 0; i < n_iter; ++i) {+ // Adding a threadgroup_barrier improves performance slightly+ // This is possibly it may help exploit cache better+ threadgroup_barrier(mem_flags::mem_none);++ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);+ }++ MTL_PRAGMA_UNROLL+ for (int tm = 0; tm < TM; tm++) {+ auto vc = static_cast<AccT>(v_coeff[tm]);+ for (int tn = 0; tn < TN; tn++) {+ inter[tn] = mat[(bm + tm) * marix_ld + out_col + tn];+ }+ for (int tn = 0; tn < TN; tn++) {+ result[tn] += vc * inter[tn];+ }+ }++ bm += blockM;+ }++ if (leftover > 0) {+ for (int tm = 0; tm < TM && bm + tm < in_vec_size; tm++) {+ v_coeff[tm] = static_cast<AccT>(in_vec[bm + tm]);++ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ inter[tn] = mat[(bm + tm) * marix_ld + out_col + tn];+ }++ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ result[tn] += v_coeff[tm] * inter[tn];+ }+ }+ }+ }++ // Simdgroup accumulations+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ MTL_PRAGMA_UNROLL+ for (ushort sm = (SM / 2); sm >= 1; sm >>= 1) {+ result[tn] += simd_shuffle_down(result[tn], SN * sm);+ }+ }++ // Threadgroup accumulation results+ if (needs_tgp_reduction) {+ threadgroup AccT* tgp_results = tgp_memory + sgM * (blockN + TN) + bn;+ if (thrM == 0) {+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ tgp_results[tn] = result[tn];+ }++ threadgroup_barrier(mem_flags::mem_none);++ if (sgM == 0) {+ MTL_PRAGMA_UNROLL+ for (int sgm = 1; sgm < BM; sgm++) {+ MTL_PRAGMA_UNROLL+ for (int tn = 0; tn < TN; tn++) {+ result[tn] += tgp_results[sgm * (blockN + TN) + tn];+ }+ }+ }+ }+ }++ // Threadgroup accumulation and writing out results+ if (cm == 0 && out_col < out_vec_size) {+ MTL_PRAGMA_UNROLL+ for (int j = 0; j < TN; j++) {+ if (kDoAxpby) {+ out_vec[out_col + j] =+ static_cast<T>(alpha) * static_cast<T>(result[j]) ++ static_cast<T>(beta) * bias[(out_col + j) * bias_stride];+ } else {+ out_vec[out_col + j] = static_cast<T>(result[j]);+ }+ }+ }+ }+};++///////////////////////////////////////////////////////////////////////////////+/// Matrix vector multiplication+///////////////////////////////////////////////////////////////////////////////++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const int TN, /* Thread cols (in elements) */+ const bool kDoNCBatch, /* Batch ndim > 1 */+ const bool kDoAxpby> /* Do out = alpha * out + beta * bias */+[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& marix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& batch_ndim [[buffer(9)]],+ const constant int* batch_shape [[buffer(10)]],+ const constant int64_t* vector_batch_stride [[buffer(11)]],+ const constant int64_t* matrix_batch_stride [[buffer(12)]],+ const constant int64_t* bias_batch_stride [[buffer(13)]],+ const constant int& bias_stride [[buffer(14)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]) {+ using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;+ threadgroup typename gemv_kernel::acc_type tgp_memory+ [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];++ // Update batch offsets+ if (kDoNCBatch) {+ in_vec += elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);+ mat += elem_to_loc(tid.z, batch_shape, matrix_batch_stride, batch_ndim);++ if (kDoAxpby) {+ bias += elem_to_loc(tid.z, batch_shape, bias_batch_stride, batch_ndim);+ }++ } else {+ in_vec += tid.z * vector_batch_stride[0];+ mat += tid.z * matrix_batch_stride[0];++ if (kDoAxpby) {+ bias += tid.z * bias_batch_stride[0];+ }+ }++ out_vec += tid.z * out_vec_size;++ gemv_kernel::run(+ mat,+ in_vec,+ bias,+ out_vec,+ in_vec_size,+ out_vec_size,+ marix_ld,+ alpha,+ beta,+ bias_stride,+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,+ tid,+ lid,+ simd_gid,+ simd_lid);+}++#define instantiate_gemv_helper( \+ name, itype, bm, bn, sm, sn, tm, tn, nc, axpby) \+ instantiate_kernel( \+ "gemv_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn "_tm" #tm \+ "_tn" #tn "_nc" #nc "_axpby" #axpby, \+ gemv, \+ itype, \+ bm, \+ bn, \+ sm, \+ sn, \+ tm, \+ tn, \+ nc, \+ axpby)++// clang-format off+#define instantiate_gemv(name, itype, bm, bn, sm, sn, tm, tn) \+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 0) \+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 1) \+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \+ instantiate_gemv_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1) // clang-format on++// clang-format off+#define instantiate_gemv_blocks(name, itype) \+ instantiate_gemv(name, itype, 1, 8, 1, 32, 4, 4) \+ instantiate_gemv(name, itype, 1, 8, 1, 32, 1, 4) \+ instantiate_gemv(name, itype, 1, 1, 8, 4, 4, 4) \+ instantiate_gemv(name, itype, 1, 1, 8, 4, 1, 4) \+ instantiate_gemv(name, itype, 4, 1, 1, 32, 1, 4) \+ instantiate_gemv(name, itype, 4, 1, 1, 32, 4, 4) \+ instantiate_gemv(name, itype, 8, 1, 1, 32, 4, 4) // clang-format on++instantiate_gemv_blocks(float32, float);+instantiate_gemv_blocks(float16, half);+instantiate_gemv_blocks(bfloat16, bfloat16_t);+instantiate_gemv_blocks(complex64, complex64_t);++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const int TN> /* Thread cols (in elements) */+[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_gather(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& marix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& batch_ndim [[buffer(9)]],+ const constant int* batch_shape [[buffer(10)]],+ const constant int64_t* index_batch_strides [[buffer(11)]],+ const constant int& vector_batch_ndim [[buffer(12)]],+ const constant int* vector_batch_shape [[buffer(13)]],+ const constant int64_t* vector_batch_stride [[buffer(14)]],+ const constant int& matrix_batch_ndim [[buffer(15)]],+ const constant int* matrix_batch_shape [[buffer(16)]],+ const constant int64_t* matrix_batch_stride [[buffer(17)]],+ const constant uint32_t* vec_indices [[buffer(18)]],+ const constant uint32_t* mat_indices [[buffer(19)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]) {+ using gemv_kernel = GEMVKernel<T, BM, BN, SM, SN, TM, TN, false>;+ threadgroup typename gemv_kernel::acc_type tgp_memory+ [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];++ uint32_t indx_vec;+ uint32_t indx_mat;++ // Update batch offsets+ if (batch_ndim > 1) {+ const constant auto* veci_bstrides = index_batch_strides;+ const constant auto* mati_bstrides = index_batch_strides + batch_ndim;++ ulong2 batch_offsets = elem_to_loc_broadcast(+ tid.z, batch_shape, veci_bstrides, mati_bstrides, batch_ndim);++ indx_vec = vec_indices[batch_offsets.x];+ indx_mat = mat_indices[batch_offsets.y];++ } else {+ indx_vec = vec_indices[index_batch_strides[0] * tid.z];+ indx_mat = mat_indices[index_batch_strides[batch_ndim] * tid.z];+ }++ if (vector_batch_ndim > 1) {+ in_vec += elem_to_loc(+ indx_vec, vector_batch_shape, vector_batch_stride, vector_batch_ndim);+ } else {+ in_vec += indx_vec * vector_batch_stride[0];+ }++ if (matrix_batch_ndim > 1) {+ mat += elem_to_loc(+ indx_mat, matrix_batch_shape, matrix_batch_stride, matrix_batch_ndim);+ } else {+ mat += indx_mat * matrix_batch_stride[0];+ }++ out_vec += tid.z * out_vec_size;++ gemv_kernel::run(+ mat,+ in_vec,+ bias,+ out_vec,+ in_vec_size,+ out_vec_size,+ marix_ld,+ alpha,+ beta,+ batch_ndim, // Not used+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,+ tid,+ lid,+ simd_gid,+ simd_lid);+}++// clang-format off+#define instantiate_gemv_bs_helper(nm, itype, bm, bn, sm, sn, tm, tn) \+ instantiate_kernel( \+ "gemv_gather_" #nm "_bm" #bm "_bn" #bn "_sm" #sm \+ "_sn" #sn "_tm" #tm "_tn" #tn, \+ gemv_gather, itype, bm, bn, sm, sn, tm, tn)++#define instantiate_gemv_bs_blocks(name, itype) \+ instantiate_gemv_bs_helper(name, itype, 4, 1, 1, 32, 1, 4) \+ instantiate_gemv_bs_helper(name, itype, 4, 1, 1, 32, 4, 4) \+ instantiate_gemv_bs_helper(name, itype, 8, 1, 1, 32, 4, 4) // clang-format on++instantiate_gemv_bs_blocks(float32, float);+instantiate_gemv_bs_blocks(float16, half);+instantiate_gemv_bs_blocks(bfloat16, bfloat16_t);+instantiate_gemv_bs_blocks(complex64, complex64_t);++///////////////////////////////////////////////////////////////////////////////+/// Vector matrix multiplication+///////////////////////////////////////////////////////////////////////////////++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const int TN, /* Thread cols (in elements) */+ const bool kDoNCBatch, /* Batch ndim > 1 */+ const bool kDoAxpby> /* Do out = alpha * out + beta * bias */+[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_t(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& marix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& batch_ndim [[buffer(9)]],+ const constant int* batch_shape [[buffer(10)]],+ const constant int64_t* vector_batch_stride [[buffer(11)]],+ const constant int64_t* matrix_batch_stride [[buffer(12)]],+ const constant int64_t* bias_batch_stride [[buffer(13)]],+ const constant int& bias_stride [[buffer(14)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]) {+ using gemv_kernel = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, kDoAxpby>;+ threadgroup typename gemv_kernel::acc_type tgp_memory+ [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];++ // Update batch offsets+ if (kDoNCBatch) {+ in_vec += elem_to_loc(tid.z, batch_shape, vector_batch_stride, batch_ndim);+ mat += elem_to_loc(tid.z, batch_shape, matrix_batch_stride, batch_ndim);++ if (kDoAxpby) {+ bias += elem_to_loc(tid.z, batch_shape, bias_batch_stride, batch_ndim);+ }++ } else {+ in_vec += tid.z * vector_batch_stride[0];+ mat += tid.z * matrix_batch_stride[0];++ if (kDoAxpby) {+ bias += tid.z * bias_batch_stride[0];+ }+ }++ out_vec += tid.z * out_vec_size;++ gemv_kernel::run(+ mat,+ in_vec,+ bias,+ out_vec,+ in_vec_size,+ out_vec_size,+ marix_ld,+ alpha,+ beta,+ bias_stride,+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,+ tid,+ lid,+ simd_gid,+ simd_lid);+}++// clang-format off+#define instantiate_gemv_t_helper( \+ name, itype, bm, bn, sm, sn, tm, tn, nc, axpby) \+ instantiate_kernel( \+ "gemv_t_" #name "_bm" #bm "_bn" #bn "_sm" #sm "_sn" #sn \+ "_tm" #tm "_tn" #tn "_nc" #nc "_axpby" #axpby, \+ gemv_t, itype, bm, bn, sm, sn, tm, tn, nc, axpby)++#define instantiate_gemv_t(name, itype, bm, bn, sm, sn, tm, tn) \+ instantiate_gemv_t_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 0) \+ instantiate_gemv_t_helper(name, itype, bm, bn, sm, sn, tm, tn, 0, 1) \+ instantiate_gemv_t_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 0) \+ instantiate_gemv_t_helper(name, itype, bm, bn, sm, sn, tm, tn, 1, 1) // clang-format on++// clang-format off+#define instantiate_gemv_t_blocks(name, itype) \+ instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 1) \+ instantiate_gemv_t(name, itype, 1, 2, 8, 4, 4, 4) \+ instantiate_gemv_t(name, itype, 1, 4, 8, 4, 4, 4) \+ instantiate_gemv_t(name, itype, 1, 16, 8, 4, 4, 4) \+ instantiate_gemv_t(name, itype, 1, 16, 4, 8, 4, 4) // clang-format on++// clang-format off+instantiate_gemv_t_blocks(float32, float);+instantiate_gemv_t_blocks(float16, half);+instantiate_gemv_t_blocks(bfloat16, bfloat16_t);+instantiate_gemv_t_blocks(complex64, complex64_t); // clang-format on++template <+ typename T,+ const int BM, /* Threadgroup rows (in simdgroups) */+ const int BN, /* Threadgroup cols (in simdgroups) */+ const int SM, /* Simdgroup rows (in threads) */+ const int SN, /* Simdgroup cols (in threads) */+ const int TM, /* Thread rows (in elements) */+ const int TN> /* Thread cols (in elements) */+[[kernel, max_total_threads_per_threadgroup(BM* BN * 32)]] void gemv_t_gather(+ const device T* mat [[buffer(0)]],+ const device T* in_vec [[buffer(1)]],+ const device T* bias [[buffer(2)]],+ device T* out_vec [[buffer(3)]],+ const constant int& in_vec_size [[buffer(4)]],+ const constant int& out_vec_size [[buffer(5)]],+ const constant int& marix_ld [[buffer(6)]],+ const constant float& alpha [[buffer(7)]],+ const constant float& beta [[buffer(8)]],+ const constant int& batch_ndim [[buffer(9)]],+ const constant int* batch_shape [[buffer(10)]],+ const constant int64_t* index_batch_strides [[buffer(11)]],+ const constant int& vector_batch_ndim [[buffer(12)]],+ const constant int* vector_batch_shape [[buffer(13)]],+ const constant int64_t* vector_batch_stride [[buffer(14)]],+ const constant int& matrix_batch_ndim [[buffer(15)]],+ const constant int* matrix_batch_shape [[buffer(16)]],+ const constant int64_t* matrix_batch_stride [[buffer(17)]],+ const constant uint32_t* vec_indices [[buffer(18)]],+ const constant uint32_t* mat_indices [[buffer(19)]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]],+ uint simd_gid [[simdgroup_index_in_threadgroup]],+ uint simd_lid [[thread_index_in_simdgroup]]) {+ using gemv_kernel = GEMVTKernel<T, BM, BN, SM, SN, TM, TN, false>;+ threadgroup typename gemv_kernel::acc_type tgp_memory+ [gemv_kernel::tgp_mem_size == 0 ? 1 : gemv_kernel::tgp_mem_size];++ uint32_t indx_vec;+ uint32_t indx_mat;++ // Update batch offsets+ if (batch_ndim > 1) {+ const constant auto* veci_bstrides = index_batch_strides;+ const constant auto* mati_bstrides = index_batch_strides + batch_ndim;++ ulong2 batch_offsets = elem_to_loc_broadcast(+ tid.z, batch_shape, veci_bstrides, mati_bstrides, batch_ndim);++ indx_vec = vec_indices[batch_offsets.x];+ indx_mat = mat_indices[batch_offsets.y];++ } else {+ indx_vec = vec_indices[index_batch_strides[0] * tid.z];+ indx_mat = mat_indices[index_batch_strides[batch_ndim] * tid.z];+ }++ if (vector_batch_ndim > 1) {+ in_vec += elem_to_loc(+ indx_vec, vector_batch_shape, vector_batch_stride, vector_batch_ndim);+ } else {+ in_vec += indx_vec * vector_batch_stride[0];+ }++ if (matrix_batch_ndim > 1) {+ mat += elem_to_loc(+ indx_mat, matrix_batch_shape, matrix_batch_stride, matrix_batch_ndim);+ } else {+ mat += indx_mat * matrix_batch_stride[0];+ }++ out_vec += tid.z * out_vec_size;++ gemv_kernel::run(+ mat,+ in_vec,+ bias,+ out_vec,+ in_vec_size,+ out_vec_size,+ marix_ld,+ alpha,+ beta,+ batch_ndim, // Not used,+ gemv_kernel::tgp_mem_size == 0 ? nullptr : tgp_memory,+ tid,+ lid,+ simd_gid,+ simd_lid);+}++// clang-format off+#define instantiate_gemv_t_bs_helper( \+ nm, itype, bm, bn, sm, sn, tm, tn) \+ instantiate_kernel( \+ "gemv_t_gather_" #nm "_bm" #bm "_bn" #bn "_sm" #sm \+ "_sn" #sn "_tm" #tm "_tn" #tn, \+ gemv_t_gather, itype, bm, bn, sm, sn, tm, tn)++#define instantiate_gemv_t_bs_blocks(name, itype) \+ instantiate_gemv_t_bs_helper(name, itype, 1, 2, 8, 4, 4, 1) \+ instantiate_gemv_t_bs_helper(name, itype, 1, 2, 8, 4, 4, 4) \+ instantiate_gemv_t_bs_helper(name, itype, 1, 4, 8, 4, 4, 4) \+ instantiate_gemv_t_bs_helper(name, itype, 1, 16, 8, 4, 4, 4) \+ instantiate_gemv_t_bs_helper(name, itype, 1, 16, 4, 8, 4, 4) // clang-format on++// clang-format off+instantiate_gemv_t_bs_blocks(float32, float);+instantiate_gemv_t_bs_blocks(float16, half);+instantiate_gemv_t_bs_blocks(bfloat16, bfloat16_t);+instantiate_gemv_t_bs_blocks(complex64, complex64_t); // clang-format ondiff --git a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rsindex 0f99c03cb..4eafd1413 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/kernel.rs@@ -60,11 +60,11 @@ pub struct MatmulKernel {}impl MatmulKernel {- fn dtype_suffix(dt: DataType) -> &'static str {+ fn steel_type_name(dt: DataType) -> &'static str {match dt {- DataType::F16 => "f16",- DataType::BF16 => "bf16",- DataType::F32 => "f32",+ DataType::F16 => "float16",+ DataType::BF16 => "bfloat16",+ DataType::F32 => "float32",_ => unreachable!(),}}@@ -73,15 +73,22 @@ impl MatmulKernel {&self,tile: &TileSelection,) -> String {- let dtype_suffix = Self::dtype_suffix(self.data_type);+ let type_name = Self::steel_type_name(self.data_type);let transpose_suffix = transpose_configuration(self.lhs_is_transposed,self.rhs_is_transposed,);+ let prefix = if tile.block_depth >= 256 {+ "steel_gemm_fused_nax"+ } else {+ "steel_gemm_fused"+ };format!(- "gemm_{}_{}_bm{}_bn{}_bk{}_wm{}_wn{}",+ "{}_{}_{}_{}_bm{}_bn{}_bk{}_wm{}_wn{}",+ prefix,transpose_suffix.as_str(),- dtype_suffix,+ type_name,+ type_name,tile.block_rows,tile.block_cols,tile.block_depth,@@ -210,7 +217,7 @@ impl MatmulKernel {// NAX path: prefer deeper K tiles on NAX-capable devices.if mtl.is_nax_available() && prefer_half_or_tf32 {let base_tile = TileSelection::new(- 128, 128, 32, 2, 2, /*swizzle_log2=*/ 0,+ 128, 128, 512, 4, 4, /*swizzle_log2=*/ 0,);let tile_rows =(args.batch + base_tile.block_rows - 1) / base_tile.block_rows;@@ -420,9 +427,9 @@ impl MatmulKernel {let elements_per_matrix_d = (args.batch as i64) * (args.ldd as i64);let batch_ndim = 1;let params = GEMMParams {- batch: m,- output_dim: n,- input_dim: k,+ M: m,+ N: n,+ K: k,lda: args.lda,ldb: args.ldb,ldd: args.ldd,diff --git a/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal b/crates/uzu/src/backends/metal/kernel/matmul/matmul.metaldeleted file mode 100644index 68226ae56..000000000--- a/crates/uzu/src/backends/metal/kernel/matmul/matmul.metal+++ /dev/null@@ -1,572 +0,0 @@-// SPDX-License-Identifier: MIT-// General matrix multiplication kernels for uzu--#include <metal_stdlib>-#include "gemm.h"--using namespace metal;-using namespace uzu::matmul;--///////////////////////////////////////////////////////////////////////////////-// Function constants for compile-time specialization-///////////////////////////////////////////////////////////////////////////////--constant bool has_batch [[function_constant(10)]];--constant bool use_out_source [[function_constant(100)]];-constant bool do_axpby [[function_constant(110)]];--constant bool align_M [[function_constant(200)]];-constant bool align_N [[function_constant(201)]];-constant bool align_K [[function_constant(202)]];--///////////////////////////////////////////////////////////////////////////////-// GEMM kernel template-///////////////////////////////////////////////////////////////////////////////--template <- typename T,- int BM,- int BN,- int BK,- int WM,- int WN,- bool transpose_a,- bool transpose_b,- typename AccumType = float>-[[kernel, max_total_threads_per_threadgroup(WM * WN * 32)]] void gemm(- const device T* input_a [[buffer(0)]],- const device T* input_b [[buffer(1)]],- const device T* input_c [[buffer(2), function_constant(use_out_source)]],- device T* output [[buffer(3)]],- const constant GEMMParams* params [[buffer(4)]],- const constant GEMMAddMMParams* addmm_params- [[buffer(5), function_constant(use_out_source)]],- const constant int* batch_shape [[buffer(6), function_constant(has_batch)]],- const constant int64_t* batch_strides- [[buffer(7), function_constant(has_batch)]],- uint simd_lane_id [[thread_index_in_simdgroup]],- uint simd_group_id [[simdgroup_index_in_threadgroup]],- uint3 threadgroup_position [[threadgroup_position_in_grid]],- uint3 thread_position [[thread_position_in_threadgroup]]-) {- // Pacifying compiler- (void)thread_position;-- using gemm_kernel = GEMMKernel<- T,- T,- BM,- BN,- BK,- WM,- WN,- transpose_a,- transpose_b,- true,- true,- AccumType>;-- using loader_a_t = typename gemm_kernel::loader_a_t;- using loader_b_t = typename gemm_kernel::loader_b_t;- using mma_t = typename gemm_kernel::mma_t;-- // Find block with swizzle- const int threadgroup_y =- ((threadgroup_position.y) << params->swizzle_log) +- ((threadgroup_position.x) & ((1 << params->swizzle_log) - 1));- const int threadgroup_x = (threadgroup_position.x) >> params->swizzle_log;-- // Exit early if out of bounds- if (params->tiles_n <= threadgroup_x || params->tiles_m <= threadgroup_y) {- return;- }-- // Adjust for batch- if (has_batch) {- // Simple batch striding (no broadcast)- input_a += params->batch_stride_a * threadgroup_position.z;- input_b += params->batch_stride_b * threadgroup_position.z;-- if (use_out_source) {- input_c += addmm_params->batch_stride_c * threadgroup_position.z;- }- } else {- input_a += params->batch_stride_a * threadgroup_position.z;- input_b += params->batch_stride_b * threadgroup_position.z;-- if (use_out_source) {- input_c += addmm_params->batch_stride_c * threadgroup_position.z;- }- }-- output += params->batch_stride_d * threadgroup_position.z;-- // Prepare threadgroup memory- threadgroup T threadgroup_a[gemm_kernel::tgp_mem_size_a];- threadgroup T threadgroup_b[gemm_kernel::tgp_mem_size_b];-- threadgroup_barrier(mem_flags::mem_none);-- // Find block in input_a, input_b, input_c- const int output_row = threadgroup_y * BM;- const int output_col = threadgroup_x * BN;- const size_t output_row_long = size_t(output_row);- const size_t output_col_long = size_t(output_col);-- input_a += transpose_a ? output_row_long : output_row_long * params->lda;- input_b += transpose_b ? output_col_long * params->ldb : output_col_long;- output += output_row_long * params->ldd + output_col_long;-- if (use_out_source) {- input_c += output_row_long * addmm_params->ldc +- output_col_long * addmm_params->fdc;- }-- // Prepare threadgroup mma operation- thread mma_t matrix_multiply_accumulate(simd_group_id, simd_lane_id);-- // Prepare threadgroup loading operations- thread loader_a_t block_loader_a(- input_a,- params->lda,- threadgroup_a,- simd_group_id,- simd_lane_id- );- thread loader_b_t block_loader_b(- input_b,- params->ldb,- threadgroup_b,- simd_group_id,- simd_lane_id- );-- // Prepare threadgroup bounds- const short threadgroup_block_batch =- align_M ? BM : short(min(BM, params->batch - output_row));- const short threadgroup_block_output =- align_N ? BN : short(min(BN, params->output_dim - output_col));-- // Prepare iterations- int gemm_k_iterations = params->gemm_k_iterations_aligned;-- // Do unaligned K iterations first- if (!align_K) {- const int input_aligned_end = params->gemm_k_iterations_aligned * BK;- const int input_remainder = params->input_dim - input_aligned_end;- const size_t input_offset_a = transpose_a- ? params->lda * size_t(input_aligned_end)- : size_t(input_aligned_end);- const size_t input_offset_b = transpose_b- ? size_t(input_aligned_end)- : params->ldb * size_t(input_aligned_end);-- // Move loader source ahead to end- block_loader_a.src += input_offset_a;- block_loader_b.src += input_offset_b;-- // Load tile- const short2 tile_dimensions_a =- transpose_a ? short2(threadgroup_block_batch, input_remainder)- : short2(input_remainder, threadgroup_block_batch);- const short2 tile_dimensions_b =- transpose_b ? short2(input_remainder, threadgroup_block_output)- : short2(threadgroup_block_output, input_remainder);-- block_loader_a.load_safe(tile_dimensions_a);- block_loader_b.load_safe(tile_dimensions_b);-- threadgroup_barrier(mem_flags::mem_threadgroup);-- // Do matmul- matrix_multiply_accumulate.mma(threadgroup_a, threadgroup_b);-- // Reset source back to start- block_loader_a.src -= input_offset_a;- block_loader_b.src -= input_offset_b;- }-- const TransformAdd<AccumType, AccumType> epilogue_operation_add(- addmm_params->alpha,- addmm_params->beta- );- const TransformAxpby<AccumType, AccumType> epilogue_operation_axpby(- addmm_params->alpha,- addmm_params->beta- );-- ///////////////////////////////////////////////////////////////////////////- // MNK aligned loop- if (align_M && align_N) {- // Do gemm- for (int iteration = 0; iteration < gemm_k_iterations; iteration++) {- threadgroup_barrier(mem_flags::mem_threadgroup);- // Load elements into threadgroup- block_loader_a.load_unsafe();- block_loader_b.load_unsafe();-- threadgroup_barrier(mem_flags::mem_threadgroup);-- // Multiply and accumulate threadgroup elements- matrix_multiply_accumulate.mma(threadgroup_a, threadgroup_b);-- // Prepare for next iteration- block_loader_a.next();- block_loader_b.next();- }-- threadgroup_barrier(mem_flags::mem_none);-- // Do epilogue- if (use_out_source) {- if (do_axpby) {- matrix_multiply_accumulate.apply_epilogue(- input_c,- addmm_params->ldc,- addmm_params->fdc,- epilogue_operation_axpby- );- } else {- matrix_multiply_accumulate.apply_epilogue(- input_c,- addmm_params->ldc,- addmm_params->fdc,- epilogue_operation_add- );- }- }-- // Store results to device memory- return matrix_multiply_accumulate.store_result(output, params->ldd);- }- ///////////////////////////////////////////////////////////////////////////- // MN unaligned loop- else { // Loop over K - unaligned case- const int leftover_block_input = 0;-- if ((align_M || threadgroup_block_batch == BM) &&- (align_N || threadgroup_block_output == BN)) {- // Do gemm- gemm_kernel::gemm_loop(- threadgroup_a,- threadgroup_b,- gemm_k_iterations,- block_loader_a,- block_loader_b,- matrix_multiply_accumulate,- threadgroup_block_batch,- threadgroup_block_output,- leftover_block_input,- LoopAlignment<true, true, true>{}- );-- // Do epilogue- if (use_out_source) {- if (do_axpby) {- matrix_multiply_accumulate.apply_epilogue(- input_c,- addmm_params->ldc,- addmm_params->fdc,- epilogue_operation_axpby- );- } else {- matrix_multiply_accumulate.apply_epilogue(- input_c,- addmm_params->ldc,- addmm_params->fdc,- epilogue_operation_add- );- }- }-- // Store results to device memory- return matrix_multiply_accumulate.store_result(output, params->ldd);-- } else if (align_N || threadgroup_block_output == BN) {- gemm_kernel::gemm_loop(- threadgroup_a,- threadgroup_b,- gemm_k_iterations,- block_loader_a,- block_loader_b,- matrix_multiply_accumulate,- threadgroup_block_batch,- threadgroup_block_output,- leftover_block_input,- LoopAlignment<false, true, true>{}- );-- // Do epilogue- if (use_out_source) {- if (do_axpby) {- matrix_multiply_accumulate.apply_epilogue_safe(- input_c,- addmm_params->ldc,- addmm_params->fdc,- short2(threadgroup_block_output, threadgroup_block_batch),- epilogue_operation_axpby- );- } else {- matrix_multiply_accumulate.apply_epilogue_safe(- input_c,- addmm_params->ldc,- addmm_params->fdc,- short2(threadgroup_block_output, threadgroup_block_batch),- epilogue_operation_add- );- }- }-- // Store results to device memory- return matrix_multiply_accumulate.store_result_safe(- output,- params->ldd,- short2(threadgroup_block_output, threadgroup_block_batch)- );-- } else if (align_M || threadgroup_block_batch == BM) {- gemm_kernel::gemm_loop(- threadgroup_a,- threadgroup_b,- gemm_k_iterations,- block_loader_a,- block_loader_b,- matrix_multiply_accumulate,- threadgroup_block_batch,- threadgroup_block_output,- leftover_block_input,- LoopAlignment<true, false, true>{}- );-- // Do epilogue- if (use_out_source) {- if (do_axpby) {- matrix_multiply_accumulate.apply_epilogue_safe(- input_c,- addmm_params->ldc,- addmm_params->fdc,- short2(threadgroup_block_output, threadgroup_block_batch),- epilogue_operation_axpby- );- } else {- matrix_multiply_accumulate.apply_epilogue_safe(- input_c,- addmm_params->ldc,- addmm_params->fdc,- short2(threadgroup_block_output, threadgroup_block_batch),- epilogue_operation_add- );- }- }-- // Store results to device memory- return matrix_multiply_accumulate.store_result_safe(- output,- params->ldd,- short2(threadgroup_block_output, threadgroup_block_batch)- );-- } else {- gemm_kernel::gemm_loop(- threadgroup_a,- threadgroup_b,- gemm_k_iterations,- block_loader_a,- block_loader_b,- matrix_multiply_accumulate,- threadgroup_block_batch,- threadgroup_block_output,- leftover_block_input,- LoopAlignment<false, false, true>{}- );-- // Do epilogue- if (use_out_source) {- if (do_axpby) {- matrix_multiply_accumulate.apply_epilogue_safe(- input_c,- addmm_params->ldc,- addmm_params->fdc,- short2(threadgroup_block_output, threadgroup_block_batch),- epilogue_operation_axpby- );- } else {- matrix_multiply_accumulate.apply_epilogue_safe(- input_c,- addmm_params->ldc,- addmm_params->fdc,- short2(threadgroup_block_output, threadgroup_block_batch),- epilogue_operation_add- );- }- }-- // Store results to device memory- return matrix_multiply_accumulate.store_result_safe(- output,- params->ldd,- short2(threadgroup_block_output, threadgroup_block_batch)- );- }- }-}--///////////////////////////////////////////////////////////////////////////////-// Kernel instantiation macros-///////////////////////////////////////////////////////////////////////////////--#define instantiate_gemm( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- element_type, \- block_batch, \- block_output, \- block_input, \- warp_batch, \- warp_output \-) \- template [[host_name( \- "gemm_" #transpose_name "_" #type_name "_bm" #block_batch \- "_bn" #block_output "_bk" #block_input "_wm" #warp_batch \- "_wn" #warp_output \- )]] [[kernel]] void \- gemm< \- element_type, \- block_batch, \- block_output, \- block_input, \- warp_batch, \- warp_output, \- transpose_a, \- transpose_b, \- float>( \- const device element_type* input_a [[buffer(0)]], \- const device element_type* input_b [[buffer(1)]], \- const device element_type* input_c \- [[buffer(2), function_constant(use_out_source)]], \- device element_type* output [[buffer(3)]], \- const constant GEMMParams* params [[buffer(4)]], \- const constant GEMMAddMMParams* addmm_params \- [[buffer(5), function_constant(use_out_source)]], \- const constant int* batch_shape \- [[buffer(6), function_constant(has_batch)]], \- const constant int64_t* batch_strides \- [[buffer(7), function_constant(has_batch)]], \- uint simd_lane_id [[thread_index_in_simdgroup]], \- uint simd_group_id [[simdgroup_index_in_threadgroup]], \- uint3 threadgroup_position [[threadgroup_position_in_grid]], \- uint3 thread_position [[thread_position_in_threadgroup]] \- );--// clang-format off-#define instantiate_gemm_transpose_helper( \- type_name, element_type, block_batch, block_output, block_input, warp_batch, warp_output \-) \- instantiate_gemm(nn, false, false, type_name, element_type, block_batch, block_output, \- block_input, warp_batch, warp_output) \- instantiate_gemm(nt, false, true, type_name, element_type, block_batch, block_output, \- block_input, warp_batch, warp_output) \- instantiate_gemm(tn, true, false, type_name, element_type, block_batch, block_output, \- block_input, warp_batch, warp_output) \- instantiate_gemm(tt, true, true, type_name, element_type, block_batch, block_output, \- block_input, warp_batch, warp_output)-// clang-format on--// clang-format off-#define instantiate_gemm_shapes_helper(type_name, element_type) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 16, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 32, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 64, 16, 1, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 32, 32, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 32, 64, 16, 1, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 32, 32, 16, 2, 2) \- instantiate_gemm_transpose_helper(type_name, element_type, 128, 128, 32, 2, 2) \- /* Small-gemm variant for complex/float32 */ \- instantiate_gemm_transpose_helper(type_name, element_type, 64, 32, 8, 4, 1)-// clang-format on--// Instantiate for float16, bfloat16, and float32-instantiate_gemm_shapes_helper(f16, half);-instantiate_gemm_shapes_helper(bf16, bfloat);-instantiate_gemm_shapes_helper(f32, float);--///////////////////////////////////////////////////////////////////////////////-// Simple GEMM kernel (for smaller matrices or vector operations)-///////////////////////////////////////////////////////////////////////////////--template <typename T>-[[kernel]] void gemv(- const device T* input_a [[buffer(0)]],- const device T* input_b [[buffer(1)]],- device T* output [[buffer(2)]],- constant int& batch [[buffer(3)]],- constant int& output_dim [[buffer(4)]],- constant int& input_dim [[buffer(5)]],- constant int& leading_dimension_a [[buffer(6)]],- constant int& leading_dimension_b [[buffer(7)]],- constant int& leading_dimension_output [[buffer(8)]],- uint2 thread_position [[thread_position_in_grid]],- uint2 grid_size [[threads_per_grid]]-) {- const int row_index = thread_position.y;- const int column_index = thread_position.x;-- if (row_index >= batch || column_index >= output_dim) {- return;- }-- float accumulator = 0.0f;- for (int input_index = 0; input_index < input_dim; input_index++) {- accumulator +=- float(input_a[row_index * leading_dimension_a + input_index]) *- float(input_b[input_index * leading_dimension_b + column_index]);- }-- output[row_index * leading_dimension_output + column_index] = T(accumulator);-}--// Simple GEMV instantiations-template [[host_name("gemv_f16")]] [[kernel]] void gemv<half>(- const device half* input_a [[buffer(0)]],- const device half* input_b [[buffer(1)]],- device half* output [[buffer(2)]],- constant int& batch [[buffer(3)]],- constant int& output_dim [[buffer(4)]],- constant int& input_dim [[buffer(5)]],- constant int& leading_dimension_a [[buffer(6)]],- constant int& leading_dimension_b [[buffer(7)]],- constant int& leading_dimension_output [[buffer(8)]],- uint2 thread_position [[thread_position_in_grid]],- uint2 grid_size [[threads_per_grid]]-);--template [[host_name("gemv_bf16")]] [[kernel]] void gemv<bfloat>(- const device bfloat* input_a [[buffer(0)]],- const device bfloat* input_b [[buffer(1)]],- device bfloat* output [[buffer(2)]],- constant int& batch [[buffer(3)]],- constant int& output_dim [[buffer(4)]],- constant int& input_dim [[buffer(5)]],- constant int& leading_dimension_a [[buffer(6)]],- constant int& leading_dimension_b [[buffer(7)]],- constant int& leading_dimension_output [[buffer(8)]],- uint2 thread_position [[thread_position_in_grid]],- uint2 grid_size [[threads_per_grid]]-);--template [[host_name("gemv_f32")]] [[kernel]] void gemv<float>(- const device float* input_a [[buffer(0)]],- const device float* input_b [[buffer(1)]],- device float* output [[buffer(2)]],- constant int& batch [[buffer(3)]],- constant int& output_dim [[buffer(4)]],- constant int& input_dim [[buffer(5)]],- constant int& leading_dimension_a [[buffer(6)]],- constant int& leading_dimension_b [[buffer(7)]],- constant int& leading_dimension_output [[buffer(8)]],- uint2 thread_position [[thread_position_in_grid]],- uint2 grid_size [[threads_per_grid]]-);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/mod.rs b/crates/uzu/src/backends/metal/kernel/matmul/mod.rsindex 95d9c8adf..fb2a346ad 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/mod.rs@@ -1,13 +1,17 @@mod arguments;+mod gather;mod gemv;mod kernel;mod pipeline;+mod segmented;#[allow(dead_code, clippy::unnecessary_operation, clippy::identity_op)]mod shared_types;mod splitk;mod transpose;pub use arguments::MatmulArguments;+pub use gather::{GatherGemm, GatherMmArguments, GatherMmRhsArguments};pub use gemv::GemvKernel;pub use kernel::MatmulKernel;+pub use segmented::{SegmentedGemm, SegmentedMmArguments};pub use splitk::SplitKGemm;diff --git a/crates/uzu/src/backends/metal/kernel/matmul/segmented.rs b/crates/uzu/src/backends/metal/kernel/matmul/segmented.rsnew file mode 100644index 000000000..8c75a8fed--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/segmented.rs@@ -0,0 +1,309 @@+use std::collections::HashMap;++use metal::{+ Buffer as MTLBuffer, ComputeCommandEncoderRef,+ ComputePipelineState as MTLComputePipelineState, MTLSize,+};++use super::shared_types::GEMMParams;+use crate::{+ DataType,+ backends::metal::{DeviceClass, MTLContext, MTLError},+};++#[derive(Debug, Clone, PartialEq, Eq, Hash)]+struct SegmentedPipelineKey {+ name: String,+ segments_contiguous: bool,+ align_m: bool,+ align_n: bool,+}++#[derive(Debug, Clone)]+pub struct SegmentedMmArguments<'a> {+ pub a: &'a MTLBuffer,+ pub b: &'a MTLBuffer,+ pub segments: &'a MTLBuffer,+ pub out: &'a MTLBuffer,+ pub m: i32,+ pub n: i32,+ pub k: i32,+ pub lda: i32,+ pub ldb: i32,+ /// Grid Z dimension for the segmented kernel (out.size / (M*N) in the reference backend).+ pub batch_size_out: i32,+ pub segments_contiguous: bool,+ pub transpose_a: bool,+ pub transpose_b: bool,+}++pub struct SegmentedGemm {+ data_type: DataType,+ pipelines: HashMap<SegmentedPipelineKey, MTLComputePipelineState>,+}++impl SegmentedGemm {+ pub fn new(data_type: DataType) -> Self {+ Self {+ data_type,+ pipelines: HashMap::new(),+ }+ }++ fn steel_type_name(&self) -> Result<&'static str, MTLError> {+ match self.data_type {+ DataType::F16 => Ok("float16"),+ DataType::BF16 => Ok("bfloat16"),+ DataType::F32 => Ok("float32"),+ other => Err(MTLError::Generic(format!(+ "Unsupported data type for segmented GEMM: {other:?}"+ ))),+ }+ }++ fn device_class_code(mtl: &MTLContext) -> char {+ match mtl.architecture.device_class {+ DeviceClass::Desktop => 'd',+ DeviceClass::Integrated => 'g',+ DeviceClass::Phone => 'p',+ DeviceClass::Unknown(_) => 'g',+ }+ }++ fn select_gemm_tparams(+ device_class: char,+ data_type: DataType,+ transpose_a: bool,+ transpose_b: bool,+ m: i32,+ n: i32,+ k: i32,+ batch_size_out: i32,+ ) -> (i32, i32, i32, i32, i32) {+ // Matches the initialization and tparam selection logic used by the+ // reference backend for segmented GEMM kernels.+ let mut bm = 64;+ let mut bn = 64;+ let mut bk = 16;+ let mut wm = 2;+ let mut wn = 2;++ let is_float32 = matches!(data_type, DataType::F32);+ let work_elements = (batch_size_out as i64) * (m as i64) * (n as i64);++ match device_class {+ 'g' | 'p' => {+ if !transpose_a && transpose_b {+ bm = 64;+ bn = 32;+ bk = 32;+ wm = 2;+ wn = 2;+ } else if !is_float32 {+ bm = 64;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ }+ },+ 'd' => {+ if work_elements >= (1_i64 << 20) {+ if !is_float32 {+ if 2 * std::cmp::max(m, n) > k {+ bm = 64;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ } else if !transpose_a && transpose_b {+ bm = 64;+ bn = 32;+ bk = 32;+ wm = 2;+ wn = 2;+ } else {+ bm = 32;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ }+ }+ } else if !is_float32 {+ if !transpose_a && transpose_b {+ bm = 64;+ bn = 32;+ bk = 32;+ wm = 2;+ wn = 2;+ } else {+ bm = 64;+ bn = 64;+ bk = 16;+ wm = 1;+ wn = 2;+ }+ }+ },+ _ => {},+ }++ (bm, bn, bk, wm, wn)+ }++ fn segmented_kernel_name(+ &self,+ transpose_a: bool,+ transpose_b: bool,+ bm: i32,+ bn: i32,+ bk: i32,+ wm: i32,+ wn: i32,+ ) -> Result<String, MTLError> {+ let tname = format!(+ "{}{}",+ if transpose_a {+ 't'+ } else {+ 'n'+ },+ if transpose_b {+ 't'+ } else {+ 'n'+ }+ );+ let dtype = self.steel_type_name()?;+ Ok(format!(+ "steel_segmented_mm_{tname}_{dtype}_{dtype}_bm{bm}_bn{bn}_bk{bk}_wm{wm}_wn{wn}"+ ))+ }++ fn get_or_compile_pipeline(+ &mut self,+ mtl: &MTLContext,+ name: &str,+ segments_contiguous: bool,+ align_m: bool,+ align_n: bool,+ ) -> Result<&MTLComputePipelineState, MTLError> {+ let key = SegmentedPipelineKey {+ name: name.to_string(),+ segments_contiguous,+ align_m,+ align_n,+ };++ if !self.pipelines.contains_key(&key) {+ let fcv = metal::FunctionConstantValues::new();+ fcv.set_constant_value_at_index(+ &segments_contiguous as *const bool as *const _,+ metal::MTLDataType::Bool,+ 199,+ );+ fcv.set_constant_value_at_index(+ &align_m as *const bool as *const _,+ metal::MTLDataType::Bool,+ 200,+ );+ fcv.set_constant_value_at_index(+ &align_n as *const bool as *const _,+ metal::MTLDataType::Bool,+ 201,+ );++ let cache_key = format!(+ "{name}_sc{}_am{}_an{}",+ segments_contiguous as u8, align_m as u8, align_n as u8+ );+ let (ps, _) = mtl.compute_pipeline_state_with_reflection_cached(+ &cache_key,+ name,+ Some(&fcv),+ )?;+ self.pipelines.insert(key.clone(), ps);+ }++ Ok(self.pipelines.get(&key).unwrap())+ }++ pub fn encode(+ &mut self,+ mtl: &MTLContext,+ enc: &ComputeCommandEncoderRef,+ args: &SegmentedMmArguments,+ ) -> Result<(), MTLError> {+ let device_class = Self::device_class_code(mtl);+ let (bm, bn, bk, wm, wn) = Self::select_gemm_tparams(+ device_class,+ self.data_type,+ args.transpose_a,+ args.transpose_b,+ args.m,+ args.n,+ args.k,+ args.batch_size_out,+ );++ let align_m = (args.m % bm) == 0;+ let align_n = (args.n % bn) == 0;++ let kname = self.segmented_kernel_name(+ args.transpose_a,+ args.transpose_b,+ bm,+ bn,+ bk,+ wm,+ wn,+ )?;+ let ps = self.get_or_compile_pipeline(+ mtl,+ &kname,+ args.segments_contiguous,+ align_m,+ align_n,+ )?;++ enc.set_compute_pipeline_state(ps);+ enc.set_buffer(0, Some(args.a), 0);+ enc.set_buffer(1, Some(args.b), 0);+ enc.set_buffer(2, Some(args.segments), 0);+ enc.set_buffer(3, Some(args.out), 0);++ let tiles_n = (args.n + bn - 1) / bn;+ let tiles_m = (args.m + bm - 1) / bm;+ let params = GEMMParams {+ M: args.m,+ N: args.n,+ K: args.k,+ lda: args.lda,+ ldb: args.ldb,+ ldd: args.n,+ tiles_n,+ tiles_m,+ batch_stride_a: 0,+ batch_stride_b: 0,+ batch_stride_d: (args.m as i64) * (args.n as i64),+ swizzle_log: 0,+ gemm_k_iterations_aligned: 0,+ batch_ndim: 0,+ };+ enc.set_bytes(+ 4,+ std::mem::size_of::<GEMMParams>() as u64,+ ¶ms as *const GEMMParams as *const _,+ );++ let threads_per_tg = MTLSize::new(32, wn as u64, wm as u64);+ let tgs = MTLSize::new(+ tiles_n as u64,+ tiles_m as u64,+ args.batch_size_out as u64,+ );+ enc.dispatch_thread_groups(tgs, threads_per_tg);+ Ok(())+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.hindex 1cb70950d..df88ff96c 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h+++ b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.h@@ -20,18 +20,14 @@ namespace matmul {#endif///////////////////////////////////////////////////////////////////////////////-// GEMM Parameters+// GEMM Parameters (mirrors steel/gemm/params.h, but C-compatible)///////////////////////////////////////////////////////////////////////////////-/// Parameters for the main GEMM kernel.-/// Layout: 8 x int32, 3 x int64, 2 x int32 = 64 bytes total+// Main GEMM parametersstruct GEMMParams {- /// M dimension - batch/number of tokens (rows of A, rows of D)- int batch;- /// N dimension - output_dim (cols of B, cols of D)- int output_dim;- /// K dimension - input_dim/reduction dimension (cols of A, rows of B)- int input_dim;+ int M;+ int N;+ int K;int lda;int ldb;@@ -50,7 +46,27 @@ struct GEMMParams {int batch_ndim;};-/// Parameters for addmm (alpha * A @ B + beta * C) operations+// Split-K GEMM parameters+struct GEMMSpiltKParams {+ int M;+ int N;+ int K;++ int lda;+ int ldb;+ int ldc;++ int tiles_n;+ int tiles_m;++ int split_k_partitions;+ int split_k_partition_stride;+ int split_k_partition_size;++ int gemm_k_iterations_aligned;+};++// AddMM parameters (alpha * A @ B + beta * C)struct GEMMAddMMParams {int ldc;int fdc;@@ -61,24 +77,6 @@ struct GEMMAddMMParams {float beta;};-struct SplitKGEMMParams {- int m;- int n;- int k;-- int leading_dim_a;- int leading_dim_b;- int leading_dim_accumulator;-- int tile_count_n;- int tile_count_m;-- int partition_count;- int output_elements_per_partition;- int k_elements_per_partition;- int gemm_k_iterations_aligned;-};-// Close Metal namespace#ifdef __METAL_VERSION__} // namespace matmuldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rsindex 4dddb9938..4867fb47e 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/shared_types.rs@@ -1,15 +1,11 @@/* automatically generated by rust-bindgen 0.72.1 */-#[doc = " Parameters for the main GEMM kernel.\n Layout: 8 x int32, 3 x int64, 2 x int32 = 64 bytes total"]#[repr(C)]#[derive(Debug, Default, Copy, Clone)]pub struct GEMMParams {- #[doc = " M dimension - batch/number of tokens (rows of A, rows of D)"]- pub batch: ::core::ffi::c_int,- #[doc = " N dimension - output_dim (cols of B, cols of D)"]- pub output_dim: ::core::ffi::c_int,- #[doc = " K dimension - input_dim/reduction dimension (cols of A, rows of B)"]- pub input_dim: ::core::ffi::c_int,+ pub M: ::core::ffi::c_int,+ pub N: ::core::ffi::c_int,+ pub K: ::core::ffi::c_int,pub lda: ::core::ffi::c_int,pub ldb: ::core::ffi::c_int,pub ldd: ::core::ffi::c_int,@@ -26,12 +22,12 @@ pub struct GEMMParams {const _: () = {["Size of GEMMParams"][::core::mem::size_of::<GEMMParams>() - 72usize];["Alignment of GEMMParams"][::core::mem::align_of::<GEMMParams>() - 8usize];- ["Offset of field: GEMMParams::batch"]- [::core::mem::offset_of!(GEMMParams, batch) - 0usize];- ["Offset of field: GEMMParams::output_dim"]- [::core::mem::offset_of!(GEMMParams, output_dim) - 4usize];- ["Offset of field: GEMMParams::input_dim"]- [::core::mem::offset_of!(GEMMParams, input_dim) - 8usize];+ ["Offset of field: GEMMParams::M"]+ [::core::mem::offset_of!(GEMMParams, M) - 0usize];+ ["Offset of field: GEMMParams::N"]+ [::core::mem::offset_of!(GEMMParams, N) - 4usize];+ ["Offset of field: GEMMParams::K"]+ [::core::mem::offset_of!(GEMMParams, K) - 8usize];["Offset of field: GEMMParams::lda"][::core::mem::offset_of!(GEMMParams, lda) - 12usize];["Offset of field: GEMMParams::ldb"]@@ -57,7 +53,63 @@ const _: () = {["Offset of field: GEMMParams::batch_ndim"][::core::mem::offset_of!(GEMMParams, batch_ndim) - 64usize];};-#[doc = " Parameters for addmm (alpha * A @ B + beta * C) operations"]+#[repr(C)]+#[derive(Debug, Default, Copy, Clone)]+pub struct GEMMSpiltKParams {+ pub M: ::core::ffi::c_int,+ pub N: ::core::ffi::c_int,+ pub K: ::core::ffi::c_int,+ pub lda: ::core::ffi::c_int,+ pub ldb: ::core::ffi::c_int,+ pub ldc: ::core::ffi::c_int,+ pub tiles_n: ::core::ffi::c_int,+ pub tiles_m: ::core::ffi::c_int,+ pub split_k_partitions: ::core::ffi::c_int,+ pub split_k_partition_stride: ::core::ffi::c_int,+ pub split_k_partition_size: ::core::ffi::c_int,+ pub gemm_k_iterations_aligned: ::core::ffi::c_int,+}+#[allow(clippy::unnecessary_operation, clippy::identity_op)]+const _: () = {+ ["Size of GEMMSpiltKParams"]+ [::core::mem::size_of::<GEMMSpiltKParams>() - 48usize];+ ["Alignment of GEMMSpiltKParams"]+ [::core::mem::align_of::<GEMMSpiltKParams>() - 4usize];+ ["Offset of field: GEMMSpiltKParams::M"]+ [::core::mem::offset_of!(GEMMSpiltKParams, M) - 0usize];+ ["Offset of field: GEMMSpiltKParams::N"]+ [::core::mem::offset_of!(GEMMSpiltKParams, N) - 4usize];+ ["Offset of field: GEMMSpiltKParams::K"]+ [::core::mem::offset_of!(GEMMSpiltKParams, K) - 8usize];+ ["Offset of field: GEMMSpiltKParams::lda"]+ [::core::mem::offset_of!(GEMMSpiltKParams, lda) - 12usize];+ ["Offset of field: GEMMSpiltKParams::ldb"]+ [::core::mem::offset_of!(GEMMSpiltKParams, ldb) - 16usize];+ ["Offset of field: GEMMSpiltKParams::ldc"]+ [::core::mem::offset_of!(GEMMSpiltKParams, ldc) - 20usize];+ ["Offset of field: GEMMSpiltKParams::tiles_n"]+ [::core::mem::offset_of!(GEMMSpiltKParams, tiles_n) - 24usize];+ ["Offset of field: GEMMSpiltKParams::tiles_m"]+ [::core::mem::offset_of!(GEMMSpiltKParams, tiles_m) - 28usize];+ ["Offset of field: GEMMSpiltKParams::split_k_partitions"][::core::mem::offset_of!(+ GEMMSpiltKParams,+ split_k_partitions+ ) - 32usize];+ ["Offset of field: GEMMSpiltKParams::split_k_partition_stride"][::core::mem::offset_of!(+ GEMMSpiltKParams,+ split_k_partition_stride+ )+ - 36usize];+ ["Offset of field: GEMMSpiltKParams::split_k_partition_size"][::core::mem::offset_of!(+ GEMMSpiltKParams,+ split_k_partition_size+ ) - 40usize];+ ["Offset of field: GEMMSpiltKParams::gemm_k_iterations_aligned"][::core::mem::offset_of!(+ GEMMSpiltKParams,+ gemm_k_iterations_aligned+ )+ - 44usize];+};#[repr(C)]#[derive(Debug, Default, Copy, Clone)]pub struct GEMMAddMMParams {@@ -84,61 +136,3 @@ const _: () = {["Offset of field: GEMMAddMMParams::beta"][::core::mem::offset_of!(GEMMAddMMParams, beta) - 20usize];};-#[repr(C)]-#[derive(Debug, Default, Copy, Clone)]-pub struct SplitKGEMMParams {- pub m: ::core::ffi::c_int,- pub n: ::core::ffi::c_int,- pub k: ::core::ffi::c_int,- pub leading_dim_a: ::core::ffi::c_int,- pub leading_dim_b: ::core::ffi::c_int,- pub leading_dim_accumulator: ::core::ffi::c_int,- pub tile_count_n: ::core::ffi::c_int,- pub tile_count_m: ::core::ffi::c_int,- pub partition_count: ::core::ffi::c_int,- pub output_elements_per_partition: ::core::ffi::c_int,- pub k_elements_per_partition: ::core::ffi::c_int,- pub gemm_k_iterations_aligned: ::core::ffi::c_int,-}-#[allow(clippy::unnecessary_operation, clippy::identity_op)]-const _: () = {- ["Size of SplitKGEMMParams"]- [::core::mem::size_of::<SplitKGEMMParams>() - 48usize];- ["Alignment of SplitKGEMMParams"]- [::core::mem::align_of::<SplitKGEMMParams>() - 4usize];- ["Offset of field: SplitKGEMMParams::m"]- [::core::mem::offset_of!(SplitKGEMMParams, m) - 0usize];- ["Offset of field: SplitKGEMMParams::n"]- [::core::mem::offset_of!(SplitKGEMMParams, n) - 4usize];- ["Offset of field: SplitKGEMMParams::k"]- [::core::mem::offset_of!(SplitKGEMMParams, k) - 8usize];- ["Offset of field: SplitKGEMMParams::leading_dim_a"]- [::core::mem::offset_of!(SplitKGEMMParams, leading_dim_a) - 12usize];- ["Offset of field: SplitKGEMMParams::leading_dim_b"]- [::core::mem::offset_of!(SplitKGEMMParams, leading_dim_b) - 16usize];- ["Offset of field: SplitKGEMMParams::leading_dim_accumulator"][::core::mem::offset_of!(- SplitKGEMMParams,- leading_dim_accumulator- ) - 20usize];- ["Offset of field: SplitKGEMMParams::tile_count_n"]- [::core::mem::offset_of!(SplitKGEMMParams, tile_count_n) - 24usize];- ["Offset of field: SplitKGEMMParams::tile_count_m"]- [::core::mem::offset_of!(SplitKGEMMParams, tile_count_m) - 28usize];- ["Offset of field: SplitKGEMMParams::partition_count"]- [::core::mem::offset_of!(SplitKGEMMParams, partition_count) - 32usize];- ["Offset of field: SplitKGEMMParams::output_elements_per_partition"][::core::mem::offset_of!(- SplitKGEMMParams,- output_elements_per_partition- )- - 36usize];- ["Offset of field: SplitKGEMMParams::k_elements_per_partition"][::core::mem::offset_of!(- SplitKGEMMParams,- k_elements_per_partition- )- - 40usize];- ["Offset of field: SplitKGEMMParams::gemm_k_iterations_aligned"][::core::mem::offset_of!(- SplitKGEMMParams,- gemm_k_iterations_aligned- )- - 44usize];-};diff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal b/crates/uzu/src/backends/metal/kernel/matmul/splitk.metaldeleted file mode 100644index a1f7f7edf..000000000--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.metal+++ /dev/null@@ -1,475 +0,0 @@-// Split-K GEMM: partitions K dimension across threadgroups for better-// parallelism on small M*N with large K.--#include <metal_stdlib>-#include "gemm.h"--using namespace metal;-using namespace uzu::matmul;--///////////////////////////////////////////////////////////////////////////////-// Split-K Partial GEMM Kernel-///////////////////////////////////////////////////////////////////////////////--template <- typename InputType,- typename AccumulatorType,- int TileRows,- int TileCols,- int TileDepth,- int WarpsPerRow,- int WarpsPerCol,- bool TransposeA,- bool TransposeB,- bool MNAligned,- bool KAligned>-[[kernel, max_total_threads_per_threadgroup(WarpsPerRow * WarpsPerCol * 32)]]-void splitk_partial_gemm(- const device InputType* input_a [[buffer(0)]],- const device InputType* input_b [[buffer(1)]],- device AccumulatorType* accumulator [[buffer(2)]],- const constant SplitKGEMMParams* params [[buffer(3)]],- uint simd_lane_id [[thread_index_in_simdgroup]],- uint simd_group_id [[simdgroup_index_in_threadgroup]],- uint3 threadgroup_id [[threadgroup_position_in_grid]],- uint3 thread_id [[thread_position_in_threadgroup]]-) {- (void)thread_id;-- using gemm_kernel = GEMMKernel<- InputType,- AccumulatorType,- TileRows,- TileCols,- TileDepth,- WarpsPerRow,- WarpsPerCol,- TransposeA,- TransposeB,- MNAligned,- KAligned,- AccumulatorType>;-- using loader_a_t = typename gemm_kernel::loader_a_t;- using loader_b_t = typename gemm_kernel::loader_b_t;- using mma_t = typename gemm_kernel::mma_t;-- threadgroup InputType shared_a[gemm_kernel::tgp_mem_size_a];- threadgroup InputType shared_b[gemm_kernel::tgp_mem_size_b];-- const int tile_x = threadgroup_id.x;- const int tile_y = threadgroup_id.y;- const int partition_index = threadgroup_id.z;-- if (params->tile_count_n <= tile_x || params->tile_count_m <= tile_y) {- return;- }-- const int output_row = tile_y * TileRows;- const int output_col = tile_x * TileCols;- const int k_partition_start =- params->k_elements_per_partition * partition_index;-- const size_t output_row_long = size_t(output_row);- const size_t output_col_long = size_t(output_col);- const size_t k_start_long = size_t(k_partition_start);-- const device InputType* a_ptr = input_a;- const device InputType* b_ptr = input_b;-- a_ptr += TransposeA- ? (output_row_long + k_start_long * params->leading_dim_a)- : (k_start_long + output_row_long * params->leading_dim_a);- b_ptr += TransposeB- ? (k_start_long + output_col_long * params->leading_dim_b)- : (output_col_long + k_start_long * params->leading_dim_b);-- device AccumulatorType* output_ptr =- accumulator +- (size_t(params->output_elements_per_partition) * partition_index) +- (output_row_long * params->leading_dim_accumulator + output_col_long);-- thread loader_a_t loader_a(- a_ptr,- params->leading_dim_a,- shared_a,- simd_group_id,- simd_lane_id- );- thread loader_b_t loader_b(- b_ptr,- params->leading_dim_b,- shared_b,- simd_group_id,- simd_lane_id- );- thread mma_t mma_op(simd_group_id, simd_lane_id);-- int gemm_k_iterations = params->gemm_k_iterations_aligned;-- short tile_bound_m = min(TileRows, params->m - output_row);- short tile_bound_n = min(TileCols, params->n - output_col);- short leftover_k = params->k % TileDepth;-- const bool is_last_partition =- (partition_index + 1) == params->partition_count;-- if (MNAligned || (tile_bound_m == TileRows && tile_bound_n == TileCols)) {- gemm_kernel::gemm_loop(- shared_a,- shared_b,- gemm_k_iterations,- loader_a,- loader_b,- mma_op,- tile_bound_m,- tile_bound_n,- leftover_k,- LoopAlignment<true, true, true>{}- );- } else if (tile_bound_n == TileCols) {- gemm_kernel::gemm_loop(- shared_a,- shared_b,- gemm_k_iterations,- loader_a,- loader_b,- mma_op,- tile_bound_m,- tile_bound_n,- leftover_k,- LoopAlignment<false, true, true>{}- );- } else if (tile_bound_m == TileRows) {- gemm_kernel::gemm_loop(- shared_a,- shared_b,- gemm_k_iterations,- loader_a,- loader_b,- mma_op,- tile_bound_m,- tile_bound_n,- leftover_k,- LoopAlignment<true, false, true>{}- );- } else {- gemm_kernel::gemm_loop(- shared_a,- shared_b,- gemm_k_iterations,- loader_a,- loader_b,- mma_op,- tile_bound_m,- tile_bound_n,- leftover_k,- LoopAlignment<false, false, true>{}- );- }-- threadgroup_barrier(mem_flags::mem_threadgroup);-- if (is_last_partition) {- int remaining_k_iterations =- (params->k - (k_partition_start + params->k_elements_per_partition)) /- TileDepth;- if (!KAligned || remaining_k_iterations > 0) {- gemm_kernel::gemm_loop(- shared_a,- shared_b,- remaining_k_iterations,- loader_a,- loader_b,- mma_op,- tile_bound_m,- tile_bound_n,- leftover_k,- LoopAlignment<false, false, KAligned>{}- );- }- }-- if (MNAligned || (tile_bound_m == TileRows && tile_bound_n == TileCols)) {- mma_op.store_result(output_ptr, params->leading_dim_accumulator);- } else {- mma_op.store_result_safe(- output_ptr,- params->leading_dim_accumulator,- short2(tile_bound_n, tile_bound_m)- );- }-}--///////////////////////////////////////////////////////////////////////////////-// Split-K Accumulation Kernel-///////////////////////////////////////////////////////////////////////////////--template <typename OutputType, typename AccumulatorType>-[[kernel]] void splitk_accumulate(- const device AccumulatorType* partitioned_accumulator [[buffer(0)]],- device OutputType* output [[buffer(1)]],- constant int& partition_count [[buffer(2)]],- constant int& output_elements_per_partition [[buffer(3)]],- constant int& leading_dim_output [[buffer(4)]],- uint2 thread_position [[thread_position_in_grid]]-) {- const size_t col = thread_position.x;- const size_t row = thread_position.y;-- output += col + row * size_t(leading_dim_output);- partitioned_accumulator += col + row * size_t(leading_dim_output);-- AccumulatorType sum = AccumulatorType(0);- size_t partition_offset = 0;-- for (int i = 0; i < partition_count; i++) {- sum += partitioned_accumulator[partition_offset];- partition_offset += output_elements_per_partition;- }-- output[0] = OutputType(sum);-}--template <typename OutputType, typename AccumulatorType>-[[kernel]] void splitk_accumulate_axpby(- const device AccumulatorType* partitioned_accumulator [[buffer(0)]],- device OutputType* output [[buffer(1)]],- constant int& partition_count [[buffer(2)]],- constant int& output_elements_per_partition [[buffer(3)]],- constant int& leading_dim_output [[buffer(4)]],- const device OutputType* bias_source [[buffer(5)]],- constant int& ldc [[buffer(6)]],- constant int& fdc [[buffer(7)]],- constant float& alpha [[buffer(8)]],- constant float& beta [[buffer(9)]],- uint2 thread_position [[thread_position_in_grid]]-) {- const size_t col = thread_position.x;- const size_t row = thread_position.y;-- bias_source += col * size_t(fdc) + row * size_t(ldc);- output += col + row * size_t(leading_dim_output);- partitioned_accumulator += col + row * size_t(leading_dim_output);-- AccumulatorType sum = AccumulatorType(0);- size_t partition_offset = 0;-- for (int i = 0; i < partition_count; i++) {- sum += partitioned_accumulator[partition_offset];- partition_offset += output_elements_per_partition;- }-- output[0] = OutputType(alpha * sum + beta * AccumulatorType(*bias_source));-}--///////////////////////////////////////////////////////////////////////////////-// Kernel Instantiation-///////////////////////////////////////////////////////////////////////////////--#define INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col, \- mn_aligned, \- k_aligned \-) \- template [[host_name( \- "splitk_partial_" #transpose_name "_" #type_name "_tm" #tile_rows \- "_tn" #tile_cols "_tk" #tile_depth "_wm" #warps_row "_wn" #warps_col \- "_mn" #mn_aligned "_k" #k_aligned \- )]] [[kernel]] void \- splitk_partial_gemm< \- input_type, \- float, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col, \- transpose_a, \- transpose_b, \- mn_aligned, \- k_aligned>( \- const device input_type* input_a [[buffer(0)]], \- const device input_type* input_b [[buffer(1)]], \- device float* accumulator [[buffer(2)]], \- const constant SplitKGEMMParams* params [[buffer(3)]], \- uint simd_lane_id [[thread_index_in_simdgroup]], \- uint simd_group_id [[simdgroup_index_in_threadgroup]], \- uint3 threadgroup_id [[threadgroup_position_in_grid]], \- uint3 thread_id [[thread_position_in_threadgroup]] \- );--#define INSTANTIATE_SPLITK_PARTIAL( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col \-) \- INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col, \- 0, \- 0 \- ) \- INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col, \- 1, \- 0 \- ) \- INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col, \- 0, \- 1 \- ) \- INSTANTIATE_SPLITK_PARTIAL_ALIGNED( \- transpose_name, \- transpose_a, \- transpose_b, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col, \- 1, \- 1 \- )--#define INSTANTIATE_SPLITK_TRANSPOSE_HELPER( \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col \-) \- INSTANTIATE_SPLITK_PARTIAL( \- nn, \- false, \- false, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col \- ) \- INSTANTIATE_SPLITK_PARTIAL( \- nt, \- false, \- true, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col \- ) \- INSTANTIATE_SPLITK_PARTIAL( \- tn, \- true, \- false, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col \- ) \- INSTANTIATE_SPLITK_PARTIAL( \- tt, \- true, \- true, \- type_name, \- input_type, \- tile_rows, \- tile_cols, \- tile_depth, \- warps_row, \- warps_col \- )--#define INSTANTIATE_SPLITK_SHAPES_HELPER(type_name, input_type) \- INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 16, 16, 16, 2, 2) \- INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 16, 32, 16, 2, 2) \- INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 32, 16, 16, 2, 2) \- INSTANTIATE_SPLITK_TRANSPOSE_HELPER(type_name, input_type, 32, 32, 16, 2, 2)--INSTANTIATE_SPLITK_SHAPES_HELPER(f16, half)-INSTANTIATE_SPLITK_SHAPES_HELPER(bf16, bfloat)-INSTANTIATE_SPLITK_SHAPES_HELPER(f32, float)--#define INSTANTIATE_SPLITK_ACCUM(type_name, output_type) \- template [[host_name("splitk_accum_" #type_name)]] [[kernel]] void \- splitk_accumulate<output_type, float>( \- const device float* partitioned_accumulator [[buffer(0)]], \- device output_type* output [[buffer(1)]], \- constant int& partition_count [[buffer(2)]], \- constant int& output_elements_per_partition [[buffer(3)]], \- constant int& leading_dim_output [[buffer(4)]], \- uint2 thread_position [[thread_position_in_grid]] \- ); \- template [[host_name("splitk_accum_" #type_name "_axpby")]] [[kernel]] void \- splitk_accumulate_axpby<output_type, float>( \- const device float* partitioned_accumulator [[buffer(0)]], \- device output_type* output [[buffer(1)]], \- constant int& partition_count [[buffer(2)]], \- constant int& output_elements_per_partition [[buffer(3)]], \- constant int& leading_dim_output [[buffer(4)]], \- const device output_type* bias_source [[buffer(5)]], \- constant int& ldc [[buffer(6)]], \- constant int& fdc [[buffer(7)]], \- constant float& alpha [[buffer(8)]], \- constant float& beta [[buffer(9)]], \- uint2 thread_position [[thread_position_in_grid]] \- );--INSTANTIATE_SPLITK_ACCUM(f16, half)-INSTANTIATE_SPLITK_ACCUM(bf16, bfloat)-INSTANTIATE_SPLITK_ACCUM(f32, float)diff --git a/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs b/crates/uzu/src/backends/metal/kernel/matmul/splitk.rsindex 13aecacba..b55e4e6b0 100644--- a/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs+++ b/crates/uzu/src/backends/metal/kernel/matmul/splitk.rs@@ -5,7 +5,10 @@ use metal::{MTLSize,};-use super::{arguments::MatmulArguments, shared_types::SplitKGEMMParams};+use super::{+ arguments::MatmulArguments,+ shared_types::GEMMSpiltKParams as SplitKGEMMParams,+};use crate::{DataType,backends::metal::{MTLContext, MTLError},@@ -50,11 +53,11 @@ impl SplitKGemm {}}- fn type_suffix(&self) -> Result<&'static str, MTLError> {+ fn steel_type_name(&self) -> Result<&'static str, MTLError> {match self.data_type {- DataType::F16 => Ok("f16"),- DataType::BF16 => Ok("bf16"),- DataType::F32 => Ok("f32"),+ DataType::F16 => Ok("float16"),+ DataType::BF16 => Ok("bfloat16"),+ DataType::F32 => Ok("float32"),_ => Err(MTLError::Generic(format!("Unsupported dtype for Split-K: {:?}",self.data_type@@ -62,6 +65,12 @@ impl SplitKGemm {}}+ fn splitk_partial_out_name(&self) -> &'static str {+ // In steel_gemm_splitk.metal, float16/bfloat16/float32 partial outputs+ // are accumulated into float32.+ "float32"+ }+fn transpose_suffix(&self) -> &'static str {match (self.transpose_a, self.transpose_b) {(false, false) => "nn",@@ -77,25 +86,41 @@ impl SplitKGemm {mn_aligned: bool,k_aligned: bool,) -> Result<String, MTLError> {- let type_suffix = self.type_suffix()?;+ let in_name = self.steel_type_name()?;+ let out_name = self.splitk_partial_out_name();let transpose_suffix = self.transpose_suffix();+ let mn_tag = if mn_aligned {+ "taligned"+ } else {+ "naligned"+ };+ let k_tag = if k_aligned {+ "taligned"+ } else {+ "naligned"+ };Ok(format!(- "splitk_partial_{}_{}_tm{}_tn{}_tk{}_wm{}_wn{}_mn{}_k{}",+ "steel_gemm_splitk_{}_{}_{}_bm{}_bn{}_bk{}_wm{}_wn{}_MN_{}_K_{}",transpose_suffix,- type_suffix,+ in_name,+ out_name,config.tile_rows,config.tile_cols,config.tile_depth,config.warps_per_row,config.warps_per_col,- mn_aligned as u8,- k_aligned as u8,+ mn_tag,+ k_tag,))}fn accum_kernel_name(&self) -> Result<String, MTLError> {- let type_suffix = self.type_suffix()?;- Ok(format!("splitk_accum_{}", type_suffix))+ let out_name = self.steel_type_name()?;+ Ok(format!(+ "steel_gemm_splitk_accum_{}_{}",+ out_name,+ self.splitk_partial_out_name()+ ))}fn get_partial_pipeline(@@ -221,17 +246,17 @@ impl SplitKGemm {);let params = SplitKGEMMParams {- m,- n,- k,- leading_dim_a: args.lda,- leading_dim_b: args.ldb,- leading_dim_accumulator: n,- tile_count_n,- tile_count_m,- partition_count,- output_elements_per_partition,- k_elements_per_partition,+ M: m,+ N: n,+ K: k,+ lda: args.lda,+ ldb: args.ldb,+ ldc: n,+ tiles_n: tile_count_n,+ tiles_m: tile_count_m,+ split_k_partitions: partition_count,+ split_k_partition_stride: output_elements_per_partition,+ split_k_partition_size: k_elements_per_partition,gemm_k_iterations_aligned: gemm_k_iterations,};diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/defines.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/defines.hnew file mode 100644index 000000000..3904dd6dd--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/defines.h@@ -0,0 +1,7 @@+++#pragma once++#define STEEL_CONST static constant constexpr const+#define STEEL_PRAGMA_UNROLL _Pragma("clang loop unroll(full)")+#define STEEL_PRAGMA_NO_UNROLL _Pragma("clang loop unroll(disable)")diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/gemm.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/gemm.hnew file mode 100644index 000000000..52c46c46e--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/gemm.h@@ -0,0 +1,293 @@+++#pragma once++#include "loader.h"+#include "mma.h"+#include "params.h"+#include "transforms.h"+#include "../utils.h"++using namespace metal;++///////////////////////////////////////////////////////////////////////////////+// GEMM kernel class+///////////////////////////////////////////////////////////////////////////////++namespace steel {++template <bool M_aligned, bool N_aligned, bool K_aligned>+struct LoopAlignment {};++template <+ typename T,+ typename U,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ bool MN_aligned,+ bool K_aligned,+ typename AccumType = typename AccumHelper<T>::accum_type,+ typename Epilogue = TransformNone<U, AccumType>>+struct GEMMKernel {+ STEEL_CONST short tgp_padding_a = 16 / sizeof(T);+ STEEL_CONST short tgp_padding_b = 16 / sizeof(T);+ STEEL_CONST short tgp_mem_size_a =+ transpose_a ? BK * (BM + tgp_padding_a) : BM * (BK + tgp_padding_a);+ STEEL_CONST short tgp_mem_size_b =+ transpose_b ? BN * (BK + tgp_padding_b) : BK * (BN + tgp_padding_b);+ STEEL_CONST short tgp_mem_size = tgp_mem_size_a + tgp_mem_size_b;++ STEEL_CONST short tgp_size = WM * WN * 32;++ using loader_a_t = BlockLoader<+ T,+ transpose_a ? BK : BM,+ transpose_a ? BM : BK,+ transpose_a ? BM + tgp_padding_a : BK + tgp_padding_a,+ !transpose_a,+ tgp_size>;+ using loader_b_t = BlockLoader<+ T,+ transpose_b ? BN : BK,+ transpose_b ? BK : BN,+ transpose_b ? BK + tgp_padding_b : BN + tgp_padding_b,+ transpose_b,+ tgp_size>;+ using mma_t = BlockMMA<+ T,+ U,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ transpose_a ? BM + tgp_padding_a : BK + tgp_padding_a,+ transpose_b ? BK + tgp_padding_b : BN + tgp_padding_b,+ AccumType,+ Epilogue>;++ /* Main kernel function */+ template <bool M_aligned, bool N_aligned, bool K_aligned_>+ static METAL_FUNC void gemm_loop(+ threadgroup T* As [[threadgroup(0)]],+ threadgroup T* Bs [[threadgroup(1)]],+ const int gemm_k_iterations,+ thread loader_a_t& loader_a,+ thread loader_b_t& loader_b,+ thread mma_t& mma_op,+ thread const short& tgp_bm,+ thread const short& tgp_bn,+ thread const short& lbk,+ LoopAlignment<M_aligned, N_aligned, K_aligned_> l = {}) {+ // Appease the compiler+ (void)l;++ short2 tile_dims_A = transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm);++ short2 tile_dims_B = transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK);++ for (int k = 0; k < gemm_k_iterations; k++) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ // Load elements into threadgroup+ if (M_aligned) {+ loader_a.load_unsafe();+ } else {+ loader_a.load_safe(tile_dims_A);+ }++ if (N_aligned) {+ loader_b.load_unsafe();+ } else {+ loader_b.load_safe(tile_dims_B);+ }++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }++ if (!K_aligned_) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ short2 tile_dims_A_last =+ transpose_a ? short2(tgp_bm, lbk) : short2(lbk, tgp_bm);+ short2 tile_dims_B_last =+ transpose_b ? short2(lbk, tgp_bn) : short2(tgp_bn, lbk);++ loader_a.load_safe(tile_dims_A_last);+ loader_b.load_safe(tile_dims_B_last);++ threadgroup_barrier(mem_flags::mem_threadgroup);++ mma_op.mma(As, Bs);+ }+ }++ /* Main kernel function */+ static METAL_FUNC void run(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ device U* D [[buffer(2)]],+ const constant GEMMParams* params [[buffer(3)]],+ threadgroup T* As [[threadgroup(0)]],+ threadgroup T* Bs [[threadgroup(1)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]]) {+ // Pacifying compiler+ (void)lid;++ const int tid_y = ((tid.y) << params->swizzle_log) ++ ((tid.x) & ((1 << params->swizzle_log) - 1));+ const int tid_x = (tid.x) >> params->swizzle_log;++ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {+ return;+ }++ threadgroup_barrier(mem_flags::mem_none);++ // Find block in A, B, C+ const int c_row = tid_y * BM;+ const int c_col = tid_x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ D += c_row_long * params->ldd + c_col_long;++ // Prepare threadgroup loading operations+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);++ // Prepare threadgroup mma operation+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ int gemm_k_iterations = params->gemm_k_iterations_aligned;++ ///////////////////////////////////////////////////////////////////////////////+ // MNK aligned loop+ if (MN_aligned) {+ for (int k = 0; k < gemm_k_iterations; k++) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }++ threadgroup_barrier(mem_flags::mem_none);++ // Loop tail+ if (!K_aligned) {+ int lbk = params->K - params->gemm_k_iterations_aligned * BK;+ short2 tile_dims_A = transpose_a ? short2(BM, lbk) : short2(lbk, BM);+ short2 tile_dims_B = transpose_b ? short2(lbk, BN) : short2(BN, lbk);++ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);++ threadgroup_barrier(mem_flags::mem_threadgroup);++ mma_op.mma(As, Bs);+ }++ // Store results to device memory+ mma_op.store_result(D, params->ldd);+ return;++ }+ ///////////////////////////////////////////////////////////////////////////////+ // MN unaligned loop+ else { // Loop over K - unaligned case+ short tgp_bm = min(BM, params->M - c_row);+ short tgp_bn = min(BN, params->N - c_col);+ short leftover_bk = params->K - params->gemm_k_iterations_aligned * BK;++ if (tgp_bm == BM && tgp_bn == BN) {+ gemm_loop<true, true, K_aligned>(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk);++ mma_op.store_result(D, params->ldd);+ return;++ } else if (tgp_bn == BN) {+ gemm_loop<false, true, K_aligned>(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk);++ mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));+ return;++ } else if (tgp_bm == BM) {+ gemm_loop<true, false, K_aligned>(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk);++ mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));+ return;++ } else {+ gemm_loop<false, false, K_aligned>(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk);++ mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));+ return;+ }+ }+ }+};++} // namespace steel\ No newline at end of filediff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/gemm_nax.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/gemm_nax.hnew file mode 100644index 000000000..cb836ac78--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/gemm_nax.h@@ -0,0 +1,156 @@+++#pragma once++#include "nax.h"+#include "params.h"+#include "transforms.h"+#include "../utils.h"++using namespace metal;++namespace steel {++template <+ typename T,+ short SM,+ short SN,+ short SK,+ short BK,+ bool transpose_a,+ bool transpose_b,+ bool kAlignedM,+ bool kAlignedN,+ bool kAlignedK,+ short UM,+ short UN,+ short UK,+ typename AccumType = float>+auto gemm_loop(+ const device T* A,+ const device T* B,+ const constant GEMMParams* params [[buffer(4)]],+ const short sgp_sm,+ const short sgp_sn) {+ constexpr short TM = SM / UM;+ constexpr short TN = SN / UN;+ constexpr short TK = SK / UK;++ constexpr int RA = transpose_a ? TK : TM;+ constexpr int CA = transpose_a ? TM : TK;++ constexpr int RB = transpose_b ? TN : TK;+ constexpr int CB = transpose_b ? TK : TN;++ using DSubTile = NAXSubTile<AccumType, UM, UN>;+ using ASubTile =+ NAXSubTile<T, (transpose_a ? UK : UM), (transpose_a ? UM : UK)>;+ using BSubTile =+ NAXSubTile<T, (transpose_b ? UN : UK), (transpose_b ? UK : UN)>;++ NAXTile<AccumType, TM, TN, DSubTile> Dtile;+ Dtile.clear();++ int gemm_k_iterations_ = params->gemm_k_iterations_aligned;++ STEEL_PRAGMA_NO_UNROLL+ for (int kk0 = 0; kk0 < gemm_k_iterations_; kk0++) {+ threadgroup_barrier(mem_flags::mem_none);++ STEEL_PRAGMA_NO_UNROLL+ for (int kk1 = 0; kk1 < BK; kk1 += SK) {+ NAXTile<T, RA, CA, ASubTile> Atile;+ NAXTile<T, RB, CB, BSubTile> Btile;+ const int k = kk1;++ volatile int compiler_barrier;++ const int A_offset = transpose_a ? k * params->lda : k;+ const int B_offset = transpose_b ? k : k * params->ldb;++ if constexpr (kAlignedM) {+ Atile.load(A + A_offset, params->lda);+ } else {+ const short rmax = transpose_a ? SK : sgp_sm;+ const short cmax = transpose_a ? sgp_sm : SK;+ Atile.load_safe(A + A_offset, params->lda, short2(cmax, rmax));+ }++ if constexpr (kAlignedN) {+ Btile.load(B + B_offset, params->ldb);+ } else {+ const short rmax = transpose_b ? sgp_sn : SK;+ const short cmax = transpose_b ? SK : sgp_sn;+ Btile.load_safe(B + B_offset, params->ldb, short2(cmax, rmax));+ }++ tile_matmad_nax(+ Dtile,+ Atile,+ metal::bool_constant<transpose_a>{},+ Btile,+ metal::bool_constant<transpose_b>{});++ (void)compiler_barrier;+ }++ A += transpose_a ? (BK * params->lda) : BK;+ B += transpose_b ? BK : (BK * params->ldb);+ }++ if constexpr (!kAlignedK) {+ simdgroup_barrier(mem_flags::mem_none);++ const short rem_bk = params->K - gemm_k_iterations_ * BK;++ STEEL_PRAGMA_NO_UNROLL+ for (int kk1 = 0; kk1 < rem_bk; kk1 += SK) {+ NAXTile<T, 1, 1, ASubTile> Atile;+ NAXTile<T, 1, 1, BSubTile> Btile;++ STEEL_PRAGMA_UNROLL+ for (int mm = 0; mm < TM; mm++) {+ STEEL_PRAGMA_UNROLL+ for (int nn = 0; nn < TN; nn++) {+ STEEL_PRAGMA_UNROLL+ for (int kk = 0; kk < TK; kk++) {+ const int m = mm * UM;+ const int n = nn * UN;+ const int k = kk1 + kk * UK;+ const short psk = max(0, rem_bk - k);++ const int A_offset =+ transpose_a ? (m + k * params->lda) : (m * params->lda + k);+ const int B_offset =+ transpose_b ? (k + n * params->ldb) : (k * params->ldb + n);++ {+ const short psm = kAlignedM ? SM : max(0, sgp_sm - m);+ const short rmax = transpose_a ? psk : psm;+ const short cmax = transpose_a ? psm : psk;+ Atile.load_safe(A + A_offset, params->lda, short2(cmax, rmax));+ }++ {+ const short psn = kAlignedN ? SN : max(0, sgp_sn - n);+ const short rmax = transpose_b ? psn : psk;+ const short cmax = transpose_b ? psk : psn;+ Btile.load_safe(B + B_offset, params->ldb, short2(cmax, rmax));+ }++ subtile_matmad_nax(+ Dtile.subtile_at(mm, nn),+ Atile.subtile_at(0, 0),+ metal::bool_constant<transpose_a>{},+ Btile.subtile_at(0, 0),+ metal::bool_constant<transpose_b>{});+ }+ }+ }+ }+ }++ return Dtile;+}++} // namespace steeldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused.hnew file mode 100644index 000000000..4c7189378--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused.h@@ -0,0 +1,346 @@+++using namespace steel;++///////////////////////////////////////////////////////////////////////////////+// GEMM kernels+///////////////////////////////////////////////////////////////////////////////++constant bool has_batch [[function_constant(10)]];++constant bool use_out_source [[function_constant(100)]];+constant bool do_axpby [[function_constant(110)]];++constant bool align_M [[function_constant(200)]];+constant bool align_N [[function_constant(201)]];+constant bool align_K [[function_constant(202)]];++// clang-format off+template <+ typename T,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ typename AccumType = float>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gemm(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ const device T* C [[buffer(2), function_constant(use_out_source)]],+ device T* D [[buffer(3)]],+ const constant GEMMParams* params [[buffer(4)]],+ const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]],+ const constant int* batch_shape [[buffer(6), function_constant(has_batch)]],+ const constant int64_t* batch_strides [[buffer(7), function_constant(has_batch)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]]) { // clang-format on+ // Pacifying compiler+ (void)lid;++ using gemm_kernel = GEMMKernel<+ T,+ T,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ true,+ true,+ AccumType>;++ using loader_a_t = typename gemm_kernel::loader_a_t;+ using loader_b_t = typename gemm_kernel::loader_b_t;+ using mma_t = typename gemm_kernel::mma_t;++ // Find block+ const int tid_y = ((tid.y) << params->swizzle_log) ++ ((tid.x) & ((1 << params->swizzle_log) - 1));+ const int tid_x = (tid.x) >> params->swizzle_log;++ // Exit early if out of bounds+ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {+ return;+ }++ // Adjust for batch+ if (has_batch) {+ const constant auto* A_bstrides = batch_strides;+ const constant auto* B_bstrides = batch_strides + params->batch_ndim;++ ulong2 batch_offsets = elem_to_loc_broadcast(+ tid.z, batch_shape, A_bstrides, B_bstrides, params->batch_ndim);++ A += batch_offsets.x;+ B += batch_offsets.y;++ if (use_out_source) {+ const constant auto* C_bstrides = B_bstrides + params->batch_ndim;+ C += elem_to_loc(tid.z, batch_shape, C_bstrides, params->batch_ndim);+ }+ } else {+ A += params->batch_stride_a * tid.z;+ B += params->batch_stride_b * tid.z;++ if (use_out_source) {+ C += addmm_params->batch_stride_c * tid.z;+ }+ }++ D += params->batch_stride_d * tid.z;++ // Prepare threadgroup memory+ threadgroup T As[gemm_kernel::tgp_mem_size_a];+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];++ threadgroup_barrier(mem_flags::mem_none);++ // Find block in A, B, C+ const int c_row = tid_y * BM;+ const int c_col = tid_x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ D += c_row_long * params->ldd + c_col_long;++ if (use_out_source) {+ C += c_row_long * addmm_params->ldc + c_col_long * addmm_params->fdc;+ }++ // Prepare threadgroup mma operation+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ // Prepare threadgroup loading operations+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);++ // Prepare threadgroup bounds+ const short tgp_bm = align_M ? BM : short(min(BM, params->M - c_row));+ const short tgp_bn = align_N ? BN : short(min(BN, params->N - c_col));++ // Prepare iterations+ int gemm_k_iterations = params->gemm_k_iterations_aligned;++ // Do unaligned K iterations first+ if (!align_K) {+ const int k_last = params->gemm_k_iterations_aligned * BK;+ const int k_remain = params->K - k_last;+ const size_t k_jump_a =+ transpose_a ? params->lda * size_t(k_last) : size_t(k_last);+ const size_t k_jump_b =+ transpose_b ? size_t(k_last) : params->ldb * size_t(k_last);++ // Move loader source ahead to end+ loader_a.src += k_jump_a;+ loader_b.src += k_jump_b;++ // Load tile+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);++ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Do matmul+ mma_op.mma(As, Bs);++ // Reset source back to start+ loader_a.src -= k_jump_a;+ loader_b.src -= k_jump_b;+ }++ const TransformAdd<AccumType, AccumType> epilogue_op_add(+ addmm_params->alpha, addmm_params->beta);+ const TransformAxpby<AccumType, AccumType> epilogue_op_axpby(+ addmm_params->alpha, addmm_params->beta);++ ///////////////////////////////////////////////////////////////////////////////+ // MNK aligned loop+ if (align_M && align_N) {+ // Do gemm+ for (int k = 0; k < gemm_k_iterations; k++) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }++ threadgroup_barrier(mem_flags::mem_none);++ // Do epilogue+ if (use_out_source) {+ if (do_axpby) {+ mma_op.apply_epilogue(+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_axpby);+ } else {+ mma_op.apply_epilogue(+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_add);+ }+ }++ // Store results to device memory+ return mma_op.store_result(D, params->ldd);++ }+ ///////////////////////////////////////////////////////////////////////////////+ // MN unaligned loop+ else { // Loop over K - unaligned case+ const int leftover_bk = 0;++ if ((align_M || tgp_bm == BM) && (align_N || tgp_bn == BN)) {+ // Do gemm+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<true, true, true>{});++ // Do epilogue+ if (use_out_source) {+ if (do_axpby) {+ mma_op.apply_epilogue(+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_axpby);+ } else {+ mma_op.apply_epilogue(+ C, addmm_params->ldc, addmm_params->fdc, epilogue_op_add);+ }+ }++ // Store results to device memory+ return mma_op.store_result(D, params->ldd);++ } else if (align_N || tgp_bn == BN) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<false, true, true>{});++ // Do epilogue+ if (use_out_source) {+ if (do_axpby) {+ mma_op.apply_epilogue_safe(+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ short2(tgp_bn, tgp_bm),+ epilogue_op_axpby);+ } else {+ mma_op.apply_epilogue_safe(+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ short2(tgp_bn, tgp_bm),+ epilogue_op_add);+ }+ }++ // Store results to device memory+ return mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));++ } else if (align_M || tgp_bm == BM) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<true, false, true>{});++ // Do epilogue+ if (use_out_source) {+ if (do_axpby) {+ mma_op.apply_epilogue_safe(+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ short2(tgp_bn, tgp_bm),+ epilogue_op_axpby);+ } else {+ mma_op.apply_epilogue_safe(+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ short2(tgp_bn, tgp_bm),+ epilogue_op_add);+ }+ }++ // Store results to device memory+ return mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));++ } else {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<false, false, true>{});++ // Do epilogue+ if (use_out_source) {+ if (do_axpby) {+ mma_op.apply_epilogue_safe(+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ short2(tgp_bn, tgp_bm),+ epilogue_op_axpby);+ } else {+ mma_op.apply_epilogue_safe(+ C,+ addmm_params->ldc,+ addmm_params->fdc,+ short2(tgp_bn, tgp_bm),+ epilogue_op_add);+ }+ }++ // Store results to device memory+ return mma_op.store_result_safe(D, params->ldd, short2(tgp_bn, tgp_bm));+ }+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused.metal b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused.metalnew file mode 100644index 000000000..7053470c3--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused.metal@@ -0,0 +1,34 @@+++// clang-format off+#include "../../../../common/utils.h"++#include "../gemm.h"+#include "steel_gemm_fused.h"++#define instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_kernel( \+ "steel_gemm_fused_" #tname "_" #iname "_" #oname \+ "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn, \+ gemm, itype, bm, bn, bk, wm, wn, trans_a, trans_b, float)++#define instantiate_gemm_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(nt, false, true , iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(tn, true , false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(tt, true , true , iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_gemm_shapes_helper(iname, itype, oname, otype) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 64, 16, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 64, 16, 1, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 32, 32, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 32, 64, 16, 1, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 32, 32, 16, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 32, 8, 4, 1)++instantiate_gemm_shapes_helper(float16, half, float16, half);+instantiate_gemm_shapes_helper(bfloat16, bfloat16_t, bfloat16, bfloat16_t);++instantiate_gemm_shapes_helper(float32, float, float32, float);+instantiate_gemm_shapes_helper(complex64, complex64_t, complex64, complex64_t);+// clang-format ondiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused_nax.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused_nax.hnew file mode 100644index 000000000..0a7593ec8--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused_nax.h@@ -0,0 +1,207 @@+++using namespace steel;++constant bool has_batch [[function_constant(10)]];++constant bool use_out_source [[function_constant(100)]];+constant bool do_axpby [[function_constant(110)]];++constant bool align_M [[function_constant(200)]];+constant bool align_N [[function_constant(201)]];+constant bool align_K [[function_constant(202)]];++// clang-format off+template <+ bool kAlignedM,+ bool kAlignedN,+ typename NAXTile_t,+ typename T>+void gemm_epilogue(+ thread NAXTile_t& Dtile,+ const device T* C,+ const constant GEMMParams* params,+ const constant GEMMAddMMParams* addmm_params,+ const short sgp_sm,+ const short sgp_sn) { // clang-format on++ (void)params;++ constexpr short UM = NAXTile_t::kSubTileRows;+ constexpr short UN = NAXTile_t::kSubTileCols;+ using CSubTile = NAXSubTile<T, UM, UN>;++ using V = typename NAXTile_t::elem_type;++ constexpr short TM = NAXTile_t::kTileRows;+ constexpr short TN = NAXTile_t::kTileCols;+ constexpr short kElemsPerSubTile = NAXTile_t::kElemsPerSubTile;++ STEEL_PRAGMA_UNROLL+ for (short mm = 0; mm < TM; mm++) {+ STEEL_PRAGMA_UNROLL+ for (short nn = 0; nn < TN; nn++) {+ const short m = mm * UM;+ const short n = nn * UN;++ CSubTile CTile;++ if constexpr (kAlignedM && kAlignedN) {+ CTile.load(C, addmm_params->ldc, addmm_params->fdc, m, n);+ } else {+ CTile.load_safe(+ C, addmm_params->ldc, addmm_params->fdc, sgp_sm, sgp_sn, m, n);+ }++ auto delems = Dtile.subtile_at(mm, nn).elems();+ auto celems = CTile.elems();++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemsPerSubTile; i++) {+ if (do_axpby) {+ delems[i] = addmm_params->alpha * delems[i] ++ addmm_params->beta * static_cast<V>(celems[i]);+ } else {+ delems[i] += static_cast<V>(celems[i]);+ }+ }+ }+ }+}++// clang-format off+template <+ typename T,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ typename AccumType = float>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gemm(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ const device T* C [[buffer(2), function_constant(use_out_source)]],+ device T* D [[buffer(3)]],+ const constant GEMMParams* params [[buffer(4)]],+ const constant GEMMAddMMParams* addmm_params [[buffer(5), function_constant(use_out_source)]],+ const constant int* batch_shape [[buffer(6), function_constant(has_batch)]],+ const constant int64_t* batch_strides [[buffer(7), function_constant(has_batch)]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on+ // Find block+ const int tid_y = ((tid.y) << params->swizzle_log) ++ ((tid.x) & ((1 << params->swizzle_log) - 1));+ const int tid_x = (tid.x) >> params->swizzle_log;++ // Exit early if out of bounds+ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {+ return;+ }++ // Adjust for batch+ if (has_batch) {+ const constant auto* A_bstrides = batch_strides;+ const constant auto* B_bstrides = batch_strides + params->batch_ndim;++ ulong2 batch_offsets = elem_to_loc_broadcast(+ tid.z, batch_shape, A_bstrides, B_bstrides, params->batch_ndim);++ A += batch_offsets.x;+ B += batch_offsets.y;++ if (use_out_source) {+ const constant auto* C_bstrides = B_bstrides + params->batch_ndim;+ C += elem_to_loc(tid.z, batch_shape, C_bstrides, params->batch_ndim);+ }+ } else {+ A += params->batch_stride_a * tid.z;+ B += params->batch_stride_b * tid.z;++ if (use_out_source) {+ C += addmm_params->batch_stride_c * tid.z;+ }+ }++ D += params->batch_stride_d * tid.z;++ // Prepare threadgroup memory+ threadgroup_barrier(mem_flags::mem_none);++ // Find block in A, B, C+ const int c_row = tid_y * BM;+ const int c_col = tid_x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ D += c_row_long * params->ldd + c_col_long;++ if (use_out_source) {+ C += c_row_long * addmm_params->ldc + c_col_long * addmm_params->fdc;+ }++ constexpr short UM = 16;+ constexpr short UN = 32;+ constexpr short UK = 16;+ constexpr short SM = BM / WM;+ constexpr short SN = BN / WN;+ constexpr short SK = 32;++ constexpr short TM = SM / UM;+ constexpr short TN = SN / UN;++ const short tm = SM * (simd_group_id / WN);+ const short tn = SN * (simd_group_id % WN);++ const short sgp_sm = align_M ? SM : min(SM, short(params->M - (c_row + tm)));+ const bool is_unaligned_sm = align_M ? false : (sgp_sm != SM);++ const short sgp_sn = align_N ? SN : min(SN, short(params->N - (c_col + tn)));+ const bool is_unaligned_sn = align_N ? false : (sgp_sn != SN);++ A += transpose_a ? tm : (tm * params->lda);+ B += transpose_b ? (tn * params->ldb) : tn;+ D += tm * params->ldd + tn;++ if (use_out_source) {+ C += tm * addmm_params->ldc + tn * addmm_params->fdc;+ }++ using DSubTile = NAXSubTile<AccumType, UM, UN>;+ NAXTile<AccumType, TM, TN, DSubTile> Dtile;++ dispatch_bool(align_K, [&](auto kAlignedK) {+ dispatch_bool(align_M || !is_unaligned_sm, [&](auto kAlignedM) {+ dispatch_bool(align_N || !is_unaligned_sn, [&](auto kAlignedN) {+ Dtile = gemm_loop<+ T,+ SM,+ SN,+ SK,+ BK,+ transpose_a,+ transpose_b,+ kAlignedM.value,+ kAlignedN.value,+ kAlignedK.value,+ UM,+ UN,+ UK,+ AccumType>(A, B, params, sgp_sm, sgp_sn);+ if (use_out_source) {+ gemm_epilogue<kAlignedM.value, kAlignedN.value>(+ Dtile, C, params, addmm_params, sgp_sm, sgp_sn);+ }+ if constexpr (kAlignedM && kAlignedN) {+ Dtile.store(D, int(params->ldd));+ } else {+ Dtile.store_safe(D, int(params->ldd), short2(sgp_sn, sgp_sm));+ }+ });+ });+ });+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused_nax.metal b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused_nax.metalnew file mode 100644index 000000000..a0c3b9dda--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_fused_nax.metal@@ -0,0 +1,30 @@+++#include <metal_stdlib>++#include "../../../../common/utils.h"++#include "../gemm_nax.h"+#include "steel_gemm_fused_nax.h"++// clang-format off+#define instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_kernel( \+ "steel_gemm_fused_nax_" #tname "_" #iname "_" #oname \+ "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn, \+ gemm, itype, bm, bn, bk, wm, wn, trans_a, trans_b, float)++#define instantiate_gemm_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(nt, false, true , iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(tn, true , false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(tt, true , true , iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_gemm_shapes_helper(iname, itype, oname, otype) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 64, 64, 256, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 128, 128, 512, 4, 4)++instantiate_gemm_shapes_helper(float16, half, float16, half);+instantiate_gemm_shapes_helper(bfloat16, bfloat, bfloat16, bfloat);+instantiate_gemm_shapes_helper(float32, float, float32, float);+// clang-format ondiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather.hnew file mode 100644index 000000000..b9c6d3c83--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather.h@@ -0,0 +1,459 @@+++using namespace steel;++constant bool has_batch [[function_constant(10)]];+constant bool align_M [[function_constant(200)]];+constant bool align_N [[function_constant(201)]];+constant bool align_K [[function_constant(202)]];++template <+ typename T,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ typename AccumType = float>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gather_mm_rhs(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ const device uint32_t* rhs_indices [[buffer(2)]],+ device T* C [[buffer(3)]],+ const constant GEMMParams* params [[buffer(4)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]]) {+ using gemm_kernel = GEMMKernel<+ T,+ T,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ true,+ true,+ AccumType>;++ using loader_a_t = typename gemm_kernel::loader_a_t;+ using loader_b_t = typename gemm_kernel::loader_b_t;+ using mma_t = typename gemm_kernel::mma_t;++ if (params->tiles_n <= static_cast<int>(tid.x) ||+ params->tiles_m <= static_cast<int>(tid.y)) {+ return;+ }++ // Prepare threadgroup memory+ threadgroup T As[gemm_kernel::tgp_mem_size_a];+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];++ // Find the block in A, B, C+ const int c_row = tid.y * BM;+ const int c_col = tid.x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ // Prepare threadgroup bounds+ const short tgp_bm = align_M ? BM : short(min(BM, params->M - c_row));+ const short tgp_bn = align_N ? BN : short(min(BN, params->N - c_col));++ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ C += c_row_long * params->ldd + c_col_long;++ // Do as many matmuls as necessary+ uint32_t index;+ short offset;+ uint32_t index_next = rhs_indices[c_row];+ short offset_next = 0;+ int n = 0;+ while (n < tgp_bm) {+ n++;+ offset = offset_next;+ index = index_next;+ offset_next = tgp_bm;+ for (; n < tgp_bm; n++) {+ if (rhs_indices[c_row + n] != index) {+ offset_next = n;+ index_next = rhs_indices[c_row + n];+ break;+ }+ }+ threadgroup_barrier(mem_flags::mem_none);++ // Prepare threadgroup mma operation+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ // Prepare threadgroup loading operations+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(+ B + index * params->batch_stride_b,+ params->ldb,+ Bs,+ simd_group_id,+ simd_lane_id);++ // Prepare iterations+ const int gemm_k_iterations = params->gemm_k_iterations_aligned;++ // Do unaligned K iterations first+ if (!align_K) {+ const int k_last = params->gemm_k_iterations_aligned * BK;+ const int k_remain = params->K - k_last;+ const size_t k_jump_a =+ transpose_a ? params->lda * size_t(k_last) : size_t(k_last);+ const size_t k_jump_b =+ transpose_b ? size_t(k_last) : params->ldb * size_t(k_last);++ // Move loader source ahead to end+ loader_a.src += k_jump_a;+ loader_b.src += k_jump_b;++ // Load tile+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);++ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Do matmul+ mma_op.mma(As, Bs);++ // Reset source back to start+ loader_a.src -= k_jump_a;+ loader_b.src -= k_jump_b;+ }++ // Matrix level aligned never check+ if (align_M && align_N) {+ for (int k = 0; k < gemm_k_iterations; k++) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }++ // Store results to device memory+ if (offset_next - offset == BM) {+ mma_op.store_result(C, params->ldd);+ } else {+ mma_op.store_result_slice(+ C, params->ldd, short2(0, offset), short2(BN, offset_next));+ }+ } else {+ const short lbk = 0;++ // Tile aligned don't check+ if ((align_M || tgp_bm == BM) && (align_N || tgp_bn == BN)) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<true, true, true>{});+ if (offset_next - offset == BM) {+ mma_op.store_result(C, params->ldd);+ } else {+ mma_op.store_result_slice(+ C, params->ldd, short2(0, offset), short2(BN, offset_next));+ }+ }++ // Tile partially aligned check rows+ else if (align_N || tgp_bn == BN) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<false, true, true>{});+ mma_op.store_result_slice(+ C, params->ldd, short2(0, offset), short2(BN, offset_next));+ }++ // Tile partially aligned check cols+ else if (align_M || tgp_bm == BM) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<true, false, true>{});+ mma_op.store_result_slice(+ C, params->ldd, short2(0, offset), short2(tgp_bn, offset_next));+ }++ // Nothing aligned so check both rows and cols+ else {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<false, false, true>{});+ mma_op.store_result_slice(+ C, params->ldd, short2(0, offset), short2(tgp_bn, offset_next));+ }+ }+ }+}++template <+ typename T,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ typename AccumType = float>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gather_mm(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ const device uint32_t* lhs_indices [[buffer(2)]],+ const device uint32_t* rhs_indices [[buffer(3)]],+ device T* C [[buffer(4)]],+ const constant GEMMParams* params [[buffer(5)]],+ const constant int* indices_shape [[buffer(6)]],+ const constant int64_t* lhs_strides [[buffer(7)]],+ const constant int64_t* rhs_strides [[buffer(8)]],+ const constant int& batch_ndim_a [[buffer(9)]],+ const constant int* batch_shape_a [[buffer(10)]],+ const constant int64_t* batch_strides_a [[buffer(11)]],+ const constant int& batch_ndim_b [[buffer(12)]],+ const constant int* batch_shape_b [[buffer(13)]],+ const constant int64_t* batch_strides_b [[buffer(14)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]]) {+ using gemm_kernel = GEMMKernel<+ T,+ T,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ true,+ true,+ AccumType>;++ using loader_a_t = typename gemm_kernel::loader_a_t;+ using loader_b_t = typename gemm_kernel::loader_b_t;+ using mma_t = typename gemm_kernel::mma_t;++ if (params->tiles_n <= static_cast<int>(tid.x) ||+ params->tiles_m <= static_cast<int>(tid.y)) {+ return;+ }++ // Move A and B to the locations pointed by lhs_indices and rhs_indices.+ uint32_t indx_A, indx_B;+ if (has_batch) {+ ulong2 indices_offsets = elem_to_loc_broadcast(+ tid.z, indices_shape, lhs_strides, rhs_strides, params->batch_ndim);+ indx_A = lhs_indices[indices_offsets.x];+ indx_B = rhs_indices[indices_offsets.y];+ } else {+ indx_A = lhs_indices[params->batch_stride_a * tid.z];+ indx_B = rhs_indices[params->batch_stride_b * tid.z];+ }+ A += elem_to_loc(indx_A, batch_shape_a, batch_strides_a, batch_ndim_a);+ B += elem_to_loc(indx_B, batch_shape_b, batch_strides_b, batch_ndim_b);+ C += params->batch_stride_d * tid.z;++ // Prepare threadgroup memory+ threadgroup T As[gemm_kernel::tgp_mem_size_a];+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];++ // Just make sure everybody's finished with the indexing math above.+ threadgroup_barrier(mem_flags::mem_none);++ // Find block in A, B, C+ const int c_row = tid.y * BM;+ const int c_col = tid.x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ C += c_row_long * params->ldd + c_col_long;++ // Prepare threadgroup mma operation+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ // Prepare threadgroup loading operations+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);++ // Prepare threadgroup bounds+ const short tgp_bm = align_M ? BM : short(min(BM, params->M - c_row));+ const short tgp_bn = align_N ? BN : short(min(BN, params->N - c_col));++ // Prepare iterations+ int gemm_k_iterations = params->gemm_k_iterations_aligned;++ // Do unaligned K iterations first+ if (!align_K) {+ const int k_last = params->gemm_k_iterations_aligned * BK;+ const int k_remain = params->K - k_last;+ const size_t k_jump_a =+ transpose_a ? params->lda * size_t(k_last) : size_t(k_last);+ const size_t k_jump_b =+ transpose_b ? size_t(k_last) : params->ldb * size_t(k_last);++ // Move loader source ahead to end+ loader_a.src += k_jump_a;+ loader_b.src += k_jump_b;++ // Load tile+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);++ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Do matmul+ mma_op.mma(As, Bs);++ // Reset source back to start+ loader_a.src -= k_jump_a;+ loader_b.src -= k_jump_b;+ }++ // Matrix level aligned never check+ if (align_M && align_N) {+ for (int k = 0; k < gemm_k_iterations; k++) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }++ // Store results to device memory+ mma_op.store_result(C, params->ldd);+ } else {+ const short lbk = 0;++ // Tile aligned don't check+ if ((align_M || tgp_bm == BM) && (align_N || tgp_bn == BN)) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<true, true, true>{});+ mma_op.store_result(C, params->ldd);+ }++ // Tile partially aligned check rows+ else if (align_N || tgp_bn == BN) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<false, true, true>{});+ mma_op.store_result_safe(C, params->ldd, short2(tgp_bn, tgp_bm));+ }++ // Tile partially aligned check cols+ else if (align_M || tgp_bm == BM) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<true, false, true>{});+ mma_op.store_result_safe(C, params->ldd, short2(tgp_bn, tgp_bm));+ }++ // Nothing aligned so check both rows and cols+ else {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ lbk,+ LoopAlignment<false, false, true>{});+ mma_op.store_result_safe(C, params->ldd, short2(tgp_bn, tgp_bm));+ }+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather.metal b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather.metalnew file mode 100644index 000000000..89372091c--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather.metal@@ -0,0 +1,59 @@+++// clang-format off+#include "../../../../common/utils.h"+#include "../gemm.h"+#include "steel_gemm_gather.h"++#define instantiate_gather_mm_rhs(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_kernel( \+ "steel_gather_mm_rhs_" #tname "_" #iname "_" #oname "_bm" #bm "_bn" #bn \+ "_bk" #bk "_wm" #wm "_wn" #wn, \+ gather_mm_rhs, \+ itype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ trans_a, \+ trans_b, \+ float)++#define instantiate_gather_mm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_kernel( \+ "steel_gather_mm_" #tname "_" #iname "_" #oname "_bm" #bm "_bn" #bn \+ "_bk" #bk "_wm" #wm "_wn" #wn, \+ gather_mm, \+ itype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ trans_a, \+ trans_b, \+ float)++#define instantiate_gather_mm_rhs_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm_rhs(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm_rhs(nt, false, true, iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_gather_mm_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm(nt, false, true , iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm(tn, true , false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm(tt, true , true , iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_gather_mm_shapes_helper(iname, itype, oname, otype) \+ instantiate_gather_mm_rhs_transpose_helper(iname, itype, oname, otype, 16, 64, 16, 1, 2) \+ instantiate_gather_mm_transpose_helper(iname, itype, oname, otype, 64, 64, 16, 2, 2) \+ instantiate_gather_mm_transpose_helper(iname, itype, oname, otype, 64, 64, 16, 1, 2) \+ instantiate_gather_mm_transpose_helper(iname, itype, oname, otype, 64, 32, 32, 2, 2) \+ instantiate_gather_mm_transpose_helper(iname, itype, oname, otype, 32, 64, 16, 1, 2) \+ instantiate_gather_mm_transpose_helper(iname, itype, oname, otype, 32, 32, 16, 2, 2)+// clang-format on++instantiate_gather_mm_shapes_helper(float16, half, float16, half);+instantiate_gather_mm_shapes_helper(bfloat16, bfloat16_t, bfloat16, bfloat16_t);+instantiate_gather_mm_shapes_helper(float32, float, float32, float);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather_nax.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather_nax.hnew file mode 100644index 000000000..05f567356--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather_nax.h@@ -0,0 +1,132 @@+++using namespace steel;++constant bool align_M [[function_constant(200)]];+constant bool align_N [[function_constant(201)]];+constant bool align_K [[function_constant(202)]];++template <+ typename T,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ typename AccumType = float>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void+gather_mm_rhs_nax(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ const device uint32_t* rhs_indices [[buffer(2)]],+ device T* C [[buffer(3)]],+ const constant GEMMParams* params [[buffer(4)]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]]) {+ constexpr short UM = 16;+ constexpr short UN = 32;+ constexpr short UK = 16;+ constexpr short SM = BM / WM;+ constexpr short SN = BN / WN;+ constexpr short SK = 32;+ constexpr short TM = SM / UM;+ constexpr short TN = SN / UN;++ if (params->tiles_n <= static_cast<int>(tid.x) ||+ params->tiles_m <= static_cast<int>(tid.y)) {+ return;+ }++ // Find the block in A, B, C+ const int c_row = tid.y * BM;+ const int c_col = tid.x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ C += c_row_long * params->ldd + c_col_long;+ rhs_indices += c_row;++ const short tm = SM * (simd_group_id / WN);+ const short tn = SN * (simd_group_id % WN);++ const short sgp_sm = align_M ? SM : min(SM, short(params->M - (c_row + tm)));+ const bool is_unaligned_sm = align_M ? false : (sgp_sm != SM);++ const short sgp_sn = align_N ? SN : min(SN, short(params->N - (c_col + tn)));+ const bool is_unaligned_sn = align_N ? false : (sgp_sn != SN);++ A += transpose_a ? tm : (tm * params->lda);+ B += transpose_b ? (tn * params->ldb) : tn;+ C += tm * params->ldd + tn;+ rhs_indices += tm;++ // Do as many matmuls as necessary+ uint32_t index;+ short offset;+ uint32_t index_next = rhs_indices[0];+ short offset_next = 0;+ int n = 0;+ while (n < sgp_sm) {+ n++;+ offset = offset_next;+ index = index_next;+ offset_next = sgp_sm;+ for (; n < sgp_sm; n++) {+ if (rhs_indices[n] != index) {+ offset_next = n;+ index_next = rhs_indices[n];+ break;+ }+ }+ threadgroup_barrier(mem_flags::mem_none);++ using DSubTile = NAXSubTile<AccumType, UM, UN>;+ NAXTile<AccumType, TM, TN, DSubTile> Ctile;++ dispatch_bool(align_K, [&](auto kAlignedK) {+ dispatch_bool(align_M || !is_unaligned_sm, [&](auto kAlignedM) {+ dispatch_bool(align_N || !is_unaligned_sn, [&](auto kAlignedN) {+ auto do_gemm = gemm_loop<+ T,+ SM,+ SN,+ SK,+ BK,+ transpose_a,+ transpose_b,+ kAlignedM.value,+ kAlignedN.value,+ kAlignedK.value,+ UM,+ UN,+ UK,+ AccumType>;+ Ctile = do_gemm(+ A, B + index * params->batch_stride_b, params, sgp_sm, sgp_sn);++ if constexpr (kAlignedN.value) {+ if (offset_next - offset == SM) {+ Ctile.store(C, int(params->ldd));+ } else {+ Ctile.store_slice(+ C,+ int(params->ldd),+ short2(0, offset),+ short2(SN, offset_next));+ }+ } else {+ Ctile.store_slice(+ C,+ int(params->ldd),+ short2(0, offset),+ short2(sgp_sn, offset_next));+ }+ });+ });+ });+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather_nax.metal b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather_nax.metalnew file mode 100644index 000000000..47585a9c6--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_gather_nax.metal@@ -0,0 +1,37 @@+++#include <metal_stdlib>++#include "../../../../common/utils.h"++#include "../gemm_nax.h"+#include "steel_gemm_gather_nax.h"++// clang-format off+#define instantiate_gather_mm_rhs(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_kernel( \+ "steel_gather_mm_rhs_nax_" #tname "_" #iname "_" #oname "_bm" #bm "_bn" #bn \+ "_bk" #bk "_wm" #wm "_wn" #wn, \+ gather_mm_rhs_nax, \+ itype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ trans_a, \+ trans_b, \+ float)++#define instantiate_gather_mm_rhs_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm_rhs(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gather_mm_rhs(nt, false, true, iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_gather_mm_shapes_helper(iname, itype, oname, otype) \+ instantiate_gather_mm_rhs_transpose_helper(iname, itype, oname, otype, 16, 128, 128, 1, 4) \+ instantiate_gather_mm_rhs_transpose_helper(iname, itype, oname, otype, 32, 128, 128, 1, 4) \+ instantiate_gather_mm_rhs_transpose_helper(iname, itype, oname, otype, 64, 128, 128, 2, 4)+// clang-format on++instantiate_gather_mm_shapes_helper(float16, half, float16, half);+instantiate_gather_mm_shapes_helper(bfloat16, bfloat, bfloat16, bfloat);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_segmented.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_segmented.hnew file mode 100644index 000000000..e7238b74e--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_segmented.h@@ -0,0 +1,266 @@+++using namespace steel;++constant bool segments_contiguous [[function_constant(199)]];+constant bool align_M [[function_constant(200)]];+constant bool align_N [[function_constant(201)]];++template <+ typename T,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ typename AccumType = float>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void segmented_mm(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ const device uint32_t* segments [[buffer(2)]],+ device T* C [[buffer(3)]],+ const constant GEMMParams* params [[buffer(4)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]]) {+ using gemm_kernel = GEMMKernel<+ T,+ T,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ true,+ true,+ AccumType>;++ using loader_a_t = typename gemm_kernel::loader_a_t;+ using loader_b_t = typename gemm_kernel::loader_b_t;+ using mma_t = typename gemm_kernel::mma_t;++ if (params->tiles_n <= static_cast<int>(tid.x) ||+ params->tiles_m <= static_cast<int>(tid.y)) {+ return;+ }++ // Prepare threadgroup memory+ threadgroup T As[gemm_kernel::tgp_mem_size_a];+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];++ // Find the block in A, B, C+ const int c_row = tid.y * BM;+ const int c_col = tid.x * BN;+ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);++ // Prepare threadgroup bounds+ const short tgp_bm = align_M ? BM : short(min(BM, params->M - c_row));+ const short tgp_bn = align_N ? BN : short(min(BN, params->N - c_col));++ // Move the pointers to the output tile+ A += transpose_a ? c_row_long : c_row_long * params->lda;+ B += transpose_b ? c_col_long * params->ldb : c_col_long;+ C += c_row_long * params->ldd + c_col_long;++ // Move the pointers to the start of the segment+ uint32_t k_start, k_end;+ if (segments_contiguous) {+ k_start = segments[2 * tid.z];+ k_end = segments[2 * tid.z + 1];+ } else {+ // We accept either contiguous (above) or weird strides where the beginning+ // of the next one is the previous one. Basically the last two strides are+ // both 1!+ k_start = segments[tid.z];+ k_end = segments[tid.z + 1];+ }+ A += transpose_a ? k_start * params->lda : k_start;+ B += transpose_b ? k_start : k_start * params->ldb;+ C += tid.z * params->batch_stride_d;++ // Prepare threadgroup mma operation+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ // Prepare threadgroup loading operations+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);++ // Matrix level alignment so only check K+ if (align_M && align_N) {+ uint32_t k = k_start + BK;+ for (; k <= k_end; k += BK) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }+ short k_remain = BK - short(k - k_end);+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);+ if (k_remain > 0) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ mma_op.mma(As, Bs);+ }+ mma_op.store_result(C, params->ldd);+ } else {+ // Tile aligned do the same as above+ if ((align_M || tgp_bm == BM) && (align_N || tgp_bn == BN)) {+ uint32_t k = k_start + BK;+ for (; k <= k_end; k += BK) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }+ short k_remain = BK - short(k - k_end);+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);+ if (k_remain > 0) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ mma_op.mma(As, Bs);+ }+ mma_op.store_result(C, params->ldd);+ }++ // Tile partially aligned check rows+ else if (align_N || tgp_bn == BN) {+ uint32_t k = k_start + BK;+ for (; k <= k_end; k += BK) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_safe(+ transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm));+ loader_b.load_unsafe();++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }+ short k_remain = BK - short(k - k_end);+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);+ if (k_remain > 0) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ mma_op.mma(As, Bs);+ }+ mma_op.store_result_safe(C, params->ldd, short2(tgp_bn, tgp_bm));+ }++ // Tile partially aligned check cols+ else if (align_M || tgp_bm == BM) {+ uint32_t k = k_start + BK;+ for (; k <= k_end; k += BK) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_unsafe();+ loader_b.load_safe(+ transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK));++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }+ short k_remain = BK - short(k - k_end);+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);+ if (k_remain > 0) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ mma_op.mma(As, Bs);+ }+ mma_op.store_result_safe(C, params->ldd, short2(tgp_bn, tgp_bm));+ }++ // Nothing aligned so check both rows and cols+ else {+ uint32_t k = k_start + BK;+ for (; k <= k_end; k += BK) {+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Load elements into threadgroup+ loader_a.load_safe(+ transpose_a ? short2(tgp_bm, BK) : short2(BK, tgp_bm));+ loader_b.load_safe(+ transpose_b ? short2(BK, tgp_bn) : short2(tgp_bn, BK));++ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Multiply and accumulate threadgroup elements+ mma_op.mma(As, Bs);++ // Prepare for next iteration+ loader_a.next();+ loader_b.next();+ }+ short k_remain = BK - short(k - k_end);+ const short2 tile_dims_A =+ transpose_a ? short2(tgp_bm, k_remain) : short2(k_remain, tgp_bm);+ const short2 tile_dims_B =+ transpose_b ? short2(k_remain, tgp_bn) : short2(tgp_bn, k_remain);+ if (k_remain > 0) {+ threadgroup_barrier(mem_flags::mem_threadgroup);+ loader_a.load_safe(tile_dims_A);+ loader_b.load_safe(tile_dims_B);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ mma_op.mma(As, Bs);+ }+ mma_op.store_result_safe(C, params->ldd, short2(tgp_bn, tgp_bm));+ }+ }+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_segmented.metal b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_segmented.metalnew file mode 100644index 000000000..fd05e307e--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_segmented.metal@@ -0,0 +1,43 @@+++// clang-format off+#include "../../../../common/utils.h"+#include "../gemm.h"+#include "steel_gemm_segmented.h"++#define instantiate_segmented_mm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_kernel( \+ "steel_segmented_mm_" #tname "_" #iname "_" #oname "_bm" #bm "_bn" #bn \+ "_bk" #bk "_wm" #wm "_wn" #wn, \+ segmented_mm, \+ itype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ trans_a, \+ trans_b, \+ float)++#define instantiate_segmented_mm_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_segmented_mm(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_segmented_mm(nt, false, true , iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_segmented_mm(tn, true , false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_segmented_mm(tt, true , true , iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_segmented_mm_shapes_helper(iname, itype, oname, otype) \+ instantiate_segmented_mm_transpose_helper(iname, itype, oname, otype, 64, 64, 16, 2, 2) \+ instantiate_segmented_mm_transpose_helper(iname, itype, oname, otype, 64, 64, 16, 1, 2) \+ instantiate_segmented_mm_transpose_helper(iname, itype, oname, otype, 64, 32, 32, 2, 2) \+ instantiate_segmented_mm_transpose_helper(iname, itype, oname, otype, 32, 64, 16, 1, 2) \+ instantiate_segmented_mm_transpose_helper(iname, itype, oname, otype, 32, 32, 16, 2, 2)+// clang-format on++instantiate_segmented_mm_shapes_helper(float16, half, float16, half);+instantiate_segmented_mm_shapes_helper(+ bfloat16,+ bfloat16_t,+ bfloat16,+ bfloat16_t);+instantiate_segmented_mm_shapes_helper(float32, float, float32, float);diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_splitk.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_splitk.hnew file mode 100644index 000000000..4d1203149--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_splitk.h@@ -0,0 +1,227 @@+++using namespace steel;++///////////////////////////////////////////////////////////////////////////////+// GEMM kernels+///////////////////////////////////////////////////////////////////////////////++template <+ typename T,+ typename U,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ bool MN_aligned,+ bool K_aligned>+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void gemm_splitk(+ const device T* A [[buffer(0)]],+ const device T* B [[buffer(1)]],+ device U* C [[buffer(2)]],+ const constant GEMMSpiltKParams* params [[buffer(3)]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]],+ uint3 tid [[threadgroup_position_in_grid]],+ uint3 lid [[thread_position_in_threadgroup]]) {+ (void)lid;++ using gemm_kernel = GEMMKernel<+ T,+ U,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ MN_aligned,+ K_aligned>;+ using loader_a_t = typename gemm_kernel::loader_a_t;+ using loader_b_t = typename gemm_kernel::loader_b_t;+ using mma_t = typename gemm_kernel::mma_t;++ threadgroup T As[gemm_kernel::tgp_mem_size_a];+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];++ const int tid_x = tid.x;+ const int tid_y = tid.y;+ const int tid_z = tid.z;++ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {+ return;+ }++ // Find block in A, B, C+ const int c_row = tid_y * BM;+ const int c_col = tid_x * BN;+ const int k_start = params->split_k_partition_size * tid_z;++ const size_t c_row_long = size_t(c_row);+ const size_t c_col_long = size_t(c_col);+ const size_t k_start_long = size_t(k_start);++ A += transpose_a ? (c_row_long + k_start_long * params->lda)+ : (k_start_long + c_row_long * params->lda);+ B += transpose_b ? (k_start_long + c_col_long * params->ldb)+ : (c_col_long + k_start_long * params->ldb);+ C += (size_t(params->split_k_partition_stride) * tid_z) ++ (c_row_long * params->ldc + c_col_long);++ // Prepare threadgroup loading operations+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);++ // Prepare threadgroup mma operation+ thread mma_t mma_op(simd_group_id, simd_lane_id);++ int gemm_k_iterations = params->gemm_k_iterations_aligned;++ short tgp_bm = min(BM, params->M - c_row);+ short tgp_bn = min(BN, params->N - c_col);+ short leftover_bk = params->K % BK;++ if (MN_aligned || (tgp_bm == BM && tgp_bn == BN)) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<true, true, true>{});+ } else if (tgp_bn == BN) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<false, true, true>{});+ } else if (tgp_bm == BM) {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<true, false, true>{});+ } else {+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iterations,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<false, false, true>{});+ }++ threadgroup_barrier(mem_flags::mem_threadgroup);++ if ((tid_z + 1) == (params->split_k_partitions)) {+ int gemm_k_iter_remaining =+ (params->K - (k_start + params->split_k_partition_size)) / BK;+ if (!K_aligned || gemm_k_iter_remaining > 0)+ gemm_kernel::gemm_loop(+ As,+ Bs,+ gemm_k_iter_remaining,+ loader_a,+ loader_b,+ mma_op,+ tgp_bm,+ tgp_bn,+ leftover_bk,+ LoopAlignment<false, false, K_aligned>{});+ }++ if (MN_aligned || (tgp_bm == BM && tgp_bn == BN)) {+ mma_op.store_result(C, params->ldc);+ } else {+ mma_op.store_result_safe(C, params->ldc, short2(tgp_bn, tgp_bm));+ }+}++///////////////////////////////////////////////////////////////////////////////+// Split k accumulation kernel+///////////////////////////////////////////////////////////////////////////////++template <+ typename AccT,+ typename OutT,+ typename Epilogue = TransformNone<OutT, AccT>>+[[kernel]] void gemm_splitk_accum(+ const device AccT* C_split [[buffer(0)]],+ device OutT* D [[buffer(1)]],+ const constant int& k_partitions [[buffer(2)]],+ const constant int& partition_stride [[buffer(3)]],+ const constant int& ldd [[buffer(4)]],+ uint2 gid [[thread_position_in_grid]]) {+ // Ajust D and C+ D += gid.x + gid.y * size_t(ldd);+ C_split += gid.x + gid.y * size_t(ldd);++ size_t offset = 0;+ AccT out = 0;++ for (int i = 0; i < k_partitions; i++) {+ out += C_split[offset];+ offset += partition_stride;+ }++ // Write output+ D[0] = Epilogue::apply(out);+}++template <+ typename AccT,+ typename OutT,+ typename Epilogue = TransformAxpby<OutT, AccT>>+[[kernel]] void gemm_splitk_accum_axpby(+ const device AccT* C_split [[buffer(0)]],+ device OutT* D [[buffer(1)]],+ const constant int& k_partitions [[buffer(2)]],+ const constant int& partition_stride [[buffer(3)]],+ const constant int& ldd [[buffer(4)]],+ const device OutT* C [[buffer(5)]],+ const constant int& ldc [[buffer(6)]],+ const constant int& fdc [[buffer(7)]],+ const constant float& alpha [[buffer(8)]],+ const constant float& beta [[buffer(9)]],+ uint2 gid [[thread_position_in_grid]]) {+ // Ajust D and C+ C += gid.x * size_t(fdc) + gid.y * size_t(ldc);+ D += gid.x + gid.y * size_t(ldd);+ C_split += gid.x + gid.y * size_t(ldd);++ size_t offset = 0;+ AccT out = 0;++ for (int i = 0; i < k_partitions; i++) {+ out += C_split[offset];+ offset += partition_stride;+ }++ // Write output+ Epilogue op(alpha, beta);+ D[0] = op.apply(out, *C);+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_splitk.metal b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_splitk.metalnew file mode 100644index 000000000..c573c9ee1--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/kernels/steel_gemm_splitk.metal@@ -0,0 +1,76 @@+++// clang-format off+#include "../../../../common/utils.h"+#include "../gemm.h"+#include "steel_gemm_splitk.h"++#define instantiate_gemm( \+ tname, \+ trans_a, \+ trans_b, \+ iname, \+ itype, \+ oname, \+ otype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ aname, \+ mn_aligned, \+ kname, \+ k_aligned) \+ instantiate_kernel( \+ "steel_gemm_splitk_" #tname "_" #iname "_" #oname \+ "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn \+ "_MN_" #aname "_K_" #kname, \+ gemm_splitk, \+ itype, \+ otype, \+ bm, \+ bn, \+ bk, \+ wm, \+ wn, \+ trans_a, \+ trans_b, \+ mn_aligned, \+ k_aligned)++#define instantiate_gemm_aligned_helper(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn, taligned, true, taligned, true) \+ instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn, taligned, true, naligned, false) \+ instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn, naligned, false, taligned, true) \+ instantiate_gemm(tname, trans_a, trans_b, iname, itype, oname, otype, bm, bn, bk, wm, wn, naligned, false, naligned, false)++#define instantiate_gemm_transpose_helper(iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm_aligned_helper(nn, false, false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm_aligned_helper(nt, false, true , iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm_aligned_helper(tn, true , false, iname, itype, oname, otype, bm, bn, bk, wm, wn) \+ instantiate_gemm_aligned_helper(tt, true , true , iname, itype, oname, otype, bm, bn, bk, wm, wn)++#define instantiate_gemm_shapes_helper(iname, itype, oname, otype) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 16, 16, 16, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 16, 32, 16, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 32, 16, 16, 2, 2) \+ instantiate_gemm_transpose_helper(iname, itype, oname, otype, 32, 32, 16, 2, 2)++instantiate_gemm_shapes_helper(float16, half, float32, float);+instantiate_gemm_shapes_helper(bfloat16, bfloat16_t, float32, float);+instantiate_gemm_shapes_helper(float32, float, float32, float);+instantiate_gemm_shapes_helper(complex64, complex64_t, complex64, complex64_t);++#define instantiate_accum(oname, otype, aname, atype) \+ instantiate_kernel( \+ "steel_gemm_splitk_accum_" #oname "_" #aname, \+ gemm_splitk_accum, atype, otype) \+ instantiate_kernel( \+ "steel_gemm_splitk_accum_" #oname "_" #aname "_axbpy", \+ gemm_splitk_accum_axpby, atype, otype) \++instantiate_accum(bfloat16, bfloat16_t, float32, float);+instantiate_accum(float16, half, float32, float);+instantiate_accum(float32, float, float32, float);+instantiate_accum(complex64, complex64_t, complex64, complex64_t); // clang-format ondiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/loader.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/loader.hnew file mode 100644index 000000000..1d03c83f8--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/loader.h@@ -0,0 +1,135 @@+++#pragma once++#include "../defines.h"++///////////////////////////////////////////////////////////////////////////////+// Loading helper+///////////////////////////////////////////////////////////////////////////////++namespace steel {++template <+ typename T,+ short BROWS,+ short BCOLS,+ short dst_ld,+ short reduction_dim,+ short tgp_size,+ short alignment = 1,+ short n_reads = (BCOLS * BROWS) / (tgp_size),+ short TCOLS = BCOLS / n_reads,+ short TROWS = tgp_size / TCOLS>+struct BlockLoader {+ STEEL_CONST short n_rows = (BROWS + TROWS - 1) / TROWS;+ STEEL_CONST short vec_size = n_reads;++ // Leading dimension for src+ const int src_ld;+ const int tile_stride;++ // Thread location indices+ const short thread_idx;+ const short bi;+ const short bj;++ // threadgroup and device memory+ threadgroup T* dst;+ const device T* src;++ struct alignas(alignment * sizeof(T)) ReadVector {+ uint8_t v[sizeof(T) * vec_size];+ };++ /* Constructor */+ METAL_FUNC BlockLoader(+ const device T* src_,+ const int src_ld_,+ threadgroup T* dst_,+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],+ ushort simd_lane_id [[thread_index_in_simdgroup]])+ : src_ld(src_ld_),+ tile_stride(reduction_dim ? BCOLS : BROWS * src_ld),+ thread_idx(simd_group_id * 32 + simd_lane_id),+ bi(thread_idx / TCOLS),+ bj(vec_size * (thread_idx % TCOLS)),+ dst(dst_ + bi * dst_ld + bj),+ src(src_ + bi * src_ld + bj) {}++ /* Apply operation to threadgroup without bound checking */+ template <typename UnaryOp>+ METAL_FUNC void apply_inplace_op(thread const UnaryOp& op) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < BROWS; i += TROWS) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < vec_size; j++) {+ dst[i * dst_ld + j] = op.apply(dst[i * dst_ld + j]);+ }+ }+ }++ /* Load from device memory into threadgroup memory - without bound checking */+ METAL_FUNC void load_unsafe() const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < BROWS; i += TROWS) {+ *((threadgroup ReadVector*)(&dst[i * dst_ld])) =+ *((const device ReadVector*)(&src[i * src_ld]));+ }+ }++ /* Load from device memory into threadgroup memory - with bound checking */+ METAL_FUNC void load_safe(short2 src_tile_dim) const {+ src_tile_dim = src_tile_dim - short2(bj, bi);++ // Skip loading if thread has no valid reads+ if (src_tile_dim.x <= 0 || src_tile_dim.y <= 0) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < BROWS; i += TROWS) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < vec_size; j++) {+ dst[i * dst_ld + j] = T(0);+ }+ }+ return;+ }++ // Use fast thread memory for bound checks+ bool tmp_idx[vec_size];+ T tmp_val[vec_size];++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < BROWS; i += TROWS) {+ // Make sure tmp_idx only contains valid indices+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < vec_size; j++) {+ tmp_idx[j] = (i < src_tile_dim.y) && (j < src_tile_dim.x);+ }++ // Read valid indices into tmp_val+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < vec_size; j++) {+ tmp_val[j] = src[(tmp_idx[j] ? i * src_ld + j : 0)];+ }++ // Zero out unneeded values+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < vec_size; j++) {+ tmp_val[j] = tmp_idx[j] ? tmp_val[j] : T(0);+ }++ // Copy values to threadgroup memory+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < vec_size; j++) {+ dst[i * dst_ld + j] = tmp_val[j];+ }+ }+ }++ /* Iteration helper */+ METAL_FUNC void next() {+ src += tile_stride;+ }+};++} // namespace steeldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/mma.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/mma.hnew file mode 100644index 000000000..38f4eec24--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/mma.h@@ -0,0 +1,1144 @@+++#pragma once++#include <metal_simdgroup>+#include <metal_simdgroup_matrix>+#include <metal_stdlib>++#include "../defines.h"+#include "transforms.h"+#include "../utils/integral_constant.h"++using namespace metal;++///////////////////////////////////////////////////////////////////////////////+// MMA helper+///////////////////////////////////////////////////////////////////////////////++namespace steel {++template <typename T, int kFragRows_, int kFragCols_>+struct BaseMMAFrag {+ static_assert(+ kFragRows_ == 8,+ "Only 8 x 8 fragment matrices are currently supported");+ static_assert(+ kFragCols_ == 8,+ "Only 8 x 8 fragment matrices are currently supported");+};++template <typename T>+struct BaseMMAFrag<T, 8, 8> {+ STEEL_CONST int kFragRows = 8;+ STEEL_CONST int kFragCols = 8;++ STEEL_CONST int kElemsPerFrag = (kFragRows * kFragCols) / 32;++ STEEL_CONST int kElemRows = 1;+ STEEL_CONST int kElemCols = 2;++ static_assert(+ kElemRows * kElemCols == kElemsPerFrag,+ "MMAFrag shape is not consistent with MMAFrag size");++ typedef metal::simdgroup_matrix<T, kFragRows, kFragCols> mat_type;+ typedef metal::vec<T, kElemsPerFrag> frag_type;++ METAL_FUNC static constexpr short2 get_coord(ushort simd_lane_id+ [[thread_index_in_simdgroup]]) {+ const short qid = simd_lane_id / 4;+ const short fm = (qid & 4) + ((simd_lane_id / 2) % 4);+ const short fn = (qid & 2) * 2 + (simd_lane_id % 2) * 2;+ return short2{fn, fm};+ }++ template <typename SrcPtrType, typename StrX, typename StrY>+ METAL_FUNC static constexpr void+ load(thread frag_type& dst, SrcPtrType src, StrX str_x, StrY str_y) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[i * kElemCols + j] = static_cast<T>(src[i * str_x + j * str_y]);+ }+ }+ }++ template <+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename LimY,+ typename OffX,+ typename OffY>+ METAL_FUNC static constexpr void load_safe(+ thread frag_type& dst,+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ LimY lim_y,+ OffX off_x = Int<0>{},+ OffY off_y = Int<0>{}) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ if ((off_x + i) < lim_x && (off_y + j) < lim_y) {+ dst[i * kElemCols + j] =+ static_cast<T>(src[(off_x + i) * str_x + (off_x + j) * str_y]);+ } else {+ dst[i * kElemCols + j] = T(0);+ }+ }+ }+ }++ template <typename DstPtrType, typename StrX, typename StrY>+ METAL_FUNC static constexpr void+ store(const thread frag_type& src, DstPtrType dst, StrX str_x, StrY str_y) {+ using U = pointer_element_t<DstPtrType>;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[i * str_x + j * str_y] = static_cast<U>(src[i * kElemCols + j]);+ }+ }+ }++ template <+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename LimY,+ typename OffX,+ typename OffY>+ METAL_FUNC static constexpr void store_safe(+ const thread frag_type& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ LimY lim_y,+ OffX off_x = Int<0>{},+ OffY off_y = Int<0>{}) {+ using U = pointer_element_t<DstPtrType>;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ if ((off_x + i) < lim_x && (off_y + j) < lim_y) {+ dst[(off_x + i) * str_x + (off_y + j) * str_y] =+ static_cast<U>(src[i * kElemCols + j]);+ }+ }+ }+ }++ template <+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename StartX,+ typename StopX,+ typename StartY,+ typename StopY,+ typename OffX,+ typename OffY>+ METAL_FUNC static constexpr void store_slice(+ const thread frag_type& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ StartX start_x,+ StopX stop_x,+ StartY start_y,+ StopY stop_y,+ OffX off_x = Int<0>{},+ OffY off_y = Int<0>{}) {+ using U = pointer_element_t<DstPtrType>;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ if ((off_x + i) < stop_x && (off_x + i) >= start_x &&+ (off_y + j) < stop_y && (off_y + j) >= start_y) {+ dst[(off_x + i) * str_x + (off_y + j) * str_y] =+ static_cast<U>(src[i * kElemCols + j]);+ }+ }+ }+ }++ METAL_FUNC static constexpr void mma(+ thread frag_type& D,+ thread frag_type& A,+ thread frag_type& B,+ thread frag_type& C) {+ mat_type D_mat;+ mat_type A_mat;+ mat_type B_mat;+ mat_type C_mat;++ reinterpret_cast<thread frag_type&>(A_mat.thread_elements()) = A;+ reinterpret_cast<thread frag_type&>(B_mat.thread_elements()) = B;+ reinterpret_cast<thread frag_type&>(C_mat.thread_elements()) = C;++ mma(D_mat, A_mat, B_mat, C_mat);++ D = reinterpret_cast<thread frag_type&>(D_mat.thread_elements());+ }++ METAL_FUNC static constexpr void mma(+ thread mat_type& D,+ thread mat_type& A,+ thread mat_type& B,+ thread mat_type& C) {+ simdgroup_multiply_accumulate(D, A, B, C);+ }+};++template <+ typename T,+ int kTileRows_,+ int kTileCols_,+ class MMAFrag_ = BaseMMAFrag<T, 8, 8>>+struct MMATile {+ using MMAFrag_t = MMAFrag_;+ using elem_type = T;+ STEEL_CONST int kFragRows = MMAFrag_t::kFragRows;+ STEEL_CONST int kFragCols = MMAFrag_t::kFragCols;+ STEEL_CONST int kElemsPerFrag = MMAFrag_t::kElemsPerFrag;++ STEEL_CONST int kTileRows = kTileRows_;+ STEEL_CONST int kTileCols = kTileCols_;++ STEEL_CONST int kRows = kTileRows * kFragRows;+ STEEL_CONST int kCols = kTileCols * kFragCols;++ STEEL_CONST int kNumFrags = kTileRows * kTileCols;+ STEEL_CONST int kElemsPerTile = kNumFrags * kElemsPerFrag;++ typedef typename MMAFrag_t::mat_type mat_type;+ typedef typename MMAFrag_t::frag_type frag_type;++ frag_type val_frags[kNumFrags] = {frag_type(0)};++ METAL_FUNC MMATile() thread {}++ METAL_FUNC constexpr void clear() {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kNumFrags; ++i) {+ val_frags[i] = frag_type(0);+ }+ }++ METAL_FUNC constexpr thread frag_type& frag_at(const short i, const short j) {+ return val_frags[i * kTileCols + j];+ }++ METAL_FUNC constexpr const thread frag_type& frag_at(+ const short i,+ const short j) const {+ return val_frags[i * kTileCols + j];+ }++ METAL_FUNC mat_type mat_at(const short i, const short j) {+ mat_type val_mat;+ STEEL_PRAGMA_UNROLL+ for (short ii = 0; ii < kElemsPerFrag; ++ii) {+ val_mat.thread_elements()[ii] = frag_at(i, j)[ii];+ }+ return val_mat;+ }++ METAL_FUNC thread elem_type* elems() {+ return reinterpret_cast<thread elem_type*>(val_frags);+ }++ METAL_FUNC const thread elem_type* elems() const {+ return reinterpret_cast<const thread elem_type*>(val_frags);+ }++ template <typename U, int w_x, int w_y, int str_x, int str_y>+ METAL_FUNC void load(const threadgroup U* src) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ MMAFrag_t::load(+ frag_at(i, j),+ &(+ src[(i * kFragRows) * w_x * str_x ++ (j * kFragCols) * w_y * str_y]),+ Int<str_x>{},+ Int<str_y>{});+ }+ }+ }++ template <typename U, int w_x, int w_y, int str_x, int str_y>+ METAL_FUNC void store(threadgroup U* dst) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ MMAFrag_t::store(+ frag_at(i, j),+ &(+ dst[(i * kFragRows) * w_x * str_x ++ (j * kFragCols) * w_y * str_y]),+ Int<str_x>{},+ Int<str_y>{});+ }+ }+ }++ template <typename U, int w_x, int w_y>+ METAL_FUNC void load(const device U* src, const int ld) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ MMAFrag_t::load(+ frag_at(i, j),+ &(src[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),+ ld,+ Int<1>{});+ }+ }+ }++ template <typename U, int w_x, int w_y>+ METAL_FUNC void store(device U* dst, const int ld) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ MMAFrag_t::store(+ frag_at(i, j),+ &(dst[(i * kFragRows) * w_x * ld + (j * kFragCols) * w_y]),+ ld,+ Int<1>{});+ }+ }+ }++ template <typename U, int w_x, int w_y>+ METAL_FUNC void+ load_safe(const device U* src, const int ld, const short2 src_tile_dims) {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ MMAFrag_t::load_safe(+ frag_at(i, j),+ src,+ ld,+ Int<1>{},+ src_tile_dims.y,+ src_tile_dims.x,+ (i * kFragRows) * w_x,+ (j * kFragCols) * w_y);+ }+ }+ }++ template <typename U, int w_x, int w_y>+ METAL_FUNC void+ store_safe(device U* dst, const int ld, const short2 dst_tile_dims) const {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ MMAFrag_t::store_safe(+ frag_at(i, j),+ dst,+ ld,+ Int<1>{},+ dst_tile_dims.y,+ dst_tile_dims.x,+ (i * kFragRows) * w_x,+ (j * kFragCols) * w_y);+ }+ }+ }++ template <typename U, int w_x, int w_y>+ METAL_FUNC void store_slice(+ device U* dst,+ const int ld,+ const short2 start,+ const short2 stop) const {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ MMAFrag_t::store_slice(+ frag_at(i, j),+ dst,+ ld,+ Int<1>{},+ start.y,+ stop.y,+ start.x,+ stop.x,+ (i * kFragRows) * w_x,+ (j * kFragCols) * w_y);+ }+ }+ }+};++template <typename T, typename U, int M, int N, int K>+METAL_FUNC void tile_matmad(+ thread MMATile<T, M, N>& D,+ thread MMATile<U, M, K>& A,+ thread MMATile<U, K, N>& B,+ thread MMATile<T, M, N>& C) {+ STEEL_PRAGMA_UNROLL+ for (short m = 0; m < M; ++m) {+ STEEL_PRAGMA_UNROLL+ for (short n = 0; n < N; ++n) {+ short n_serp = (m % 2) ? (N - 1 - n) : n;+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < K; ++k) {+ MMATile<T, M, N>::MMAFrag_t::mma(+ D.frag_at(m, n_serp),+ A.frag_at(m, k),+ B.frag_at(k, n_serp),+ C.frag_at(m, n_serp));+ }+ }+ }+}++template <typename InT>+struct TransformNone<complex64_t, InT> {+ static METAL_FUNC complex64_t apply(complex64_t x) {+ return x;+ }+ static METAL_FUNC complex64_t apply(complex64_t x, complex64_t) {+ return x;+ }+};++template <+ typename T,+ typename U,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ short lda_tgp,+ short ldb_tgp,+ typename AccumType = float,+ typename Epilogue = TransformNone<U, AccumType>>+struct BlockMMA {+ // MMAFrag size+ STEEL_CONST short kFragSize = 8;+ using MMAFrag_acc_t = BaseMMAFrag<AccumType, kFragSize, kFragSize>;++ // Warp tile simdgroup matrix strides along M+ STEEL_CONST short TM_stride = kFragSize * WM;+ // Warp tile simdgroup matrix strides along M+ STEEL_CONST short TN_stride = kFragSize * WN;++ // Warp tile size along M+ STEEL_CONST short TM = BM / (kFragSize * WM);+ // Warp tile size along N+ STEEL_CONST short TN = BN / (kFragSize * WN);++ // Threadgroup A strides+ STEEL_CONST short A_str_m = transpose_a ? 1 : lda_tgp; // M+ STEEL_CONST short A_str_k = transpose_a ? lda_tgp : 1; // K++ // Threadgroup B strides+ STEEL_CONST short B_str_k = transpose_b ? 1 : ldb_tgp; // K+ STEEL_CONST short B_str_n = transpose_b ? ldb_tgp : 1; // N++ // Threadgroup strides along K+ STEEL_CONST short tile_stride_a = kFragSize * A_str_k;+ STEEL_CONST short tile_stride_b = kFragSize * B_str_k;++ // Simdgroup matrices+ MMATile<AccumType, TM, 1, MMAFrag_acc_t> Atile;+ MMATile<AccumType, 1, TN, MMAFrag_acc_t> Btile;+ MMATile<AccumType, TM, TN, MMAFrag_acc_t> Ctile;++ // Offsets within threadgroup+ short sm;+ short sn;++ short As_offset;+ short Bs_offset;++ /* Constructor */+ METAL_FUNC BlockMMA(+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],+ ushort simd_lane_id [[thread_index_in_simdgroup]]) {+ // Determine thread position in simdgroup matrix+ short tm = kFragSize * (simd_group_id / WN);+ short tn = kFragSize * (simd_group_id % WN);++ short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id);+ sm = simd_coord.y;+ sn = simd_coord.x;++ // Determine thread and simdgroup offset+ As_offset = (tm + sm) * A_str_m + (sn)*A_str_k; // M, K+ Bs_offset = (sm)*B_str_k + (tn + sn) * B_str_n; // K, N++ sm += tm;+ sn += tn;+ }++ /* (BM, BK) X (BK, BN) multiply accumulate function */+ METAL_FUNC void mma(const threadgroup T* As, const threadgroup T* Bs) {+ // Adjust for simdgroup and thread location+ As += As_offset;+ Bs += Bs_offset;++ // Iterate over BK in blocks of kFragSize+ STEEL_PRAGMA_UNROLL+ for (short kk = 0; kk < BK; kk += kFragSize) {+ simdgroup_barrier(mem_flags::mem_none);++ Atile.template load<T, WM, 1, A_str_m, A_str_k>(As);++ simdgroup_barrier(mem_flags::mem_none);++ Btile.template load<T, 1, WN, B_str_k, B_str_n>(Bs);++ simdgroup_barrier(mem_flags::mem_none);++ tile_matmad(Ctile, Atile, Btile, Ctile);++ // Progress to next simdgroup tile+ As += tile_stride_a;+ Bs += tile_stride_b;+ }+ }++ /* Store results from simdgroup_matrix results into device memory */+ METAL_FUNC void store_result(device U* D, const int ldd) {+ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {+ Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]);+ }++ // Adjust for simdgroup and thread location+ D += sm * ldd + sn;++ Ctile.template store<U, WM, WN>(D, ldd);+ }++ METAL_FUNC void+ store_result_slice(device U* D, const int ldd, short2 start, short2 stop) {+ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {+ Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]);+ }++ D += sm * ldd + sn;+ start -= short2(sn, sm);+ stop -= short2(sn, sm);++ // TODO: Check the start as well+ if (stop.y <= 0 || stop.x <= 0) {+ return;+ }++ Ctile.template store_slice<U, WM, WN>(D, ldd, start, stop);+ }++ METAL_FUNC void+ store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) {+ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {+ Ctile.elems()[i] = Epilogue::apply(Ctile.elems()[i]);+ }++ // Adjust for simdgroup and thread location+ D += sm * ldd + sn;+ dst_tile_dims -= short2(sn, sm);++ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)+ return;++ Ctile.template store_safe<U, WM, WN>(D, ldd, dst_tile_dims);+ }++ /* Apply epilogue */+ template <typename UnaryEpilogue>+ METAL_FUNC void apply_epilogue(thread const UnaryEpilogue& epilogue_op) {+ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ctile)::kElemsPerTile; i++) {+ Ctile.elems()[i] = epilogue_op.apply(Ctile.elems()[i]);+ }+ }++ /* Apply epilogue */+ template <typename BinaryEpilogue>+ METAL_FUNC void apply_epilogue(+ const device U* C,+ const int ldc,+ const int fdc,+ thread const BinaryEpilogue& epilogue_op) {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;++ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in C+ thread auto& accum = Ctile.frag_at(i, j);+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < decltype(Ctile)::kElemsPerFrag; k++) {+ accum[k] = epilogue_op.apply(accum[k], C[offset_c + k * fdc]);+ }+ }+ }+ }++ /* Apply epilogue */+ template <typename BinaryEpilogue>+ METAL_FUNC void apply_epilogue_safe(+ const device U* C,+ const int ldc,+ const int fdc,+ short2 dst_tile_dims,+ thread const BinaryEpilogue& epilogue_op) {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;+ dst_tile_dims -= short2(sn, sm);++ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)+ return;++ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in C+ thread auto& accum = Ctile.frag_at(i, j);+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;++ constexpr short kelems = decltype(Ctile)::kElemsPerFrag;++ // Read C+ U c_elems[kelems] = {0};++ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ if ((j * TN_stride + k) < dst_tile_dims.x) {+ c_elems[k] = C[offset_c + k * fdc];+ }+ }++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ accum[k] = epilogue_op.apply(accum[k], c_elems[k]);+ }+ }+ }+ }++ /* Store results from simdgroup_matrix results into device memory */+ METAL_FUNC void store_result(+ device U* D,+ const int ldd,+ const device U* C,+ const int ldc,+ const int fdc,+ thread const Epilogue& epilogue_op) const {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;+ D += (sm)*ldd + sn;++ constexpr short kelems = decltype(Ctile)::kElemsPerFrag;++ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in C+ thread const auto& accum = Ctile.frag_at(i, j);+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;+ int offset_d = (i * TM_stride) * ldd + (j * TN_stride);++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ D[offset_d + k] = epilogue_op.apply(accum[k], C[offset_c + k * fdc]);+ }+ }+ }+ }++ METAL_FUNC void store_result_safe(+ device U* D,+ const int ldd,+ const device U* C,+ const int ldc,+ const int fdc,+ short2 dst_tile_dims,+ thread const Epilogue& epilogue_op) const {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;+ D += (sm)*ldd + sn;+ dst_tile_dims -= short2(sn, sm);++ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)+ return;++ constexpr short kelems = decltype(Ctile)::kElemsPerFrag;++ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < TM; i++) {+ if (i * TM_stride < dst_tile_dims.y) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in C+ thread const auto& accum = Ctile.frag_at(i, j);+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;+ int offset_d = (i * TM_stride) * ldd + (j * TN_stride);++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ if ((j * TN_stride + k) < dst_tile_dims.x) {+ D[offset_d + k] =+ epilogue_op.apply(accum[k], C[offset_c + k * fdc]);+ }+ }+ }+ }+ }+ }+};++template <+ typename U,+ int BM,+ int BN,+ int BK,+ int WM,+ int WN,+ bool transpose_a,+ bool transpose_b,+ short lda_tgp,+ short ldb_tgp,+ typename AccumType,+ typename Epilogue>+struct BlockMMA<+ complex64_t,+ U,+ BM,+ BN,+ BK,+ WM,+ WN,+ transpose_a,+ transpose_b,+ lda_tgp,+ ldb_tgp,+ AccumType,+ Epilogue> {+ static_assert(+ metal::is_same_v<AccumType, float>,+ "BlockMMA<complex64_t,...> expects float accumulators");+ static_assert(+ metal::is_same_v<U, complex64_t>,+ "For complex BlockMMA, U must be complex64_t; use a different epilogue for projections");+ // MMAFrag size+ STEEL_CONST short kFragSize = 8;+ using MMAFrag_acc_t = BaseMMAFrag<AccumType, kFragSize, kFragSize>;++ // Warp tile simdgroup matrix strides along M+ STEEL_CONST short TM_stride = kFragSize * WM;+ // Warp tile simdgroup matrix strides along M+ STEEL_CONST short TN_stride = kFragSize * WN;++ // Warp tile size along M+ STEEL_CONST short TM = BM / (kFragSize * WM);+ // Warp tile size along N+ STEEL_CONST short TN = BN / (kFragSize * WN);++ // Threadgroup A strides+ STEEL_CONST short A_str_m = transpose_a ? 1 : lda_tgp; // M+ STEEL_CONST short A_str_k = transpose_a ? lda_tgp : 1; // K++ // Threadgroup B strides+ STEEL_CONST short B_str_k = transpose_b ? 1 : ldb_tgp; // K+ STEEL_CONST short B_str_n = transpose_b ? ldb_tgp : 1; // N++ // Threadgroup strides along K+ STEEL_CONST short tile_stride_a = kFragSize * A_str_k;+ STEEL_CONST short tile_stride_b = kFragSize * B_str_k;++ // When indexing complex as float[2]+ STEEL_CONST short A_str_m_f = A_str_m * 2;+ STEEL_CONST short A_str_k_f = A_str_k * 2;+ STEEL_CONST short B_str_k_f = B_str_k * 2;+ STEEL_CONST short B_str_n_f = B_str_n * 2;+ STEEL_CONST short tile_stride_a_f = tile_stride_a * 2;+ STEEL_CONST short tile_stride_b_f = tile_stride_b * 2;++ // Accumulators (real/imag)+ MMATile<AccumType, TM, TN, MMAFrag_acc_t> Ctile_r;+ MMATile<AccumType, TM, TN, MMAFrag_acc_t> Ctile_i;++ // Offsets within threadgroup+ short sm, sn;+ short As_offset, Bs_offset;++ /* Constructor */+ METAL_FUNC BlockMMA(+ ushort simd_group_id [[simdgroup_index_in_threadgroup]],+ ushort simd_lane_id [[thread_index_in_simdgroup]]) {+ // Determine thread position in simdgroup matrix+ short tm = kFragSize * (simd_group_id / WN);+ short tn = kFragSize * (simd_group_id % WN);++ short2 simd_coord = MMAFrag_acc_t::get_coord(simd_lane_id);+ sm = simd_coord.y;+ sn = simd_coord.x;++ // Determine thread and simdgroup offset+ As_offset = (tm + sm) * A_str_m + (sn)*A_str_k; // (M,K)+ Bs_offset = (sm)*B_str_k + (tn + sn) * B_str_n; // (K,N)++ sm += tm;+ sn += tn;+ }++ /* Karatsuba MMA: 3 real MMAs per K-chunk */+ METAL_FUNC void mma(+ const threadgroup complex64_t* As,+ const threadgroup complex64_t* Bs) {+ // Adjust for simdgroup and thread location+ As += As_offset;+ Bs += Bs_offset;+ threadgroup const float* As_f =+ reinterpret_cast<threadgroup const float*>(As);+ threadgroup const float* Bs_f =+ reinterpret_cast<threadgroup const float*>(Bs);++ // Iterate over BK in blocks of kFragSize+ STEEL_PRAGMA_UNROLL+ for (short kk = 0; kk < BK; kk += kFragSize) {+ simdgroup_barrier(mem_flags::mem_none);++ MMATile<AccumType, TM, 1, MMAFrag_acc_t> Ar, Ai;+ Ar.template load<float, WM, 1, A_str_m_f, A_str_k_f>(As_f + 0);+ Ai.template load<float, WM, 1, A_str_m_f, A_str_k_f>(As_f + 1);++ simdgroup_barrier(mem_flags::mem_none);++ MMATile<AccumType, 1, TN, MMAFrag_acc_t> Br, Bi;+ Br.template load<float, 1, WN, B_str_k_f, B_str_n_f>(Bs_f + 0);+ Bi.template load<float, 1, WN, B_str_k_f, B_str_n_f>(Bs_f + 1);++ simdgroup_barrier(mem_flags::mem_none);++ // P = Ar*Br ; Q = Ai*Bi ; R = (Ar+Ai)*(Br+Bi)+ MMATile<AccumType, TM, TN, MMAFrag_acc_t> P, Q, R;++ tile_matmad(P, Ar, Br, P);+ tile_matmad(Q, Ai, Bi, Q);++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ar)::kElemsPerTile; ++i)+ Ar.elems()[i] += Ai.elems()[i];+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Br)::kElemsPerTile; ++i)+ Br.elems()[i] += Bi.elems()[i];++ tile_matmad(R, Ar, Br, R);++ // C_r += P - Q ; C_i -= Q+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ctile_r)::kElemsPerTile; ++i) {+ const auto p = P.elems()[i];+ const auto q = Q.elems()[i];+ const auto r = R.elems()[i];+ Ctile_r.elems()[i] += (p - q);+ Ctile_i.elems()[i] += (r - p - q);+ }++ // Progress to next simdgroup tile+ As_f += tile_stride_a_f;+ Bs_f += tile_stride_b_f;+ }+ }++ /* Store results from simdgroup_matrix results into device memory */+ METAL_FUNC void store_result(device U* D, const int ldd) {+ // Adjust for simdgroup and thread location+ D += sm * ldd + sn;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ thread const auto& r = Ctile_r.frag_at(i, j);+ thread const auto& im = Ctile_i.frag_at(i, j);+ int off = (i * TM_stride) * ldd + (j * TN_stride);+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) {+ D[off + k] = Epilogue::apply(complex64_t(r[k], im[k]));+ }+ }+ }+ }++ METAL_FUNC void+ store_result_slice(device U* D, const int ldd, short2 start, short2 stop) {+ D += sm * ldd + sn;+ start -= short2(sn, sm);+ stop -= short2(sn, sm);++ if (stop.y <= 0 || stop.x <= 0)+ return;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; ++i) {+ const int row = i * TM_stride;+ if (row >= start.y && row < stop.y) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; ++j) {+ const int off = row * ldd + (j * TN_stride);+ thread const auto& r = Ctile_r.frag_at(i, j);+ thread const auto& im = Ctile_i.frag_at(i, j);++ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; ++k) {+ const int col = j * TN_stride + k;+ if (col >= start.x && col < stop.x) {+ D[off + k] = Epilogue::apply(complex64_t(r[k], im[k]));+ }+ }+ }+ }+ }+ }++ METAL_FUNC void+ store_result_safe(device U* D, const int ldd, short2 dst_tile_dims) {+ D += sm * ldd + sn;+ dst_tile_dims -= short2(sn, sm);+ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)+ return;+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ if (i * TM_stride < dst_tile_dims.y) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ int off = (i * TM_stride) * ldd + (j * TN_stride);+ thread const auto& r = Ctile_r.frag_at(i, j);+ thread const auto& im = Ctile_i.frag_at(i, j);+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) {+ if ((j * TN_stride + k) < dst_tile_dims.x) {+ D[off + k] = Epilogue::apply(complex64_t(r[k], im[k]));+ }+ }+ }+ }+ }+ }++ /* Apply epilogue */+ template <typename UnaryEpilogue>+ METAL_FUNC void apply_epilogue(thread const UnaryEpilogue& epilogue_op) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < decltype(Ctile_r)::kElemsPerTile; i++) {+ complex64_t out = epilogue_op.apply(+ complex64_t(Ctile_r.elems()[i], Ctile_i.elems()[i]));+ Ctile_r.elems()[i] = out.real;+ Ctile_i.elems()[i] = out.imag;+ }+ }++ /* Apply epilogue */+ template <typename BinaryEpilogue>+ METAL_FUNC void apply_epilogue(+ const device U* C,+ const int ldc,+ const int fdc,+ thread const BinaryEpilogue& epilogue_op) {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;++ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in Cr, Ci+ thread auto& r = Ctile_r.frag_at(i, j);+ thread auto& im = Ctile_i.frag_at(i, j);+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;++ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < decltype(Ctile_r)::kElemsPerFrag; k++) {+ complex64_t out = epilogue_op.apply(+ complex64_t(r[k], im[k]), C[offset_c + k * fdc]);+ r[k] = out.real;+ im[k] = out.imag;+ }+ }+ }+ }++ /* Apply epilogue */+ template <typename BinaryEpilogue>+ METAL_FUNC void apply_epilogue_safe(+ const device U* C,+ const int ldc,+ const int fdc,+ short2 dst_tile_dims,+ thread const BinaryEpilogue& epilogue_op) {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;+ dst_tile_dims -= short2(sn, sm);++ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)+ return;++ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in Cr, Ci+ thread auto& r = Ctile_r.frag_at(i, j);+ thread auto& im = Ctile_i.frag_at(i, j);+ int offset_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;++ constexpr short kelems = decltype(Ctile_r)::kElemsPerFrag;+ complex64_t tmp[kelems];++ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ if ((j * TN_stride + k) < dst_tile_dims.x &&+ (i * TM_stride) < dst_tile_dims.y) {+ tmp[k] = C[offset_c + k * fdc];+ } else {+ tmp[k] = complex64_t(0.0f, 0.0f);+ }+ }++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ complex64_t out = epilogue_op.apply(complex64_t(r[k], im[k]), tmp[k]);+ r[k] = out.real;+ im[k] = out.imag;+ }+ }+ }+ }++ /* Store results from simdgroup_matrix results into device memory */+ METAL_FUNC void store_result(+ device U* D,+ const int ldd,+ const device U* C,+ const int ldc,+ const int fdc,+ thread const Epilogue& epilogue_op) const {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;+ D += (sm)*ldd + sn;++ constexpr short kelems = decltype(Ctile_r)::kElemsPerFrag;++ // Loop over all simdgroup tiles+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in Cr, Ci+ thread const auto& r = Ctile_r.frag_at(i, j);+ thread const auto& im = Ctile_i.frag_at(i, j);+ int off_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;+ int off_d = (i * TM_stride) * ldd + (j * TN_stride);++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ D[off_d + k] =+ epilogue_op.apply(complex64_t(r[k], im[k]), C[off_c + k * fdc]);+ }+ }+ }+ }++ METAL_FUNC void store_result_safe(+ device U* D,+ const int ldd,+ const device U* C,+ const int ldc,+ const int fdc,+ short2 dst_tile_dims,+ thread const Epilogue& epilogue_op) const {+ // Adjust for simdgroup and thread location+ C += (sm)*ldc + (sn)*fdc;+ D += (sm)*ldd + sn;+ dst_tile_dims -= short2(sn, sm);++ if (dst_tile_dims.x <= 0 || dst_tile_dims.y <= 0)+ return;++ constexpr short kelems = decltype(Ctile_r)::kElemsPerFrag;++ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < TM; i++) {+ if (i * TM_stride < dst_tile_dims.y) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < TN; j++) {+ // Get accumulated result and associated offset in Cr, Ci+ thread const auto& r = Ctile_r.frag_at(i, j);+ thread const auto& im = Ctile_i.frag_at(i, j);+ int off_c = (i * TM_stride) * ldc + (j * TN_stride) * fdc;+ int off_d = (i * TM_stride) * ldd + (j * TN_stride);++ // Apply epilogue+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < kelems; k++) {+ if ((j * TN_stride + k) < dst_tile_dims.x) {+ D[off_d + k] = epilogue_op.apply(+ complex64_t(r[k], im[k]), C[off_c + k * fdc]);+ }+ }+ }+ }+ }+ }+};++} // namespace steeldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/nax.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/nax.hnew file mode 100644index 000000000..738ce48f8--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/nax.h@@ -0,0 +1,1082 @@+++#pragma once++#include <metal_simdgroup>+#include <metal_simdgroup_matrix>+#include <metal_stdlib>++#include "../defines.h"+#include "transforms.h"+#include "../utils/integral_constant.h"++#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>++using namespace metal;++///////////////////////////////////////////////////////////////////////////////+// MMA helper+///////////////////////////////////////////////////////////////////////////////++namespace steel {++///////////////////////////////////////////////////////////////////////////////+// NAX Steel with new tiles+///////////////////////////////////////////////////////////////////////////////++struct BaseNAXFrag {+ STEEL_CONST short kFragRows = 16;+ STEEL_CONST short kFragCols = 16;++ STEEL_CONST short kElemsPerFrag = (kFragRows * kFragCols) / 32;++ STEEL_CONST short kElemRows = 2;+ STEEL_CONST short kElemCols = 4;++ STEEL_CONST short kElemRowsJump = 8;++ static_assert(+ kElemRows * kElemCols == kElemsPerFrag,+ "MMAFrag shape is not consistent with MMAFrag size");++ template <typename U>+ using dtype_frag_t = typename metal::vec<U, kElemsPerFrag>;++ METAL_FUNC static short2 get_coord() {+ const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort());+ const short qid = simd_lane_id >> 2;+ const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3));+ const short fn = ((qid & 2) | (simd_lane_id & 1)) * 4;+ return short2{fn, fm};+ }++ METAL_FUNC static short2 get_coord(short idx) {+ const ushort simd_lane_id = __metal_get_thread_index_in_simdgroup(ushort());+ const short qid = simd_lane_id >> 2;+ const short fm = ((qid & 4) | ((simd_lane_id >> 1) & 3)) + (idx >> 2) * 8;+ const short fn = ((qid & 2) | (simd_lane_id & 1)) * 4 + idx % 4;+ return short2{fn, fm};+ }++ template <+ typename T,+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void load(+ thread dtype_frag_t<T>& dst,+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ OffX off_x = {},+ OffY off_y = {}) {+ const short2 sc = get_coord();+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ const auto r = off_x + i * kElemRowsJump + sc.y;+ const auto c = off_y + sc.x;++ if constexpr (metal::is_same_v<StrY, Int<1>>) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[i * kElemCols + j] = static_cast<T>(src[r * str_x + c + j]);+ }+ } else {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[i * kElemCols + j] =+ static_cast<T>(src[r * str_x + (c + j) * str_y]);+ }+ }+ }+ }++ template <+ typename T,+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void load_rows(+ thread dtype_frag_t<T>& dst,+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ OffX off_x = {},+ OffY off_y = {}) {+ const short2 sc = get_coord();+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ const auto r = off_x + i * kElemRowsJump + sc.y;+ const auto c = off_y + sc.x;++ if (r < lim_x) {+ if constexpr (metal::is_same_v<StrY, Int<1>>) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[i * kElemCols + j] = static_cast<T>(src[r * str_x + (c + j)]);+ }+ } else {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[i * kElemCols + j] =+ static_cast<T>(src[r * str_x + (c + j) * str_y]);+ }+ }++ } else {+ dst = dtype_frag_t<T>(0);+ }+ }+ }++ template <+ typename T,+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename LimY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void load_safe(+ thread dtype_frag_t<T>& dst,+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ LimY lim_y,+ OffX off_x = {},+ OffY off_y = {}) {+ const short2 sc = get_coord();+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ const auto r = off_x + i * kElemRowsJump + sc.y;+ const auto c = off_y + sc.x;+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ if (r < lim_x && (c + j) < lim_y) {+ dst[i * kElemCols + j] =+ static_cast<T>(src[r * str_x + (c + j) * str_y]);+ } else {+ dst[i * kElemCols + j] = T(0);+ }+ }+ }+ }++ template <+ typename T,+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void store(+ const thread dtype_frag_t<T>& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ OffX off_x = {},+ OffY off_y = {}) {+ using U = pointer_element_t<DstPtrType>;++ const short2 sc = get_coord();+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ const auto r = off_x + i * kElemRowsJump + sc.y;+ const auto c = off_y + sc.x;++ if constexpr (metal::is_same_v<StrY, Int<1>>) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[r * str_x + c + j] = static_cast<U>(src[i * kElemCols + j]);+ }+ } else {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[r * str_x + (c + j) * str_y] =+ static_cast<U>(src[i * kElemCols + j]);+ }+ }+ }+ }++ template <+ typename T,+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void store_rows(+ const thread dtype_frag_t<T>& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ OffX off_x = {},+ OffY off_y = {}) {+ using U = pointer_element_t<DstPtrType>;++ const short2 sc = get_coord();+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ const auto r = off_x + i * kElemRowsJump + sc.y;+ const auto c = off_y + sc.x;++ if (r < lim_x) {+ if constexpr (metal::is_same_v<StrY, Int<1>>) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[r * str_x + c + j] = static_cast<U>(src[i * kElemCols + j]);+ }+ } else {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ dst[r * str_x + (c + j) * str_y] =+ static_cast<U>(src[i * kElemCols + j]);+ }+ }+ }+ }+ }++ template <+ typename T,+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename LimY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void store_safe(+ const thread dtype_frag_t<T>& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ LimY lim_y,+ OffX off_x = {},+ OffY off_y = {}) {+ using U = pointer_element_t<DstPtrType>;++ const short2 sc = get_coord();+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ const auto r = off_x + i * kElemRowsJump + sc.y;+ const auto c = off_y + sc.x;++ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ if (r < lim_x && (c + j) < lim_y) {+ dst[r * str_x + (c + j) * str_y] =+ static_cast<U>(src[i * kElemCols + j]);+ }+ }+ }+ }++ template <+ typename T,+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename StartX,+ typename StopX,+ typename StartY,+ typename StopY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC static constexpr void store_slice(+ const thread dtype_frag_t<T>& src,+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ StartX start_x,+ StopX stop_x,+ StartY start_y,+ StopY stop_y,+ OffX off_x = Int<0>{},+ OffY off_y = Int<0>{}) {+ using U = pointer_element_t<DstPtrType>;++ const short2 sc = get_coord();++ const_for_loop<0, kElemRows, 1>([&](auto idx_row) {+ const auto r = off_x + idx_row * Int<kElemRowsJump>{};+ if (r >= stop_x - sc.y || r < start_x - sc.y) {+ return;+ }++ const_for_loop<0, kElemCols, 1>([&](auto idx_col) {+ const auto c = off_y + idx_col;+ if (c >= stop_y - sc.x || c < start_y - sc.x) {+ return;+ }++ const auto src_idx = idx_row * Int<kElemCols>{} + idx_col;+ dst[(r + sc.y) * str_x + (c + sc.x) * str_y] =+ static_cast<U>(src[src_idx]);+ });+ });+ }++ template <typename Op, typename T>+ METAL_FUNC static constexpr void row_reduce(+ thread const dtype_frag_t<T>& inp_vals,+ thread T* reduced_vals) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ T thr_reduce = Op::apply(+ Op::apply(inp_vals[i * kElemCols + 0], inp_vals[i * kElemCols + 1]),+ Op::apply(inp_vals[i * kElemCols + 2], inp_vals[i * kElemCols + 3]));++ T qgr_reduce = simd_shuffle_xor(thr_reduce, ushort(1));+ qgr_reduce = Op::apply(thr_reduce, qgr_reduce);++ T sgr_reduce = simd_shuffle_xor(qgr_reduce, ushort(8));+ sgr_reduce = Op::apply(qgr_reduce, sgr_reduce);++ reduced_vals[i] = Op::apply(reduced_vals[i], sgr_reduce);+ }+ }++ template <typename Op, typename T>+ METAL_FUNC static constexpr void row_bin_op(+ thread dtype_frag_t<T>& inp_vals,+ thread T* row_vals) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kElemRows; i++) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kElemCols; j++) {+ inp_vals[i * kElemCols + j] =+ Op::apply(inp_vals[i * kElemCols + j], row_vals[i]);+ }+ }+ }+};++template <+ typename T,+ short kRows_,+ short kCols_,+ typename NAXFrag_t = BaseNAXFrag>+struct NAXSubTile {+ STEEL_CONST short kRows = kRows_;+ STEEL_CONST short kCols = kCols_;++ STEEL_CONST short kFragRows = NAXFrag_t::kFragRows;+ STEEL_CONST short kFragCols = NAXFrag_t::kFragCols;+ STEEL_CONST short kElemsPerFrag = NAXFrag_t::kElemsPerFrag;++ STEEL_CONST short kSubTileRows = kRows / kFragRows;+ STEEL_CONST short kSubTileCols = kCols / kFragCols;++ STEEL_CONST short kNumFrags = kSubTileRows * kSubTileCols;+ STEEL_CONST short kElemsPerSubTile = kNumFrags * kElemsPerFrag;++ STEEL_CONST int kRowsPerThread = kSubTileRows * NAXFrag_t::kElemRows;+ STEEL_CONST int kColsPerThread = kSubTileCols * NAXFrag_t::kElemCols;++ STEEL_CONST short kFragThrRows = NAXFrag_t::kElemRows;+ STEEL_CONST short kFragThrCols = NAXFrag_t::kElemCols;+ STEEL_CONST short kFragRowsJump = NAXFrag_t::kElemRowsJump;++ using frag_type = typename NAXFrag_t::template dtype_frag_t<T>;++ frag_type val_frags[kNumFrags];++ METAL_FUNC constexpr void clear() {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kNumFrags; ++i) {+ val_frags[i] = frag_type(0);+ }+ }++ METAL_FUNC constexpr thread frag_type& frag_at(const short i, const short j) {+ return val_frags[i * kSubTileCols + j];+ }++ METAL_FUNC constexpr const thread frag_type& frag_at(+ const short i,+ const short j) const {+ return val_frags[i * kSubTileCols + j];+ }++ template <int i, int j>+ METAL_FUNC constexpr thread frag_type& frag_at() {+ return val_frags[i * kSubTileCols + j];+ }++ template <int i, int j>+ METAL_FUNC constexpr const thread frag_type& frag_at() const {+ return val_frags[i * kSubTileCols + j];+ }++ METAL_FUNC thread T* elems() {+ return reinterpret_cast<thread T*>(val_frags);+ }++ METAL_FUNC const thread T* elems() const {+ return reinterpret_cast<const thread T*>(val_frags);+ }++ template <typename Op>+ METAL_FUNC void row_reduce(thread metal::vec<T, kRowsPerThread>& vals) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::template row_reduce<Op>(+ frag_at(i, j), &vals[i * kFragThrRows]);+ }+ }+ }++ template <typename Op>+ METAL_FUNC void row_bin_op(thread metal::vec<T, kRowsPerThread>& vals) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::template row_bin_op<Op>(+ frag_at(i, j), &vals[i * kFragThrRows]);+ }+ }+ }++ template <+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void load(+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ OffX off_x = {},+ OffY off_y = {}) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::load(+ frag_at(i, j),+ src,+ str_x,+ str_y,+ off_x + i * kFragRows,+ off_y + j * kFragCols);+ }+ }+ }++ template <+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void store(+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ OffX off_x = {},+ OffY off_y = {}) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::store(+ frag_at(i, j),+ dst,+ str_x,+ str_y,+ off_x + i * kFragRows,+ off_y + j * kFragCols);+ }+ }+ }++ template <+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void load_rows(+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ OffX off_x = {},+ OffY off_y = {}) {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::load_rows(+ frag_at(i, j),+ src,+ str_x,+ str_y,+ lim_x,+ off_x + (i * kFragRows),+ off_y + (j * kFragCols));+ }+ }+ }++ template <+ typename SrcPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename LimY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void load_safe(+ SrcPtrType src,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ LimY lim_y,+ OffX off_x = {},+ OffY off_y = {}) {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::load_safe(+ frag_at(i, j),+ src,+ str_x,+ str_y,+ lim_x,+ lim_y,+ off_x + (i * kFragRows),+ off_y + (j * kFragCols));+ }+ }+ }++ template <+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename LimY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void store_safe(+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ LimY lim_y,+ OffX off_x = {},+ OffY off_y = {}) const {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::store_safe(+ frag_at(i, j),+ dst,+ str_x,+ str_y,+ lim_x,+ lim_y,+ off_x + (i * kFragRows),+ off_y + (j * kFragCols));+ }+ }+ }++ template <+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename LimX,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void store_rows(+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ LimX lim_x,+ OffX off_x = {},+ OffY off_y = {}) const {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kSubTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kSubTileCols; ++j) {+ NAXFrag_t::store_safe(+ frag_at(i, j),+ dst,+ str_x,+ str_y,+ lim_x,+ off_x + (i * kFragRows),+ off_y + (j * kFragCols));+ }+ }+ }++ template <+ typename DstPtrType,+ typename StrX,+ typename StrY,+ typename StartX,+ typename StopX,+ typename StartY,+ typename StopY,+ typename OffX = Int<0>,+ typename OffY = Int<0>>+ METAL_FUNC constexpr void store_slice(+ DstPtrType dst,+ StrX str_x,+ StrY str_y,+ StartX start_x,+ StopX stop_x,+ StartY start_y,+ StopY stop_y,+ OffX off_x = Int<0>{},+ OffY off_y = Int<0>{}) const {+ const_for_loop<0, kSubTileRows, 1>([&](auto idx_row) {+ const_for_loop<0, kSubTileCols, 1>([&](auto idx_col) {+ NAXFrag_t::store_slice(+ frag_at<idx_row.value, idx_col.value>(),+ dst,+ str_x,+ str_y,+ start_x,+ stop_x,+ start_y,+ stop_y,+ off_x + idx_row * Int<kFragRows>{},+ off_y + idx_col * Int<kFragCols>{});+ });+ });+ }+};++template <+ short RC,+ short CC,+ short RA,+ short CA,+ short RB,+ short CB,+ typename CType,+ typename AType,+ typename BType,+ bool transpose_a,+ bool transpose_b,+ typename NAXFrag_t = BaseNAXFrag>+METAL_FUNC void subtile_matmad_nax(+ thread NAXSubTile<CType, RC, CC, NAXFrag_t>& C,+ thread NAXSubTile<AType, RA, CA, NAXFrag_t>& A,+ metal::bool_constant<transpose_a>,+ thread NAXSubTile<BType, RB, CB, NAXFrag_t>& B,+ metal::bool_constant<transpose_b>) {+ // Static checks+ constexpr short FMa = transpose_a ? CA : RA;+ constexpr short FMc = RC;+ static_assert(FMa == FMc, "NAX matmul: M dimensions do not match");++ constexpr short FNb = transpose_b ? RB : CB;+ constexpr short FNc = CC;+ static_assert(FNb == FNc, "NAX matmul: N dimensions do not match");++ constexpr short FKa = transpose_a ? RA : CA;+ constexpr short FKb = transpose_b ? CB : RB;+ static_assert(FKa == FKb, "NAX matmul: N dimensions do not match");++ constexpr short FM = FMc;+ constexpr short FN = FNc;+ constexpr short FK = FKa;++ constexpr int TM = FM / 16;+ constexpr int TN = FN / 16;+ constexpr int TK = FK / 16;++ // Create Matmul descriptor+ constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor(+ FM,+ FN,+ FK,+ transpose_a,+ transpose_b,+ true,+ mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate);++ // Create matmul op+ mpp::tensor_ops::matmul2d<desc, metal::execution_simdgroup> gemm_op;++ // Create matmul operands in registers+ auto ct_a =+ gemm_op.template get_left_input_cooperative_tensor<AType, BType, CType>();+ auto ct_b =+ gemm_op+ .template get_right_input_cooperative_tensor<AType, BType, CType>();++ // Create matmul output in register+ auto ct_c = gemm_op.template get_destination_cooperative_tensor<+ decltype(ct_a),+ decltype(ct_b),+ CType>();++ // Load A in to left operand registers+ STEEL_PRAGMA_UNROLL+ for (short mm = 0; mm < TM; mm++) {+ STEEL_PRAGMA_UNROLL+ for (short kk = 0; kk < TK; kk++) {+ const short fi = transpose_a ? kk : mm;+ const short fj = transpose_a ? mm : kk;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < 8; i++) {+ ct_a[(TK * mm + kk) * 8 + i] = A.frag_at(fi, fj)[i];+ }+ }+ }++ // Load B into right operand registers+ STEEL_PRAGMA_UNROLL+ for (short nn = 0; nn < TN; nn++) {+ STEEL_PRAGMA_UNROLL+ for (short kk = 0; kk < TK; kk++) {+ const short fi = transpose_b ? nn : kk;+ const short fj = transpose_b ? kk : nn;++ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < 8; i++) {+ ct_b[(TN * kk + nn) * 8 + i] = B.frag_at(fi, fj)[i];+ }+ }+ }++ // Load C into output registers (op handles accumulation)+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < ct_c.get_capacity(); i++) {+ ct_c[i] = C.elems()[i];+ }++ // Do matmul+ gemm_op.run(ct_a, ct_b, ct_c);++ // Copy out results+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < ct_c.get_capacity(); i++) {+ C.elems()[i] = ct_c[i];+ }+}++template <typename T, short kTileRows_, short kTileCols_, class NAXSubTile_>+struct NAXTile {+ using NAXSubTile_t = NAXSubTile_;+ using elem_type = T;+ STEEL_CONST short kSubTileRows = NAXSubTile_t::kRows;+ STEEL_CONST short kSubTileCols = NAXSubTile_t::kCols;+ STEEL_CONST short kElemsPerSubTile = NAXSubTile_t::kElemsPerSubTile;++ STEEL_CONST short kTileRows = kTileRows_;+ STEEL_CONST short kTileCols = kTileCols_;++ STEEL_CONST short kRows = kTileRows * kSubTileRows;+ STEEL_CONST short kCols = kTileCols * kSubTileCols;++ STEEL_CONST short kSubTiles = kTileRows * kTileCols;+ STEEL_CONST short kElemsPerTile = kSubTiles * kElemsPerSubTile;++ STEEL_CONST short kRowsPerThread = kTileRows * NAXSubTile_t::kRowsPerThread;+ STEEL_CONST short kColsPerThread = kTileCols * NAXSubTile_t::kColsPerThread;++ STEEL_CONST short kSubTileThrRows = NAXSubTile_t::kRowsPerThread;+ STEEL_CONST short kSubTileThrCols = NAXSubTile_t::kColsPerThread;++ NAXSubTile_t val_subtiles[kSubTiles];++ METAL_FUNC NAXTile() thread {}++ METAL_FUNC constexpr void clear() {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kSubTiles; ++i) {+ val_subtiles[i].clear();+ }+ }++ METAL_FUNC constexpr thread NAXSubTile_t& subtile_at(+ const short i,+ const short j) {+ return val_subtiles[i * kTileCols + j];+ }++ METAL_FUNC constexpr const thread NAXSubTile_t& subtile_at(+ const short i,+ const short j) const {+ return val_subtiles[i * kTileCols + j];+ }++ template <int i, int j>+ METAL_FUNC constexpr const thread NAXSubTile_t& subtile_at() const {+ return val_subtiles[i * kTileCols + j];+ }++ METAL_FUNC thread elem_type* elems() {+ return reinterpret_cast<thread elem_type*>(val_subtiles[0].elems());+ }++ METAL_FUNC const thread elem_type* elems() const {+ return reinterpret_cast<const thread elem_type*>(val_subtiles[0].elems());+ }++ template <typename Op>+ METAL_FUNC void row_reduce(thread metal::vec<T, kRowsPerThread>& vals) const {+ auto sub_rows = (thread metal::vec<T, kSubTileThrRows>*)(&vals);+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).template row_reduce<Op>(sub_rows[i]);+ }+ }+ }++ template <typename Op>+ METAL_FUNC void row_bin_op(thread metal::vec<T, kRowsPerThread>& vals) {+ auto sub_rows = (thread metal::vec<T, kSubTileThrRows>*)(&vals);+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).template row_bin_op<Op>(sub_rows[i]);+ }+ }+ }++ template <typename U, int str_x, int str_y>+ METAL_FUNC void load(const threadgroup U* src) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).load(+ src,+ Int<str_x>{},+ Int<str_y>{},+ i * kSubTileRows,+ j * kSubTileCols);+ }+ }+ }++ template <typename U, int str_x, int str_y>+ METAL_FUNC void store(threadgroup U* dst) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).store(+ dst,+ Int<str_x>{},+ Int<str_y>{},+ i * kSubTileRows,+ j * kSubTileCols);+ }+ }+ }++ template <typename U>+ METAL_FUNC void load(const device U* src, const int ld) {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).load(+ &src[(i * kSubTileRows * ld + j * kSubTileCols)], ld, Int<1>{});+ }+ }+ }++ template <typename U>+ METAL_FUNC void store(device U* dst, const int ld) const {+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).store(+ &dst[(i * kSubTileRows * ld + j * kSubTileCols)], ld, Int<1>{});+ }+ }+ }++ template <typename U>+ METAL_FUNC void+ load_rows(const device U* src, const int ld, const short n_rows) {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).load_rows(+ &src[(i * kSubTileRows) * ld + (j * kSubTileCols)],+ ld,+ Int<1>{},+ n_rows - i * kSubTileRows);+ }+ }+ }++ template <typename U>+ METAL_FUNC void+ load_safe(const device U* src, const int ld, const short2 src_tile_dims) {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).load_safe(+ src,+ ld,+ Int<1>{},+ src_tile_dims.y,+ src_tile_dims.x,+ i * kSubTileRows,+ j * kSubTileCols);+ }+ }+ }++ template <typename U>+ METAL_FUNC void store_rows(device U* dst, const int ld, const short n_rows)+ const {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).store_rows(+ &dst[(i * kSubTileRows) * ld + (j * kSubTileCols)],+ ld,+ Int<1>{},+ n_rows - i * kSubTileRows);+ }+ }+ }++ template <typename U>+ METAL_FUNC void+ store_safe(device U* dst, const int ld, const short2 dst_tile_dims) const {+ STEEL_PRAGMA_UNROLL+ for (int i = 0; i < kTileRows; ++i) {+ STEEL_PRAGMA_UNROLL+ for (int j = 0; j < kTileCols; ++j) {+ subtile_at(i, j).store_safe(+ dst,+ ld,+ Int<1>{},+ dst_tile_dims.y,+ dst_tile_dims.x,+ i * kSubTileRows,+ j * kSubTileCols);+ }+ }+ }++ template <typename U>+ METAL_FUNC void store_slice(+ device U* dst,+ const int ld,+ const short2 start,+ const short2 stop) const {+ const_for_loop<0, kTileRows, 1>([&](auto idx_row) {+ const_for_loop<0, kTileCols, 1>([&](auto idx_col) {+ subtile_at<idx_row.value, idx_col.value>().store_slice(+ dst,+ ld,+ Int<1>{},+ start.y,+ stop.y,+ start.x,+ stop.x,+ idx_row * Int<kSubTileRows>{},+ idx_col * Int<kSubTileCols>{});+ });+ });+ }+};++template <+ class CTile,+ class ATile,+ class BTile,+ bool transpose_a,+ bool transpose_b>+METAL_FUNC void tile_matmad_nax(+ thread CTile& C,+ thread ATile& A,+ metal::bool_constant<transpose_a>,+ thread BTile& B,+ metal::bool_constant<transpose_b>) {+ // Static checks+ constexpr short TMa = transpose_a ? ATile::kTileCols : ATile::kTileRows;+ constexpr short TMc = CTile::kTileRows;+ static_assert(TMa == TMc, "NAX tile matmul: M dimensions do not match");++ constexpr short FMa = transpose_a ? ATile::kSubTileCols : ATile::kSubTileRows;+ constexpr short FMc = CTile::kSubTileRows;+ static_assert(FMa == FMc, "NAX subtile matmul: M dimensions do not match");++ constexpr short TNb = transpose_b ? BTile::kTileRows : BTile::kTileCols;+ constexpr short TNc = CTile::kTileCols;+ static_assert(TNb == TNc, "NAX tile matmul: N dimensions do not match");++ constexpr short FNb = transpose_b ? BTile::kSubTileRows : BTile::kSubTileCols;+ constexpr short FNc = CTile::kSubTileCols;+ static_assert(FNb == FNc, "NAX subtile matmul: N dimensions do not match");++ constexpr short TKa = transpose_a ? ATile::kTileRows : ATile::kTileCols;+ constexpr short TKb = transpose_b ? BTile::kTileCols : BTile::kTileRows;+ static_assert(TKa == TKb, "NAX tile matmul: K dimensions do not match");++ constexpr short FKa = transpose_a ? ATile::kSubTileRows : ATile::kSubTileCols;+ constexpr short FKb = transpose_b ? BTile::kSubTileCols : BTile::kSubTileRows;+ static_assert(FKa == FKb, "NAX subtile matmul: K dimensions do not match");++ constexpr short TM = TMc;+ constexpr short TN = TNc;+ constexpr short TK = TKa;++ // Do matmul here+ STEEL_PRAGMA_UNROLL+ for (short i = 0; i < TM; ++i) {+ STEEL_PRAGMA_UNROLL+ for (short j = 0; j < TN; ++j) {+ STEEL_PRAGMA_UNROLL+ for (short k = 0; k < TK; ++k) {+ const short ra = transpose_a ? k : i;+ const short ca = transpose_a ? i : k;+ const short rb = transpose_b ? j : k;+ const short cb = transpose_b ? k : j;++ subtile_matmad_nax(+ C.subtile_at(i, j),+ A.subtile_at(ra, ca),+ metal::bool_constant<transpose_a>{},+ B.subtile_at(rb, cb),+ metal::bool_constant<transpose_b>{});+ }+ }+ }+}++} // namespace steeldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/params.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/params.hnew file mode 100644index 000000000..e94df081f--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/params.h@@ -0,0 +1,62 @@+++#pragma once++///////////////////////////////////////////////////////////////////////////////+// GEMM param classes+///////////////////////////////////////////////////////////////////////////////++namespace steel {++struct GEMMParams {+ const int M;+ const int N;+ const int K;++ const int lda;+ const int ldb;+ const int ldd;++ const int tiles_n;+ const int tiles_m;++ const int64_t batch_stride_a;+ const int64_t batch_stride_b;+ const int64_t batch_stride_d;++ const int swizzle_log;+ const int gemm_k_iterations_aligned;++ const int batch_ndim;+};++struct GEMMSpiltKParams {+ const int M;+ const int N;+ const int K;++ const int lda;+ const int ldb;+ const int ldc;++ const int tiles_n;+ const int tiles_m;++ const int split_k_partitions;+ const int split_k_partition_stride;+ const int split_k_partition_size;++ const int gemm_k_iterations_aligned;+};++struct GEMMAddMMParams {+ const int ldc;+ const int fdc;++ const int64_t batch_stride_c;++ const float alpha;+ const float beta;+};++} // namespace steeldiff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/transforms.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/transforms.hnew file mode 100644index 000000000..76a87e808--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/gemm/transforms.h@@ -0,0 +1,70 @@+++#pragma once++#include "../utils.h"++///////////////////////////////////////////////////////////////////////////////+// Transforms and Epilogues+///////////////////////////////////////////////////////////////////////////////++namespace steel {++template <typename OutT, typename InT>+struct TransformNone {+ static METAL_FUNC OutT apply(InT x) {+ return static_cast<OutT>(x);+ }++ static METAL_FUNC OutT apply(InT x, OutT) {+ return static_cast<OutT>(x);+ }+};++template <typename OutT, typename InT>+struct TransformAdd {+ TransformAdd(const float, const float) {}++ static METAL_FUNC OutT apply(InT x) {+ return static_cast<OutT>(x);+ }++ static METAL_FUNC OutT apply(InT x, OutT c) {+ return static_cast<OutT>(x) + c;+ }+};++template <typename OutT, typename InT>+struct TransformAxpby {+ const float alpha;+ const float beta;++ TransformAxpby(const float alpha_, const float beta_)+ : alpha(alpha_), beta(beta_) {}++ static METAL_FUNC OutT apply(InT x) {+ return static_cast<OutT>(x);+ }++ METAL_FUNC OutT apply(InT x, OutT c) const {+ return static_cast<OutT>(+ x * static_cast<InT>(alpha) + (static_cast<OutT>(beta) * c));+ }+};++template <typename T>+struct AccumHelper {+ typedef float accum_type;+};++struct BlockSwizzle {+ static METAL_FUNC int2+ swizzle(uint3 tid [[threadgroup_position_in_grid]], const int swizzle_log) {+ const int tid_x = (tid.x) >> swizzle_log;+ const int tid_y =+ ((tid.y) << swizzle_log) + ((tid.x) & ((1 << swizzle_log) - 1));+ return int2(tid_x, tid_y);+ }+};++} // namespace steel\ No newline at end of filediff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/utils.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/utils.hnew file mode 100644index 000000000..2241b7f6e--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/utils.h@@ -0,0 +1,42 @@+++#pragma once++#include <metal_stdlib>++METAL_FUNC ulong2 elem_to_loc_broadcast(+ uint elem,+ constant const int* shape,+ constant const int64_t* a_strides,+ constant const int64_t* b_strides,+ int ndim) {+ ulong loc_a{0};+ ulong loc_b{0};+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {+ int pos_in_dim = (elem % shape[i]);+ elem /= shape[i];+ loc_a += pos_in_dim * a_strides[i];+ loc_b += pos_in_dim * b_strides[i];+ }+ return ulong2(loc_a, loc_b);+}++METAL_FUNC ulong3 elem_to_loc_broadcast(+ uint elem,+ constant const int* shape,+ constant const int64_t* a_strides,+ constant const int64_t* b_strides,+ constant const int64_t* c_strides,+ int ndim) {+ ulong loc_a{0};+ ulong loc_b{0};+ ulong loc_c{0};+ for (int i = ndim - 1; i >= 0 && elem > 0; --i) {+ int pos_in_dim = (elem % shape[i]);+ elem /= shape[i];+ loc_a += pos_in_dim * a_strides[i];+ loc_b += pos_in_dim * b_strides[i];+ loc_c += pos_in_dim * c_strides[i];+ }+ return ulong3(loc_a, loc_b, loc_c);+}diff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/utils/integral_constant.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/utils/integral_constant.hnew file mode 100644index 000000000..39007d45a--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/utils/integral_constant.h@@ -0,0 +1,132 @@+++#pragma once++#include <metal_stdlib>+#include "type_traits.h"++#pragma METAL internals : enable++namespace steel {++///////////////////////////////////////////////////////////////////////////////+// Integral constant with casting+///////////////////////////////////////////////////////////////////////////////++template <typename T, T v>+struct integral_constant {+ static constexpr constant T value = v;+ using value_type = T;+ using type = integral_constant;++ METAL_FUNC constexpr operator value_type() const noexcept {+ return value;+ }++ // METAL_FUNC constexpr value_type operator()() const noexcept {+ // return value;+ // }+};++template <bool B>+using bool_constant = integral_constant<bool, B>;+using true_type = bool_constant<true>;+using false_type = bool_constant<false>;++template <class T>+struct is_integral : bool_constant<metal::is_integral<T>::value> {};++template <class T, T v>+struct is_integral<integral_constant<T, v>>+ : bool_constant<metal::is_integral<T>::value> {};++template <typename T>+constexpr constant bool is_integral_v = is_integral<T>::value;++template <int val>+using Int = integral_constant<int, val>;++///////////////////////////////////////////////////////////////////////////////+// Binary Operators on Integral constants+///////////////////////////////////////////////////////////////////////////////++#define integral_const_binop(__op__, __operator__) \+ template <typename T, T tv, typename U, U uv> \+ METAL_FUNC constexpr auto __operator__( \+ integral_constant<T, tv>, integral_constant<U, uv>) { \+ constexpr auto res = tv __op__ uv; \+ return integral_constant<decltype(res), res>{}; \+ }++integral_const_binop(+, operator+);+integral_const_binop(-, operator-);+integral_const_binop(*, operator*);+integral_const_binop(/, operator/);++integral_const_binop(==, operator==);+integral_const_binop(!=, operator!=);+integral_const_binop(<, operator<);+integral_const_binop(>, operator>);+integral_const_binop(<=, operator<=);+integral_const_binop(>=, operator>=);++integral_const_binop(&&, operator&&);+integral_const_binop(||, operator||);++template <typename T, typename = metal::enable_if_t<!is_integral_v<T>>>+METAL_FUNC constexpr auto operator||(true_type, T) {+ return true_type{};+}+template <typename T, typename = metal::enable_if_t<!is_integral_v<T>>>+METAL_FUNC constexpr auto operator||(T, true_type) {+ return true_type{};+}++template <typename T, typename = metal::enable_if_t<!is_integral_v<T>>>+METAL_FUNC constexpr auto operator&&(false_type, T) {+ return false_type{};+}++template <typename T, typename = metal::enable_if_t<!is_integral_v<T>>>+METAL_FUNC constexpr auto operator&&(T, false_type) {+ return false_type{};+}++// Dispatch utilities+template <typename F>+void dispatch_bool(bool v, F f) {+ if (v) {+ f(true_type{});+ } else {+ f(false_type{});+ }+}++template <int start, int stop, int step, typename F>+constexpr void const_for_loop(F f) {+ if constexpr (start < stop) {+ constexpr auto idx = Int<start>{};+ f(idx);+ const_for_loop<start + step, stop, step, F>(f);+ }+}++#undef integral_const_binop++///////////////////////////////////////////////////////////////////////////////+// Reduction operators+///////////////////////////////////////////////////////////////////////////////++template <typename T>+METAL_FUNC constexpr T sum(T x) {+ return x;+}++template <typename T, typename... Us>+METAL_FUNC constexpr auto sum(T x, Us... us) {+ return x + sum(us...);+}++} // namespace steel++#pragma METAL internals : disable\ No newline at end of filediff --git a/crates/uzu/src/backends/metal/kernel/matmul/steel/utils/type_traits.h b/crates/uzu/src/backends/metal/kernel/matmul/steel/utils/type_traits.hnew file mode 100644index 000000000..3c8aca4b9--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/matmul/steel/utils/type_traits.h@@ -0,0 +1,55 @@+++#pragma once++#include <metal_stdlib>++#pragma METAL internals : enable++namespace metal {++template <typename T>+struct is_empty : metal::bool_constant<__is_empty(T)> {};++#ifdef __cpp_variable_templates+template <typename T>+constexpr constant bool is_empty_v = is_empty<T>::value;+#endif++template <typename... Ts>+struct make_void {+ typedef void type;+};++template <typename... Ts>+using void_t = typename make_void<Ts...>::type;++template <class T>+struct is_static : metal::bool_constant<is_empty<remove_cv_t<T>>::value> {};++template <typename T>+struct pointer_element {};++template <typename T>+struct pointer_element<thread T*> {+ using type = remove_cv_t<T>;+};+template <typename T>+struct pointer_element<device T*> {+ using type = remove_cv_t<T>;+};+template <typename T>+struct pointer_element<constant T*> {+ using type = remove_cv_t<T>;+};+template <typename T>+struct pointer_element<threadgroup T*> {+ using type = remove_cv_t<T>;+};++template <typename T>+using pointer_element_t = typename pointer_element<remove_cv_t<T>>::type;++} // namespace metal++#pragma METAL internals : disable\ No newline at end of file