2148 lines
127 KiB
Diff
2148 lines
127 KiB
Diff
diff --git a/CMakeLists.txt b/CMakeLists.txt
|
|
index 4efc2976..4d9f2ca1 100644
|
|
--- a/CMakeLists.txt
|
|
+++ b/CMakeLists.txt
|
|
@@ -34,6 +34,15 @@ endif()
|
|
|
|
option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF)
|
|
option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF)
|
|
+option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF)
|
|
+if(STRATA_CUDA_STATIC)
|
|
+ if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux"
|
|
+ OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
|
+ message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)")
|
|
+ endif()
|
|
+ # Applies to subsequently created CUDA targets, including device-link runtime edges.
|
|
+ set(CMAKE_CUDA_RUNTIME_LIBRARY Static)
|
|
+endif()
|
|
option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF)
|
|
# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads
|
|
# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every
|
|
@@ -110,6 +119,16 @@ if(STRATA_ENABLE_CUDA)
|
|
message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}")
|
|
set(_strata_gpu_runtime_target CUDA::cudart)
|
|
set(_strata_gpu_blas_target CUDA::cublas)
|
|
+ if(STRATA_CUDA_STATIC)
|
|
+ foreach(_required CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static CUDA::culibos)
|
|
+ if(NOT TARGET ${_required})
|
|
+ message(FATAL_ERROR "STRATA_CUDA_STATIC requires toolkit archive target ${_required}")
|
|
+ endif()
|
|
+ endforeach()
|
|
+ set(_strata_gpu_runtime_target CUDA::cudart_static)
|
|
+ set(_strata_gpu_blas_target CUDA::cublas_static)
|
|
+ message(STATUS "Strata: static CUDA toolkit libraries; host glibc and NVIDIA driver remain required")
|
|
+ endif()
|
|
set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
|
|
elseif(STRATA_ENABLE_HIP)
|
|
set(_strata_gpu_runtime_target strata_hip_runtime)
|
|
@@ -257,6 +276,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
|
src/kernels/cuda/fused_gr.cu
|
|
src/kernels/cuda/cvec.cu
|
|
src/kernels/cuda/qsa_decode_attn.cu
|
|
+ src/kernels/cuda/keyless.cu
|
|
src/kernels/cuda/qsa_prompt_attn.cu
|
|
src/kernels/cuda/fused_gdn.cu
|
|
src/kernels/cuda/dequant_bf16.cu
|
|
@@ -267,12 +287,41 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
|
src/ngram/ple_reader.cpp
|
|
src/platform/direct_file.cpp)
|
|
target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact)
|
|
+ option(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE "Capture private PLE row traces for offline cache studies" OFF)
|
|
+ if(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE)
|
|
+ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
|
+ message(FATAL_ERROR "The experimental PLE row trace requires Linux")
|
|
+ endif()
|
|
+ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=1)
|
|
+ endif()
|
|
+ option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build optional KAR PLE CPU and GPU-cache experiment arms" OFF)
|
|
+ set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)")
|
|
+ if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
|
+ message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA")
|
|
+ endif()
|
|
+ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu")
|
|
+ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory")
|
|
+ endif()
|
|
+ add_library(strata_next_kar STATIC
|
|
+ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu"
|
|
+ "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cache.cu")
|
|
+ target_include_directories(strata_next_kar PUBLIC
|
|
+ "${STRATA_NEXT_KAR_DIR}/vendor"
|
|
+ "${STRATA_NEXT_KAR_DIR}/include")
|
|
+ target_link_libraries(strata_next_kar PUBLIC ${_strata_gpu_runtime_target})
|
|
+ set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON)
|
|
+ target_link_libraries(strata_kernels PUBLIC strata_next_kar)
|
|
+ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1)
|
|
+ add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp")
|
|
+ target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels)
|
|
+ endif()
|
|
# perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with
|
|
# the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out.
|
|
if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA)
|
|
add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp)
|
|
target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
|
|
- target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart)
|
|
+ target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
|
|
endif()
|
|
# the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a
|
|
# scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a
|
|
@@ -338,11 +387,35 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
|
# already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third
|
|
# library is the honest shape of the dependency graph: core knows about devices and weights, kernels know
|
|
# about arithmetic, and this one knows the ORDER the arithmetic happens in.
|
|
- add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
|
|
+ add_library(strata_engine STATIC src/core/keyless.cpp src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
|
|
src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp
|
|
src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp)
|
|
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
|
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})
|
|
+ option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF)
|
|
+ if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS)
|
|
+ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
|
+ message(FATAL_ERROR "Experimental KAR experts require Linux CUDA")
|
|
+ endif()
|
|
+ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp")
|
|
+ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to strata-next/gpu/kar")
|
|
+ endif()
|
|
+ add_library(strata_next_kar_experts STATIC
|
|
+ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu"
|
|
+ "${STRATA_NEXT_KAR_DIR}/src/kar_expert.cu"
|
|
+ "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp")
|
|
+ target_include_directories(strata_next_kar_experts PUBLIC
|
|
+ "${STRATA_NEXT_KAR_DIR}/vendor" "${STRATA_NEXT_KAR_DIR}/include")
|
|
+ target_link_libraries(strata_next_kar_experts PUBLIC ${_strata_gpu_runtime_target})
|
|
+ set_target_properties(strata_next_kar_experts PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON)
|
|
+ target_compile_features(strata_next_kar_experts PRIVATE cxx_std_20)
|
|
+ target_link_libraries(strata_engine PUBLIC strata_next_kar_experts)
|
|
+ target_compile_definitions(strata_engine PUBLIC STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=1)
|
|
+ endif()
|
|
+ add_executable(keyless_parity src/kernels/keyless_parity.cpp)
|
|
+ target_link_libraries(keyless_parity PRIVATE strata_engine)
|
|
+ add_test(NAME keyless_parity COMMAND keyless_parity)
|
|
+ set_tests_properties(keyless_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
|
|
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")
|
|
enable_testing()
|
|
add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp)
|
|
@@ -369,6 +442,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
|
set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
|
|
endif()
|
|
if(STRATA_BUILD_CONVERSATION_TESTS)
|
|
+ add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp)
|
|
+ target_link_libraries(keyless_stream_parity PRIVATE strata_engine)
|
|
+ add_test(NAME keyless_stream_parity COMMAND keyless_stream_parity --v-only)
|
|
+ set_tests_properties(keyless_stream_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
|
|
add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp)
|
|
target_link_libraries(conversation_snapshot_test PRIVATE strata_engine)
|
|
add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test)
|
|
@@ -406,6 +483,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
|
add_executable(strata src/program/generate.cpp)
|
|
target_include_directories(strata PRIVATE ${_strata_gpu_include_directories})
|
|
target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target})
|
|
+ if(STRATA_CUDA_STATIC)
|
|
+ target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc)
|
|
+ set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "")
|
|
+ endif()
|
|
|
|
if(STRATA_ENABLE_HIP)
|
|
enable_testing()
|
|
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp
|
|
index 307edd98..e2669ebe 100644
|
|
--- a/include/strata/core/expert_source.hpp
|
|
+++ b/include/strata/core/expert_source.hpp
|
|
@@ -211,6 +211,12 @@ struct GpuPlanSink {
|
|
|
|
/// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10).
|
|
struct ExpertDispatch {
|
|
+ // Default-off local extension. The callback owns only kind==-1 entries and
|
|
+ // marks completed host rows as kind=3. Native hits/PCIe/remote rows are untouched.
|
|
+ using ExperimentalMiss = bool (*)(void*, int64_t, const float*, const int32_t*,
|
|
+ int64_t, int64_t, int32_t*, float*, std::string&);
|
|
+ ExperimentalMiss experimental_miss = nullptr;
|
|
+ void* experimental_miss_user = nullptr;
|
|
strata::kernels::cpu::ExpertPool* pool = nullptr;
|
|
ExpertSource* src = nullptr;
|
|
RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts
|
|
diff --git a/include/strata/core/keyless.hpp b/include/strata/core/keyless.hpp
|
|
new file mode 100644
|
|
index 00000000..4665c458
|
|
--- /dev/null
|
|
+++ b/include/strata/core/keyless.hpp
|
|
@@ -0,0 +1,11 @@
|
|
+#pragma once
|
|
+#include "strata/core/layout.hpp"
|
|
+#include <string>
|
|
+namespace strata::core {
|
|
+bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error);
|
|
+const float* keyless_routing(int64_t layer);
|
|
+}
|
|
+namespace strata::kernels {
|
|
+// In-place, one independent matrix for each query head. No cached keys are produced.
|
|
+void keyless_route_query(float* q, const float* output_major_matrices, int64_t tokens, int heads, int dim, void* stream);
|
|
+}
|
|
diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp
|
|
index a8965da1..e7cfeb24 100644
|
|
--- a/include/strata/core/layer.hpp
|
|
+++ b/include/strata/core/layer.hpp
|
|
@@ -204,6 +204,7 @@ struct QsaState {
|
|
uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode)
|
|
uint16_t* v_pool = nullptr;
|
|
/// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64.
|
|
+ bool without_key = false;
|
|
bool kv_int8 = false;
|
|
int8_t* k_q = nullptr;
|
|
int8_t* v_q = nullptr;
|
|
@@ -282,6 +283,8 @@ uint64_t qsa_kv_host_bytes();
|
|
/// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and
|
|
/// initializing the session; default off until gate G-C accepts it.
|
|
void qsa_set_kv_int8(bool enabled);
|
|
+void qsa_set_without_key(bool enabled);
|
|
+bool qsa_without_key();
|
|
/// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1)
|
|
void qsa_set_kv_int8_rotate(bool enabled);
|
|
bool qsa_kv_int8();
|
|
@@ -299,6 +302,7 @@ inline int qsa_kv_format(const QsaState& st) {
|
|
std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n");
|
|
std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu)
|
|
}
|
|
+ if (st.without_key) return strata::kernels::kKvValueInt8;
|
|
return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16;
|
|
}
|
|
uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st,
|
|
diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp
|
|
index 5717eb4f..29b064fb 100644
|
|
--- a/include/strata/core/verify.hpp
|
|
+++ b/include/strata/core/verify.hpp
|
|
@@ -213,6 +213,10 @@ private:
|
|
int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}]
|
|
float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd
|
|
int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids
|
|
+ float* trace_h_ = nullptr; // optional pinned K/V activation trace for offline keyless study
|
|
+ std::FILE* trace_file_ = nullptr;
|
|
+ float* trace_q_h_ = nullptr; // first accepted token's Q, per QSA layer
|
|
+ std::FILE* trace_q_file_ = nullptr;
|
|
float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd
|
|
int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k
|
|
float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k
|
|
diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp
|
|
index b3ebee34..90483fa0 100644
|
|
--- a/include/strata/kernels/kv_stream.hpp
|
|
+++ b/include/strata/kernels/kv_stream.hpp
|
|
@@ -38,12 +38,12 @@ struct KvHostPools {
|
|
uint16_t* v_scale = nullptr;
|
|
uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head
|
|
uint8_t* v_q4 = nullptr;
|
|
- bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; }
|
|
+ bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr || v_q != nullptr; }
|
|
};
|
|
|
|
/// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0.
|
|
/// (A bool `int8` argument still reads as kKvF16 / kKvInt8.)
|
|
-enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2 };
|
|
+enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvValueInt8 = 4 };
|
|
|
|
/// The residency map of a streamed layer, all device memory at fixed addresses (the graphs bake them in).
|
|
struct KvStreamMap {
|
|
diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp
|
|
index 3c6f8fab..688c74d9 100644
|
|
--- a/include/strata/kernels/ngram.hpp
|
|
+++ b/include/strata/kernels/ngram.hpp
|
|
@@ -22,6 +22,7 @@
|
|
// All of those are asserted observable in `ple_parity.cpp` rather than trusted.
|
|
#pragma once
|
|
|
|
+#include <cstddef>
|
|
#include <cstdint>
|
|
#include <string>
|
|
|
|
@@ -139,6 +140,21 @@ public:
|
|
/// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct).
|
|
bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io);
|
|
|
|
+ /// Experimental CPU quality arm: read rows from a verified KAR-2 archive
|
|
+ /// while the rest of the engine continues to use its normal model pack.
|
|
+ /// The CUDA selective-row path is measured separately and is not used here.
|
|
+ bool open_kar(const std::string& kar_path, uint32_t level, std::string& err,
|
|
+ uint64_t expected_rows = PLE_TABLE_ROWS);
|
|
+
|
|
+ /// Experimental bounded compressed-row cache. It accepts only the
|
|
+ /// level-2/group-32 KAR PLE layout and leaves the CPU gather available
|
|
+ /// for consumers that still use mapped host memory.
|
|
+ bool enable_kar_gpu_cache(uint32_t cache_mib, std::string& err);
|
|
+ bool kar_gpu_cache_enabled() const;
|
|
+ bool collect_device(float* device_out2560, void* stream, std::string& err);
|
|
+ bool gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out,
|
|
+ void* stream, std::string& err);
|
|
+
|
|
/// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1
|
|
/// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches.
|
|
bool issue(const uint32_t* rows16);
|
|
diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp
|
|
index 45c0f301..f67bfad2 100644
|
|
--- a/include/strata/kernels/qsa_decode_attn.hpp
|
|
+++ b/include/strata/kernels/qsa_decode_attn.hpp
|
|
@@ -21,6 +21,11 @@
|
|
namespace strata::kernels {
|
|
|
|
struct QsaAttnPools {
|
|
+ bool without_key = false;
|
|
+ const float* keyless_cos = nullptr;
|
|
+ const float* keyless_sin = nullptr;
|
|
+ int keyless_n_rot = 0;
|
|
+ const int32_t* keyless_mrope = nullptr; // optional per-cell time/height/width positions
|
|
const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8
|
|
const uint16_t* v_pool = nullptr;
|
|
const int8_t* k_q = nullptr; ///< int8 codes, same layout
|
|
diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp
|
|
index 759daa65..0d8453d9 100644
|
|
--- a/src/core/conversation_snapshot.cpp
|
|
+++ b/src/core/conversation_snapshot.cpp
|
|
@@ -59,6 +59,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index
|
|
}
|
|
l.value_data = l.data;
|
|
l.value_scales = l.scales;
|
|
+ if (st.without_key) { l.data = 0; l.scales = 0; }
|
|
if (st.kv_hybrid) {
|
|
if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv,
|
|
(uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) {
|
|
@@ -98,7 +99,7 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error
|
|
}
|
|
}
|
|
if (st.kv_mode == 2 && (!st.page_table ||
|
|
- (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale
|
|
+ (st.without_key ? !st.v_q || !st.v_scale : st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale
|
|
: !st.k_pool || !st.v_pool))) {
|
|
error = "conversation snapshot: invalid draft ring";
|
|
return false;
|
|
diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp
|
|
index da95113c..3792cd4b 100644
|
|
--- a/src/core/conversation_snapshot_test.cpp
|
|
+++ b/src/core/conversation_snapshot_test.cpp
|
|
@@ -42,13 +42,14 @@ struct Fixture {
|
|
}
|
|
Fixture(int fmt, int mode) {
|
|
auto& st = state;
|
|
- st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3;
|
|
+ st.kv_mode = mode; st.without_key = fmt==kKvValueInt8; st.kv_int8 = fmt==kKvInt8 || st.without_key; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3;
|
|
st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages;
|
|
st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2;
|
|
const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*((st.kv_int8 || st.kv_hybrid) ? 1:2);
|
|
const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv;
|
|
- sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0,
|
|
- fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4};
|
|
+ sizes = {rows*per, rows*per, (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0,
|
|
+ (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4};
|
|
+ if (st.without_key) { sizes[0]=0; sizes[2]=0; }
|
|
if (fmt==3) {
|
|
sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0,
|
|
(size_t)st.idx_pooled_rows*g.idx_key_dim*4};
|
|
@@ -58,9 +59,11 @@ struct Fixture {
|
|
alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per);
|
|
if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);}
|
|
sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4;
|
|
- } else if (fmt==kKvInt8) {
|
|
- alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per);
|
|
- alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2);
|
|
+ } else if (st.kv_int8) {
|
|
+ if (!st.without_key) alloc(st.k_q,slot_rows*per);
|
|
+ alloc(st.v_q,slot_rows*per);
|
|
+ if (!st.without_key) alloc(st.k_scale,slot_rows*(g.head_dim/64)*2);
|
|
+ alloc(st.v_scale,slot_rows*(g.head_dim/64)*2);
|
|
if (mode) {
|
|
alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true);
|
|
alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true);
|
|
@@ -105,7 +108,7 @@ bool equal(const ConversationKv& a,const ConversationKv& b) {
|
|
}
|
|
|
|
void full_session(int fmt, int mode, int experts) {
|
|
- Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2);
|
|
+ Fixture main(fmt,mode), draft((fmt==3 || fmt==kKvValueInt8)?kKvInt8:fmt,2);
|
|
auto& g=main.g;
|
|
g.n_layers=4; g.n_expert=experts;
|
|
g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8;
|
|
@@ -162,7 +165,7 @@ void full_session(int fmt, int mode, int experts) {
|
|
check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base");
|
|
ConversationKvReuse reuse{a.kv,65,dirty};
|
|
const uint8_t* original = nullptr;
|
|
- reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;});
|
|
+ reuse.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;});
|
|
main.fill_after(91,dirty); draft.fill_after(91,std::max<int64_t>(0,dirty-1));
|
|
cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn));
|
|
ids.resize(70);
|
|
@@ -179,7 +182,7 @@ void full_session(int fmt, int mode, int experts) {
|
|
incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) &&
|
|
equal(incremental.kv[1],fresh.kv[1]),"incremental capture equals full capture after growth or rewind");
|
|
check((dirty>=4)==(reused>0),"only complete unchanged pages or rows are retained");
|
|
- incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){
|
|
+ incremental.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){
|
|
check(p==original,"growth never reallocates the retained payload");return true;
|
|
});
|
|
check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot");
|
|
@@ -198,7 +201,7 @@ void full_session(int fmt, int mode, int experts) {
|
|
int main() {
|
|
int devices=0;
|
|
if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77;
|
|
- for (int fmt : std::array<int,4>{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) {
|
|
+ for (int fmt : std::array<int,5>{kKvF16,kKvInt8,kKvQ4,3,kKvValueInt8}) for (int mode : {0,1,2}) {
|
|
if (fmt==3 && mode!=0) continue;
|
|
Fixture f(fmt,mode);
|
|
if (fmt==3) {
|
|
@@ -227,6 +230,12 @@ int main() {
|
|
ConversationKv a,b,restored;
|
|
cuda_check(cudaDeviceSynchronize());
|
|
check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A");
|
|
+ if (fmt==kKvValueInt8) {
|
|
+ check(a.k.empty() && a.k_scale.empty() && !f.state.k_q && !f.state.host.k_q,
|
|
+ "V-only snapshot and resident/host pools have no K");
|
|
+ auto wrong=a; wrong.format=kKvInt8;
|
|
+ check(!conversation_kv_restore(wrong,f.state,f.g,upto,index,err),"reject K+V snapshot in V-only state");
|
|
+ }
|
|
check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload");
|
|
f.fill(177);
|
|
check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B");
|
|
@@ -247,13 +256,13 @@ int main() {
|
|
const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max<int64_t>(0,b1-f.state.n_slots);
|
|
const size_t block=kv_block_bytes(s,fmt)/2;
|
|
// Codes and scales are separate in INT8; check code bytes here.
|
|
- const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block;
|
|
- const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool;
|
|
+ const size_t code_block=(fmt==kKvInt8 || fmt==kKvValueInt8) ? s.page_size*s.n_head_kv*s.head_dim : block;
|
|
+ const void* slots=fmt==kKvValueInt8?(void*)f.state.v_q:fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool;
|
|
std::vector<uint8_t> got(code_block);
|
|
for (int64_t page=b0;page<b1;++page) {
|
|
cuda_check(cudaMemcpy(got.data(),(const uint8_t*)slots+(page%f.state.n_slots)*code_block,code_block,cudaMemcpyDeviceToHost));
|
|
std::vector<uint8_t> expected(code_block);
|
|
- check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page");
|
|
+ check((fmt==kKvValueInt8?a.v:a.k).read(expected.data(), page*code_block, code_block),"read segmented expected draft page");
|
|
check(got == expected,"draft ring contains restored pages");
|
|
}
|
|
}
|
|
@@ -276,7 +285,7 @@ int main() {
|
|
}
|
|
}
|
|
}
|
|
- for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512})
|
|
+ for (int fmt : {kKvF16,kKvInt8,kKvQ4,kKvValueInt8}) for (int mode : {0,1}) for (int experts : {256,512})
|
|
full_session(fmt,mode,experts);
|
|
for (int experts : {256,512}) full_session(3,0,experts);
|
|
std::printf("conversation_snapshot_test: %d checks passed\n",checks);
|
|
diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp
|
|
index 087854ed..4d3cb759 100644
|
|
--- a/src/core/expert_source.cpp
|
|
+++ b/src/core/expert_source.cpp
|
|
@@ -1745,6 +1745,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
|
|
for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2;
|
|
}
|
|
}
|
|
+ if (d.experimental_miss != nullptr) {
|
|
+ static thread_local std::string miss_error;
|
|
+ if (!d.experimental_miss(d.experimental_miss_user, d.layers, x_f, ids,
|
|
+ n_tok, k, kind, out, miss_error)) {
|
|
+ d.failed = true; d.fail = miss_error.c_str(); d.fail_layer = d.layers; return;
|
|
+ }
|
|
+ }
|
|
const auto c1 = std::chrono::steady_clock::now();
|
|
if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations
|
|
for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
|
|
@@ -1776,9 +1783,10 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
|
|
d.fail_expert = e;
|
|
return;
|
|
}
|
|
- if (kind[i] >= 0) { // CUDA0, PCIe, or a remote result staged into this row below
|
|
+ if (kind[i] >= 0) { // CUDA0, PCIe, remote, or completed experimental host row
|
|
if (kind[i] == 0) ++d.cache_hits;
|
|
- std::memset(row, 0, (size_t) H * sizeof(float));
|
|
+ if (kind[i] == 3) ++d.cache_refused;
|
|
+ else std::memset(row, 0, (size_t) H * sizeof(float));
|
|
continue;
|
|
}
|
|
++d.cache_refused;
|
|
diff --git a/src/core/keyless.cpp b/src/core/keyless.cpp
|
|
new file mode 100644
|
|
index 00000000..7699b579
|
|
--- /dev/null
|
|
+++ b/src/core/keyless.cpp
|
|
@@ -0,0 +1,79 @@
|
|
+#include "strata/core/keyless.hpp"
|
|
+#include <cuda_runtime.h>
|
|
+#include <array>
|
|
+#include <algorithm>
|
|
+#include <cmath>
|
|
+#include <cstring>
|
|
+#include <fstream>
|
|
+#include <map>
|
|
+#include <vector>
|
|
+
|
|
+namespace strata::core {
|
|
+namespace {
|
|
+std::map<int64_t, float*> routes;
|
|
+uint32_t u32(std::istream& f) {
|
|
+ unsigned char b[4]{}; f.read((char*) b, 4);
|
|
+ return (uint32_t)b[0] | (uint32_t)b[1]<<8 | (uint32_t)b[2]<<16 | (uint32_t)b[3]<<24;
|
|
+}
|
|
+uint64_t u64(std::istream& f) { const uint64_t a = u32(f); return a | (uint64_t)u32(f)<<32; }
|
|
+}
|
|
+const float* keyless_routing(int64_t layer) {
|
|
+ const auto it = routes.find(layer);
|
|
+ return it == routes.end() ? nullptr : it->second;
|
|
+}
|
|
+bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error) {
|
|
+ if (!routes.empty()) { error = "keyless routing already loaded"; return false; }
|
|
+ std::ifstream f(path, std::ios::binary);
|
|
+ std::array<char,8> magic{}; f.read(magic.data(), 8);
|
|
+ const uint32_t version = u32(f), layers = u32(f), heads = u32(f), dim = u32(f);
|
|
+ if (!f || std::memcmp(magic.data(), "SKLROUT1", 8) || version != 1 ||
|
|
+ layers != (uint32_t)g.n_qsa_layers() || heads != (uint32_t)g.n_head || dim != (uint32_t)g.head_dim || dim != 256) {
|
|
+ error = "invalid keyless artifact header/geometry"; return false;
|
|
+ }
|
|
+ std::map<int64_t, float*> pending;
|
|
+ auto fail = [&](const std::string& why) {
|
|
+ error = why; for (auto& row : pending) cudaFree(row.second); return false;
|
|
+ };
|
|
+ for (uint32_t ordinal = 0; ordinal < layers; ++ordinal) {
|
|
+ const uint32_t layer = u32(f);
|
|
+ if (!f || layer >= g.n_layers || !is_qsa_layer(g, layer) || pending.count(layer))
|
|
+ return fail("keyless artifact has invalid/duplicate layer");
|
|
+ for (const char* role : {"q", "k", "v"}) {
|
|
+ const uint32_t kind = u32(f); const uint64_t bytes = u64(f), wanted = u64(f);
|
|
+ const auto* w = weights.find("blk." + std::to_string(layer) + ".attn_" + role + ".weight");
|
|
+ // Quantized projection size is recorded by the source decoder. Bound before any device read.
|
|
+ const uint64_t expected_elements = (uint64_t)g.n_embd * g.head_dim *
|
|
+ (std::strcmp(role,"q") == 0 ? g.n_head * 2 : g.n_head_kv);
|
|
+ if (!f || !w || !w->native_data || w->native_type != (int)kind ||
|
|
+ bytes == 0 || bytes > expected_elements * 4 || expected_elements != (uint64_t)w->elements)
|
|
+ return fail("keyless artifact source projection geometry/type mismatch");
|
|
+ // NativeDense owns source GGUF blocks. Verify the artifact was derived from these actual bytes.
|
|
+ // Source byte length must agree with ggml geometry; ne0/ne1 cannot validate a quantized byte span.
|
|
+ const uint64_t block_elements = kind == 42 ? 64 : kind == 8 ? 32 : 256;
|
|
+ const uint64_t block_bytes = kind == 42 ? 18 : kind == 11 ? 110 : kind == 12 ? 144 :
|
|
+ kind == 13 ? 176 : kind == 14 ? 210 : kind == 23 ? 136 : kind == 8 ? 34 : 0;
|
|
+ if (!block_bytes || expected_elements % block_elements || bytes != expected_elements / block_elements * block_bytes)
|
|
+ return fail("keyless artifact unsupported/mismatched native projection encoding");
|
|
+ std::vector<uint8_t> raw((size_t)bytes);
|
|
+ if (cudaMemcpy(raw.data(), w->native_data, raw.size(), cudaMemcpyDeviceToHost) != cudaSuccess)
|
|
+ return fail("keyless source projection readback failed");
|
|
+ uint64_t hash = 0xcbf29ce484222325ull;
|
|
+ for (uint8_t byte : raw) hash = (hash ^ byte) * 0x100000001b3ull;
|
|
+ if (hash != wanted) return fail("keyless artifact source projection fingerprint mismatch");
|
|
+ }
|
|
+ std::vector<float> matrix((size_t)heads * dim * dim);
|
|
+ f.read((char*)matrix.data(), matrix.size()*sizeof(float));
|
|
+ if (!f || !std::all_of(matrix.begin(), matrix.end(), [](float v) { return std::isfinite(v); }))
|
|
+ return fail("truncated/nonfinite keyless query matrix");
|
|
+ float* device = nullptr;
|
|
+ if (cudaMalloc((void**)&device, matrix.size()*sizeof(float)) != cudaSuccess)
|
|
+ return fail("keyless query matrices do not fit in GPU memory");
|
|
+ pending[layer] = device;
|
|
+ if (cudaMemcpy(device, matrix.data(), matrix.size()*sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess)
|
|
+ return fail("keyless query matrix upload failed");
|
|
+ }
|
|
+ if (f.peek() != std::char_traits<char>::eof()) return fail("keyless artifact has trailing data");
|
|
+ routes = std::move(pending);
|
|
+ return true;
|
|
+}
|
|
+}
|
|
diff --git a/src/core/layer.cpp b/src/core/layer.cpp
|
|
index ff7fc17b..7e132895 100644
|
|
--- a/src/core/layer.cpp
|
|
+++ b/src/core/layer.cpp
|
|
@@ -1,6 +1,7 @@
|
|
|
|
// src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps.
|
|
#include "strata/core/layer.hpp"
|
|
+#include "strata/core/keyless.hpp"
|
|
#include "strata/core/native_head.hpp"
|
|
#include "strata/kernels/bf16_bits.hpp"
|
|
#include "strata/kernels/bf16_gemv.hpp"
|
|
@@ -173,7 +174,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset,
|
|
// namespace
|
|
void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; }
|
|
void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; }
|
|
-namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; }
|
|
+namespace { bool g_without_key = false, g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; }
|
|
+void qsa_set_without_key(bool enabled) { g_without_key = enabled; }
|
|
+bool qsa_without_key() { return g_without_key; }
|
|
void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; }
|
|
void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; }
|
|
bool qsa_kv_int8() { return g_kv_int8; }
|
|
@@ -512,6 +515,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) {
|
|
return p;
|
|
}
|
|
uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) {
|
|
+ if (g_without_key) return (uint64_t)pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) / 2 + 64;
|
|
if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation)
|
|
const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv;
|
|
return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 +
|
|
@@ -552,6 +556,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
|
|
const KvPlan p = kv_plan(s, max_cells, ring_cells);
|
|
const int64_t pages = p.pages;
|
|
Cursor c{(uint8_t*) base};
|
|
+ st.without_key = g_without_key;
|
|
st.kv_int8 = g_kv_int8 && !g_kv_q4;
|
|
st.kv_q4 = g_kv_q4;
|
|
// Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 -
|
|
@@ -578,9 +583,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
|
|
st.k_q4 = c.take<uint8_t>(rows * q4_row);
|
|
st.v_q4 = c.take<uint8_t>(rows * q4_row);
|
|
} else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too
|
|
- st.k_q = c.take<int8_t>(rows * s.head_dim);
|
|
+ if (!st.without_key) st.k_q = c.take<int8_t>(rows * s.head_dim);
|
|
st.v_q = c.take<int8_t>(rows * s.head_dim);
|
|
- st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
|
|
+ if (!st.without_key) st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
|
|
st.v_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
|
|
} else {
|
|
st.k_pool = c.take<uint16_t>(rows * s.head_dim);
|
|
@@ -646,9 +651,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
|
|
st.host.k_q4 = hc.take<uint8_t>(hrows * q4_row);
|
|
st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);
|
|
} else if (st.kv_int8) {
|
|
- st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);
|
|
+ if (!st.without_key) st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);
|
|
st.host.v_q = hc.take<int8_t>(hrows * s.head_dim);
|
|
- st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
|
|
+ if (!st.without_key) st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
|
|
st.host.v_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
|
|
} else {
|
|
st.host.k_pool = hc.take<uint16_t>(hrows * s.head_dim);
|
|
@@ -689,16 +694,16 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {
|
|
cudaStream_t cs = (cudaStream_t) stream;
|
|
const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size;
|
|
if (st.kv_hybrid) {
|
|
- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
|
|
- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
|
|
+ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
|
|
+ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
|
|
cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);
|
|
} else if (st.kv_q4) {
|
|
cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);
|
|
cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);
|
|
} else if (st.kv_int8) {
|
|
- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
|
|
+ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
|
|
cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs);
|
|
- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
|
|
+ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
|
|
cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
|
|
} else {
|
|
cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs);
|
|
@@ -716,6 +721,8 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {
|
|
strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) {
|
|
strata::kernels::QsaAttnPools pools;
|
|
pools.page_table = st.page_table;
|
|
+ pools.without_key = st.without_key;
|
|
+ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table();
|
|
if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; }
|
|
else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; }
|
|
else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; }
|
|
@@ -845,11 +852,12 @@ void stage_timing_report(int64_t n_layers) {
|
|
// needs nothing from the layer it is called for beyond its index.
|
|
static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off,
|
|
uint64_t n, void* stream);
|
|
-bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s);
|
|
+bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; if (st.without_key && pos_base != 0) { err = "V-only requires zero position base"; return false; } /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s);
|
|
const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) {
|
|
try {
|
|
if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream);
|
|
else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream);
|
|
+ if (st.without_key && data == b.qcur) keyless_route_query(data, keyless_routing(layer), 1, (int)g.n_head, (int)g.head_dim, stream);
|
|
if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream);
|
|
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream);
|
|
return true;
|
|
@@ -893,7 +901,7 @@ SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"
|
|
// k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this
|
|
// artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor,
|
|
// and "it happens to be uniform here" is the assumption that was wrong for `attn_q`.
|
|
-if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false;
|
|
+if (!st.without_key && !gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, !st.without_key && w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!st.without_key && !normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false;
|
|
// ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion).
|
|
// EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every
|
|
// launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The
|
|
@@ -947,7 +955,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2;
|
|
// KV streaming: every block the selection names is made resident before anything reads it
|
|
qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream);
|
|
if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // <Hq, Hk> = <q, k>
|
|
- if (g_fast_attn && !native_flash_attn_short && dump == nullptr) {
|
|
+ if (st.without_key || (g_fast_attn && !native_flash_attn_short && dump == nullptr)) {
|
|
const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st);
|
|
strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream);
|
|
} else {
|
|
@@ -1269,6 +1277,13 @@ bool ple_issue_token(const PleRun& p, std::string& err) {
|
|
|
|
bool ple_finish_token(const PleRun& p, void* stream, std::string& err) {
|
|
if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; }
|
|
+ if (p.table->kar_gpu_cache_enabled()) {
|
|
+ if (!p.table->collect_device(p.emb_dev, stream, err)) {
|
|
+ err = "ple_finish_token: " + err;
|
|
+ return false;
|
|
+ }
|
|
+ return true;
|
|
+ }
|
|
if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; }
|
|
if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float),
|
|
cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) {
|
|
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
|
|
index 17e36556..5db90887 100644
|
|
--- a/src/core/mtp.cpp
|
|
+++ b/src/core/mtp.cpp
|
|
@@ -212,6 +212,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
|
|
int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0;
|
|
// K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats
|
|
// only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback).
|
|
+ struct RestoreKeylessMode {
|
|
+ bool previous = qsa_without_key();
|
|
+ ~RestoreKeylessMode() { qsa_set_without_key(previous); }
|
|
+ } restore_keyless_mode;
|
|
+ qsa_set_without_key(false);
|
|
const bool kv_hybrid_was = qsa_kv_hybrid();
|
|
const bool kv_int8_was = qsa_kv_int8();
|
|
qsa_set_kv_hybrid(false);
|
|
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
|
|
index 999f85d8..58f7594b 100644
|
|
--- a/src/core/verify.cpp
|
|
+++ b/src/core/verify.cpp
|
|
@@ -1,5 +1,6 @@
|
|
// src/core/verify.cpp - see include/strata/core/verify.hpp.
|
|
#include "strata/core/verify.hpp"
|
|
+#include "strata/core/keyless.hpp"
|
|
#if defined(_WIN32)
|
|
#include <intrin.h>
|
|
#endif
|
|
@@ -179,7 +180,9 @@ Verifier::~Verifier() {
|
|
if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); }
|
|
if (commit_done_) cudaEventDestroy(commit_done_);
|
|
if (arena_) cudaFree(arena_);
|
|
- void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
|
|
+ if (trace_file_) std::fclose(trace_file_);
|
|
+ if (trace_q_file_) std::fclose(trace_q_file_);
|
|
+ void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, trace_h_, trace_q_h_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
|
|
h_flagA_, h_plan_, h_flagB_};
|
|
for (void* h : hosts)
|
|
if (h) cudaFreeHost(h);
|
|
@@ -202,6 +205,21 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
|
|
hits_ = hits;
|
|
head_ = head;
|
|
max_t_ = max_t;
|
|
+ if (const char* path = std::getenv("STRATA_KEYLESS_TRACE")) {
|
|
+ if (!*path) { err = "verify: STRATA_KEYLESS_TRACE needs a private output path"; return false; }
|
|
+ trace_file_ = std::fopen(path, "wb");
|
|
+ trace_q_file_ = std::fopen((std::string(path) + ".q").c_str(), "wb");
|
|
+ const size_t trace_bytes = (size_t) g.n_qsa_layers() * (size_t) max_t *
|
|
+ (size_t) g.n_head_kv * (size_t) g.head_dim * 2 * sizeof(float);
|
|
+ const size_t query_bytes = (size_t) g.n_qsa_layers() * (size_t) g.n_head *
|
|
+ (size_t) g.head_dim * sizeof(float);
|
|
+ if (!trace_file_ || !trace_q_file_ ||
|
|
+ cudaHostAlloc((void**) &trace_h_, trace_bytes, cudaHostAllocDefault) != cudaSuccess ||
|
|
+ cudaHostAlloc((void**) &trace_q_h_, query_bytes, cudaHostAllocDefault) != cudaSuccess) {
|
|
+ err = "verify: cannot create pinned keyless activation trace";
|
|
+ return false;
|
|
+ }
|
|
+ }
|
|
sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise
|
|
sampling_.temperature = 0.0f;
|
|
if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) {
|
|
@@ -557,6 +575,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
|
auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) {
|
|
if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs);
|
|
else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs);
|
|
+ if (st.without_key && norm == wqn) keyless_route_query(data, keyless_routing(l), rows / (int)NH, (int)NH, (int)HD, cs);
|
|
if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs);
|
|
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs);
|
|
};
|
|
@@ -569,16 +588,29 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
|
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);
|
|
stamp(l, 7, grp);
|
|
- native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
|
|
+ if (!st.without_key) native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
|
|
native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
|
|
- if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
|
|
- else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
|
|
+ if (!st.without_key && qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
|
|
+ else if (!st.without_key) for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
|
|
if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp)
|
|
fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
|
|
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
|
|
} else if (st.kv_hybrid) { // K8V4: only V is rotated
|
|
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
|
|
}
|
|
+ if (trace_h_) {
|
|
+ const size_t width = (size_t) NKV * HD;
|
|
+ for (int t = tb; t < te; ++t) {
|
|
+ float* dst = trace_h_ + ((size_t) qi * max_t_ + t) * 2 * width;
|
|
+ if (cudaMemcpyAsync(dst, kcur_ + (size_t) t * width, width * sizeof(float),
|
|
+ cudaMemcpyDeviceToHost, cs) != cudaSuccess ||
|
|
+ cudaMemcpyAsync(dst + width, vcur_ + (size_t) t * width, width * sizeof(float),
|
|
+ cudaMemcpyDeviceToHost, cs) != cudaSuccess) {
|
|
+ err = "verify: keyless trace copy could not be captured";
|
|
+ return false;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
stamp(l, 8, grp);
|
|
if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);
|
|
for (int t = tb; t < te; ++t) {
|
|
@@ -646,6 +678,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
|
const QsaAttnPools pools = qsa_attn_pools(st);
|
|
qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,
|
|
s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);
|
|
+ if (trace_q_h_ && tb == 0 &&
|
|
+ cudaMemcpyAsync(trace_q_h_ + (size_t) qi * NH * HD, qcur_,
|
|
+ (size_t) NH * HD * sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess) {
|
|
+ err = "verify: keyless query trace copy could not be captured";
|
|
+ return false;
|
|
+ }
|
|
stamp(l, 13, grp);
|
|
if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H
|
|
if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD,
|
|
@@ -1127,6 +1165,30 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
|
|
// beside the expert workers).
|
|
const cudaError_t se = cudaStreamSynchronize(cs_);
|
|
if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
|
|
+ if (trace_file_) {
|
|
+ const uint32_t count = (uint32_t) T;
|
|
+ const size_t width = (size_t) g_->n_head_kv * (size_t) g_->head_dim;
|
|
+ bool written = std::fwrite(&count, sizeof(count), 1, trace_file_) == 1 &&
|
|
+ std::fwrite(&pos0, sizeof(pos0), 1, trace_file_) == 1;
|
|
+ for (int64_t q = 0; written && q < g_->n_qsa_layers(); ++q)
|
|
+ for (int t = 0; written && t < T; ++t)
|
|
+ written = std::fwrite(trace_h_ + ((size_t) q * max_t_ + t) * 2 * width,
|
|
+ sizeof(float), 2 * width, trace_file_) == 2 * width;
|
|
+ if (!written || std::fflush(trace_file_) != 0) {
|
|
+ err = "verify: cannot write keyless activation trace";
|
|
+ return false;
|
|
+ }
|
|
+ const size_t query_width = (size_t) g_->n_head * (size_t) g_->head_dim;
|
|
+ bool q_written = std::fwrite(&count, sizeof(count), 1, trace_q_file_) == 1 &&
|
|
+ std::fwrite(&pos0, sizeof(pos0), 1, trace_q_file_) == 1 &&
|
|
+ std::fwrite(trace_q_h_, sizeof(float),
|
|
+ (size_t) g_->n_qsa_layers() * query_width, trace_q_file_) ==
|
|
+ (size_t) g_->n_qsa_layers() * query_width;
|
|
+ if (!q_written || std::fflush(trace_q_file_) != 0) {
|
|
+ err = "verify: cannot write keyless query trace";
|
|
+ return false;
|
|
+ }
|
|
+ }
|
|
progress_at("verify window: waiting for the expert copies", (int64_t) T);
|
|
cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one
|
|
if (prof_on_ && G == 1) { // the window's GPU stage stamps
|
|
diff --git a/src/kernels/cuda/keyless.cu b/src/kernels/cuda/keyless.cu
|
|
new file mode 100644
|
|
index 00000000..16485d30
|
|
--- /dev/null
|
|
+++ b/src/kernels/cuda/keyless.cu
|
|
@@ -0,0 +1,25 @@
|
|
+#include "strata/core/keyless.hpp"
|
|
+#include <cuda_runtime.h>
|
|
+#include <stdexcept>
|
|
+namespace strata::kernels {
|
|
+namespace {
|
|
+__global__ void route_kernel(float* q, const float* matrices, int heads) {
|
|
+ __shared__ float row[256];
|
|
+ const int d = threadIdx.x, h = blockIdx.x % heads;
|
|
+ float* query = q + (size_t)blockIdx.x * 256;
|
|
+ row[d] = query[d];
|
|
+ __syncthreads();
|
|
+ const float* weight = matrices + ((size_t)h * 256 + d) * 256;
|
|
+ float sum = 0;
|
|
+ for (int i = 0; i < 256; ++i) sum = fmaf(row[i], weight[i], sum);
|
|
+ query[d] = sum;
|
|
+}
|
|
+}
|
|
+void keyless_route_query(float* q, const float* matrices, int64_t tokens, int heads, int dim, void* stream) {
|
|
+ if (!q || !matrices || tokens < 1 || heads < 1 || dim != 256 || tokens > INT32_MAX / heads)
|
|
+ throw std::runtime_error("invalid keyless query routing geometry or artifact");
|
|
+ route_kernel<<<(unsigned)(tokens*heads),256,0,(cudaStream_t)stream>>>(q, matrices, heads);
|
|
+ const auto error = cudaGetLastError();
|
|
+ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
|
|
+}
|
|
+}
|
|
diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu
|
|
index fb2ccec4..077e3167 100644
|
|
--- a/src/kernels/cuda/kv_q8.cu
|
|
+++ b/src/kernels/cuda/kv_q8.cu
|
|
@@ -34,7 +34,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict
|
|
int head_dim, int page_size, KvHostPools host) {
|
|
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 = k_q == nullptr || 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
|
|
@@ -58,7 +58,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict
|
|
(is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q;
|
|
if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits;
|
|
}
|
|
- if (host.k_q != nullptr) {
|
|
+ if ((is_v ? host.v_q : host.k_q) != nullptr) {
|
|
const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
|
|
(is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q;
|
|
if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits;
|
|
@@ -104,7 +104,7 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_
|
|
const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
|
|
const KvHostPools* host) {
|
|
validate(s, "kv_append_q8");
|
|
- const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2);
|
|
+ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), k_q ? 2 : 1);
|
|
kv_append_q8_kernel<<<grid, KV_Q8_GROUP, 0, (cudaStream_t) stream>>>(
|
|
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{});
|
|
diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu
|
|
index ec01ff22..ae78d8f0 100644
|
|
--- a/src/kernels/cuda/kv_stream.cu
|
|
+++ b/src/kernels/cuda/kv_stream.cu
|
|
@@ -33,7 +33,11 @@ struct Runs {
|
|
Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) {
|
|
const int rows = (int) (s.n_head_kv * s.page_size);
|
|
Runs r{};
|
|
- if (fmt == kKvQ4) {
|
|
+ if (fmt == kKvValueInt8) {
|
|
+ r.src[0] = (const uint8_t*) host.v_q; r.dst[0] = (uint8_t*) slots.v_q; r.len[0] = rows * (int)s.head_dim;
|
|
+ r.src[1] = (const uint8_t*) host.v_scale; r.dst[1] = (uint8_t*) slots.v_scale; r.len[1] = rows * (int)(s.head_dim / KV_Q8_GROUP) * 2;
|
|
+ r.n = 2;
|
|
+ } else if (fmt == kKvQ4) {
|
|
const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim);
|
|
r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes;
|
|
r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes;
|
|
@@ -191,6 +195,7 @@ __global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slot
|
|
|
|
uint64_t kv_block_bytes(const QsaShapes& s, int fmt) {
|
|
const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size);
|
|
+ if (fmt == kKvValueInt8) return rows * ((uint64_t)s.head_dim + (uint64_t)(s.head_dim / KV_Q8_GROUP)*2);
|
|
if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2;
|
|
return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2
|
|
: rows * (uint64_t) s.head_dim * 2 * 2;
|
|
diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu
|
|
index 4035999a..c59f21d4 100644
|
|
--- a/src/kernels/cuda/qsa_decode_attn.cu
|
|
+++ b/src/kernels/cuda/qsa_decode_attn.cu
|
|
@@ -1,5 +1,6 @@
|
|
// src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp.
|
|
#include "strata/kernels/qsa_decode_attn.hpp"
|
|
+#include "strata/kernels/mrope.hpp"
|
|
#include "strata/kernels/kv_q8.hpp"
|
|
#include "strata/kernels/kv_q4.hpp"
|
|
|
|
@@ -71,7 +72,7 @@ __device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long
|
|
template <int KV_MODE>
|
|
__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
|
|
if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out);
|
|
- else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out);
|
|
+ else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out);
|
|
else if constexpr (KV_MODE == 3) {
|
|
// hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call
|
|
// reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review)
|
|
@@ -127,7 +128,22 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
|
|
continue;
|
|
}
|
|
float k8[8];
|
|
- load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
|
|
+ load8<KV_MODE>(p, KV_MODE == 4, srow[c], lane * 8, k8);
|
|
+ if constexpr (KV_MODE == 4) {
|
|
+ const int d0 = lane * 8, half = p.keyless_n_rot / 2;
|
|
+ if (d0 < p.keyless_n_rot) {
|
|
+ float paired[8];
|
|
+ load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired);
|
|
+ const int cell = ids[c0 + c];
|
|
+ for (int d = 0; d < 8; ++d) {
|
|
+ const int pair = (d0 + d) % half;
|
|
+ const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair);
|
|
+ const float co = p.keyless_cos[(size_t)rotary_pos * half + pair];
|
|
+ const float si = p.keyless_sin[(size_t)rotary_pos * half + pair];
|
|
+ k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
#pragma unroll
|
|
for (int h = 0; h < G; ++h) {
|
|
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
|
|
@@ -160,7 +176,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
|
|
float v;
|
|
if constexpr (KV_MODE == 0) {
|
|
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
|
|
- } else if constexpr (KV_MODE == 1) {
|
|
+ } else if constexpr (KV_MODE == 1 || KV_MODE == 4) {
|
|
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
|
|
v = (float) p.v_q[srow[c] * HD + t] * sc;
|
|
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
|
|
@@ -211,13 +227,18 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_
|
|
void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
|
|
int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
|
|
if (n_q <= 0) return;
|
|
- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps ||
|
|
+ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !steps ||
|
|
!pools.page_table || n_q > 65535) {
|
|
std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n");
|
|
std::exit(1);
|
|
}
|
|
- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
|
|
+ const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
|
|
: (pools.k_q != nullptr ? 1 : 0));
|
|
+ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 ||
|
|
+ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) {
|
|
+ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n");
|
|
+ std::exit(1);
|
|
+ }
|
|
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
|
|
// per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride
|
|
const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
|
|
@@ -227,7 +248,9 @@ 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;
|
|
- if (kv_mode == 3)
|
|
+ if (kv_mode == 4)
|
|
+ attn_chunk_kernel<4><<<grid, THREADS, 0, st>>>(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);
|
|
+ else if (kv_mode == 3)
|
|
attn_chunk_kernel<3><<<grid, THREADS, 0, st>>>(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);
|
|
else if (kv_mode == 2)
|
|
@@ -255,19 +278,25 @@ uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
|
|
|
|
void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step,
|
|
int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) {
|
|
- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step ||
|
|
+ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !step ||
|
|
!pools.page_table) {
|
|
std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n");
|
|
std::exit(1);
|
|
}
|
|
- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
|
|
+ const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
|
|
: (pools.k_q != nullptr ? 1 : 0));
|
|
- if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4)
|
|
+ if (kv_mode == 4 ? (!pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)
|
|
+ : (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4)
|
|
: (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale)
|
|
- : (!pools.k_pool || !pools.v_pool)))) {
|
|
+ : (!pools.k_pool || !pools.v_pool))))) {
|
|
std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n");
|
|
std::exit(1);
|
|
}
|
|
+ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 ||
|
|
+ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) {
|
|
+ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n");
|
|
+ std::exit(1);
|
|
+ }
|
|
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
|
|
float* part_acc = scratch;
|
|
float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
|
|
@@ -275,7 +304,9 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32
|
|
const float scale = 1.0f / sqrtf((float) HD);
|
|
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv);
|
|
cudaStream_t st = (cudaStream_t) stream;
|
|
- if (kv_mode == 3)
|
|
+ if (kv_mode == 4)
|
|
+ attn_chunk_kernel<4><<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks);
|
|
+ else if (kv_mode == 3)
|
|
attn_chunk_kernel<3><<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
|
|
scale, part_acc, part_m, part_l, n_chunks);
|
|
else if (kv_mode == 2)
|
|
diff --git a/src/kernels/keyless_parity.cpp b/src/kernels/keyless_parity.cpp
|
|
new file mode 100644
|
|
index 00000000..107ebf2b
|
|
--- /dev/null
|
|
+++ b/src/kernels/keyless_parity.cpp
|
|
@@ -0,0 +1,119 @@
|
|
+// Independent CPU reference for query routing and physical V-only attention.
|
|
+#include "strata/core/keyless.hpp"
|
|
+#include "strata/core/layer.hpp"
|
|
+#include "strata/kernels/qsa_decode_attn.hpp"
|
|
+#include "strata/kernels/f16_bits.hpp"
|
|
+#include "strata/kernels/kv_stream.hpp"
|
|
+#include <cuda_runtime.h>
|
|
+#include <algorithm>
|
|
+#include <cmath>
|
|
+#include <cstdio>
|
|
+#include <stdexcept>
|
|
+#include <vector>
|
|
+
|
|
+namespace {
|
|
+void check(cudaError_t e) { if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); }
|
|
+template<class T> T* device(const std::vector<T>& values) {
|
|
+ T* p; check(cudaMalloc((void**)&p, values.size()*sizeof(T)));
|
|
+ check(cudaMemcpy(p, values.data(), values.size()*sizeof(T), cudaMemcpyHostToDevice)); return p;
|
|
+}
|
|
+}
|
|
+int main() {
|
|
+ using namespace strata::kernels;
|
|
+ try {
|
|
+ int count=0; if (cudaGetDeviceCount(&count)!=cudaSuccess || count==0) return 77;
|
|
+ constexpr int H=24, D=256, KV=2, CELLS=96, PAGE=4, BATCH=3, CAP=96;
|
|
+ std::vector<float> query(BATCH*H*D), routing(H*D*D), routed(query.size()), co(CELLS*32), si(co.size());
|
|
+ for (size_t i=0;i<query.size();++i) query[i]=(float)((int)(i*17%103)-51)/51;
|
|
+ for (int h=0;h<H;++h) for(int d=0;d<D;++d) for(int j=0;j<D;++j)
|
|
+ routing[((size_t)h*D+d)*D+j]=(d==j?.8f:0.f)+(float)(((h*19+d*3+j*11)%17)-8)*.001f;
|
|
+ for (int b=0;b<BATCH;++b) for(int h=0;h<H;++h) for(int d=0;d<D;++d) {
|
|
+ double sum=0; for(int j=0;j<D;++j) sum+=(double)query[(b*H+h)*D+j]*routing[(h*D+d)*D+j];
|
|
+ routed[(b*H+h)*D+d]=(float)sum;
|
|
+ }
|
|
+ float *dq=device(query), *da=device(routing);
|
|
+ keyless_route_query(dq,da,BATCH,H,D,nullptr);
|
|
+ std::vector<float> actual(query.size()); check(cudaMemcpy(actual.data(),dq,actual.size()*4,cudaMemcpyDeviceToHost));
|
|
+ double route_error=0; for(size_t i=0;i<actual.size();++i) route_error=std::max(route_error,(double)std::abs(actual[i]-routed[i]));
|
|
+ if(route_error>2e-6) throw std::runtime_error("query routing disagrees with independent matrix product");
|
|
+ const int pos[BATCH]={31,63,95};
|
|
+ for(int p=0;p<CELLS;++p) for(int d=0;d<32;++d) {
|
|
+ const double angle=p*std::pow(1e7,-2.0*d/64);
|
|
+ co[p*32+d]=(float)std::cos(angle); si[p*32+d]=(float)std::sin(angle);
|
|
+ }
|
|
+ const std::vector<float> unrotated=routed;
|
|
+ std::vector<int32_t> positions(CELLS*3);
|
|
+ for(int cell=0;cell<CELLS;++cell) for(int sector=0;sector<3;++sector) positions[cell*3+sector]=cell/(sector+2);
|
|
+ const int32_t* dp=device(positions);
|
|
+ for(int vision=0;vision<2;++vision) {
|
|
+ routed=unrotated;
|
|
+ for(int b=0;b<BATCH;++b) for(int h=0;h<H;++h) for(int d=0;d<32;++d) {
|
|
+ const int i=(b*H+h)*D+d;
|
|
+ const float a=routed[i], v=routed[i+32], c=co[(vision?positions[pos[b]*3+d%3]:pos[b])*32+d], s=si[(vision?positions[pos[b]*3+d%3]:pos[b])*32+d];
|
|
+ routed[i]=a*c-v*s; routed[i+32]=a*s+v*c;
|
|
+ }
|
|
+ check(cudaMemcpy(dq,routed.data(),routed.size()*4,cudaMemcpyHostToDevice));
|
|
+ std::vector<int32_t> table(CELLS/PAGE), ids(BATCH*CAP,-1), steps(BATCH*kStepCount);
|
|
+ for(int page=0;page<CELLS/PAGE;++page) table[page]=(page*5+7)%(CELLS/PAGE);
|
|
+ std::vector<int8_t> values(CELLS*KV*D);
|
|
+ std::vector<uint16_t> scales(CELLS*KV*4);
|
|
+ for(int cell=0;cell<CELLS;++cell) for(int h=0;h<KV;++h) {
|
|
+ const int row=(table[cell/PAGE]*KV+h)*PAGE+cell%PAGE;
|
|
+ for(int d=0;d<D;++d) values[row*D+d]=(int8_t)((cell*7+h*37+d*13)%127-63);
|
|
+ for(int d=0;d<4;++d) scales[row*4+d]=f16_from_f32(.002f*(1+h+d));
|
|
+ }
|
|
+ for(int b=0;b<BATCH;++b) {
|
|
+ qsa_step_fill(steps.data()+b*kStepCount,pos[b],qsa_real_shapes());
|
|
+ int width=0; for(int cell=0;cell<=pos[b];++cell) if(cell%3!=1) ids[b*CAP+width++]=cell;
|
|
+ steps[b*kStepCount+kStepWidth]=width;
|
|
+ }
|
|
+ QsaAttnPools pools;
|
|
+ pools.without_key=true; pools.keyless_n_rot=64; pools.keyless_mrope=vision?dp:nullptr;
|
|
+ pools.v_q=device(values); pools.v_scale=device(scales); pools.page_table=device(table);
|
|
+ pools.keyless_cos=device(co); pools.keyless_sin=device(si);
|
|
+ auto *di=device(ids), *ds=device(steps);
|
|
+ std::vector<float> scratch(BATCH*qsa_decode_attn_scratch_floats(CAP,qsa_real_shapes())), result(BATCH*H*D);
|
|
+ float *dsc=device(scratch), *dout=device(result);
|
|
+ qsa_decode_attn_batch(dq,pools,di,ds,CAP,qsa_real_shapes(),dsc,dout,BATCH,nullptr);
|
|
+ check(cudaMemcpy(result.data(),dout,result.size()*4,cudaMemcpyDeviceToHost));
|
|
+ double error_sq=0, reference_sq=0, max_error=0;
|
|
+ for(int b=0;b<BATCH;++b) for(int h=0;h<H;++h) {
|
|
+ const int width=steps[b*kStepCount+kStepWidth], kvh=h/12;
|
|
+ std::vector<double> scores(width), weights(width), reference(D,0);
|
|
+ for(int j=0;j<width;++j) {
|
|
+ const int cell=ids[b*CAP+j], row=(table[cell/PAGE]*KV+kvh)*PAGE+cell%PAGE;
|
|
+ double sum=0;
|
|
+ for(int d=0;d<D;++d) {
|
|
+ double v=(double)values[row*D+d]*f32_from_f16(scales[row*4+d/64]);
|
|
+ if(d<64) {
|
|
+ const int other=d<32?d+32:d-32;
|
|
+ const double pair=(double)values[row*D+other]*f32_from_f16(scales[row*4+other/64]);
|
|
+ const int rotary_pos=vision?positions[cell*3+(d%32)%3]:cell;
|
|
+ v=v*co[rotary_pos*32+d%32]+(d<32?-1:1)*pair*si[rotary_pos*32+d%32];
|
|
+ }
|
|
+ sum+=routed[(b*H+h)*D+d]*v;
|
|
+ }
|
|
+ scores[j]=sum/16;
|
|
+ }
|
|
+ const double max=*std::max_element(scores.begin(),scores.end()); double total=0;
|
|
+ for(int j=0;j<width;++j) { weights[j]=std::exp(scores[j]-max); total+=weights[j]; }
|
|
+ for(int j=0;j<width;++j) {
|
|
+ const int cell=ids[b*CAP+j], row=(table[cell/PAGE]*KV+kvh)*PAGE+cell%PAGE;
|
|
+ for(int d=0;d<D;++d) reference[d]+=weights[j]/total*values[row*D+d]*f32_from_f16(scales[row*4+d/64]);
|
|
+ }
|
|
+ for(int d=0;d<D;++d) {
|
|
+ const double error=result[(b*H+h)*D+d]-reference[d];
|
|
+ error_sq+=error*error; reference_sq+=reference[d]*reference[d]; max_error=std::max(max_error,std::abs(error));
|
|
+ }
|
|
+ }
|
|
+ const double l2=std::sqrt(error_sq/reference_sq);
|
|
+ if(l2>1e-5 || max_error>1e-5) throw std::runtime_error("V-only attention disagrees with positional CPU reference");
|
|
+ if(kv_block_bytes(qsa_real_shapes(),kKvValueInt8)*2!=kv_block_bytes(qsa_real_shapes(),kKvInt8))
|
|
+ throw std::runtime_error("V-only block accounting is not half of K+V");
|
|
+ std::printf("mrope=%d query_max_abs_error=%.9g attention_relative_l2=%.9g attention_max_abs_error=%.9g\n",vision,route_error,l2,max_error);
|
|
+ }
|
|
+
|
|
+ std::printf("PASS: routed queries; three causal selections; permuted pages; raw value retrieval; no K allocation\n");
|
|
+ return 0;
|
|
+ } catch(const std::exception& e) { std::fprintf(stderr,"keyless parity: %s\n",e.what()); return 1; }
|
|
+}
|
|
diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp
|
|
index 07557347..e8b28765 100644
|
|
--- a/src/kernels/kv_stream_parity.cpp
|
|
+++ b/src/kernels/kv_stream_parity.cpp
|
|
@@ -24,11 +24,13 @@
|
|
#include <random>
|
|
#include <set>
|
|
#include <vector>
|
|
+#include <cmath>
|
|
|
|
namespace k = strata::kernels;
|
|
|
|
namespace {
|
|
int g_fail = 0;
|
|
+float *keyless_cos=nullptr, *keyless_sin=nullptr;
|
|
void ck(cudaError_t e, const char* w) {
|
|
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
|
|
}
|
|
@@ -55,10 +57,10 @@ struct Pools { // one K/V pool set of `pages` pages
|
|
const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);
|
|
p.k_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
|
|
p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
|
|
- } else if (fmt == k::kKvInt8) {
|
|
- p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
|
|
+ } else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) {
|
|
+ if (fmt != k::kKvValueInt8) p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
|
|
p.v_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
|
|
- p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
|
|
+ if (fmt != k::kKvValueInt8) p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
|
|
p.v_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
|
|
} else {
|
|
p.k_pool = host ? halloc<uint16_t>(rows * s.head_dim) : dalloc<uint16_t>(rows * s.head_dim);
|
|
@@ -68,6 +70,8 @@ struct Pools { // one K/V pool set of `pages` pages
|
|
k::QsaAttnPools attn(const int32_t* table) const {
|
|
k::QsaAttnPools a;
|
|
a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale;
|
|
+ a.without_key = p.v_q && !p.k_q;
|
|
+ a.keyless_cos=keyless_cos; a.keyless_sin=keyless_sin; a.keyless_n_rot=64;
|
|
a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table;
|
|
return a;
|
|
}
|
|
@@ -76,7 +80,7 @@ struct Pools { // one K/V pool set of `pages` pages
|
|
void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc,
|
|
const k::QsaShapes& s, int fmt, const k::KvHostPools* host) {
|
|
if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host);
|
|
- else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host);
|
|
+ else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host);
|
|
else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host);
|
|
}
|
|
|
|
@@ -103,7 +107,7 @@ std::vector<int32_t> selection(int64_t n_kv, int64_t width, std::mt19937& rng) {
|
|
}
|
|
|
|
bool run(int fmt) {
|
|
- const char* name = fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";
|
|
+ const char* name = fmt == k::kKvValueInt8 ? "v-only-int8" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";
|
|
k::QsaShapes s = k::qsa_real_shapes();
|
|
const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks
|
|
const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8;
|
|
@@ -111,6 +115,16 @@ bool run(int fmt) {
|
|
std::mt19937 rng(7 + 4 * fmt);
|
|
std::normal_distribution<float> nd(0.f, 1.f);
|
|
|
|
+ if (fmt == k::kKvValueInt8) {
|
|
+ std::vector<float> co(N*32), si(N*32);
|
|
+ for(int64_t pos=0;pos<N;++pos) for(int d=0;d<32;++d) {
|
|
+ const double angle=pos*std::pow(1e7,-2.0*d/64);
|
|
+ co[pos*32+d]=(float)std::cos(angle); si[pos*32+d]=(float)std::sin(angle);
|
|
+ }
|
|
+ keyless_cos=dalloc<float>(co.size()); keyless_sin=dalloc<float>(si.size());
|
|
+ ck(cudaMemcpy(keyless_cos,co.data(),co.size()*4,cudaMemcpyHostToDevice),"cos");
|
|
+ ck(cudaMemcpy(keyless_sin,si.data(),si.size()*4,cudaMemcpyHostToDevice),"sin");
|
|
+ }
|
|
Pools ref, slots, host;
|
|
ref.alloc(n_blocks, s, fmt, false);
|
|
slots.alloc(n_slots, s, fmt, false);
|
|
@@ -225,7 +239,9 @@ bool run(int fmt) {
|
|
}
|
|
} // namespace
|
|
|
|
-int main() {
|
|
+int main(int argc, char** argv) {
|
|
+ int count=0; if(cudaGetDeviceCount(&count)!=cudaSuccess || !count) return 77;
|
|
+ if(argc==2 && std::strcmp(argv[1],"--v-only")==0) return run(k::kKvValueInt8)?0:1;
|
|
std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n");
|
|
const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4);
|
|
if (!a || !b || !c) ++g_fail;
|
|
diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp
|
|
index 1a1552bf..bcb611c1 100644
|
|
--- a/src/kernels/ngram.cpp
|
|
+++ b/src/kernels/ngram.cpp
|
|
@@ -11,12 +11,31 @@
|
|
#include <cmath>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
+#include <algorithm>
|
|
+#include <memory>
|
|
+#include <string>
|
|
#if !defined(_WIN32)
|
|
#include <sys/mman.h>
|
|
#endif
|
|
#include <vector>
|
|
#include <stdexcept>
|
|
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE)
|
|
+#include <cstdlib>
|
|
+#include <mutex>
|
|
+#endif
|
|
+
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) || defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+#include <fcntl.h>
|
|
+#include <unistd.h>
|
|
+#endif
|
|
+
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+#include "kar_ple_cache.hpp"
|
|
+#include "libkar.h"
|
|
+#include <sys/stat.h>
|
|
+#endif
|
|
+
|
|
#if defined(_WIN32)
|
|
// `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below.
|
|
#define WIN32_LEAN_AND_MEAN
|
|
@@ -29,6 +48,69 @@ namespace strata::kernels {
|
|
namespace {
|
|
/// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`.
|
|
bool g_ple_prefetch = true;
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE)
|
|
+struct PleRowTrace {
|
|
+ int fd = -1;
|
|
+ std::mutex lock;
|
|
+ bool failed = false;
|
|
+
|
|
+ PleRowTrace() {
|
|
+ const char* path = std::getenv("STRATA_PLE_ROW_TRACE_PATH");
|
|
+ if (!path) return;
|
|
+ if (!*path) {
|
|
+ std::fprintf(stderr, "PLE row trace needs a private output path\n");
|
|
+ return;
|
|
+ }
|
|
+ fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);
|
|
+ if (fd < 0) {
|
|
+ std::perror("cannot create private PLE row trace");
|
|
+ return;
|
|
+ }
|
|
+ constexpr char header[] = "# strata-ple-rows v1: 16 global u32 row IDs per line\n";
|
|
+ if (write(fd, header, sizeof(header) - 1) != static_cast<ssize_t>(sizeof(header) - 1)) {
|
|
+ std::fprintf(stderr, "cannot write PLE row trace header\n");
|
|
+ failed = true;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ ~PleRowTrace() { if (fd >= 0) close(fd); }
|
|
+
|
|
+ void emit(const uint32_t* rows) {
|
|
+ if (fd < 0) return;
|
|
+ std::lock_guard<std::mutex> guard(lock);
|
|
+ if (failed) return;
|
|
+ char line[PLE_N_HEADS * 12];
|
|
+ size_t used = 0;
|
|
+ for (int h = 0; h < PLE_N_HEADS; ++h) {
|
|
+ const int written = std::snprintf(line + used, sizeof(line) - used, "%u%c",
|
|
+ rows[h], h + 1 == PLE_N_HEADS ? '\n' : ' ');
|
|
+ if (written < 0 || static_cast<size_t>(written) >= sizeof(line) - used) {
|
|
+ failed = true;
|
|
+ std::fprintf(stderr, "PLE row trace line exceeded its buffer\n");
|
|
+ return;
|
|
+ }
|
|
+ used += static_cast<size_t>(written);
|
|
+ }
|
|
+ size_t done = 0;
|
|
+ while (done < used) {
|
|
+ const ssize_t n = write(fd, line + done, used - done);
|
|
+ if (n < 0 && errno == EINTR) continue;
|
|
+ if (n <= 0) {
|
|
+ failed = true;
|
|
+ if (n < 0) std::perror("cannot write PLE row trace");
|
|
+ else std::fprintf(stderr, "cannot write PLE row trace: short write\n");
|
|
+ return;
|
|
+ }
|
|
+ done += static_cast<size_t>(n);
|
|
+ }
|
|
+ }
|
|
+};
|
|
+
|
|
+PleRowTrace& ple_row_trace() {
|
|
+ static PleRowTrace trace;
|
|
+ return trace;
|
|
+}
|
|
+#endif
|
|
} // namespace
|
|
|
|
void ple_prefetch_enable(bool on) { g_ple_prefetch = on; }
|
|
@@ -89,6 +171,9 @@ void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const
|
|
out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]);
|
|
}
|
|
}
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE)
|
|
+ ple_row_trace().emit(out + i * PLE_N_HEADS);
|
|
+#endif
|
|
}
|
|
}
|
|
|
|
@@ -153,6 +238,51 @@ struct PleTable::Impl {
|
|
bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL
|
|
float scale = 1.0f; // the FP8 table's one scale
|
|
uint32_t rb = PLE_ROW_BYTES; // bytes per row
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ struct KarPart {
|
|
+ uint32_t number = 0;
|
|
+ uint64_t row_base = 0;
|
|
+ const kar_tensor_info* tensor = nullptr;
|
|
+ };
|
|
+ kar_archive* kar = nullptr;
|
|
+ int kar_fd = -1;
|
|
+ const uint8_t* kar_map = nullptr;
|
|
+ size_t kar_bytes = 0;
|
|
+ uint32_t kar_level = 0;
|
|
+ std::string kar_format;
|
|
+ std::vector<KarPart> kar_parts;
|
|
+ std::unique_ptr<strata::kar::PleRowCache> kar_gpu_cache;
|
|
+ void decode_kar_row(uint32_t row, float* out160) const {
|
|
+ const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row,
|
|
+ [](const KarPart& item, uint32_t wanted) {
|
|
+ return item.row_base + item.tensor->row_count <= wanted;
|
|
+ });
|
|
+ const kar_tensor_info* t = part->tensor;
|
|
+ const uint64_t local_row = uint64_t(row) - part->row_base;
|
|
+ const uint64_t first_word = local_row * t->row_words;
|
|
+ const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2;
|
|
+ for (uint32_t word = 0; word < t->row_words; ++word) {
|
|
+ const uint64_t source_word = first_word + word;
|
|
+ const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32));
|
|
+ const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset));
|
|
+ uint32_t bits[8] = {};
|
|
+ for (uint32_t level = 0; level < kar_level; ++level) {
|
|
+ const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes
|
|
+ + source_word * 4;
|
|
+ bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) |
|
|
+ (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24);
|
|
+ }
|
|
+ for (uint32_t bit = 0; bit < 32; ++bit) {
|
|
+ uint32_t code = 0;
|
|
+ for (uint32_t level = 0; level < kar_level; ++level)
|
|
+ code = (code << 1) | ((bits[level] >> bit) & 1u);
|
|
+ const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2));
|
|
+ out160[word * 32 + bit] = book * scale;
|
|
+ }
|
|
+ }
|
|
+ bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2);
|
|
+ }
|
|
+#endif
|
|
void decode(const uint8_t* row, float* out160) const {
|
|
if (fp8) fp8_e4m3_dequant_row(row, scale, out160);
|
|
else if (q5_0)
|
|
@@ -164,6 +294,177 @@ struct PleTable::Impl {
|
|
PleTable::PleTable() : impl_(new Impl) {}
|
|
PleTable::~PleTable() { close(); delete impl_; }
|
|
|
|
+bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err,
|
|
+ uint64_t expected_rows) {
|
|
+#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ (void) kar_path; (void) level; (void) expected_rows;
|
|
+ err = "experimental KAR PLE support is not compiled into this engine";
|
|
+ return false;
|
|
+#else
|
|
+ close();
|
|
+ if (level < 1 || level > 8 || expected_rows == 0) {
|
|
+ err = "KAR PLE level or expected row count is invalid";
|
|
+ return false;
|
|
+ }
|
|
+ kar_archive* archive = nullptr;
|
|
+ const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive);
|
|
+ if (status != KAR_OK) {
|
|
+ err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error();
|
|
+ return false;
|
|
+ }
|
|
+ impl_->kar = archive;
|
|
+ impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC);
|
|
+ struct stat file_info {};
|
|
+ if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 ||
|
|
+ uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) {
|
|
+ err = "KAR PLE cannot reopen the verified archive at its expected length";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ impl_->kar_bytes = size_t(file_info.st_size);
|
|
+ void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0);
|
|
+ if (map == MAP_FAILED) {
|
|
+ err = "KAR PLE cannot map the verified archive";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ impl_->kar_map = static_cast<const uint8_t*>(map);
|
|
+ const std::string parent = "per_layer_token_embd.weight";
|
|
+ const std::string prefix = parent + "#strata-part-";
|
|
+ uint32_t declared_parts = 0;
|
|
+ for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) {
|
|
+ const kar_tensor_info* t = kar_tensor(impl_->kar, i);
|
|
+ const std::string name = t->name;
|
|
+ uint32_t number = 0, total = 0;
|
|
+ if (name == parent) {
|
|
+ number = total = 1;
|
|
+ } else if (name.rfind(prefix, 0) == 0) {
|
|
+ char extra = 0;
|
|
+ if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) {
|
|
+ err = "KAR PLE part name is malformed";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ } else {
|
|
+ continue;
|
|
+ }
|
|
+ if (!number || !total || number > total || (declared_parts && declared_parts != total) ||
|
|
+ t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 ||
|
|
+ t->nesting != KAR_TOPDOWN || t->n_dims != 2 ||
|
|
+ t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 ||
|
|
+ t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 ||
|
|
+ level < t->planes_min || level > t->planes_max) {
|
|
+ err = "KAR PLE part geometry or precision level differs from the model";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ declared_parts = total;
|
|
+ impl_->kar_parts.push_back({number, 0, t});
|
|
+ }
|
|
+ std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(),
|
|
+ [](const Impl::KarPart& left, const Impl::KarPart& right) {
|
|
+ return left.number < right.number;
|
|
+ });
|
|
+ if (!declared_parts || impl_->kar_parts.size() != declared_parts) {
|
|
+ err = "KAR PLE parts are absent or incomplete";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ uint64_t rows = 0;
|
|
+ for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) {
|
|
+ auto& part = impl_->kar_parts[i];
|
|
+ if (part.number != i + 1 || part.tensor->row_count == 0 ||
|
|
+ part.tensor->row_count > expected_rows - rows) {
|
|
+ err = "KAR PLE parts are out of order or exceed expected rows";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ part.row_base = rows;
|
|
+ rows += part.tensor->row_count;
|
|
+ }
|
|
+ if (rows != expected_rows) {
|
|
+ err = "KAR PLE row count differs from the model";
|
|
+ close();
|
|
+ return false;
|
|
+ }
|
|
+ impl_->n_rows = rows;
|
|
+ impl_->kar_level = level;
|
|
+ impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU";
|
|
+ impl_->mode = PleIo::Mmap;
|
|
+ return true;
|
|
+#endif
|
|
+}
|
|
+
|
|
+bool PleTable::enable_kar_gpu_cache(uint32_t cache_mib, std::string& err) {
|
|
+#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ (void) cache_mib;
|
|
+ err = "experimental KAR PLE support is not compiled into this engine";
|
|
+ return false;
|
|
+#else
|
|
+ if (!impl_->kar || impl_->kar_level != 2 || impl_->kar_gpu_cache) {
|
|
+ err = "KAR PLE GPU cache requires an open level-2 archive and no existing cache";
|
|
+ return false;
|
|
+ }
|
|
+ std::vector<strata::kar::PlePart> parts;
|
|
+ parts.reserve(impl_->kar_parts.size());
|
|
+ for (const auto& part : impl_->kar_parts) parts.push_back({part.row_base, part.tensor});
|
|
+ auto cache = std::make_unique<strata::kar::PleRowCache>();
|
|
+ if (!cache->open(impl_->kar_map, impl_->kar_bytes, parts, cache_mib, 65536, err)) return false;
|
|
+ impl_->kar_gpu_cache = std::move(cache);
|
|
+ impl_->kar_format = "KAR-L2-GPU-cache";
|
|
+ return true;
|
|
+#endif
|
|
+}
|
|
+
|
|
+bool PleTable::kar_gpu_cache_enabled() const {
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ return impl_->kar_gpu_cache != nullptr;
|
|
+#else
|
|
+ return false;
|
|
+#endif
|
|
+}
|
|
+
|
|
+bool PleTable::collect_device(float* device_out2560, void* stream, std::string& err) {
|
|
+#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ (void) device_out2560; (void) stream;
|
|
+ err = "experimental KAR PLE support is not compiled into this engine";
|
|
+ return false;
|
|
+#else
|
|
+ if (!impl_->kar_gpu_cache || !impl_->pending) {
|
|
+ err = "KAR PLE GPU collect requires a cache and an issued token";
|
|
+ return false;
|
|
+ }
|
|
+ if (!impl_->kar_gpu_cache->enqueue(impl_->rows, PLE_N_HEADS, device_out2560,
|
|
+ reinterpret_cast<cudaStream_t>(stream), err)) return false;
|
|
+ impl_->pending = false;
|
|
+ return true;
|
|
+#endif
|
|
+}
|
|
+
|
|
+bool PleTable::gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out,
|
|
+ void* stream, std::string& err) {
|
|
+#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ (void) rows; (void) n_tokens; (void) device_out; (void) stream;
|
|
+ err = "experimental KAR PLE support is not compiled into this engine";
|
|
+ return false;
|
|
+#else
|
|
+ if (!impl_->kar_gpu_cache || impl_->pending || !rows || !device_out ||
|
|
+ n_tokens == 0 || n_tokens > 65536) {
|
|
+ err = "KAR PLE GPU gather requires a cache, no pending token, and 1..65536 tokens";
|
|
+ return false;
|
|
+ }
|
|
+ const size_t count = n_tokens * PLE_N_HEADS;
|
|
+ const size_t chunk_rows = std::min<size_t>(65536, impl_->kar_gpu_cache->slots());
|
|
+ for (size_t offset = 0; offset < count; offset += chunk_rows) {
|
|
+ const size_t length = std::min(chunk_rows, count - offset);
|
|
+ if (!impl_->kar_gpu_cache->enqueue(rows + offset, length,
|
|
+ device_out + offset * PLE_HEAD_DIM,
|
|
+ reinterpret_cast<cudaStream_t>(stream), err)) return false;
|
|
+ }
|
|
+ return true;
|
|
+#endif
|
|
+}
|
|
+
|
|
bool PleTable::open(const std::string& gguf_path, std::string& err) {
|
|
return open(gguf_path, err, PleIoOptions{});
|
|
}
|
|
@@ -280,6 +581,19 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
|
|
}
|
|
|
|
void PleTable::close() {
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ impl_->kar_gpu_cache.reset();
|
|
+ if (impl_->kar_map) munmap(const_cast<uint8_t*>(impl_->kar_map), impl_->kar_bytes);
|
|
+ impl_->kar_map = nullptr;
|
|
+ impl_->kar_bytes = 0;
|
|
+ if (impl_->kar_fd >= 0) ::close(impl_->kar_fd);
|
|
+ impl_->kar_fd = -1;
|
|
+ if (impl_->kar) kar_close(impl_->kar);
|
|
+ impl_->kar = nullptr;
|
|
+ impl_->kar_parts.clear();
|
|
+ impl_->kar_level = 0;
|
|
+ impl_->kar_format.clear();
|
|
+#endif
|
|
impl_->reader.close();
|
|
impl_->pending = false;
|
|
impl_->locked = false; // the unmap below releases the lock
|
|
@@ -293,14 +607,31 @@ void PleTable::close() {
|
|
impl_->fp8 = false;
|
|
}
|
|
|
|
-bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); }
|
|
+bool PleTable::is_open() const {
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ if (impl_->kar) return true;
|
|
+#endif
|
|
+ return impl_->data != nullptr || impl_->reader.is_open();
|
|
+}
|
|
bool PleTable::locked() const { return impl_->locked; }
|
|
-const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; }
|
|
+const char* PleTable::format() const {
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ if (impl_->kar) return impl_->kar_format.c_str();
|
|
+#endif
|
|
+ return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL";
|
|
+}
|
|
PleIo PleTable::mode() const { return impl_->mode; }
|
|
uint64_t PleTable::rows() const { return impl_->n_rows; }
|
|
uint64_t PleTable::bytes_read() const { return impl_->bytes_read; }
|
|
|
|
void PleTable::read_row(uint32_t row, float* out160) const {
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ if (impl_->kar) {
|
|
+ if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float));
|
|
+ else impl_->decode_kar_row(row, out160);
|
|
+ return;
|
|
+ }
|
|
+#endif
|
|
if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
|
|
uint8_t raw[PLE_ROW_BYTES_MAX];
|
|
std::string err;
|
|
@@ -378,6 +709,21 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s
|
|
void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); }
|
|
|
|
std::string PleTable::io_report() const {
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE)
|
|
+ if (impl_->kar_gpu_cache) {
|
|
+ const auto s = impl_->kar_gpu_cache->stats();
|
|
+ char buf[300];
|
|
+ std::snprintf(buf, sizeof buf,
|
|
+ "PLE GPU cache: %llu hits, %llu misses (%.2f%% hit), %u slots (%.1f MiB compressed), "
|
|
+ "%llu compressed bytes, %llu H2D argument bytes",
|
|
+ (unsigned long long) s.hits, (unsigned long long) s.misses,
|
|
+ s.hits + s.misses ? 100.0 * double(s.hits) / double(s.hits + s.misses) : 0.0,
|
|
+ impl_->kar_gpu_cache->slots(), double(impl_->kar_gpu_cache->slots()) * 64.0 / 1048576.0,
|
|
+ (unsigned long long) s.compressed_bytes,
|
|
+ (unsigned long long) s.host_to_device_bytes);
|
|
+ return buf;
|
|
+ }
|
|
+#endif
|
|
if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {};
|
|
const strata::ngram::ReaderStats s = impl_->reader.snapshot();
|
|
char buf[400];
|
|
diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu
|
|
index de833442..4c5f4b82 100644
|
|
--- a/src/prefill/kernels.cu
|
|
+++ b/src/prefill/kernels.cu
|
|
@@ -604,8 +604,9 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res
|
|
uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,
|
|
strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) {
|
|
const int64_t t = blockIdx.x;
|
|
- const int kvh = blockIdx.y, g = blockIdx.z >> 1;
|
|
- const bool is_v = (blockIdx.z & 1) != 0;
|
|
+ const bool value_only = k_pool == nullptr && k_q == nullptr;
|
|
+ const int kvh = blockIdx.y, g = value_only ? blockIdx.z : blockIdx.z >> 1;
|
|
+ const bool is_v = value_only || (blockIdx.z & 1) != 0;
|
|
const int d = g * 64 + threadIdx.x;
|
|
const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d];
|
|
const int64_t pos = pos0 + t;
|
|
@@ -633,11 +634,11 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res
|
|
(is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q;
|
|
if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb;
|
|
}
|
|
- if (host.k_q != nullptr) {
|
|
+ if ((is_v ? host.v_q : host.k_q) != nullptr) {
|
|
(is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q;
|
|
if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb;
|
|
}
|
|
- if (stage.k_q != nullptr) {
|
|
+ if ((is_v ? stage.v_q : stage.k_q) != nullptr) {
|
|
(is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q;
|
|
if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb;
|
|
}
|
|
@@ -665,7 +666,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in
|
|
uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,
|
|
void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) {
|
|
if (T <= 0) return;
|
|
- kv_append_kernel<<<dim3((unsigned) T, 2, 8), 64, 0, (cudaStream_t) stream>>>(
|
|
+ kv_append_kernel<<<dim3((unsigned) T, 2, (k_pool || k_q) ? 8 : 4), 64, 0, (cudaStream_t) stream>>>(
|
|
K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale,
|
|
host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{});
|
|
check("kv_append");
|
|
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
|
|
index ed47b975..37edb9f0 100644
|
|
--- a/src/prefill/prefill.cpp
|
|
+++ b/src/prefill/prefill.cpp
|
|
@@ -13,10 +13,12 @@
|
|
#include "strata/kernels/iq_kernels.hpp"
|
|
#include "strata/kernels/cpu/expert_layout.hpp"
|
|
#include "strata/kernels/qsa.hpp"
|
|
+#include "strata/kernels/mrope.hpp"
|
|
#include "strata/kernels/kv_stream.hpp"
|
|
#include "strata/kernels/cvec.hpp"
|
|
#include "strata/kernels/kv_q4.hpp"
|
|
#include "strata/core/layer.hpp"
|
|
+#include "strata/core/keyless.hpp"
|
|
#include "strata/core/native_head.hpp"
|
|
#include "strata/kernels/verify_kernels.hpp"
|
|
#include "strata/kernels/qsa_decode_attn.hpp"
|
|
@@ -40,6 +42,8 @@
|
|
#include <mutex>
|
|
#include <thread>
|
|
#include <vector>
|
|
+#include <fstream>
|
|
+#include <filesystem>
|
|
|
|
#ifndef STRATA_PREFILL_MMQ
|
|
// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere.
|
|
@@ -386,9 +390,9 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k
|
|
st.k_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
|
|
st.v_q4 = o.take<uint8_t>(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok);
|
|
} else if (q0.kv_int8) {
|
|
- st.k_q = o.take<int8_t>(rows * s.head_dim, ok);
|
|
+ if (!q0.without_key) st.k_q = o.take<int8_t>(rows * s.head_dim, ok);
|
|
st.v_q = o.take<int8_t>(rows * s.head_dim, ok);
|
|
- st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
|
|
+ if (!q0.without_key) st.k_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
|
|
st.v_scale = o.take<uint16_t>(rows * (s.head_dim / 64), ok);
|
|
} else {
|
|
st.k_pool = o.take<uint16_t>(rows * s.head_dim, ok);
|
|
@@ -998,6 +1002,21 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
const core::ModelGeometry& g = *m.g;
|
|
core::SessionState& ss = *m.ss;
|
|
const auto t_start = Clock::now();
|
|
+ // Offline teacher capture for fitting only the paper's query-routing parameters.
|
|
+ // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode.
|
|
+ std::ofstream keyless_trace;
|
|
+ if (const char* path = std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) {
|
|
+ if (!*path || n > 4096 || pos0 != 0 || ss.qsa_states[0].without_key || std::filesystem::exists(path)) {
|
|
+ err = "keyless teacher trace requires a new private file, ordinary K+V and at most 4096 prompt tokens";
|
|
+ return false;
|
|
+ }
|
|
+ keyless_trace.open(path, std::ios::binary);
|
|
+ if (!keyless_trace) { err = "cannot open keyless teacher trace"; return false; }
|
|
+ std::filesystem::permissions(path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write);
|
|
+ keyless_trace.write("SKLTRACE", 8);
|
|
+ const uint32_t header[5] = {1, (uint32_t)g.n_qsa_layers(), (uint32_t)g.n_head, (uint32_t)g.n_head_kv, (uint32_t)g.head_dim};
|
|
+ keyless_trace.write((const char*)header, sizeof(header));
|
|
+ }
|
|
const int64_t LB = stage_lb_, LE = stage_le_;
|
|
// the next stage reads chunk c on a thread while this one reads chunk c + 1 (declared first: an early return
|
|
// waits for it before anything it reads goes away)
|
|
@@ -1020,6 +1039,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
// after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows
|
|
// depend only on the tokens (the two before a position name its n-grams), so this is the same data.
|
|
const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE;
|
|
+ const bool ple_gpu_cache = ple_on && ss.ple.table->kar_gpu_cache_enabled();
|
|
// the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token);
|
|
// STRATA_PLE_BATCH=0 keeps the per-token block (the A/B)
|
|
static const bool ple_batch_env = [] {
|
|
@@ -1030,7 +1050,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
(ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) &&
|
|
m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64;
|
|
const int32_t prev0[2] = {prev[0], prev[1]};
|
|
- auto ple_gather = [&m, &ss, tokens, n, prev0](int64_t c0, int buf, std::string& e) -> bool {
|
|
+ auto ple_gather = [&m, &ss, tokens, n, prev0, ple_gpu_cache](int64_t c0, int buf, std::string& e) -> bool {
|
|
const int64_t T = std::min(m.T, n - c0);
|
|
auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens
|
|
int32_t pv[2] = {at(c0), at(c0 + 1)};
|
|
@@ -1041,7 +1061,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
pv[0] = pv[1];
|
|
pv[1] = tok;
|
|
}
|
|
- return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e);
|
|
+ return ple_gpu_cache || ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T,
|
|
+ m.ple_emb_host[buf], e);
|
|
};
|
|
std::string ple_next_err;
|
|
std::future<bool> ple_next; // declared after everything it reads: an early return waits for it
|
|
@@ -1112,21 +1133,27 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
// ---- the PLE rows of the whole chunk, one batched SSD request (read ahead on a thread, see ple_gather)
|
|
if (ple_on) {
|
|
const auto tp = Clock::now();
|
|
- if (!ple_next.valid()) {
|
|
+ if (ple_gpu_cache) {
|
|
+ if (!ple_gather(c0, 0, err) ||
|
|
+ !ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T,
|
|
+ m.ple_emb, m.cs, err)) return false;
|
|
+ } else if (!ple_next.valid()) {
|
|
if (!ple_gather(c0, ple_buf, err)) return false;
|
|
} else if (!ple_next.get()) {
|
|
err = ple_next_err;
|
|
return false;
|
|
}
|
|
- cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs);
|
|
- cudaEventRecord(m.ple_copied[ple_buf], m.cs);
|
|
- if (c0 + m.T < n) {
|
|
- cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done
|
|
- ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] {
|
|
- return ple_gather(c1, b, ple_next_err);
|
|
- });
|
|
+ if (!ple_gpu_cache) {
|
|
+ cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs);
|
|
+ cudaEventRecord(m.ple_copied[ple_buf], m.cs);
|
|
+ if (c0 + m.T < n) {
|
|
+ cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done
|
|
+ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] {
|
|
+ return ple_gather(c1, b, ple_next_err);
|
|
+ });
|
|
+ }
|
|
+ ple_buf ^= 1;
|
|
}
|
|
- ple_buf ^= 1;
|
|
stats_.ms_ple += ms_since(tp);
|
|
}
|
|
for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; }
|
|
@@ -1374,13 +1401,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
*wikn = need(v, "indexer.k_norm.weight", err);
|
|
if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
|
|
pt.mark(kPfQsa, cs);
|
|
- if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
|
|
+ if (!st.without_key && !native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
|
|
if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
|
|
if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
|
|
if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
|
|
if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
|
|
- rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs);
|
|
- rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs);
|
|
+ if (!st.without_key) rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs);
|
|
+ if (!st.without_key) rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs);
|
|
// KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the
|
|
// chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks
|
|
const bool staged = st.kv_mode == 1;
|
|
@@ -1413,6 +1440,19 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
}
|
|
split_q(m.Qf, m.q, T, m.cs);
|
|
rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs);
|
|
+ if (keyless_trace.is_open()) {
|
|
+ const int32_t record[3] = {(int32_t)l, (int32_t)p0, (int32_t)T};
|
|
+ keyless_trace.write((const char*)record, sizeof(record));
|
|
+ for (const auto& tensor : std::vector<std::pair<const float*,size_t>>{
|
|
+ {m.q,(size_t)T*24*256}, {m.Kc,(size_t)T*2*256}, {m.Vc,(size_t)T*2*256}}) {
|
|
+ std::vector<float> host(tensor.second);
|
|
+ if (cudaMemcpyAsync(host.data(), tensor.first, host.size()*sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess ||
|
|
+ cudaStreamSynchronize(cs) != cudaSuccess) { err="keyless teacher readback failed"; return false; }
|
|
+ keyless_trace.write((const char*)host.data(), host.size()*sizeof(float));
|
|
+ }
|
|
+ if (!keyless_trace) { err="keyless teacher trace write failed"; return false; }
|
|
+ }
|
|
+ if (st.without_key) strata::kernels::keyless_route_query(m.q, core::keyless_routing(l), T, 24, 256, m.cs);
|
|
rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs);
|
|
if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs);
|
|
rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs);
|
|
@@ -1539,15 +1579,17 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
|
|
}
|
|
}
|
|
}
|
|
- const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table)
|
|
+ strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table)
|
|
: core::qsa_attn_pools(st);
|
|
+ pools.without_key = st.without_key;
|
|
+ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table();
|
|
pt.mark(kPfQsaAttn, cs);
|
|
// perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level
|
|
// accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the
|
|
// decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K,
|
|
// V dequantized from its q4_0 blocks to fp16 at gather)
|
|
static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr;
|
|
- if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,
|
|
+ if (st.without_key || old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s,
|
|
m.attn, T, m.cs))
|
|
for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) {
|
|
const int64_t nb = std::min(m.attn_batch, T - t0);
|
|
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
|
|
index 53c38a00..1e8cdfa3 100644
|
|
--- a/src/program/generate.cpp
|
|
+++ b/src/program/generate.cpp
|
|
@@ -20,6 +20,9 @@
|
|
#include "strata/core/conversation_memory.hpp"
|
|
#include "strata/core/coupled_draft.hpp"
|
|
#include "strata/core/expert_source.hpp"
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS)
|
|
+#include "kar_expert_miss.hpp"
|
|
+#endif
|
|
#include "strata/core/pinned.hpp"
|
|
#include "strata/core/remote_experts.hpp"
|
|
#include "strata/core/on_device.hpp"
|
|
@@ -50,6 +53,7 @@
|
|
#include "strata/core/mtp.hpp"
|
|
#include "strata/prefill/prefill.hpp"
|
|
#include "strata/core/native_dense.hpp"
|
|
+#include "strata/core/keyless.hpp"
|
|
#include "strata/program/logits_selection.hpp"
|
|
#include "strata/program/conv_cache.hpp"
|
|
#include "strata/spec/draft_policy.hpp"
|
|
@@ -220,6 +224,9 @@ struct Options {
|
|
std::string embd_gguf;
|
|
/// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM.
|
|
std::string ple_io = "direct";
|
|
+ std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native
|
|
+ uint32_t ple_kar_level = 2;
|
|
+ uint32_t ple_kar_gpu_cache_mib = 0; ///< opt-in bounded compressed GPU PLE cache; 0 keeps CPU gather
|
|
int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables
|
|
int ple_inflight = 64;
|
|
double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this
|
|
@@ -423,6 +430,9 @@ void usage() {
|
|
" --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n"
|
|
" --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n"
|
|
" shard that holds per_layer_token_embd.weight when not given\n"
|
|
+ " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n"
|
|
+ " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n"
|
|
+ " --ple-kar-gpu-cache-mib N experimental compressed PLE row cache in VRAM (1..1024; level 2)\n"
|
|
" --no-ple explicit diagnostic ablation of the PLE layer\n"
|
|
" --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"
|
|
" reads, the table never enters RAM or the file cache; mmap: A/B arm;\n"
|
|
@@ -1053,6 +1063,29 @@ int main(int argc, char** argv) {
|
|
else if (a == "--dump-halves") o.dump_halves = next("--dump-halves");
|
|
else if (a == "--dump-routing") o.dump_routing = next("--dump-routing");
|
|
else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf");
|
|
+ else if (a == "--ple-kar") o.ple_kar = next("--ple-kar");
|
|
+ else if (a == "--ple-kar-level") {
|
|
+ const std::string value = next("--ple-kar-level");
|
|
+ unsigned level = 0;
|
|
+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level);
|
|
+ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() ||
|
|
+ level < 1 || level > 8) {
|
|
+ std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n");
|
|
+ return 2;
|
|
+ }
|
|
+ o.ple_kar_level = level;
|
|
+ }
|
|
+ else if (a == "--ple-kar-gpu-cache-mib") {
|
|
+ const std::string value = next("--ple-kar-gpu-cache-mib");
|
|
+ unsigned mib = 0;
|
|
+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), mib);
|
|
+ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() ||
|
|
+ mib < 1 || mib > 1024) {
|
|
+ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib must be 1..1024\n");
|
|
+ return 2;
|
|
+ }
|
|
+ o.ple_kar_gpu_cache_mib = mib;
|
|
+ }
|
|
else if (a == "--no-ple") o.no_ple = true;
|
|
else if (a == "--ple-io") o.ple_io = next("--ple-io");
|
|
else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache"));
|
|
@@ -1254,6 +1287,10 @@ int main(int argc, char** argv) {
|
|
}
|
|
}
|
|
strata::core::set_coupled_draft(o.coupled_draft);
|
|
+ if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) {
|
|
+ std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n");
|
|
+ return 2;
|
|
+ }
|
|
if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))
|
|
std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",
|
|
o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");
|
|
@@ -1469,6 +1506,11 @@ int main(int argc, char** argv) {
|
|
std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n");
|
|
return 2;
|
|
}
|
|
+ const char* keyless_path = std::getenv("STRATA_KEYLESS_ROUTING");
|
|
+ if (keyless_path && (!*keyless_path || o.kv != "int8" || o.gpu_stages || !o.dump_halves.empty() || std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE") || (std::getenv("STRATA_KV_ROT") && std::getenv("STRATA_KV_ROT")[0] == '1'))) {
|
|
+ std::fprintf(stderr, "strata: keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps\n"); return 2;
|
|
+ }
|
|
+ strata::core::qsa_set_without_key(keyless_path != nullptr);
|
|
strata::core::qsa_set_kv_int8(o.kv == "int8");
|
|
strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp)
|
|
// STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to
|
|
@@ -1547,6 +1589,15 @@ int main(int argc, char** argv) {
|
|
std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n");
|
|
return 2;
|
|
}
|
|
+ if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) ||
|
|
+ (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) {
|
|
+ std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n");
|
|
+ return 2;
|
|
+ }
|
|
+ if (o.ple_kar_gpu_cache_mib && (o.ple_kar.empty() || o.ple_kar_level != 2)) {
|
|
+ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib requires --ple-kar at level 2\n");
|
|
+ return 2;
|
|
+ }
|
|
if (o.native_ple_postops && o.no_ple) {
|
|
std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n");
|
|
return 2;
|
|
@@ -1843,6 +1894,37 @@ int main(int argc, char** argv) {
|
|
rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale());
|
|
}
|
|
}
|
|
+ const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE");
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS)
|
|
+ strata::kar::ExpertMiss kar_expert_miss;
|
|
+ if (kar_expert_archive != nullptr) {
|
|
+ const char* level_text = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL");
|
|
+ if (!native_pack || o.no_pool || !split_devs.empty() || remote_caches ||
|
|
+ !level_text || std::strlen(level_text) != 1 || level_text[0] < '1' || level_text[0] > '8' ||
|
|
+ g.n_embd != strata::kernels::cpu::H) {
|
|
+ std::fprintf(stderr, "strata generate: experimental KAR misses require a native pack, one GPU, "
|
|
+ "the expert pool and explicit STRATA_NEXT_KAR_EXPERTS_LEVEL=1..8\n");
|
|
+ return 2;
|
|
+ }
|
|
+ for (const auto& f : strata::kernels::cpu::expert_layout().fmt)
|
|
+ if (f.n_embd != strata::kernels::cpu::H || f.n_ff != strata::kernels::cpu::FF) {
|
|
+ std::fprintf(stderr, "strata generate: unsupported KAR expert geometry\n"); return 2;
|
|
+ }
|
|
+ if (!kar_expert_miss.open(kar_expert_archive, (uint32_t) g.n_layers, (uint32_t) g.n_expert,
|
|
+ (uint32_t) g.n_embd, strata::kernels::cpu::FF,
|
|
+ (uint32_t) (level_text[0] - '0'), err)) {
|
|
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1;
|
|
+ }
|
|
+ // Native resident hits are the baseline. Route all otherwise CPU/PCIe
|
|
+ // misses to the explicit experimental arm; use pcie-frac=0 in its baseline.
|
|
+ o.pcie_frac = 0;
|
|
+ }
|
|
+#else
|
|
+ if (kar_expert_archive != nullptr) {
|
|
+ std::fprintf(stderr, "strata generate: this build has no experimental KAR expert support\n");
|
|
+ return 2;
|
|
+ }
|
|
+#endif
|
|
strata::core::NativeEmbed native_embed;
|
|
if (native_pack) {
|
|
if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical ||
|
|
@@ -1965,6 +2047,10 @@ int main(int argc, char** argv) {
|
|
return 2;
|
|
}
|
|
|
|
+ if (keyless_path && !strata::core::keyless_load(keyless_path, wt, g, err)) {
|
|
+ std::fprintf(stderr, "strata: keyless routing: %s\n", err.c_str()); return 1;
|
|
+ }
|
|
+ if (keyless_path) std::fprintf(stderr, "strata: experimental V-only QSA query routing; indexer and MTP keys retained; quality gate pending\n");
|
|
strata::core::SessionState ss;
|
|
void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve)
|
|
// **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session
|
|
@@ -2041,15 +2127,26 @@ int main(int argc, char** argv) {
|
|
pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0;
|
|
if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0;
|
|
}
|
|
- if (!ple_table.open(o.ple_gguf, err, pio)) {
|
|
+ const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio)
|
|
+ : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err);
|
|
+ if (!ple_open) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
+ if (o.ple_kar_gpu_cache_mib && !ple_table.enable_kar_gpu_cache(o.ple_kar_gpu_cache_mib, err)) {
|
|
+ std::fprintf(stderr, "strata generate: PLE GPU cache: %s\n", err.c_str());
|
|
+ return 1;
|
|
+ }
|
|
if (pio.lock)
|
|
std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n",
|
|
ple_table.locked() ? "locked in RAM" : "loaded (not locked)",
|
|
std::chrono::duration<double>(Clock::now() - tpl).count());
|
|
- if (pio.keepalive_ms > 0)
|
|
+ if (!o.ple_kar.empty())
|
|
+ std::fprintf(stderr, "strata generate: experimental PLE KAR %s arm at level %u%s\n",
|
|
+ o.ple_kar_gpu_cache_mib ? "bounded GPU-cache" : "CPU quality",
|
|
+ o.ple_kar_level,
|
|
+ o.ple_kar_gpu_cache_mib ? " (prefill/decode CUDA, speculative verification CPU)" : "");
|
|
+ else if (pio.keepalive_ms > 0)
|
|
std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after "
|
|
"%.0f ms without a read, until %.0f s after the last request "
|
|
"(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s);
|
|
@@ -2468,7 +2565,8 @@ int main(int argc, char** argv) {
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n",
|
|
- (unsigned long long) ple_table.rows(), o.ple_gguf.c_str());
|
|
+ (unsigned long long) ple_table.rows(),
|
|
+ o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str());
|
|
}
|
|
}
|
|
for (size_t i = 0; i < stages.size(); ++i) {
|
|
@@ -3022,6 +3120,12 @@ int main(int argc, char** argv) {
|
|
}
|
|
|
|
Drive drive;
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS)
|
|
+ if (kar_expert_archive != nullptr) {
|
|
+ drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch;
|
|
+ drive.d.experimental_miss_user = &kar_expert_miss;
|
|
+ }
|
|
+#endif
|
|
for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
|
|
drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r];
|
|
drive.d.hit_cpu_order = o.expert_cache_cpu_order;
|
|
@@ -4791,6 +4895,10 @@ int main(int argc, char** argv) {
|
|
// unknown keys are skipped: the ids start at the first token without '='
|
|
}
|
|
}
|
|
+ if (kar_expert_archive != nullptr && req_pcie_frac != 0.0) {
|
|
+ std::printf("ERR experimental KAR misses require pcie_frac=0\n");
|
|
+ continue;
|
|
+ }
|
|
std::string emb_path;
|
|
if (geni && endp != nullptr) {
|
|
while (*endp == ' ') ++endp;
|
|
@@ -5586,6 +5694,8 @@ int main(int argc, char** argv) {
|
|
const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim);
|
|
a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b},
|
|
{h ? st.host.k_scale : st.k_scale, scb}};
|
|
+ } else if (st.without_key) {
|
|
+ a = {{h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.v_scale : st.v_scale, scb}};
|
|
} else if (st.kv_int8) {
|
|
a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb},
|
|
{h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}};
|
|
@@ -5651,6 +5761,11 @@ int main(int argc, char** argv) {
|
|
100.0 * (double) req_hits / (double) req_look,
|
|
(long long) req_hits, (long long) req_look);
|
|
}
|
|
+#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS)
|
|
+ if (kar_expert_archive != nullptr)
|
|
+ std::fprintf(stderr, "strata serve: KAR verifier entries computed since startup: %llu\n",
|
|
+ (unsigned long long) kar_expert_miss.computed());
|
|
+#endif
|
|
// the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain
|
|
// mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it)
|
|
if (src.complement_ready())
|
|
@@ -5703,6 +5818,8 @@ int main(int argc, char** argv) {
|
|
remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r],
|
|
remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]);
|
|
}
|
|
+ if (o.stats && ple_table.kar_gpu_cache_enabled())
|
|
+ std::fprintf(stderr, "strata serve: %s\n", ple_table.io_report().c_str());
|
|
return 0;
|
|
}
|
|
|