diff --git a/CMakeLists.txt b/CMakeLists.txt index 0121bb00..24e472b8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -481,7 +481,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits # against llama.cpp on the SAME ids and a tokenizer on one side of that comparison is a second variable. # plan v0.3 P5: batched prompt processing (tensor-core GEMMs through cuBLAS). - add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) + add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/wmma_gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) @@ -544,6 +544,17 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME hip_prefill_native_batch COMMAND hip_prefill_native_batch) list(APPEND _strata_hip_tests hip_prefill_native_batch) endif() + # Aurora: the prompt GDN recurrence's per-head kernel against the column-split + norm kernels, bitwise + add_executable(hip_gdn_rec_head tests/hip/gdn_rec_head.cpp) + target_link_libraries(hip_gdn_rec_head PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_gdn_rec_head COMMAND hip_gdn_rec_head) + list(APPEND _strata_hip_tests hip_gdn_rec_head) + # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference + add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp) + target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + target_link_libraries(hip_prefill_wmma_gemm_parity PRIVATE strata_prefill strata_hip_runtime) + add_test(NAME hip_prefill_wmma_gemm_parity COMMAND hip_prefill_wmma_gemm_parity) + list(APPEND _strata_hip_tests hip_prefill_wmma_gemm_parity) # S6: the AMD fast router against the portable kernel, bitwise add_executable(hip_router_fast tests/hip/router_fast.cpp) target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) @@ -896,7 +907,8 @@ endif() # worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the # features, and the fallback exists for tests, exactly as P2.S3 specifies. # Plan v0.3 P6: speculation components that need no GPU. -add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) +add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp + src/spec/draft_source.cpp) target_include_directories(strata_spec PUBLIC include) if(STRATA_BUILD_TESTS) add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) @@ -1109,14 +1121,20 @@ if(STRATA_NATIVE_EXPERTS) if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") endif() + # Aurora: moe_fused.cu's and moe_fused_iq.cu's gfx11 WMMA kernels for the prompt experts (opt-in STRATA_PF_FUSED=1) set(_strata_mmq_sources src/prefill/moe_mmq.cu + src/prefill/moe_fused.cu + src/prefill/moe_fused_iq.cu src/prefill/ggml_cuda_host.cu "${_strata_mmq}/quantize.cu") foreach(_t IN LISTS _strata_mmq_types) list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") endforeach() set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) + # moe_fused.cu is Strata's own CUDA-shaped source: it takes the HIP compat headers, ggml's MMQ sources do not + set_source_files_properties(src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu + PROPERTIES INCLUDE_DIRECTORIES "${STRATA_HIP_COMPAT_INCLUDE_DIR}") add_library(strata_mmq STATIC ${_strata_mmq_sources}) target_include_directories(strata_mmq PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" @@ -1127,7 +1145,20 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + # Aurora: the gfx11 fused experts against the FP64 reference and MMQ (tests/cuda's test; exit 77 off gfx11) + add_executable(hip_prefill_fused_moe tests/cuda/prefill_fused_moe_test.cpp) + target_include_directories(hip_prefill_fused_moe PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_fused_moe PRIVATE strata_mmq ggml-base strata_hip_runtime) + add_test(NAME hip_prefill_fused_moe COMMAND hip_prefill_fused_moe) + set_tests_properties(hip_prefill_fused_moe PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + list(APPEND _strata_hip_tests hip_prefill_fused_moe) + add_executable(hip_prefill_fused_iq tests/cuda/prefill_fused_iq_test.cpp) + target_include_directories(hip_prefill_fused_iq PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_fused_iq PRIVATE strata_mmq ggml-base strata_hip_runtime) + add_test(NAME hip_prefill_fused_iq COMMAND hip_prefill_fused_iq) + set_tests_properties(hip_prefill_fused_iq PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + list(APPEND _strata_hip_tests hip_prefill_fused_iq) # Numerical diagnostic: synthetic layouts by default, optional first-expert IQ3_XXS/IQ4_NL check with a pack. add_executable(hip_prefill_mmq_parity tests/hip/prefill_mmq_parity.cpp) diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index d59bba9a..676ce31b 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -8,10 +8,11 @@ endif() # maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the # same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. RDNA2 gfx1030 (RX 6800 / 6900) has the # same LDS limit and wave32 but an older dot4 instruction (v_dot4_i32_i8, hip_compat/intrinsics.hpp); a community -# report ran it (#311), the maintainers have not. +# report ran it (#311), the maintainers have not. gfx1151 (Ryzen AI Max / Strix Halo, Radeon 8060S, RDNA3.5) is the +# same wave32 / 64 KiB LDS / sudot4 family as gfx1100, on a unified-memory APU; experimental. set(_strata_hip_validated gfx1100 gfx1201) set(_strata_hip_community gfx1101 gfx1200) -set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031) +set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031 gfx1151) # CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use # spaces, which foreach(IN LISTS) would otherwise treat as one element. string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") @@ -78,6 +79,11 @@ option(STRATA_GFX1012_PORTABLE_DOT "Use the portable signed-byte dot control on if(STRATA_GFX1012_PORTABLE_DOT) target_compile_definitions(strata_hip_runtime INTERFACE STRATA_GFX1012_PORTABLE_DOT=1) endif() +# #313: the RDNA3 WMMA GEMM's intrinsics only compile for gfx11 targets and the host pass does not define +# __gfx11xx__, so the build supplies the macro for gfx11 configs (the kernels also gate on the device at runtime) +if(CMAKE_HIP_ARCHITECTURES MATCHES "gfx11") + target_compile_definitions(strata_hip_runtime INTERFACE STRATA_WMMA_GFX11=1) +endif() target_link_libraries(strata_hip_runtime INTERFACE hip::host) # The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host # compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 8c031ff3..844f6aea 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -69,6 +69,12 @@ std::vector> rank_learned_profile(int64_t n_layers, bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, const std::vector>& ranked, std::string& err); +/// Free device memory for the expert cache. On a unified memory system - one memory for the CPU and the GPU, such as +/// the DGX Spark (GB10); CUDA reports it as cudaDevAttrIntegrated - cudaMemGetInfo counts only MemFree, not the page cache - which, with the experts read from the GGUF in place, is mostly those +/// files' clean pages and gives way to a device allocation. There the figure is MemAvailable less 6 GiB for the OS +/// and the engine's host side (STRATA_UMA_HEADROOM_GIB). Elsewhere it is cudaMemGetInfo's. +size_t device_free_bytes(); + class ExpertCache { public: ExpertCache() = default; diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index bfb6ee0f..97da1e89 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -48,6 +48,20 @@ public: void set_prompt_len(int64_t n) { prompt_len_ = n; } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. void set_max_drafts(int k) { max_drafts_ = k; } + /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each + /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four. + void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; } + bool hnorm_per_stream() const { return hnorm_stream_; } + /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0) + /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token. + /// (The prompt path's batched K/V pass keeps the Q8_0 originals.) + void set_q4(bool proj, bool head) { q4_ = proj; q4_head_ = head; } + /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of + /// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens) + void set_draft_vocab(const std::string& path) { dvocab_path_ = path; } + /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown) + static bool top2_env(); + int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; } uint64_t vram_bytes() const { return vram_; } /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) const QsaState& kv_state() const { return st_; } @@ -132,6 +146,20 @@ private: int max_t_ = 0; int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) int max_drafts_ = 1 << 30; + bool hnorm_stream_ = false; + bool q4_ = false, q4_head_ = false; + uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors + std::vector> q4_off_; + int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0) + std::string dvocab_path_; + std::string vocab_file() const { return dvocab_path_.empty() ? rt_dir_ + "/draft_vocab.bin" : dvocab_path_; } + /// a projection's weights for the draft layer's own pass: the Q4_0 copy under --mtp-q4, else the Q8_0 original + const void* wq(const char* name, int& type) const; + bool make_q4_dense(const std::vector& blob, std::string& err); + bool make_q4_head(std::string& err); + void record_top2(int j); + std::vector top2_, dvocab_host_; + std::vector lg_host_; int64_t n_vocab_ = 0; uint64_t vram_ = 0; cudaStream_t cs_ = nullptr; diff --git a/include/strata/core/native_dense.hpp b/include/strata/core/native_dense.hpp index 2d3cb94c..5bd2b4c6 100644 --- a/include/strata/core/native_dense.hpp +++ b/include/strata/core/native_dense.hpp @@ -35,10 +35,11 @@ public: /// of `skip` and `load` does not upload the GGUF key over it. A quantized row leaves `skip` unchanged. static bool keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, std::string& err); uint64_t weight_bytes() const { return bytes_; } - size_t tensor_count() const { return weights_.size(); } + size_t tensor_count() const { return weights_.size() - packed_keys_.size(); } private: std::vector weights_; + std::vector packed_keys_; // GGUF-layout pointers registered with STRATA_Q8_PACKED=1 void* scratch_ = nullptr; uint64_t bytes_ = 0; }; diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index e68f7b3a..3fbfe6a1 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -257,7 +257,9 @@ private: std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graph bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) + bool resident_ = false; ///< STRATA_VERIFY_RESIDENT: every expert resident, no host step per layer uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) + unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32) unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) const float* hand_in_ = nullptr; @@ -290,6 +292,8 @@ private: VerifyHits hits_; const NativeHead* head_ = nullptr; int max_t_ = 0; + float* ple_key_ = nullptr; ///< STRATA_PLE_BATCH: the window rows' PLE key / value projections + float* ple_val_ = nullptr; int last_t_ = 0; int64_t last_pos0_ = 0; int32_t last_tokens_[8] = {}; diff --git a/include/strata/core/weights.hpp b/include/strata/core/weights.hpp index 5c6414f8..a9949123 100644 --- a/include/strata/core/weights.hpp +++ b/include/strata/core/weights.hpp @@ -90,6 +90,9 @@ struct WeightRef { const void* native_data = nullptr; void* native_q8_1 = nullptr; int native_type = -1; + /// S23 experiment (STRATA_HC_Q8=1): a hyper-connection projection's Q8_0 bytes as the GGUF stores them, owned by + /// NativeDense, for the verify window's read (every other path keeps the pack's BF16 `data`) + const void* hc_q8 = nullptr; /// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it /// (native GGUF projections, the native head). The metadata above stays valid; `data` is null. bool resident = true; diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index 8ea907a9..f9d7e548 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -20,6 +20,7 @@ #define cudaDevAttrClockRate hipDeviceAttributeClockRate #define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor #define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor +#define cudaDevAttrIntegrated hipDeviceAttributeIntegrated #define cudaDeviceGetAttribute hipDeviceGetAttribute #define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer #define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess diff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hpp index 3129f049..6ed99dfd 100644 --- a/include/strata/hip_compat/intrinsics.hpp +++ b/include/strata/hip_compat/intrinsics.hpp @@ -16,7 +16,8 @@ __device__ __forceinline__ int signed_byte(uint32_t word, int lane) { // CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. __device__ __forceinline__ int dp4a(int a, int b, int c) { -#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1200__) || \ +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \ + defined(__gfx1151__) || defined(__gfx1200__) || \ defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) // RDNA3 and RDNA4 expose the signed/unsigned dot4 form (v_dot4_i32_iu8). Mark // both packed operands signed to preserve CUDA __dp4a semantics; keep the diff --git a/include/strata/kernels/bf16_gemv.hpp b/include/strata/kernels/bf16_gemv.hpp index e3efe0ff..f040b04c 100644 --- a/include/strata/kernels/bf16_gemv.hpp +++ b/include/strata/kernels/bf16_gemv.hpp @@ -52,5 +52,11 @@ void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64 /// the weight read once, every output bit-identical to its own single-row call. void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int64_t n_in, int64_t n_out, int n_tok, void* stream); +/// S26 STRATA_LFUSE: bf16_gemv_fp32_mmvf_multi(x, ldx, w, y, ldy, n_in, n_out, n_tok) plus the 1-row +/// bf16_gemv_fp32_mmvf_multi(x, ldx, w_aux, y_aux, ldy_aux, n_in, 1, n_tok) in ONE launch, every output bitwise the +/// two calls'. Returns false (nothing launched) unless the rows path applies (STRATA_MMVF_ROWS=1, n_out >= 64, 2-8 rows). +bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, + int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux, + int64_t ldy_aux, void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/cvec.hpp b/include/strata/kernels/cvec.hpp index a447eb52..c9347483 100644 --- a/include/strata/kernels/cvec.hpp +++ b/include/strata/kernels/cvec.hpp @@ -52,6 +52,10 @@ bool cvec_replicate(std::string& err); void cvec_set_enabled(bool on); bool cvec_enabled(); +/// The CURRENT device's tables (dir n_layers x n_embd, s n_layers, the request flag), for a caller that applies the +/// vector inside its own kernel (the prompt path's STRATA_CVEC_FUSE). False without a vector on this device. +bool cvec_tables(const float** dir, const float** s, const int** on); + /// Layer `layer`'s vector on T tokens' residual stacks (`R + t * r_ld`, hc streams of n_embd). With `write`, the /// pending FFN write `R += bo * 2 sigmoid(inj / hc)` (the fused read's arithmetic) is applied first, for callers /// whose writes are folded into the next layer's read; without it, R must already hold the layer's output. diff --git a/include/strata/kernels/dequant_bf16.hpp b/include/strata/kernels/dequant_bf16.hpp index 5a8ed088..bcc7e38f 100644 --- a/include/strata/kernels/dequant_bf16.hpp +++ b/include/strata/kernels/dequant_bf16.hpp @@ -21,6 +21,11 @@ void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, void* stream); +/// dequant_f16 with output row stride `ld` >= cols (a multiple of 8): S23's padded weight scratch. False (nothing +/// launched) for the i-quant formats and unsupported shapes. +bool dequant_f16_ld(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, int64_t ld, + uint16_t* out, void* stream); + /// The same into FP32 (tests and small tensors). void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream); diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index b5f95fcb..982b33bd 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -36,6 +36,15 @@ struct FusedGrArgs { float* rs = nullptr; ///< workspace, hc floats float* inject_out = nullptr; ///< hc floats (when w_inject) float* mixed = nullptr; ///< n_embd + /// S23 experiment (STRATA_HC_Q8=1): the GGUF's Q8_0 projections (null: the BF16 ones above); fused_gr_read_multi + /// only + const uint8_t* q8_down = nullptr; ///< Q8_0 [hc_lr][hc*n_embd] + const uint8_t* q8_up = nullptr; ///< Q8_0 [hc*n_embd][hc_lr] + const uint8_t* q8_inject = nullptr;///< Q8_0 [hc][hc*n_embd] + /// S26 STRATA_QFUSE=1 (fused_gr_read_multi, the default and Q8_0 reads): also write `mixed`'s q8_1 image here (the + /// bytes native_quantize_q8_1 would write); q8_cnt = n_embd / 32 zeroed counters owned by the caller (token 0's) + uint8_t* q8_mixed = nullptr; + unsigned* q8_cnt = nullptr; }; bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr); @@ -46,7 +55,8 @@ void fused_gr_read(const FusedGrArgs& a, void* stream); /// weight pointers and eps must be the same for every t); `xn_scratch` is n_tok * hc * n_embd floats. Every /// token's outputs are bitwise `fused_gr_read(a[t])`. constexpr int kFusedGrMaxT = 8; -void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, +/// Returns true when it also wrote the q8_1 images (every token's q8_mixed set and this read supports it). +bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); /// The bench only: the AMD latency-hidden kernels on (1) or off (0); -1 = STRATA_GR_FAST. diff --git a/include/strata/kernels/kv_q8.hpp b/include/strata/kernels/kv_q8.hpp index a535cc32..f8a12f39 100644 --- a/include/strata/kernels/kv_q8.hpp +++ b/include/strata/kernels/kv_q8.hpp @@ -28,6 +28,11 @@ inline uint64_t kv_q8_bytes_per_cell(const QsaShapes& s) { /// Append the cell at step[kStepPos] (graph-capturable: position and page come from device memory). With a host /// copy (KV streaming, `kv_stream.hpp`) the cell is written there too, and to VRAM only if its block is resident. +/// S26 STRATA_LFUSE: n_tok kv_append_q8_step calls (token j: step + j * step_stride, kcur / vcur + j * cur_stride) +/// in one launch, bitwise the same stores (the tokens' cells are distinct). +void kv_append_q8_steps(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, + const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride, + int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host); void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host = nullptr); diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index a1554e5d..ae39fe1c 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -93,6 +93,24 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); +/// STRATA_Q8_PACKED=1 (opt-in): a lossless load-time repack of a Q8_0 matrix into a qs plane (n_out x n_in int8) +/// followed by a d plane (n_out x n_in / 32 fp16), the same bytes (34 per 32 values). A registered matrix's +/// native_q8_0_mmvq calls (keyed by its GGUF-layout device pointer, which stays valid for the prompt path) read the +/// packed copy instead; every output is bitwise equal to the GGUF-layout kernels. +bool native_q8_0_packed_enabled(); +bool native_q8_0_packed_eligible(int n_in, int n_out); +void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out); +void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out); +void native_q8_0_packed_unregister(const void* gguf_weights); + +/// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh / +/// scales / d planes - that native_q6_k_mmvq calls on `weights` read instead (bitwise equal outputs). The copy is +/// owned here: native_q6_k_pack builds it from the device matrix (false: not eligible or failed; nothing changes), +/// native_q6_k_unpack frees it. STRATA_Q6P_SELFTEST=1 checks it bitwise and times it at load. +bool native_q6_k_packed_enabled(); +bool native_q6_k_pack(const void* weights, int n_in, int n_out, const char* what); +void native_q6_k_unpack(const void* weights); + void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); @@ -111,5 +129,9 @@ bool native_mmvq_supported(int ggml_type) noexcept; std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out); void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); +/// S26 STRATA_LFUSE: native_mmvq(w1 -> y1) and native_mmvq(w2 -> y2), same type / shape / input, in ONE launch, +/// bitwise the two calls. Returns false (nothing launched) where that is not the case (Q8_0, 2-8 columns only). +bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2, + int n_in, int n_out, int ncols, void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/native_moe.hpp b/include/strata/kernels/native_moe.hpp index 34760efe..6fc81076 100644 --- a/include/strata/kernels/native_moe.hpp +++ b/include/strata/kernels/native_moe.hpp @@ -18,4 +18,13 @@ void native_moe_combine(const float* parts, const float* weights, const float* s /// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call. void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, int64_t n_embd, int64_t k, int n_tok, void* stream); +/// STRATA_VERIFY_RESIDENT: the same, reading every part as `0.0f + hit[i]` - bitwise what a zeroed part row plus +/// moe_hit_add (parts += hit) gave, without the zero fill and the add launch. +void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, + int64_t n_embd, int64_t k, int n_tok, void* stream); +/// S26 STRATA_LFUSE: the same with `shared` unscaled and shared_gate[t] the shared expert's raw gate logit: the +/// row is scaled by sigmoid(shared_gate[t]) here, bitwise what shared_expert_multi's sigmoid + scale gave. +void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared, + const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok, + void* stream); } diff --git a/include/strata/kernels/native_qsa.hpp b/include/strata/kernels/native_qsa.hpp index c56eb4d2..e789fa3e 100644 --- a/include/strata/kernels/native_qsa.hpp +++ b/include/strata/kernels/native_qsa.hpp @@ -21,6 +21,11 @@ bool native_qsa_enabled(); void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, int n_cols, int n_rows, float epsilon, void* stream); +// The same per row with gamma[n_cols * groups]: row r is normalized on its own and scaled by gamma's slice +// r % groups (the MTP's hidden input, one row per hyper-connection stream: --mtp-hnorm stream). +void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output, + int n_cols, int groups, int n_rows, float epsilon, void* stream); + // attn/output [head_dim,n_head]; q_full [2*head_dim,n_head], each row is // [query channels, gate channels]. Output is attn*sigmoid(second-half gate). // Exact output==attn is supported; all other spans must be disjoint. diff --git a/include/strata/kernels/ple.hpp b/include/strata/kernels/ple.hpp index 76ae7890..98bfc388 100644 --- a/include/strata/kernels/ple.hpp +++ b/include/strata/kernels/ple.hpp @@ -71,6 +71,11 @@ struct PleWeights { /// Plan v0.3 P6: the IQ model files keep `ple_key` in BF16 ([n_embd, hc_dim], `w[o*n_embd+i]`); when set it /// replaces both key paths above. const uint16_t* key_bf16 = nullptr; + /// S25 (STRATA_PLE_BATCH=1): the key (hc_dim) and value (n_embd) projections of `emb`, already computed by the + /// caller for a window's rows at once (the same kernels' multi-row forms); ple_block then copies them instead of + /// running its own GEMVs + const float* pre_key = nullptr; + const float* pre_value = nullptr; }; /// Everything the block produces, in the order `ple_layer_xcheck`'s oracle writes it. Any pointer may be diff --git a/include/strata/kernels/shared_expert.hpp b/include/strata/kernels/shared_expert.hpp index 44b37d82..5a898b5f 100644 --- a/include/strata/kernels/shared_expert.hpp +++ b/include/strata/kernels/shared_expert.hpp @@ -74,9 +74,13 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* /// multi-column MMVQ, so the weights are read once; every token is bitwise `shared_expert` on that token. /// `x` (n_tok, n_embd) f32, `x_bf16` the same rounded (only read when the native BF16 gate is off), `gate`/`up` /// (n_tok, n_ff) scratch, `g` n_tok floats, `out` (n_tok, n_embd). `nw.q8_1` must hold n_tok columns of n_embd. +/// x_q8_1_ready: the q8_1 image of x (n_tok rows), already quantized by the caller with the same quantizer (the +/// same bytes native_quantize_q8_1 writes): its gate/up read it and x is not quantized again, and the SwiGLU and +/// its q8_1 run as one launch (same values). Null: the separate launches. void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream); + int64_t n_ff, void* stream, const void* x_q8_1_ready = nullptr, + int lfuse = 0); // S26 STRATA_LFUSE: bit 0 gate computed + applied by the caller, bit 1 gate/up pair /// The MoE block's final combination, `ref/moe.py::moe` L156: /// diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 50d951a6..11f31b61 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -34,7 +34,9 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet /// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`. void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, - const int32_t* n_keep, void* stream, int t_out_begin = 0); + const int32_t* n_keep, void* stream, int t_out_begin = 0, void* xq_out = nullptr); +/// (xq_out, S26 STRATA_QFUSE: also write the q8_1 image of output rows [t_out_begin, n_tok) there - the bytes +/// native_quantize_q8_1(y + t_out_begin * value_dim, xq_out, value_dim, n_tok - t_out_begin) would write.) /// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be /// outstanding at once (the split verify window keeps two). void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream); diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 60d1c717..ab148380 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -29,15 +29,21 @@ public: /// Below sm_80 (no BF16 tensor cores): Volta converts both to FP16 and runs the FP16 tensor-core GEMM (Turing with /// STRATA_BF16_TC=1), Pascal widens both to fp32 (cublasSgemm); see gemm.cu. void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, - float beta = 0.0f); + float beta = 0.0f, int64_t ldx = 0); + + /// S (STRATA_HCD_EXACT): the HC down projection (N 320, K 10240) by the WMMA kernel that reproduces hipBLASLt's + /// solution 1176 / 1177 bit for bit; false (nothing launched) unless hipBLASLt would take one of those for this + /// shape (so the caller falls back to bf16(), with the same ldx). + bool bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K); /// Y = X . W^T with both in FP16 (bits). void f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, float beta = 0.0f); - /// W given as native GGUF blocks of `ggml_type`, dequantized to FP16 in the scratch, X in FP16. + /// W given as native GGUF blocks of `ggml_type`, dequantized to FP16 in the scratch, X in FP16. `ldx` (> K) is + /// X's padded row stride, taken only by STRATA_PF_PAD's path (0 = K). void native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, - int64_t ldy = 0, float beta = 0.0f); + int64_t ldy = 0, float beta = 0.0f, int64_t ldx = 0); /// Caller-owned buffers only: the scratch and workspace moved (the prompt path laid its buffers out again). void rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes); diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index 3358bea6..18f51be1 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -19,14 +19,25 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t uint16_t* xn16_lo = nullptr); /// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R. void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo = nullptr); + uint16_t* xn16_lo = nullptr, int64_t ldx = 0); // ldx: xn16's token stride (0 = 10240) /// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits). void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); /// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as /// the two calls, without reading R back. +/// S23 (opt-in STRATA_HC_UPMIX=1): the up projection (lo16 x w_up^T, BF16, FP32 accumulate) with gr_mix_r as its +/// epilogue - `gated` is never written. False (nothing launched) off gfx11. +bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm, + float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream); void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr, + int64_t ldx = 0); +/// S23 (STRATA_CVEC_FUSE=1): gr_write, then the control vector (v_l = layer l's direction row, *s_l its scale, +/// *on the request flag, mode 0 project / 1 add; cvec_kernel's arithmetic), then gr_norm_rs with the next half's +/// norm - one pass over R, the same bits as the three kernels. +void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l, + const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs, + uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr, int64_t ldx = 0); /// lo16[t, k] = bf16(silu(lo[t, k] / hc)) void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); /// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). @@ -46,7 +57,14 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i /// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the /// out projection reads); y is FP32 scratch. void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream); + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, + int64_t ld16 = 0); // ld16: y16's row stride (0 = 6144; S23 STRATA_PF_PAD pads it) +/// The kernels behind gdn_recurrence, for the parity test: 0 = the column-split kernels + the norm kernel (or the +/// one-block-per-head kernel under STRATA_GDN_REC_HEADS), 1 = four lanes per column (no barrier per token) + the grid-stride norm, 2 = the +/// one-block-per-head kernel (its fused norm rounds differently). 0 and 1 give the same bits. +void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, + void* stream, int64_t ld16 = 0); // ---- MoE /// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router). @@ -79,7 +97,7 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p /// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256] void split_q(const float* q_full, float* q, int64_t T, void* stream); /// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) -void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream); +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16 = 0); /// K and V of T consecutive cells (positions pos0..pos0+T-1; K normed and rotated) into the paged pools: FP16 /// (`k_pool`/`v_pool`) or INT8 codes + FP16 scale per 64 (`k_q`...), the decode append's arithmetic. diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index c77b8696..c4981e92 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -35,6 +35,14 @@ public: /// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft). void observe(bool lookup, int t, int accepted, int match, double round_ms); + /// --lookup-chain: how many of `k_avail` lookup tokens to append after an MTP window of `t_mtp` tokens whose + /// drafts all hold with probability `p_mtp` (estimated from the draft layer's own probabilities): the k with the + /// best expected tokens per ms, E(t_mtp) + p_mtp (c + c^2 + .. + c^k) at the cost of t_mtp + k, if it beats the MTP + /// window alone by `margin`; c = the acceptance of chained drafts by match length (their own counts). 0 = none. + int chain(int t_mtp, double p_mtp, int k_avail, int match) const; + /// After a chained round: the MTP window's size, the chained tokens, the window's accepted drafts, its time. + void observe_chain(int t_mtp, int k, int accepted, int match, double round_ms); + double chain_rate(int match) const; double lookup_rate(int match) const; // current q for a match length double cost_ms(int t) const; // measured or scaled round time of a window of t tokens @@ -47,6 +55,7 @@ private: std::array cost_{}, cost_n_{}; // round ms by window size std::array mtp_tok_{}, mtp_n_{}; // tokens committed by MTP windows of that size std::array ok_{}, bad_{}; // lookup drafts accepted / windows cut short, decayed + std::array cok_{}, cbad_{}; // chained lookup drafts, the same (reached rounds only) }; } // namespace strata::spec diff --git a/include/strata/spec/draft_source.hpp b/include/strata/spec/draft_source.hpp new file mode 100644 index 00000000..109d3c74 --- /dev/null +++ b/include/strata/spec/draft_source.hpp @@ -0,0 +1,62 @@ +// include/strata/spec/draft_source.hpp - a source of draft tokens beside the MTP layer (--lookup-chain). +// +// A source proposes how the context continues; the verify window checks the proposal, so a source can only change +// the speed, never the output. The engine asks its sources after the MTP has drafted: the context it passes ends +// with those MTP drafts (not yet verified), and whatever a source returns is appended to the same window. +// +// The built-in source is the request's own text (PromptLookupSource: the suffix drafter over prompt + output). +// Other sources (a retrieval store over a codebase or earlier conversations) register with +// extra_draft_sources() before the first request; the engine takes the proposal with the longest match. +#pragma once + +#include "strata/spec/suffix_drafter.hpp" + +#include +#include +#include +#include + +namespace strata::spec { + +class DraftSource { +public: + virtual ~DraftSource() = default; + virtual const char* name() const = 0; + /// A new request starts (its prompt follows through append()). + virtual void reset() {} + /// Committed context, in order: the request's prompt, then every token the verify windows accept. + virtual void append(const int32_t* tokens, size_t n) { (void) tokens; (void) n; } + /// Propose up to `max_k` tokens that follow the context. `tail` holds the context's last `n_tail` tokens (at most + /// 64); its last `n_pending` are drafts not yet verified (never passed to append()). Writes `out`, returns how + /// many (0 = nothing to propose) and sets `*match` to the number of trailing context tokens the proposal is based + /// on (its confidence: the engine requires --lookup-chain-min and prefers the longest). + virtual int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) = 0; +}; + +/// The request's own text: the suffix drafter (prompt lookup) behind the DraftSource interface. +class PromptLookupSource final : public DraftSource { +public: + explicit PromptLookupSource(SuffixDrafter& d) : d_(d) {} + const char* name() const override { return "prompt-lookup"; } + void reset() override { d_.reset(); } + void append(const int32_t* tokens, size_t n) override { d_.append(tokens, n); } + int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) override { + n_pending = n_pending < n_tail ? n_pending : n_tail; + const int k = d_.propose_after(tail + (n_tail - n_pending), n_pending, max_k, out); + *match = k > 0 ? d_.last_match() : 0; + return k; + } + +private: + SuffixDrafter& d_; +}; + +/// Sources besides the request's own text, asked after it (empty unless something registered one at startup). +std::vector>& extra_draft_sources(); + +/// Ask `own` and then every extra source; the proposal with the longest match of at least `min_match` wins +/// (ties keep the earlier source). Returns its length (0 = none); `*match` and `*source` (index: 0 = own) describe it. +int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match, + int32_t* out, int* match, int* source); + +} // namespace strata::spec diff --git a/include/strata/spec/suffix_drafter.hpp b/include/strata/spec/suffix_drafter.hpp index 731bbef1..e84593bf 100644 --- a/include/strata/spec/suffix_drafter.hpp +++ b/include/strata/spec/suffix_drafter.hpp @@ -30,9 +30,15 @@ public: /// Write up to `max_k` proposed next tokens to `out`; returns how many (0 = no match of at least min_match). int propose(int max_k, int32_t* out); + /// --lookup-chain: as propose(), for the history followed by `extra` (the draft head's proposal for the next + /// tokens), so the lookup continues where those drafts end. The history itself is unchanged; the extra tokens are + /// only part of the suffix being matched and may be read back as part of a periodic continuation. + int propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out); + /// Length of the match behind the last proposal (0 if none). int last_match() const { return last_match_; } size_t size() const { return hist_.size(); } + const std::vector& history() const { return hist_; } private: struct Slot { diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index b8df2faf..5eacb0ef 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -15,11 +15,49 @@ #include #include #include +#include #include #include namespace strata::core { +// See the header. NVIDIA's DGX Spark Porting Guide (section 5.5, "Memory reporting on UMA systems") recommends the same: +// not to rely on cudaMemGetInfo alone but to count the memory the OS can reclaim. Swap is not counted here (unlike +// NVIDIA's reference snippet): an expert cache that pushes the system into swap would be far slower than a smaller one. +size_t device_free_bytes() { + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); +#if defined(__linux__) + static const bool unified_memory = [] { + int dev = 0, v = 0; + return cudaGetDevice(&dev) == cudaSuccess && cudaDeviceGetAttribute(&v, cudaDevAttrIntegrated, dev) == cudaSuccess && v; + }(); + if (unified_memory) { + if (FILE* m = std::fopen("/proc/meminfo", "r")) { + char line[256]; + unsigned long long kb = 0; + while (std::fgets(line, sizeof line, m)) + if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) break; + std::fclose(m); + // STRATA_UMA_HEADROOM_GIB: a whole number of GiB, 0..1024; anything else keeps the default 6 (said once) + static const long gib = [] { + const char* h = std::getenv("STRATA_UMA_HEADROOM_GIB"); + if (h == nullptr) return 6L; + char* end = nullptr; + const long v = std::strtol(h, &end, 10); + if (end != h && *end == '\0' && v >= 0 && v <= 1024) return v; + std::fprintf(stderr, "strata: STRATA_UMA_HEADROOM_GIB=%s is not a whole number of GiB (0-1024): using 6\n", h); + return 6L; + }(); + const unsigned long long head = (unsigned long long) gib << 30; + const unsigned long long avail = kb << 10; + if (avail > head && avail - head > free_b) free_b = (size_t) (avail - head); + } + } +#endif + return free_b; +} + bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, std::vector>& ranked, int64_t& slots, std::string& err) { std::FILE* f = std::fopen(path.c_str(), "rb"); @@ -422,6 +460,7 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int6 // and the two numbers are named in the refusal. size_t free_b = 0, total_b = 0; if (cudaMemGetInfo(&free_b, &total_b) == cudaSuccess) { + free_b = device_free_bytes(); // unified memory: what the OS can give back counts (see the header) if ((uint64_t) free_b < want) { char buf[320]; std::snprintf(buf, sizeof buf, diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index e9953e30..130dc275 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -44,11 +44,16 @@ #include #endif +#ifdef STRATA_NATIVE_EXPERTS +#include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load +#endif + namespace strata::core { namespace { constexpr float EPS = 1e-6f; constexpr int GGML_Q8_0 = 8; +constexpr int GGML_Q4_0 = 2; using Clock = std::chrono::steady_clock; double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } @@ -112,6 +117,7 @@ MtpDrafter::~MtpDrafter() { for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e); for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e); if (pf_dev_) cudaFree(pf_dev_); + if (dense4_) cudaFree(dense4_); for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e); for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e); for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e); @@ -128,7 +134,7 @@ MtpDrafter::~MtpDrafter() { if (state_arena_) cudaFree(state_arena_); if (arena_) cudaFree(arena_); if (head_logits_) cudaFree(head_logits_); - if (dhead_) cudaFree(dhead_); + if (dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); } if (dvocab_) cudaFree(dvocab_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_}; for (void* h : hosts) if (h) cudaFreeHost(h); @@ -146,6 +152,74 @@ const void* MtpDrafter::q8(const char* name) const { for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off; return nullptr; } +const void* MtpDrafter::wq(const char* name, int& type) const { + if (dense4_ != nullptr) + for (const auto& e : q4_off_) + if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; } + type = GGML_Q8_0; + return q8(name); +} + +// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer +bool MtpDrafter::make_q4_dense(const std::vector& blob, std::string& err) { +#ifdef STRATA_NATIVE_EXPERTS + uint64_t total = 0; + std::vector> plan; + for (const auto& t : tensors_) { + if (t.kind != "q8_0" || t.cols % 32 != 0) continue; + plan.push_back({&t, total}); + total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull; + } + std::vector host((size_t) total); + std::vector row; + const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0); + for (const auto& [t, off] : plan) { + row.resize((size_t) t->cols); + const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18; + for (int64_t r = 0; r < t->rows; ++r) { + q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols); + ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols, + nullptr); + } + q4_off_.push_back({t->name, off}); + } + if (cudaMalloc((void**) &dense4_, (size_t) total) != cudaSuccess) { err = "mtp: the Q4_0 projections do not fit"; return false; } + cudaMemcpy(dense4_, host.data(), (size_t) total, cudaMemcpyHostToDevice); + vram_ += total; + std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0); + return true; +#else + (void) blob; + err = "mtp: --mtp-q4 needs a build with native experts (ggml)"; + return false; +#endif +} + +// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format) +bool MtpDrafter::make_q4_head(std::string& err) { +#ifdef STRATA_NATIVE_EXPERTS + const int64_t N = g_->n_embd; + const auto* tt = ggml_get_type_traits((ggml_type) head_->type()); + if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; } + const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18; + std::vector src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row); + if (cudaMemcpy(src.data(), dhead_, src.size(), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: reading the draft head"; return false; } + std::vector row((size_t) N); + for (int64_t r = 0; r < n_dvocab_; ++r) { + tt->to_float(src.data() + (size_t) r * in_row, row.data(), N); + ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr); + } + // the Q4_0 rows replace the subset in place (they are smaller) + if (cudaMemcpy(dhead_, dst.data(), dst.size(), cudaMemcpyHostToDevice) != cudaSuccess) { err = "mtp: writing the draft head"; return false; } + dhead_type_ = GGML_Q4_0; + std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n", + (long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0); + return true; +#else + err = "mtp: --mtp-q4 needs a build with native experts (ggml)"; + return false; +#endif +} bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, int64_t window) { @@ -185,6 +259,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session } cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice); vram_ += blob.size(); + if (q4_ && !make_q4_dense(blob, err)) return false; } // ---- the 512 routed experts, one blob each { @@ -310,10 +385,44 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session return true; } +namespace { +// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of +// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance +bool full_head_env() { + static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }(); + return on; +} +} // namespace + +bool MtpDrafter::top2_env() { + static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }(); + return on; +} + +// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits +// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught. +void MtpDrafter::record_top2(int j) { + const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_; + if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv); + if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1); + if (j < 0 || j >= max_t_) return; + if (cudaMemcpy(lg_host_.data(), head_logits_, (size_t) nv * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { + top2_[(size_t) j] = -1; + return; + } + int64_t b1 = -1, b2 = -1; + for (int64_t i = 0; i < nv; ++i) { + const float v = lg_host_[(size_t) i]; + if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; } + else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i; + } + top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2; +} + uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); - if (dhead_ == nullptr) { - if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) { + if (dhead_ == nullptr && !full_head_env()) { + if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) { std::fseek(f, 0, SEEK_END); const long size = std::ftell(f); std::fclose(f); @@ -435,9 +544,9 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float return false; } // the draft head's token subset, when tools/draft_vocab.py wrote one - if (dhead_ == nullptr) { + if (dhead_ == nullptr && !full_head_env()) { std::vector raw; - if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) { + if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) { n_dvocab_ = (int64_t) (raw.size() / 4); const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess || @@ -447,11 +556,18 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float return false; } cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice); + dvocab_host_.resize((size_t) n_dvocab_); + std::memcpy(dvocab_host_.data(), raw.data(), raw.size()); strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr); cudaDeviceSynchronize(); vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size(); std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_, (double) (n_dvocab_ * row_bytes) / 1048576.0); + dhead_type_ = head->type(); + if (q4_head_ && !make_q4_head(err)) return false; + if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1 + strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_, + "MTP draft head"); } } if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; @@ -472,6 +588,14 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri const GrShapes gs{g.n_embd, g.hc, g.hc_lr}; const int32_t* step = step_ + row0 * 4; const int32_t* pos = pos_ + row0 * NH; + // --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist) + int wt_fc_embedding, wt_fc_hidden, wt_k_proj, wt_v_proj, wt_q_proj, wt_o_proj; + const void* wp_fc_embedding = wq("fc_embedding.weight", wt_fc_embedding); + const void* wp_fc_hidden = wq("fc_hidden.weight", wt_fc_hidden); + const void* wp_k_proj = wq("self_attn.k_proj.weight", wt_k_proj); + const void* wp_v_proj = wq("self_attn.v_proj.weight", wt_v_proj); + const void* wp_q_proj = wq("self_attn.q_proj.weight", wt_q_proj); + const void* wp_o_proj = wq("self_attn.o_proj.weight", wt_o_proj); try { // ---- the two input branches const WeightRef* we = wt_->find("token_embd.weight"); @@ -487,12 +611,15 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri } native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs); native_quantize_q8_1(en_, xq_, (int) N, T, cs); - native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs); - native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs); + native_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs); + if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight + native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs); + else + native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs); for (int c0 = 0; c0 < T * HC; c0 += 8) { const int nc = (int) std::min(8, T * HC - c0); native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs); - native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs); + native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs); } add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs); // ---- the attention hyper-connection @@ -516,8 +643,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs); }; native_quantize_q8_1(mixed_, xq_, (int) N, T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); + native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs); + native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); for (int t = 0; t < T; ++t) { norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 @@ -536,7 +663,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri vcur_ + t * NKV * HD, s, cs, &st_.host); } if (!full) return true; - native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs); + native_mmvq(wt_q_proj, wp_q_proj, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs); for (int t = 0; t < T; ++t) { float* qc = qcur_ + t * NH * HD; if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, (size_t) HD * 4, @@ -554,7 +681,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri for (int t = 0; t < T; ++t) native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs); native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs); - native_mmvq(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs); + native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs); // ---- the MLP hyper-connection (the attention write folded in) { FusedGrArgs fa[kFusedGrMaxT]; @@ -582,9 +709,9 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_, hit_xs_, hit_scratch_, parts_, cs); NativeSharedWeights nsw; - nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight"); - nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight"); - nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight"); + nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type); + nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type); + nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type); nsw.q8_1 = xq_; const SForm none{}; const bool need_bf16_x = !shared_expert_native_bf16_enabled(); @@ -628,7 +755,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri native_quantize_q8_1(sample_, xq_, (int) N, T, cs); const bool sub = dhead_ != nullptr; const int64_t nv = sub ? n_dvocab_ : n_vocab_; - native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs); + native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, + (int) nv, T, cs); if (coupled_rec_) { // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer) diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index e0609fdc..b5c33a8b 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -7,11 +7,15 @@ #include #include #include +#include #include #include #include #include #include +#include +#include +#include namespace strata::core { namespace { @@ -21,6 +25,55 @@ bool in_range(const std::string& name) { const int l = std::atoi(name.c_str() + 4); return l >= g_layer_lb && l < g_layer_le; } +// S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read +bool hc_q8_requested() { + static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8"); return v != nullptr && v[0] == '1'; }(); + return on; +} +bool hc_q8_name(const std::string& name) { + if (name == "output_hc_down.weight" || name == "output_hc_up.weight") return true; // S25: the final mixer too + if (name.rfind("blk.", 0) != 0) return false; + static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight", + ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"}; + for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true; + return false; +} +// S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read +// covers every hc projection +uint16_t half_bits(float f) { + uint32_t x; + std::memcpy(&x, &f, 4); + const uint32_t sign = (x >> 16) & 0x8000u; + int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15; + uint32_t m = x & 0x7fffffu; + if (e <= 0) { // subnormal or zero + if (e < -10) return (uint16_t) sign; + m |= 0x800000u; + const uint32_t shift = (uint32_t) (14 - e); + uint32_t h = m >> shift; + const uint32_t rem = m & ((1u << shift) - 1), half = 1u << (shift - 1); + if (rem > half || (rem == half && (h & 1u))) ++h; + return (uint16_t) (sign | h); + } + if (e >= 31) return (uint16_t) (sign | 0x7c00u); + uint32_t h = ((uint32_t) e << 10) | (m >> 13); + const uint32_t rem = m & 0x1fffu; + if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; + return (uint16_t) (sign | h); +} +std::vector q8_0_of(const float* x, uint64_t n) { + std::vector out((size_t) (n / 32 * 34)); + for (uint64_t b = 0; b < n / 32; ++b) { + float amax = 0.0f; + for (int j = 0; j < 32; ++j) amax = (std::max)(amax, std::fabs(x[b * 32 + j])); + const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f; + uint8_t* o = out.data() + b * 34; + const uint16_t hb = half_bits(d); + std::memcpy(o, &hb, 2); + for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id); + } + return out; +} bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { const auto& name = tensor.name; if (name.rfind("blk.", 0) != 0) return false; @@ -41,6 +94,7 @@ struct Pending { int type; uint64_t bytes; DevicePtr data; + DevicePtr packed; // STRATA_Q8_PACKED=1 copy, or null }; } @@ -73,6 +127,7 @@ bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set } NativeDense::~NativeDense() { + for (const void* p : packed_keys_) strata::kernels::native_q8_0_packed_unregister(p); if (scratch_) cudaFree(scratch_); for (void* p : weights_) cudaFree(p); } @@ -90,7 +145,7 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl std::vector pending; std::set seen; int max_in = 0; - uint64_t total = 0; + uint64_t total = 0, hc_q8_bytes = 0; uint64_t split_count = 0, split_tensors = 0; std::set split_numbers; bool have_architecture = false; @@ -183,8 +238,53 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl } max_in = (std::max)(max_in, (int) ref.ne0); total += bytes; - pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data)}); + // STRATA_Q8_PACKED=1: a second, packed copy of an eligible Q8_0 matrix for the decode MMVQ (the GGUF + // copy stays: the prompt path's GEMMs read it). + DevicePtr packed; + if (tensor.type == 8 && tensor.name != "blk.1.ple_key.weight" && // the PLE has its own kernel + strata::kernels::native_q8_0_packed_enabled() && + strata::kernels::native_q8_0_packed_eligible((int) ref.ne0, (int) ref.ne1)) { + std::vector host(bytes); + strata::kernels::native_q8_0_pack_host(gguf.tensor_data(tensor), host.data(), (int) ref.ne0, + (int) ref.ne1); + void* packed_allocation = nullptr; + auto packed_status = cudaMalloc(&packed_allocation, bytes); + packed.reset(packed_allocation); + if (packed_status == cudaSuccess) + packed_status = cudaMemcpy(packed.get(), host.data(), bytes, cudaMemcpyHostToDevice); + if (packed_status != cudaSuccess) { + err = "native dense packed upload " + tensor.name + ": " + cudaGetErrorString(packed_status); + return false; + } + } + pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data), std::move(packed)}); } + if (hc_q8_requested()) + for (const auto& tensor : gguf.tensors()) { + // S25: the F32 inject rows hold BF16-exact values: the read takes the pack's BF16 rows unless + // STRATA_HC_Q8_INJECT=1 asks for a Q8_0 copy + static const bool q8_inject = [] { const char* v = std::getenv("STRATA_HC_Q8_INJECT"); return v && v[0] == '1'; }(); + const bool f32_inject = q8_inject && tensor.type == 0 && tensor.name.ends_with("_inject.weight"); + if ((tensor.type != 8 && !f32_inject) || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue; + auto found = table.table_.find(tensor.name); + if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue; + auto& ref = found->second; + if (tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1 || ref.ne0 % 32 != 0) { + err = "native dense (STRATA_HC_Q8): incompatible matrix " + tensor.name; return false; + } + const uint64_t bytes = (uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1; + void* p = nullptr; + std::vector q8; + if (f32_inject) q8 = q8_0_of((const float*) gguf.tensor_data(tensor), (uint64_t) ref.ne0 * (uint64_t) ref.ne1); + if (cudaMalloc(&p, bytes) != cudaSuccess || + cudaMemcpy(p, f32_inject ? (const void*) q8.data() : gguf.tensor_data(tensor), bytes, + cudaMemcpyHostToDevice) != cudaSuccess) { + err = "native dense (STRATA_HC_Q8) upload " + tensor.name; return false; + } + ref.hc_q8 = p; + weights_.push_back(p); + hc_q8_bytes += bytes; + } } if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; } void* allocation = nullptr; @@ -193,14 +293,30 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl if (status != cudaSuccess) { err = std::string("native dense scratch: ") + cudaGetErrorString(status); return false; } // All checks and allocations finish before publishing any reference. weights_.reserve(pending.size()); + uint64_t packed_bytes = 0; + size_t packed_count = 0; for (auto& item : pending) { item.ref->native_data = item.data.get(); item.ref->native_type = item.type; item.ref->native_q8_1 = scratch.get(); + if (item.packed) { + strata::kernels::native_q8_0_packed_register(item.data.get(), item.packed.get(), (int) item.ref->ne0, + (int) item.ref->ne1); + packed_keys_.push_back(item.data.get()); + packed_bytes += item.bytes; + ++packed_count; + weights_.push_back(item.packed.release()); + } weights_.push_back(item.data.release()); } + if (packed_count) + std::fprintf(stderr, "native dense: STRATA_Q8_PACKED=1 packed %zu Q8_0 matrices for decode (+%.1f MiB)\n", + packed_count, packed_bytes / 1048576.0); scratch_ = scratch.release(); - bytes_ = total; + bytes_ = total + hc_q8_bytes; + if (hc_q8_requested()) + std::fprintf(stderr, "strata: STRATA_HC_Q8=1: %.2f GiB of Q8_0 hyper-connection projections for the verify read\n", + (double) hc_q8_bytes / 1073741824.0); return true; } catch (const std::exception& error) { err = std::string("native dense: ") + error.what(); diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index acb4f81f..7c976b2d 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -12,6 +12,7 @@ namespace strata::core { NativeHead::~NativeHead() { + if (weights_) strata::kernels::native_q6_k_unpack(weights_); if (scratch_) cudaFree(scratch_); if (weights_) cudaFree(weights_); } @@ -61,6 +62,8 @@ bool NativeHead::load(const std::vector& shards, int64_t n_in, int6 n_in_ = (int) n_in; n_out_ = (int) n_out; type_ = (int) tensor->type; + if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1 + strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head"); return true; } catch (const std::exception& error) { err = std::string("native head: ") + error.what(); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index dd5362ba..d7f47e91 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -58,6 +58,12 @@ constexpr float EPS = 1e-6f; using Clock = std::chrono::steady_clock; double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr; +const bool g_lfuse = [] { const char* v = std::getenv("STRATA_LFUSE"); return v != nullptr && v[0] == '1'; }(); +const bool g_lfuse_gate = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); +const bool g_lfuse_pair = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); +const bool g_qdedup = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); +// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes +const bool g_qfuse = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); #define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) struct Bump { @@ -285,6 +291,7 @@ Verifier::~Verifier() { if (kv.second) cudaGraphExecDestroy(kv.second); if (arena_b_) cudaFree(arena_b_); if (h_commitb_) cudaFreeHost(h_commitb_); + if (qcnt_) cudaFree(qcnt_); if (cs_) cudaStreamDestroy(cs_); if (sh_cs_) cudaStreamDestroy(sh_cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } @@ -436,6 +443,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& sh_up_ = b.take(T * (uint64_t) g.n_ff); sh_g_ = b.take(T + 4); head_logits_ = b.take(T * (uint64_t) n_vocab_); hist_snap_ = b.take(T * HS); + ple_key_ = b.take(T * (uint64_t) strata::kernels::NG_HC_DIM); ple_val_ = b.take(T * N); }; Bump count; carve(count); @@ -513,6 +521,34 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0); } + // STRATA_VERIFY_RESIDENT=1 (opt-in): when EVERY routed expert of every layer is resident in the VRAM/UMA tier + // (checked here, once; a full cache never evicts), the window graph is recorded without the host round trip: + // no doorbell, no flag waits, no plan copy from mapped memory, no PCIe/CPU share (fetch, rebase, its grouped + // launch, the mapped-row copy); the device plans each group (the host's exact loop, E-6) and the combine reads + // the hit rows as `0.0f + hit` (what the zeroed CPU rows + moe_hit_add gave). Same tokens, same arithmetic. + { + const char* v = std::getenv("STRATA_VERIFY_RESIDENT"); + if (v != nullptr && std::atoi(v) != 0 && lb_ == 0 && le_ == g.n_layers && next_ == nullptr && + remote_opt_ == nullptr && hits.d_res != nullptr) { + std::vector res((size_t) (g.n_layers * g.n_expert)); + bool all = cudaMemcpy(res.data(), hits.d_res, res.size() * sizeof(int32_t), cudaMemcpyDeviceToHost) == + cudaSuccess; + for (size_t i = 0; all && i < res.size(); ++i) all = res[i] >= 0; + if (all) { device_plan_ = true; all_resident_ = false; } // (this window's own resident path) + resident_ = all; + std::fprintf(stderr, "strata verify: STRATA_VERIFY_RESIDENT=1: %s\n", + all ? "every expert resident, the window runs without the host round trip" + : "not every expert is resident - the host-planned window stays"); + } + } + if (g_qfuse) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero) + if (cudaMalloc((void**) &qcnt_, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess || + cudaMemset(qcnt_, 0, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess) { + cudaGetLastError(); + if (qcnt_) cudaFree(qcnt_); + qcnt_ = nullptr; + } + } if (all_resident_ || device_plan_) { bool ok2 = true; if (device_plan_) @@ -522,7 +558,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long), cudaMemcpyHostToDevice) == cudaSuccess; } - if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; } + if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; resident_ = false; } } std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t, (double) count.used / 1048576.0, @@ -565,6 +601,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs); // #649 }; const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T}; + // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken) + auto lfuse_on = [&](int n) { + return g_lfuse && resident_ && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 && + shared_expert_native_bf16_enabled(); + }; + bool sg_gated_[2] = {false, false}; // per group: the combine applies the shared gate if (!batch_rec_) groups_[T] = G; const int64_t nQall = g.n_qsa_layers(); // a batch window: row t is slot t, whose state lives in its own session @@ -646,6 +688,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss.ple.w.key_bf16 != nullptr && ss.ple.w.value_bf16 != nullptr && ple_native_bf16_enabled() && ple_native_postops_enabled(); + // S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so + // the group's rows run through the multi-row forms of the same kernels (the weights read once); every + // row's arithmetic is the single-row call's. The history-dependent rest stays row by row. + static const bool ple_batch = [] { const char* e = std::getenv("STRATA_PLE_BATCH"); return e && e[0] == '1'; }(); + PleWeights pw = ss.ple.w; + const bool nkey = pw.key_native_data != nullptr && pw.key_bf16 == nullptr; + const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16_enabled(); if (ple_batch_kv) { try { bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.key_bf16, @@ -656,8 +705,24 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { err = std::string("verify PLE multi: ") + e.what(); return false; } + } else if (batched) { + try { + if (pw.key_bf16 != nullptr) + bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.key_bf16, ple_key_ + (size_t) tb * NG_HC_DIM, + NG_HC_DIM, N, NG_HC_DIM, n, cs); + else { + native_quantize_q8_1(ple_ + tb * N, xq_, (int) N, n, cs); + native_mmvq(pw.key_native_type, pw.key_native_data, xq_, ple_key_ + (size_t) tb * NG_HC_DIM, + (int) N, NG_HC_DIM, n, cs); + } + bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.value_bf16, ple_val_ + tb * N, N, N, N, n, cs); + } catch (const std::exception& e) { + err = std::string("verify PLE batch: ") + e.what(); + return false; + } } for (int t = tb; t < te; ++t) { + if (batched) { pw.pre_key = ple_key_ + (size_t) t * NG_HC_DIM; pw.pre_value = ple_val_ + t * N; } gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); PleOut po; po.normalized = normalized; @@ -668,7 +733,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { ple_block_projected(xn_ + (size_t) t * HC * N, z_ + (size_t) t * N, Rt(t), hist, ss.ple.w, po, ss.ple.scratch, cs); } else { - ple_block(ple_ + t * N, Rt(t), hist, ss.ple.w, po, ss.ple.scratch, cs); + ple_block(ple_ + t * N, Rt(t), hist, pw, po, ss.ple.scratch, cs); } ple_history_advance(hist, normalized, cs); } catch (const std::exception& e) { @@ -687,13 +752,20 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC; a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data; a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data; + a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8; + a.q8_inject = (const uint8_t*) wi[half]->hc_q8; a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N; + if (qcnt_ != nullptr) { // S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself + a.q8_cnt = qcnt_; + if (half == 0) a.q8_mixed = xq_ + (size_t) (t - tb) * (N / 32) * 36; + else if (strata::kernels::cpu::expert_layout().native) a.q8_mixed = nat_xq_ + (size_t) t * (N / 32) * 36; + } } - fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr, + return fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr, (int) (l * kProfPer + (half == 0 ? 27 : 30))); }; - gr_read_group(0, pending, inj2_, inj_); + const bool q8_attn = gr_read_group(0, pending, inj2_, inj_); // true: xq_ holds mixed's q8_1 (STRATA_QFUSE) stamp(l, 1, grp); float* xm = mixed_ + tb * N; try { @@ -715,7 +787,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { float* hb = h_L_ + (size_t) gi * MT * C; float* gate = gate_L_ + (size_t) gi * MT * HV; float* beta = beta_L_ + (size_t) gi * MT * HV; - native_quantize_q8_1(xm, xq_, (int) N, n, cs); + if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs); native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs); stamp(l, 2, grp); if (batch_rec_) { // each row from its own slot's conv history, one row each @@ -746,9 +818,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } else gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK, - (int) HV, te, nullptr, cs, tb); + (int) HV, te, nullptr, cs, tb, g_qfuse ? (void*) xq_ : nullptr); stamp(l, 6, grp); - native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); + if (!g_qfuse) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); // STRATA_QFUSE: done above native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs); } else { // ======================= QSA ======================= @@ -773,7 +845,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token) const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4; - native_quantize_q8_1(xm, xq_, (int) N, n, cs); + if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs); if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs); else for (int t = tb; t < te; ++t) bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs); @@ -795,6 +867,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { TS, cs); } else if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); + const bool kv_multi = g_lfuse && !st.kv_hybrid && !st.kv_q4 && st.kv_int8 && n > 1; // S26 STRATA_LFUSE + if (kv_multi) + kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_ + tb * kStepCount, + (int) kStepCount, kcur_ + tb * NKV * HD, vcur_ + tb * NKV * HD, (int) (NKV * HD), n, + s, cs, &st.host); + else for (int t = tb; t < te; ++t) { const QsaState& st = slot_ss(t).qsa_states[qi]; // the row's own K/V (ss's outside a batch) const int32_t* step_t = step_ + t * kStepCount; @@ -899,7 +977,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } stamp(l, 16, grp); - gr_read_group(1, true, inj_, inj2_); + const bool q8_ffn = gr_read_group(1, true, inj_, inj2_); // true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE) static const bool sh_stream_env = [] { const char* e = std::getenv("STRATA_SH_STREAM"); return !e || e[0] != '0'; @@ -913,8 +991,17 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // the window's rows routed in 2 launches (one router GEMV reading the weight once, one // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) const WeightRef* w_router = v.get("ffn_gate_inp.weight"); + // S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale + // move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only) + const WeightRef* w_sgi = lfuse_on(n) && g_lfuse_gate ? v.get("ffn_gate_inp_shexp.weight") : nullptr; + bool sg_ready = false; if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) { try { + if (w_sgi != nullptr) + sg_ready = bf16_gemv_fp32_mmvf_multi_aux(mixed_ + tb * N, N, (const uint16_t*) w_router->data, + logits_ + tb * NE, NE, N, NE, n, + (const uint16_t*) w_sgi->data, sh_g_ + tb, 1, cs); + if (!sg_ready) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N, NE, n, cs); native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs); @@ -944,6 +1031,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { hits_.cache_base, slot_off_d_, (long long) hits_.blob, plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, (uint32_t) ((l - lb_) * G + grp + 1), cs); + if (!resident_) { // STRATA_VERIFY_RESIDENT: no host step, so no doorbell #if defined(STRATA_USE_HIP) if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, @@ -958,6 +1046,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs); } + } } stamp(l, 17, grp); { @@ -972,22 +1061,31 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data; nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data; nsw.q8_1 = sh_fork ? sh_xq_ : xq_; + // STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the + // experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and + // native_quantize_q8_1 write the same bytes) + const bool qdedup = g_qdedup && !sh_fork && strata::kernels::cpu::expert_layout().native; + if (qdedup && !q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); if (!shared_expert_native_bf16_enabled()) { if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, sh_stream); // contiguous rows else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, sh_stream); } try { shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff, - sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream); + sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream, + qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr, + (sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair ? 2 : 0)); + sg_gated_[grp] = sg_ready; } catch (const std::exception& e) { err = std::string("verify shared expert: ") + e.what(); return false; } if (sh_fork) cudaEventRecord(ev_join_, sh_cs_); } - if (strata::kernels::cpu::expert_layout().native) - quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); - else + if (strata::kernels::cpu::expert_layout().native) { + if (!(g_qdedup && strata::kernels::cpu::expert_layout().native)) + if (!q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + } else quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); stamp(l, 18, grp); return true; @@ -1005,6 +1103,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1); const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K; int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16); + bool combined = false; // STRATA_VERIFY_RESIDENT: the combine below already wrote bo_ const int32_t* p_counts = pl; const int32_t* p_start = pl + 4; const int32_t* p_dst = p_start + capx + 1; @@ -1030,7 +1129,31 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs); } }; - if (all_resident_) { + if (resident_) { + // STRATA_VERIFY_RESIDENT: every expert is resident and resident_plan (pre) wrote this group's plan: no host step + stamp(l, 19, grp); + grouped(p_ptr, p_start, p_counts, 0, hit_out); + stamp(l, 20, grp); + if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) + cudaStreamWaitEvent(cs, ev_join_, 0); // the shared expert's rows are read below + if (native_moe_combine_enabled()) { + // every row is a hit: combine straight from hit_out as 0.0f + hit (= the zeroed row + moe_hit_add) + try { + if (sg_gated_[grp]) + native_moe_combine_multi_hits_gated(hit_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, + N, K, n, cs); + else + native_moe_combine_multi_hits(hit_out, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); + } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } + combined = true; + } else { + if (cudaMemsetAsync(parts_out, 0, sizeof(float) * (size_t) n * K * N, cs) != cudaSuccess) { + err = "verify: zeroing the parts failed"; + return false; + } + moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs); + } + } else if (all_resident_) { stamp(l, 19, grp); grouped(p_ptr, p_start, p_counts, 0, parts_out); stamp(l, 20, grp); @@ -1078,6 +1201,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) { cudaStreamWaitEvent(cs, ev_join_, 0); } + if (!combined) { if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows try { native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); @@ -1088,6 +1212,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { mb.weights = w_ + t * K; mb.shared = shared_ + t * N; if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false; } + } // !combined if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n, device_plan_ ? skip_ + grp : nullptr, ring, cs); stamp(l, 24, grp); @@ -1123,7 +1248,23 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"), *hu = wt.find("output_hc_up.weight"); if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; } - if (fuse_head_gr) { + // S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read + // (no pending write, no inject) + const bool mix_q8 = hd->hc_q8 != nullptr && hu->hc_q8 != nullptr && head_ != nullptr && head_->loaded(); + if (mix_q8) { + FusedGrArgs fa[kFusedGrMaxT]; + for (int t = 0; t < T; ++t) { + FusedGrArgs& a = fa[t]; + a.R = Rt(t); a.R_out = Rt(t); a.apply = false; + a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data; + a.w_up = (const uint16_t*) hu->data; a.w_inject = nullptr; + a.q8_down = (const uint8_t*) hd->hc_q8; a.q8_up = (const uint8_t*) hu->hc_q8; + a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; + a.mixed = head_mixed_ + t * N; + } + fused_gr_read_multi(fa, T, xn_, cs); + } + else if (fuse_head_gr) { FusedGrArgs fa[kFusedGrMaxT]; for (int t = 0; t < T; ++t) { FusedGrArgs& a = fa[t]; @@ -1293,7 +1434,8 @@ bool Verifier::capture_commit(std::string& err) { gdn_conv_commit(conv, qkv, (int) C, commit_, cs_); gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV, beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_, - (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, (int) MT); + (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_, + (int) MT); // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read ++gdn_index; } else { const QsaState& st = ss.qsa_states[qsa_index]; @@ -1427,7 +1569,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, volatile uint32_t* const flag = h_flag_; const int G = groups_[T] > 0 ? groups_[T] : 1; const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; - const int64_t steps = (le_ - lb_) * G; + const int64_t steps = resident_ ? 0 : (le_ - lb_) * G; // STRATA_VERIFY_RESIDENT: the GPU never rings const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) if (all_resident_ && !test_stall) { if (do_ple) { diff --git a/src/kernels/cuda/cvec.cu b/src/kernels/cuda/cvec.cu index 66829324..3f5fe764 100644 --- a/src/kernels/cuda/cvec.cu +++ b/src/kernels/cuda/cvec.cu @@ -151,6 +151,14 @@ void cvec_set_enabled(bool on) { bool cvec_enabled() { return g_cvec.loaded() && g_on_host; } +bool cvec_tables(const float** dir, const float** s, const int** on) { + if (!g_cvec.loaded()) return false; + const DevTables& t = g_dev[cur_device()]; + if (t.dir == nullptr) return false; + *dir = t.dir; *s = t.s; *on = t.on; + return true; +} + void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, int64_t inj_ld, bool write, void* stream) { if (!g_cvec.loaded() || T < 1) return; diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index 32601d60..e159a96c 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -167,11 +167,11 @@ __device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row template __global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, int64_t rows, - int64_t groups_per_row, T* __restrict__ out) { + int64_t groups_per_row, int64_t ld, T* __restrict__ out) { const int64_t g = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (g >= rows * groups_per_row) return; const int64_t r = g / groups_per_row, gi = g % groups_per_row; - group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * groups_per_row * 32 + gi * 32); + group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * ld + gi * 32); } bool geometry(int type, int& block_elems, int& block_bytes) { @@ -192,7 +192,8 @@ bool geometry(int type, int& block_elems, int& block_bytes) { } template -void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream) { +void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream, + int64_t ld = 0) { int be = 0, bb = 0; if (!geometry(type, be, bb) || cols % be != 0 || rows <= 0) { std::fprintf(stderr, "dequant: unsupported type %d or shape %lld x %lld\n", type, (long long) rows, @@ -200,10 +201,11 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co std::exit(1); } const int64_t row_bytes = cols / be * bb, gpr = cols / 32, total = rows * gpr; + if (ld <= 0) ld = cols; const unsigned grid = (unsigned) ((total + 255) / 256); const uint8_t* p = (const uint8_t*) blocks; cudaStream_t st = (cudaStream_t) stream; -#define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, out); break +#define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, ld, out); break switch (type) { case 2: STRATA_DQ(2); case 6: STRATA_DQ(6); @@ -249,6 +251,15 @@ void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, launch(ggml_type, blocks, row0, rows, cols, reinterpret_cast(out), stream); } +bool dequant_f16_ld(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, int64_t ld, + uint16_t* out, void* stream) { + int be = 0, bb = 0; + if (iq_only(ggml_type) || !geometry(ggml_type, be, bb) || cols % be != 0 || rows <= 0 || ld < cols || ld % 8 != 0) + return false; + launch(ggml_type, blocks, row0, rows, cols, reinterpret_cast(out), stream, ld); + return true; +} + void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream) { if (iq_only(ggml_type)) { iq_dequant_f32(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols, diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 71012ffc..2d70514e 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -3,7 +3,9 @@ #include "strata/kernels/fused_gr.hpp" #include "strata/kernels/bf16_bits.hpp" #include "strata/kernels/verify_kernels.hpp" +#include "s26_tsum.cuh" +#include #include #include @@ -144,6 +146,41 @@ struct GrMulti { int T; }; + +// S26 STRATA_QFUSE=1: the q8_1 image of `mixed`, written by the up kernels below. A q8_1 block is 32 columns and an +// up block owns UPM_COLS = 16, so the second of the two blocks that own a 32-column group (a per-group counter, +// incremented after the block's writes are fenced, reset by that block for the next launch) reads the 32 values back +// and quantizes them with native_quantize_q8_1_kernel's quantizer: one warp per token, the same XOR-tree max and sum, +// d = amax / 127, roundf(x / d), ds = (d, sum) - the bytes the separate launch writes. +struct GrQ81 { half2 ds; int8_t qs[32]; }; +static_assert(2 * 16 == 32, "two up blocks per q8_1 group"); +__device__ __forceinline__ void gr_q8_tail(const GrMulti& m, int d0) { + __shared__ int last; + __threadfence(); + __syncthreads(); + if (threadIdx.x == 0) { + unsigned* c = m.a[0].q8_cnt + d0 / 32; + last = atomicAdd(c, 1u) == 1u; + if (last) atomicExch(c, 0u); + } + __syncthreads(); + if (!last) return; + __threadfence(); + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (warp >= m.T) return; + const int c0 = (d0 / 32) * 32; + const float xi = *reinterpret_cast(m.a[warp].mixed + c0 + lane); + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + GrQ81* y = reinterpret_cast(m.a[warp].q8_mixed) + c0 / 32; + y->qs[lane] = q; + if (lane == 0) y->ds = make_half2(d, sum); +} // Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global. __global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { __shared__ float part[WARPS][HC]; @@ -305,6 +342,7 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { for (int c = 0; c < HC; ++c) s += g[k][c][col]; m.a[k].mixed[d0 + col] = s / (float) HC; } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE } @@ -1040,6 +1078,468 @@ __global__ void gr_down_finish_kernel(GrMulti m) { #endif +// ================================ S23 experiment (STRATA_HC_Q8=1): the read with the GGUF's Q8_0 projections ====== +// The pack holds the hyper-connection projections as BF16 (iq_pack.py --compat-bf16 rounds the GGUF's Q8_0 values to +// BF16: 1.20 GiB per verify step); this read takes the Q8_0 bytes as stored (0.65 GiB - and the GGUF's own values, +// not a rounding of them). The layout is the stream split of the v3 read above, at 4 chunks per stream: `down` runs +// on (10 groups of 32 rows + the inject rows) x 16 chunks of 640 columns = 176 blocks, each staging its chunk of +// R' * w_norm (unscaled) for the T tokens and writing the chunk's partial dots and sums of squares; `up` sums them +// per stream in a fixed order, applies rs, SwiGLU-free silu, and runs the default epilogue. Another summation order +// and other weights than the default read: an output-changing step (measured, quality-checked). +constexpr int Q8B = 34; // Q8_0 block: fp16 d + 32 int8 +constexpr int Q8_RPW = 4; // down rows per warp +constexpr int Q8_RG = LR / (WARPS * Q8_RPW); // 10 row groups (+1: the inject rows) +constexpr int Q8_KC = 640, Q8_NKC = D / Q8_KC; // 16 chunks, 4 per stream +constexpr int Q8_CPS = N / Q8_KC; // chunks per stream +constexpr int Q8_SPB = Q8_KC / 128; // 5 steps of 4 Q8_0 blocks (8 lanes x 4 values each) +__device__ __forceinline__ uint32_t q8_ld16(const uint8_t* p) { return *(const uint16_t*) p; } +__device__ __forceinline__ float q8_half(uint32_t h) { return __half2float(__ushort_as_half((unsigned short) h)); } +__device__ __forceinline__ float4 q8_four(uint32_t q, float d) { + return make_float4(d * (float) (int8_t) (q & 255u), d * (float) (int8_t) ((q >> 8) & 255u), + d * (float) (int8_t) ((q >> 16) & 255u), d * (float) (int8_t) (q >> 24)); +} + +template +__global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { + __shared__ __align__(16) float xs[T][Q8_KC]; + __shared__ float red[WARPS][T]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; + const bool inj = rg == Q8_RG; + // S25: the inject rows are F32 in the GGUF with BF16-exact values, so by default they are read as the pack's BF16 + // (exact); a Q8_0 copy (STRATA_HC_Q8_INJECT=1) is the other option + const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr; + const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : Q8_RPW; + const int row0 = inj ? warp : (rg * WARPS + warp) * Q8_RPW; + const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; + const int sub = lane & 7, bl = lane >> 3; // lanes 8b..8b+7: one Q8_0 block, 4 values each + uint32_t q[Q8_RPW][Q8_SPB]; + float dq[Q8_RPW][Q8_SPB]; +#pragma unroll + for (int r = 0; r < Q8_RPW; ++r) { + if (r >= nrows || inj_bf16) break; + const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const uint8_t* blk = row + (4 * s + bl) * Q8B; + dq[r][s] = q8_half(q8_ld16(blk)); + q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16; + } + } + float ssp[T]; +#pragma unroll + for (int k = 0; k < T; ++k) { + ssp[k] = 0.0f; + const FusedGrArgs& a = m.a[k]; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + for (int i = t; i < Q8_KC / 4; i += THREADS) { + const int col = kc * Q8_KC + 4 * i; + float4 r = *reinterpret_cast(a.R + col); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + (col - c * N)); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + col); + ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + *reinterpret_cast(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } + } +#pragma unroll + for (int k = 0; k < T; ++k) { + const float v = warp_sum(ssp[k]); + if (lane == 0) red[warp][k] = v; + } + __syncthreads(); + if (rg == 0 && t < T) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += red[w][t]; + ssg[t * Q8_NKC + kc] = s; + } + if (nrows == 0) return; +#pragma unroll + for (int r = 0; r < Q8_RPW; ++r) { + if (r >= nrows) break; + float acc[T]; +#pragma unroll + for (int k = 0; k < T; ++k) acc[k] = 0.0f; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const int v = 32 * (4 * s + bl) + 4 * sub; + float4 w; + if (inj_bf16) { + const uint2 b = *reinterpret_cast(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v); + w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u), + __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u)); + } else { + w = q8_four(q[r][s], dq[r][s]); + } +#pragma unroll + for (int k = 0; k < T; ++k) { + const float4 x = *reinterpret_cast(&xs[k][v]); + acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]); + acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]); + } + } + const int prow = inj ? LR + warp : row0 + r; +#pragma unroll + for (int k = 0; k < T; ++k) { + const float v = warp_sum(acc[k]); + if (lane == 0) part[((size_t) k * Q8_NKC + kc) * PR + prow] = v; + } + } +} + +template +__global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const float* __restrict__ part, + const float* __restrict__ ssg) { + __shared__ __align__(16) float lo[T][LR]; + __shared__ float rsS[T][HC]; + __shared__ float g[T][HC][UPM_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int d0 = blockIdx.x * UPM_COLS; + if (t < T * HC) { + const int k = t / HC, c = t - k * HC; + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; + const float r = rsqrtf(ss / (float) N + m.a[k].eps); + rsS[k][c] = r; + if (blockIdx.x == 0) m.a[k].rs[c] = r; + } + __syncthreads(); + for (int i = t; i < T * PR; i += THREADS) { + const int k = i / PR, r = i - k * PR; + if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + float p = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; + sum = fmaf(rsS[k][c], p, sum); + } + if (r < LR) { + const float x = sum / (float) HC; + lo[k][r] = x / (1.0f + __expf(-x)); + } else { + m.a[k].inject_out[r - LR] = sum; + } + } + __syncthreads(); + constexpr int RPW8 = HC * UPM_COLS / WARPS; // 8 rows per warp +#pragma unroll 1 + for (int qq = 0; qq < RPW8; ++qq) { + const int r = warp + qq * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; + float4 w[3]; +#pragma unroll + for (int s = 0; s < 3; ++s) { // lane: values 4 lane + 128 s (the third step: lanes 0-15) + const int v = 4 * lane + 128 * s; + if (v < LR) { + const uint8_t* blk = row + (v >> 5) * Q8B; + w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); + } else { + w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + } + float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (lane < T) { + const FusedGrArgs& a = m.a[lane]; + rv = a.R[i]; + wn = a.w_norm[i]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float mine = 0.0f; +#pragma unroll + for (int k = 0; k < T; ++k) { + float acc = 0.0f; +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (v < LR) { + const float4 x = *reinterpret_cast(&lo[k][v]); + acc = fmaf(w[s].x, x.x, acc); acc = fmaf(w[s].y, x.y, acc); + acc = fmaf(w[s].z, x.z, acc); acc = fmaf(w[s].w, x.w, acc); + } + } + acc = warp_sum(acc); + if (lane == k) mine = acc; + } + if (lane < T) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[lane].R_out[i] = rv; + } + const float x = rv * wn * rsS[lane][c]; + g[lane][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) sum += g[k][c][col]; + m.a[k].mixed[d0 + col] = sum / (float) HC; + } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE +} + + +// S26 STRATA_TSUM=1: gr_down_q8_kernel / gr_up_q8_kernel with each row's T per-token warp sums (and the sums of +// squares) as one transposed butterfly (s26_tsum.cuh): bitwise the same values (S26 ws4 harness, every output equal, +// T 1-4: 1.00 / 1.03 / 1.03 / 1.15x per read). PF (all rows' weights in registers before the part / lo phase) was +// slower (0.92-1.03x) and is off. +using s26ts::tsum; +using s26ts::tsum_token; +using s26ts::tsum_lane; +using s26ts::pow2_ceil; +// gr_down_q8_kernel / gr_up_q8_kernel with every per-token warp sum done as one transposed butterfly per row (tsum) +template +__global__ void __launch_bounds__(THREADS) gr_down_q8_fast_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { + constexpr int P = pow2_ceil(T); + constexpr int RG_ = LR / (WARPS * RPW); + __shared__ __align__(16) float xs[T][Q8_KC]; + __shared__ float red[WARPS][T]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; + const bool inj = rg == RG_; + const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr; + const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : RPW; + const int row0 = inj ? warp : (rg * WARPS + warp) * RPW; + const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; + const int sub = lane & 7, bl = lane >> 3; + const int tk = tsum_token

(lane); + const bool owner = lane == tsum_lane

(tk) && tk < T; + uint32_t q[RPW][Q8_SPB]; + float dq[RPW][Q8_SPB]; +#pragma unroll + for (int r = 0; r < RPW; ++r) { + if (r >= nrows || inj_bf16) break; + const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const uint8_t* blk = row + (4 * s + bl) * Q8B; + dq[r][s] = q8_half(q8_ld16(blk)); + q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16; + } + } + float ssp[P]; +#pragma unroll + for (int k = 0; k < P; ++k) ssp[k] = 0.0f; +#pragma unroll + for (int k = 0; k < T; ++k) { + const FusedGrArgs& a = m.a[k]; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + for (int i = t; i < Q8_KC / 4; i += THREADS) { + const int col = kc * Q8_KC + 4 * i; + float4 r = *reinterpret_cast(a.R + col); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + (col - c * N)); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + col); + ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + *reinterpret_cast(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } + } + { + const float v = tsum

(ssp, lane); + if (owner) red[warp][tk] = v; + } + __syncthreads(); + if (rg == 0 && t < T) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += red[w][t]; + ssg[t * Q8_NKC + kc] = s; + } + if (nrows == 0) return; +#pragma unroll + for (int r = 0; r < RPW; ++r) { + if (r >= nrows) break; + float acc[P]; +#pragma unroll + for (int k = 0; k < P; ++k) acc[k] = 0.0f; +#pragma unroll + for (int s = 0; s < Q8_SPB; ++s) { + const int v = 32 * (4 * s + bl) + 4 * sub; + float4 w; + if (inj_bf16) { + const uint2 b = *reinterpret_cast(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v); + w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u), + __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u)); + } else { + w = q8_four(q[r][s], dq[r][s]); + } +#pragma unroll + for (int k = 0; k < T; ++k) { + const float4 x = *reinterpret_cast(&xs[k][v]); + acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]); + acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]); + } + } + const int prow = inj ? LR + warp : row0 + r; + const float v = tsum

(acc, lane); + if (owner) part[((size_t) tk * Q8_NKC + kc) * PR + prow] = v; + } +} + +template +__global__ void __launch_bounds__(THREADS) gr_up_q8_fast_kernel(GrMulti m, const float* __restrict__ part, + const float* __restrict__ ssg) { + constexpr int P = pow2_ceil(T); + constexpr int RPW8 = HC * UPM_COLS / WARPS; + __shared__ __align__(16) float lo[T][LR]; + __shared__ float rsS[T][HC]; + __shared__ float g[T][HC][UPM_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int d0 = blockIdx.x * UPM_COLS; + const int tk = tsum_token

(lane); + const bool owner = lane == tsum_lane

(tk) && tk < T; + // PF: every row's weights in registers before the part / lo phase (its latency hides the weight read) + uint32_t pq[PF ? RPW8 : 1][3]; + float pd[PF ? RPW8 : 1][3]; + if constexpr (PF) { +#pragma unroll + for (int qq = 0; qq < RPW8; ++qq) { + const int r = warp + qq * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (v < LR) { + const uint8_t* blk = row + (v >> 5) * Q8B; + pq[qq][s] = q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16; + pd[qq][s] = q8_half(q8_ld16(blk)); + } else { + pq[qq][s] = 0u; pd[qq][s] = 0.0f; + } + } + } + } + if (t < T * HC) { + const int k = t / HC, c = t - k * HC; + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; + const float r = rsqrtf(ss / (float) N + m.a[k].eps); + rsS[k][c] = r; + if (blockIdx.x == 0) m.a[k].rs[c] = r; + } + __syncthreads(); + for (int i = t; i < T * PR; i += THREADS) { + const int k = i / PR, r = i - k * PR; + if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + float p = 0.0f; +#pragma unroll + for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; + sum = fmaf(rsS[k][c], p, sum); + } + if (r < LR) { + const float x = sum / (float) HC; + lo[k][r] = x / (1.0f + __expf(-x)); + } else { + m.a[k].inject_out[r - LR] = sum; + } + } + __syncthreads(); +#pragma unroll(PF ? RPW8 : 2) + for (int qq = 0; qq < RPW8; ++qq) { + const int r = warp + qq * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; + float4 w[3]; +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (PF) { + w[s] = v < LR ? q8_four(pq[PF ? qq : 0][s], pd[PF ? qq : 0][s]) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } else if (v < LR) { + const uint8_t* blk = row + (v >> 5) * Q8B; + w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); + } else { + w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + } + float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (owner) { + const FusedGrArgs& a = m.a[tk]; + rv = a.R[i]; + wn = a.w_norm[i]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float acc[P]; +#pragma unroll + for (int k = 0; k < P; ++k) acc[k] = 0.0f; +#pragma unroll + for (int k = 0; k < T; ++k) { +#pragma unroll + for (int s = 0; s < 3; ++s) { + const int v = 4 * lane + 128 * s; + if (v < LR) { + const float4 x = *reinterpret_cast(&lo[k][v]); + acc[k] = fmaf(w[s].x, x.x, acc[k]); acc[k] = fmaf(w[s].y, x.y, acc[k]); + acc[k] = fmaf(w[s].z, x.z, acc[k]); acc[k] = fmaf(w[s].w, x.w, acc[k]); + } + } + } + const float mine = tsum

(acc, lane); + if (owner) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[tk].R_out[i] = rv; + } + const float x = rv * wn * rsS[tk][c]; + g[tk][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) sum += g[k][c][col]; + m.a[k].mixed[d0 + col] = sum / (float) HC; + } + if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE +} + +template void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf, + int stamp_i0) { + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); + if (ts) gr_down_q8_fast_kernel<<>>(m, part, ssg); + else gr_down_q8_kernel<<>>(m, part, ssg); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); + if (ts) gr_up_q8_fast_kernel<<>>(m, part, ssg); + else gr_up_q8_kernel<<>>(m, part, ssg); +} +void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { + float* part = scratch; + float* ssg = scratch + (size_t) m.T * Q8_NKC * PR; + switch (m.T) { + case 1: launch_q8_t<1>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 2: launch_q8_t<2>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 3: launch_q8_t<3>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 4: launch_q8_t<4>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 5: launch_q8_t<5>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 6: launch_q8_t<6>(m, part, ssg, st, stamp_buf, stamp_i0); break; + case 7: launch_q8_t<7>(m, part, ssg, st, stamp_buf, stamp_i0); break; + default: launch_q8_t<8>(m, part, ssg, st, stamp_buf, stamp_i0); break; + } +} + } // namespace #if defined(STRATA_HIP_GFX906) @@ -1053,7 +1553,7 @@ int g_gr_fast = -1; #endif void fused_gr_set_fast(int on) { g_gr_fast = on; } -void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, +bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, int stamp_i0) { if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n"); @@ -1065,14 +1565,29 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi const FusedGrArgs& x = a[t]; if (!x.R || !x.w_norm || !x.w_down || !x.w_up || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) || (x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up || - x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm) { + x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm || x.q8_down != a[0].q8_down || + x.q8_up != a[0].q8_up || x.q8_inject != a[0].q8_inject) { std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t); std::exit(1); } } + // S26 STRATA_QFUSE: every token needs its q8_1 destination and token 0 the counters; otherwise none is written + bool q8 = a[0].q8_cnt != nullptr; + for (int t = 0; t < n_tok; ++t) q8 = q8 && a[t].q8_mixed != nullptr; + if (!q8) + for (int t = 0; t < n_tok; ++t) m.a[t].q8_mixed = nullptr; m.xn = xn_scratch; m.T = n_tok; cudaStream_t st = (cudaStream_t) stream; + if (a[0].q8_down != nullptr && a[0].q8_up != nullptr) { // inject: Q8_0 copy, or the BF16 rows + launch_q8(m, xn_scratch, st, stamp_buf, stamp_i0); // S23 experiment: STRATA_HC_Q8=1 + const cudaError_t eq = cudaGetLastError(); + if (eq != cudaSuccess) { + std::fprintf(stderr, "fused_gr_read_multi q8: %s\n", cudaGetErrorString(eq)); + std::exit(1); + } + return q8; + } // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in) static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit @@ -1125,7 +1640,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi std::fprintf(stderr, "fused_gr_read_multi v3: %s\n", cudaGetErrorString(e3)); std::exit(1); } - return; + return false; // the v3 read: no q8_1 (the caller quantizes) } #if defined(STRATA_HIP_GFX906) // gfx906, opt-in STRATA_GR_SPLIT=1: the latency-hidden norm/up (STRATA_GR_FAST) with the K-split down (~3% faster @@ -1159,6 +1674,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); std::exit(1); } + return q8; } bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) { diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 5c552fa7..3fe38ecb 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -7,6 +7,7 @@ #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/dp4a.hpp" #include "strata/kernels/q8_1_finite.hpp" +#include "s26_tsum.cuh" #include #include @@ -16,6 +17,7 @@ #include "ggml-common.h" #include +#include #include #include @@ -1745,6 +1747,662 @@ void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int } } + +// ---------------------------------------------------------------- S26 STRATA_EXPERT_V2=1 (opt-in): IQ3_S gate/up + IQ4_NL down +// Bitwise equal to native_gu_multi_kernel / native_down_multi_kernel (S26 harness, real UD-IQ4_XS expert blobs, T 1-3, +// memcmp of every output): each row's lane sums and warp_sum are the same; a warp interleaves RPW rows (more loads in +// flight) and reads the chunk's activation rows from LDS and, for IQ3_S, the grid table from LDS (the same values). +template __device__ __forceinline__ int ld16i(const uint16_t* p) { + if constexpr (NT) return (int) __builtin_nontemporal_load(p); else return (int) *p; +} +template __device__ __forceinline__ int ldb2(const void* x, int i32) { + const uint16_t* x16 = (const uint16_t*) x; + int x32 = ld16i(x16 + 2 * i32 + 0) << 0; + x32 |= ld16i(x16 + 2 * i32 + 1) << 16; + return x32; +} +template __device__ __forceinline__ int ld8i(const uint8_t* p) { + if constexpr (NT) return (int) __builtin_nontemporal_load(p); else return (int) *p; +} +template __device__ __forceinline__ float ldhalf(const half* p) { + return __half2float(__ushort_as_half((unsigned short) ld16i(reinterpret_cast(p)))); +} +template struct S26Split; +template struct S26Split<21, NT> { // IQ3_S: Split<21>::load with the loads made explicit + using W = Split<21>::W; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(ldb2(bq3->qs, iqs + 0), ldb2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = ld8i(bq3->qh + iqs / 2); + const int signs_packed_32 = ldb2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = 1 + 2 * ((ld8i(bq3->scales + iqs / 4) >> ((iqs << 1) & 0x04)) & 0x0F); + r.dw = ldhalf(&bq3->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<21>::apply(r, b, iqs); } +}; +template struct S26Split<20, NT> { // IQ4_NL + using W = Split<20>::W; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; + W r; +#pragma unroll + for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(ldb2(bq4->qs, iqs + l), kvalues_iq4nl); + r.dw = ldhalf(&bq4->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<20>::apply(r, b, iqs); } +}; + +// S26 v13+: v6 (4 interleaved rows per warp) with the IQ3_S grid table (LT) and / or the chunk's activation rows (LX) +// read from LDS: the same table values and the same q8_1 bytes, so the same arithmetic and bits. +struct S26IQ3S { // Split<21>::load with the grid from `grid` (LT) or iq3s_grid itself + using W = Split<21>::W; + template + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq3->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int i0 = qs[l0 + 0] | ((qh << (8 - l0)) & 0x100), i1 = qs[l0 + 1] | ((qh << (7 - l0)) & 0x100); + const int2 grid_pos = LT ? make_int2(grid[i0], grid[i1]) : make_int2(iq3s_grid[i0], iq3s_grid[i1]); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); + r.dw = __half2float(bq3->d); + return r; + } +}; + +constexpr int S26_XMAX = 2560 / 32; // q8_1 blocks of one activation row (n_embd 2560) + +// S26 BAL: step I of a warp's RPW x NI items (item p = 32 I + lane): rows QA / QB (lanes >= THR take QB) +template struct S26Bal { + static constexpr int P0 = 32 * I, QA = P0 / NI, QB0 = (P0 + 31) / NI, QB = QB0 < RPW ? QB0 : RPW - 1; + static constexpr int THR = (QA + 1) * NI - P0; + static_assert(NI >= 32, "a step spans at most two rows"); +}; + +template +__global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + __shared__ uint32_t s_grid[LT ? 512 : 1]; + __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + if constexpr (LT) + for (int i = threadIdx.x; i < 512; i += 256) s_grid[i] = iq3s_grid[i]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row0 = blockIdx.x * GU_ROWS * RPW + warp; + const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; + int rr[RPW]; + bool upq[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { + const int row = row0 + q * GU_ROWS; + upq[q] = row >= L.n_ff; + rr[q] = upq[q] ? row - (int) L.n_ff : row; + wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row; + } + const uint32_t* grid = LT ? s_grid : reinterpret_cast(iq3s_grid); + const int nb = (int) (L.n_embd / 256), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* xbase = xq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); // the previous chunk is done with s_x + for (int i = threadIdx.x; i < n * xb; i += 256) { + const int c = i / xb, j = i - c * xb; + s_x[c * S26_XMAX + j] = xq[(size_t) ent_tok[e + c] * xb + j]; + } +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX; + xbase = s_x; + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + } + if constexpr (LT || LX) __syncthreads(); // s_grid / s_x ready + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * 8; k += 32) { + const int kbx = k / 8, iqs = 2 * (k % 8); + Split<21>::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { if constexpr (SL && !LT) w[q] = S26Split<21, false>::load(wr[q], kbx, iqs); else w[q] = S26IQ3S::load(wr[q], kbx, iqs, grid); } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += Split<21>::apply(w[q], xbase + off[c] + kbx * 8, iqs); + } + if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums) + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC) { + const int c = j % GRP_NC; +#pragma unroll + for (int q = 0; q < RPW; ++q) + if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum; + } + continue; + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c]; + } +} + +constexpr int S26_HMAX = 640 / 32; // q8_1 blocks of one SwiGLU row (n_ff 640) + +template +__global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r0 = blockIdx.x * 8 * RPW + warp; + const bool live = r0 + 8 * (RPW - 1) < L.n_embd; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row; + const int nb = (int) (L.n_ff / 32), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* hbase = hq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); + for (int i = threadIdx.x; i < n * hb; i += 256) { + const int c = i / hb, j = i - c * hb; + s_h[c * S26_HMAX + j] = hq[(size_t) (e + c) * hb + j]; + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX; + hbase = s_h; + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + } + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + if constexpr (BAL > 0) { // S26: 5 items per lane instead of 8 / 4, in BAL groups (loads first) + constexpr int NI = 2 * S26_HMAX, IT = RPW * NI / 32; + static_assert(RPW * NI % 32 == 0, "whole steps"); + auto group = [&](std::integer_sequence) { + Split<20>::W w[sizeof...(J)]; + int kk[sizeof...(J)]; + bool hh[sizeof...(J)]; + ([&] { + using B = S26Bal; + hh[J] = B::QB != B::QA && lane >= B::THR; + kk[J] = B::P0 + lane - (hh[J] ? B::QB : B::QA) * NI; + const uint8_t* rp = hh[J] ? wr[B::QB] : wr[B::QA]; + if constexpr (SL) w[J] = S26Split<20, false>::load(rp, kk[J] / 2, 2 * (kk[J] % 2)); + else w[J] = Split<20>::load(rp, kk[J] / 2, 2 * (kk[J] % 2)); + }(), ...); + ([&] { + using B = S26Bal; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) { + const float v = Split<20>::apply(w[J], hbase + off[c] + kk[J] / 2, 2 * (kk[J] % 2)); + if (hh[J]) s[B::QB][c] += v; else s[B::QA][c] += v; + } + }(), ...); + }; + constexpr int G = (IT + BAL - 1) / BAL; + [&](std::integer_sequence) { + (group.template operator()(std::make_integer_sequence{}), ...); + }(std::make_integer_sequence{}); + } else + for (int k = lane; k < nb * 2; k += 32) { + const int kbx = k / 2, iqs = 2 * (k % 2); + Split<20>::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { if constexpr (SL) w[q] = S26Split<20, false>::load(wr[q], kbx, iqs); else w[q] = Split<20>::load(wr[q], kbx, iqs); } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += Split<20>::apply(w[q], hbase + off[c] + kbx, iqs); + } + if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums) + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + const int q = j / GRP_NC, c = j % GRP_NC; + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC && c < n) + out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum; + continue; + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c]; + } +} + + +// S26: swiglu_entries_kernel + quantize_q8_1_kernel in one launch (the same h expression, then the same block quantizer, +// contraction off so the product cannot fuse into the first sum); h is still written (it is the scratch the old pair used) +__global__ void s26_swiglu_q8_1_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h, + block_q8_1* __restrict__ y, long long n) { +#pragma clang fp contract(off) + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; // n is a multiple of 32: whole warps only + const float g = gate[i]; + const float xi = (g / (1.0f + __expf(-g))) * up[i]; + h[i] = xi; + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); + sum += __shfl_xor_sync(0xffffffffu, sum, o); + } + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const long long ib = i / 32, iqs = i % 32; + y[ib].qs[iqs] = q; + if (iqs == 0) y[ib].ds = make_half2(d, sum); +} +template +void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, + const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) { + const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups); + s26_gu_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + if (FQ) { + s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh); + } else { + swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh); + quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); + } + const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); + s26_down_l_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); +} +// ---------------------------------------------------------------- stream B: UD-Q4_K_XL grouped decode experts +// STRATA_EXPERT_V2K=1: s26_gu_l_kernel / s26_down_l_kernel's structure (4 interleaved rows per warp, the chunk's q8_1 +// activation rows in LDS, SwiGLU + q8_1 fused, optionally STRATA_TSUM's transposed butterfly) for Q4_K / Q5_K gate/up +// and Q5_1 / Q8_0 down, which otherwise run native_gu_kernel / native_down_kernel (one entry at a time, the weight +// words re-read per column). Each Fmt::dot is split into S27::load (everything that depends on the weight) and +// apply (the activation words and the same integer / float expression), the same impl functions, so a row's lane-strided +// k order, its terms and warp_sum are the old kernels': every output is bitwise the old one's (iq harness, memcmp). +template struct S27; +template<> struct S27<12> { // Q4_K + struct W { int v[2]; uint16_t aux[2]; half2 dm; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q4_K* b = (const block_q4_K*) vbq + kbx; + W r; + const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); + const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + r.v[0] = q4[0]; + r.v[1] = q4[4]; + k_scale_min(b->scales, bq8_offset, r.aux); + r.dm = b->dm; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); + int u[2 * QR4_K]; + float d8[QR4_K]; +#pragma unroll + for (int i = 0; i < QR4_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + const uint8_t* sc = (const uint8_t*) r.aux; + const uint8_t* m = sc + 2; + return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8); + } +}; +template<> struct S27<13> { // Q5_K + struct W { int vl[2]; int vh[2]; uint16_t aux[2]; half2 dm; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q5_K* b = (const block_q5_K*) vbq + kbx; + W r; + const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); + const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4)); + r.vl[0] = ql[0]; + r.vl[1] = ql[4]; + r.vh[0] = qh[0] >> bq8_offset; + r.vh[1] = qh[4] >> bq8_offset; + k_scale_min(b->scales, bq8_offset, r.aux); + r.dm = b->dm; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); + int u[2 * QR5_K]; + float d8[QR5_K]; +#pragma unroll + for (int i = 0; i < QR5_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + const uint8_t* sc = (const uint8_t*) r.aux; + const uint8_t* m = sc + 2; + return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8); + } +}; +template<> struct S27<7> { // Q5_1 + struct W { int vl[VDR_Q5_1]; int qh; half2 dm; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q5_1* b = (const block_q5_1*) vbq + kbx; + W r; +#pragma unroll + for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i); + r.qh = get_int_b4(b->qh, 0); + r.dm = b->dm; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0, sumu = 0; +#pragma unroll + for (int i = 0; i < VDR_Q5_1; ++i) { + const int vl = r.vl[i]; + const int vh = r.qh >> (4 * (iqs + i)); + const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1); + int vi0 = (vl >> 0) & 0x0F0F0F0F; + vi0 |= (vh << 4) & 0x00000010; + vi0 |= (vh << 11) & 0x00001000; + vi0 |= (vh << 18) & 0x00100000; + vi0 |= (vh << 25) & 0x10000000; + sumi = ggml_cuda_dp4a(vi0, u0, sumi); + int vi1 = (vl >> 4) & 0x0F0F0F0F; + vi1 |= (vh >> 12) & 0x00000010; + vi1 |= (vh >> 5) & 0x00001000; + vi1 |= (vh << 2) & 0x00100000; + vi1 |= (vh << 9) & 0x10000000; + sumi = ggml_cuda_dp4a(vi1, u1, sumi); + sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); + } + const float2 dm5 = __half22float2(r.dm); + const float d8 = __low2float(bq8_1->ds); + return sumi * (dm5.x * d8) + sumu * (dm5.y * d8); + } +}; +template<> struct S27<8> { // Q8_0 + struct W { int q[VDR_Q8_0]; float d; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q8_0* b = (const block_q8_0*) vbq + kbx; + W r; +#pragma unroll + for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i); + r.d = __half2float(b->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi); + const float d8_1 = __low2float(bq8_1->ds); + return r.d * d8_1 * ((float) sumi); + } +}; + +template +__global__ void __launch_bounds__(256) s27_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + using F = Fmt; + using S = S27; + __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row0 = blockIdx.x * GU_ROWS * RPW + warp; + const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; + int rr[RPW]; + bool upq[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) { + const int row = row0 + q * GU_ROWS; + upq[q] = row >= L.n_ff; + rr[q] = upq[q] ? row - (int) L.n_ff : row; + wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row; + } + const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* xbase = xq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); // the previous chunk is done with s_x + for (int i = threadIdx.x; i < n * xb; i += 256) { + const int c = i / xb, j = i - c * xb; + s_x[c * S26_XMAX + j] = xq[(size_t) ent_tok[e + c] * xb + j]; + } +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX; + xbase = s_x; + __syncthreads(); + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + } + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += S::apply(w[q], xbase + off[c] + kbx * (F::qk / 32), iqs); + } + if constexpr (TS) { + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC) { + const int c = j % GRP_NC; +#pragma unroll + for (int q = 0; q < RPW; ++q) + if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum; + } + continue; + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c]; + } +} + +template +__global__ void __launch_bounds__(256) s27_down_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + using F = Fmt; + using S = S27; + __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r0 = blockIdx.x * 8 * RPW + warp; + const bool live = r0 + 8 * (RPW - 1) < L.n_embd; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row; + const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + const block_q8_1* hbase = hq; + int off[GRP_NC]; + if constexpr (LX) { + __syncthreads(); + for (int i = threadIdx.x; i < n * hb; i += 256) { + const int c = i / hb, j = i - c * hb; + s_h[c * S26_HMAX + j] = hq[(size_t) (e + c) * hb + j]; + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX; + hbase = s_h; + } else { +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + } + if (!live) continue; + float s[RPW][GRP_NC]; +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + typename S::W w[RPW]; +#pragma unroll + for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] += S::apply(w[q], hbase + off[c] + kbx * (F::qk / 32), iqs); + } + if constexpr (TS) { + constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC); + float v[P]; +#pragma unroll + for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f; + const float sum = s26ts::tsum

(v, lane); + const int j = s26ts::tsum_token

(lane); + const int q = j / GRP_NC, c = j % GRP_NC; + if (lane == s26ts::tsum_lane

(j) && j < RPW * GRP_NC && c < n) + out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum; + continue; + } +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n) s[q][c] = warp_sum(s[q][c]); +#pragma unroll + for (int q = 0; q < RPW; ++q) +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c]; + } +} + +template +void s27_launch(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, + const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, + const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) { + const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups); + s27_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh); + const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups); + s27_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); +} +template +void s27_launch_ts(bool ts, const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, + const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, + const int32_t* ent_dst, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, float* h, + block_q8_1* hq, float* out, long long nh) { + if (ts) s27_launch(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh); + else s27_launch(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh); +} + template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, @@ -2458,6 +3116,34 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long float* h = (float*) ((uint8_t*) scratch + 2 * fa); block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa); const auto* X = (const block_q8_1*) x_q8_1; + static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }(); + if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel + // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values) + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + // (+ down rows' items spread evenly over the lanes, one load group: bitwise, harness 1.09-1.12x vs 1.03-1.06x; + // the same for gate / up was 0.6-0.8x) + if (ts) s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, + hq, out, (long long) cap_entries * L.n_ff); + else s26_launch_l(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, + hq, out, (long long) cap_entries * L.n_ff); + check("native_expert_grouped (v2)"); + return; + } + // stream B: UD-Q4_K_XL's Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down (see S27 above) + static const bool v2k = [] { const char* v = std::getenv("STRATA_EXPERT_V2K"); return v && v[0] == '1'; }(); + if (v2k && (L.gu_type == 12 || L.gu_type == 13) && (L.d_type == 7 || L.d_type == 8) && L.n_embd == 2560 && + L.n_ff == 640) { + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + const long long nh = (long long) cap_entries * L.n_ff; +#define STRATA_V2K(G, D) s27_launch_ts(ts, L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh) + if (L.gu_type == 12 && L.d_type == 7) STRATA_V2K(12, 7); + else if (L.gu_type == 12) STRATA_V2K(12, 8); + else if (L.d_type == 7) STRATA_V2K(13, 7); + else STRATA_V2K(13, 8); +#undef STRATA_V2K + check("native_expert_grouped (v2k)"); + return; + } const bool v1 = g_grouped_v1; const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups; const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) gy); diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu index fb2ccec4..2965f233 100644 --- a/src/kernels/cuda/kv_q8.cu +++ b/src/kernels/cuda/kv_q8.cu @@ -27,14 +27,22 @@ void validate(const QsaShapes& s, const char* what) { } // One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each. +// MULTI (S26 STRATA_LFUSE): blockIdx.z = 2 * token + (K / V); token j reads step + j * step_stride and its rows at +// kcur / vcur + j * cur_stride - every token's code is the single launch's +template __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict__ v_q, uint16_t* __restrict__ k_scale, uint16_t* __restrict__ v_scale, const int32_t* __restrict__ table, const int32_t* __restrict__ step, const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, - int head_dim, int page_size, KvHostPools host) { + int head_dim, int page_size, KvHostPools host, int step_stride = 0, + int cur_stride = 0) { + if constexpr (MULTI) { + const int j = blockIdx.z >> 1; + step += (size_t) j * step_stride; kcur += (size_t) j * cur_stride; vcur += (size_t) j * cur_stride; + } const long long pos = (long long) __ldg(step + kStepPos); const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; - const bool is_v = blockIdx.z == 1; + const bool is_v = MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1; const int groups = head_dim / KV_Q8_GROUP; const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order @@ -111,6 +119,18 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_ check("kv_append_q8 launch"); } +void kv_append_q8_steps(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, + const int32_t* step, int step_stride, const float* kcur, const float* vcur, int cur_stride, + int n_tok, const QsaShapes& s, void* stream, const KvHostPools* host) { + validate(s, "kv_append_q8 (steps)"); + if (n_tok < 1) return; + const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), (unsigned) (2 * n_tok)); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}, step_stride, cur_stride); + check("kv_append_q8 (steps) launch"); +} + void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale, const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { diff --git a/src/kernels/cuda/native_bf16.cu b/src/kernels/cuda/native_bf16.cu index fdbdc947..9715e460 100644 --- a/src/kernels/cuda/native_bf16.cu +++ b/src/kernels/cuda/native_bf16.cu @@ -1,7 +1,9 @@ #include "strata/kernels/bf16_gemv.hpp" +#include "s26_tsum.cuh" #include "strata/kernels/bf16_bits.hpp" #include +#include #include #include #include @@ -118,6 +120,124 @@ __global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t if (k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k]; } +// S25 (STRATA_MMVF_ROWS=1): RPB output rows per block. Each block read its row's weights once but all T activation +// rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the +// activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two +// ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel. +// S26 STRATA_LFUSE=1 (AUX): one more block computes row 0 of w_aux into y_aux[k * ldy_aux] - the same per-output +// code, so each aux output is bitwise what its own bf16_f32_mmvf_multi_kernel launch gave (the shared expert's gate) +template +__global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w, + float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok, + const uint16_t* __restrict__ w_aux = nullptr, float* __restrict__ y_aux = nullptr, + int64_t ldy_aux = 0) { + const int t = threadIdx.x; + int o0 = blockIdx.x * RPB; + if constexpr (AUX) { + if (blockIdx.x == gridDim.x - 1) { w = w_aux; y = y_aux; ldy = ldy_aux; n_out = 1; o0 = 0; } + } + __shared__ float partials[RPB][NT][32]; + if constexpr (BLOCK_SIZE > 32) { + if (t < 32) +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) partials[r][k][t] = 0.0f; + __syncthreads(); + } + float acc[RPB][NT]; +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[r][k] = 0.0f; + for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) { + float2 in[NT]; +#pragma unroll + for (int k = 0; k < NT; ++k) + if (k < n_tok) in[k] = reinterpret_cast(x + (size_t) k * ldx)[pair]; +#pragma unroll + for (int r = 0; r < RPB; ++r) { + if (o0 + r >= n_out) break; + const uint32_t weight = reinterpret_cast(w + (size_t) (o0 + r) * n_in)[pair]; + const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16)); +#pragma unroll + for (int k = 0; k < NT; ++k) { + if (k < n_tok) { + acc[r][k] = __fmaf_rn(w0, in[k].x, acc[r][k]); + acc[r][k] = __fmaf_rn(w1, in[k].y, acc[r][k]); + } + } + } + } + if constexpr (TS) { // S26 STRATA_TSUM=1: the RPB x NT warp sums (both stages) as transposed butterflies, bitwise the same + constexpr int V = RPB * NT, P = s26ts::pow2_ceil(V); + const int lane = t & 31, j = s26ts::tsum_token

(lane); + const bool own = lane == s26ts::tsum_lane

(j) && j < V; + float v[P]; +#pragma unroll + for (int q = 0; q < P; ++q) v[q] = q < V ? acc[q / NT][q % NT] : 0.0f; + float sum = s26ts::tsum

(v, lane); + if constexpr (BLOCK_SIZE > 32) { + if (own) partials[j / NT][j % NT][t / 32] = sum; + __syncthreads(); + if (t >= 32) return; +#pragma unroll + for (int q = 0; q < P; ++q) v[q] = q < V ? partials[q / NT][q % NT][t] : 0.0f; + sum = s26ts::tsum

(v, lane); + } + const int r = j / NT, k = j % NT; + if (own && o0 + r < n_out && k < n_tok) y[(size_t) k * ldy + o0 + r] = sum; + return; + } +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(acc[r][k]); + if constexpr (BLOCK_SIZE > 32) { + if ((t & 31) == 0) +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) partials[r][k][t / 32] = acc[r][k]; + __syncthreads(); + if (t < 32) +#pragma unroll + for (int r = 0; r < RPB; ++r) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(partials[r][k][t]); + } + if (t == 0) +#pragma unroll + for (int r = 0; r < RPB; ++r) + if (o0 + r < n_out) +#pragma unroll + for (int k = 0; k < NT; ++k) + if (k < n_tok) y[(size_t) k * ldy + o0 + r] = acc[r][k]; +} + +template +void launch_rows(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int n_in, int n_out, int n_tok, + cudaStream_t st, const uint16_t* w_aux = nullptr, float* y_aux = nullptr, int64_t ldy_aux = 0) { + constexpr int RPB = 4; + const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB); + static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + if (w_aux != nullptr) { // S26 STRATA_LFUSE: + one aux row block +#define S26_AUX(TSV) \ + if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok, w_aux, y_aux, ldy_aux); \ + else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok, w_aux, y_aux, ldy_aux); + if (ts) { S26_AUX(true) } else { S26_AUX(false) } +#undef S26_AUX + return; + } + if (ts) { + if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); + else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); + return; + } + if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); + else bf16_f32_mmvf_rows_kernel<<>>(x, ldx, w, y, ldy, n_in, n_out, n_tok); +} + int mmvf_block_size(int64_t n_in) { int best = 32; int64_t best_iterations = (n_in + 63) / 64; @@ -133,6 +253,32 @@ int mmvf_block_size(int64_t n_in) { } // namespace +bool bf16_gemv_fp32_mmvf_multi_aux(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, + int64_t n_in, int64_t n_out, int n_tok, const uint16_t* w_aux, float* y_aux, + int64_t ldy_aux, void* stream) { + static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }(); + // exactly the conditions under which both calls would take the rows / multi kernels at the same block size + if (!rows || n_out < 64 || n_tok < 2 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || (ldx & 1) != 0 || x == nullptr || + w == nullptr || y == nullptr || w_aux == nullptr || y_aux == nullptr || (reinterpret_cast(x) & 7u) != 0) + return false; + const cudaStream_t st = (cudaStream_t) stream; + const int ni = (int) n_in, no = (int) n_out; + switch (mmvf_block_size(n_in)) { + case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st, w_aux, y_aux, ldy_aux); break; + } + const cudaError_t result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi_aux launch: ") + cudaGetErrorString(result)); + return true; +} + void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int64_t n_in, int64_t n_out, int n_tok, void* stream) { if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; } @@ -140,6 +286,24 @@ void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, f w == nullptr || y == nullptr || (reinterpret_cast(x) & 7u) != 0) throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers"); const cudaStream_t st = (cudaStream_t) stream; + static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }(); + if (rows && n_out >= 64) { + const int ni = (int) n_in, no = (int) n_out; + switch (mmvf_block_size(n_in)) { + case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st); break; + } + const cudaError_t result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result)); + return; + } #define STRATA_MMVF_M(N) case N: \ if (n_tok <= 4) bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); \ else bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); break diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index e0d11bf1..29b1b6b2 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -27,15 +27,21 @@ #include "strata/kernels/dp4a.hpp" #include "strata/kernels/q8_1_finite.hpp" #include "strata/kernels/iq_kernels.hpp" +#include "s26_tsum.cuh" #include #include +#include #include #include +#include #include #include #include +#include +#include +#include namespace strata::kernels { namespace { @@ -1026,14 +1032,27 @@ struct SmallTraits { // equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently). bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured) -template +// S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same +static bool s26_tsum_on() { + static const bool on = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); + return on; +} + +// S26 STRATA_LFUSE (PAIR): blocks n_out.. compute the same rows of w2 into y2 (two matrices of one shape on one +// input in one launch; each output's code is the single matrix's) +template __launch_bounds__(NW * WARP, (ROWS <= 2 ? 4 : 1)) __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x, - float* __restrict__ y, int n_in, int n_out) { + float* __restrict__ y, int n_in, int n_out, + const typename F::Block* __restrict__ w2 = nullptr, float* __restrict__ y2 = nullptr) { constexpr int BPI = F::BPI * NW / WARPS; // blocks per iteration scale with the warp count const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); - const int row0 = ROWS * int(blockIdx.x); + int bxi = int(blockIdx.x); + if constexpr (PAIR) { + if (bxi >= n_out / ROWS) { bxi -= n_out / ROWS; w = w2; y = y2; } + } + const int row0 = ROWS * bxi; const int blocks_per_row = n_in / F::DIV; const int x_stride = n_in / Q8K; // Q8_1 blocks per activation column float tmp[NCOLS][ROWS] = {}; @@ -1060,6 +1079,25 @@ __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w } __syncthreads(); if (threadIdx.y > 0) return; + if constexpr (TS) { + constexpr int V = NCOLS * ROWS, P = s26ts::pow2_ceil(V); + float v[P]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < NW - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x]; + v[j * ROWS + i] = tmp[j][i]; + } +#pragma unroll + for (int k = V; k < P; ++k) v[k] = 0.0f; + const float sum = s26ts::tsum

(v, int(threadIdx.x)); + const int k = s26ts::tsum_token

(int(threadIdx.x)); + const int j = k / ROWS, i = k % ROWS; + if (int(threadIdx.x) == s26ts::tsum_lane

(k) && k < V && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum; + return; + } #pragma unroll for (int j = 0; j < NCOLS; ++j) { #pragma unroll @@ -1086,9 +1124,11 @@ void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, if (n_in / F::DIV < F::BPI) { constexpr int ROWS = 2; const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS); - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + if (s26_tsum_on()) native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + else native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); } else { - native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + if (s26_tsum_on()) native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + else native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); } } @@ -1242,8 +1282,429 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1, small_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); } +// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================ +// +// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row) +// followed by the SAME fp16 scales in a d plane (row-major, n_in / 32 per row) - no requantization, same bytes. +// The GGUF's 34-byte blocks leave every int 2-byte aligned (load_int_b2 = two 16-bit loads); the planes give each +// thread one aligned 8-byte run, read with streaming (non-temporal) loads. Every thread owns exactly the bytes of +// the ncols = 1 / multi-column EXACT layout (block kbx = tid / 4 + 32 i, ints 2 (tid % 4) and +1), accumulates them +// in the same order with the same expression, and the cross-warp sum and XOR tree are the same: every output is +// BITWISE equal to native_small_mmvq_kernel / native_mmvq_multi_kernel, NC, 4, 1>. +// Eligible: 1024 <= n_in <= 4096 and n_out >= 2048, run as 640 persistent workgroups (a grid-stride over rows, two +// partial buffers). Measured on gfx1151 (S26, 8 real UD-IQ4_XS layers per shape, paired, 1-5 columns): 2560 -> +// 6144/10240/12288 +10-12% per call (engine trace: -10.7% on those calls). 6144 -> 2560 (one workgroup per row) +// was +2-4% standalone but -3% in the engine, and rows < 2048 lose: neither is packed. +#if defined(__HIPCC__) +#define STRATA_Q8P_LOAD(p) __builtin_nontemporal_load(p) +#else +#define STRATA_Q8P_LOAD(p) __ldcs(p) +#endif +constexpr int Q8P_PERSIST_GRID = 640; +constexpr int Q8P_PERSIST_MAX_IN = 4096; + +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q8_0_packed_kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl, + const Q81Block* __restrict__ x, float* __restrict__ y, + int n_in, int n_out, int row_step) { + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int nb = n_in / 32; + const int kqs = 2 * (tid % 4); + __shared__ float partial[2][WARPS - 1][NCOLS][WARP]; + int buf = 0; + for (int row = int(blockIdx.x); row < n_out; row += row_step, buf ^= 1) { + float tmp[NCOLS] = {}; + for (int kbx = tid / 4; kbx < nb; kbx += 2 * WARPS * WARP / 8) { + const std::size_t block = std::size_t(row) * nb + kbx; + const int* p = reinterpret_cast(qs + block * 32) + kqs; + const int v0 = STRATA_Q8P_LOAD(p); + const int v1 = STRATA_Q8P_LOAD(p + 1); + const float d0 = dpl[block]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { + const Q81Block* xb = x + std::size_t(j) * nb + kbx; + const int* u = reinterpret_cast(xb->qs); + int sumi = 0; + sumi = STRATA_DP4A(v0, u[kqs], sumi); + sumi = STRATA_DP4A(v1, u[kqs + 1], sumi); + const float d1 = __low2float(xb->ds); + tmp[j] += d0 * d1 * float(sumi); + } + } + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j]; + } + __syncthreads(); + if (TS && threadIdx.y == 0) { // S26 STRATA_TSUM=1: one transposed butterfly, bitwise the same sums + constexpr int P = s26ts::pow2_ceil(NCOLS); + float v[P]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + v[j] = tmp[j]; + } +#pragma unroll + for (int j = NCOLS; j < P; ++j) v[j] = 0.0f; + const float sum = s26ts::tsum

(v, int(threadIdx.x)); + const int j = s26ts::tsum_token

(int(threadIdx.x)); + if (int(threadIdx.x) == s26ts::tsum_lane

(j) && j < NCOLS) y[std::size_t(j) * n_out + row] = sum; + } else if (threadIdx.y == 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + tmp[j] = warp_sum(tmp[j]); + if (threadIdx.x == 0) y[std::size_t(j) * n_out + row] = tmp[j]; + } + } + } +} + +struct Q8Packed { const int8_t* qs; const half* d; int n_in, n_out; }; +std::unordered_map& q8_packed_registry() { + static std::unordered_map registry; + return registry; +} + +template +void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream_t s) { + const bool persist = w.n_in <= Q8P_PERSIST_MAX_IN; + const int grid = persist ? (std::min)(w.n_out, Q8P_PERSIST_GRID) : w.n_out; + if (s26_tsum_on()) + native_q8_0_packed_kernel<<>>(w.qs, w.d, x, y, w.n_in, w.n_out, + persist ? grid : w.n_out); + else + native_q8_0_packed_kernel<<>>(w.qs, w.d, x, y, w.n_in, w.n_out, + persist ? grid : w.n_out); +} + +bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + auto& registry = q8_packed_registry(); + if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false; // packed = the EXACT layout only + const auto found = registry.find(weights); + if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false; + validate_shape(n_in, ncols, 32); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + switch (ncols) { + case 1: q8_packed_launch<1>(found->second, x, y, s); break; + case 2: q8_packed_launch<2>(found->second, x, y, s); break; + case 3: q8_packed_launch<3>(found->second, x, y, s); break; + case 4: q8_packed_launch<4>(found->second, x, y, s); break; + case 5: q8_packed_launch<5>(found->second, x, y, s); break; + case 6: q8_packed_launch<6>(found->second, x, y, s); break; + case 7: q8_packed_launch<7>(found->second, x, y, s); break; + case 8: q8_packed_launch<8>(found->second, x, y, s); break; + default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); + } + launch_check(); + return true; +} + + +// ============================ STRATA_Q6_PACKED=1: the packed Q6_K head layout (opt-in) ============================ +// +// The output heads (the main head, 248320 rows, and the MTP draft head's row subset) are Q6_K matrices of 2560-wide +// rows: 10 blocks of 210 bytes each, so every int load is 2-byte aligned and a row is 2100 bytes. The packed copy +// holds the SAME bytes as four planes - ql (128 B per block), qh (64 B), scales (16 B), d (2 B) - so a thread's +// two words are aligned dword loads (non-temporal). Thread ownership (block tid / 32 + 4 i, word tid % 32), the +// q6_q8_dot_impl expression, the per-thread order and the reduction are those of native_q6_k_mmvq_kernel / +// native_mmvq_multi_kernel: every output is bitwise equal. Persistent workgroups. +int g_q6p_grid_override = 0; // the self-test's grid sweep (STRATA_Q6P_SELFTEST=2) +int q6p_grid() { + if (g_q6p_grid_override > 0) return g_q6p_grid_override; + static const int grid = [] { + const char* v = std::getenv("STRATA_Q6P_GRID"); + const int g = v ? std::atoi(v) : 0; + return g > 0 ? g : 640; + }(); + return grid; +} + +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q6_k_packed_kernel(const int* __restrict__ ql, const int* __restrict__ qh, + const int8_t* __restrict__ sc, const half* __restrict__ dpl, + const Q81Block* __restrict__ x, float* __restrict__ y, + int n_in, int n_out, int row_step) { + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int nb = n_in / 256; + const int x_stride = n_in / Q8K; + const int iqs = tid % 32; + const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; + const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; + const int vh_shift = 2 * ((iqs % 16) / 8); + const int qh_word = 8 * (iqs / 16) + iqs % 8; + __shared__ float partial[2][WARPS - 1][NCOLS][WARP]; + int buf = 0; + for (int row = int(blockIdx.x); row < n_out; row += row_step, buf ^= 1) { + float tmp[NCOLS] = {}; + for (int kbx = tid / 32; kbx < nb; kbx += WARPS * WARP / 32) { + const std::size_t block = std::size_t(row) * nb + kbx; + const int vl = STRATA_Q8P_LOAD(ql + block * 32 + iqs); + const int vh = STRATA_Q8P_LOAD(qh + block * 16 + qh_word) >> vh_shift; + const int8_t* scales = sc + block * 16 + scale_offset; + const float d = dpl[block]; + const int kby = kbx * 8; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { + const Q81Block* xb = x + std::size_t(j) * x_stride + kby; + int u[2]; + float d8[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + u[i] = reinterpret_cast(xb[bq8_offset + 2 * i].qs)[iqs % 8]; + d8[i] = __low2float(xb[bq8_offset + 2 * i].ds); + } + tmp[j] += q6_q8_dot_impl(vl, vh, u, scales, d, d8); + } + } + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j]; + } + __syncthreads(); + if (TS && threadIdx.y == 0) { // S26 STRATA_TSUM=1: one transposed butterfly, bitwise the same sums + constexpr int P = s26ts::pow2_ceil(NCOLS); + float v[P]; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + v[j] = tmp[j]; + } +#pragma unroll + for (int j = NCOLS; j < P; ++j) v[j] = 0.0f; + const float sum = s26ts::tsum

(v, int(threadIdx.x)); + const int j = s26ts::tsum_token

(int(threadIdx.x)); + if (int(threadIdx.x) == s26ts::tsum_lane

(j) && j < NCOLS) y[std::size_t(j) * n_out + row] = sum; + } else if (threadIdx.y == 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x]; + tmp[j] = warp_sum(tmp[j]); + if (threadIdx.x == 0) y[std::size_t(j) * n_out + row] = tmp[j]; + } + } + } +} + +bool g_q6_bypass = false; // the load-time self-test times the GGUF-layout kernels with the copy registered + +// the packed planes of one Q6_K matrix (owned: allocated by native_q6_k_pack, freed by native_q6_k_unpack) +struct Q6Packed { void* base; const int* ql; const int* qh; const int8_t* sc; const half* d; int n_in, n_out; }; +std::unordered_map& q6_packed_registry() { + static std::unordered_map registry; + return registry; +} + +template +void q6_packed_launch(const Q6Packed& w, const Q81Block* x, float* y, cudaStream_t s) { + const int grid = (std::min)(w.n_out, q6p_grid()); + if (s26_tsum_on()) + native_q6_k_packed_kernel<<>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in, + w.n_out, grid); + else + native_q6_k_packed_kernel<<>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in, + w.n_out, grid); +} + +bool q6_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + auto& registry = q6_packed_registry(); + if (registry.empty() || g_q6_bypass || (ncols > 1 && !g_multi_exact)) return false; + const auto found = registry.find(weights); + if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false; + validate_shape(n_in, ncols, 256); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + switch (ncols) { + case 1: q6_packed_launch<1>(found->second, x, y, s); break; + case 2: q6_packed_launch<2>(found->second, x, y, s); break; + case 3: q6_packed_launch<3>(found->second, x, y, s); break; + case 4: q6_packed_launch<4>(found->second, x, y, s); break; + case 5: q6_packed_launch<5>(found->second, x, y, s); break; + case 6: q6_packed_launch<6>(found->second, x, y, s); break; + case 7: q6_packed_launch<7>(found->second, x, y, s); break; + case 8: q6_packed_launch<8>(found->second, x, y, s); break; + default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); + } + launch_check(); + return true; +} } // namespace +bool native_q8_0_packed_enabled() { + static const bool enabled = [] { + const char* v = std::getenv("STRATA_Q8_PACKED"); + return v && v[0] == '1' && v[1] == '\0'; + }(); + return enabled; +} + +bool native_q8_0_packed_eligible(int n_in, int n_out) { + return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN && + n_out >= 2048; +} + +void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) { + const auto* blocks = static_cast(gguf_blocks); + auto* qs = static_cast(out); + auto* d = reinterpret_cast(qs + std::size_t(n_in) * n_out); + const std::size_t count = std::size_t(n_in / 32) * n_out; + for (std::size_t b = 0; b < count; ++b) { + std::memcpy(qs + b * 32, blocks[b].qs, 32); + std::memcpy(d + b, &blocks[b].d, sizeof(half)); + } +} + +void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out) { + validate_pointer(gguf_weights); + validate_pointer(packed); + if (!native_q8_0_packed_eligible(n_in, n_out)) throw std::invalid_argument("Q8_0 packed: ineligible shape"); + const auto* qs = static_cast(packed); + q8_packed_registry()[gguf_weights] = + Q8Packed{qs, reinterpret_cast(qs + std::size_t(n_in) * n_out), n_in, n_out}; +} + +void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); } + +bool native_q6_k_packed_enabled() { + static const bool enabled = [] { + const char* v = std::getenv("STRATA_Q6_PACKED"); + return v && v[0] == '1' && v[1] == '\0'; + }(); + return enabled; +} + +bool native_q6_k_pack(const void* weights, int n_in, int n_out, const char* what) { + if (!weights || n_in <= 0 || n_in % 256 || n_in / 256 < WARPS * WARP / 32 || n_out < 2048) return false; + if (q6_packed_registry().count(weights)) return true; + const std::size_t nb = std::size_t(n_in / 256) * std::size_t(n_out); + const std::size_t bytes = nb * sizeof(Q6KBlock); + std::vector host(nb); + if (cudaMemcpy(host.data(), weights, bytes, cudaMemcpyDeviceToHost) != cudaSuccess) { cudaGetLastError(); return false; } + // planes: ql | qh | scales | d, each 256-byte aligned + const std::size_t o_qh = (nb * 128 + 255) & ~std::size_t(255); + const std::size_t o_sc = (o_qh + nb * 64 + 255) & ~std::size_t(255); + const std::size_t o_d = (o_sc + nb * 16 + 255) & ~std::size_t(255); + const std::size_t total = o_d + nb * 2; + std::vector packed(total, 0); + for (std::size_t b = 0; b < nb; ++b) { + std::memcpy(packed.data() + b * 128, host[b].ql, 128); + std::memcpy(packed.data() + o_qh + b * 64, host[b].qh, 64); + std::memcpy(packed.data() + o_sc + b * 16, host[b].scales, 16); + std::memcpy(packed.data() + o_d + b * 2, &host[b].d, 2); + } + void* dev = nullptr; + if (cudaMalloc(&dev, total) != cudaSuccess) { cudaGetLastError(); return false; } + if (cudaMemcpy(dev, packed.data(), total, cudaMemcpyHostToDevice) != cudaSuccess) { + cudaFree(dev); cudaGetLastError(); return false; + } + auto* base = static_cast(dev); + q6_packed_registry()[weights] = Q6Packed{dev, reinterpret_cast(base), + reinterpret_cast(base + o_qh), + reinterpret_cast(base + o_sc), + reinterpret_cast(base + o_d), n_in, n_out}; + std::fprintf(stderr, "strata: STRATA_Q6_PACKED=1 packed the %s (%d x %d, +%.1f MiB)\n", what, n_out, n_in, + total / 1048576.0); + // STRATA_Q6P_SELFTEST=1: bitwise check against the GGUF-layout kernels (1..4 columns) and paired timings + if (const char* v = std::getenv("STRATA_Q6P_SELFTEST"); v && (v[0] == '1' || v[0] == '2')) { + cudaStream_t s = nullptr; + cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking); + const int nq = n_in / Q8K; + std::vector hx(std::size_t(4) * nq); + uint32_t r = 12345u; + for (auto& blk : hx) { + for (auto& q : blk.qs) { r = r * 1664525u + 1013904223u; q = int8_t(int((r >> 24) & 255u) - 128); } + r = r * 1664525u + 1013904223u; + blk.ds = __floats2half2_rn(0.001f + float(r >> 8) * 1e-9f, 0.0f); + } + void *dx = nullptr, *ya = nullptr, *yb = nullptr; + cudaMalloc(&dx, hx.size() * sizeof(Q81Block)); + cudaMalloc(&ya, std::size_t(4) * n_out * 4); + cudaMalloc(&yb, std::size_t(4) * n_out * 4); + cudaMemcpy(dx, hx.data(), hx.size() * sizeof(Q81Block), cudaMemcpyHostToDevice); + std::vector a(std::size_t(4) * n_out), c(std::size_t(4) * n_out); + bool same = true; + for (int nc = 1; nc <= 4; ++nc) { + g_q6_bypass = true; + native_q6_k_mmvq(weights, dx, (float*) ya, n_in, n_out, nc, s); + g_q6_bypass = false; + native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s); + cudaStreamSynchronize(s); + cudaMemcpy(a.data(), ya, std::size_t(nc) * n_out * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(c.data(), yb, std::size_t(nc) * n_out * 4, cudaMemcpyDeviceToHost); + same = same && std::memcmp(a.data(), c.data(), std::size_t(nc) * n_out * 4) == 0; + } + cudaEvent_t e0, e1; + cudaEventCreate(&e0); cudaEventCreate(&e1); + for (int nc : {1, 2, 4}) { + std::vector tb, tc; + for (int k = 0; k < 11; ++k) { + for (int pass = 0; pass < 2; ++pass) { + const bool cand = (pass == 0) == (k % 2 == 1); + g_q6_bypass = !cand; + cudaEventRecord(e0, s); + for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) (cand ? yb : ya), n_in, n_out, nc, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + float ms = 0; cudaEventElapsedTime(&ms, e0, e1); + (cand ? tc : tb).push_back(ms * 1000.0f / 5); + } + } + g_q6_bypass = false; + std::sort(tb.begin(), tb.end()); std::sort(tc.begin(), tc.end()); + std::fprintf(stderr, "strata: Q6_K packed self-test %s ncols %d: GGUF %.1f us (%.1f-%.1f), packed %.1f us " + "(%.1f-%.1f), 11 paired samples\n", what, nc, tb[5], tb[0], tb[10], tc[5], tc[0], tc[10]); + } + std::fprintf(stderr, "strata: Q6_K packed self-test %s: outputs %s (1-4 columns)\n", what, + same ? "BITWISE EQUAL" : "DIFFER"); + if (v[0] == '2') { // grid sweep of the packed kernel + for (int grid : {160, 320, 640, 1280, 2560, 5120, 20480}) { + g_q6p_grid_override = grid; + for (int nc : {1, 2, 4}) { + std::vector tc; + for (int k = 0; k < 7; ++k) { + cudaEventRecord(e0, s); + for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + float ms = 0; cudaEventElapsedTime(&ms, e0, e1); + tc.push_back(ms * 1000.0f / 5); + } + std::sort(tc.begin(), tc.end()); + std::fprintf(stderr, "strata: Q6_K packed grid sweep %s grid %d ncols %d: %.1f us (%.1f-%.1f)\n", + what, grid, nc, tc[3], tc[0], tc[6]); + } + } + g_q6p_grid_override = 0; + } + cudaEventDestroy(e0); cudaEventDestroy(e1); + cudaFree(dx); cudaFree(ya); cudaFree(yb); + cudaStreamDestroy(s); + if (!same) { native_q6_k_unpack(weights); return false; } + } + return true; +} + +void native_q6_k_unpack(const void* weights) { + auto& registry = q6_packed_registry(); + const auto found = registry.find(weights); + if (found == registry.end()) return; + cudaFree(found->second.base); + registry.erase(found); +} + void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; } bool native_mmvq_multi_exact() { return g_multi_exact; } @@ -1484,6 +1945,7 @@ void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1, void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + if (q6_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q6_PACKED=1 heads validate_shape(n_in, ncols, 256); if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); validate_pointer(weights); @@ -1542,8 +2004,46 @@ void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); } +template +void q8_0_pair_launch(const Q80Block* w1, const Q80Block* w2, const Q81Block* x, float* y1, float* y2, int n_in, int n_out, + cudaStream_t s) { + using F = SmallTraits; + const dim3 threads(WARP, WARPS); + if (s26_tsum_on()) + native_mmvq_multi_kernel<<>>(w1, x, y1, n_in, n_out, w2, y2); + else + native_mmvq_multi_kernel<<>>(w1, x, y1, n_in, n_out, w2, y2); +} + +bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2, + int n_in, int n_out, int ncols, void* stream) { + using F = SmallTraits; + // only where both calls would run native_mmvq_multi_kernel (exact layout, not packed) + if (ggml_type != 8 || !g_multi_exact || ncols < 2 || ncols > 8 || n_out <= 0 || n_in <= 0 || n_in % 32 != 0 || + n_in / F::DIV < F::BPI || !w1 || !w2 || !x_q8_1 || !y1 || !y2 || !stream) + return false; + const auto& reg = q8_packed_registry(); + if (reg.count(w1) || reg.count(w2)) return false; + const auto* a = static_cast(w1); + const auto* b = static_cast(w2); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + switch (ncols) { + case 2: q8_0_pair_launch<2>(a, b, x, y1, y2, n_in, n_out, s); break; + case 3: q8_0_pair_launch<3>(a, b, x, y1, y2, n_in, n_out, s); break; + case 4: q8_0_pair_launch<4>(a, b, x, y1, y2, n_in, n_out, s); break; + case 5: q8_0_pair_launch<5>(a, b, x, y1, y2, n_in, n_out, s); break; + case 6: q8_0_pair_launch<6>(a, b, x, y1, y2, n_in, n_out, s); break; + case 7: q8_0_pair_launch<7>(a, b, x, y1, y2, n_in, n_out, s); break; + default: q8_0_pair_launch<8>(a, b, x, y1, y2, n_in, n_out, s); break; + } + launch_check(); + return true; +} + void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + if (q8_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return; // STRATA_Q8_PACKED=1 tensors small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); } diff --git a/src/kernels/cuda/native_moe.cu b/src/kernels/cuda/native_moe.cu index 7f1f91ce..ab3950d9 100644 --- a/src/kernels/cuda/native_moe.cu +++ b/src/kernels/cuda/native_moe.cu @@ -31,19 +31,36 @@ namespace strata::kernels { namespace { std::atomic enabled{false}; +// GATED (S26 STRATA_LFUSE): `shared` is the shared expert's unscaled output and sg its raw gate logit per token; +// the row is scaled here as shared_expert_multi did (native_scalar_sigmoid_multi_kernel's expression, then one +// rounded multiply = scale_rows_kernel's `out *= g`), then added as before +template __global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights, const float* __restrict__ shared, float* __restrict__ output, - int64_t n_embd, int k) { + int64_t n_embd, int k, const float* __restrict__ sg = nullptr) { // blockIdx.y = the token of a multi-token launch (0 for the single one) const int64_t tk = blockIdx.y; parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd; const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; if (col >= n_embd) return; - float sum = parts[col] * weights[0]; + // ZADD: a part is 0.0f + hit (the zeroed row plus moe_hit_add of the verify window), rounded as that add + float p0 = parts[col]; + if (ZADD) p0 = 0.0f + p0; + float sum = p0 * weights[0]; for (int expert = 1; expert < k; ++expert) { - sum += parts[int64_t(expert) * n_embd + col] * weights[expert]; + float p = parts[int64_t(expert) * n_embd + col]; + if (ZADD) p = 0.0f + p; + sum += p * weights[expert]; + } + if constexpr (GATED) { + // contraction off in this block only: the product is rounded on its own (scale_rows' store), then added +#pragma clang fp contract(off) + const float g = __fdividef(1.0f, 1.0f + __expf(-sg[tk])); + const float sh = shared[col] * g; + sum += sh; + } else { + if (shared) sum += shared[col]; } - if (shared) sum += shared[col]; output[col] = sum; } bool valid_span(const void* p, size_t bytes) { @@ -83,4 +100,23 @@ void native_moe_combine_multi(const float* parts, const float* weights, const fl const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } +void native_moe_combine_multi_hits_gated(const float* hits, const float* weights, const float* shared, + const float* shared_gate, float* output, int64_t n_embd, int64_t k, int n_tok, + void* stream) { + if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1 || !shared || !shared_gate) + throw std::invalid_argument("native MoE combine (hits, gated) requires a stream, width, 1..15 experts, tokens"); + combine<<(stream)>>>( + hits, weights, shared, output, n_embd, int(k), shared_gate); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +void native_moe_combine_multi_hits(const float* hits, const float* weights, const float* shared, float* output, + int64_t n_embd, int64_t k, int n_tok, void* stream) { + if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) + throw std::invalid_argument("native MoE combine (hits) requires a stream, width, 1..15 experts, tokens"); + combine<<(stream)>>>( + hits, weights, shared, output, n_embd, int(k)); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} } diff --git a/src/kernels/cuda/native_qsa.cu b/src/kernels/cuda/native_qsa.cu index 32e2511c..2e2e1e6b 100644 --- a/src/kernels/cuda/native_qsa.cu +++ b/src/kernels/cuda/native_qsa.cu @@ -66,6 +66,31 @@ __global__ void norm(const float* input, const float* __restrict__ gamma, float* for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) output[col] = scale * input[col] * gamma[col]; } +// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma. +template +__global__ void norm_grouped(const float* input, const float* __restrict__ gamma, float* output, + int n_cols, int groups, float epsilon) { + const int tid = threadIdx.x; + const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; + input += row_offset; output += row_offset; + gamma += std::size_t(blockIdx.x % unsigned(groups)) * n_cols; + float partial = 0.0f; + for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) { + const float x = input[col]; + partial += x * x; + } + __shared__ float sums[32]; + partial = warp_sum(partial); + const int lane = tid % 32; + if (lane == 0) sums[tid / 32] = partial; + __syncthreads(); + partial = lane < BlockSize / 32 ? sums[lane] : 0.0f; + partial = warp_sum(partial); + const float mean = partial / n_cols; + const float scale = rsqrtf(mean + epsilon); + for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) + output[col] = scale * input[col] * gamma[col]; +} __global__ void gate(const float* attn, const float* __restrict__ q_full, float* output, int n_head, int head_dim) { const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; @@ -117,6 +142,21 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* norm<1024><<(stream)>>>(input, gamma, output, n_cols, epsilon); check_launch(); } +void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output, + int n_cols, int groups, int n_rows, float epsilon, void* stream) { + if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions"); + const auto count = elements(n_cols, n_rows); + if (!std::isfinite(epsilon) || epsilon < 0.0f) + throw std::invalid_argument("native QSA requires finite nonnegative epsilon"); + buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream); + if (n_cols < 1024) + norm_grouped<256><<(stream)>>>(input, gamma, output, n_cols, + groups, epsilon); + else + norm_grouped<1024><<(stream)>>>(input, gamma, output, n_cols, + groups, epsilon); + check_launch(); +} void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, int n_head, int head_dim, void* stream) { const auto count = elements(head_dim, n_head); diff --git a/src/kernels/cuda/ple.cu b/src/kernels/cuda/ple.cu index 984512b0..f945ef3b 100644 --- a/src/kernels/cuda/ple.cu +++ b/src/kernels/cuda/ple.cu @@ -304,7 +304,9 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co // ---- key = grouped_norm(ple_key @ emb). The optional native projection // follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path. - if (w.key_bf16 != nullptr) { + if (w.pre_key != nullptr) { + cudaMemcpyAsync(d_key, w.pre_key, (size_t) hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st); + } else if (w.key_bf16 != nullptr) { bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream); } else if (native_key) { native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream); @@ -320,7 +322,9 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co } // The value projection's independent option leaves the nonlinear PLE operations unchanged. - if (native_bf16) { + if (w.pre_value != nullptr) { + cudaMemcpyAsync(d_value, w.pre_value, (size_t) n_embd * sizeof(float), cudaMemcpyDeviceToDevice, st); + } else if (native_bf16) { bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream); } else { to_bf16_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(emb, d_emb16, n_embd); diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index f487c4f3..37c24120 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -80,7 +80,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo } else load8_q4(p, value, row, d0, out); } -template +template __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, @@ -120,6 +120,41 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest srow[t] = r; } __syncthreads(); + if constexpr (LANE_CELL) { + // S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same + // 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as + // lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle + // reductions per cell + constexpr int HPT = G * CHUNK / THREADS; // heads per thread (3) + const int c = t % CHUNK, h0 = (t / CHUNK) * HPT; + if (c >= n_here || srow[c] < 0) { +#pragma unroll + for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX; + } else { + float a[HPT][32]; +#pragma unroll + for (int l = 0; l < 32; ++l) { + float k8[8]; + load8(p, false, srow[c], l * 8, k8); +#pragma unroll + for (int j = 0; j < HPT; ++j) { + const float4 qa = *reinterpret_cast(&sq[h0 + j][l * 8]); + const float4 qb = *reinterpret_cast(&sq[h0 + j][l * 8 + 4]); + float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; + a[j][l] = s; + } + } +#pragma unroll + for (int j = 0; j < HPT; ++j) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) +#pragma unroll + for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o]; + sp[h0 + j][c] = a[j][0] * scale; + } + } + } else // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. for (int c = warp; c < CHUNK; c += WARPS) { if (c >= n_here || srow[c] < 0) { @@ -466,6 +501,16 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); cudaStream_t st = (cudaStream_t) stream; + // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) + static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); +#define STRATA_ATTN_LC(M) attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride) + if (lane_cell) { + if (kv_mode == 3) STRATA_ATTN_LC(3); + else if (kv_mode == 2) STRATA_ATTN_LC(2); + else if (kv_mode == 1) STRATA_ATTN_LC(1); + else STRATA_ATTN_LC(0); + } else +#undef STRATA_ATTN_LC if (kv_mode == 3) STRATA_ATTN_CHUNK(3)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 9b481929..cfc5a001 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1129,12 +1129,30 @@ bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, // FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order). // Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds // B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7. +// gfx11 (RDNA3 / RDNA3.5: gfx110x, gfx115x) has the same instruction with another layout: A lane l holds all 16 k of +// row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l all 16 k of column l % 16, and C/D lane l holds +// D[2 * i + l / 16][l % 16]. PA_KL is the k values per lane (8 or 16), PA_KOFF(half) the first one, PA_ROW the C row. #if defined(__gfx1200__) || defined(__gfx1201__) #define STRATA_PA_WMMA 1 +#define STRATA_PA_GFX11 0 +#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \ + defined(__gfx1151__) +#define STRATA_PA_WMMA 1 +#define STRATA_PA_GFX11 1 #else #define STRATA_PA_WMMA 0 +#define STRATA_PA_GFX11 0 #endif -typedef _Float16 wh8 __attribute__((ext_vector_type(8))); +#if STRATA_PA_GFX11 +constexpr int PA_KL = 16; +#define PA_KOFF(half) 0 +#define PA_ROW(i, half) (2 * (i) + (half)) +#else +constexpr int PA_KL = 8; +#define PA_KOFF(half) ((half) * 8) +#define PA_ROW(i, half) ((half) * 8 + (i)) +#endif +typedef _Float16 wh8 __attribute__((ext_vector_type(PA_KL))); typedef float wf8 __attribute__((ext_vector_type(8))); constexpr int WCH = 32; // cells per chunk (two 16-cell tiles) constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread) @@ -1151,7 +1169,9 @@ struct alignas(16) SmemW { }; __device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { -#if STRATA_PA_WMMA +#if STRATA_PA_WMMA && STRATA_PA_GFX11 + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#elif STRATA_PA_WMMA return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); #else __builtin_trap(); @@ -1159,16 +1179,17 @@ __device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { #endif } -__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128 +__device__ __forceinline__ wh8 i8_to_h(const uint32_t* x) { // PA_KL codes, exact: |code| <= 128 wh8 h; #pragma unroll - for (int i = 0; i < 4; ++i) { - h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i)); - h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i)); - } + for (int i = 0; i < PA_KL; ++i) h[i] = (_Float16) (int) (int8_t) (x[i / 4] >> (8 * (i % 4))); return h; } +// SPLIT = true (default): q and p carried as FP16 hi + lo pairs (two WMMAs each: FP32-level). S23 (opt-in +// STRATA_PA_FAST=1): SPLIT = false, one FP16 image each - half the matrix work, rounding-level (FP16 attention as the +// usual flash-attention kernels), quality-gated +template __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ steps, int n_kv_heads, @@ -1197,21 +1218,24 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* int qe = 0; if (qm > 0.0f) frexpf(qm, &qe); const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); - // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i + // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + PA_KOFF(half) + i wh8 qh[4], ql[4]; #pragma unroll for (int kk = 0; kk < 4; ++kk) { - float x[8]; + float x[PA_KL]; if (col < G) { - const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + half * 8); - const float4 a = src[0], b = src[1]; - x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w; + const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + PA_KOFF(half)); +#pragma unroll + for (int j = 0; j < PA_KL / 4; ++j) { + const float4 a = src[j]; + x[4 * j] = a.x; x[4 * j + 1] = a.y; x[4 * j + 2] = a.z; x[4 * j + 3] = a.w; + } } else { #pragma unroll - for (int i = 0; i < 8; ++i) x[i] = 0.0f; + for (int i = 0; i < PA_KL; ++i) x[i] = 0.0f; } #pragma unroll - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < PA_KL; ++i) { const float v = x[i] * qup; const _Float16 hi = (_Float16) v; qh[kk][i] = hi; @@ -1258,14 +1282,23 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp))); #pragma unroll for (int kk = 0; kk < 4; ++kk) { - uint2 kx = make_uint2(0, 0); - if (rr >= 0) kx = __ldg(reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + half * 8)); - const wh8 b = i8x8_to_h8(kx); + uint32_t kx[PA_KL / 4] = {}; + if (rr >= 0) { + const uint32_t* src = reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + PA_KOFF(half)); +#if STRATA_PA_GFX11 + const uint4 v = __ldg(reinterpret_cast(src)); + kx[0] = v.x; kx[1] = v.y; kx[2] = v.z; kx[3] = v.w; +#else + const uint2 v = __ldg(reinterpret_cast(src)); + kx[0] = v.x; kx[1] = v.y; +#endif + } + const wh8 b = i8_to_h(kx); s = wmma_f16(qh[kk], b, s); - s = wmma_f16(ql[kk], b, s); + if constexpr (SPLIT) s = wmma_f16(ql[kk], b, s); } #pragma unroll - for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc; + for (int i = 0; i < 8; ++i) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * ksc; } __syncthreads(); // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread @@ -1312,10 +1345,10 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; #pragma unroll for (int ks = 0; ks < 2; ++ks) { - const int cb = ks * 16 + half * 8; // this lane's 8 cells + const int cb = ks * 16 + PA_KOFF(half); // this lane's PA_KL cells wh8 ah, al; #pragma unroll - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < PA_KL; ++i) { const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup); const _Float16 hi = (_Float16) pv; ah[i] = hi; @@ -1326,14 +1359,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* const int d = j * 16 + col; wh8 b; #pragma unroll - for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; + for (int i = 0; i < PA_KL; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; tmp[j] = wmma_f16(ah, b, tmp[j]); - tmp[j] = wmma_f16(al, b, tmp[j]); + if constexpr (SPLIT) tmp[j] = wmma_f16(al, b, tmp[j]); } } float a[8]; #pragma unroll - for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i]; + for (int i = 0; i < 8; ++i) a[i] = S.alpha[PA_ROW(i, half)]; #pragma unroll for (int j = 0; j < 4; ++j) #pragma unroll @@ -1345,14 +1378,14 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* float inv[8]; #pragma unroll for (int i = 0; i < 8; ++i) { - const float l = S.lsum[half * 8 + i]; + const float l = S.lsum[PA_ROW(i, half)]; inv[i] = l > 0.0f ? 1.0f / l : 0.0f; } #pragma unroll for (int j = 0; j < 4; ++j) #pragma unroll for (int i = 0; i < 8; ++i) { - const int row = half * 8 + i; + const int row = PA_ROW(i, half); if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i]; } #else @@ -1360,20 +1393,22 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* #endif } -// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits +// gfx12 (RDNA4) and gfx11 (RDNA3 / RDNA3.5), only on request: the output differs from the default kernel's in its +// last bits bool hip_wmma_usable() { static const bool want = [] { const char* e = std::getenv("STRATA_HIP_WMMA"); return e != nullptr && e[0] == '1'; }(); if (!want) return false; - static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other + static int arch[64] = {}; // 0 unknown, 1 gfx11 / gfx12, 2 other int dev = 0; if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } if (arch[dev] == 0) { hipDeviceProp_t prop{}; if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; } - arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2; + arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 || std::strncmp(prop.gcnArchName, "gfx11", 5) == 0 + ? 1 : 2; static bool told = false; if (!told) { told = true; @@ -1389,9 +1424,16 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; - prompt_attn_wmma_kernel<<>>( - q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, - (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + static const bool fast = [] { const char* e = std::getenv("STRATA_PA_FAST"); return e != nullptr && e[0] == '1'; }(); + static const int64_t min_t = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }(); + if (fast && n_q >= min_t) + prompt_attn_wmma_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + else + prompt_attn_wmma_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); } const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index 56222c51..305969e6 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -291,14 +291,32 @@ __global__ void __launch_bounds__(128) block_scores_tc_kernel(const float* __res // a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its // 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are // split once per CTA into LDS. +// gfx11 (RDNA3 / RDNA3.5) has the same instruction with another fragment layout: a lane holds all 16 k of its row +// (A) or column (B) - lanes 16..31 repeat lanes 0..15 - and D[2i + l/16][l%16]; SEL_KL is the k per lane, SEL_KOFF(g) +// the first, SEL_ROW(i, g) the D row of element i. Same products, same order per element as on gfx12. #if defined(__gfx1200__) || defined(__gfx1201__) #define STRATA_SEL_GFX12 1 +#define STRATA_SEL_GFX11 0 +#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \ + defined(__gfx1151__) +#define STRATA_SEL_GFX12 0 +#define STRATA_SEL_GFX11 1 #else #define STRATA_SEL_GFX12 0 +#define STRATA_SEL_GFX11 0 #endif -typedef short sel_s8 __attribute__((ext_vector_type(8))); +#if STRATA_SEL_GFX11 +constexpr int SEL_KL = 16; +#define SEL_KOFF(g) 0 +#define SEL_ROW(i, g) (2 * (i) + (g)) +#else +constexpr int SEL_KL = 8; +#define SEL_KOFF(g) ((g) * 8) +#define SEL_ROW(i, g) ((g) * 8 + (i)) +#endif +typedef short sel_s8 __attribute__((ext_vector_type(SEL_KL))); typedef float sel_f8 __attribute__((ext_vector_type(8))); -typedef uint32_t sel_u4 __attribute__((ext_vector_type(4))); +typedef uint32_t sel_u4 __attribute__((ext_vector_type(SEL_KL / 2))); constexpr int WQT = 16; // queries per CTA (the N of one WMMA) constexpr int WITER = 4; // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks) constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads @@ -306,6 +324,8 @@ constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 byt __device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) { #if STRATA_SEL_GFX12 return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +#elif STRATA_SEL_GFX11 + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); #else __trap(); return c; @@ -319,7 +339,7 @@ __device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uin lo = __float_as_uint(r1 - __uint_as_float(mid)) & 0xffff0000u; // exact: at most 8 significant bits left } __device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) { // low half = a's bf16, high half = b's -#if STRATA_SEL_GFX12 +#if STRATA_SEL_GFX12 || STRATA_SEL_GFX11 return __builtin_amdgcn_perm(b, a, 0x07060302u); #else return (a >> 16) | (b & 0xffff0000u); @@ -360,7 +380,7 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r if (b0 >= reach || b0 >= hi_nbid) break; // warp-uniform; later tiles start higher const int64_t row = b0 + l16; const bool rv = row < hi_nbid && row < max_blocks; - const float* kp = pooled + (rv ? row : 0) * IDX_DIM + g * 8; + const float* kp = pooled + (rv ? row : 0) * IDX_DIM + SEL_KOFF(g); // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7 // of the score scale; apart, near the warp kernel's) @@ -369,18 +389,19 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r for (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; #pragma unroll 2 for (int kk = 0; kk < IDX_DIM / 16; ++kk) { - float4 k0 = make_float4(0.f, 0.f, 0.f, 0.f), k1 = k0; - if (rv) { - k0 = *reinterpret_cast(kp + kk * 16); - k1 = *reinterpret_cast(kp + kk * 16 + 4); - } - const float x[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w}; - uint32_t hb[8], mb[8], lb[8]; + float x[SEL_KL]; #pragma unroll - for (int j = 0; j < 8; ++j) split3(x[j], hb[j], mb[j], lb[j]); + for (int j = 0; j < SEL_KL / 4; ++j) { + float4 kv = make_float4(0.f, 0.f, 0.f, 0.f); + if (rv) kv = *reinterpret_cast(kp + kk * 16 + 4 * j); + x[4 * j] = kv.x; x[4 * j + 1] = kv.y; x[4 * j + 2] = kv.z; x[4 * j + 3] = kv.w; + } + uint32_t hb[SEL_KL], mb[SEL_KL], lb[SEL_KL]; +#pragma unroll + for (int j = 0; j < SEL_KL; ++j) split3(x[j], hb[j], mb[j], lb[j]); sel_u4 ah, am, al; #pragma unroll - for (int j = 0; j < 4; ++j) { + for (int j = 0; j < SEL_KL / 2; ++j) { ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]); am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]); al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]); @@ -389,9 +410,9 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r Al = __builtin_bit_cast(sel_s8, al); #pragma unroll for (int h = 0; h < IDX_HEADS; ++h) { - const sel_s8 Bh = *reinterpret_cast(&sq[0][h][l16][kk * 16 + g * 8]); - const sel_s8 Bm = *reinterpret_cast(&sq[1][h][l16][kk * 16 + g * 8]); - const sel_s8 Bl = *reinterpret_cast(&sq[2][h][l16][kk * 16 + g * 8]); + const sel_s8 Bh = *reinterpret_cast(&sq[0][h][l16][kk * 16 + SEL_KOFF(g)]); + const sel_s8 Bm = *reinterpret_cast(&sq[1][h][l16][kk * 16 + SEL_KOFF(g)]); + const sel_s8 Bl = *reinterpret_cast(&sq[2][h][l16][kk * 16 + SEL_KOFF(g)]); cor[h] = wmma_bf16(Al, Bh, cor[h]); cor[h] = wmma_bf16(Ah, Bl, cor[h]); cor[h] = wmma_bf16(Am, Bm, cor[h]); @@ -400,11 +421,11 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r acc[h] = wmma_bf16(Ah, Bh, acc[h]); } } - // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + 8g .. 8g+7 + // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + SEL_ROW(i, g) if (qi < nq) { #pragma unroll for (int i = 0; i < 8; ++i) { - const int64_t b = b0 + g * 8 + i; + const int64_t b = b0 + SEL_ROW(i, g); if (b >= nb_q || b >= max_blocks) continue; float score = 0.0f; #pragma unroll @@ -418,7 +439,7 @@ __global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __r } } -// the gfx12 kernel needs gfx1200/gfx1201 code objects and a gfx12 device (gfx1100 has WMMA too, with another layout) +// the WMMA kernel needs gfx12 (gfx1200/gfx1201) or gfx11 (gfx110x/gfx115x: the other fragment layout) code objects bool sel_gfx12_device() { static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 no int dev = 0; @@ -426,7 +447,8 @@ bool sel_gfx12_device() { if (ok[dev] == 0) { cudaDeviceProp prop; ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess && - (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0)) + (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0 || + std::strncmp(prop.gcnArchName, "gfx110", 6) == 0 || std::strncmp(prop.gcnArchName, "gfx115", 6) == 0)) ? 1 : 2; cudaGetLastError(); } diff --git a/src/kernels/cuda/s26_tsum.cuh b/src/kernels/cuda/s26_tsum.cuh new file mode 100644 index 00000000..38cfc97c --- /dev/null +++ b/src/kernels/cuda/s26_tsum.cuh @@ -0,0 +1,69 @@ +// S26: several warp sums at once (P per-lane values -> P sums), bitwise equal to P separate xor-butterfly warp sums +// (`for (o = 16; o > 0; o >>= 1) v += shfl_xor(v, o)`). At offset 16 a lane keeps half of its P values and adds the +// partner's copy of that half, at 8 half again, ... until one value is left, then plain xor steps for the remaining +// offsets. Every level adds the same pair of values as the butterfly does (fp add commutes, so x + y == y + x +// bitwise), only each lane carries fewer of them: P - 1 + (5 - log2 P) cross-lane moves instead of 5 P. Value j's sum +// ends in the lanes whose bits 4, 3, .. (MSB first) spell j: tsum_lane

(j) is one of them. On AMD the moves are +// DPP row_xmask / permlanex16 instead of ds_bpermute. +#pragma once + +namespace strata::kernels::s26ts { + +#if defined(__HIP_PLATFORM_AMD__) +__device__ __forceinline__ float xmov16(float v) { + return __int_as_float(__builtin_amdgcn_permlanex16(__float_as_int(v), __float_as_int(v), 0x76543210u, 0xfedcba98u, + false, false)); +} +template +__device__ __forceinline__ float xmov(float v) { + if constexpr (O == 16) return xmov16(v); + else return __int_as_float(__builtin_amdgcn_update_dpp(0, __float_as_int(v), 0x160 + O, 0xf, 0xf, false)); +} +#else +template +__device__ __forceinline__ float xmov(float v) { return __shfl_xor_sync(0xffffffffu, v, O); } +#endif + +constexpr int pow2_ceil(int t) { return t <= 1 ? 1 : t <= 2 ? 2 : t <= 4 ? 4 : t <= 8 ? 8 : t <= 16 ? 16 : 32; } +constexpr int log2c(int p) { return p <= 1 ? 0 : p == 2 ? 1 : p == 4 ? 2 : p == 8 ? 3 : p == 16 ? 4 : 5; } + +template +__device__ __forceinline__ float tplain(float x) { + if constexpr (O >= 1) { x += xmov(x); return tplain(x); } + else return x; +} +// v[0..CNT) (CNT a power of two <= 32): this lane's values; returns the sum of value tsum_token(lane) +template +__device__ __forceinline__ float tsum(float* v, int lane) { + if constexpr (CNT > 1) { + constexpr int H = CNT / 2; + const bool hi = (lane & O) != 0; +#pragma unroll + for (int j = 0; j < H; ++j) { + const float send = hi ? v[j] : v[j + H]; + const float keep = hi ? v[j + H] : v[j]; + v[j] = keep + xmov(send); + } + return tsum(v, lane); + } else { + return tplain(v[0]); + } +} +template +__device__ __forceinline__ int tsum_token(int lane) { + constexpr int L = log2c(P); + int k = 0; +#pragma unroll + for (int b = 0; b < L; ++b) k = (k << 1) | ((lane >> (4 - b)) & 1); + return k; +} +template +__device__ __forceinline__ int tsum_lane(int k) { + constexpr int L = log2c(P); + int lane = 0; +#pragma unroll + for (int b = 0; b < L; ++b) lane |= ((k >> (L - 1 - b)) & 1) << (4 - b); + return lane; +} + +} // namespace strata::kernels::s26ts diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu index 28bb7edc..2214c7f9 100644 --- a/src/kernels/cuda/shared_expert.cu +++ b/src/kernels/cuda/shared_expert.cu @@ -69,6 +69,7 @@ __global__ void native_swiglu_kernel(const float* gate, const float* up, float* out[i] = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i]; } + __global__ void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) { const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) out[i] = f16_from_f32(in[i]); @@ -187,17 +188,23 @@ bool fused_swiglu_q81_enabled() { void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, - int64_t n_ff, void* stream) { + int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse) { + const bool gate_deferred = (lfuse & 1) != 0, pair = (lfuse & 2) != 0; if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream) throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream"); cudaStream_t cs = (cudaStream_t) stream; - const void* x_q8_1 = nw.x_q8_1; + // the activation's q8_1: the caller's (STRATA_VERIFY_QDEDUP, x_q8_1_ready) or the descriptor's, else quantized here + const void* x_q8_1 = x_q8_1_ready ? x_q8_1_ready : nw.x_q8_1; if (!x_q8_1) { native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream); x_q8_1 = nw.q8_1; } - native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream); - native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream); + // S26 STRATA_LFUSE (gate_deferred): gate and up in one launch where the pair applies (bitwise the two calls) + if (!(pair && nw.gate_type == nw.up_type && + native_mmvq_pair(nw.gate_type, nw.gate_data, nw.up_data, x_q8_1, gate, up, (int) n_embd, (int) n_ff, n_tok, stream))) { + native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream); + native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream); + } const int n = (int) (n_ff * n_tok); if (fused_swiglu_q81_enabled()) { native_swiglu_quantize_q8_1(gate, up, nw.q8_1, (int) n_ff, n_tok, stream); @@ -206,6 +213,11 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream); } native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream); + if (gate_deferred) { // the caller computed g (raw) with the router and scales `out` in the combine + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e)); + return; + } static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), fused sigmoid+scale bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream); diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index f7c48438..d48015da 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -5,6 +5,7 @@ #include "strata/kernels/verify_kernels.hpp" #include "strata/kernels/dp4a.hpp" +#include #include #include @@ -157,6 +158,25 @@ __global__ void __launch_bounds__(32 * RG) gdn_step_commit_kernel(float* __restr for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; } +// S26 (STRATA_QFUSE=1): the q8_1 image of a 32-column block, written by the warp that holds those columns with +// native_quantize_q8_1_kernel's quantizer (the same XOR-tree max and sum, d = amax / 127, roundf(x / d), ds = (d, sum)). +struct GdnQ81 { half2 ds; int8_t qs[32]; }; +__device__ __forceinline__ void gdn_q8_1_store(GdnQ81* __restrict__ xq, size_t idx, float xi) { + // no contraction: xi is a product here, and fma(a, b, shfl) would round the first sum unlike the separate + // quantizer, which reads xi from memory (S26 harness: ds.sum differed by 1 ulp without this) +#pragma clang fp contract(off) + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + xq[idx / 32].qs[idx % 32] = q; + if (idx % 32 == 0) xq[idx / 32].ds = make_half2(d, sum); +} + +template __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __restrict__ state, const float* __restrict__ hbuf, int C, const float* __restrict__ gate, @@ -164,7 +184,8 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y, int h_k, int h_v, int T, - const int32_t* __restrict__ n_keep, int t_out_begin) { + const int32_t* __restrict__ n_keep, int t_out_begin, + GdnQ81* __restrict__ xq) { __shared__ float sk[S], sq[S]; __shared__ float red[RG][S]; __shared__ float wsum[S * RG / 32]; @@ -224,7 +245,13 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float scale = rsqrtf(ss / (float) S + eps); const float zz = z[(size_t) t * value_dim + head * S + col]; - y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + if constexpr (Q) { + const float yv = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + y[(size_t) t * value_dim + head * S + col] = yv; + gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv); + } else { + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } } } if (n_keep != nullptr && n > 0) { @@ -233,6 +260,178 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re } } +// S25 (STRATA_GDN_SPLIT=1): the same recurrence with each head's 128 state columns over 4 blocks of 32 columns +// (128 threads: the same (column, row group) threads, each with the same 32 state rows), so 4x the blocks of +// gdn_step_norm_multi_kernel - which ran one 512-thread block per head (32 blocks) and read the 2 MB state of a layer +// at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head, +// moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the +// squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order. +// S26: OUT = false (the commit, whose outputs nobody reads) drops the output reduction and its two barriers; the +// norm kernel below has the old kernel's code shape (S x RG threads, rg 0 holding oc), which makes it bitwise equal - +// the 128-thread version differed from the old kernel by 1 ulp in ~7% of the outputs. +constexpr int GS_COLS = 32; +template +__global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __restrict__ state, + const float* __restrict__ hbuf, int C, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ y, int h_k, int h_v, int T, + const int32_t* __restrict__ n_keep, + int t_out_begin) { + __shared__ float sk[S], sq[S]; + __shared__ float red[RG][GS_COLS]; + const int head = blockIdx.x; + const int c0 = blockIdx.y * GS_COLS; + const int lc = threadIdx.x; // local column + const int col = c0 + lc; + const int rg = threadIdx.y; + const int tid = rg * GS_COLS + lc; + const int qh = head % h_k; + const int qk = S * h_k; + const int value_dim = S * h_v; + const int n = n_keep ? *n_keep : T; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; + for (int t = 0; t < n; ++t) { + const float* ht = hbuf + (size_t) t * C; + __syncthreads(); + if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[(size_t) t * h_v + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][lc] = kv; + __syncthreads(); + const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]; + const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + if (!OUT) continue; + __syncthreads(); + red[rg][lc] = o; + __syncthreads(); + if (rg == 0 && t >= t_out_begin) + y[(size_t) t * value_dim + head * S + col] = + (red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) * rsqrtf((float) S); + } + if (n_keep != nullptr && n > 0) { +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; + } +} + + +// S26: the state-only replay (the commit) with its per-token inputs prefetched - gate, beta and the v column of every +// row up front, the next row's k / q while the current one computes. The arithmetic and its order are +// gdn_step_split_kernel's (gfx1151 harness: state bitwise equal; 44.5 -> 39.1 us at 1 row, 47.4 -> 40.5 at 2, +// 53.8 -> 42.9 at 4, h_v 48). With outputs the prefetch lost (register pressure), so the window keeps the plain split. +template +__global__ void __launch_bounds__(GS_COLS * RG) gdn_state_replay_kernel(float* __restrict__ state, + const float* __restrict__ hbuf, int C, + const float* __restrict__ gate, + const float* __restrict__ beta, int h_k, + int h_v, int T, const int32_t* __restrict__ n_keep) { + __shared__ float sk[S], sq[S]; + __shared__ float red[RG][GS_COLS]; + const int head = blockIdx.x; + const int c0 = blockIdx.y * GS_COLS; + const int lc = threadIdx.x; + const int col = c0 + lc; + const int rg = threadIdx.y; + const int tid = rg * GS_COLS + lc; + const int qh = head % h_k; + const int qk = S * h_k; + const int n = n_keep ? *n_keep : T; + float gv[MAXT], bv[MAXT], vv[MAXT]; +#pragma unroll + for (int t = 0; t < MAXT; ++t) { + if (t < n) { + gv[t] = gate[(size_t) t * h_v + head]; + bv[t] = beta[(size_t) t * h_v + head]; + vv[t] = hbuf[(size_t) t * C + 2 * qk + head * S + col]; + } + } + float kn = 0.0f, qn = 0.0f; + if (n > 0) { kn = hbuf[qk + qh * S + tid]; qn = hbuf[qh * S + tid]; } + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; +#pragma unroll + for (int t = 0; t < MAXT; ++t) { + if (t >= n) break; + __syncthreads(); + sk[tid] = kn; sq[tid] = qn; + __syncthreads(); + if (t + 1 < n) { + const float* hn = hbuf + (size_t) (t + 1) * C; + kn = hn[qk + qh * S + tid]; qn = hn[qh * S + tid]; + } + const float g = __expf(gv[t]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][lc] = kv; + __syncthreads(); + const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]; + const float delta = (vv[t] - g * kv_col) * bv[t]; + float o = 0.0f; // unused: kept because the measured code had it (without it: 51 us instead of 39 at 1 row) +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + (void) o; + } + if (n_keep != nullptr && n > 0) { +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; + } +} +// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token: gdn_step_norm_multi_kernel's tail with its +// code shape (S x RG threads; rg 0 holds oc, the other row groups contribute 0 to wsum), reading oc from y +template +__global__ void __launch_bounds__(S * RG) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, int h_v, int T, + const int32_t* __restrict__ n_keep, int t_out_begin, + GdnQ81* __restrict__ xq) { + __shared__ float wsum[S * RG / 32]; + const int head = blockIdx.x, t = blockIdx.y + t_out_begin, col = threadIdx.x, rg = threadIdx.y; + const int tid = rg * S + col; + const int n = n_keep ? *n_keep : T; + if (t >= n) return; + const int value_dim = S * h_v; + float oc = 0.0f, sq_part = 0.0f; + if (rg == 0) { + oc = y[(size_t) t * value_dim + head * S + col]; + sq_part = oc * oc; + } + for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); + if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; + __syncthreads(); + if (rg == 0) { + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[(size_t) t * value_dim + head * S + col]; + if constexpr (Q) { + const float yv = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + y[(size_t) t * value_dim + head * S + col] = yv; + gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv); + } else { + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } + } +} + __global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, const float* __restrict__ offsets, const int32_t* __restrict__ tokens, int64_t n, int code_bits, int code_bias, int group_elems, @@ -472,12 +671,31 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, - const int32_t* n_keep, void* stream, int t_out_begin) { + const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) { + GdnQ81* const xq = static_cast(xq_out); // S26: non-null = also the outputs' q8_1 (STRATA_QFUSE) if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 || n_tok > kVerifyMaxT) { std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n"); std::exit(1); } + static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }(); + // S26: the split runs where it is faster (gfx1151 harness, h_v 48: the commit 8-19% per call; a window of 2+ rows + // 3-13%; one row: no gain, the old kernel stays) - bitwise equal in every case + if (split && (t_out_begin >= n_tok || n_tok - t_out_begin >= 2)) { + const dim3 grid((unsigned) h_v, S / GS_COLS), block(GS_COLS, RG); + if (t_out_begin >= n_tok) { // no outputs (the commit): the state only + gdn_state_replay_kernel<<>>( + state, h, conv_channels, gate, beta, h_k, h_v, n_tok, n_keep); + } else { + gdn_step_split_kernel<<>>( + state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin); + const dim3 ng((unsigned) h_v, (unsigned) (n_tok - t_out_begin)); + if (xq) gdn_out_norm_kernel<<>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, xq); + else gdn_out_norm_kernel<<>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, nullptr); + } + check("gdn_step_norm_multi (split)"); + return; + } static const bool commit_split = [] { const char* e = std::getenv("STRATA_GDN_COMMIT_SPLIT"); return !e || e[0] != '0'; @@ -485,10 +703,15 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const if (commit_split && n_keep != nullptr && t_out_begin >= n_tok) { gdn_step_commit_kernel<<>>( state, h, conv_channels, gate, beta, h_k, h_v, n_keep); - } else { - gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( - state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin); + check("gdn_step_commit"); + return; } + if (xq && t_out_begin < n_tok) + gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( + state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, xq); + else + gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( + state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, nullptr); check("gdn_step_norm_multi"); } @@ -592,6 +815,71 @@ __global__ void __launch_bounds__(kResidentPlanMax) resident_plan_kernel(const i } } } +// The same plan in one block of 128 threads (n <= 128): thread i owns entry i. Groups are the distinct experts in +// order of first occurrence; group g's entries are its occurrences in increasing i - exactly the loop above +// (S26: the one-thread loop took ~44 us per call on gfx1151, 48 per window). +__global__ void resident_plan_par_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, + int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, + long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, + uint32_t ring) { + __shared__ int32_t s_id[128]; + __shared__ int s_first[128], s_size[128]; + __shared__ int s_bad; + const int i = threadIdx.x; + if (i == 0) s_bad = 0; + __syncthreads(); + int32_t e = -1; + if (i < n) { + e = ids[i]; + s_id[i] = e; + if (e < 0 || e >= n_expert || res[e] < 0) s_bad = 1; + } + __syncthreads(); + if (s_bad) { if (i == 0) *skip = 0; return; } + int first = i, rank = 0, size = 0; + if (i < n) { + for (int j = 0; j < n; ++j) { + const bool same = s_id[j] == e; + if (same && j < first) first = j; + if (same && j < i) ++rank; + size += same; + } + } + if (i < n) { s_first[i] = first; s_size[i] = size; } + __syncthreads(); + int32_t* counts = pl; + int32_t* start = pl + 4; + int32_t* dst = start + capx + 1; + int32_t* tok = dst + capx; + const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll; + unsigned long long* ptr = (unsigned long long*) (pl + ptr_off); + int32_t* start2 = pl + ptr_off + 4 * capx; + if (i < n) { + // group of entry i = the number of first occurrences before `first`; its start = their sizes' sum + int group = 0, gstart = 0; + for (int j = 0; j < first; ++j) + if (s_first[j] == j) { ++group; gstart += s_size[j]; } + if (i == first) { + const int32_t slot = res[e]; + ptr[group] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); + start[group] = gstart; + } + dst[gstart + rank] = i; + tok[gstart + rank] = i / k; + if (i == 0) { + int groups = 0; + for (int j = 0; j < n; ++j) groups += s_first[j] == j; + start[groups] = n; + start2[0] = n; + counts[0] = groups; + counts[1] = n; + counts[2] = 0; + } + } + __threadfence(); + __syncthreads(); + if (i == 0) *skip = ring; +} __global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) { if (*skip == value) return; while (*flag < value) strata_spin_pause(); diff --git a/src/kernels/gr_parity.cpp b/src/kernels/gr_parity.cpp index b5ceb76c..ce119678 100644 --- a/src/kernels/gr_parity.cpp +++ b/src/kernels/gr_parity.cpp @@ -21,6 +21,7 @@ // Asserted as a property, not as a value, because that is what the source comment claims. #include "strata/kernels/gr.hpp" #include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/native_mmvq.hpp" #include @@ -405,6 +406,54 @@ int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const ui ++bad; } + + // S26 STRATA_QFUSE: the read's own q8_1 image of `mixed` must be the bytes native_quantize_q8_1 writes from it - + // for every T (1..8), directly and through a captured graph replayed twice (the group counters must reset) + { + uint8_t *d_q = nullptr, *d_ref = nullptr; + unsigned* d_cnt = nullptr; + const size_t qbytes = (size_t) T * (N / 32) * 36; + check(cudaMalloc(&d_q, qbytes), "qfuse q8"); + check(cudaMalloc(&d_ref, qbytes), "qfuse ref"); + check(cudaMalloc(&d_cnt, (N / 32) * sizeof(unsigned)), "qfuse counters"); + check(cudaMemset(d_cnt, 0, (N / 32) * sizeof(unsigned)), "qfuse counters zero"); + int qbad = 0; + std::vector hq(qbytes), hr(qbytes); + for (int tt = 1; tt <= T && !qbad; ++tt) { + std::vector qa(args.begin(), args.begin() + tt); + for (int t = 0; t < tt; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = d_cnt; } + for (int rep = 0; rep < 3 && !qbad; ++rep) { + check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "qfuse poison"); + bool wrote = false; + cudaGraph_t qg = nullptr; + cudaGraphExec_t qx = nullptr; + if (rep == 0) { + wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream); + } else { // a captured read, replayed (twice: rep 1 and 2 use fresh captures, each replayed twice) + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "qfuse begin"); + wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream); + check(cudaStreamEndCapture(stream, &qg), "qfuse end"); + check(cudaGraphInstantiate(&qx, qg, nullptr, nullptr, 0), "qfuse instantiate"); + check(cudaGraphLaunch(qx, stream), "qfuse replay 1"); + check(cudaMemsetAsync(d_q, 0x5a, qbytes, stream), "qfuse poison 2"); + check(cudaGraphLaunch(qx, stream), "qfuse replay 2"); + } + strata::kernels::native_quantize_q8_1(d_mixed, d_ref, N, tt, stream); + check(cudaStreamSynchronize(stream), "qfuse sync"); + if (qx) { cudaGraphExecDestroy(qx); cudaGraphDestroy(qg); } + if (v3) { std::printf(" QFUSE: the v3 read writes no q8_1 (%s)\n", wrote ? "WRONG: it says it did" : "ok"); qbad += wrote; break; } + check(cudaMemcpy(hq.data(), d_q, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "qfuse read"); + check(cudaMemcpy(hr.data(), d_ref, (size_t) tt * (N / 32) * 36, cudaMemcpyDeviceToHost), "qfuse ref read"); + if (!wrote || std::memcmp(hq.data(), hr.data(), (size_t) tt * (N / 32) * 36) != 0) { + std::printf(" QFUSE: T=%d rep %d: %s\n", tt, rep, wrote ? "q8_1 bytes differ" : "not written"); + ++qbad; + } + } + } + std::printf(" fused GR read + q8_1 (STRATA_QFUSE), T 1..8, direct and graph replays: %s\n", qbad ? "FAIL" : "pass"); + bad += qbad; + cudaFree(d_q); cudaFree(d_ref); cudaFree(d_cnt); + } std::printf(" fused GR multi max-T=8 LDS launch and changing graph replay %s\n", bad == 0 ? "pass" : "FAIL"); check(cudaGraphExecDestroy(graph_exec), "multi graph exec destroy"); diff --git a/src/kernels/qsa_prompt_attn_parity.cpp b/src/kernels/qsa_prompt_attn_parity.cpp index 4a0921db..3c8867c5 100644 --- a/src/kernels/qsa_prompt_attn_parity.cpp +++ b/src/kernels/qsa_prompt_attn_parity.cpp @@ -125,6 +125,62 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 std::sort(v.begin(), v.end()); std::copy(v.begin(), v.end(), sel); } + // QA_SAME=1 (S23 probe): every query reads the same first-w cells - the best case of any K/V sharing between queries + // (all loads hit the caches); QA_SAME=2: query i reads a window of w cells at i / 4 * 64 (neighbours share ~90%) + if (const char* sm = std::getenv("QA_SAME")) { + const int mode = std::atoi(sm); + for (int64_t i = 0; i < nq; ++i) { + const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1; + if (w == nkv) continue; + if (mode == 3 || mode == 4) { // 3: w random cells per query (no overlap beyond chance); 4: a 4-query group shares + // one random set of w - 512 cells (the union of 4 queries = 1x), the last 512 cells recent + std::mt19937 r3((unsigned) (mode == 3 ? i : i / 4) * 2654435761u + 7); + std::vector all((size_t) (nkv - 512)); + for (int64_t c = 0; c < nkv - 512; ++c) all[c] = (int32_t) c; + std::shuffle(all.begin(), all.end(), r3); + std::vector v(all.begin(), all.begin() + (w - 512)); + for (int64_t c = nkv - 512; c < nkv; ++c) v.push_back((int32_t) c); + std::sort(v.begin(), v.end()); + std::copy(v.begin(), v.end(), ids.data() + i * cap); + continue; + } + const int64_t base = mode == 1 ? 0 : std::min(i / 4 * 64, nkv - w); + for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c); + } + } + // QA_DUMP= QA_LAYER=n (S23 probe): the engine's own selections (STRATA_QSA_DUMP records {layer, pos0, T, cap} + + // T*cap cells): the last record of that layer, whose T must be nq and pos0 + T ctx + if (const char* df = std::getenv("QA_DUMP")) { + const int want = std::getenv("QA_LAYER") ? std::atoi(std::getenv("QA_LAYER")) : 3; + std::FILE* f = std::fopen(df, "rb"); + if (!f) { std::fprintf(stderr, "QA_DUMP: cannot open\n"); std::exit(2); } + int32_t h[4]; + long at = -1; + while (std::fread(h, 4, 4, f) == 4) { + const long data = std::ftell(f); + if (h[0] == want && h[2] == nq && h[1] + h[2] == ctx && h[3] == cap) at = data; + std::fseek(f, (long) h[2] * h[3] * 4, SEEK_CUR); + } + if (at < 0) { std::fprintf(stderr, "QA_DUMP: no record for layer %d, T %lld, ctx %lld\n", want, (long long) nq, (long long) ctx); std::exit(2); } + std::fseek(f, at, SEEK_SET); + if (std::fread(ids.data(), 4, ids.size(), f) != ids.size()) std::exit(2); + std::fclose(f); + for (int grp : {2, 4, 8, 16}) { // the union of `grp` neighbouring queries' cells against grp x the width + double su = 0, sw = 0; + for (int64_t i0 = 0; i0 + grp <= nq; i0 += grp * 16) { + std::vector u; + for (int g2 = 0; g2 < grp; ++g2) { + const int64_t w = steps[(i0 + g2) * k::kStepCount + k::kStepWidth]; + u.insert(u.end(), ids.begin() + (i0 + g2) * cap, ids.begin() + (i0 + g2) * cap + w); + sw += (double) w; + } + std::sort(u.begin(), u.end()); + su += (double) (std::unique(u.begin(), u.end()) - u.begin()); + } + std::printf("QA_DUMP overlap: %d-query groups read %.2fx the cells of one query (%.1f%% of %d x)\n", grp, + su * grp / sw, 100.0 * su / sw, grp); + } + } k::QsaAttnPools pl; if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); } else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); } @@ -165,6 +221,11 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 std::vector o((size_t) (nq * NH * HD)), nw(o.size()); ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down"); ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down"); + { // a hash of the new kernel's output bits (bitwise A/B of two builds / switches) + uint64_t hh = 1469598103934665603ull; + for (float x : nw) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; } + std::printf("NEWHASH %016llx\n", (unsigned long long) hh); + } // 1. FP64 reference on a sample of queries double err_old = 0, err_new = 0, ref_scale = 0; for (int64_t i = 0; i < nq; i += std::max(1, nq / 16)) { @@ -246,8 +307,8 @@ int main(int argc, char** argv) { int dev = 0; hipDeviceProp_t prop{}; if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2; - if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) { - std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName); + if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0 && std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) { + std::printf("SKIP: %s is not gfx11 / gfx12 (the matrix-core prompt attention)\n", prop.gcnArchName); return 77; } #if defined(_WIN32) diff --git a/src/prefill/gemm.cu b/src/prefill/gemm.cu index a35daeb2..8377ae38 100644 --- a/src/prefill/gemm.cu +++ b/src/prefill/gemm.cu @@ -2,6 +2,10 @@ #include "strata/prefill/gemm.hpp" #include "strata/kernels/dequant_bf16.hpp" +#ifdef STRATA_USE_HIP +#include "wmma_gemm.h" +#endif + #include #include #include @@ -127,7 +131,7 @@ struct HipLtDescriptors { if (c) hipblasLtMatrixLayoutDestroy(c); } - bool init(hipDataType type, int t, int n, int k, int ldy) { + bool init(hipDataType type, int t, int n, int k, int ldy, int ldb = 0) { const hipblasOperation_t trans_a = HIPBLAS_OP_T; const hipblasOperation_t trans_b = HIPBLAS_OP_N; if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS || @@ -136,7 +140,7 @@ struct HipLtDescriptors { hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) != HIPBLAS_STATUS_SUCCESS || hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS || - hipblasLtMatrixLayoutCreate(&b, type, k, t, k) != HIPBLAS_STATUS_SUCCESS || + hipblasLtMatrixLayoutCreate(&b, type, k, t, ldb > k ? ldb : k) != HIPBLAS_STATUS_SUCCESS || hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) { return false; } @@ -243,9 +247,20 @@ HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipbl return state.cache.emplace(key, resolved).first->second; } +// the hipBLASLt solution index the tuning table gives this call (-1: none / unsupported) +int hipblaslt_solution_for(void* opaque_state, strata::prefill::hipblaslt::InputType type, int64_t t, int64_t n, int64_t k, + int64_t ldy, float beta) { + auto* state = static_cast(opaque_state); + if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) return -1; + const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta); + if (!resolved.supported || resolved.workspace_bytes > state->workspace_bytes) return -1; + auto algo = resolved.algo; + return hipblaslt_ext::getIndexFromAlgo(algo); +} + bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x, const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta, - void* stream) { + void* stream, int64_t ldx = 0) { auto* state = static_cast(opaque_state); if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || ldy < n) { @@ -269,7 +284,7 @@ bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType typ HipLtDescriptors desc; const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F; - if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy)) return false; + if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy, (int) ldx)) return false; const float alpha = 1.0f; const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y, desc.c, y, desc.c, &resolved.algo, state->workspace, @@ -460,15 +475,37 @@ bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-by constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32) } // namespace #endif +bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) { +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + if (!hipblaslt_state_ || N != 320 || K != 10240 || T < 1) return false; + const int id = hipblaslt_solution_for(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, T, N, K, N, 0.0f); + if (id != 1176 && id != 1177) return false; + return strata_pf_hcdown_exact_bf16(X, ldx, W, Y, T, N, K, stream_); +#else + (void) X; (void) ldx; (void) W; (void) Y; (void) T; (void) N; (void) K; + return false; +#endif +} void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, - float beta) { + float beta, int64_t ldx) { if (T <= 0 || N <= 0) return; if (ldy <= 0) ldy = N; + if (ldx <= K) ldx = 0; +#ifdef STRATA_USE_HIP + // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before + // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through + static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); + static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }(); + if (wmma_on && bf16_on && ldx == 0 && T >= 16 && (beta == 0.0f || beta == 1.0f) && + strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) { + return; + } +#endif const float alpha = 1.0f; #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy, - beta, stream_)) { + beta, stream_, ldx)) { STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16"); return; } @@ -510,7 +547,7 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64 #endif // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T]. ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, - CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, + CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) (ldx ? ldx : K), &beta, Y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), "cublasGemmEx"); STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx"); @@ -520,6 +557,17 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ float beta) { if (T <= 0 || N <= 0) return; if (ldy <= 0) ldy = N; +#ifdef STRATA_USE_HIP + // #313 (opt-in STRATA_WMMA_GEMM=1): RDNA3 / RDNA3.5 WMMA dense GEMM, before hipBLASLt (falls through when false) + static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }(); + static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }(); + static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }(); + if (pf_on && T >= pf_min_t && strata_pf_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) return; // S23: opt-in + if (wmma_on && T >= 16 && (beta == 0.0f || beta == 1.0f) && + strata_wmma_gemm_f16(X, W, Y, T, N, K, ldy, beta, stream_)) { + return; + } +#endif const float alpha = 1.0f; #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy, @@ -536,7 +584,40 @@ void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_ } void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, - int64_t ldy, float beta) { + int64_t ldy, float beta, int64_t ldx) { +#ifdef STRATA_USE_HIP + // S23 (opt-in STRATA_PF_PAD=1, with STRATA_PF_GEMM=1 on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the weight + // dequantized into the scratch with row stride K + 64 halves, so no 4 KB-multiple stride camps on the memory + // channels (gemm_probe8: K 6144 19 -> 29 TFLOPS from W alone, 35 with X padded too). Bitwise the same products. + static const bool pad_on = [] { const char* v = std::getenv("STRATA_PF_PAD"); return v && v[0] == '1'; }(); + static const bool pf_on = [] { const char* v = std::getenv("STRATA_PF_GEMM"); return v && v[0] == '1'; }(); + static const int64_t pf_min_t = [] { const char* v = std::getenv("STRATA_PF_SWITCH_MIN_T"); return v ? (int64_t) std::atoll(v) : (int64_t) 0; }(); + if (pad_on && pf_on && T >= pf_min_t && T >= 64 && N >= 512 && K % 32 == 0 && N * (K + 64) <= scratch_elems_) { + const int64_t ldw = K + 64; + if (strata::kernels::dequant_f16_ld(ggml_type, W_blocks, 0, N, K, ldw, scratch_, stream_) && + strata_pf_gemm_f16_ld(X, ldx > 0 ? ldx : K, scratch_, ldw, Y, T, N, K, ldy, beta, stream_)) { + return; + } + } +#endif + if (ldx > 0 && ldx != K) { +#ifdef STRATA_USE_HIP + // X arrived padded but the weight cannot be (an i-quant without a strided dequant, or the scratch is too + // small for N x (K + 64)): the weight unpadded, X read at its stride - the same products, the same bits + const int64_t rows = scratch_elems_ / K; + bool ok = rows > 0; + if (ldy <= 0) ldy = N; + for (int64_t r0 = 0; ok && r0 < N; r0 += rows) { + const int64_t n = (N - r0 < rows) ? N - r0 : rows; + strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_); + ok = strata_pf_gemm_f16_ld(X, ldx, scratch_, K, Y + r0, T, n, K, ldy, beta, stream_); + } + if (ok) return; +#endif + std::fprintf(stderr, "prefill gemm: a padded X (ldx %lld, K %lld) needs STRATA_PF_PAD's path\n", + (long long) ldx, (long long) K); + std::exit(1); + } if (N * K > scratch_elems_) { // Too large for the scratch at once: in row slices. const int64_t rows = scratch_elems_ / K; diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 4ad67b1a..38586df6 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -7,10 +7,12 @@ #include #include +#include #include #include #include #include +#include namespace strata::prefill { namespace { @@ -84,11 +86,12 @@ __global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restr // so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { + uint16_t* __restrict__ xn16_lo, int64_t ldx) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int c = (int) (row % HC); const float* r = R + row * N; + const int64_t xo = (row / HC) * ldx + (int64_t) c * N; // the BF16 image's row (token stride ldx) float ss = 0.0f; for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); @@ -96,8 +99,8 @@ __global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __re for (int d = threadIdx.x; d < N; d += blockDim.x) { const float v = r[d] * rs * w[c * N + d]; const uint16_t h = bf(v); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); + xn16[xo + d] = h; + if (xn16_lo) xn16_lo[xo + d] = bf_lo(v, h); } } __global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w, @@ -130,12 +133,13 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict const float* __restrict__ inj, int64_t inj_ld, const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, - uint16_t* __restrict__ xn16_lo) { + uint16_t* __restrict__ xn16_lo, int64_t ldx) { __shared__ float sh[32]; const int64_t row = blockIdx.x; // t * 4 + c const int64_t t = row / HC; const int c = (int) (row % HC); float* r = R + row * N; + const int64_t xo = t * ldx + (int64_t) c * N; const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC); float v[GRW_PER]; float ss = 0.0f; @@ -154,8 +158,70 @@ __global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict for (int d = threadIdx.x; d < N; d += 256, ++k) { const float x = v[k] * rs * w[c * N + d]; const uint16_t h = bf(x); - xn16[row * N + d] = h; - if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); + xn16[xo + d] = h; + if (xn16_lo) xn16_lo[xo + d] = bf_lo(x, h); + } +} +// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write, its control vector and the next half's norm in one +// pass over R (was gr_write + cvec_apply + gr_norm_rs: three). The write is gr_write_kernel's, the vector +// cvec_kernel's (the same per-thread dot order over d = tid + 256 k, the same two-level xor reduction), the norm +// gr_norm_rs_kernel's (the same ss order and block_sum): the same bits. +__global__ void __launch_bounds__(256) gr_write_cvec_norm_rs_kernel( + float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, int64_t inj_ld, + const float* __restrict__ v_l, const float* __restrict__ s_l, const int* __restrict__ on, int mode, + const float* __restrict__ w, float eps, float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo, int64_t ldx) { + __shared__ float sh[32]; + __shared__ float part[8]; + const int64_t row = blockIdx.x; // t * 4 + c + const int64_t t = row / HC; + const int c = (int) (row % HC); + float* r = R + row * N; + const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC); + const float s = *s_l; + const bool steer = *on != 0 && s != 0.0f; + float x[GRW_PER]; + float dot = 0.0f; + int k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float xv = fmaf(bo[t * N + d], sc, r[d]); + x[k] = xv; + if (steer && mode == 0) dot = fmaf(xv, v_l[d], dot); + } + if (steer && mode == 0) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot; + __syncthreads(); + if (threadIdx.x < 32) { + float p = threadIdx.x < 8 ? part[threadIdx.x] : 0.0f; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o); + if (threadIdx.x == 0) part[0] = p; + } + __syncthreads(); + dot = part[0] * s; + } + float ss = 0.0f; + k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + float xv = x[k]; + if (steer) xv = mode == 0 ? fmaf(-dot, v_l[d], xv) : xv + v_l[d]; + r[d] = xv; + x[k] = xv; + ss += xv * xv; + } + const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); + if (threadIdx.x == 0) rs_out[row] = rs; + k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float y = x[k] * rs * w[c * N + d]; + const uint16_t h = bf(y); + xn16[t * ldx + (int64_t) c * N + d] = h; + if (xn16_lo) xn16_lo[t * ldx + (int64_t) c * N + d] = bf_lo(y, h); } } __global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, @@ -250,6 +316,46 @@ __global__ void gdn_conv_tiled_kernel(const float* __restrict__ hist, const floa v0 = v1; v1 = v2; v2 = x; } } +// Aurora (S23, opt-in STRATA_GDN_CONVL2=1): gdn_conv_tiled_kernel with gdn_l2_kernel folded in. A block's 128 threads +// are the 128 channels of one head, so for the q / k heads (block < 2 HK) the norm's sum of squares is the block's: +// the same warp_sum, the same four partials added in the same order, the same v * rsqrtf(ss + eps) on the same +// stored value - the same bits, without writing h and reading it back (16 tokens per round). +__global__ void gdn_conv_l2_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ w, float* __restrict__ h, int64_t T, float eps) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE; + if (t0 >= T) return; + const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T; + auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; }; + float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1); + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + for (int64_t t = t0; t < t1; ++t) { // gdn_conv_tiled_kernel's loop, verbatim + const float x = qkv[t * C + c]; + const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + h[t * C + c] = s / (1.0f + __expf(-s)); + v0 = v1; v1 = v2; v2 = x; + } + if (blockIdx.x >= 2 * HK) return; // v channels: no norm + __shared__ float part[16][4]; + for (int64_t tb = t0; tb < t1; tb += 16) { + const int n = (int) (t1 - tb < 16 ? t1 - tb : 16); + for (int j = 0; j < n; ++j) { // (each thread reads back its own stored value) + const float v = h[(tb + j) * C + c]; + // gdn_l2_kernel as the compiler built it: the first xor step adds the partner's rounded square to an + // unrounded own one (an fma), the other steps are plain adds - spelled out so no contraction can differ + float sq = __fmaf_rn(v, v, __shfl_xor_sync(0xffffffffu, __fmul_rn(v, v), 16)); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) sq = __fadd_rn(sq, __shfl_xor_sync(0xffffffffu, sq, o)); + if ((threadIdx.x & 31) == 0) part[j][threadIdx.x >> 5] = sq; + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + const float ss = part[j][0] + part[j][1] + part[j][2] + part[j][3]; + h[(tb + j) * C + c] = h[(tb + j) * C + c] * rsqrtf(ss + eps); + } + __syncthreads(); + } +} // the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3) __global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int64_t T) { const int c = blockIdx.x * blockDim.x + threadIdx.x; @@ -279,7 +385,8 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta const float* __restrict__ gate, const float* __restrict__ beta, const float* __restrict__ z, const float* __restrict__ gamma, float eps, - float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T) { + float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T, + int64_t ld16) { __shared__ float sk[S], sq[S], red[RG][S], wsum[16]; const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; const int qh = head % HK; @@ -323,7 +430,7 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(z[t * HV * S + head * S + col]); y[t * HV * S + head * S + col] = v; - y16[t * HV * S + head * S + col] = hf(v); + y16[t * ld16 + head * S + col] = hf(v); } } #pragma unroll @@ -595,11 +702,417 @@ bool gdn_keyhead_ok() { return known[dev] == 1; } #endif -// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the -// norm stays in its scratch buffer) +#if defined(__HIPCC__) // the Aurora (gfx11) recurrence kernels: AMD builds only +// Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value +// head) but FOUR LANES per column, lane g holding the column's state rows 32g .. 32g + 31 in registers - exactly the +// row group the old kernel's thread (col, rg = g) held - so a token needs no __syncthreads: the four kv / o partials +// meet through wave shuffles and are added in the old order red[0] + red[1] + red[2] + red[3] (the same bits; +// tests/hip/gdn_rec_head.cpp). The q/k rows, v, gate and beta are staged in LDS HT tokens at a time, the next chunk +// loaded into registers while this one computes, and a token's k and q rows are read into registers before its +// products (one LDS latency per token, not one per load). The old kernels took ~4 barriers per token and ~3.5 us +// per token and layer on the Radeon 8060S; the output norm runs after it in gdn_out_norm_warp_kernel. +// STRATA_GDN_HEAD=0: the old kernels. +constexpr int HT = 4; // tokens per staged chunk (LDS ~10 KB: all 192 blocks resident) +constexpr int QCB = 32; // columns per block +constexpr int QTH = QCB * 4; // threads per block: 4 lanes per column +constexpr int QRS = 36; // staged row-group stride (32 rows + 4 pad: the 4 groups' reads + // land in different LDS banks) +constexpr int QPF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2) +__global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)] + __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token] + __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v + const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head + const int qh = head % HK; + float s[32]; + { + const float* base = state + ((size_t) (g * 32) * HV + head) * S + col; +#pragma unroll + for (int r = 0; r < 32; ++r) s[r] = base[(size_t) r * HV * S]; + } + float4 pf[QPF]; + float pv[HT], pgb = 0.0f; + // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of + // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT` + auto fetch = [&](int64_t c) { + const int64_t t0 = c * HT; +#pragma unroll + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int64_t t = t0 + tt; + pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + const int64_t t = t0 + tt; + pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f; + } + } + if (tid < 2 * HT) { + const int64_t t = t0 + (tid % HT); + pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f; + } + }; + const float rs_s = rsqrtf((float) S); + const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j + const int64_t nch = (T + HT - 1) / HT; + if (nch > 0) fetch(0); + for (int64_t c = 0; c < nch; ++c) { + const int b = (int) (c & 1); + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt]; + } +#pragma unroll + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int row = r4 * 4; + *reinterpret_cast(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u]; + } + if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; + __syncthreads(); // chunk c staged (buffer b was last read two chunks ago) + if (c + 1 < nch) fetch(c + 1); + const int64_t t0 = c * HT; + const int nt = (int) (T - t0 < HT ? T - t0 : HT); + for (int tt = 0; tt < nt; ++tt) { + float k[32], q[32]; + { + const float4* k4 = reinterpret_cast(&sqk[b][tt][1][g * QRS]); + const float4* q4 = reinterpret_cast(&sqk[b][tt][0][g * QRS]); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float4 kk = k4[j], qq = q4[j]; + k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w; + q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w; + } + } + const float g_exp = __expf(sgb[b][0][tt]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) kv = fmaf(s[r], k[r], kv); + const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8), + p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24); + const float kv_col = p0 + p1 + p2 + p3; + const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt]; + const float delta = (cvt - g_exp * kv_col) * cbt; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { + s[r] = fmaf(g_exp, s[r], k[r] * delta); + o = fmaf(s[r], q[r], o); + } + const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8), + o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24); + if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s; + } + } + { + float* base = state + ((size_t) (g * 32) * HV + head) * S + col; +#pragma unroll + for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r]; + } +} +// Aurora (S23, opt-in STRATA_GDN_PP=1): gdn_rec_quad_kernel with the same arithmetic in the same order, two changes in +// how it is compiled. (1) The VGPR count: the 32 state-row addresses of the first loads were kept live across the +// whole walk to be reused by the final stores (64 VGPRs, 196 in all = 7 waves a SIMD for the 192 blocks of 4 waves +// that need 9.6): the stores' lane offset goes through an asm so the addresses are made again, 133 VGPRs, all blocks +// resident. (2) A full chunk's four tokens run with the state alternating between two register sets (the update +// writes the other set), so the compiler emits no 32 register copies after the update. +__global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)] + __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token] + __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v + const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head + const int qh = head % HK; + float s[32]; + { + const float* sb = state + (size_t) head * S; + const uint32_t voff = (uint32_t) ((g * 32) * HV * S + col); +#pragma unroll + for (int r = 0; r < 32; ++r) s[r] = sb[(size_t) r * HV * S + voff]; + } + float4 pf[QPF]; + float pv[HT], pgb = 0.0f; + // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of + // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT` + auto fetch = [&](int64_t c) { + const int64_t t0 = c * HT; +#pragma unroll + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int64_t t = t0 + tt; + pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + const int64_t t = t0 + tt; + pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f; + } + } + if (tid < 2 * HT) { + const int64_t t = t0 + (tid % HT); + pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f; + } + }; + const float rs_s = rsqrtf((float) S); + const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j + const int64_t nch = (T + HT - 1) / HT; + if (nch > 0) fetch(0); + for (int64_t c = 0; c < nch; ++c) { + const int b = (int) (c & 1); + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt]; + } +#pragma unroll + for (int u = 0; u < QPF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int row = r4 * 4; + *reinterpret_cast(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u]; + } + if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; + __syncthreads(); // chunk c staged (buffer b was last read two chunks ago) + if (c + 1 < nch) fetch(c + 1); + const int64_t t0 = c * HT; + const int nt = (int) (T - t0 < HT ? T - t0 : HT); + auto token = [&](int tt, float (&sin)[32], float (&sout)[32]) { + float k[32], q[32]; + { + const float4* k4 = reinterpret_cast(&sqk[b][tt][1][g * QRS]); + const float4* q4 = reinterpret_cast(&sqk[b][tt][0][g * QRS]); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float4 kk = k4[j], qq = q4[j]; + k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w; + q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w; + } + } + const float g_exp = __expf(sgb[b][0][tt]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) kv = fmaf(sin[r], k[r], kv); + const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8), + p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24); + const float kv_col = p0 + p1 + p2 + p3; + const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt]; + const float delta = (cvt - g_exp * kv_col) * cbt; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { + sout[r] = fmaf(g_exp, sin[r], k[r] * delta); + o = fmaf(sout[r], q[r], o); + } + const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8), + o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24); + if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s; + }; + if (nt == HT) { // the state alternates between two register sets: no copy after the update + float s2[32]; + token(0, s, s2); + token(1, s2, s); + token(2, s, s2); + token(3, s2, s); + } else { + for (int tt = 0; tt < nt; ++tt) { + float s2[32]; + token(tt, s, s2); +#pragma unroll + for (int r = 0; r < 32; ++r) s[r] = s2[r]; + } + } + } + { + float* sb = state + (size_t) head * S; + uint32_t voff = (uint32_t) ((g * 32) * HV * S + col); + asm volatile("" : "+v"(voff)); // (so the loads' 32 addresses are not kept alive across the whole loop) +#pragma unroll + for (int r = 0; r < 32; ++r) sb[(size_t) r * HV * S + voff] = s[r]; + } +} + +// Aurora (S23, opt-in STRATA_GDN_PP=2): gdn_rec_quad_kernel with two columns per lane (a wave: 4 row groups x 8 lanes x +// 2 columns = 16 columns; a block of 4 waves 64 columns, 96 blocks). A lane's two columns share the k / q rows it +// reads from shared memory (half the LDS reads and shuffles per column, the kernel's limit) and give each wave two +// independent dependency chains; the 384 waves fit in one round at 230 VGPRs. Per column the same arithmetic in +// the same order (the same bits as gdn_rec_quad_kernel). The store of the state goes through an asm for the reason +// given at gdn_rec_quad_pp_kernel. + +// ---- C2: two columns per lane (a wave: 4 row groups x 8 lanes x 2 columns = 16 columns; a block of 4 waves 64 +// columns). A lane's two columns share the k / q rows it reads from LDS (half the LDS reads and shuffles per column +// and two independent dependency chains in each wave). Per column the same arithmetic in the same order. +constexpr int C2CB = 64; // columns per block +constexpr int C2PF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2) +__global__ void __launch_bounds__(QTH) gdn_rec_quad2c_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; + __shared__ float sgb[2][2][HT]; + __shared__ float sv[2][HT][C2CB]; + const int head = blockIdx.x / (S / C2CB), cb = blockIdx.x % (S / C2CB); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int g = lane >> 3, cl0 = wave * 16 + (lane & 7), cl1 = cl0 + 8; // the lane's two columns in the block + const int col0 = cb * C2CB + cl0, col1 = cb * C2CB + cl1; + const int qh = head % HK; + float s0[32], s1[32]; + { + const float* sb = state + (size_t) head * S; + const uint32_t voff = (uint32_t) ((g * 32) * HV * S); +#pragma unroll + for (int r = 0; r < 32; ++r) { s0[r] = sb[(size_t) r * HV * S + voff + col0]; s1[r] = sb[(size_t) r * HV * S + voff + col1]; } + } + float4 pf[C2PF]; + float pv[2][HT], pgb = 0.0f; + auto fetch = [&](int64_t c) { + const int64_t t0 = c * HT; +#pragma unroll + for (int u = 0; u < C2PF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int64_t t = t0 + tt; + pf[u] = t < T ? *reinterpret_cast(h + t * C + part * HK * S + qh * S + r4 * 4) + : make_float4(0.f, 0.f, 0.f, 0.f); + } + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { + const int64_t t = t0 + tt; + pv[0][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col0] : 0.0f; + pv[1][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col1] : 0.0f; + } + } + if (tid < 2 * HT) { + const int64_t t = t0 + (tid % HT); + pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f; + } + }; + const float rs_s = rsqrtf((float) S); + const int src0 = lane & 7; + const int64_t nch = (T + HT - 1) / HT; + if (nch > 0) fetch(0); + for (int64_t c = 0; c < nch; ++c) { + const int b = (int) (c & 1); + if (g == 0) { +#pragma unroll + for (int tt = 0; tt < HT; ++tt) { sv[b][tt][cl0] = pv[0][tt]; sv[b][tt][cl1] = pv[1][tt]; } + } +#pragma unroll + for (int u = 0; u < C2PF; ++u) { + const int i = tid + u * QTH; + const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4); + const int row = r4 * 4; + *reinterpret_cast(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u]; + } + if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb; + __syncthreads(); + if (c + 1 < nch) fetch(c + 1); + const int64_t t0 = c * HT; + const int nt = (int) (T - t0 < HT ? T - t0 : HT); + for (int tt = 0; tt < nt; ++tt) { + float k[32], q[32]; + { + const float4* k4 = reinterpret_cast(&sqk[b][tt][1][g * QRS]); + const float4* q4 = reinterpret_cast(&sqk[b][tt][0][g * QRS]); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float4 kk = k4[j], qq = q4[j]; + k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w; + q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w; + } + } + const float g_exp = __expf(sgb[b][0][tt]); + float kv0 = 0.0f, kv1 = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { kv0 = fmaf(s0[r], k[r], kv0); kv1 = fmaf(s1[r], k[r], kv1); } + const float a0 = __shfl_sync(0xffffffffu, kv0, src0), a1 = __shfl_sync(0xffffffffu, kv0, src0 + 8), + a2 = __shfl_sync(0xffffffffu, kv0, src0 + 16), a3 = __shfl_sync(0xffffffffu, kv0, src0 + 24); + const float b0 = __shfl_sync(0xffffffffu, kv1, src0), b1 = __shfl_sync(0xffffffffu, kv1, src0 + 8), + b2 = __shfl_sync(0xffffffffu, kv1, src0 + 16), b3 = __shfl_sync(0xffffffffu, kv1, src0 + 24); + const float kvc0 = a0 + a1 + a2 + a3, kvc1 = b0 + b1 + b2 + b3; + const float cbt = sgb[b][1][tt]; + const float d0 = (sv[b][tt][cl0] - g_exp * kvc0) * cbt, d1 = (sv[b][tt][cl1] - g_exp * kvc1) * cbt; + float o0 = 0.0f, o1 = 0.0f; +#pragma unroll + for (int r = 0; r < 32; ++r) { + s0[r] = fmaf(g_exp, s0[r], k[r] * d0); + s1[r] = fmaf(g_exp, s1[r], k[r] * d1); + o0 = fmaf(s0[r], q[r], o0); + o1 = fmaf(s1[r], q[r], o1); + } + const float x0 = __shfl_sync(0xffffffffu, o0, src0), x1 = __shfl_sync(0xffffffffu, o0, src0 + 8), + x2 = __shfl_sync(0xffffffffu, o0, src0 + 16), x3 = __shfl_sync(0xffffffffu, o0, src0 + 24); + const float y0 = __shfl_sync(0xffffffffu, o1, src0), y1 = __shfl_sync(0xffffffffu, o1, src0 + 8), + y2 = __shfl_sync(0xffffffffu, o1, src0 + 16), y3 = __shfl_sync(0xffffffffu, o1, src0 + 24); + if (g == 0) { + oc_out[(t0 + tt) * HV * S + head * S + col0] = (x0 + x1 + x2 + x3) * rs_s; + oc_out[(t0 + tt) * HV * S + head * S + col1] = (y0 + y1 + y2 + y3) * rs_s; + } + } + } + { + float* sb = state + (size_t) head * S; + uint32_t voff = (uint32_t) ((g * 32) * HV * S); + asm volatile("" : "+v"(voff)); +#pragma unroll + for (int r = 0; r < 32; ++r) { sb[(size_t) r * HV * S + voff + col0] = s0[r]; sb[(size_t) r * HV * S + voff + col1] = s1[r]; } + } +} + +// gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread +// block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave +// per row with four values per lane rounded differently in its first xor step). +template +__global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, uint16_t* __restrict__ y16, + int64_t rows, int64_t ld16) { + __shared__ float wsum[4]; + const int col = threadIdx.x; + for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) { + const size_t at = (size_t) row * S + col; + const float oc = y[at]; + // (warp_sum as the compiler built it: the first xor step adds the partner's rounded square to an unrounded own + // one, an fma; spelled out so neither instance's contraction can differ) + float sp = __fmaf_rn(oc, oc, __shfl_xor_sync(0xffffffffu, __fmul_rn(oc, oc), 16)); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) sp = __fadd_rn(sp, __shfl_xor_sync(0xffffffffu, sp, o)); + __syncthreads(); // the previous row's sums are read + if ((col & 31) == 0) wsum[col >> 5] = sp; + __syncthreads(); + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float bp = oc * rsqrtf(ss / (float) S + eps) * gamma[col], sg = sigm(z[at]); + const size_t o16 = (size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col; + if constexpr (WY) { + const float v = bp * sg; + y[at] = v; + y16[o16] = hf(v); + } else { + // STRATA_GDN_NOY=1: nothing reads the FP32 result (403 MB per 16K chunk). The FP16 value is what the + // compiler makes of hf(v) next to the store: v_fma_mixlo_f16, the product rounded to FP16 once + unsigned r; + asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(r) : "v"(sg), "v"(bp)); + y16[o16] = (uint16_t) r; + } + } +} +#endif // __HIPCC__ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, - float eps, const float* __restrict__ y, - uint16_t* __restrict__ y16) { + float eps, float* __restrict__ y, uint16_t* __restrict__ y16, + int64_t ld16) { __shared__ float wsum[4]; const int64_t t = blockIdx.x; const int head = blockIdx.y, col = threadIdx.x; @@ -610,7 +1123,7 @@ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict __syncthreads(); const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]); - y16[at] = hf(v); + y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v); // (the FP32 normalized value is not stored: nothing reads it) } // ---------------------------------------------------------------- MoE @@ -713,6 +1226,32 @@ __global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* bo[i] = s + shared[i] * sigm(sg[t]); } +// W (X5): four columns per thread, one float4 load per slot; the per-element expression and the k order are unchanged +// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16). +__global__ void moe_combine4_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, + const float* __restrict__ w, const float4* __restrict__ shared, + const float* __restrict__ sg, float4* __restrict__ bo, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // float4 index + if (i >= T * (N / 4)) return; + const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4; + float4 s = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + float4 v[10]; + float ww[10]; +#pragma unroll + for (int k = 0; k < 10; ++k) { + ww[k] = w[t * 10 + k]; + v[k] = *reinterpret_cast(Dm + (int64_t) slot[t * 10 + k] * N + d); + } +#pragma unroll + for (int k = 0; k < 10; ++k) { + s.x = fmaf(ww[k], v[k].x, s.x); s.y = fmaf(ww[k], v[k].y, s.y); + s.z = fmaf(ww[k], v[k].z, s.z); s.w = fmaf(ww[k], v[k].w, s.w); + } + const float g = sigm(sg[t]); + const float4 sh = shared[i]; + bo[i] = make_float4(s.x + sh.x * g, s.y + sh.y * g, s.z + sh.z * g, s.w + sh.w * g); +} + // ---------------------------------------------------------------- QSA helpers __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t cols, int64_t ld, float eps) { __shared__ float sh[32]; @@ -754,11 +1293,11 @@ __global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q[i] = qf[t * 24 * 512 + h * 512 + d]; } __global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16, - int64_t T) { + int64_t T, int64_t ld16) { const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i >= T * 24 * 256) return; const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256; - o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d])))); + o16[t * ld16 + h * 256 + d] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d])))); } // one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is @@ -823,6 +1362,77 @@ __global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict } } +// S23 (opt-in STRATA_HC_UPMIX=1, gfx11): the hyper-connection read's up projection with gr_mix_r as its epilogue. The +// up GEMM's FP32 output `gated` (T x 10240: 671 MB per 16K chunk) is never written or read back: a block computes a +// tile of 64 tokens x 64 columns for all 4 streams on the matrix cores (BF16 in, FP32 accumulate over K = 320; the +// lo16 and w_up tiles staged in LDS), and each lane already holds the 4 streams' values of its (token, column) - the +// mix (x_c = R * rs * w, sum of x_c * sigmoid(gated_c), / 4) runs in registers, in gr_mix_r_kernel's order. The +// GEMM sums K in another order than hipBLASLt: rounding-level, hence opt-in and quality-gated. +#if defined(__HIPCC__) +typedef __bf16 um_b16 __attribute__((ext_vector_type(16))); +typedef float um_f8 __attribute__((ext_vector_type(8))); +__device__ __forceinline__ um_f8 um_wmma(um_b16 a, um_b16 b, um_f8 c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +#else + (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate) +#endif +} +constexpr int UM_T = 128, UM_D = 16, UM_LD = LR + 8; // a block: 128 tokens x 16 columns x the 4 streams +__device__ __forceinline__ um_b16 um_frag(const uint16_t* p) { // 16 BF16 (32 bytes, 16-byte aligned) + const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(um_b16, w); +} +// The block's w_up rows (16 columns x 4 streams x all 320 k) are staged in LDS once; each wave streams its own 16 +// tokens' lo16 rows from global memory (every A fragment feeds the 4 streams' WMMAs) - one barrier per block. +__global__ void __launch_bounds__(256) gr_upmix_kernel(const uint16_t* __restrict__ lo16, const uint16_t* __restrict__ wu, + const float* __restrict__ R, const float* __restrict__ rs, + const float* __restrict__ w, float* __restrict__ mixed, + uint16_t* __restrict__ mixed16, uint16_t* __restrict__ mixed_h, + int64_t T) { + __shared__ __align__(16) uint16_t sB[HC * UM_D][UM_LD]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + // blocks ordered column-tile fastest: the blocks in flight share a token tile, so the epilogue's R reads run + // along rows (token-tile fastest scattered them over 512 rows x 40 KB per block: 28 ms instead of 3.7 at 8K) + const int64_t t0 = (int64_t) blockIdx.y * UM_T + 16 * wave; + const int d0 = blockIdx.x * UM_D; + for (int i = tid; i < HC * UM_D * (LR / 8); i += 256) { + const int rr = i / (LR / 8), q = i % (LR / 8); + const int c = rr / UM_D, dd = rr % UM_D; + *reinterpret_cast(&sB[rr][8 * q]) = *reinterpret_cast(wu + (size_t) (c * N + d0 + dd) * LR + 8 * q); + } + __syncthreads(); + if (t0 >= T) return; + const int64_t ta = t0 + l16 < T ? t0 + l16 : T - 1; + const uint16_t* arow = lo16 + ta * LR; + um_f8 acc[HC]; +#pragma unroll + for (int c = 0; c < HC; ++c) acc[c] = um_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int ks = 0; ks < LR; ks += 16) { + const um_b16 a = um_frag(arow + ks); +#pragma unroll + for (int c = 0; c < HC; ++c) acc[c] = um_wmma(a, um_frag(&sB[c * UM_D + l16][ks]), acc[c]); + } + const int d = d0 + l16; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int64_t t = t0 + 2 * i + hi; + if (t >= T) continue; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + const float x = R[t * D + c * N + d] * rs[t * HC + c] * w[c * N + d]; // gr_mix_r_kernel's order + s = fmaf(x, sigm(acc[c][i]), s); + } + s /= (float) HC; + mixed[t * N + d] = s; + if (mixed16) mixed16[t * N + d] = bf(s); + if (mixed_h) mixed_h[t * N + d] = hf(s); + } +} +#endif } // namespace void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, @@ -856,8 +1466,9 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t check("gr_norm"); } void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, - uint16_t* xn16_lo) { - gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo); + uint16_t* xn16_lo, int64_t ldx) { + gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo, + ldx > 0 ? ldx : D); check("gr_norm_rs"); } void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, @@ -866,12 +1477,40 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* mixed_h, mixed16_lo); check("gr_mix_r"); } +bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm, + float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream) { +#if defined(__HIPCC__) + static const bool gfx11 = [] { + int dev = 0; + cudaDeviceProp p; + if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false; + return std::strncmp(p.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11 || T <= 0) return false; + gr_upmix_kernel<<>>( + lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T); + check("gr_upmix"); + return true; +#else + (void) lo16; (void) w_up; (void) R; (void) rs; (void) w_norm; (void) mixed; (void) mixed16; (void) mixed_h; + (void) T; (void) stream; + return false; +#endif +} void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, - float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) { gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, - rs, xn16, xn16_lo); + rs, xn16, xn16_lo, + ldx > 0 ? ldx : D); check("gr_write_norm_rs"); } +void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l, + const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs, + uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx) { + gr_write_cvec_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>( + R, bo, inj, inj_ld, v_l, s_l, on, mode, w_norm_next, eps, rs, xn16, xn16_lo, ldx > 0 ? ldx : D); + check("gr_write_cvec_norm_rs"); +} void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { gr_silu_kernel<<>>(lo, lo16, lo16_lo, T * LR); check("gr_silu"); @@ -898,6 +1537,14 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i if (serial || T <= CONV_TILE) { gdn_conv_kernel<<>>(history, qkv, conv_w, h, T); } else { + static const bool fused = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v && std::atoi(v) != 0; }(); + if (fused) { + gdn_conv_l2_kernel<<>>(history, qkv, conv_w, h, T, eps); + gdn_conv_hist_kernel<<>>(history, qkv, T); + check("gdn_conv"); + return; + } gdn_conv_tiled_kernel<<>>(history, qkv, conv_w, h, T); gdn_conv_hist_kernel<<>>(history, qkv, T); @@ -905,11 +1552,56 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, i gdn_l2_kernel<<>>(h, eps); check("gdn_conv"); } -void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, - const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { +void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, + void* stream, int64_t ld16) { + if (ld16 <= 0) ld16 = (int64_t) HV * S; +#if defined(__HIPCC__) + if (variant == 3) { // diagnostics: the quad recurrence + the old norm kernel + if (T > 0) { + gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); + } + return; + } + if (variant == 4 || variant == 5) { // diagnostics: the quad recurrence's PP / two-column kernels + the norm + if (T > 0) { + if (variant == 5) + gdn_rec_quad2c_kernel<<>>(state, h, gate, beta, y, T); + else + gdn_rec_quad_pp_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV, ld16); + } + check("gdn_recurrence (quad pp)"); + return; + } + if (variant == 1) { + if (T > 0) { + static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }(); + if (pp == 2) + gdn_rec_quad2c_kernel<<>>(state, h, gate, beta, y, T); + else if (pp) + gdn_rec_quad_pp_kernel<<>>(state, h, gate, beta, y, T); + else + gdn_rec_quad_kernel<<>>(state, h, gate, beta, y, T); + static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }(); + if (noy) + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV, ld16); + else + gdn_out_norm_loop_kernel<<<(unsigned) std::min(T * HV, 4096), S, 0, (cudaStream_t) stream>>>( + z, gamma, eps, y, y16, T * HV, ld16); + } + check("gdn_recurrence (quad)"); + return; + } +#else + (void) variant; // the quad recurrence kernels are AMD-only +#endif static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) - if (serial || T <= 0) { - gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); + if (serial || T <= 0 || variant == 2) { + gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16); } else { static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); #if !defined(__HIPCC__) @@ -921,10 +1613,19 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); else gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); - gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16, ld16); } check("gdn_recurrence"); } +void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) { + // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp); + // STRATA_GDN_HEAD=1 (on by default on gfx1151; off with STRATA_GDN_HEAD=0 or STRATA_GDN_REC_HEADS) takes them + // (AMD builds only; the arch defaults set STRATA_GDN_HEAD=1 on gfx1151 and leave other cards on the earlier kernels) + static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }(); + static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; + gdn_recurrence_variant(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16); +} void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) { if (n_expert == 512) route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T); @@ -983,6 +1684,14 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int } void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, int64_t T, void* stream) { +#ifndef STRATA_W_NO_COMB + if (((reinterpret_cast(Dm) | reinterpret_cast(shared) | reinterpret_cast(bo)) & 15) == 0) { + moe_combine4_kernel<<>>( + Dm, slot, w, reinterpret_cast(shared), sg, reinterpret_cast(bo), T); + check("moe_combine"); + return; + } +#endif moe_combine_kernel<<>>(Dm, slot, w, shared, sg, bo, T); check("moe_combine"); } @@ -1016,8 +1725,9 @@ void split_q(const float* q_full, float* q, int64_t T, void* stream) { split_q_kernel<<>>(q_full, q, T); check("split_q"); } -void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream) { - gate_attn_kernel<<>>(attn, q_full, out16, T); +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16) { + gate_attn_kernel<<>>(attn, q_full, out16, T, + ld16 > 0 ? ld16 : 24 * 256); check("gate_attn"); } diff --git a/src/prefill/mmq_resident_sort.hpp b/src/prefill/mmq_resident_sort.hpp new file mode 100644 index 00000000..2e03856b --- /dev/null +++ b/src/prefill/mmq_resident_sort.hpp @@ -0,0 +1,59 @@ +// Host-only opt-in grouping permutation. No HIP calls, device math, or precision changes. +#pragma once + +#include +#include +#include +#include +#include + +namespace strata::prefill::detail { + +inline bool mmq_resident_sort_flag(const char* value) { + return value != nullptr && std::strcmp(value, "1") == 0; +} + +inline bool mmq_resident_sort_requested() { + static const bool on = mmq_resident_sort_flag(std::getenv("STRATA_MMQ_RESIDENT_SORT_NE")); + return on; +} + +inline bool mmq_resident_sort_eligible(bool requested, bool use_mmq, bool native_layout, bool has_cache, + const int32_t* layer_resident, int64_t n_expert, + bool stream_all, bool layer_stream_empty) { + if (!requested || !use_mmq || native_layout || !has_cache || !layer_resident || n_expert <= 0) return false; + // All experts, including unselected ones: leave every partial/streamed layer in ID order. + if (stream_all && !layer_stream_empty) return false; + for (int64_t e = 0; e < n_expert; ++e) if (layer_resident[e] < 0) return false; + return true; +} + +// Preconditions are established by the existing caller: IDs were range-checked and counted; +// order contains each positive-count expert once in ID order; off has count.size()+1 entries; +// routes fits its original int32 offsets, and slot/src each have routes writable entries. +// After sorting, off[e] is an expert-indexed START, not an ID-prefix end at off[e+1]. +inline void mmq_resident_sort_rows(const int32_t* ids, int64_t routes, int32_t k, + const std::vector& count, std::vector& off, + std::vector& order, int32_t* slot, int32_t* src) { + std::stable_sort(order.begin(), order.end(), [&](int32_t a, int32_t b) { + return count[(size_t) a] != count[(size_t) b] + ? count[(size_t) a] < count[(size_t) b] : a < b; + }); + std::fill(off.begin(), off.end(), 0); + int32_t cursor = 0; + for (int32_t e : order) { + off[(size_t) e] = cursor; + cursor += count[(size_t) e]; + } + off.back() = cursor; + std::vector fill(off.begin(), off.end() - 1); + // Preserve token-major/rank-major traversal, hence the original within-expert row order. + for (int64_t i = 0; i < routes; ++i) { + const int32_t e = ids[(size_t) i]; + const int32_t p = fill[(size_t) e]++; + slot[(size_t) i] = p; + src[(size_t) p] = (int32_t) (i / k); + } +} + +} // namespace strata::prefill::detail diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu index 19d1c949..abcbe729 100644 --- a/src/prefill/moe_fused.cu +++ b/src/prefill/moe_fused.cu @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace strata::prefill::fused { @@ -55,6 +56,15 @@ constexpr size_t smem_bytes(bool gu) { // the stored position of value k of a 32-value half-block (see "The K order") __host__ __device__ __forceinline__ int perm32(int k) { return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2); } +// where value k of a 32-value half-block is stored: perm32 for the CUDA kernel; on HIP the gfx11 WMMA kernel's order +// (value 4b + t of a 16-value word at 4t + b: see expert_w11_kernel) +__host__ __device__ __forceinline__ int act_pos(int k) { +#if defined(__HIPCC__) + return (k & 16) | ((k & 3) << 2) | ((k >> 2) & 3); +#else + return perm32(k); +#endif +} struct Tables { int32_t *cnt, *off, *fill, *ts; // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1) @@ -88,8 +98,8 @@ __global__ void quant_act_kernel(const float* __restrict__ x, int64_t nblk, uint s1 += __shfl_xor_sync(0xffffffffu, s1, o); } uint8_t* out = xa + w * AB; - out[perm32(lane)] = (uint8_t) (int8_t) q0; - out[32 + perm32(lane)] = (uint8_t) (int8_t) q1; + out[act_pos(lane)] = (uint8_t) (int8_t) q0; + out[32 + act_pos(lane)] = (uint8_t) (int8_t) q1; if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, -(MAGICF + (float) s0), a1 / 127.0f, -(MAGICF + (float) s1)); } @@ -348,6 +358,216 @@ expert_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, c #endif } +#if defined(__HIPCC__) +// ---- Aurora (S23): the same products on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 (wave32). +// Fragments (gfx11): A lane l holds the 16 k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of +// column l % 16, C/D lane l holds D[2i + l / 16][l % 16], i = 0..7. A = 16 weight rows, B = 16 tile rows (tokens): +// a lane's eight results are eight weight rows of ONE tile row, whose activation scales it already holds. +// The K order of a 16-weight word (one k-step): A register t = (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, +// t+12, so k index p = 4t + b stands for weight 4b + t; the activations are stored in that order (act_pos). The +// integer dot of each 32-value half (two k-steps) is exact and the epilogue is the CUDA kernel's, so the numbers are +// those of expert_kernel (another K order inside exact integer sums). +// No LDS staging: a wave reads its weight rows (16 B per row and 64-weight block) and its tile rows' activation +// blocks (80 B) straight from global memory (L2: an expert's rows are read by every tile, a token's by every weight +// block), one block ahead in registers; the work item's weight scales go to LDS once. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) +#define STRATA_FUSED_W11 1 +#else +#define STRATA_FUSED_W11 0 +#endif +typedef int w11_i4 __attribute__((ext_vector_type(4))); +typedef int w11_i8 __attribute__((ext_vector_type(8))); +constexpr int W_ROWS = 128; // weight rows per work item (GU: 64 features = one H block) +constexpr int W_THREADS = 256; // 8 waves: 4 along the weight rows (32 each) x 2 along the tile (32) + +__device__ __forceinline__ w11_i8 wmma_iu8(w11_i4 a, w11_i4 b, w11_i8 c) { +#if STRATA_FUSED_W11 + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(false, a, true, b, c, false); +#else + __builtin_trap(); + return c; +#endif +} + +template +__global__ void __launch_bounds__(W_THREADS) +expert_w11_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, + uint8_t* __restrict__ out, float* __restrict__ dm) { +#if STRATA_FUSED_W11 + constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K + constexpr int NFB = (GU ? 1280 : 2560) / W_ROWS; // work items per tile + constexpr int CODE_LD = GU ? 640 : 160; // code bytes per weight row + constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC; + constexpr int ACT_LD = NKB * AB; // bytes per activation row + constexpr unsigned M2 = 0x03030303u; + __shared__ __align__(16) uint16_t wsc[W_ROWS * NKB]; // the item's weight scales (fp16), [row][kb] + __shared__ int srow[kTileRows]; + __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1]; // GU: H of the item's 64 features, [tile row][feature] + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4; + const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; + for (int w = blockIdx.x; w < nwork; w += gridDim.x) { + const int2 tl = tb.tiles[t0 + w / NFB]; + const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0); + const uint8_t* blob = b.blob[e - b.e0]; + const int rbase = fb * W_ROWS; + __syncthreads(); // the previous item is done with srow / wsc / hs + if (tid < kTileRows) { + const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one + srow[tid] = GU ? src[r] : r; + } + { + const uint4* s4 = reinterpret_cast(blob + O_SC + (size_t) rbase * NKB * 2); + for (int i = tid; i < W_ROWS * NKB / 8; i += W_THREADS) reinterpret_cast(wsc)[i] = s4[i]; + } + __syncthreads(); + const bool on = 32 * wn < nrows; // a wave past the tile's rows only stages + float acc[2][2][8]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f; + if (on) { + const uint8_t* arow[2]; + const uint8_t* brow[2]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) arow[mt] = blob + O_CODES + (size_t) (rbase + 32 * wm + 16 * mt + l16) * CODE_LD; +#pragma unroll + for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD; + uint4 ac[2], bq[2][4]; + float4 bs[2]; + auto fetch = [&](int kb, uint4 (&a)[2], uint4 (&q)[2][4], float4 (&s)[2]) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) a[mt] = *reinterpret_cast(arow[mt] + kb * 16); +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const uint4* p = reinterpret_cast(brow[nt] + kb * AB); + q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3]; + s[nt] = *reinterpret_cast(brow[nt] + kb * AB + 64); + } + }; + fetch(0, ac, bq, bs); + for (int kb = 0; kb < NKB; ++kb) { + uint4 nac[2], nbq[2][4]; + float4 nbs[2]; + if (kb + 1 < NKB) fetch(kb + 1, nac, nbq, nbs); + w11_i8 c[2][2][2]; // [half][mt][nt] +#pragma unroll + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) c[h][mt][nt] = w11_i8{0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int ks = 0; ks < 4; ++ks) { // k-step = 16-weight word ks of the block + w11_i4 A[2]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + const unsigned wd = ks == 0 ? ac[mt].x : ks == 1 ? ac[mt].y : ks == 2 ? ac[mt].z : ac[mt].w; + A[mt] = w11_i4{(int) (wd & M2), (int) ((wd >> 2) & M2), (int) ((wd >> 4) & M2), + (int) ((wd >> 6) & M2)}; + } +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const uint4 q = bq[nt][ks]; + const w11_i4 B = w11_i4{(int) q.x, (int) q.y, (int) q.z, (int) q.w}; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) c[ks >> 1][mt][nt] = wmma_iu8(A[mt], B, c[ks >> 1][mt][nt]); + } + } + // the epilogue: per 64-weight block acc += d_w * (d_x0 * (dot0 - sum0) + d_x1 * (dot1 - sum1)) +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + float dw[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int m = 32 * wm + 16 * mt + 2 * i + hi; + dw[i] = __half2float(__ushort_as_half(wsc[m * NKB + kb])); + } +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const float4 z = bs[nt]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float u0 = __int_as_float(MAGIC + c[0][mt][nt][i]) + z.y; + const float u1 = __int_as_float(MAGIC + c[1][mt][nt][i]) + z.w; + acc[mt][nt][i] = fmaf(dw[i], fmaf(z.z, u1, z.x * u0), acc[mt][nt][i]); + } + } + } + if (kb + 1 < NKB) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) ac[mt] = nac[mt]; +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + bs[nt] = nbs[nt]; +#pragma unroll + for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j]; + } + } + } + } + if constexpr (GU) { + // SwiGLU: row 2f is feature f's gate (lanes 0..15), 2f + 1 its up (lanes 16..31) - the same (mt, i) + if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16); + const float gt = acc[mt][nt][i]; + if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up; + } + } + __syncthreads(); + // H block fb (features 64 fb .. 64 fb + 63) to int8: a thread per (tile row, half) + if (tid < 2 * kTileRows) { + const int r = tid >> 1, hh = tid & 1; + if (r < nrows) { + float am = 0.0f; +#pragma unroll 8 + for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j])); + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB; + int sum = 0; + uint32_t wd[8] = {}; +#pragma unroll + for (int j = 0; j < 32; ++j) { + const int qv = __float2int_rn(hs[r][32 * hh + j] * inv); + sum += qv; + const int p = act_pos(j); + wd[p >> 2] |= (uint32_t) (uint8_t) (int8_t) qv << (8 * (p & 3)); + } + uint4* o4 = reinterpret_cast(o + 32 * hh); + o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); + o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); + *reinterpret_cast(o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum)); + } + } + } else if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const int r = 32 * wn + 16 * nt + l16; + if (r < nrows) { + float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi; +#pragma unroll + for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i]; + } + } + } + } +#else + __builtin_trap(); +#endif +} +#endif // __HIPCC__ + unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } struct DevInfo { @@ -357,6 +577,20 @@ struct DevInfo { std::mutex g_mu; DevInfo g_dev[32]; +#if defined(__HIPCC__) +// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids. HIP counts a gfx11 +// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query +// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room. gfx1151 (20 +// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same +// work items and arithmetic: the results do not change). STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob). +static int wgp_blocks(int occ) { + static const int env = [] { + const char* v = std::getenv("STRATA_PF_OCC"); + return v != nullptr ? std::atoi(v) : 0; + }(); + return env > 0 ? env : 2 * std::max(occ, 1); +} +#endif const DevInfo& dev_info() { int dev = 0; cudaGetDevice(&dev); @@ -368,6 +602,23 @@ const DevInfo& dev_info() { // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs) return d; +#elif defined(__HIPCC__) + { // gfx11 (RDNA3 / RDNA3.5) with this build's code for it: the WMMA kernels + cudaDeviceProp prop; + cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); + hipFuncAttributes fa{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 || + hipFuncGetAttributes(&fa, reinterpret_cast(expert_w11_kernel)) != hipSuccess) { + cudaGetLastError(); + return d; + } + if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_w11_kernel, W_THREADS, 0) != hipSuccess || + hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_w11_kernel, W_THREADS, 0) != hipSuccess) + d.occ_gu = d.occ_d = 0; + d.cc = d.occ_gu >= 1 && d.occ_d >= 1 ? 80 : 0; + cudaGetLastError(); + return d; + } #else int major = 0, minor = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); @@ -392,6 +643,7 @@ const DevInfo& dev_info() { cudaGetLastError(); #endif return d; +#endif } } // namespace @@ -404,7 +656,11 @@ bool available() { return dev_info().cc >= 80; } bool enabled() { static const bool env = [] { const char* v = std::getenv("STRATA_PF_FUSED"); +#if defined(__HIPCC__) + return v != nullptr && v[0] == '1'; // Aurora: the gfx11 WMMA kernels are opt-in (STRATA_PF_FUSED=1) +#else return v == nullptr || v[0] != '0'; +#endif }(); return env && available(); } @@ -454,11 +710,18 @@ void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const const Tables tb = tables(const_cast(scratch), n_expert); // the most tiles the batch can have: every row in it, plus a partial tile per expert const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); +#if defined(__HIPCC__) + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_gu)); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_d)); + expert_w11_kernel<<>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr); + expert_w11_kernel<<>>(b, tb, (const uint8_t*) ha, src, nullptr, dm); +#else const unsigned g_gu = (unsigned) std::min(tiles * 5, (int64_t) d.sms * d.occ_gu); const unsigned g_d = (unsigned) std::min(tiles * 10, (int64_t) d.sms * d.occ_d); expert_kernel<<>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr); expert_kernel<<>>(b, tb, (const uint8_t*) ha, src, nullptr, dm); +#endif ck(cudaGetLastError(), "experts"); } diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index b2d99086..c05573f0 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -33,6 +33,7 @@ #include #include #include +#include #include namespace strata::prefill::fused { @@ -61,15 +62,28 @@ constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and o // the formats (ggml type ids) constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S, T_IQ3_XXS = GGML_TYPE_IQ3_XXS, T_IQ3_S = GGML_TYPE_IQ3_S, T_IQ4_XS = GGML_TYPE_IQ4_XS, - T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0; + T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0, + // Aurora (opt-in, HIP gfx11 only): Unsloth UD-Q4_K_XL's experts - gate/up Q4_K (one layer Q5_K), down Q5_1 + // (five layers Q8_0). Their weights are w = d_w q + m_w (a minimum), so a sub-block's dot is + // sum w x = d_x (d_w sum q a + m_w sum a): + // the activation blocks carry sum a per 32 values in their eight spare bytes (quant_act_nat_kernel and + // the H epilogue write it for every path; no other format reads it) + T_Q4_K = GGML_TYPE_Q4_K, T_Q5_K = GGML_TYPE_Q5_K, T_Q5_1 = GGML_TYPE_Q5_1, T_Q8_0 = GGML_TYPE_Q8_0; static_assert(sizeof(block_iq2_xxs) == 66 && sizeof(block_iq2_xs) == 74 && sizeof(block_iq2_s) == 82 && sizeof(block_iq3_xxs) == 98 && sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136 && - sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18, "the block layouts this file decodes"); + sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18 && sizeof(block_q4_K) == 144 && + sizeof(block_q5_K) == 176 && sizeof(block_q5_1) == 24 && sizeof(block_q8_0) == 34, + "the block layouts this file decodes"); // block bytes, scale per 16 values, codebook bytes in shared memory __host__ __device__ constexpr int block_bytes(int t) { return t == T_IQ2_XXS ? 66 : t == T_IQ2_XS ? 74 : t == T_IQ2_S ? 82 : t == T_IQ3_XXS ? 98 : t == T_IQ3_S ? 110 - : t == T_IQ4_XS ? 136 : 18; + : t == T_IQ4_XS ? 136 : t == T_Q4_K ? 144 : t == T_Q5_K ? 176 : t == T_Q5_1 ? 24 : t == T_Q8_0 ? 34 : 18; +} +// the formats with a minimum (w = d q + m), and the raw words a sub-block's load stage holds +__host__ __device__ constexpr bool has_min(int t) { return t == T_Q4_K || t == T_Q5_K || t == T_Q5_1; } +__host__ __device__ constexpr int raw_words(int t) { + return t == T_Q4_K ? 10 : t == T_Q5_K ? 18 : t == T_Q5_1 ? 6 : t == T_Q8_0 ? 9 : 5; } __host__ __device__ constexpr bool per16(int t) { return t == T_IQ2_XS || t == T_IQ2_S; } __host__ __device__ constexpr int grid_bytes(int t) { @@ -106,9 +120,16 @@ __global__ void quant_act_nat_kernel(const float* __restrict__ x, int64_t nblk, a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o)); } uint8_t* out = xa + w * AB; - out[lane] = (uint8_t) (int8_t) (a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0); - out[32 + lane] = (uint8_t) (int8_t) (a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0); - if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, a1 / 127.0f, 0.0f, 0.0f); + const int c0 = a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0, c1 = a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0; + out[lane] = (uint8_t) (int8_t) c0; + out[32 + lane] = (uint8_t) (int8_t) c1; + int s0 = c0, s1 = c1; // the codes' sums per 32 values (the formats with a minimum read them) +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + s0 += __shfl_xor_sync(0xffffffffu, s0, o); + s1 += __shfl_xor_sync(0xffffffffu, s1, o); + } + if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, a1 / 127.0f, (float) s0, (float) s1); } #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 @@ -142,6 +163,11 @@ __device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { : "memory"); } +#endif +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800) || defined(__HIPCC__) +#if defined(__HIPCC__) +__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; } +#endif // ---- the load stage: a 32-value sub-block's bytes into registers, then int8 and scales __device__ __forceinline__ uint32_t ld16(const uint8_t* p) { return *(const uint16_t*) p; } __device__ __forceinline__ uint32_t ld32(const uint8_t* p) { return ld16(p) | (ld16(p + 2) << 16); } @@ -158,7 +184,39 @@ __device__ __forceinline__ void signed8(uint32_t gx, uint32_t gy, uint32_t s, ui qx = __vsub4(gx ^ m0, m0); qy = __vsub4(gy ^ m1, m1); } +#if defined(__HIPCC__) +// gfx11 (Aurora): the signs from a shared-memory table instead of the compare / subtract emulation. An entry (one per +// sign byte b; for the 7-bit sign formats per 7 bits, the parity bit folded in) is {m0, c0, m1, c1}: m = 0xFF in the +// bytes whose sign bit is set (bits 0-3 for .x, 4-7 for .y), c = m & 0x01010101. q = (g ^ m) + c is -g where the sign +// is set - the two's complement, byte-wise - and g elsewhere; no byte carries into the next, because no codebook entry +// has a zero byte (256 - g with g in 1..127; the grids' bytes are 1..62), so it is the bytes signed8 gives. +__device__ __forceinline__ void signed8t(uint32_t gx, uint32_t gy, const uint4 sg, uint32_t& qx, uint32_t& qy) { + qx = (gx ^ sg.x) + sg.y; + qy = (gy ^ sg.z) + sg.w; +} +__host__ __device__ constexpr int sign_entries(int t) { return t == T_IQ2_S || t == T_IQ3_S ? 256 : 128; } +__device__ __forceinline__ uint4 sign_entry(int i, bool parity) { + uint32_t b = (uint32_t) i; + if (parity) b ^= (__popc(b) & 1) << 7; + const uint32_t m0 = __vcmpne4(((b & 15) * 0x01010101u) & 0x08040201u, 0), + m1 = __vcmpne4(((b >> 4) * 0x01010101u) & 0x08040201u, 0); + return make_uint4(m0, m0 & 0x01010101u, m1, m1 & 0x01010101u); +} +#endif // 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y +// W (X5): direct-selector form on gfx: p = low 3 bits of each nibble picks within the table half, bit 3 picks the half; +// exhaustively bit-exact over all 2^32 inputs (X5). Disable with -DSTRATA_W_NO_T16. +#if defined(__HIPCC__) && !defined(STRATA_W_NO_T16) +__device__ __forceinline__ uint32_t table16_one(uint32_t x, const uint32_t (&t)[4]) { + const uint32_t p = x & 0x07070707u; + const uint32_t a = __builtin_amdgcn_perm(t[1], t[0], p), b = __builtin_amdgcn_perm(t[3], t[2], p); + return __builtin_amdgcn_perm(b, a, ((x >> 1) & 0x04040404u) | 0x03020100u); +} +__device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { + lo = table16_one(q4, t); + hi = table16_one(q4 >> 4, t); +} +#else __device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { uint32_t tmp[2]; const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1); @@ -171,10 +229,16 @@ __device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uin lo = __byte_perm(tmp[0], tmp[1], 0x6420); hi = __byte_perm(tmp[0], tmp[1], 0x7531); } +#endif // Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block, // ib 0..1; IQ4_NL: the 32-value block). -template __device__ __forceinline__ void load_unit(const uint8_t* bp, int ib, uint32_t (&w)[5]) { +// 32 bits at a 2-byte aligned address (one load when it is 4-byte aligned) +__device__ __forceinline__ uint32_t ld32a(const uint8_t* p) { + return ((uintptr_t) p & 3) == 0 ? *(const uint32_t*) p : ld32(p); +} +template __device__ __forceinline__ void load_unit(const uint8_t* bp, int ib, uint32_t (&w)[NW]) { + static_assert(NW >= raw_words(T), "raw words"); if constexpr (T == T_IQ2_XXS) { w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); } else if constexpr (T == T_IQ2_XS) { @@ -196,21 +260,78 @@ template __device__ __forceinline__ void load_unit(const uint8_t* bp, in #pragma unroll for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 2 + 4 * k); w[4] = ld16(bp); + } else if constexpr (T == T_Q4_K || T == T_Q5_K) { + // qs: 32 bytes of the sub-block pair (ib / 2), the nibble chosen in convert; w[8] = d | dmin << 16; w[9]: the + // scale/min bytes (get_scale_min_k4's: ib < 4: sc[ib], sc[ib + 4]; else sc[ib + 4], sc[ib - 4], sc[ib]), ib << 24 + constexpr int QS = T == T_Q4_K ? 16 : 48; + const uint8_t* q = bp + QS + 32 * (ib >> 1); +#pragma unroll + for (int k = 0; k < 8; ++k) w[k] = ld32a(q + 4 * k); + w[8] = ld32a(bp); + const uint8_t* sc = bp + 4; + w[9] = ib < 4 ? (uint32_t) sc[ib] | ((uint32_t) sc[ib + 4] << 8) + : (uint32_t) sc[ib + 4] | ((uint32_t) sc[ib - 4] << 8) | ((uint32_t) sc[ib] << 16); + w[9] |= (uint32_t) ib << 24; + if constexpr (T == T_Q5_K) { +#pragma unroll + for (int k = 0; k < 8; ++k) w[10 + k] = ld32a(bp + 16 + 4 * k); // qh + } + } else if constexpr (T == T_Q5_1) { // d, m, qh, qs[16] +#pragma unroll + for (int k = 0; k < 4; ++k) w[k] = ld32a(bp + 8 + 4 * k); + w[4] = ld32a(bp + 4); + w[5] = ld32a(bp); + } else if constexpr (T == T_Q8_0) { // d, qs[32] +#pragma unroll + for (int k = 0; k < 8; ++k) w[k] = ld32(bp + 2 + 4 * k); + w[8] = ld16(bp); } else { // Q2_0 w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); } } // The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31). -template -__device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* grid, const uint32_t (&kv)[4], - uint32_t (&q)[8], float& s0, float& s1) { - if constexpr (T == T_IQ2_XXS) { +template +__device__ __forceinline__ void convert(const uint32_t (&w)[NW], const uint8_t* grid, const uint32_t (&kv)[4], + uint32_t (&q)[8], float& s0, float& s1, const uint4* sgn = nullptr) { + if constexpr (T == T_Q4_K || T == T_Q5_K) { + const int ib = (int) (w[9] >> 24), sh = 4 * (ib & 1); + uint32_t sc, mn; + if (ib < 4) { sc = w[9] & 63; mn = (w[9] >> 8) & 63; } + else { + sc = ((w[9] & 0xF) | (((w[9] >> 8) & 0xC0) >> 2)); // sc[ib + 4] & 15 | (sc[ib - 4] >> 6) << 4 + mn = (((w[9]) >> 4) & 0xF) | (((w[9] >> 16) & 0xC0) >> 2); // sc[ib + 4] >> 4 | (sc[ib] >> 6) << 4 + } +#pragma unroll + for (int k = 0; k < 8; ++k) { + q[k] = (w[k] >> sh) & 0x0F0F0F0Fu; + if constexpr (T == T_Q5_K) q[k] |= ((w[10 + k] >> ib) & 0x01010101u) << 4; + } + s0 = half_at(w[8]) * (float) sc; + s1 = -(half_at(w[8] >> 16) * (float) mn); + } else if constexpr (T == T_Q5_1) { +#pragma unroll + for (int k = 0; k < 4; ++k) { + const uint32_t lo = ((w[4] >> (4 * k)) & 0xF) * 0x00204081u, hi = ((w[4] >> (16 + 4 * k)) & 0xF) * 0x00204081u; + q[k] = (w[k] & 0x0F0F0F0Fu) | ((lo & 0x01010101u) << 4); + q[4 + k] = ((w[k] >> 4) & 0x0F0F0F0Fu) | ((hi & 0x01010101u) << 4); + } + s0 = half_at(w[5]); + s1 = half_at(w[5] >> 16); + } else if constexpr (T == T_Q8_0) { +#pragma unroll + for (int k = 0; k < 8; ++k) q[k] = w[k]; + s0 = s1 = half_at(w[8]); + } else if constexpr (T == T_IQ2_XXS) { const uint2* g = (const uint2*) grid; #pragma unroll for (int l = 0; l < 4; ++l) { const uint2 e = g[(w[0] >> (8 * l)) & 255]; +#if defined(__HIPCC__) + signed8t(e.x, e.y, sgn[(w[1] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]); +#else signed8(e.x, e.y, unpack_ksigns(w[1] >> (7 * l)), q[2 * l], q[2 * l + 1]); +#endif } s0 = s1 = half_at(w[2]) * (float) ((w[1] >> 27) | 1) * 0.125f; } else if constexpr (T == T_IQ2_XS) { @@ -219,7 +340,11 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g for (int l = 0; l < 4; ++l) { const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF; const uint2 e = g[c & 511]; +#if defined(__HIPCC__) + signed8t(e.x, e.y, sgn[(c >> 9) & 127], q[2 * l], q[2 * l + 1]); +#else signed8(e.x, e.y, unpack_ksigns(c >> 9), q[2 * l], q[2 * l + 1]); +#endif } const float d = half_at(w[2]); const uint32_t sc = w[2] >> 16; @@ -231,7 +356,11 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g #pragma unroll for (int l = 0; l < 4; ++l) { const uint2 e = g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)]; +#if defined(__HIPCC__) + signed8t(e.x, e.y, sgn[(w[1] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]); +#else signed8(e.x, e.y, ((w[1] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); +#endif } const float d = half_at(w[2]); const uint32_t sc = w[2] >> 24; @@ -242,7 +371,11 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g #pragma unroll for (int l = 0; l < 4; ++l) { const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; +#if defined(__HIPCC__) + signed8t(g[i0], g[i1], sgn[(w[2] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]); +#else signed8(g[i0], g[i1], unpack_ksigns(w[2] >> (7 * l)), q[2 * l], q[2 * l + 1]); +#endif } s0 = s1 = half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f; } else if constexpr (T == T_IQ3_S) { @@ -251,8 +384,13 @@ __device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* g #pragma unroll for (int l = 0; l < 4; ++l) { const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; +#if defined(__HIPCC__) + signed8t(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)], + sgn[(w[2] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]); +#else signed8(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)], ((w[2] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); +#endif } s0 = s1 = half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24)); } else if constexpr (T == T_IQ4_XS || T == T_IQ4_NL) { @@ -506,6 +644,251 @@ native_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_ #endif } +#if defined(__HIPCC__) +// ---- Aurora (S23): the native packs' fused experts on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 +// (wave32). The CUDA kernel's arithmetic: a 32-value sub-block decoded to int8 (load_unit / convert above) and its +// scales; per 32 values the int32 dot starts from MAGIC (the C operand), so as_float(d) - 1.5 * 2^23 is the dot; the +// formats with a scale per 16 values take each 16-value k-step's dot alone. Fragments (gfx11): A lane l holds the 16 +// k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of column l % 16, C/D lane l holds +// D[2i + l / 16][l % 16]. Both operands are in natural order: the decoded weights (LDS, double-buffered) and the +// activations (quant_act_nat_kernel; read by each lane from global/L2, a stage ahead). +// A work item = NW_ROWS weight rows x a 64-row tile; 8 waves: 4 along the weight rows (32 each) x 2 along the tile +// (32 each), each 2 x 2 WMMA tiles. Gate/up: local row r is feature r / 2, its gate (r even) or up (r odd) row, so a +// lane pair l, l + 16 holds gate and up of one feature. +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) +#define STRATA_NAT_W11 1 +#else +#define STRATA_NAT_W11 0 +#endif +typedef int nw_i4 __attribute__((ext_vector_type(4))); +typedef int nw_i8 __attribute__((ext_vector_type(8))); +constexpr int NW_ROWS = 128; +constexpr int NW_THREADS = 256; + +__device__ __forceinline__ nw_i8 nw_wmma(nw_i4 a, nw_i4 b, nw_i8 c) { +#if STRATA_NAT_W11 + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false); +#else + __builtin_trap(); + return c; +#endif +} +__device__ __forceinline__ nw_i4 nw_u4(uint4 v) { return nw_i4{(int) v.x, (int) v.y, (int) v.z, (int) v.w}; } + +// W (X1): ALIAS = the H tile lives on the weight buffers (one extra barrier); LB > 0 = amdgpu_waves_per_eu(LB) (VGPR cap). +// Disable both with -DSTRATA_W_NO_OCC (the launch sites then use and grid factor wgp_blocks). +template +__global__ void __launch_bounds__(NW_THREADS) __attribute__((amdgpu_waves_per_eu(LB > 0 ? LB : 1))) +native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, + const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { +#if STRATA_NAT_W11 + constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K + constexpr int NFB = (GU ? 1280 : 2560) / NW_ROWS; // work items per tile + constexpr int ACT_LD = NS * AB; + constexpr int BS = block_bytes(WT); + constexpr bool K16 = per16(WT); + constexpr int GB = grid_bytes(WT) > 0 ? grid_bytes(WT) : 16; + __shared__ __align__(16) uint8_t wtbuf[2 * NW_ROWS * WLD]; + uint8_t(*wt)[NW_ROWS][WLD] = reinterpret_cast(wtbuf); + __shared__ __align__(16) float ws[2][NW_ROWS][4]; // their scales per 16 values + __shared__ __align__(16) uint8_t sgrid[GB]; + constexpr int SGN = (WT == T_IQ2_XXS || WT == T_IQ2_XS || WT == T_IQ2_S || WT == T_IQ3_XXS || WT == T_IQ3_S) + ? sign_entries(WT) : 1; + __shared__ __align__(16) uint4 ssign[SGN]; // the signs of a sign byte, as byte masks + __shared__ int srow[kTileRows]; + __shared__ float hs_sep[(GU && !ALIAS) ? kTileRows : 1][65]; + static_assert(!ALIAS || (size_t) kTileRows * 65 * 4 <= (size_t) 2 * NW_ROWS * WLD, "H tile must fit the weight buffers"); + float(*hs)[65] = ALIAS ? reinterpret_cast(wtbuf) : hs_sep; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4; + if constexpr (grid_bytes(WT) > 0) { + const uint32_t* gs = (const uint32_t*) grid_src(); + for (int i = tid; i < grid_bytes(WT) / 4; i += NW_THREADS) ((uint32_t*) sgrid)[i] = gs[i]; + } + if constexpr (SGN > 1) { + for (int i = tid; i < SGN; i += NW_THREADS) ssign[i] = sign_entry(i, SGN == 128); + } + uint32_t kv[4] = {0, 0, 0, 0}; + if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { +#pragma unroll + for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3)); + } + const int ur = tid >> 1, uj = tid & 1; // this thread's decode unit: row ur, sub-block uj + const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; + for (int w = blockIdx.x; w < nwork; w += gridDim.x) { + const int2 tl = tb.tiles[t0 + w / NFB]; + const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0); + const uint8_t* blob = b.blob[e - b.e0]; + const int rbase = fb * NW_ROWS; + const uint8_t* wrow = GU ? blob + ((ur & 1) ? geo.up_off : 0) + (size_t) (fb * (NW_ROWS / 2) + (ur >> 1)) * geo.gu_row + : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row; + auto unit = [&](int s) -> const uint8_t* { + if (GU) return wrow + (s >> 2) * BS; + return (WT == T_IQ4_NL || WT == T_Q5_1 || WT == T_Q8_0) ? wrow + (2 * s + uj) * BS : wrow + s * BS; + }; + auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; }; + auto put = [&](const uint32_t (&raw)[raw_words(WT)], int buf) { + uint32_t q[8]; + float s0, s1; + convert(raw, sgrid, kv, q, s0, s1, ssign); + uint4* d = (uint4*) &wt[buf][ur][32 * uj]; + d[0] = make_uint4(q[0], q[1], q[2], q[3]); + d[1] = make_uint4(q[4], q[5], q[6], q[7]); + *(float2*) &ws[buf][ur][2 * uj] = make_float2(s0, s1); + }; + __syncthreads(); // the previous item is done with the buffers + if (tid < kTileRows) { + const int r = row0 + min(tid, nrows - 1); // rows past the tile's end repeat its last one + srow[tid] = GU ? src[r] : r; + } + uint32_t raw[raw_words(WT)] = {}; + load_unit(unit(0), sub(0), raw); + put(raw, 0); + if (NS > 1) load_unit(unit(1), sub(1), raw); + __syncthreads(); // srow + const bool on = 32 * wn < nrows; + const uint8_t* brow[2]; +#pragma unroll + for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD; + float acc[2][2][8]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f; + uint4 bq[2][4]; + float2 bx[2], bsum[2]; // the activation scales, and (the formats with a minimum) the codes' sums per 32 values + auto fetch_b = [&](int s, uint4 (&q)[2][4], float2 (&x)[2], float2 (&sm)[2]) { +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const uint4* p = reinterpret_cast(brow[nt] + s * AB); + q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3]; + x[nt] = *reinterpret_cast(brow[nt] + s * AB + 64); + if constexpr (has_min(WT)) sm[nt] = *reinterpret_cast(brow[nt] + s * AB + 72); + else sm[nt] = make_float2(0.0f, 0.0f); + } + }; + if (on) fetch_b(0, bq, bx, bsum); + for (int s = 0; s < NS; ++s) { + __syncthreads(); // stage s's weights are in buffer s & 1 + uint4 nbq[2][4]; + float2 nbx[2], nbsum[2]; + if (on && s + 1 < NS) fetch_b(s + 1, nbq, nbx, nbsum); + if (on) { + const int bf = s & 1; +#pragma unroll + for (int h = 0; h < 2; ++h) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + const int rb = 32 * wm + 16 * mt; + const uint4* ap = reinterpret_cast(&wt[bf][rb + l16][32 * h]); + const nw_i4 A0 = nw_u4(ap[0]), A1 = nw_u4(ap[1]); + float w0[8], w1[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float2 sw = *reinterpret_cast(&ws[bf][rb + 2 * i + hi][2 * h]); + w0[i] = sw.x; w1[i] = sw.y; + } +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const float dx = h ? bx[nt].y : bx[nt].x; + const nw_i4 B0 = nw_u4(bq[nt][2 * h]), B1 = nw_u4(bq[nt][2 * h + 1]); + const nw_i8 m = nw_i8{MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC}; + if constexpr (K16) { + const nw_i8 d0 = nw_wmma(A0, B0, m), d1 = nw_wmma(A1, B1, m); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float v = fmaf(w1[i], dotf(d1[i]), w0[i] * dotf(d0[i])); + acc[mt][nt][i] = fmaf(dx, v, acc[mt][nt][i]); + } + } else { + const nw_i8 d = nw_wmma(A1, B1, nw_wmma(A0, B0, m)); +#pragma unroll + for (int i = 0; i < 8; ++i) { + acc[mt][nt][i] = fmaf(w0[i] * dx, dotf(d[i]), acc[mt][nt][i]); + if constexpr (has_min(WT)) acc[mt][nt][i] = fmaf(w1[i] * dx, h ? bsum[nt].y : bsum[nt].x, acc[mt][nt][i]); + } + } + } + } + } + } + if (s + 1 < NS) { + put(raw, (s + 1) & 1); // the other buffer: its readers passed this barrier + if (s + 2 < NS) load_unit(unit(s + 2), sub(s + 2), raw); + if (on) { +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + bx[nt] = nbx[nt]; + bsum[nt] = nbsum[nt]; +#pragma unroll + for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j]; + } + } + } + } + if constexpr (GU) { + if constexpr (ALIAS) __syncthreads(); // every wave is done reading the weight buffers + if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16); + const float gt = acc[mt][nt][i]; + if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up; + } + } + __syncthreads(); + // H block fb (features 64 fb ..) to int8 per 32, natural order: a thread per (tile row, half) + if (tid < 2 * kTileRows) { + const int r = tid >> 1, hh = tid & 1; + if (r < nrows) { + float am = 0.0f; +#pragma unroll 8 + for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j])); + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB; + uint32_t wd[8] = {}; + int csum = 0; +#pragma unroll + for (int j = 0; j < 32; ++j) { + const int c = __float2int_rn(hs[r][32 * hh + j] * inv); + csum += c; + wd[j >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (j & 3)); + } + uint4* o4 = reinterpret_cast(o + 32 * hh); + o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); + o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); + *reinterpret_cast(o + 64 + 4 * hh) = am / 127.0f; + *reinterpret_cast(o + 72 + 4 * hh) = (float) csum; // (the formats with a minimum) + } + } + } else { + if (on) { +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const int r = 32 * wn + 16 * nt + l16; + if (r < nrows) { + float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi; +#pragma unroll + for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i]; + } + } + } + } + } +#else + __builtin_trap(); +#endif +} +#endif // __HIPCC__ + unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } // per device: whether every kernel here runs (sm_80+, device code in this build, fits), and their occupancy @@ -516,7 +899,7 @@ struct DevInfo { std::mutex g_mu; DevInfo g_dev[32]; -#if !defined(STRATA_HIP_GFX906) +#if !defined(__HIPCC__) template bool setup_ww(int& occ) { cudaFuncAttributes fa{}; if (cudaFuncGetAttributes(&fa, native_kernel) != cudaSuccess || fa.ptxVersion < 80) return false; @@ -533,6 +916,20 @@ template bool setup_ww(int& occ) { template bool setup_one(int& occ) { return setup_ww(occ) && setup_ww(occ); } #endif +#if defined(__HIPCC__) +// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids. HIP counts a gfx11 +// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query +// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room. gfx1151 (20 +// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same +// work items and arithmetic: the results do not change). STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob). +static int wgp_blocks(int occ) { + static const int env = [] { + const char* v = std::getenv("STRATA_PF_OCC"); + return v != nullptr ? std::atoi(v) : 0; + }(); + return env > 0 ? env : 2 * std::max(occ, 1); +} +#endif const DevInfo& dev_info() { int dev = 0; cudaGetDevice(&dev); @@ -544,6 +941,24 @@ const DevInfo& dev_info() { // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs) return d; +#elif defined(__HIPCC__) + { // gfx11 with this build's code: the WMMA kernels (one occupancy for all: the same shape and LDS budget) + cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); + cudaDeviceProp prop; + hipFuncAttributes fa{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 || + hipFuncGetAttributes(&fa, reinterpret_cast(native_w11_kernel)) != hipSuccess) { + cudaGetLastError(); + return d; + } + int o = 0; + if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_w11_kernel, NW_THREADS, 0) != hipSuccess) + o = 0; + d.ok = o >= 1; + d.occ = d.ok ? o : 1; + cudaGetLastError(); + return d; + } #else int major = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); @@ -557,12 +972,32 @@ const DevInfo& dev_info() { cudaGetLastError(); #endif return d; +#endif } +// opt-in on top of STRATA_PF_FUSED=1: STRATA_PF_FUSED_KQ=1 takes UD-Q4_K_XL's formats (the output differs from the FP16 +// expert path's at rounding level; KL-gated, see aurora_s23.md) +bool kq_on() { + static const bool on = [] { + const char* v = std::getenv("STRATA_PF_FUSED_KQ"); + return v != nullptr && v[0] == '1'; + }(); + return on; +} bool gu_covered(int t) { - return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS; + return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS +#if defined(__HIPCC__) + || ((t == T_Q4_K || t == T_Q5_K) && kq_on()) // the gfx11 kernels only +#endif + ; +} +bool d_covered(int t) { + return t == T_Q2_0 || t == T_IQ4_NL +#if defined(__HIPCC__) + || ((t == T_Q5_1 || t == T_Q8_0) && kq_on()) +#endif + ; } -bool d_covered(int t) { return t == T_Q2_0 || t == T_IQ4_NL; } template void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Tables& tb, const void* act, @@ -616,6 +1051,45 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n } const cudaStream_t s = (cudaStream_t) stream; const Tables tb = tables(const_cast(scratch), n_expert); +#if defined(__HIPCC__) + { + const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); + // W (X1): LDS alias of the H tile + waves_per_eu(8) (192 VGPRs) + 4 blocks per WGP, only for the types whose + // kernels do not spill under the cap (measured: gate/up IQ2_*, IQ3_*, IQ4_XS 0-5 regs; down IQ4_NL 11, Q8_0 / Q2_0 0; + // Q4_K / Q5_K gate/up and Q5_1 down spill 100+ and keep the old launch). +#ifdef STRATA_W_NO_OCC + const bool occ_gu = false, occ_d = false; +#else + const bool occ_gu = g.gu_type == T_IQ2_XXS || g.gu_type == T_IQ2_XS || g.gu_type == T_IQ2_S || + g.gu_type == T_IQ3_XXS || g.gu_type == T_IQ3_S || g.gu_type == T_IQ4_XS; + const bool occ_d = g.d_type == T_Q2_0 || g.d_type == T_Q8_0 || g.d_type == T_IQ4_NL; +#endif + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / NW_ROWS), (int64_t) d.sms * (occ_gu ? 4 : wgp_blocks(d.occ))); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / NW_ROWS), (int64_t) d.sms * (occ_d ? 4 : wgp_blocks(d.occ))); + const uint8_t* xa8 = (const uint8_t*) xa; + uint8_t* ha8 = (uint8_t*) ha; +#define STRATA_NW_GU(T) do { if (occ_gu) native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr); else native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr); } while (0) + switch (g.gu_type) { + case T_IQ2_XXS: STRATA_NW_GU(T_IQ2_XXS); break; + case T_IQ2_XS: STRATA_NW_GU(T_IQ2_XS); break; + case T_IQ2_S: STRATA_NW_GU(T_IQ2_S); break; + case T_IQ3_XXS: STRATA_NW_GU(T_IQ3_XXS); break; + case T_IQ3_S: STRATA_NW_GU(T_IQ3_S); break; + case T_Q4_K: STRATA_NW_GU(T_Q4_K); break; + case T_Q5_K: STRATA_NW_GU(T_Q5_K); break; + default: STRATA_NW_GU(T_IQ4_XS); break; + } +#undef STRATA_NW_GU +#define STRATA_NW_D(T) do { if (occ_d) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); else native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); } while (0) + if (g.d_type == T_Q2_0) STRATA_NW_D(T_Q2_0); + else if (g.d_type == T_Q5_1) STRATA_NW_D(T_Q5_1); + else if (g.d_type == T_Q8_0) STRATA_NW_D(T_Q8_0); + else STRATA_NW_D(T_IQ4_NL); +#undef STRATA_NW_D + ck(cudaGetLastError(), "experts_native"); + return; + } +#endif const int ww = pick_ww(n, n_expert); // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the // ones inside a larger item end at once diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e76fb6dd..9ff9d1ba 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,11 +1,14 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. #include "strata/prefill/prefill.hpp" +#include "mmq_resident_sort.hpp" +#include "wmma_gemm.h" #include "strata/core/mtp.hpp" #include "strata/core/progress.hpp" #include "strata/core/on_device.hpp" #include "strata/core/layout.hpp" #include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/native_qsa.hpp" #include "strata/kernels/native_qsa_indexer.hpp" #include "strata/kernels/ngram.hpp" #include "strata/kernels/ple.hpp" @@ -212,7 +215,51 @@ inline int bf16x2_mode() { return v; } inline bool bf16x2() { return bf16x2_mode() != 0; } +// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11); +// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` +static int64_t pf_switch_min_t() { // S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of + // N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones) + static const int64_t v = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }(); + return v; +} +inline bool hc_upmix() { + static const bool v = [] { const char* e = std::getenv("STRATA_HC_UPMIX"); return e != nullptr && e[0] == '1'; }(); + return v; +} inline bool bf16x2_hc() { return bf16x2_mode() == 1; } +// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass +// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces) +// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and +// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride +// 10240 + 64. Rounding-level (another k order than hipBLASLt): quality-gated. +inline bool pf_hcdown() { + static const bool v = [] { const char* e = std::getenv("STRATA_PF_HCDOWN"); return e && e[0] == '1'; }(); + return v; +} +constexpr int64_t XN_PAD = 64; +// S (opt-in STRATA_HCD_EXACT=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the HC down projection by a WMMA kernel with +// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject +// projection stays on hipBLASLt, reading that stride) +inline bool hcd_exact() { + static const bool v = [] { const char* e = std::getenv("STRATA_HCD_EXACT"); return e && e[0] == '1'; }(); + return v; +} +inline bool hc_pad() { return pf_hcdown() || hcd_exact(); } +inline bool cvec_fuse() { + static const bool v = [] { const char* e = std::getenv("STRATA_CVEC_FUSE"); return e && e[0] == '1'; }(); + return v; +} +// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's +// y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the +// 4 KB-multiple stride; Gemm::native pads the weight the same way). Same bits. +inline bool pf_pad() { + static const bool v = [] { + const char* p = std::getenv("STRATA_PF_PAD"); const char* g = std::getenv("STRATA_PF_GEMM"); + return p && p[0] == '1' && g && g[0] == '1'; + }(); + return v; +} +constexpr int64_t ZV_PAD = 64; // F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm inline bool gr_unfused() { @@ -640,14 +687,16 @@ constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspace uint64_t gdn_set_bytes(size_t T) { Alloc a; a.count_only = true; bool ok = true; a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * 2 * HV, ok); a.take(T * HV, ok); - a.take(T * HV, ok); a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + a.take(T * HV, ok); a.take(T * C, ok); a.take(T * ZV, ok); + a.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); return a.used; } uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch, const strata::kernels::QsaShapes& s) { Alloc a; a.count_only = true; bool ok = true; a.take(T * 512, ok); a.take(T * 512, ok); a.take(T * 12288, ok); a.take(T * ZV, ok); - a.take(T * 128, ok); a.take(T * 512, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + a.take(T * 128, ok); a.take(T * 512, ok); a.take(T * ZV, ok); + a.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); a.take(T * (size_t) cap, ok); a.take((size_t) sel_batch * (size_t) max_blocks, ok); a.take((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok); @@ -664,6 +713,8 @@ constexpr size_t MMQ_TAIL = 4096; struct MmqPlan { bool any = false, fallback = true; std::vector layer; // per layer: MMQ + std::vector fo; // per layer: no MMQ here but the native fused kernels cover its formats + // (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1) size_t gu_max = 0, d_max = 0; }; const MmqPlan& mmq_plan() { @@ -674,11 +725,17 @@ const MmqPlan& mmq_plan() { const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0); const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers; p.layer.assign((size_t) std::max(layers, 0), 0); + p.fo.assign(p.layer.size(), 0); p.fallback = !on || layers <= 0; for (int64_t l = 0; on && l < layers; ++l) { const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; // #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path - if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { p.fallback = true; continue; } + if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { + p.fallback = true; + // the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path + if (on && lay.native && fused::native_supported(gt, dt)) { p.fo[(size_t) l] = 1; p.any = true; } + continue; + } p.layer[(size_t) l] = 1; p.any = true; p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N)); @@ -852,7 +909,7 @@ bool Prefill::carve(size_t T, void* alloc) { m.emb = o.take(T * N, ok); m.R = o.take(T * D, ok); m.xn = gr_unfused() ? o.take(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R) m.grs = o.take(T * HC, ok); - m.xn16 = o.take(T * D, ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); + m.xn16 = o.take(T * (D + (hc_pad() ? XN_PAD : 0)), ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); @@ -877,12 +934,12 @@ bool Prefill::carve(size_t T, void* alloc) { a.base = base; a.cap = region; a.owned = &m.owned; m.qkv = a.take(T * C, ok); m.z = a.take(T * ZV, ok); m.ab = a.take(T * 2 * HV, ok); m.gate = a.take(T * HV, ok); m.beta = a.take(T * HV, ok); m.hbuf = a.take(T * C, ok); - m.y = a.take(T * ZV, ok); m.y_h = a.take(T * ZV, ok); + m.y = a.take(T * ZV, ok); m.y_h = a.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); Alloc b; b.base = base; b.cap = region; b.owned = &m.owned; m.Kc = b.take(T * 512, ok); m.Vc = b.take(T * 512, ok); m.Qf = b.take(T * 12288, ok); m.q = b.take(T * ZV, ok); m.idx_raw = b.take(T * 128, ok); m.q_idx = b.take(T * 512, ok); - m.attn = b.take(T * ZV, ok); m.attn_h = b.take(T * ZV, ok); + m.attn = b.take(T * ZV, ok); m.attn_h = b.take(T * (ZV + (pf_pad() ? ZV_PAD : 0)), ok); m.sel_ids = b.take(T * (size_t) m.cap, ok); m.sel_scores = b.take((size_t) m.sel_batch * (size_t) m.max_blocks, ok); m.attn_scratch = b.take((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok); @@ -1080,7 +1137,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t if (!q8) to_f16(emb, en16, nb * Nn, m.cs); proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0); cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs); - rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs); + if (mtp.hnorm_per_stream()) // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp) + strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs); + else + rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs); if (!q8) to_f16(hn, hn16, nb * HCN, m.cs); proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hidden strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs); @@ -1376,7 +1436,7 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session } else { // STRATA_RING_BYTES=0: 0.1.39's count f(T * N); f(T * D); f(T * D); } - o.take(T * D, ok); f(T * LR); o.take(T * LR, ok); + o.take(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take(T * LR, ok); f(T * D); f(T * HC); f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); if (bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } if (bf16x2()) o.take(T * N, ok); @@ -1439,15 +1499,15 @@ const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::s return r; } bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0) { + std::string& err, int64_t ldy = 0, int64_t ldx = 0) { if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; } - gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy); + gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy, 0.0f, ldx); return true; } bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, - std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) { + std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr, int64_t ldx = 0) { if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } - gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy); + gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 0.0f, ldx); if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); return true; } @@ -1982,16 +2042,65 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err); if (!wn || !wd || !wu || !wi) return false; pt.mark(kPfHc, cs); + // the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it) + const int64_t ldx = hc_pad() && T >= std::max(pf_switch_min_t(), 64) && !gr_unfused() && + !m.xn16_lo ? D + XN_PAD : D; if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); - else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); + else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo, ldx); normed = false; - if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; + bool hcd = false; + bool hdown = false; + if (ldx != D && !pf_hcdown()) { // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177 + hdown = wd->kind == core::WeightKind::Bf16InF32 && wd->data && wd->ne0 == D && wd->ne1 == LR && + m.gemm.bf16_hcd_exact(m.xn16, ldx, (const uint16_t*) wd->data, m.lo, T, LR, D); + } else if (ldx != D) { + if (wd->kind != core::WeightKind::Bf16InF32 || !wd->data || wd->ne0 != D || wd->ne1 != LR || + wi->kind != core::WeightKind::Bf16InF32 || !wi->data || wi->ne0 != D || wi->ne1 != HC || + !strata_pf_hcdown_bf16(m.xn16, ldx, (const uint16_t*) wd->data, (const uint16_t*) wi->data, LR, + HC, m.lo, m.inj, T, D, m.cs)) { + err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections"; + return false; + } + hcd = true; + } + if (!hcd && !hdown && !bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false; gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); - if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; - if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; - if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); - else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, - m.mixed_bf_lo); + bool upmixed = false; + if (hc_upmix() && T >= pf_switch_min_t() && !gr_unfused() && !m.lo16_lo && !m.mixed_bf_lo && + wu->kind == core::WeightKind::Bf16InF32 && wu->data && wu->ne0 == LR && wu->ne1 == D) { + static int checks = [] { const char* e = std::getenv("STRATA_HC_UPMIX_CHECK"); return e ? std::atoi(e) : 0; }(); + if (checks > 0) { // the default pair first, kept for the comparison + --checks; + if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false; + gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h); + std::vector ref((size_t) T * N), got((size_t) T * N); + cudaMemcpyAsync(ref.data(), m.mixed, ref.size() * 4, cudaMemcpyDeviceToHost, m.cs); + upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data, + m.mixed, m.mixed_bf, m.mixed_h, T, m.cs); + cudaMemcpyAsync(got.data(), m.mixed, got.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + double e2 = 0, r2 = 0, emax = 0; + for (size_t i = 0; i < ref.size(); ++i) { + const double dd = (double) got[i] - ref[i]; + e2 += dd * dd; r2 += (double) ref[i] * ref[i]; emax = std::max(emax, std::fabs(dd)); + } + std::fprintf(stderr, "strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, " + "max |diff| %.3e (%s)\n", (long long) l, half, (long long) T, + std::sqrt(e2 / std::max(r2, 1e-30)), emax, upmixed ? "upmix" : "upmix refused"); + } else { + upmixed = gr_upmix(m.lo16, (const uint16_t*) wu->data, m.R, m.grs, (const float*) wn->data, + m.mixed, m.mixed_bf, m.mixed_h, T, m.cs); + } + } + if (!upmixed && !bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; + if (!hcd && !bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo, ldx != D ? ldx : 0)) return false; + if (upmixed) { + } else if (gr_unfused()) { + gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); + } else { + gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, + m.mixed_bf_lo); + } if (half == 0 && !core::is_qsa_layer(g, l)) { // ======================= GDN ======================= @@ -2012,9 +2121,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs); gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); pt.mark(kPfGdnRec, cs); - gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs); + const int64_t ld_y = pf_pad() && T >= std::max(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0; + gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs, + ld_y); pt.mark(kPfGdnOut, cs); - if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false; + if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err, 0, ld_y)) return false; ++gdn_index; } else if (half == 0) { // ======================= QSA ======================= @@ -2229,8 +2340,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); pt.mark(kPfQsa, cs); - gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs); - if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false; + const int64_t ld_a = pf_pad() && T >= std::max(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0; + gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a); + if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false; ++qsa_index; } else { // ======================= MoE ======================= @@ -2265,7 +2377,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as // fused_ring() sized the ring and the buffers for it const bool no_peer = !core::peer_portable(); - const bool fused_nat = use_mmq && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt); + const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l]; + const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt); const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat; size_t n_order = 0; // the routed experts (the debug report; unknown when fused) bool peer_now = false; // multi-GPU: the peer computed rows of this layer (MMQ path only) @@ -2393,13 +2506,6 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri slot_h[(size_t) i] = p; src_h[(size_t) p] = (int32_t) (i / K); } - if (grp_mapped) { - copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs); - copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs); - } else { - cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); - cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); - } // the experts, in id order: resident ones from VRAM, the others through the staging ring std::vector order, order_peer; for (int32_t e = 0; e < m.g->n_expert; ++e) @@ -2407,6 +2513,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e); for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last: if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most time + // Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and + // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows + // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently + // before the upload, the routed ids, weights and the within-expert row order stay as they are. + if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested() && on_peer.empty(), use_mmq, lay.native, + m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr, + m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1])) + detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h); + if (grp_mapped) { + copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs); + copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs); + } else { + cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); + cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); + } n_order = order.size(); const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; @@ -2889,22 +3010,64 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a // control vector) const int64_t nl = half == 0 ? l : l + 1; - const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && - !(half == 1 && strata::kernels::cvec().covers(l)); + const bool steered = half == 1 && strata::kernels::cvec().covers(l); + const float *cv_dir = nullptr, *cv_s = nullptr; + const int* cv_on = nullptr; + const bool cv_fused = steered && cvec_fuse() && !gr_unfused() && nl < LE && !(nl == 1 && ple_on) && + strata::kernels::cvec().n_embd == N && strata::kernels::cvec().hc == HC && + strata::kernels::cvec_tables(&cv_dir, &cv_s, &cv_on); + const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused); const core::WeightRef* wnn = nullptr; if (fuse) { const core::LayerView vn(*m.wt, nl); wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err); if (!wnn) return false; } - if (wnn) { + if (wnn && cv_fused) { + // STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy + // of R and report whether R, the row scales and the BF16 image are bit-identical + static int checks = [] { const char* e = std::getenv("STRATA_CVEC_FUSE_CHECK"); return e ? std::atoi(e) : 0; }(); + if (checks > 0) { + --checks; + float *Rc = nullptr, *rc = nullptr; + uint16_t* xc = nullptr; + cudaMalloc(&Rc, (size_t) T * D * 4); cudaMalloc(&rc, (size_t) T * HC * 4); + cudaMalloc(&xc, (size_t) T * D * 2); + cudaMemcpyAsync(Rc, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, m.cs); + gr_write(Rc, m.bo, m.inj, HC, T, m.cs); + strata::kernels::cvec_apply(Rc, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); + gr_norm_rs(Rc, (const float*) wnn->data, EPS, rc, xc, T, m.cs, nullptr, D); + gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on, + strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, + m.xn16, T, m.cs, m.xn16_lo, ldx); + std::vector a((size_t) T * D), b((size_t) T * D), ra((size_t) T * HC), rb((size_t) T * HC); + std::vector xa((size_t) T * D), xb((size_t) T * D); + cudaMemcpyAsync(a.data(), m.R, a.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(b.data(), Rc, b.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(ra.data(), m.grs, ra.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(rb.data(), rc, rb.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(xa.data(), m.xn16, xa.size() * 2, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(xb.data(), xc, xb.size() * 2, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + cudaFree(Rc); cudaFree(rc); cudaFree(xc); + std::fprintf(stderr, "strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n", + (long long) l, (long long) T, + std::memcmp(a.data(), b.data(), a.size() * 4) ? "DIFFERS" : "identical", + std::memcmp(ra.data(), rb.data(), ra.size() * 4) ? "DIFFERS" : "identical", + std::memcmp(xa.data(), xb.data(), xa.size() * 2) ? "DIFFERS" : "identical"); + } else + gr_write_cvec_norm_rs(m.R, m.bo, m.inj, HC, cv_dir + l * N, cv_s + l, cv_on, + strata::kernels::cvec().mode, (const float*) wnn->data, EPS, m.grs, m.xn16, + T, m.cs, m.xn16_lo, ldx); + normed = true; + } else if (wnn) { gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, - m.xn16_lo); + m.xn16_lo, ldx); normed = true; } else { gr_write(m.R, m.bo, m.inj, HC, T, m.cs); } - if (half == 1 && strata::kernels::cvec().covers(l)) // --control-vector-scaled + if (steered && !cv_fused) // --control-vector-scaled strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); } } @@ -2952,6 +3115,28 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri std::fclose(f); } } + if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R_ALL")) { + // S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16 + // (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd] + cudaStreamSynchronize(m.cs); + if (std::FILE* f = std::fopen(dump, "ab")) { + constexpr int64_t kRows = 512; + std::vector rows((size_t) (kRows * D)); + std::vector out((size_t) (kRows * D)); + for (int64_t t0 = 0; t0 < T; t0 += kRows) { + const int64_t nr = std::min(kRows, T - t0); + cudaMemcpy(rows.data(), m.R + t0 * D, (size_t) (nr * D) * 4, cudaMemcpyDeviceToHost); + for (int64_t i = 0; i < nr * D; ++i) { + uint32_t u; + std::memcpy(&u, &rows[(size_t) i], 4); + u += 0x7fffu + ((u >> 16) & 1u); + out[(size_t) i] = (uint16_t) (u >> 16); + } + std::fwrite(out.data(), 2, (size_t) (nr * D), f); + } + std::fclose(f); + } + } if (on_chunk || on_stage_chunk) { const auto toc = Clock::now(); if (cudaStreamSynchronize(m.cs) != cudaSuccess) { diff --git a/src/prefill/wmma_gemm.cu b/src/prefill/wmma_gemm.cu new file mode 100644 index 00000000..9547596a --- /dev/null +++ b/src/prefill/wmma_gemm.cu @@ -0,0 +1,737 @@ +// src/prefill/wmma_gemm.cu - RDNA3 WMMA FP16 & BF16 GEMM for Strata prefill (gfx1100). +// +// Computes Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA intrinsics: +// * X is T x K row-major (leading dim K), fp16 or bf16 +// * W is N x K row-major (leading dim K), fp16 or bf16 +// * Y is T x N row-major with leading dimension ldy >= N, fp32 +// +// Hardware: AMD RDNA3 (gfx1100, e.g. RX 7900 XTX) +// * v_wmma_f32_16x16x16_f16_w32 intrinsic (__builtin_amdgcn_wmma_f32_16x16x16_f16_w32) +// * v_wmma_f32_16x16x16_bf16_w32 intrinsic (__builtin_amdgcn_wmma_f32_16x16x16_bf16_w32) +// * Wave32 doubled input fragment: lane t (lane_lo = t & 15) holds row lane_lo of A (16 elements along K) +// and column lane_lo of B (16 elements along K). Lanes 16..31 duplicate lanes 0..15. +// * Wave32 C output mapping: lane t holds column lane_lo of 16x16 output tile, +// with 8 elements alternating rows: row m = 2*i + lane_hi (lane_hi = t >> 4). +// * Tile variants: +// 1. gemm_wmma_64x64_4w: 4 waves (128 threads), 64T x 64N x 16K tile, double-buffered LDS for W. +// 2. gemm_wmma_16x16_1w: 1 wave (32 threads), 16T x 16N x 16K tile, zero LDS/barriers, for small T/N. + +#include "wmma_gemm.h" + +#include +#include +#include + +#include +#include + +// STRATA_WMMA_GFX11 is defined by the BUILD (CMakeLists.txt, from CMAKE_HIP_ARCHITECTURES), not inferred +// from compiler macros: measured on this toolchain the HOST pass of a HIP compile does not define +// __gfx1100__ but does define __HIP_DEVICE_COMPILE__, so a compiler-macro guard here silently selected the +// "return false" stub at the bottom of this file for the very symbol the engine links - the WMMA path then +// never ran, while the same file compiled with hipcc (as the probes do) took the real branch. One +// build-defined macro is uniform across the host and device passes. +#if defined(STRATA_WMMA_GFX11) + +using v8fp32 = float __attribute__((ext_vector_type(8))); + +template +struct WmmaTraits; + +template <> +struct WmmaTraits<_Float16> { + using vec_t = _Float16 __attribute__((ext_vector_type(16))); + __device__ static inline v8fp32 mma(vec_t a, vec_t b, v8fp32 c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#else + (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate) +#endif + } +}; + +template <> +struct WmmaTraits<__bf16> { + using vec_t = __bf16 __attribute__((ext_vector_type(16))); + __device__ static inline v8fp32 mma(vec_t a, vec_t b, v8fp32 c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +#else + (void) a; (void) b; return c; // not a gfx11 device pass: never launched (runtime gate) +#endif + } +}; + +// =========================================================================== +// Variant 1: 16x16_1w - Single-wave kernel for small T / N. +// Zero LDS, zero barrier synchronization, full register residency. +// =========================================================================== +template +__global__ void gemm_wmma_16x16_1w( + const uint16_t* __restrict__ X, + const uint16_t* __restrict__ W, + float* __restrict__ Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta) { + + using vec_t = typename WmmaTraits::vec_t; + const int m_tile = blockIdx.y * 16; + const int n_tile = blockIdx.x * 16; + if (m_tile >= T || n_tile >= N) return; + + const int lane = threadIdx.x; // 0..31 + const int lane_lo = lane & 15; // 0..15 + const int lane_hi = lane >> 4; // 0 or 1 + + v8fp32 c_acc = {0, 0, 0, 0, 0, 0, 0, 0}; + + const int m_row = m_tile + lane_lo; + const int n_row = n_tile + lane_lo; + + for (int k_tile = 0; k_tile < K; k_tile += 16) { + vec_t a_frag, b_frag; + + if (m_row < T) { + __builtin_memcpy(&a_frag, X + (int64_t)m_row * K + k_tile, sizeof(a_frag)); + } else { + #pragma unroll + for (int i = 0; i < 16; ++i) a_frag[i] = 0; + } + + if (n_row < N) { + __builtin_memcpy(&b_frag, W + (int64_t)n_row * K + k_tile, sizeof(b_frag)); + } else { + #pragma unroll + for (int i = 0; i < 16; ++i) b_frag[i] = 0; + } + + c_acc = WmmaTraits::mma(a_frag, b_frag, c_acc); + } + + const int out_n = n_tile + lane_lo; + if (out_n < N) { + #pragma unroll + for (int i = 0; i < 8; ++i) { + const int out_m = m_tile + 2 * i + lane_hi; + if (out_m < T) { + float* dst = Y + (int64_t)out_m * ldy + out_n; + if (beta == 0.0f) { + *dst = c_acc[i]; + } else { + *dst = beta * (*dst) + c_acc[i]; + } + } + } + } +} + +// =========================================================================== +// Variant 2: 64x64_4w - 4 waves per block (128 threads), 64T x 64N tile. +// Double-buffered LDS tile for W (4 KB LDS total), cooperative 128-bit global loads. +// =========================================================================== +template +__global__ void gemm_wmma_64x64_4w( + const uint16_t* __restrict__ X, + const uint16_t* __restrict__ W, + float* __restrict__ Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta) { + + using vec_t = typename WmmaTraits::vec_t; + const int m_tile = blockIdx.y * 64; + const int n_tile = blockIdx.x * 64; + if (m_tile >= T || n_tile >= N) return; + + const int tid = threadIdx.x; // 0..127 + const int wave_id = tid >> 5; // 0..3 + const int lane = tid & 31; // 0..31 + const int lane_lo = lane & 15; // 0..15 + const int lane_hi = lane >> 4; // 0 or 1 + + // 4 accumulators per wave covering 4 x 16 N-subtiles + v8fp32 c_acc0 = {0, 0, 0, 0, 0, 0, 0, 0}; + v8fp32 c_acc1 = {0, 0, 0, 0, 0, 0, 0, 0}; + v8fp32 c_acc2 = {0, 0, 0, 0, 0, 0, 0, 0}; + v8fp32 c_acc3 = {0, 0, 0, 0, 0, 0, 0, 0}; + + // Double-buffered LDS tile: 64 rows of N x 16 elements of K (2 KB per buffer) + alignas(16) __shared__ ElemT b_lds[2][64][16]; + + // Thread mapping for cooperative loading of W into LDS (128 threads load 64x16 elements) + // Each thread loads 8 halfs (16 bytes = uint4) + const int row_in_tile = tid >> 1; // 0..63 + const int k_sub = (tid & 1) << 3; // 0 or 8 + const int actual_n = n_tile + row_in_tile; + + auto load_w_into_lds = [&](int buf, int k_tile) { + const int actual_k = k_tile + k_sub; + uint4 val = {0, 0, 0, 0}; + if (actual_n < N && actual_k < K) { + const void* ptr = reinterpret_cast(W + (int64_t)actual_n * K + actual_k); + val = *reinterpret_cast(ptr); + } + *reinterpret_cast(&b_lds[buf][row_in_tile][k_sub]) = val; + }; + + // Pre-fill buffer 0 + load_w_into_lds(0, 0); + __syncthreads(); + + const int m_row = m_tile + wave_id * 16 + lane_lo; + int cur_buf = 0; + + for (int k_tile = 0; k_tile < K; k_tile += 16) { + const int next_buf = 1 - cur_buf; + const int k_next = k_tile + 16; + + // Prefetch next K-tile of W into LDS + if (k_next < K) { + load_w_into_lds(next_buf, k_next); + } + + // Load A fragment from X for current wave's 16 M-rows + vec_t a_frag; + if (m_row < T) { + __builtin_memcpy(&a_frag, X + (int64_t)m_row * K + k_tile, sizeof(a_frag)); + } else { + #pragma unroll + for (int i = 0; i < 16; ++i) a_frag[i] = 0; + } + + // Read B fragments from LDS and compute WMMA + vec_t b_frag0, b_frag1, b_frag2, b_frag3; + __builtin_memcpy(&b_frag0, &b_lds[cur_buf][0 + lane_lo][0], sizeof(vec_t)); + __builtin_memcpy(&b_frag1, &b_lds[cur_buf][16 + lane_lo][0], sizeof(vec_t)); + __builtin_memcpy(&b_frag2, &b_lds[cur_buf][32 + lane_lo][0], sizeof(vec_t)); + __builtin_memcpy(&b_frag3, &b_lds[cur_buf][48 + lane_lo][0], sizeof(vec_t)); + + c_acc0 = WmmaTraits::mma(a_frag, b_frag0, c_acc0); + c_acc1 = WmmaTraits::mma(a_frag, b_frag1, c_acc1); + c_acc2 = WmmaTraits::mma(a_frag, b_frag2, c_acc2); + c_acc3 = WmmaTraits::mma(a_frag, b_frag3, c_acc3); + + __syncthreads(); + cur_buf = next_buf; + } + + // Store C to Y (coalesced 64-byte writes per wave half) + const int m_tile_wave = m_tile + wave_id * 16; + auto store_acc = [&](const v8fp32& acc, int n_base) { + const int out_n = n_base + lane_lo; + if (out_n < N) { + #pragma unroll + for (int i = 0; i < 8; ++i) { + const int out_m = m_tile_wave + 2 * i + lane_hi; + if (out_m < T) { + float* dst = Y + (int64_t)out_m * ldy + out_n; + if (beta == 0.0f) { + *dst = acc[i]; + } else { + *dst = beta * (*dst) + acc[i]; + } + } + } + } + }; + + store_acc(c_acc0, n_tile + 0); + store_acc(c_acc1, n_tile + 16); + store_acc(c_acc2, n_tile + 32); + store_acc(c_acc3, n_tile + 48); +} + +template +static inline bool strata_wmma_gemm_dispatch(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream) { + if (!X || !W || !Y) return false; + if (T <= 0 || N <= 0 || K <= 0) return false; + // Runtime gate (review): run only on gfx11 devices, whatever this build compiled for. The build-time + // STRATA_WMMA_GFX11 macro controls whether the intrinsics compile; this check controls whether they run. + { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + if (std::strncmp(prop.gcnArchName, "gfx11", 5) != 0) return false; + } + if (K % 16 != 0) return false; + if (beta != 0.0f && beta != 1.0f) return false; + if (ldy <= 0) ldy = N; + if (ldy < N) return false; + + hipStream_t s = static_cast(stream); + + if (T >= 32 && N >= 32) { + dim3 block(128); + dim3 grid((uint32_t)((N + 63) / 64), (uint32_t)((T + 63) / 64), 1); + gemm_wmma_64x64_4w<<>>(X, W, Y, T, N, K, ldy, beta); + } else { + dim3 block(32); + dim3 grid((uint32_t)((N + 15) / 16), (uint32_t)((T + 15) / 16), 1); + gemm_wmma_16x16_1w<<>>(X, W, Y, T, N, K, ldy, beta); + } + return true; +} + +bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream) { + return strata_wmma_gemm_dispatch<_Float16>(X, W, Y, T, N, K, ldy, beta, stream); +} + +bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream) { + return strata_wmma_gemm_dispatch<__bf16>(X, W, Y, T, N, K, ldy, beta, stream); +} + +// =========================================================================== +// S23 (opt-in STRATA_PF_GEMM=1): the prompt projections' FP16 GEMM on gfx11 (gfx1151: 30-33 TFLOPS on the 16K-row +// projection shapes where the tuned hipBLASLt reaches 25-27; s23/gemm_probe4.hip). Block 128 x BN (BN 256 or 128), +// BK 32, 8 waves of 64 x BN/4, LDS double buffer with the next stage prefetched into named registers (arrays there +// went to scratch), grouped tile order (8 row tiles sweep all column tiles: the weights stream from DRAM once per +// group). FP32 accumulation, K in another order than hipBLASLt: rounding-level, quality-gated. +// =========================================================================== +namespace pfg { +typedef _Float16 h16 __attribute__((ext_vector_type(16))); +typedef float f8 __attribute__((ext_vector_type(8))); +constexpr int BM = 128, BK = 32, LDK = BK + 8, GM = 8; +__device__ __forceinline__ h16 frag(const _Float16* p) { + const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(h16, w); +} +template +__global__ void __launch_bounds__(256) kernel(const _Float16* __restrict__ X, const _Float16* __restrict__ W, + float* __restrict__ Y, int M, int N, int K, int ldy, int accumulate, + int ldx, int ldw) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int TN = WN / 16, NB = BN / 64; + __shared__ __align__(16) _Float16 sA[2][BM][LDK]; + __shared__ __align__(16) _Float16 sB[2][BN][LDK]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave & 1, wn = wave >> 1; + const int num_m = (M + BM - 1) / BM, num_n = (N + BN - 1) / BN, b = blockIdx.x; + const int group = b / (GM * num_n), first_m = group * GM, gsize = min(GM, num_m - first_m); + const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; + const int sr = tid >> 2, sq = tid & 3; + auto ldA = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * sq); + }; + auto ldB = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(W + (size_t) min(n0 + r, N - 1) * ldw + k0 + 8 * sq); + }; + f8 acc[4][TN]; + for (int i = 0; i < 4; ++i) for (int j = 0; j < TN; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + uint4 ra0 = ldA(0, sr), ra1 = ldA(0, sr + 64), rb0 = ldB(0, sr), rb1 = ldB(0, sr + 64), rb2 = rb0, rb3 = rb0; + if constexpr (NB > 2) { rb2 = ldB(0, sr + 128); rb3 = ldB(0, sr + 192); } + int buf = 0; + *reinterpret_cast(&sA[0][sr][8 * sq]) = ra0; *reinterpret_cast(&sA[0][sr + 64][8 * sq]) = ra1; + *reinterpret_cast(&sB[0][sr][8 * sq]) = rb0; *reinterpret_cast(&sB[0][sr + 64][8 * sq]) = rb1; + if constexpr (NB > 2) { *reinterpret_cast(&sB[0][sr + 128][8 * sq]) = rb2; *reinterpret_cast(&sB[0][sr + 192][8 * sq]) = rb3; } + __syncthreads(); + for (int k0 = 0; k0 < K; k0 += BK) { + const bool more = k0 + BK < K; + if (more) { + ra0 = ldA(k0 + BK, sr); ra1 = ldA(k0 + BK, sr + 64); rb0 = ldB(k0 + BK, sr); rb1 = ldB(k0 + BK, sr + 64); + if constexpr (NB > 2) { rb2 = ldB(k0 + BK, sr + 128); rb3 = ldB(k0 + BK, sr + 192); } + } +#pragma unroll + for (int ks = 0; ks < BK; ks += 16) { + h16 a[4], bb[TN]; +#pragma unroll + for (int i = 0; i < 4; ++i) a[i] = frag(&sA[buf][64 * wm + 16 * i + l16][ks]); +#pragma unroll + for (int j = 0; j < TN; ++j) bb[j] = frag(&sB[buf][WN * wn + 16 * j + l16][ks]); +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a[i], bb[j], acc[i][j]); + } + if (more) { + const int nb = buf ^ 1; + *reinterpret_cast(&sA[nb][sr][8 * sq]) = ra0; *reinterpret_cast(&sA[nb][sr + 64][8 * sq]) = ra1; + *reinterpret_cast(&sB[nb][sr][8 * sq]) = rb0; *reinterpret_cast(&sB[nb][sr + 64][8 * sq]) = rb1; + if constexpr (NB > 2) { *reinterpret_cast(&sB[nb][sr + 128][8 * sq]) = rb2; *reinterpret_cast(&sB[nb][sr + 192][8 * sq]) = rb3; } + __syncthreads(); + buf = nb; + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int n = n0 + WN * wn + 16 * j + l16; + if (n >= N) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 64 * wm + 16 * i + 2 * e + hi; + if (m < M) { + float* y = Y + (size_t) m * ldy + n; + *y = accumulate ? *y + acc[i][j][e] : acc[i][j][e]; + } + } + } +#endif +} +// The 128 x 256 kernel with a 64-k LDS tile (single buffer, the next tile in 12 named staging registers, 2 barriers +// per tile: half the loop trips and barriers per k of the BK 32 double buffer). Each accumulator takes the same +// WMMAs in the same k order as `kernel`: the same bits (s23/gemm_probe11.hip, memcmp). gfx1151, M 16384, both +// operands padded: 38.0 -> 41.3 TFLOPS (N 2560 K 6144), 38.9 -> 40.9 (N 12288 K 2560), 40.3 -> 40.4 (N 10240). +// K a multiple of 64. +__global__ void __launch_bounds__(256) kernel_bk64(const _Float16* __restrict__ X, const _Float16* __restrict__ W, + float* __restrict__ Y, int M, int N, int K, int ldy, int accumulate, + int ldx, int ldw) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int BN = 256, WN = 64, BK64 = 64, LDK64 = BK64 + 8; + __shared__ __align__(16) _Float16 sA[BM][LDK64]; + __shared__ __align__(16) _Float16 sB[BN][LDK64]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave & 1, wn = wave >> 1; + const int num_m = (M + BM - 1) / BM, num_n = (N + BN - 1) / BN, b = blockIdx.x; + const int group = b / (GM * num_n), first_m = group * GM, gsize = min(GM, num_m - first_m); + const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; + const int sr = tid >> 3, sq = tid & 7; // 32 rows per pass, 8 x 8 halves per row + auto ldA = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * sq); + }; + auto ldB = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(W + (size_t) min(n0 + r, N - 1) * ldw + k0 + 8 * sq); + }; + uint4 ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3, rb4, rb5, rb6, rb7; + auto load = [&](int k0) { + ra0 = ldA(k0, sr); ra1 = ldA(k0, sr + 32); ra2 = ldA(k0, sr + 64); ra3 = ldA(k0, sr + 96); + rb0 = ldB(k0, sr); rb1 = ldB(k0, sr + 32); rb2 = ldB(k0, sr + 64); rb3 = ldB(k0, sr + 96); + rb4 = ldB(k0, sr + 128); rb5 = ldB(k0, sr + 160); rb6 = ldB(k0, sr + 192); rb7 = ldB(k0, sr + 224); + }; + auto store = [&]() { + *reinterpret_cast(&sA[sr][8 * sq]) = ra0; *reinterpret_cast(&sA[sr + 32][8 * sq]) = ra1; + *reinterpret_cast(&sA[sr + 64][8 * sq]) = ra2; *reinterpret_cast(&sA[sr + 96][8 * sq]) = ra3; + *reinterpret_cast(&sB[sr][8 * sq]) = rb0; *reinterpret_cast(&sB[sr + 32][8 * sq]) = rb1; + *reinterpret_cast(&sB[sr + 64][8 * sq]) = rb2; *reinterpret_cast(&sB[sr + 96][8 * sq]) = rb3; + *reinterpret_cast(&sB[sr + 128][8 * sq]) = rb4; *reinterpret_cast(&sB[sr + 160][8 * sq]) = rb5; + *reinterpret_cast(&sB[sr + 192][8 * sq]) = rb6; *reinterpret_cast(&sB[sr + 224][8 * sq]) = rb7; + }; + f8 acc[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + load(0); + store(); + __syncthreads(); + const int ar = 64 * wm + l16, br = WN * wn + l16; + for (int k0 = 0; k0 < K; k0 += BK64) { + const bool more = k0 + BK64 < K; + if (more) load(k0 + BK64); +#pragma unroll + for (int ks = 0; ks < BK64; ks += 16) { + const h16 a0 = frag(&sA[ar][ks]), a1 = frag(&sA[ar + 16][ks]), a2 = frag(&sA[ar + 32][ks]), + a3 = frag(&sA[ar + 48][ks]); + const h16 b0 = frag(&sB[br][ks]), b1 = frag(&sB[br + 16][ks]), b2 = frag(&sB[br + 32][ks]), + b3 = frag(&sB[br + 48][ks]); +#define PFG_ROW(i, a) \ + acc[i][0] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b0, acc[i][0]); \ + acc[i][1] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b1, acc[i][1]); \ + acc[i][2] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b2, acc[i][2]); \ + acc[i][3] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b3, acc[i][3]); + PFG_ROW(0, a0) PFG_ROW(1, a1) PFG_ROW(2, a2) PFG_ROW(3, a3) +#undef PFG_ROW + } + if (more) { + __syncthreads(); // every wave is done reading the tile + store(); + __syncthreads(); + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int n = n0 + WN * wn + 16 * j + l16; + if (n >= N) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 64 * wm + 16 * i + 2 * e + hi; + if (m < M) { + float* y = Y + (size_t) m * ldy + n; + *y = accumulate ? *y + acc[i][j][e] : acc[i][j][e]; + } + } + } +#endif +} +// S23 (STRATA_PF_HCDOWN=1): the hyper-connection read's down (N nd = 320) and inject (N ni = 4) projections of xn16 +// (BF16, T x 10240, token stride ldx: 10240 + 64 avoids the 4 KB-multiple stride) as ONE GEMM - weight rows +// [w_down; w_inject] read from the two tensors, the epilogue splitting the columns into lo (T x nd) and inj (T x ni), +// so xn16 is read once. 128 x 128 blocks, the BK 64 single-buffer scheme of kernel_bk64. s23/hcdown_probe.hip, +// 16K tokens: 3.60 / 3.77 ms (hipBLASLt in the engine: down 6.78 + inject 1.81). FP32 accumulation in another k +// order than hipBLASLt: rounding-level. +typedef __bf16 hb16 __attribute__((ext_vector_type(16))); +__device__ __forceinline__ hb16 bfrag(const uint16_t* p) { + const uint4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(hb16, w); +} +__global__ void __launch_bounds__(256) kernel_hcdown(const uint16_t* __restrict__ X, int ldx, + const uint16_t* __restrict__ Wd, const uint16_t* __restrict__ Wi, + int nd, int ni, float* __restrict__ lo, float* __restrict__ inj, + int M, int K) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int BN = 128, WN = 32, TN = 2, BK64 = 64, LDK64 = BK64 + 8; + __shared__ __align__(16) uint16_t sA[BM][LDK64]; + __shared__ __align__(16) uint16_t sB[BN][LDK64]; + const int N = nd + ni; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave & 1, wn = wave >> 1; + const int num_m = (M + BM - 1) / BM, num_n = (N + BN - 1) / BN, b = blockIdx.x; + const int group = b / (GM * num_n), first_m = group * GM, gsize = min(GM, num_m - first_m); + const int m0 = (first_m + (b % (GM * num_n)) % gsize) * BM, n0 = ((b % (GM * num_n)) / gsize) * BN; + const int sr = tid >> 3, sq = tid & 7; + auto ldA = [&](int k0, int r) -> uint4 { + return *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * sq); + }; + auto ldB = [&](int k0, int r) -> uint4 { + const int n = min(n0 + r, N - 1); + const uint16_t* row = n < nd ? Wd + (size_t) n * K : Wi + (size_t) (n - nd) * K; + return *reinterpret_cast(row + k0 + 8 * sq); + }; + uint4 ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3; + auto load = [&](int k0) { + ra0 = ldA(k0, sr); ra1 = ldA(k0, sr + 32); ra2 = ldA(k0, sr + 64); ra3 = ldA(k0, sr + 96); + rb0 = ldB(k0, sr); rb1 = ldB(k0, sr + 32); rb2 = ldB(k0, sr + 64); rb3 = ldB(k0, sr + 96); + }; + auto store = [&]() { + *reinterpret_cast(&sA[sr][8 * sq]) = ra0; *reinterpret_cast(&sA[sr + 32][8 * sq]) = ra1; + *reinterpret_cast(&sA[sr + 64][8 * sq]) = ra2; *reinterpret_cast(&sA[sr + 96][8 * sq]) = ra3; + *reinterpret_cast(&sB[sr][8 * sq]) = rb0; *reinterpret_cast(&sB[sr + 32][8 * sq]) = rb1; + *reinterpret_cast(&sB[sr + 64][8 * sq]) = rb2; *reinterpret_cast(&sB[sr + 96][8 * sq]) = rb3; + }; + f8 acc[4][TN]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + load(0); + store(); + __syncthreads(); + const int ar = 64 * wm + l16, br = WN * wn + l16; + for (int k0 = 0; k0 < K; k0 += BK64) { + const bool more = k0 + BK64 < K; + if (more) load(k0 + BK64); +#pragma unroll + for (int ks = 0; ks < BK64; ks += 16) { + const hb16 a0 = bfrag(&sA[ar][ks]), a1 = bfrag(&sA[ar + 16][ks]), a2 = bfrag(&sA[ar + 32][ks]), + a3 = bfrag(&sA[ar + 48][ks]); + const hb16 b0 = bfrag(&sB[br][ks]), b1 = bfrag(&sB[br + 16][ks]); + acc[0][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a0, b0, acc[0][0]); + acc[1][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a1, b0, acc[1][0]); + acc[2][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a2, b0, acc[2][0]); + acc[3][0] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a3, b0, acc[3][0]); + acc[0][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a0, b1, acc[0][1]); + acc[1][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a1, b1, acc[1][1]); + acc[2][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a2, b1, acc[2][1]); + acc[3][1] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a3, b1, acc[3][1]); + } + if (more) { + __syncthreads(); + store(); + __syncthreads(); + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int n = n0 + WN * wn + 16 * j + l16; + if (n >= N) continue; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 64 * wm + 16 * i + 2 * e + hi; + if (m < M) { + if (n < nd) lo[(size_t) m * nd + n] = acc[i][j][e]; + else inj[(size_t) m * ni + (n - nd)] = acc[i][j][e]; + } + } + } +#endif +} + +// S23/S (STRATA_HCD_EXACT=1): the HC down projection (N 320, K 10240, BF16 in, FP32 out) bitwise equal to hipBLASLt +// solution 1176 / 1177 (MT32x96 / MT96x96, StaggerU 32, stride 256 B): every output is the k tiles of 32 accumulated in +// order, 16 per WMMA, starting at k tile 4 * (token tile of 96 % 32) and wrapping (hcd_bit / hcd_perm probes: 0 of +// 5.2 M outputs differ at T 16384). 96 x 160 blocks (two per token tile), 6 waves of 32 x 80. +typedef uint32_t hx_u4 __attribute__((ext_vector_type(4))); +constexpr int HX_N = 320, HX_BN = 160, HX_BM = 96, HX_BK = 64, HX_LDK = HX_BK + 8, HX_NT = 192, HX_K = 10240; +__device__ __forceinline__ hb16 hx_frag(const uint16_t* p) { + const hx_u4 a = *reinterpret_cast(p), b = *reinterpret_cast(p + 8); + const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w}; + return __builtin_bit_cast(hb16, w); +} +__global__ void __launch_bounds__(HX_NT) kernel_hcd_exact(const uint16_t* __restrict__ X, int ldx, + const uint16_t* __restrict__ W, float* __restrict__ Y, int M) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__) + constexpr int K = HX_K, BN = HX_BN, BMT = HX_BM, BK = HX_BK, NT = HX_NT; + __shared__ __align__(16) uint16_t sA[BMT][HX_LDK]; + __shared__ __align__(16) uint16_t sB[BN][HX_LDK]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4; + const int wm = wave % 3, wn = wave / 3, nbase = BN * (blockIdx.x & 1); + const int tt = blockIdx.x >> 1, m0 = tt * BMT; + constexpr int nslab = K / BK; + const int rot = (2 * (tt & 31)) % nslab; // 4 k tiles of 32 = 2 slabs of 64 + hx_u4 ra0, ra1, ra2, ra3, rb0, rb1, rb2, rb3, rb4, rb5, rb6; +#define HX_LDA(v, i) { const int idx = tid + NT * (i), r = idx >> 3, q = idx & 7; v = *reinterpret_cast(X + (size_t) min(m0 + r, M - 1) * ldx + k0 + 8 * q); } +#define HX_LDB(v, i) { const int idx = min(tid + NT * (i), BN * 8 - 1), r = idx >> 3, q = idx & 7; v = *reinterpret_cast(W + (size_t) (nbase + r) * K + k0 + 8 * q); } +#define HX_STA(v, i) { const int idx = tid + NT * (i); *reinterpret_cast(&sA[idx >> 3][8 * (idx & 7)]) = v; } +#define HX_STB(v, i) { const int idx = tid + NT * (i); if (idx < BN * 8) *reinterpret_cast(&sB[idx >> 3][8 * (idx & 7)]) = v; } +#define HX_LOAD(k0v) { const int k0 = (k0v); HX_LDA(ra0, 0) HX_LDA(ra1, 1) HX_LDA(ra2, 2) HX_LDA(ra3, 3) HX_LDB(rb0, 0) HX_LDB(rb1, 1) HX_LDB(rb2, 2) HX_LDB(rb3, 3) HX_LDB(rb4, 4) HX_LDB(rb5, 5) HX_LDB(rb6, 6) } +#define HX_STORE() { HX_STA(ra0, 0) HX_STA(ra1, 1) HX_STA(ra2, 2) HX_STA(ra3, 3) HX_STB(rb0, 0) HX_STB(rb1, 1) HX_STB(rb2, 2) HX_STB(rb3, 3) HX_STB(rb4, 4) HX_STB(rb5, 5) HX_STB(rb6, 6) } + f8 acc[2][5]; +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 5; ++j) acc[i][j] = f8{0, 0, 0, 0, 0, 0, 0, 0}; + HX_LOAD(rot * BK); + HX_STORE(); + __syncthreads(); + const int ar = 32 * wm + l16, br = 80 * wn + l16; + for (int s = 0; s < nslab; ++s) { + const bool more = s + 1 < nslab; + if (more) HX_LOAD(((s + 1 + rot) % nslab) * BK); +#pragma unroll + for (int ks = 0; ks < BK; ks += 16) { + const hb16 a0 = hx_frag(&sA[ar][ks]), a1 = hx_frag(&sA[ar + 16][ks]); + const hb16 b0 = hx_frag(&sB[br][ks]), b1 = hx_frag(&sB[br + 16][ks]), b2 = hx_frag(&sB[br + 32][ks]), + b3 = hx_frag(&sB[br + 48][ks]), b4 = hx_frag(&sB[br + 64][ks]); +#define HX_W2(j, bj) acc[0][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a0, bj, acc[0][j]); acc[1][j] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a1, bj, acc[1][j]); + HX_W2(0, b0) HX_W2(1, b1) HX_W2(2, b2) HX_W2(3, b3) HX_W2(4, b4) +#undef HX_W2 + } + if (more) { + __syncthreads(); + HX_STORE(); + __syncthreads(); + } + } +#undef HX_LDA +#undef HX_LDB +#undef HX_STA +#undef HX_STB +#undef HX_LOAD +#undef HX_STORE +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 5; ++j) { + const int n = nbase + 80 * wn + 16 * j + l16; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int m = m0 + 32 * wm + 16 * i + 2 * e + hi; + if (m < M) Y[(size_t) m * HX_N + n] = acc[i][j][e]; + } + } +#endif +} +} // namespace pfg + +bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, const uint16_t* Wi, int64_t nd, + int64_t ni, float* lo, float* inj, int64_t T, int64_t K, void* stream) { + if (!X || !Wd || !Wi || !lo || !inj || T < 64 || nd < 1 || ni < 0 || K % 64 != 0 || ldx < K || ldx % 8 != 0) return false; + if (T > (1LL << 30) || K > (1LL << 30) || ldx > (1LL << 30)) return false; + static const bool gfx11 = [] { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + return std::strncmp(prop.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11) return false; + const int64_t mt = (T + pfg::BM - 1) / pfg::BM; + const unsigned grid = (unsigned) (mt * ((nd + ni + 127) / 128)); + pfg::kernel_hcdown<<(stream)>>>(X, (int) ldx, Wd, Wi, (int) nd, (int) ni, + lo, inj, (int) T, (int) K); + return hipGetLastError() == hipSuccess; +} + +bool strata_pf_hcdown_exact_bf16(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, + int64_t K, void* stream) { + if (!X || !W || !Y || T < 1 || N != pfg::HX_N || K != pfg::HX_K || ldx < K || ldx % 8 != 0 || ldx > (1LL << 30) || + T > (1LL << 30)) + return false; + static const bool gfx11 = [] { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + return std::strncmp(prop.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11) return false; + const unsigned grid = (unsigned) (2 * ((T + pfg::HX_BM - 1) / pfg::HX_BM)); + pfg::kernel_hcd_exact<<(stream)>>>(X, (int) ldx, W, Y, (int) T); + return hipGetLastError() == hipSuccess; +} + +bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta, void* stream) { + return strata_pf_gemm_f16_ld(X, K, W, K, Y, T, N, K, ldy, beta, stream); +} + +bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, int64_t ldw, float* Y, int64_t T, + int64_t N, int64_t K, int64_t ldy, float beta, void* stream) { + if (!X || !W || !Y || T < 64 || N < 512 || K % pfg::BK != 0 || K < pfg::BK) return false; + if (beta != 0.0f && beta != 1.0f) return false; + if (ldy <= 0) ldy = N; + if (ldx < K || ldw < K || ldx % 8 != 0 || ldw % 8 != 0 || ldx > (1LL << 30) || ldw > (1LL << 30)) return false; + if (ldy < N || T > (1LL << 30) || N > (1LL << 30) || K > (1LL << 30)) return false; + static const bool gfx11 = [] { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return false; + return std::strncmp(prop.gcnArchName, "gfx11", 5) == 0; + }(); + if (!gfx11) return false; + hipStream_t s = static_cast(stream); + const int acc = beta == 1.0f ? 1 : 0; + const int64_t mt = (T + pfg::BM - 1) / pfg::BM; + // STRATA_PF_BK64=0: the BK 32 kernel for the wide shapes too (the A/B; the same bits) + static const bool bk64 = [] { const char* v = std::getenv("STRATA_PF_BK64"); return !v || v[0] != '0'; }(); + if (N >= 1024 && bk64 && K % 64 == 0) { + const unsigned grid = (unsigned) (mt * ((N + 255) / 256)); + pfg::kernel_bk64<<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, + (int) ldy, acc, (int) ldx, (int) ldw); + } else if (N >= 1024) { + const unsigned grid = (unsigned) (mt * ((N + 255) / 256)); + pfg::kernel<256, 64><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, + (int) ldy, acc, (int) ldx, (int) ldw); + } else { + const unsigned grid = (unsigned) (mt * ((N + 127) / 128)); + pfg::kernel<128, 32><<>>((const _Float16*) X, (const _Float16*) W, Y, (int) T, (int) N, (int) K, + (int) ldy, acc, (int) ldx, (int) ldw); + } + return hipGetLastError() == hipSuccess; +} + +#else +// Non-HIP / Non-GFX11 compilation fallback +bool strata_pf_gemm_f16(const uint16_t*, const uint16_t*, float*, int64_t, int64_t, int64_t, int64_t, float, void*) { + return false; +} +bool strata_pf_gemm_f16_ld(const uint16_t*, int64_t, const uint16_t*, int64_t, float*, int64_t, int64_t, int64_t, + int64_t, float, void*) { + return false; +} +bool strata_pf_hcdown_bf16(const uint16_t*, int64_t, const uint16_t*, const uint16_t*, int64_t, int64_t, float*, float*, + int64_t, int64_t, void*) { + return false; +} +bool strata_pf_hcdown_exact_bf16(const uint16_t*, int64_t, const uint16_t*, float*, int64_t, int64_t, int64_t, void*) { + return false; +} +bool strata_wmma_gemm_f16(const uint16_t*, const uint16_t*, float*, + int64_t, int64_t, int64_t, int64_t, float, + void*) { + return false; +} + +bool strata_wmma_gemm_bf16(const uint16_t*, const uint16_t*, float*, + int64_t, int64_t, int64_t, int64_t, float, + void*) { + return false; +} +#endif diff --git a/src/prefill/wmma_gemm.h b/src/prefill/wmma_gemm.h new file mode 100644 index 00000000..1e54e911 --- /dev/null +++ b/src/prefill/wmma_gemm.h @@ -0,0 +1,41 @@ +// src/prefill/wmma_gemm.h - RDNA3 WMMA FP16 & BF16 GEMM for Strata prefill. +#pragma once + +#include + +/// Compute Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA instructions. +/// X: T x K row-major (leading dim K), fp16 (uint16_t) +/// W: N x K row-major (leading dim K), fp16 (uint16_t) +/// Y: T x N row-major with leading dimension ldy >= N, fp32 (float) +/// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas). +bool strata_wmma_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream = nullptr); + +/// Compute Y[t, n] = beta * Y[t, n] + sum_k W[n, k] * X[t, k] using RDNA3 WMMA instructions. +/// X: T x K row-major (leading dim K), bf16 (uint16_t) +/// W: N x K row-major (leading dim K), bf16 (uint16_t) +/// Y: T x N row-major with leading dimension ldy >= N, fp32 (float) +/// Returns true if executed on WMMA, false if unsupported shape/parameters (fall back to hipblas). +/// S23 (opt-in STRATA_PF_GEMM=1): Y = beta * Y + X . W^T, FP16 in, FP32 out, beta 0 or 1, K a multiple of 32, +/// T >= 64, N >= 512; the 128 x 256 / 128 x 128 grouped-order WMMA kernel. False (nothing launched) otherwise / off gfx11. +bool strata_pf_gemm_f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta, void* stream = nullptr); +/// The same with row strides ldx >= K and ldw >= K (multiples of 8): a 4 KB-multiple row stride (K 2048 / 4096 / +/// 6144) camps on the memory channels, K + 64 does not (S23 gemm_probe7/8: K 6144 19 -> 35 TFLOPS). +/// S23 (STRATA_PF_HCDOWN=1): lo[t, n] = sum_k X[t, k] Wd[n, k] (n < nd) and inj[t, n] = sum_k X[t, k] Wi[n, k] +/// (n < ni) in one BF16 WMMA GEMM over X (T x K, token stride ldx >= K, a multiple of 8; Wd / Wi row-major, stride +/// K); lo T x nd and inj T x ni, FP32. K a multiple of 64, T >= 64. False (nothing launched) otherwise / off gfx11. +bool strata_pf_hcdown_bf16(const uint16_t* X, int64_t ldx, const uint16_t* Wd, const uint16_t* Wi, int64_t nd, + int64_t ni, float* lo, float* inj, int64_t T, int64_t K, void* stream = nullptr); +/// S (STRATA_HCD_EXACT=1): Y[t, n] = sum_k X[t, k] W[n, k] for N 320, K 10240 (BF16, FP32 out, X token stride ldx >= K, a +/// multiple of 8), bitwise equal to hipBLASLt solution 1176 / 1177 for that shape (its k order, StaggerU included). +/// False (nothing launched) for any other shape / off gfx11. +bool strata_pf_hcdown_exact_bf16(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, + int64_t K, void* stream = nullptr); +bool strata_pf_gemm_f16_ld(const uint16_t* X, int64_t ldx, const uint16_t* W, int64_t ldw, float* Y, int64_t T, + int64_t N, int64_t K, int64_t ldy, float beta, void* stream = nullptr); + +bool strata_wmma_gemm_bf16(const uint16_t* X, const uint16_t* W, float* Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + void* stream = nullptr); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 085c3d8c..04b8041f 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -55,6 +55,7 @@ #include "strata/program/logits_selection.hpp" #include "strata/program/conv_cache.hpp" #include "strata/spec/draft_policy.hpp" +#include "strata/spec/draft_source.hpp" #include "strata/spec/suffix_drafter.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" @@ -526,6 +527,18 @@ struct Options { int suffix_draft = 3; /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. int mtp_max_t = 0; + /// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches + /// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same + /// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept. + int lookup_chain = 0; + int lookup_chain_min = 3; ///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on + /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on + /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). + bool mtp_hnorm_stream = false; + /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step) + std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only) + /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of /draft_vocab.bin + std::string mtp_draft_vocab; /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. @@ -633,6 +646,13 @@ void usage() { " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" + " --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n" + " them (the window grows to at most 8; default 0 = off)\n" + " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" + " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" + " (default) or one per stream (llama.cpp's MTP graph)\n" + " --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n" + " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" @@ -718,6 +738,23 @@ void usage() { " does not fit. Same answers as --mmap-experts for the same placement.\n"); } +// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last +int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector& tail) { + const std::vector& h = sfx.history(); + const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending)); + tail.assign(h.end() - keep, h.end()); + tail.insert(tail.end(), pending, pending + n_pending); + return (int) tail.size(); +} + +// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too +void extra_sources_reset() { + for (auto& src : strata::spec::extra_draft_sources()) src->reset(); +} +void extra_sources_append(const int32_t* t, size_t n) { + for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n); +} + bool parse_i64_list(const char* s, std::vector& out, std::string& err) { out.clear(); std::string text(s); @@ -1435,6 +1472,24 @@ int main(int argc, char** argv) { else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); + else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7); + else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min"))); + else if (a == "--mtp-hnorm") { + const std::string v = next("--mtp-hnorm"); + if (v != "pooled" && v != "stream") { + std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n"); + return 2; + } + o.mtp_hnorm_stream = v == "stream"; + } + else if (a == "--mtp-q4") { + o.mtp_q4 = next("--mtp-q4"); + if (o.mtp_q4 != "all" && o.mtp_q4 != "proj" && o.mtp_q4 != "head") { + std::fprintf(stderr, "strata generate: --mtp-q4 takes all, proj or head\n"); + return 2; + } + } + else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab"); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive @@ -1778,6 +1833,11 @@ int main(int argc, char** argv) { o.mtp_max_t = o.spec; o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT } + // --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K + if (o.lookup_chain > 0 && o.spec >= 2) { + if (o.mtp_max_t == 0) o.mtp_max_t = o.spec; + o.spec = std::max(o.spec, std::min(o.mtp_max_t + o.lookup_chain, 8)); // kVerifyMaxT + } strata::core::layer_set_shared_early(!o.shared_late); if (!o.native_preset.empty()) { try { @@ -3008,6 +3068,9 @@ int main(int argc, char** argv) { o.mtp.clear(); } if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); + mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture + mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load + if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab); // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference static const strata::core::ModelGeometry draft_geometry{}; @@ -3205,7 +3268,7 @@ int main(int argc, char** argv) { bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; // Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - // under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is @@ -3278,7 +3341,7 @@ int main(int argc, char** argv) { // fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends // slots instead and `prefill_mib` is 0, so only the reserve is checked) size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20; const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); @@ -3298,7 +3361,7 @@ int main(int argc, char** argv) { std::vector sized_slots; if (native_pack && o.expert_cache > 0 && !profile.empty() && !o.expert_cache_per_layer) { size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; const auto& lay = strata::kernels::cpu::expert_layout(); const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted uint64_t used = 0; @@ -3402,7 +3465,7 @@ int main(int argc, char** argv) { cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes()); cudaDeviceSynchronize(); size_t free_b = 0, total_b = 0; - cudaMemGetInfo(&free_b, &total_b); + free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t want = (int64_t) o.vram_reserve_mib << 20; if ((int64_t) free_b >= want - (64ll << 20)) break; // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB @@ -7050,12 +7113,22 @@ int main(int argc, char** argv) { std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); std::vector dprob((size_t) S, 0.0f); std::vector sbuf((size_t) S, 0); - if (o.suffix_draft > 0) { + const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; + if (sfx_on) { sfx.reset(); for (int64_t t : ids) sfx.append((int32_t) t); } + if (o.lookup_chain > 0) { + extra_sources_reset(); + for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } + } bool first_window = true; int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; + int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts + int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits + std::vector cbuf((size_t) S, 0), ctail; + strata::spec::PromptLookupSource lookup_src(sfx); + static const bool chain_fixed = std::getenv("STRATA_LOOKUP_CHAIN_FIXED") != nullptr; // no policy gate int64_t draft_offered = 0, draft_accepted = 0; // what the session holds once this request is done: the prompt read so far, then every committed token std::vector consumed; @@ -7103,11 +7176,29 @@ int main(int argc, char** argv) { if (pk.lookup) { T = pk.t; from_sfx = true; } } } + // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them + int chain_n = 0, cm = 0; + if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) { + int csrc = -1; + const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); + chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, + std::min(o.lookup_chain, S - T), o.lookup_chain_min, + cbuf.data(), &cm, &csrc); + // the policy keeps the chained tokens that pay at this machine's measured window costs + if (chain_n > 0 && !chain_fixed) { + double p_mtp = 1.0; + for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i]; + chain_n = policy.chain(T, p_mtp, chain_n, cm); + } + } + const int T_mtp = T; + T += chain_n; const bool timed_round = !first_window; const Clock::time_point round0 = Clock::now(); if (p + T > o.max_context) break; window[0] = x; - for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; + for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; + for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i]; drive.d.layers = 0; drive.d.experts = 0; drive.d.failed = false; @@ -7135,6 +7226,11 @@ int main(int argc, char** argv) { int a = 0; while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } + if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } + if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) { + ++t2_rej[a]; + if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a]; + } const Clock::time_point tw1 = Clock::now(); std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate) bool adapt_ok = true; @@ -7155,7 +7251,8 @@ int main(int argc, char** argv) { std::printf("T %d\n", (int) outv[(size_t) i]); strata::core::progress_beat(); ++produced_n; - if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); + if (sfx_on) sfx.append(outv[(size_t) i]); + if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1); eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); } std::fflush(stdout); @@ -7182,9 +7279,12 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } - if (timed_round && !eos) + if (timed_round && !eos && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, std::chrono::duration(Clock::now() - round0).count()); + else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost + policy.observe_chain(T_mtp, chain_n, a, cm, + std::chrono::duration(Clock::now() - round0).count()); if (eos) { finish = "stop"; break; } if (stop_req.load()) { finish = "cancel"; break; } x = outv[(size_t) a]; @@ -7340,14 +7440,22 @@ int main(int argc, char** argv) { // [prompt tokens read] (#471: fewer than - when a cancel stopped the read) // [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed; // not in [lookups]) - if (yielded_at >= 0) std::printf("YIELDED %d %lld\n", yielded_slot, (long long) yielded_at); - std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld\n", + // [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows] + // (only with --lookup-chain) + char chain_txt[128] = ""; + if (o.lookup_chain > 0) + std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok, + (long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows); + if (yielded_at >= 0) std::printf("YIELDED %d %lld +", yielded_slot, (long long) yielded_at); + std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s +", (long long) produced_n, (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) resume, (long long) req_hits, (long long) req_look, (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, - (long long) req_offload); + (long long) req_offload, chain_txt); std::fflush(stdout); if (admit_slot >= 0) { // --batch: BADM <1 = continues in the batch windows | 0 = done> bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 && @@ -7452,6 +7560,14 @@ int main(int argc, char** argv) { if (sfx_windows > 0) std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n", (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); + if (o.lookup_chain > 0) + std::fprintf(stderr, "strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n", + (long long) chain_windows, (long long) dec_windows, (long long) chain_ok, (long long) chain_drafts); + if (strata::core::MtpDrafter::top2_env()) + std::fprintf(stderr, "strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld " + "of %lld windows\n", (long long) t2_rej[0], (long long) t2_hit[0], (long long) t2_rej[1], + (long long) t2_hit[1], (long long) t2_rej[2], (long long) t2_hit[2], (long long) t2_rej[3], + (long long) t2_hit[3], (long long) dec_windows); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned " "(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms " @@ -7991,10 +8107,19 @@ int main(int argc, char** argv) { strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp) std::vector sbuf((size_t) o.spec, 0); int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; - if (o.suffix_draft > 0) { + int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts + std::vector cbuf((size_t) o.spec, 0), ctail; + strata::spec::PromptLookupSource lookup_src(sfx); + const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; + if (sfx_on) { for (int64_t t : o.tokens) sfx.append((int32_t) t); for (int64_t t : produced) sfx.append((int32_t) t); } + if (o.lookup_chain > 0) { + extra_sources_reset(); + for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } + for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); } + } const double pool_ms0 = drive.cpu_ms; const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries; while ((int64_t) produced.size() < o.max_new) { @@ -8015,6 +8140,22 @@ int main(int argc, char** argv) { if (pk.lookup) { T = pk.t; from_sfx = true; } } } + // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them + int chain_n = 0, cm = 0; + if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) { + int csrc = -1; + const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail); + chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1, + std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min, + cbuf.data(), &cm, &csrc); + if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) { + double p_mtp = 1.0; + for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i]; + chain_n = policy.chain(T, p_mtp, chain_n, cm); + } + } + const int T_mtp = T; + T += chain_n; const bool timed_round = !first_window; ++window_hist[(size_t) T]; if (p + T > o.max_context) { @@ -8026,6 +8167,7 @@ int main(int argc, char** argv) { const size_t at = produced.size() - 1 + (size_t) i; int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1] : at < oracle.size() ? (int32_t) oracle[at] : 0; + if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)]; if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab; window[(size_t) i] = d; } @@ -8078,10 +8220,12 @@ int main(int argc, char** argv) { drafts_ok += a; ++accepted_hist[(size_t) a]; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } + if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } bool eos = false; for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) { produced.push_back(outv[(size_t) i]); - if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); + if (sfx_on) sfx.append(outv[(size_t) i]); + if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1); eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); } if (eos) { @@ -8101,7 +8245,8 @@ int main(int argc, char** argv) { p += a + 1; const double round_ms = std::chrono::duration(Clock::now() - t0).count(); total_ms += round_ms; - if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms); + if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); + else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms); if (rounds % 64 == 0) std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); @@ -8123,6 +8268,9 @@ int main(int argc, char** argv) { if (o.suffix_draft > 0) std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); + if (o.lookup_chain > 0) + std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain", + (long long) chain_windows, (long long) chain_ok, (long long) chain_drafts); std::printf("%-24s", "accepted per round"); for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]); std::printf("\n"); diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 1ac77198..858f4a56 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -98,4 +98,49 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro } } +double DraftPolicy::chain_rate(int match) const { + // prior: a chained draft is a lookup continuing the MTP's drafts - weaker evidence than a plain match of that length + constexpr double kChainPrior[kBuckets] = {0.45, 0.65, 0.8, 0.9}; + const int b = bucket(match); + return (cok_[b] + kPriorN * kChainPrior[b]) / (cok_[b] + cbad_[b] + kPriorN); +} + +int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const { + t_mtp = std::clamp(t_mtp, 1, max_t_); + const int kmax = std::min(k_avail, max_t_ - t_mtp); + if (kmax <= 0) return 0; + const double e0 = mtp_tokens(t_mtp), base = e0 / cost_ms(t_mtp), c = chain_rate(match); + p_mtp = std::clamp(p_mtp, 0.0, 1.0); + double gain = 0.0, ci = 1.0, best = 0.0; + int best_k = 0; + for (int k = 1; k <= kmax; ++k) { + ci *= c; + gain += ci; + const double r = (e0 + p_mtp * gain) / cost_ms(t_mtp + k); + if (r > best) { best = r; best_k = k; } + } + if (best_k > 0 && best > base * (1.0 + margin_)) return best_k; + // as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely + const int t_full = t_mtp + kmax; + if (cost_n_[t_full] < kProbes && p_mtp * c >= 0.6) return kmax; + return 0; +} + +void DraftPolicy::observe_chain(int t_mtp, int k, int accepted, int match, double round_ms) { + const int t = std::clamp(t_mtp + k, 1, kMaxT); + if (round_ms > 0) { + cost_[t] = cost_n_[t] > 0 ? (1.0 - kCostAlpha) * cost_[t] + kCostAlpha * round_ms : round_ms; + cost_n_[t] += 1.0; + } + // the MTP part is an ordinary MTP window as far as its own drafts go + const int mtp_acc = std::min(accepted, t_mtp - 1); + const double got = mtp_acc + 1.0; + mtp_tok_[t_mtp] = mtp_n_[t_mtp] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t_mtp] + kTokAlpha * got : got; + mtp_n_[t_mtp] += 1.0; + if (accepted < t_mtp - 1) return; // the chain was never reached: it says nothing about the lookup + const int b = bucket(match), ok = accepted - (t_mtp - 1); + cok_[b] = kDecay * cok_[b] + ok; + cbad_[b] = kDecay * cbad_[b] + (ok < k ? 1.0 : 0.0); +} + } // namespace strata::spec diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index e04b3de8..3a7a3e61 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -58,6 +58,23 @@ int main() { for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6)); // it turns out very expensive check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides"); } + { + // --lookup-chain: rows cheap (UMA-like) and the chain always accepted -> chained; rows dear or the chain + // always rejected -> not + auto cheap = [](int t) { return 40.0 + 2.0 * (t - 1); }; + DraftPolicy p(8); + for (int t = 2; t <= 8; ++t) + for (int i = 0; i < 5; ++i) p.observe(false, t, 1, 0, cheap(t)); + for (int i = 0; i < 30; ++i) p.observe(false, 4, 2, 0, cheap(4)); + for (int i = 0; i < 30; ++i) p.observe_chain(4, 3, 6, 12, cheap(7)); // every chained token accepted + check(p.chain(4, 0.9, 3, 12) == 3, "chain: cheap rows, always accepted -> all 3 chained"); + DraftPolicy q(8); + for (int t = 2; t <= 8; ++t) + for (int i = 0; i < 5; ++i) q.observe(false, t, 1, 0, cost(t)); + for (int i = 0; i < 30; ++i) q.observe_chain(4, 3, 3, 4, cost(7)); // reached, never accepted + check(q.chain(4, 0.9, 3, 4) == 0, "chain: dear rows, never accepted -> none"); + check(q.chain(4, 0.9, 0, 4) == 0 && q.chain(8, 1.0, 3, 40) == 0, "chain: nothing proposed / no room -> none"); + } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; } diff --git a/src/spec/draft_source.cpp b/src/spec/draft_source.cpp new file mode 100644 index 00000000..2fcbc406 --- /dev/null +++ b/src/spec/draft_source.cpp @@ -0,0 +1,36 @@ +// src/spec/draft_source.cpp - see include/strata/spec/draft_source.hpp. +#include "strata/spec/draft_source.hpp" + +#include + +namespace strata::spec { + +std::vector>& extra_draft_sources() { + static std::vector> sources; + return sources; +} + +int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match, + int32_t* out, int* match, int* source) { + *match = 0; + *source = -1; + if (max_k <= 0) return 0; + int best = 0; + std::vector buf((size_t) max_k); + auto ask = [&](DraftSource& s, int index) { + int m = 0; + const int k = s.propose(tail, n_tail, n_pending, max_k, buf.data(), &m); + if (k <= 0 || m < min_match || m <= *match) return; + for (int i = 0; i < k && i < max_k; ++i) out[i] = buf[(size_t) i]; + best = k < max_k ? k : max_k; + *match = m; + *source = index; + }; + ask(own, 0); + int index = 1; + for (auto& s : extra_draft_sources()) + if (s) ask(*s, index++); + return best; +} + +} // namespace strata::spec diff --git a/src/spec/suffix_drafter.cpp b/src/spec/suffix_drafter.cpp index 6f04f76d..86c7da15 100644 --- a/src/spec/suffix_drafter.cpp +++ b/src/spec/suffix_drafter.cpp @@ -85,4 +85,14 @@ int SuffixDrafter::propose(int max_k, int32_t* out) { return k; } +int SuffixDrafter::propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out) { + if (n_extra <= 0) return propose(max_k, out); + // the index holds the history's trigrams only: appended without indexing, the extra tokens just form the suffix + const size_t n0 = hist_.size(); + hist_.insert(hist_.end(), extra, extra + n_extra); + const int k = propose(max_k, out); + hist_.resize(n0); + return k; +} + } // namespace strata::spec diff --git a/src/spec/suffix_drafter_test.cpp b/src/spec/suffix_drafter_test.cpp index 9fa8611e..79dc1532 100644 --- a/src/spec/suffix_drafter_test.cpp +++ b/src/spec/suffix_drafter_test.cpp @@ -111,6 +111,23 @@ void unit_tests() { int32_t out[4]; check(d.propose(4, out) > 0, "propose after overflow of nominal capacity"); } + { + // --lookup-chain: the match continues from the drafts appended to the history, which stays unchanged + SuffixDrafter d(3, 32, 256); + const int32_t hist[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 1, 2}; + d.append(hist, sizeof(hist) / sizeof(hist[0])); + const int32_t drafts[] = {3, 4}; + int32_t out[8] = {}; + const int k = d.propose_after(drafts, 2, 3, out); + check(k == 3 && out[0] == 5 && out[1] == 6 && out[2] == 7, "propose_after continues after the drafts"); + check(d.last_match() >= 4, "propose_after match length counts the drafts"); + check(d.size() == sizeof(hist) / sizeof(hist[0]), "propose_after leaves the history unchanged"); + const int32_t miss[] = {99, 98, 97}; + check(d.propose_after(miss, 3, 3, out) == 0, "propose_after without a match proposes nothing"); + // the plain proposal is unaffected: the history's own suffix (52, 1, 2) has no earlier occurrence + check(d.propose(3, out) == 0, "propose after propose_after"); + check(d.propose_after(nullptr, 0, 3, out) == d.propose(3, out), "propose_after with no drafts == propose"); + } std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK"); } } // namespace diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp index d436a605..30242cff 100644 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -57,6 +57,8 @@ struct Pair { ggml_type gu, d; const char* name; }; +// MMQ covers this pair (the HIP build has no Q4_K / Q5_K / Q5_1 MMQ: those pairs are checked against the reference only) +bool mmq_ok(const Pair& p) { return mmq::supported((int) p.gu) && mmq::supported((int) p.d); } struct Geo { size_t gu_row, d_row, up_off, down_off, bytes; @@ -80,13 +82,18 @@ struct Geo { void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) { const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t)); std::uniform_int_distribution byte(0, 255); - const float lo = t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f + const float lo = t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K ? 0.00004f : t == GGML_TYPE_Q5_1 ? 0.0006f + : t == GGML_TYPE_Q8_0 ? 0.0001f : t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f; std::uniform_real_distribution sc(lo, 6.0f * lo); for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng); for (size_t b = 0; b < nb; ++b) { const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); std::memcpy(m + b * bs, &h, 2); + if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) { // the minimum's scale, either sign + const ggml_fp16_t h2 = ggml_fp32_to_fp16(sc(rng) * ((rng() & 1) ? 1.0f : -1.0f) * (t == GGML_TYPE_Q5_1 ? 4.0f : 1.0f)); + std::memcpy(m + b * bs + 2, &h2, 2); + } } } std::vector make_blob(const Pair& p, const Geo& g, std::mt19937& rng) { @@ -271,6 +278,16 @@ Err compare(const std::vector& a, RA row_a, const std::vector& b, return out; } +// the kernels' int8 rounding per 32 values (quant_act_nat_kernel / the H epilogue), as floats: codes * (amax / 127) +void quant32(const float* in, float* out, int n) { + for (int b = 0; b < n; b += 32) { + float am = 0.0f; + for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(in[b + j])); + const float inv = am > 0.0f ? 127.0f / am : 0.0f, d = am / 127.0f; + for (int j = 0; j < 32; ++j) out[b + j] = (float) std::nearbyint(in[b + j] * inv) * d; + } +} + std::vector download(const Dev& d, size_t n) { std::vector h(n); ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); @@ -310,27 +327,30 @@ void reference_part(const Pair& p, cudaStream_t s) { // (the uploads above are on the legacy stream and the work below on a non-blocking one: a cudaMemcpy from pageable // memory may return before its DMA lands - on Windows it can wait in the queue until the next synchronous call) ck(cudaDeviceSynchronize(), "uploads"); + const bool mq = mmq_ok(p); mmq::Context ctx; - MmqBufs mb(p, rows, E); - run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); + MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr; + if (mq) run_mmq(p, geo, ctx, *mbp, r, x_dev.as(), src_dev.as(), blob, rows, s); FusedBufs fb(T, rows, E); ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN ck(cudaDeviceSynchronize(), "uploads"); run_fused(p, geo, fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); ck(cudaStreamSynchronize(s), "sync"); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector y_mmq = mq ? download(mbp->dm, (size_t) rows * N) : std::vector((size_t) rows * N, 0.0f), + y_f = download(fb.dm, (size_t) rows * N); + delete mbp; const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); for (int64_t i = 0; i < rows; ++i) if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); // the reference, an expert at a time on all cores - std::vector ref((size_t) rows * N); + std::vector ref((size_t) rows * N), ref2((size_t) rows * N); // ref2: the same with the kernels' int8 rounding std::vector th; const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); for (int w = 0; w < nth; ++w) th.emplace_back([&, w] { - std::vector gu, dn, h(FF); + std::vector gu, dn, h(FF), h2(FF), hq(FF), xq(N); for (int e = w; e < E; e += nth) { if (r.cnt[(size_t) e] == 0) continue; dequant(p, geo, host[(size_t) e], gu, dn); @@ -349,6 +369,20 @@ void reference_part(const Pair& p, cudaStream_t s) { for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; ref[(size_t) i * N + o] = (float) a; } + quant32(xr, xq.data(), N); + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xq[(size_t) k]; up += (double) wu[k] * xq[(size_t) k]; } + h2[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + quant32(h2.data(), hq.data(), FF); + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * hq[(size_t) f]; + ref2[(size_t) i * N + o] = (float) a; + } } } }); @@ -357,17 +391,27 @@ void reference_part(const Pair& p, cudaStream_t s) { auto pair = [](size_t i) { return (int64_t) i; }; auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; auto frow = [&](size_t i) { return (int64_t) slot[i]; }; - const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); + const Err em = mq ? compare(y_mmq, mrow, ref, pair, (size_t) rows) : Err{}; const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); - const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); - std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); + const Err efm = mq ? compare(y_f, frow, y_mmq, mrow, (size_t) rows) : Err{}; + const Err e2 = compare(y_f, frow, ref2, pair, (size_t) rows); + std::printf(" fused vs the int8-rounded model (same activation / H rounding, double sums): rel RMS %.3e worst %.3e\n", + e2.rms, e2.worst); + if (e2.rms > 2e-3 || e2.worst > 3e-2) + throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model"); + if (mq) std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); - std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); + if (mq) std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); double zmax = 0; for (int k = 0; k < K; ++k) for (int o = 0; o < N; ++o) zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero"); + if (!mq) { // no MMQ here: the int8 activations' own error (the IQ pairs' fused path sits at ~1e-2 rel RMS) + if (ef.rms > 0.03 || ef.worst > 0.25) + throw std::runtime_error(std::string(p.name) + ": the fused path's error against the reference is too large"); + return; + } if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's"); } @@ -401,8 +445,10 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + const bool mq = mmq_ok(p); mmq::Context ctx; - MmqBufs mb(p, rows, E); + MmqBufs* mbp = mq ? new MmqBufs(p, rows, E) : nullptr; + MmqBufs& mb = *mbp; // (only used when mq) FusedBufs fb(T, rows, E); ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); ck(cudaDeviceSynchronize(), "uploads"); // (see reference_part) @@ -420,7 +466,7 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { }; auto mmq_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }; auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as(), T, E, {0, E}, blob, s); }; - const bool all_routed = std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; + const bool all_routed = mq && std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; auto direct_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s, true, stride); }; @@ -446,7 +492,7 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { } } // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians - const bool no_mmq = std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) + const bool no_mmq = !mq || std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) for (float spent = 0; spent < 1000.0f;) spent += (no_mmq ? 0.0f : once(mmq_run)) + once(fused_run); std::vector tm, tf, td; for (int rep = 0; rep < 8; ++rep) { @@ -467,10 +513,17 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { std::sort(tf2.begin(), tf2.end()); std::printf(" (fused back to back: median %.3f ms, min %.3f; alternating min %.3f; MMQ min %.3f)\n", tf2[4], tf2[0], tf[0], tm[0]); - const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector y_mmq = mq ? download(mb.dm, (size_t) rows * N) : std::vector((size_t) rows * N, 0.0f), + y_f = download(fb.dm, (size_t) rows * N); const std::vector slot = download_i(fb.slot, (size_t) rows); - const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, - [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); + { // (Aurora S23) a hash of the fused output's bits, to compare two builds bit for bit + uint64_t hsh = 1469598103934665603ull; + for (size_t i = 0; i < (size_t) rows; ++i) // in pair order: the rows of an expert are placed in any order + for (size_t c = 0; c < (size_t) N; ++c) { uint32_t u; std::memcpy(&u, &y_f[(size_t) slot[i] * N + c], 4); hsh = (hsh ^ u) * 1099511628211ull; } + std::printf(" fused output bits hash %016llx\n", (unsigned long long) hsh); + } + const Err efm = mq ? compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, + [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows) : Err{}; std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms " "(%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n", p.name, T, K, E, t_mmq, t_f, t_mmq / t_f, efm.rms, efm.worst); @@ -560,18 +613,19 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; ref[j * N + o] = (float) a; } - std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); + if (mq) std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N)); } auto id = [](size_t j) { return (int64_t) j; }; - const Err em = compare(ym, id, ref, id, pick.size()), ef = compare(yf, id, ref, id, pick.size()); + const Err em = mq ? compare(ym, id, ref, id, pick.size()) : Err{}, ef = compare(yf, id, ref, id, pick.size()); std::printf(" sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst " "%.3e\n", pick.size(), em.rms, em.worst, ef.rms, ef.worst); - if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + if (!mq ? (ef.rms > 0.03 || ef.worst > 0.25) : (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst)) throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's (timing)"); } cudaEventDestroy(a); cudaEventDestroy(b); + delete mbp; if (efm.rms > 0.05) throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape"); } } // namespace @@ -582,6 +636,7 @@ int main(int argc, char** argv) { _putenv_s("STRATA_PF_FUSED", "1"); #else setenv("STRATA_PF_FUSED", "1", 1); + setenv("STRATA_PF_FUSED_KQ", "1", 1); // (the HIP build's Q4_K / Q5_K / Q5_1 / Q8_0 pairs) #endif int n = 0; if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } @@ -590,7 +645,10 @@ int main(int argc, char** argv) { const std::vector pairs = { {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"}, - {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}}; + {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}, + // (HIP only) UD-Q4_K_XL's: 47 layers Q4_K / Q5_1, 4 Q4_K / Q8_0, and the one Q5_K layer + {GGML_TYPE_Q4_K, GGML_TYPE_Q5_1, "Q4_K / Q5_1"}, {GGML_TYPE_Q4_K, GGML_TYPE_Q8_0, "Q4_K / Q8_0"}, + {GGML_TYPE_Q5_K, GGML_TYPE_Q5_1, "Q5_K / Q5_1"}, {GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, "Q5_K / Q8_0"}}; const char* only = nullptr; // --only=NAME: the pairs whose name contains NAME for (int i = 1; i < argc; ++i) if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7; @@ -611,14 +669,14 @@ int main(int argc, char** argv) { cudaStream_t s = nullptr; ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); for (const Pair& p : pairs) { - if (only && std::string(p.name).find(only) == std::string::npos) continue; + if (only ? std::string(p.name).find(only) == std::string::npos : p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K) continue; if (!fused::native_supported((int) p.gu, (int) p.d)) throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels"); if (ref) reference_part(p, s); } if (timing) { // the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's - for (const Pair& p : {pairs[0], pairs[1], pairs[4], pairs[3]}) { + for (const Pair& p : only ? pairs : std::vector{pairs[0], pairs[1], pairs[4], pairs[3]}) { if (only && std::string(p.name).find(only) == std::string::npos) continue; for (int T : chunks) timing_part(p, T, s); } diff --git a/tests/hip/gdn_rec_head.cpp b/tests/hip/gdn_rec_head.cpp new file mode 100644 index 00000000..0e3a6cc9 --- /dev/null +++ b/tests/hip/gdn_rec_head.cpp @@ -0,0 +1,116 @@ +// tests/hip/gdn_rec_head.cpp - the prompt GDN recurrence's four-lanes-per-column kernel + norm (gdn_recurrence_variant 1) +// against the column-split kernels + the norm kernel (variant 0, the default before it): +// y, its FP16 bits and the final state must be BITWISE equal, over chunk lengths around the 8-token staging and a +// long one, from a nonzero state. Synthetic inputs in the model's ranges (unit q/k rows, log-decay gates < 0). +#include "strata/prefill/kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int S = 128, HK = 16, HV = 48, C = 10240; +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dev(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T)), "malloc"); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +template std::vector host(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return h; +} +} // namespace + +int main() { + std::mt19937 rng(11); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution ud(0.f, 1.f); + int failures = 0; + const int64_t lens[] = {1, 7, 8, 9, 17, 100, 2048, 2051}; + for (const int64_t T : lens) { + std::vector h((size_t) T * C), gate((size_t) T * HV), beta((size_t) T * HV), z((size_t) T * HV * S), + gamma(S), state((size_t) S * HV * S); + for (int64_t t = 0; t < T; ++t) { + float* ht = h.data() + t * C; + for (int i = 0; i < C; ++i) ht[i] = nd(rng); + for (int hh = 0; hh < 2 * HK; ++hh) { // q and k heads: unit rows, as after gdn_conv's L2 norm + double ss = 0; + for (int d = 0; d < S; ++d) ss += (double) ht[hh * S + d] * ht[hh * S + d]; + for (int d = 0; d < S; ++d) ht[hh * S + d] = (float) (ht[hh * S + d] / std::sqrt(ss + 1e-6)); + } + } + for (auto& x : gate) x = -2.0f * ud(rng); + for (auto& x : beta) x = ud(rng); + for (auto& x : z) x = nd(rng); + for (auto& x : gamma) x = 0.5f + ud(rng); + for (auto& x : state) x = 0.1f * nd(rng); + const float* dh = dev(h); + const float* dg = dev(gate); + const float* db = dev(beta); + const float* dz = dev(z); + const float* dgm = dev(gamma); + std::vector y_ref, st_ref; + std::vector y16_ref; + for (int variant : {0, 3, 1, 4, 5}) { + float* dst = dev(state); + float* dy = nullptr; + uint16_t* dy16 = nullptr; + ck(cudaMalloc(&dy, (size_t) T * HV * S * 4), "malloc"); + ck(cudaMalloc(&dy16, (size_t) T * HV * S * 2), "malloc"); + strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, nullptr); + ck(cudaDeviceSynchronize(), "run"); + auto y = host(dy, (size_t) T * HV * S); + auto y16 = host(dy16, (size_t) T * HV * S); + auto st = host(dst, state.size()); + if (variant == 0) { + y_ref = y; y16_ref = y16; st_ref = st; + } else { + size_t dy_n = 0, d16 = 0, dsn = 0; + for (size_t i = 0; i < y.size(); ++i) dy_n += std::memcmp(&y[i], &y_ref[i], 4) != 0; + for (size_t i = 0; i < y16.size(); ++i) d16 += y16[i] != y16_ref[i]; + for (size_t i = 0; i < st.size(); ++i) dsn += std::memcmp(&st[i], &st_ref[i], 4) != 0; + const bool ok = dy_n == 0 && d16 == 0 && dsn == 0; + failures += !ok; + std::printf("%s T %lld variant %d vs 0: y %zu, y16 %zu, state %zu values differ\n", ok ? "PASS" : "FAIL", + (long long) T, variant, dy_n, d16, dsn); + } + cudaFree(dst); cudaFree(dy); cudaFree(dy16); + } + // timing at the long lengths: variant 0 vs 1 + if (T >= 2048) { + float* dst = dev(state); + float* dy = nullptr; + uint16_t* dy16 = nullptr; + ck(cudaMalloc(&dy, (size_t) T * HV * S * 4), "malloc"); + ck(cudaMalloc(&dy16, (size_t) T * HV * S * 2), "malloc"); + for (int variant : {0, 1}) { + cudaEvent_t a, b; + cudaEventCreate(&a); cudaEventCreate(&b); + strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, nullptr); + cudaEventRecord(a); + for (int r = 0; r < 3; ++r) + strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, nullptr); + cudaEventRecord(b); + ck(cudaEventSynchronize(b), "time"); + float ms = 0; + cudaEventElapsedTime(&ms, a, b); + std::printf(" T %lld variant %d: %.3f ms per call (%.2f us per token)\n", (long long) T, variant, ms / 3, + ms / 3 * 1000 / (double) T); + } + cudaFree(dst); cudaFree(dy); cudaFree(dy16); + } + cudaFree((void*) dh); cudaFree((void*) dg); cudaFree((void*) db); cudaFree((void*) dz); cudaFree((void*) dgm); + } + std::printf("FAILURES: %d\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/hip/prefill_wmma_gemm_parity.cpp b/tests/hip/prefill_wmma_gemm_parity.cpp new file mode 100644 index 00000000..bb7c1591 --- /dev/null +++ b/tests/hip/prefill_wmma_gemm_parity.cpp @@ -0,0 +1,441 @@ +// tests/hip/prefill_wmma_gemm_parity.cpp - Numerical parity test for RDNA3 WMMA GEMM kernels. +#include +#include +#include + +#include "wmma_gemm.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ============================================================================ +// Exact Representability & Parity Rationale: +// +// Inputs (X, W, and initial Y for beta=1) are chosen from discrete binary fractions +// k / 16.0f with integer k in [-8, 8]. +// +// In IEEE 754 half-precision (fp16, 10-bit explicit mantissa) and bfloat16 +// (7-bit explicit mantissa), every such value k * 2^-4 requires at most 4 bits +// of significand and is therefore EXACTLY representable without rounding. +// +// The product of any two such values is an exact integer multiple of 2^-8: +// (a * 2^-4) * (b * 2^-4) = (a * b) * 2^-8 +// with (a * b) in [-64, 64]. +// +// For K <= 80, the sum of K products: +// sum_k (W[n, k] * X[t, k]) = (sum_k a_k * b_k) * 2^-8 +// has a maximum absolute magnitude of 80 * (0.5 * 0.5) = 20.0, and the integer +// numerator cannot exceed 80 * 64 = 5120 (< 2^13). +// +// In IEEE 754 single-precision (fp32, 23-bit explicit mantissa, 24 bits total), +// any integer multiple of 2^-8 up to 20.0 requires at most 13 bits of significand. +// Because the RDNA3 hardware instructions (v_wmma_f32_16x16x16_f16_w32 and +// v_wmma_f32_16x16x16_bf16_w32) accumulate in native FP32 registers, every +// intermediate product and addition has ZERO truncation or rounding error. +// +// Furthermore, floating-point addition of exact binary fractions whose sum fits +// within the mantissa is strictly associative and exact. Consequently, the GPU +// WMMA pipeline and the CPU reference compute identical bitwise results, making +// an exact assertion (max_abs == 0.0f) mathematically legitimate. +// ============================================================================ + +#define HIP_CHECK(call) do { \ + const hipError_t status_ = (call); \ + if (status_ != hipSuccess) { \ + std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \ + std::exit(2); \ + } \ +} while (0) + +namespace { + +constexpr float kSentinel = -999.5f; + +struct DeviceBuffer { + void* p = nullptr; + explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); } + ~DeviceBuffer() { if (p) (void) hipFree(p); } + DeviceBuffer(const DeviceBuffer&) = delete; + DeviceBuffer& operator=(const DeviceBuffer&) = delete; +}; + +uint16_t encode(float value, bool bf16) { + if (bf16) return hip_bfloat16(value).data; + const __half half = __float2half_rn(value); + return static_cast<__half_raw>(half).x; +} + +float decode(uint16_t bits, bool bf16) { + if (bf16) { + const uint32_t u = static_cast(bits) << 16; + float f = 0.0f; + std::memcpy(&f, &u, sizeof(f)); + return f; + } + const __half_raw raw{bits}; + return __half2float(__half(raw)); +} + +struct MismatchRecord { + const char* dtype = ""; + int64_t T = 0, N = 0, K = 0, ldy = 0; + float beta = 0.0f; + int64_t row = 0, col = 0; + float got = 0.0f, ref = 0.0f; + double delta = 0.0; + bool is_padding = false; +}; + +// Independent host CPU reference computed in double precision. +void gemm_reference(const uint16_t* X, const uint16_t* W, const float* initial_Y, float* ref_Y, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, bool is_bf16) { + std::vector x_dec((size_t) T * K); + std::vector w_dec((size_t) N * K); + for (size_t i = 0; i < x_dec.size(); ++i) x_dec[i] = decode(X[i], is_bf16); + for (size_t i = 0; i < w_dec.size(); ++i) w_dec[i] = decode(W[i], is_bf16); + + for (int64_t t = 0; t < T; ++t) { + const double* x_row = x_dec.data() + t * K; + for (int64_t n = 0; n < N; ++n) { + const double* w_row = w_dec.data() + n * K; + double sum = 0.0; + for (int64_t k = 0; k < K; ++k) { + sum += x_row[k] * w_row[k]; + } + const size_t out_idx = (size_t) t * ldy + n; + const double y_init = (beta == 0.0f) ? 0.0 : static_cast(initial_Y[out_idx]); + ref_Y[out_idx] = static_cast(beta * y_init + sum); + } + } +} + +enum class CaseStatus { + Passed, + Skipped, + Failed +}; + +CaseStatus run_gemm_case(DeviceBuffer& dx, DeviceBuffer& dw, DeviceBuffer& dy, + hipStream_t stream, bool is_bf16, + int64_t T, int64_t N, int64_t K, int64_t ldy, float beta, + uint32_t seed, double& out_max_abs, + MismatchRecord* first_mismatch, size_t& failure_count) { + const char* dtype_str = is_bf16 ? "bf16" : "f16"; + std::mt19937 rng(seed); + std::uniform_int_distribution dist(-8, 8); + + const size_t x_count = (size_t) T * K; + const size_t w_count = (size_t) N * K; + const size_t y_count = (size_t) T * ldy + 16; // 16 guard floats past end of matrix + + std::vector x(x_count); + std::vector w(w_count); + for (size_t i = 0; i < x_count; ++i) x[i] = encode(dist(rng) * 0.0625f, is_bf16); + for (size_t i = 0; i < w_count; ++i) w[i] = encode(dist(rng) * 0.0625f, is_bf16); + + std::vector initial_y(y_count, kSentinel); + for (int64_t t = 0; t < T; ++t) { + for (int64_t n = 0; n < N; ++n) { + if (beta == 0.0f) { + initial_y[(size_t) t * ldy + n] = -888.25f; + } else { + // beta == 1.0f: pre-fill with a known exact pattern to verify accumulation + initial_y[(size_t) t * ldy + n] = static_cast((t * 5 + n * 3) % 17 - 8) * 0.0625f; + } + } + } + + HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dy.p, initial_y.data(), y_count * sizeof(float), hipMemcpyHostToDevice, stream)); + + const bool launched = is_bf16 ? strata_wmma_gemm_bf16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + T, N, K, ldy, beta, stream) + : strata_wmma_gemm_f16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + T, N, K, ldy, beta, stream); + + if (!launched) { + // Declined by kernel: caller falls back to hipBLAS. Test must SKIP rather than fail. + HIP_CHECK(hipStreamSynchronize(stream)); + return CaseStatus::Skipped; + } + + std::vector got_y(y_count); + HIP_CHECK(hipMemcpyAsync(got_y.data(), dy.p, y_count * sizeof(float), hipMemcpyDeviceToHost, stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + + // 1. Verify padding columns and end guards are untouched. + for (int64_t t = 0; t < T; ++t) { + for (int64_t col = N; col < ldy; ++col) { + const size_t idx = (size_t) t * ldy + col; + if (got_y[idx] != kSentinel) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, col, + got_y[idx], kSentinel, + std::abs((double) got_y[idx] - (double) kSentinel), true}; + } + std::fprintf(stderr, "FAIL: output touched padding column: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f row=%ld col=%ld got=%.9g expected=%.9g\n", + dtype_str, T, N, K, ldy, beta, t, col, got_y[idx], kSentinel); + return CaseStatus::Failed; + } + } + } + for (size_t g = (size_t) T * ldy; g < y_count; ++g) { + if (got_y[g] != kSentinel) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, -1, (int64_t) g, + got_y[g], kSentinel, + std::abs((double) got_y[g] - (double) kSentinel), true}; + } + std::fprintf(stderr, "FAIL: output touched end guard: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f index=%zu got=%.9g expected=%.9g\n", + dtype_str, T, N, K, ldy, beta, g, got_y[g], kSentinel); + return CaseStatus::Failed; + } + } + + // 2. Compute reference on CPU and verify exact match. + std::vector ref_y(y_count, kSentinel); + gemm_reference(x.data(), w.data(), initial_y.data(), ref_y.data(), T, N, K, ldy, beta, is_bf16); + + double case_max_abs = 0.0; + for (int64_t t = 0; t < T; ++t) { + for (int64_t n = 0; n < N; ++n) { + const size_t idx = (size_t) t * ldy + n; + if (!std::isfinite(got_y[idx])) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n, + got_y[idx], ref_y[idx], 1e30, false}; + } + std::fprintf(stderr, "FAIL: non-finite output: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g\n", + dtype_str, T, N, K, ldy, beta, t, n, got_y[idx]); + return CaseStatus::Failed; + } + const double delta = std::abs(static_cast(got_y[idx]) - static_cast(ref_y[idx])); + case_max_abs = std::max(case_max_abs, delta); + // The RDNA3 matrix core accumulates in fp32 but rounds toward zero rather than to nearest, while + // this reference sums in double and rounds to nearest, so a correct result may differ by one ULP + // (measured: every mismatch on this hardware is <= 1 ULP and toward zero). Compare against a + // tolerance of 4 ULP - tight enough to stay diagnostic, since a wrong row, column, stride or tile + // boundary differs by O(value) rather than by 1e-7. STRATA_WMMA_PARITY_EXACT=1 demands bit + // equality for anyone who wants to see the raw deltas. + static const bool exact = std::getenv("STRATA_WMMA_PARITY_EXACT") != nullptr; + const double tol = exact ? 0.0 + : 4.0 * (double)std::numeric_limits::epsilon() * + std::max(1.0, std::abs(static_cast(ref_y[idx]))); + if (delta > tol) { + failure_count++; + if (first_mismatch && first_mismatch->dtype[0] == '\0') { + *first_mismatch = MismatchRecord{dtype_str, T, N, K, ldy, beta, t, n, + got_y[idx], ref_y[idx], delta, false}; + } + std::fprintf(stderr, "FAIL: mismatch: dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n", + dtype_str, T, N, K, ldy, beta, t, n, got_y[idx], ref_y[idx], delta); + return CaseStatus::Failed; + } + } + } + + out_max_abs = std::max(out_max_abs, case_max_abs); + return CaseStatus::Passed; +} + +struct DeclinedShape { + int64_t T, N, K, ldy; + float beta; + const char* reason; +}; + +} // namespace + +int main() { + int device = 0; + HIP_CHECK(hipGetDevice(&device)); + hipDeviceProp_t properties{}; + HIP_CHECK(hipGetDeviceProperties(&properties, device)); + std::printf("Device %d: %s (arch %s, warpSize %d)\n", + device, properties.name, properties.gcnArchName, properties.warpSize); + + hipStream_t stream = nullptr; + HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); + + // Allocate reusable device buffers sized for the maximum test dimensions: + // Max T = 127, Max N = 256, Max K = 80, Max ldy = 256 + 16. + constexpr size_t kMaxXBytes = 127 * 80 * sizeof(uint16_t); + constexpr size_t kMaxWBytes = 256 * 80 * sizeof(uint16_t); + constexpr size_t kMaxYBytes = (127 * (256 + 16) + 64) * sizeof(float); + + DeviceBuffer dx(kMaxXBytes); + DeviceBuffer dw(kMaxWBytes); + DeviceBuffer dy(kMaxYBytes); + + const std::vector k_t_values = {1, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127}; + const std::vector k_n_values = {16, 17, 32, 48, 64, 65, 127, 256}; + const std::vector k_k_values = {16, 32, 48, 64, 80}; + + // Test matrix configurations for (beta, ldy): + // Covers beta=0 (overwrite) and beta=1 (accumulate), with ldy == N and ldy > N. + struct Config { + float beta; + int64_t ldy_offset; + }; + const std::vector kConfigs = { + {0.0f, 0}, // beta=0, packed (ldy == N) + {1.0f, 3}, // beta=1, strided (ldy == N + 3), tests accumulation + padding + {0.0f, 7}, // beta=0, strided (ldy == N + 7), tests overwrite + padding + {1.0f, 0}, // beta=1, packed (ldy == N), tests accumulation in packed layout + }; + + const std::vector kDeclinedShapes = { + // K not a multiple of 16 + {1, 16, 15, 16, 0.0f, "K not multiple of 16 (K=15)"}, + {15, 17, 24, 17, 0.0f, "K not multiple of 16 (K=24)"}, + {32, 32, 35, 32, 1.0f, "K not multiple of 16 (K=35)"}, + {64, 64, 47, 67, 1.0f, "K not multiple of 16 (K=47)"}, + {127, 256, 79, 256, 0.0f, "K not multiple of 16 (K=79)"}, + // ldy < N + {16, 32, 16, 16, 0.0f, "ldy < N (ldy=16, N=32)"}, + {32, 48, 32, 40, 1.0f, "ldy < N (ldy=40, N=48)"}, + // beta not 0 or 1 + {16, 16, 16, 16, 0.5f, "beta not 0 or 1 (beta=0.5)"}, + {32, 32, 32, 32, 2.0f, "beta not 0 or 1 (beta=2.0)"}, + // Non-positive sizes + {0, 16, 16, 16, 0.0f, "T <= 0 (T=0)"}, + {16, 0, 16, 16, 0.0f, "N <= 0 (N=0)"}, + {16, 16, 0, 16, 0.0f, "K <= 0 (K=0)"}, + {-1, 16, 16, 16, 0.0f, "T < 0 (T=-1)"}, + }; + + size_t passed_count = 0; + size_t skipped_count = 0; + size_t failure_count = 0; + double global_max_abs = 0.0; + MismatchRecord first_mismatch{}; + uint32_t case_seed = 0x574d4d41u; + + const bool verbose = (std::getenv("STRATA_TEST_VERBOSE") != nullptr); + + for (bool is_bf16 : {false, true}) { + const char* dtype_str = is_bf16 ? "bf16" : "f16"; + std::printf("Testing strata_wmma_gemm_%s across %zu shapes (%zu execution configs)...\n", + dtype_str, k_t_values.size() * k_n_values.size() * k_k_values.size(), kConfigs.size()); + + for (int64_t T : k_t_values) { + double t_max_abs = 0.0; + size_t t_passed = 0; + size_t t_skipped = 0; + + for (int64_t N : k_n_values) { + for (int64_t K : k_k_values) { + for (const auto& cfg : kConfigs) { + const int64_t ldy = N + cfg.ldy_offset; + double case_max_abs = 0.0; + case_seed = case_seed * 1664525u + 1013904223u; + + const CaseStatus status = run_gemm_case( + dx, dw, dy, stream, is_bf16, T, N, K, ldy, cfg.beta, + case_seed, case_max_abs, &first_mismatch, failure_count); + + if (status == CaseStatus::Passed) { + passed_count++; + t_passed++; + t_max_abs = std::max(t_max_abs, case_max_abs); + global_max_abs = std::max(global_max_abs, case_max_abs); + if (verbose) { + std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f max_abs=%.9g PASS\n", + dtype_str, T, N, K, ldy, cfg.beta, case_max_abs); + } + } else if (status == CaseStatus::Skipped) { + skipped_count++; + t_skipped++; + if (verbose) { + std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f SKIP (declined)\n", + dtype_str, T, N, K, ldy, cfg.beta); + } + } else { + // Failed: first_mismatch already recorded and reported to stderr + if (verbose) { + std::printf(" case dtype=%s T=%3ld N=%3ld K=%2ld ldy=%3ld beta=%.1f FAIL\n", + dtype_str, T, N, K, ldy, cfg.beta); + } + } + } + } + } + std::printf(" dtype=%s T=%3ld: %zu passed, %zu skipped, max_abs=%.9g %s\n", + dtype_str, T, t_passed, t_skipped, t_max_abs, + (failure_count == 0) ? "PASS" : "FAIL"); + } + + // Test declined shapes: the kernel must return false and be skipped. + for (const auto& decl : kDeclinedShapes) { + const bool launched = is_bf16 + ? strata_wmma_gemm_bf16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream) + : strata_wmma_gemm_f16(static_cast(dx.p), + static_cast(dw.p), + static_cast(dy.p), + decl.T, decl.N, decl.K, decl.ldy, decl.beta, stream); + + if (launched) { + failure_count++; + std::fprintf(stderr, "FAIL: expected kernel to decline shape (%s) dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f but it returned true!\n", + decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta); + } else { + skipped_count++; + if (verbose) { + std::printf(" declined shape correctly rejected (%s): dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f SKIP\n", + decl.reason, dtype_str, decl.T, decl.N, decl.K, decl.ldy, decl.beta); + } + } + } + } + + HIP_CHECK(hipStreamDestroy(stream)); + + if (failure_count > 0) { + if (first_mismatch.dtype[0] != '\0') { + if (first_mismatch.is_padding) { + std::fprintf(stderr, "\nSUMMARY: First mismatch was padding/guard corruption:\n" + " dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g expected=%.9g\n", + first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K, + first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col, + first_mismatch.got, first_mismatch.ref); + } else { + std::fprintf(stderr, "\nSUMMARY: First mismatch occurred at:\n" + " dtype=%s T=%ld N=%ld K=%ld ldy=%ld beta=%.1f at (%ld, %ld): got=%.9g ref=%.9g delta=%.9g\n", + first_mismatch.dtype, first_mismatch.T, first_mismatch.N, first_mismatch.K, + first_mismatch.ldy, first_mismatch.beta, first_mismatch.row, first_mismatch.col, + first_mismatch.got, first_mismatch.ref, first_mismatch.delta); + } + } + std::fprintf(stderr, "WMMA GEMM parity FAILED: %zu failures detected, max_abs=%.9g\n", + failure_count, global_max_abs); + return 1; + } + + if (passed_count == 0) { + std::fprintf(stderr, "WMMA GEMM parity FAILED: zero test cases passed (all were declined or skipped)\n"); + return 1; + } + + std::printf("\nWMMA GEMM parity OK: %zu test cases passed, %zu declined shapes skipped, max_abs=%.9g\n", + passed_count, skipped_count, global_max_abs); + return 0; +} diff --git a/tools/hip/gfx1151-hipblaslt-100401.txt b/tools/hip/gfx1151-hipblaslt-100401.txt new file mode 100644 index 00000000..260f983e --- /dev/null +++ b/tools/hip/gfx1151-hipblaslt-100401.txt @@ -0,0 +1,92 @@ +# solution IDs are scoped to this hipBLASLt version and device architecture +STRATA_HIPBLASLT_TUNING_V1 gfx1151 100401 +bf16 10240 320 10240 2047 1177 +bf16 128 2560 128 2047 1177 +bf16 1 2560 1 2047 1174 +bf16 2560 2560 2560 2047 1177 +bf16 320 10240 320 2047 1176 +bf16 48 2560 96 2047 1176 +bf16 4 10240 4 2047 1174 +bf16 512 2560 512 2047 1177 +f16 10240 2560 10240 2047 2390 +f16 12288 2560 12288 2047 2390 +f16 2560 6144 2560 2047 2390 +f16 2560 640 2560 2047 2390 +f16 512 2560 512 2047 2389 +f16 6144 2560 6144 2047 2390 +f16 640 2560 640 2047 2389 +bf16 10240 320 10240 2048 1177 +bf16 128 2560 128 2048 1177 +bf16 1 2560 1 2048 1174 +bf16 2560 2560 2560 2048 1177 +bf16 320 10240 320 2048 1176 +bf16 48 2560 96 2048 1176 +bf16 4 10240 4 2048 1175 +bf16 512 2560 512 2048 1176 +f16 10240 2560 10240 2048 2390 +f16 12288 2560 12288 2048 2390 +f16 2560 6144 2560 2048 2390 +f16 2560 640 2560 2048 2390 +f16 512 2560 512 2048 2390 +f16 6144 2560 6144 2048 2390 +f16 640 2560 640 2048 2390 +bf16 10240 320 10240 8191 1177 +bf16 128 2560 128 8191 1177 +bf16 1 2560 1 8191 1175 +bf16 2560 2560 2560 8191 1177 +bf16 320 10240 320 8191 1176 +bf16 48 2560 96 8191 1176 +bf16 4 10240 4 8191 1174 +bf16 512 2560 512 8191 1177 +f16 10240 2560 10240 8191 2390 +f16 12288 2560 12288 8191 2390 +f16 2560 6144 2560 8191 2390 +f16 2560 640 2560 8191 2390 +f16 512 2560 512 8191 2390 +f16 6144 2560 6144 8191 2390 +f16 640 2560 640 8191 2390 +bf16 10240 320 10240 8192 1177 +bf16 128 2560 128 8192 1177 +bf16 1 2560 1 8192 1175 +bf16 2560 2560 2560 8192 1177 +bf16 320 10240 320 8192 1176 +bf16 48 2560 96 8192 1176 +bf16 4 10240 4 8192 1175 +bf16 512 2560 512 8192 1177 +f16 10240 2560 10240 8192 2390 +f16 12288 2560 12288 8192 2390 +f16 2560 6144 2560 8192 2390 +f16 2560 640 2560 8192 2390 +f16 512 2560 512 8192 2390 +f16 6144 2560 6144 8192 2390 +f16 640 2560 640 8192 2390 +bf16 10240 320 10240 16383 1177 +bf16 128 2560 128 16383 1176 +bf16 1 2560 1 16383 1175 +bf16 2560 2560 2560 16383 1177 +bf16 320 10240 320 16383 1176 +bf16 48 2560 96 16383 1176 +bf16 4 10240 4 16383 1174 +bf16 512 2560 512 16383 1177 +f16 10240 2560 10240 16383 2390 +f16 12288 2560 12288 16383 2390 +f16 2560 6144 2560 16383 2390 +f16 2560 640 2560 16383 2390 +f16 512 2560 512 16383 2390 +f16 6144 2560 6144 16383 2390 +f16 640 2560 640 16383 2390 +bf16 10240 320 10240 16384 1177 +bf16 128 2560 128 16384 1177 +bf16 1 2560 1 16384 1174 +bf16 2560 2560 2560 16384 1177 +bf16 320 10240 320 16384 1176 +bf16 48 2560 96 16384 1175 +bf16 4 10240 4 16384 1174 +bf16 512 2560 512 16384 1177 +f16 10240 2560 10240 16384 2390 +f16 12288 2560 12288 16384 2390 +f16 2560 6144 2560 16384 2390 +f16 2560 640 2560 16384 2390 +f16 512 2560 512 16384 2390 +f16 6144 2560 6144 16384 2390 +f16 640 2560 640 16384 2390