sycl: port upstream 0.1.38
3-way merge from the port's "main + PRs" migration to dpct of upstream 0.1.38 (prefill.cpp re-merged with the histogram diff: upstream's peer-device and fused restructure kept, the port's edits carried over - the stager's GGUF job, the stream-all gate, the fp16 NaN checks; generate.cpp: the pipelined profile fill beside upstream's prefetching serial fill; mtp/verify: the SYCL host mapping). - the PRs' header forks dropped: upstream has them now - stubs: --peer-device (peer_experts.cpp; open refuses) and the fused int8 prompt kernels (moe_fused_stub.cpp; MMQ is not built here) - off on SYCL: the sm_90 cluster greedy sampler and QSA top-k (fixups.py) - fused_gr: dpct's undeduced kernel names filled in (fixups.py) - STRATA_GDN_KEYHEAD stays opt-in on the port (upstream's gate is NVIDIA SM counts) - version 0.1.38 Tested on the B70: build clean; native_grouped, iq_multi, gr, qsa, kv_hybrid, quantize_act parity pass, qsa_prompt_attn's int8/fp16 pass (its new Q4_0 tensor-core cases are refused: not in the port); Coder short/long, IQ2_XS, 40K outputs identical; 128K int8 KV streaming 892 / 66.8 tok/s; GR_DOWN_MAX4 neutral, GDN_KEYHEAD 8% slower (stays off).
This commit is contained in:
1 parent
733590721d
commit
b7760573ec
26 files changed
+3989
-1010
No files matched your search
+14
-1
@@ -28,7 +28,7 @@ PCIe 3.0 x8 slot (the card trains at Gen3 x8 there; it can do Gen5 x16).
|
||||
|
||||
Decode speed with speculative decoding depends on the text: code drafts well, prose less so (see "Speed depends
|
||||
on the text"). The SYCL numbers are greedy runs of the engine (as in "How to run it by hand" below, 256 new
|
||||
tokens) on engine 0.1.31-sycl (2026-10-01; 0.1.32-0.1.35-sycl reproduce them exactly);
|
||||
tokens) on engine 0.1.31-sycl (2026-10-01; 0.1.32-0.1.38-sycl reproduce them exactly);
|
||||
"Decode round 2" below lists what each change bought.
|
||||
|
||||
## Setup
|
||||
@@ -559,6 +559,19 @@ page-locked batches of 64, and a batch's copies run while the next one is read.
|
||||
(0.33 -> 1.34 GB/s); a whole Coder start from the engine's launch to its first token 82 s -> 26 s, the IQ2_XS
|
||||
120 s -> 41 s (its 8.2 GB host mirror is ~9 s of the rest). Output identical. `STRATA_FILL_SERIAL=1` is the old fill.
|
||||
|
||||
**The 0.1.38 merge (2026-10-03).** Upstream 0.1.35 -> 0.1.38 (83 commits) merged the seven PRs the port had taken
|
||||
early, so their header forks in `sycl/include` are gone; the merge base for the 3-way merge was the port's own "main +
|
||||
PRs" migration. New in the port with it: the DeltaNet output norm without its dead FP32 store, two prompt-path
|
||||
fixes (the fused layout's buffers, the streamed walk's resident lookup), `STRATA_GR_DOWN_MAX4=1` (opt-in; neutral on
|
||||
the B70: 2,184-token prompt 793 vs 788 tok/s, decode 76.2 vs 76.3). Stubbed in the port: `--peer-device` (a second
|
||||
GPU as an expert-cache tier: upstream's code is CUDA calls; `open` refuses with a message) and the fused int8 prompt
|
||||
kernels (#136, part of the MMQ library the port does not build). Off on SYCL: the sm_90 thread-block-cluster greedy
|
||||
sampler and QSA top-k (no SYCL counterpart; the callers take the plain kernels). `STRATA_GDN_KEYHEAD=1` stays opt-in
|
||||
(still 8% slower here: 727 vs 788 tok/s). `qsa_prompt_attn_parity` now also tests upstream's Q4_0 tensor-core mode
|
||||
(#452), which the port does not have: those cases report "refused" (the int8 and fp16 XMX cases pass); a `--kv
|
||||
q4_0` prompt takes the older kernel, as before. Outputs identical (Coder, IQ2_XS, 40K); 128K int8 KV streaming
|
||||
892 / 66.8 tok/s.
|
||||
|
||||
**0.1.35 and seven open upstream PRs (2026-10-02).** Upstream main 0.1.33 -> 0.1.35 merged as before, then seven open
|
||||
PRs ported into `sycl/` ahead of upstream (one dpct run of main + all of them, 3-way merged into only the files they
|
||||
touch; `sycl/tools/merge_upstream.py`). Their header changes live in `sycl/include` until upstream merges them.
|
||||
|
||||
+5
-3
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# Device code is JIT-compiled from SPIR-V unless STRATA_SYCL_AOT names a device (bmg-g31 for the Arc Pro B70).
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(strata_sycl VERSION 0.1.35 LANGUAGES C CXX) # the upstream engine version this port tracks
|
||||
project(strata_sycl VERSION 0.1.38 LANGUAGES C CXX) # the upstream engine version this port tracks
|
||||
set(STRATA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -156,14 +156,16 @@ target_link_libraries(strata_kernels PUBLIC strata_core)
|
||||
strata_resolve(_engine 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) # 0.1.31: the conversation snapshots (#216)
|
||||
src/core/conversation_memory.cpp # 0.1.31: the conversation snapshots (#216)
|
||||
src/core/peer_experts.cpp) # 0.1.36+: --peer-device (a stub in the port: no second GPU tier yet)
|
||||
add_library(strata_engine STATIC ${_engine} ${CMAKE_CURRENT_SOURCE_DIR}/src/core/gguf_expert_source.cpp)
|
||||
target_include_directories(strata_engine PRIVATE ${STRATA_ROOT}/src/core) # conversation_checked.hpp (#include "...")
|
||||
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu)
|
||||
|
||||
# cuBLAS -> oneMKL through dpct::blas (needs the MKL SYCL BLAS domain)
|
||||
strata_resolve(_prefill src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp)
|
||||
add_library(strata_prefill STATIC ${_prefill})
|
||||
add_library(strata_prefill STATIC ${_prefill}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_fused_stub.cpp) # upstream's fused int8 kernels: not built here
|
||||
target_compile_options(strata_prefill PUBLIC -qmkl=sequential)
|
||||
target_link_options(strata_prefill PUBLIC -qmkl=sequential)
|
||||
target_link_libraries(strata_prefill PUBLIC strata_engine)
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// include/strata/core/peer_experts.hpp - multi-GPU: a second expert tier on another GPU.
|
||||
//
|
||||
// The primary GPU (device 0) keeps everything it had: the dense weights, the KV cache, the MTP layer, its own
|
||||
// adaptive expert tier and the captured verify graph. This class adds an expert tier on a SECOND card. From
|
||||
// the verify graph's point of view nothing changes: for each layer the pool thread decides which routed experts
|
||||
// the primary computes (its VRAM tier, the PCIe share), and every remaining expert is a "CPU row" the graph reads
|
||||
// from mapped host memory after the pool raises its flag. The peer takes the rows whose experts it holds: the
|
||||
// pool thread launches them on the peer right after publishing the primary's plan, the CPU computes the rest at
|
||||
// the same time, and the peer's rows are written into the same mapped rows before the pool returns.
|
||||
//
|
||||
// The peer computes with the SAME kernels as the primary's hit path (q8_1 activations + native_expert_grouped),
|
||||
// from the same activation values, so an expert gives bit-identical rows on either card.
|
||||
//
|
||||
// The tier follows the conversation like the primary's: `adapt` swaps the most-routed experts that neither card
|
||||
// holds into the peer's least-used slots (per layer, so a slot keeps its layer's blob size).
|
||||
#pragma once
|
||||
|
||||
#define DPCT_PROFILING_ENABLED
|
||||
#include <sycl/sycl.hpp>
|
||||
#include <dpct/dpct.hpp>
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
#include "strata/core/expert_source.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
/// multi-GPU: set once at startup when a peer device is configured (--peer-device N). The mapped host buffers
|
||||
/// the peer card writes into are then allocated with cudaHostAllocPortable; without a peer the flag stays off.
|
||||
void set_peer_portable(bool on);
|
||||
bool peer_portable();
|
||||
|
||||
class PeerExperts {
|
||||
public:
|
||||
PeerExperts() = default;
|
||||
~PeerExperts();
|
||||
PeerExperts(const PeerExperts&) = delete;
|
||||
PeerExperts& operator=(const PeerExperts&) = delete;
|
||||
|
||||
/// Opens the tier on `device`: fills it with the first pairs of `ranked` that `primary` does not hold, as many
|
||||
/// as fit in the card's free memory minus `reserve_mib` (`max_slots` > 0 caps the count).
|
||||
bool open(int device, const std::vector<std::pair<int32_t, int32_t>>& ranked, const ExpertCache& primary,
|
||||
ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots,
|
||||
std::string& err);
|
||||
void close();
|
||||
bool valid() const { return device_ >= 0; }
|
||||
int device() const { return device_; }
|
||||
|
||||
/// Whether the peer holds (layer, expert) right now.
|
||||
bool has(int64_t layer, int64_t expert) const { return res_[(size_t) (layer * n_expert_ + expert)] >= 0; }
|
||||
|
||||
/// The device address of (layer, expert)'s blob on the peer, or null when it is not resident.
|
||||
const uint8_t* slot_ptr(int64_t layer, int64_t expert) {
|
||||
const int32_t sl = res_[(size_t) (layer * n_expert_ + expert)];
|
||||
return sl >= 0 ? cache_.device_slot(sl) : nullptr;
|
||||
}
|
||||
/// Whether the primary (device 0) and the peer can read each other's memory directly (NVLink / PCIe P2P).
|
||||
bool p2p() const { return p2p_; }
|
||||
|
||||
/// Starts the peer's share of one layer: the entries i with kind[i] == 2 (x: n_tok rows of n_embd floats).
|
||||
/// multi-GPU: with `out` (pinned, portable host rows) the peer writes its rows straight into
|
||||
/// out[entry] with a scatter kernel (no D2H copy + host memcpy in finish); STRATA_PEER_DIRECT=0: the old way.
|
||||
bool launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k, const int32_t* kind,
|
||||
std::string& err, float* out = nullptr);
|
||||
/// Waits for the launched share and writes its rows into `out` (row i = entry i, n_embd floats).
|
||||
bool finish(float* out, std::string& err);
|
||||
|
||||
/// Adaptive tier: swap up to `max_swaps` experts routed at least twice that neither the primary (`res0`, slot
|
||||
/// or -1) nor the peer holds into the peer's least-used slots. Copies run on the peer's refill stream; a
|
||||
/// swapped-in expert becomes resident at `apply_pending`. Call only between verify windows.
|
||||
bool adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err);
|
||||
void apply_pending(bool wait);
|
||||
|
||||
int64_t resident() const { return resident_; }
|
||||
/// the last launch writes its rows into the host rows itself (the caller must not touch them)
|
||||
bool launched_direct() const { return launched_direct_; }
|
||||
double gib() const { return cache_.gib(); }
|
||||
int64_t entries() const { return entries_; } ///< routed entries the peer computed
|
||||
int64_t experts() const { return experts_; } ///< distinct (layer, expert) the peer computed
|
||||
int64_t swaps() const { return swaps_; }
|
||||
double ms_wait = 0; ///< host time spent in finish() waiting for the peer
|
||||
|
||||
private:
|
||||
int device_ = -1;
|
||||
bool p2p_ = false;
|
||||
int64_t n_layers_ = 0, n_expert_ = 0;
|
||||
ExpertCache cache_;
|
||||
ExpertSource* src_ = nullptr;
|
||||
std::vector<int32_t> res_; ///< [n_layers * n_expert] -> peer slot or -1
|
||||
std::vector<std::pair<int32_t, int32_t>> pending_; ///< (residency index, slot) once the copies land
|
||||
int64_t resident_ = 0, entries_ = 0, experts_ = 0, swaps_ = 0;
|
||||
dpct::queue_ptr stream_ = &dpct::get_in_order_queue(),
|
||||
refill_ = &dpct::get_in_order_queue();
|
||||
dpct::event_ptr refill_ev_ = nullptr;
|
||||
float* h_x_ = nullptr; float* d_x_ = nullptr; // n_tok x n_embd
|
||||
float* h_out_ = nullptr; float* d_out_ = nullptr; // compact rows
|
||||
void* h_meta_ = nullptr; void* d_meta_ = nullptr; // groups: ptr | start | dst | tok | count
|
||||
uint8_t* d_q8_ = nullptr;
|
||||
void* d_scratch_ = nullptr;
|
||||
std::vector<int32_t> row_of_; ///< compact row -> original entry
|
||||
int64_t launched_rows_ = 0;
|
||||
bool launched_direct_ = false;
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,77 +0,0 @@
|
||||
// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S,
|
||||
// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's
|
||||
// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding).
|
||||
//
|
||||
// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh,
|
||||
// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it
|
||||
// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
/// ggml type ids handled here.
|
||||
bool iq_supported(int ggml_type) noexcept;
|
||||
/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30).
|
||||
bool embed_type_supported(int ggml_type) noexcept;
|
||||
/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block).
|
||||
size_t iq_row_bytes(int ggml_type, int64_t n) noexcept;
|
||||
|
||||
/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks.
|
||||
void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);
|
||||
|
||||
/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column).
|
||||
void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream);
|
||||
|
||||
/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32.
|
||||
void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream);
|
||||
void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream);
|
||||
/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped
|
||||
/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256).
|
||||
void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,
|
||||
int64_t n_embd, float* out, void* stream);
|
||||
/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path
|
||||
/// uses: row 2r = gate row r, row 2r+1 = up row r.
|
||||
void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst,
|
||||
void* stream);
|
||||
|
||||
/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.
|
||||
struct NativeExpertLayout {
|
||||
int gu_type = -1, d_type = -1;
|
||||
int64_t n_embd = 0, n_ff = 0;
|
||||
size_t gu_row = 0, d_row = 0; // bytes per row
|
||||
size_t up_off = 0, down_off = 0; // byte offsets inside the blob
|
||||
size_t bytes = 0; // the whole blob
|
||||
};
|
||||
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);
|
||||
/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the
|
||||
/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated).
|
||||
bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;
|
||||
|
||||
/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries.
|
||||
size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff);
|
||||
|
||||
/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries
|
||||
/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1)
|
||||
/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device.
|
||||
/// `grid_groups` (1 .. cap_groups; 0 = cap_groups) groups run side by side, a block row each striding over the rest:
|
||||
/// a call that usually has few groups or none (the verify window's PCIe share) launches less for the ones it does
|
||||
/// not have. The results do not depend on it.
|
||||
void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,
|
||||
const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,
|
||||
int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,
|
||||
int64_t grid_groups = 0);
|
||||
/// true: `native_expert_grouped`'s launches before the group stride (STRATA_GROUPED_V1=1 at startup) - a block row
|
||||
/// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results
|
||||
/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs.
|
||||
void native_grouped_set_v1(bool v1);
|
||||
|
||||
/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;
|
||||
/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give
|
||||
/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.
|
||||
void iq_set_old_kernels(bool old);
|
||||
bool iq_old_kernels();
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -1,213 +0,0 @@
|
||||
// include/strata/kernels/ngram.hpp - P2.S4: the PLE n-gram hash and the per-layer token table.
|
||||
//
|
||||
// Two halves that share nothing but the row indices they exchange:
|
||||
//
|
||||
// * `ngram_rows` - the HOST hash. Sixteen row indices per token from the last three token ids, computed
|
||||
// with 64-bit multiply/xor and no tensor op at all. `qwen4exp.cpp` L1092-1124, where the source says
|
||||
// outright that it is host-side because "ggml has no int64 and no xor".
|
||||
// * `PleTable` - the row gather. `per_layer_token_embd.weight` is IQ4_NL and is NOT IN THE PACK: it is
|
||||
// 51.2e9 elements (28.8 GB) in the ORIGINAL second GGUF shard, and it is the only tensor this engine
|
||||
// reads from the GGUF rather than from the canonical pack.
|
||||
//
|
||||
// THE HASH IS THE ONE PLACE IN THIS MODEL WHERE A WRONG BIT IS SILENTLY PLAUSIBLE. Every one of its
|
||||
// properties has a rival reading that produces a valid index in range:
|
||||
//
|
||||
// * XOR, not sum. Two equal tokens with equal multipliers cancel to zero under XOR and double under sum.
|
||||
// * `%` vocab_size, not `& (vocab_size-1)`. The vocab sizes are 20000003, 20000023, 20000033, ... - not
|
||||
// powers of two, so a mask would be a different function.
|
||||
// * the EOS cut propagates FORWARD: an EOS at any position replaces that position AND every older one.
|
||||
// * a missing predecessor is `LLAMA_TOKEN_NULL = -1`, tested as `t < 0`. Token id 0 is a REAL token.
|
||||
// * the token's OWN eos does not cut its own context - only the predecessors are examined.
|
||||
//
|
||||
// All of those are asserted observable in `ple_parity.cpp` rather than trusted.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace strata::kernels {
|
||||
|
||||
// ---- geometry, every value confirmed against the artifact (docs/gguf-metadata.txt) ----
|
||||
inline constexpr int NG_N_EMBD = 2560; // n_embd
|
||||
inline constexpr int PLE_HEAD_DIM = 160; // qwen4exp.embedding_length_per_layer_input
|
||||
inline constexpr int NGRAM_SIZE = 3; // qwen4exp.ple.ngram_size
|
||||
inline constexpr int HEADS_PER_NGRAM = 8; // qwen4exp.ple.heads_per_ngram
|
||||
inline constexpr int PLE_N_HEADS = (NGRAM_SIZE - 1) * HEADS_PER_NGRAM; // 16
|
||||
inline constexpr int PLE_CONV_KERNEL = 4; // qwen4exp.ple.conv_kernel
|
||||
inline constexpr int32_t PLE_EOS_TOKEN_ID = 248044;
|
||||
inline constexpr int NG_HC = 4; // hyper_connection.count
|
||||
inline constexpr int NG_HC_DIM = NG_HC * NG_N_EMBD; // 10240
|
||||
inline constexpr int NG_HIST = (PLE_CONV_KERNEL - 1) * NGRAM_SIZE; // 9
|
||||
inline constexpr int32_t TOKEN_NULL = -1; // LLAMA_TOKEN_NULL
|
||||
inline constexpr float NG_RMS_EPS = 1e-6f;
|
||||
|
||||
// The table: [160, 320001536] IQ4_NL. ne0 = 160 is the FAST axis, so one row is 160 contiguous elements =
|
||||
// 5 blocks of 32 at 18 bytes = 90 bytes. The head-slowest flatten then makes 16 rows exactly n_embd = 2560.
|
||||
inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull;
|
||||
inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row
|
||||
inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value
|
||||
inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8;
|
||||
|
||||
/// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`:
|
||||
///
|
||||
/// layer_multipliers = [23703573157769, 20109073645365, 8052911324071]
|
||||
/// head_vocab_sizes = [20000003, 20000023, ...] 16 entries, NOT an arithmetic sequence
|
||||
/// head_offsets = [0, 20000003, 40000026, ...] the running sum of head_vocab_sizes
|
||||
///
|
||||
/// `ref/ngram.py::selftest` calls its own copies "synthetic but STRUCTURALLY REAL"; they are in fact
|
||||
/// `20000003 + 10*i` for the vocab sizes, which the artifact's are not (20000003, 20000023, 20000033 - the
|
||||
/// differences are 20, 10, ...). A selftest is free to use whatever constants it likes, but a PARITY test
|
||||
/// against the artifact must use these, and the difference is recorded because it is exactly the kind of
|
||||
/// thing that gets copied from the reference into an engine.
|
||||
struct PleConsts {
|
||||
uint64_t mult[NGRAM_SIZE];
|
||||
uint64_t vocab[PLE_N_HEADS];
|
||||
uint64_t offset[PLE_N_HEADS];
|
||||
};
|
||||
PleConsts ple_artifact_consts();
|
||||
|
||||
/// `mixed_n = (ctx[0]*m[0]) ^ (ctx[1]*m[1]) ^ ... ^ (ctx[n-1]*m[n-1])` in uint64.
|
||||
///
|
||||
/// Exposed separately so a test can assert the XOR STRUCTURE directly rather than only its consequences.
|
||||
uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n);
|
||||
|
||||
/// The sixteen row indices per token. `qwen4exp.cpp` L1092-1124.
|
||||
///
|
||||
/// tokens (n_tokens,) the ubatch's own tokens
|
||||
/// prev (n_tokens, 2) predecessors OLDEST FIRST, `TOKEN_NULL` where there is none
|
||||
/// out (n_tokens, 16) row indices into the PLE table
|
||||
///
|
||||
/// The window is built once per token and then only its PREFIXES are used, which is what makes the bigram
|
||||
/// heads (0..7) and the trigram heads (8..15) agree about the recent history.
|
||||
void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out);
|
||||
|
||||
/// The IQ4_NL codebook: `{-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}`,
|
||||
/// which is `kvalues_iq4nl` from `ggml-common.h` L1121 and also the manifest's `codebooks.IQ4NL`.
|
||||
///
|
||||
/// There is NO `-8` in this version of ggml. Some releases of `dequantize_row_iq4_nl` subtract 8 from the
|
||||
/// codebook value; at 3cf03257 they do not, and the difference would shift every one of the 51.2e9 elements.
|
||||
int iq4nl_code(int code);
|
||||
|
||||
/// One 90-byte row -> 160 floats. The canonical rule `value = cb[code] * scale + offset` with offset 0,
|
||||
/// because IQ4_NL has no min term (`has_offset` is false in the manifest).
|
||||
///
|
||||
/// THE NIBBLE ORDER IS SPLIT-HALF, NOT INTERLEAVED, and that is the trap here. `dequantize_row_iq4_nl` is
|
||||
/// y[j] = d * kvalues[qs[j] & 0xf];
|
||||
/// y[j + QK4_NL/2] = d * kvalues[qs[j] >> 4];
|
||||
/// so byte j carries elements j and j+16 - NOT 2j and 2j+1, which is the natural reading and which produces
|
||||
/// a perfectly plausible embedding of the wrong 160 values.
|
||||
void iq4nl_dequant_row(const uint8_t* row, float* out160);
|
||||
|
||||
/// One FP8 row -> 160 floats: each byte an E4M3 value (the "fn" variant: no infinities, 0x7F/0xFF are NaN), times the
|
||||
/// table's one scale. This is the table as Qwen3.8-Flash-Next ships it (`...ngram_embedding.shard_k`, F8_E4M3, and
|
||||
/// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row.
|
||||
void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160);
|
||||
|
||||
/// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD,
|
||||
/// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the
|
||||
/// A/B arm; it returns the same bytes.
|
||||
///
|
||||
/// NEVER KEEP THE SHARD MAPPED WHILE READING IT DIRECT: a live section on the same file serializes the unbuffered
|
||||
/// reads (311 -> 1,575 us per token, bench/results/2026-09-23-p2-ssd-direct). Direct mode drops its own mapping
|
||||
/// after the header parse; nothing else in the process may hold one.
|
||||
enum class PleIo { Direct, Mmap };
|
||||
|
||||
struct PleIoOptions {
|
||||
PleIo mode = PleIo::Direct;
|
||||
uint32_t max_inflight = 256; ///< outstanding SSD reads (decode needs 16; a prompt chunk saturates the SSD at 256)
|
||||
uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables
|
||||
bool io_thread = true; ///< reads submitted by a worker thread, not the caller
|
||||
/// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on
|
||||
/// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome.
|
||||
bool lock = false;
|
||||
/// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table
|
||||
/// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows
|
||||
/// (see PleReader::set_keepalive).
|
||||
double keepalive_ms = 0;
|
||||
double keepalive_window_s = 60;
|
||||
};
|
||||
|
||||
/// The PLE table. Held by pointer-to-impl so this header does not drag `<windows.h>` into every
|
||||
/// translation unit that wants the hash.
|
||||
class PleTable {
|
||||
public:
|
||||
PleTable();
|
||||
~PleTable();
|
||||
PleTable(const PleTable&) = delete;
|
||||
PleTable& operator=(const PleTable&) = delete;
|
||||
|
||||
/// 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);
|
||||
|
||||
/// 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);
|
||||
bool collect(float* out2560, std::string& err);
|
||||
/// Plan v0.3 P5: the rows of `n_tokens` tokens (16 each, `rows` token-major) into `out` (2560 floats per token),
|
||||
/// as ONE reader request - page dedupe and sort across the whole batch, the reader's full queue depth. Not
|
||||
/// while a single-token `issue` is pending. The mapped mode gathers row by row.
|
||||
bool gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err);
|
||||
|
||||
/// Fault injection (Direct mode): every row read completes no earlier than `us` after issue.
|
||||
void set_injected_delay_us(double us);
|
||||
|
||||
/// Maps the ORIGINAL second GGUF shard read-only. The tensor's data does NOT start at file offset 0:
|
||||
/// the manifest's `shard2_tensor.offset` is relative to the GGUF's DATA SECTION, and the header before it
|
||||
/// is 192 bytes. Reading at 0 would silently decode the header plus 192 bytes of shifted rows - still
|
||||
/// plausible IQ4_NL, which is why the reader takes the offset from a real GGUF parse (`GgufFile`, the
|
||||
/// project's validated reader) and checks that the tensor exactly fills the rest of the file.
|
||||
bool open(const std::string& gguf_path, std::string& err);
|
||||
void close();
|
||||
bool is_open() const;
|
||||
/// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched).
|
||||
bool locked() const;
|
||||
uint64_t rows() const;
|
||||
/// "IQ4_NL" or "F8_E4M3" (a GGUF from tools/ple_fp8_pack.py: type I8, strata.ple.format = f8_e4m3).
|
||||
const char* format() const;
|
||||
|
||||
/// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values
|
||||
/// occupy `out[h*160, (h+1)*160)`, which is what `ggml_get_rows` does and what makes the result a plain
|
||||
/// n_embd-wide vector for the block that consumes it.
|
||||
void gather(const uint32_t* rows16, float* out2560) const;
|
||||
|
||||
/// One row -> 160 floats, for diagnostics and for the parity test's oracle comparison.
|
||||
void read_row(uint32_t row, float* out160) const;
|
||||
|
||||
/// Bytes actually touched since `open`, for the "how often is it not ready" measurement P2.S4 asks for.
|
||||
uint64_t bytes_read() const;
|
||||
|
||||
/// One line of reader statistics (Direct mode), e.g. for --stats. Empty in Mmap mode.
|
||||
std::string io_report() const;
|
||||
PleIo mode() const;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
Impl* impl_ = nullptr;
|
||||
};
|
||||
|
||||
// ================================ THE PLE GATHER'S PREFETCH, AND ITS A/B ARM ================================
|
||||
//
|
||||
// `gather` issues its sixteen row reads as sixteen SEPARATE page faults into a 26.8 GB mapping, which measured
|
||||
// **2.10-2.61 ms per token** and is second only to the layer loop among the token's avoidable terms. The table
|
||||
// is 90 B per row, so the sixteen rows are 1,440 B - 0.5 MB/s, which is latency and not bandwidth, and it is
|
||||
// because the sixteen pages are taken one at a time. `PrefetchVirtualMemory` issues them in one call.
|
||||
//
|
||||
// **THIS SWITCH EXISTS SO THE CLAIM CAN BE MEASURED RATHER THAN ASSERTED.** Cross-build comparisons in this
|
||||
// project have repeatedly turned out to be machine drift - `LAYERS` alone moves 48.9 -> 52.3 between runs of
|
||||
// one binary - so the two arms are alternated inside one session. Off is `--no-ple-prefetch`.
|
||||
void ple_prefetch_enable(bool on);
|
||||
bool ple_prefetch_enabled();
|
||||
|
||||
// ---- NOTE ON `madvise(MADV_RANDOM)` ------------------------------------------------------------------
|
||||
// P2.S4 asks for `madvise(MADV_RANDOM)` on the mapping, and on Linux that is exactly right: a token gathers
|
||||
// 16 rows scattered over 28.8 GB, so read-ahead is pure waste and would evict useful pages.
|
||||
//
|
||||
// THERE IS NO LINUX, SO THERE IS NO MADV_RANDOM HERE. Windows has no equivalent of the advice - the closest
|
||||
// is `FILE_FLAG_RANDOM_ACCESS` at CreateFile time, which suppresses the cache-manager's read-ahead for the
|
||||
// whole handle, and `PrefetchVirtualMemory` for the positive case. `GgufFile` opens with neither, so this
|
||||
// build gets the DEFAULT sequential read-ahead on a random access pattern. Saying so is the point: a
|
||||
// comment claiming MADV_RANDOM here would be a comment about code that does not run. On Linux the advice
|
||||
// belongs in `GgufFile::open`, which this module does not own.
|
||||
// ------------------------------------------------------------------------------------------------------
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -43,6 +43,11 @@ struct SamplerParams {
|
||||
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
|
||||
const SamplerParams& p, int* out, void* stream);
|
||||
|
||||
// The greedy pick (no penalties) on a thread-block cluster of 8 CTAs per row (sm_90+, CUDA; S19): the same token as
|
||||
// sample_tokens' one-block argmax, which takes it unless STRATA_ARGMAX_MULTI=0. False (nothing launched) where it
|
||||
// cannot run: HIP, a card or a build below sm_90. Device pointers; capturable.
|
||||
bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int* out, void* stream);
|
||||
|
||||
// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers
|
||||
// throughout; every per-request / per-round value comes from device memory, so the calls can be captured.
|
||||
//
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
// include/strata/prefill/kernels.hpp - plan v0.3 P5: the element-wise and stateful kernels of a prompt chunk.
|
||||
//
|
||||
// T tokens at a time, all row-major with the token as the slow index. The arithmetic mirrors the per-token native
|
||||
// kernels (the decode path), batched; where a step is a recurrence in time (the GDN conv and state, the PLE conv)
|
||||
// the kernel walks the chunk's tokens in order inside one launch.
|
||||
#pragma once
|
||||
|
||||
#include "strata/kernels/kv_stream.hpp"
|
||||
#include "strata/kernels/rope_scaling.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::prefill {
|
||||
|
||||
// ---- hyper-connection (n_embd 2560, hc 4, hc_lr 320)
|
||||
/// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image.
|
||||
/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x.
|
||||
void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo = nullptr);
|
||||
/// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R.
|
||||
void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
|
||||
uint16_t* xn16_lo = nullptr);
|
||||
/// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits).
|
||||
void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,
|
||||
int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr);
|
||||
/// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as
|
||||
/// the two calls, without reading R back.
|
||||
void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
|
||||
float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr);
|
||||
/// lo16[t, k] = bf16(silu(lo[t, k] / hc))
|
||||
void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr);
|
||||
/// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null).
|
||||
void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream,
|
||||
uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr);
|
||||
/// R[t, c, d] += bo[t, d] * 2 sigmoid(inj[t, c] / hc) (inj has row stride inj_ld)
|
||||
void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream);
|
||||
/// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast).
|
||||
void gr_broadcast(const float* e, float* R, int64_t T, void* stream);
|
||||
|
||||
// ---- GDN (state 128, 16 k heads, 48 v heads, 10240 conv channels, 4 taps)
|
||||
/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, 48 + h]) (ab: [T, 96])
|
||||
void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream);
|
||||
/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then
|
||||
/// the L2 norm of the q and k heads of every token. h: [T, C].
|
||||
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream);
|
||||
/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the
|
||||
/// out projection reads); y is FP32 scratch.
|
||||
void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,
|
||||
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream);
|
||||
|
||||
// ---- MoE
|
||||
/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router).
|
||||
void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream);
|
||||
/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640].
|
||||
void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);
|
||||
/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up)
|
||||
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream);
|
||||
/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640)
|
||||
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream);
|
||||
/// dst[i] = src[i] for n int32s, as a kernel: either side may be mapped host memory, and the copy never waits
|
||||
/// behind the copy engine's queue (the prompt path's grouping tables, while the expert stream fills it).
|
||||
void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream);
|
||||
/// Gather rows: dst16[i, :] = x16[src[i], :] (n rows of `width` BF16).
|
||||
void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream);
|
||||
/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :]
|
||||
void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
|
||||
int64_t T, void* stream);
|
||||
|
||||
// ---- QSA helpers
|
||||
/// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`).
|
||||
void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream);
|
||||
/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. The rope
|
||||
/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly.
|
||||
void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0,
|
||||
const strata::kernels::RopeScaling& scaling, void* stream);
|
||||
/// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256]
|
||||
void split_q(const float* q_full, float* q, int64_t T, void* stream);
|
||||
/// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized)
|
||||
void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream);
|
||||
|
||||
/// K and V of T consecutive cells (positions pos0..pos0+T-1; K normed and rotated) into the paged pools: FP16
|
||||
/// (`k_pool`/`v_pool`) or INT8 codes + FP16 scale per 64 (`k_q`...), the decode append's arithmetic.
|
||||
/// K, V: [T, 2, 256].
|
||||
void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size,
|
||||
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 = nullptr,
|
||||
const strata::kernels::KvHostPools* stage = nullptr);
|
||||
|
||||
/// fp32 -> fp16 bits and fp32 -> bf16, n elements (the two activation images of the prompt GEMMs).
|
||||
void to_f16(const float* x, uint16_t* y, int64_t n, void* stream);
|
||||
void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo = nullptr);
|
||||
/// y = fp32(fp16(x)): what an FP16 store of x would read back (the FP16 indexer-key experiment)
|
||||
void round_f16(const float* x, float* y, int64_t n, void* stream);
|
||||
/// Expert blob -> FP16 (Q2_0 values are exact in FP16).
|
||||
void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);
|
||||
|
||||
} // namespace strata::prefill
|
||||
@@ -141,6 +141,97 @@ catch (sycl::exception const &exc) {
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
} // namespace strata::core
|
||||
|
||||
#if defined(STRATA_USE_HIP) && defined(_WIN32)
|
||||
// The free VRAM figure on Windows HIP (include/strata/hip_compat/cuda_runtime.h maps cudaMemGetInfo here).
|
||||
//
|
||||
// hipMemGetInfo (ROCclr's PAL backend, Device::globalFreeMemory) is the card's size minus this process's own
|
||||
// allocations: it asks Windows for this process's usage only, never for what the desktop and other programs hold.
|
||||
// So on a card that also drives the desktop the engine counted ~930 MiB that was not there, the expert cache filled
|
||||
// the card, and WDDM moved memory out to system RAM: decode at 30 tok/s instead of 41 (RX 6800, HIP SDK 7.2).
|
||||
// Windows itself gives each process a video memory budget (DXGI QueryVideoMemoryInfo) that does account for the
|
||||
// others. Measured on that card: the budget sits 0.8 GiB below the card's size while this process is small and
|
||||
// 1.8 GiB below once it holds 11 GiB; allocations past it still succeed, and are what Windows moves out. The
|
||||
// free figure here is hipMemGetInfo's lowered by what the budget withholds (the card's size minus the budget).
|
||||
// Subtracting from HIP's own figure, rather than taking the budget minus DXGI's usage, keeps memory the HIP runtime
|
||||
// has freed and holds in its cache counted as free, as hipMemGetInfo counts it. dxgi.dll is loaded at run time, so
|
||||
// nothing new is linked; when it or the card's adapter cannot be found, hipMemGetInfo's figure stands.
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <dxgi1_4.h>
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
|
||||
namespace strata::hip_compat {
|
||||
namespace {
|
||||
IDXGIAdapter3* budget_adapter(int device) {
|
||||
constexpr int kMaxDevices = 16;
|
||||
static std::mutex mu;
|
||||
static IDXGIAdapter3* adapters[kMaxDevices] = {};
|
||||
static bool tried[kMaxDevices] = {};
|
||||
if (device < 0 || device >= kMaxDevices) return nullptr;
|
||||
std::lock_guard<std::mutex> lock(mu);
|
||||
if (tried[device]) return adapters[device];
|
||||
tried[device] = true;
|
||||
hipDeviceProp_t p{};
|
||||
if (hipGetDeviceProperties(&p, device) != hipSuccess) {
|
||||
(void) hipGetLastError();
|
||||
return nullptr;
|
||||
}
|
||||
LUID luid{};
|
||||
std::memcpy(&luid, p.luid, sizeof luid);
|
||||
using CreateFactory = HRESULT(WINAPI*)(REFIID, void**);
|
||||
static HMODULE dxgi = LoadLibraryW(L"dxgi.dll"); // kept for the process' lifetime, like the adapters
|
||||
const auto create = dxgi ? (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1") : nullptr;
|
||||
IDXGIFactory4* factory = nullptr;
|
||||
if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory4), (void**) &factory))) return nullptr;
|
||||
IDXGIAdapter3* adapter = nullptr;
|
||||
if (FAILED(factory->EnumAdapterByLuid(luid, __uuidof(IDXGIAdapter3), (void**) &adapter))) adapter = nullptr;
|
||||
factory->Release();
|
||||
adapters[device] = adapter;
|
||||
return adapter;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes) {
|
||||
const hipError_t e = hipMemGetInfo(free_bytes, total_bytes);
|
||||
static const bool off = [] {
|
||||
const char* v = std::getenv("STRATA_WDDM_BUDGET");
|
||||
return v != nullptr && std::atoi(v) == 0;
|
||||
}();
|
||||
if (e != hipSuccess || off || free_bytes == nullptr || total_bytes == nullptr) return e;
|
||||
int device = 0;
|
||||
if (hipGetDevice(&device) != hipSuccess) {
|
||||
(void) hipGetLastError();
|
||||
return e;
|
||||
}
|
||||
IDXGIAdapter3* adapter = budget_adapter(device);
|
||||
DXGI_QUERY_VIDEO_MEMORY_INFO local{};
|
||||
if (adapter == nullptr || FAILED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local)) ||
|
||||
local.Budget == 0 || local.Budget >= *total_bytes)
|
||||
return e;
|
||||
const size_t withheld = *total_bytes - (size_t) local.Budget; // the desktop's and other programs' share
|
||||
static std::atomic<bool> said{false};
|
||||
if (!said.exchange(true)) {
|
||||
std::fprintf(stderr, "strata: Windows budgets %llu of this card's %llu MiB for this process; free VRAM is "
|
||||
"counted within that (STRATA_WDDM_BUDGET=0: off)\n",
|
||||
(unsigned long long) (local.Budget >> 20), (unsigned long long) (*total_bytes >> 20));
|
||||
}
|
||||
*free_bytes = *free_bytes > withheld ? *free_bytes - withheld : 0;
|
||||
return e;
|
||||
}
|
||||
} // namespace strata::hip_compat
|
||||
#endif
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
std::string gpu_arch_problem(int ordinal) {
|
||||
#if defined(STRATA_USE_HIP)
|
||||
int count = 0;
|
||||
@@ -323,8 +414,8 @@ DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison)
|
||||
});
|
||||
}
|
||||
/*
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use
|
||||
the error codes. The cudaGetLastError function call was replaced
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not
|
||||
use the error codes. The cudaGetLastError function call was replaced
|
||||
with 0. You need to rewrite this code.
|
||||
*/
|
||||
check(0, "poison_kernel");
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
#include "strata/sycl_queue.hpp"
|
||||
#include "strata/core/expert_cache.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <utility>
|
||||
#include <cstring>
|
||||
|
||||
@@ -69,6 +71,77 @@ bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_ex
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::pair<int32_t, int32_t>> rank_learned_profile(int64_t n_layers, int64_t n_expert,
|
||||
const std::vector<uint8_t>& resident,
|
||||
const std::vector<double>& heat,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& prior) {
|
||||
const size_t n = (size_t) (n_layers * n_expert);
|
||||
std::vector<int64_t> prior_rank(n, INT64_MAX);
|
||||
for (size_t r = 0; r < prior.size(); ++r) {
|
||||
const auto [l, e] = prior[r];
|
||||
if (l >= 0 && l < n_layers && e >= 0 && e < n_expert) {
|
||||
int64_t& pr = prior_rank[(size_t) (l * n_expert + e)];
|
||||
if (pr == INT64_MAX) pr = (int64_t) r;
|
||||
}
|
||||
}
|
||||
std::vector<int64_t> order(n);
|
||||
for (size_t i = 0; i < n; ++i) order[i] = (int64_t) i;
|
||||
auto res = [&](int64_t i) { return (size_t) i < resident.size() && resident[(size_t) i] != 0; };
|
||||
auto ht = [&](int64_t i) { return (size_t) i < heat.size() ? heat[(size_t) i] : 0.0; };
|
||||
std::stable_sort(order.begin(), order.end(), [&](int64_t a, int64_t b) {
|
||||
if (res(a) != res(b)) return res(a);
|
||||
if (ht(a) != ht(b)) return ht(a) > ht(b);
|
||||
if (prior_rank[(size_t) a] != prior_rank[(size_t) b]) return prior_rank[(size_t) a] < prior_rank[(size_t) b];
|
||||
return a < b;
|
||||
});
|
||||
std::vector<std::pair<int32_t, int32_t>> ranked(n);
|
||||
for (size_t r = 0; r < n; ++r)
|
||||
ranked[r] = {(int32_t) (order[r] / n_expert), (int32_t) (order[r] % n_expert)};
|
||||
return ranked;
|
||||
}
|
||||
|
||||
bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& ranked, std::string& err) {
|
||||
if (n_layers <= 0 || n_expert <= 0 || n_layers > 65535 || n_expert > 65535) {
|
||||
err = "write_expert_profile: the model's layout does not fit the format";
|
||||
return false;
|
||||
}
|
||||
std::vector<int32_t> table((size_t) (n_layers * n_expert), -1);
|
||||
std::vector<uint16_t> pairs;
|
||||
pairs.reserve(ranked.size() * 2);
|
||||
for (size_t r = 0; r < ranked.size(); ++r) {
|
||||
const auto [l, e] = ranked[r];
|
||||
if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) {
|
||||
err = "write_expert_profile: a ranked pair is out of range";
|
||||
return false;
|
||||
}
|
||||
table[(size_t) (l * n_expert + e)] = (int32_t) r;
|
||||
pairs.push_back((uint16_t) l);
|
||||
pairs.push_back((uint16_t) e);
|
||||
}
|
||||
const uint32_t hdr[5] = {1u, (uint32_t) n_layers, (uint32_t) n_expert, (uint32_t) ranked.size(),
|
||||
(uint32_t) ranked.size()};
|
||||
const std::string tmp = path + ".tmp";
|
||||
std::FILE* f = std::fopen(tmp.c_str(), "wb");
|
||||
if (f == nullptr) {
|
||||
err = "write_expert_profile: cannot create " + tmp;
|
||||
return false;
|
||||
}
|
||||
// the format is little-endian (make_profile.py's "<"): so is every machine this engine runs on
|
||||
bool ok = std::fwrite("STRP", 1, 4, f) == 4 && std::fwrite(hdr, 4, 5, f) == 5 &&
|
||||
(pairs.empty() || std::fwrite(pairs.data(), 2, pairs.size(), f) == pairs.size()) &&
|
||||
std::fwrite(table.data(), 4, table.size(), f) == table.size();
|
||||
ok = (std::fclose(f) == 0) && ok;
|
||||
std::error_code ec;
|
||||
if (ok) std::filesystem::rename(tmp, path, ec); // replaces an existing file (MoveFileEx / rename(2))
|
||||
if (!ok || ec) {
|
||||
std::filesystem::remove(tmp, ec);
|
||||
err = "write_expert_profile: cannot write " + path;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
ExpertCache::~ExpertCache() { close(); }
|
||||
|
||||
#if defined(STRATA_USE_HIP)
|
||||
@@ -140,8 +213,8 @@ bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert,
|
||||
real error-handling function.
|
||||
*/
|
||||
/*
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use
|
||||
the error codes. The cudaGetLastError function call was replaced
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not
|
||||
use the error codes. The cudaGetLastError function call was replaced
|
||||
with 0. You need to rewrite this code.
|
||||
*/
|
||||
(double)want / 1073741824.0, dpct::get_error_string_dummy(0));
|
||||
@@ -360,9 +433,9 @@ bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t *host_blob,
|
||||
const cudaError_t e = cudaMemcpy(dst, blocking_staging_, n, cudaMemcpyHostToDevice);
|
||||
#else
|
||||
/*
|
||||
DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
|
||||
the original code the source host memory is pageable memory. If the memory
|
||||
is not pageable, call wait() on event return by memcpy API to ensure
|
||||
DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
|
||||
in the original code the source host memory is pageable memory. If the
|
||||
memory is not pageable, call wait() on event return by memcpy API to ensure
|
||||
synchronization behavior.
|
||||
*/
|
||||
const dpct::err0 e =
|
||||
|
||||
+404
-22
@@ -5,6 +5,7 @@
|
||||
#include "strata/sycl_queue.hpp"
|
||||
#include "strata/core/expert_source.hpp"
|
||||
#include "strata/core/remote_experts.hpp"
|
||||
#include "strata/core/peer_experts.hpp"
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
|
||||
@@ -428,6 +429,7 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64
|
||||
file_ = f;
|
||||
mapping_ = m;
|
||||
base_ = (const uint8_t*) view;
|
||||
paths_.assign(1, path);
|
||||
#else
|
||||
const int fd = ::open(path.c_str(), O_RDONLY);
|
||||
if (fd < 0) { err = "FileExpertSource: cannot open " + path; return false; }
|
||||
@@ -516,6 +518,12 @@ void FileExpertSource::close() {
|
||||
}
|
||||
role_ptr_.clear();
|
||||
role_bytes_.clear();
|
||||
role_file_.clear();
|
||||
paths_.clear();
|
||||
#if defined(_WIN32)
|
||||
for (void* h : direct_) CloseHandle((HANDLE) h);
|
||||
#endif
|
||||
direct_.clear();
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(stage_mu_);
|
||||
stage_buf_.clear();
|
||||
@@ -581,6 +589,7 @@ bool FileExpertSource::open_gguf(std::string& err) {
|
||||
std::map<std::string, size_t> index;
|
||||
role_ptr_.assign((size_t) (3 * n_layers_), nullptr);
|
||||
role_bytes_.assign((size_t) (3 * n_layers_), 0);
|
||||
role_file_.assign((size_t) (3 * n_layers_), 0);
|
||||
for (int64_t l = 0; l < n_layers_; ++l) {
|
||||
const auto& fm = lay.fmt[(size_t) l];
|
||||
const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off};
|
||||
@@ -630,9 +639,11 @@ bool FileExpertSource::open_gguf(std::string& err) {
|
||||
m.base = (const uint8_t*) view;
|
||||
#endif
|
||||
maps_.push_back(m);
|
||||
paths_.push_back(path);
|
||||
it = index.emplace(path, maps_.size() - 1).first;
|
||||
}
|
||||
const Map& m = maps_[it->second];
|
||||
role_file_[i] = (int) it->second;
|
||||
const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_;
|
||||
if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree
|
||||
err = "FileExpertSource: an expert span runs past the end of " + path;
|
||||
@@ -650,6 +661,10 @@ bool FileExpertSource::open_gguf(std::string& err) {
|
||||
|
||||
bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const {
|
||||
if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
|
||||
if (!direct_.empty()) { // #286: from the drive; a failed read falls back to the mapping below
|
||||
const Fill f{0, layer, expert, dst};
|
||||
if (read_direct(&f, 1)) return true;
|
||||
}
|
||||
if (!role_ptr_.empty()) {
|
||||
uint64_t at = 0;
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
@@ -720,7 +735,11 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
|
||||
bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const bool ok = copy_from_files(layer, expert, dst);
|
||||
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
|
||||
publish_stage(v, layer, ok, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count());
|
||||
return ok;
|
||||
}
|
||||
|
||||
void FileExpertSource::publish_stage(size_t v, int64_t layer, bool ok, double us) {
|
||||
file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed);
|
||||
if (ok) {
|
||||
file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
|
||||
@@ -735,7 +754,6 @@ bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8
|
||||
}
|
||||
}
|
||||
stage_cv_.notify_all();
|
||||
return ok;
|
||||
}
|
||||
|
||||
const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
|
||||
@@ -759,8 +777,7 @@ const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
|
||||
}
|
||||
|
||||
void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) {
|
||||
if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return;
|
||||
struct Fill { size_t v; int64_t e; uint8_t* dst; };
|
||||
if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return;
|
||||
std::vector<Fill> todo;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(stage_mu_);
|
||||
@@ -774,7 +791,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
|
||||
size_t v = 0;
|
||||
bool fill = false;
|
||||
if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) {
|
||||
todo.push_back({v, e, stage_buf_[v].get()});
|
||||
todo.push_back({v, layer, e, stage_buf_[v].get()});
|
||||
if (warm_stamp_) {
|
||||
const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed);
|
||||
if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed);
|
||||
@@ -782,7 +799,52 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
|
||||
}
|
||||
}
|
||||
}
|
||||
fill_many(todo);
|
||||
}
|
||||
|
||||
void FileExpertSource::prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) {
|
||||
if (direct_.empty() || pairs == nullptr || n <= 0) return; // unbuffered only: the mapped fill stays as it was
|
||||
std::vector<Fill> todo;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(stage_mu_);
|
||||
for (int64_t i = 0; i < std::min<int64_t>(n, 64); ++i) {
|
||||
const int64_t l = pairs[i].first, e = pairs[i].second;
|
||||
if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
|
||||
size_t v = 0;
|
||||
bool fill = false;
|
||||
if (!claim_stage(l * n_expert_ + e, v, fill) && fill) todo.push_back({v, l, e, stage_buf_[v].get()});
|
||||
}
|
||||
}
|
||||
fill_many(todo);
|
||||
}
|
||||
|
||||
void FileExpertSource::fill_many(const std::vector<Fill>& todo) {
|
||||
if (todo.empty()) return;
|
||||
if (!direct_.empty()) {
|
||||
// #286: overlapped batches - every role window of 16 blobs in flight at once; a big batch (the profile
|
||||
// fill) on up to 4 threads, a decode layer's few misses on this one
|
||||
std::atomic<size_t> next{0};
|
||||
auto work = [&] {
|
||||
for (size_t at; (at = next.fetch_add(16)) < todo.size();) {
|
||||
const size_t k = std::min<size_t>(16, todo.size() - at);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const bool ok = read_direct(todo.data() + at, k);
|
||||
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
|
||||
for (size_t i = at; i < at + k; ++i) {
|
||||
const Fill& f = todo[i];
|
||||
// a failed batch: each blob again on its own (copy_from_files falls back to the mapping)
|
||||
if (ok) publish_stage(f.v, f.layer, true, us / (double) k);
|
||||
else (void) fill_stage(f.v, f.layer, f.e, f.dst);
|
||||
}
|
||||
}
|
||||
};
|
||||
const size_t nt = std::min<size_t>(4, (todo.size() + 15) / 16);
|
||||
std::vector<std::thread> th;
|
||||
for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
|
||||
work();
|
||||
for (auto& t : th) t.join();
|
||||
return;
|
||||
}
|
||||
#if defined(_WIN32)
|
||||
// One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large
|
||||
// requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below
|
||||
@@ -799,7 +861,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
|
||||
ranges.reserve(todo.size() * 3);
|
||||
for (const Fill& f : todo)
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
const size_t i = (size_t) (3 * layer + r);
|
||||
const size_t i = (size_t) (3 * f.layer + r);
|
||||
ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])),
|
||||
(SIZE_T) role_bytes_[i]});
|
||||
}
|
||||
@@ -811,7 +873,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
|
||||
std::atomic<size_t> next{0};
|
||||
auto work = [&] {
|
||||
for (size_t i; (i = next.fetch_add(1)) < todo.size();)
|
||||
(void) fill_stage(todo[i].v, layer, todo[i].e, todo[i].dst);
|
||||
(void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst);
|
||||
};
|
||||
const size_t nt = std::min<size_t>(todo.size(), (size_t) fetch_threads_);
|
||||
std::vector<std::thread> th;
|
||||
@@ -820,6 +882,159 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
|
||||
for (auto& t : th) t.join();
|
||||
}
|
||||
|
||||
bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) {
|
||||
#if defined(_WIN32)
|
||||
if (base_ == nullptr || paths_.empty() || !direct_.empty()) {
|
||||
why = !direct_.empty() ? "already unbuffered" : "no expert files open";
|
||||
return !direct_.empty();
|
||||
}
|
||||
if (!experts_unbuffered(paths_, ram_bytes, why, /*cache_counts=*/false)) return false;
|
||||
for (const std::string& path : paths_) {
|
||||
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
||||
std::vector<wchar_t> w((size_t) (wide > 0 ? wide : 1), L'\0');
|
||||
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, w.data(), wide);
|
||||
HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr);
|
||||
if (h == INVALID_HANDLE_VALUE) {
|
||||
why += "; cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) +
|
||||
"), read through the file cache";
|
||||
for (void* d : direct_) CloseHandle((HANDLE) d);
|
||||
direct_.clear();
|
||||
return false;
|
||||
}
|
||||
direct_.push_back(h);
|
||||
}
|
||||
if (role_ptr_.empty()) { // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
|
||||
std::lock_guard<std::mutex> lk(stage_mu_);
|
||||
for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
|
||||
}
|
||||
return true;
|
||||
#else
|
||||
(void) ram_bytes;
|
||||
why = "through the file cache (not Windows)";
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool FileExpertSource::read_direct(const Fill* fills, size_t n) const {
|
||||
#if defined(_WIN32)
|
||||
// NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine
|
||||
// maps the GGUF shards for the token embedding and the PLE table): measured on a PCIe 5 drive, 512 KiB reads at
|
||||
// queue depth 48 make 10.4 GB/s on a file nobody maps and 3.4 GB/s on a mapped one, 8 MiB reads 8.6 GB/s. So
|
||||
// windows less than kGap apart (the same role of nearby experts) are merged into requests of up to kMerge bytes.
|
||||
constexpr uint64_t kSector = 4096, kGap = 1ull << 20, kMerge = 32ull << 20;
|
||||
struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; };
|
||||
struct Req { HANDLE h; uint64_t a0, size, pos; };
|
||||
// this thread's aligned buffer and events, kept for its next batch
|
||||
struct Scratch {
|
||||
uint8_t* buf = nullptr;
|
||||
size_t cap = 0;
|
||||
std::vector<HANDLE> ev;
|
||||
std::vector<OVERLAPPED> ov;
|
||||
std::vector<Window> win;
|
||||
std::vector<size_t> order;
|
||||
std::vector<Req> req;
|
||||
std::vector<DWORD> got;
|
||||
~Scratch() {
|
||||
if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE);
|
||||
for (HANDLE e : ev) CloseHandle(e);
|
||||
}
|
||||
};
|
||||
thread_local Scratch sc;
|
||||
sc.win.clear();
|
||||
for (size_t k = 0; k < n; ++k) {
|
||||
const Fill& f = fills[k];
|
||||
if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false;
|
||||
if (role_ptr_.empty()) { // experts.bin: the blob is one contiguous range
|
||||
const uint64_t per = layer_blob_bytes_[(size_t) f.layer];
|
||||
const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per;
|
||||
const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
|
||||
sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0});
|
||||
continue;
|
||||
}
|
||||
uint64_t at = 0;
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
const size_t i = (size_t) (3 * f.layer + r);
|
||||
const uint64_t per = role_bytes_[i];
|
||||
const Map& m = maps_[(size_t) role_file_[i]];
|
||||
const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per;
|
||||
const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
|
||||
sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0});
|
||||
at += per;
|
||||
}
|
||||
}
|
||||
sc.order.resize(sc.win.size());
|
||||
for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w;
|
||||
std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) {
|
||||
return sc.win[a].file != sc.win[b].file ? sc.win[a].file < sc.win[b].file : sc.win[a].a0 < sc.win[b].a0;
|
||||
});
|
||||
sc.req.clear();
|
||||
uint64_t total = 0;
|
||||
int last_file = -1;
|
||||
for (size_t w : sc.order) {
|
||||
Window& x = sc.win[w];
|
||||
if (!sc.req.empty() && x.file == last_file) {
|
||||
Req& q = sc.req.back();
|
||||
const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size;
|
||||
if (x.a0 <= end + kGap && std::max(end, xend) - q.a0 <= kMerge) {
|
||||
if (xend > end) {
|
||||
total += xend - end;
|
||||
q.size = xend - q.a0;
|
||||
}
|
||||
x.req = sc.req.size() - 1;
|
||||
x.in_req = x.a0 - q.a0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
sc.req.push_back({(HANDLE) direct_[(size_t) x.file], x.a0, x.size, total});
|
||||
total += x.size;
|
||||
last_file = x.file;
|
||||
x.req = sc.req.size() - 1;
|
||||
x.in_req = 0;
|
||||
}
|
||||
if (total > sc.cap) {
|
||||
if (sc.buf != nullptr) VirtualFree(sc.buf, 0, MEM_RELEASE);
|
||||
sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20);
|
||||
sc.buf = (uint8_t*) VirtualAlloc(nullptr, sc.cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
if (sc.buf == nullptr) { sc.cap = 0; return false; }
|
||||
}
|
||||
while (sc.ev.size() < sc.req.size()) {
|
||||
HANDLE e = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
if (e == nullptr) return false;
|
||||
sc.ev.push_back(e);
|
||||
}
|
||||
sc.ov.assign(sc.req.size(), OVERLAPPED{});
|
||||
// every request in flight before the first wait: the drive sees the whole batch as one queue
|
||||
size_t issued = 0;
|
||||
bool ok = true;
|
||||
for (size_t q = 0; q < sc.req.size(); ++q) {
|
||||
const Req& r = sc.req[q];
|
||||
OVERLAPPED& o = sc.ov[q];
|
||||
o.Offset = (DWORD) r.a0;
|
||||
o.OffsetHigh = (DWORD) (r.a0 >> 32);
|
||||
o.hEvent = sc.ev[q];
|
||||
if (!ReadFile(r.h, sc.buf + r.pos, (DWORD) r.size, nullptr, &o) && GetLastError() != ERROR_IO_PENDING) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
++issued;
|
||||
}
|
||||
std::vector<DWORD>& got = sc.got;
|
||||
got.assign(sc.req.size(), 0);
|
||||
for (size_t q = 0; q < issued; ++q)
|
||||
if (!GetOverlappedResult(sc.req[q].h, &sc.ov[q], &got[q], TRUE)) ok = false;
|
||||
if (!ok || issued < sc.req.size()) return false;
|
||||
for (const Window& x : sc.win) {
|
||||
// a request may run past the end of the file: only the role's own bytes have to arrive
|
||||
if ((uint64_t) got[x.req] < x.in_req + x.skip + x.n) return false;
|
||||
std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);
|
||||
}
|
||||
return true;
|
||||
#else
|
||||
(void) fills; (void) n;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
|
||||
if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return;
|
||||
@@ -942,7 +1157,7 @@ void RouterLookahead::run() {
|
||||
void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) {
|
||||
(void) ids;
|
||||
(void) k;
|
||||
if (role_ptr_.empty()) return;
|
||||
if (!staged()) return;
|
||||
std::lock_guard<std::mutex> lk(stage_mu_);
|
||||
if (layer != last_layer_) {
|
||||
++epoch_;
|
||||
@@ -951,7 +1166,7 @@ void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k)
|
||||
}
|
||||
|
||||
bool FileExpertSource::transient(int64_t layer, int64_t expert) const {
|
||||
if (role_ptr_.empty() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
|
||||
if (!staged() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
|
||||
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
|
||||
if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)
|
||||
return false;
|
||||
@@ -1367,17 +1582,43 @@ bool FileExpertSource::pin_cache_complement(
|
||||
const int64_t layer = next_layer.fetch_add(1);
|
||||
if (layer >= n_layers_ || failed.load()) return;
|
||||
const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer];
|
||||
std::vector<Fill> batch; // #286, unbuffered: 32 blobs' reads in flight at once, merged where near
|
||||
auto flush = [&]() {
|
||||
if (batch.empty()) return true;
|
||||
bool ok = read_direct(batch.data(), batch.size());
|
||||
for (size_t i = 0; !ok && i < batch.size(); ++i)
|
||||
if (!copy_from_files(batch[i].layer, batch[i].e, batch[i].dst)) return false;
|
||||
copied.fetch_add(blob_bytes * (uint64_t) batch.size());
|
||||
batch.clear();
|
||||
return true;
|
||||
};
|
||||
for (int64_t expert = 0; expert < n_expert_; ++expert) {
|
||||
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
|
||||
const uint64_t offset = offsets[index];
|
||||
if (offset == kNoComplement) continue;
|
||||
if (offset > bytes || blob_bytes > bytes - offset ||
|
||||
!copy_from_files(layer, expert, (uint8_t*) host + (size_t) offset)) {
|
||||
if (offset > bytes || blob_bytes > bytes - offset) {
|
||||
fail("FileExpertSource: invalid blob bounds while building the cache complement");
|
||||
return;
|
||||
}
|
||||
uint8_t* dst = (uint8_t*) host + (size_t) offset;
|
||||
if (!direct_.empty()) {
|
||||
batch.push_back({0, layer, expert, dst});
|
||||
if (batch.size() == 32 && !flush()) {
|
||||
fail("FileExpertSource: an expert could not be read while building the cache complement");
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!copy_from_files(layer, expert, dst)) {
|
||||
fail("FileExpertSource: invalid blob bounds while building the cache complement");
|
||||
return;
|
||||
}
|
||||
copied.fetch_add(blob_bytes);
|
||||
}
|
||||
if (!flush()) {
|
||||
fail("FileExpertSource: an expert could not be read while building the cache complement");
|
||||
return;
|
||||
}
|
||||
#if !defined(_WIN32)
|
||||
if (role_ptr_.empty()) { // experts.bin; the GGUF in place leaves its pages to the OS
|
||||
const uint64_t layer_offset = layer_offsets_[(size_t) layer];
|
||||
@@ -1482,9 +1723,9 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string &err) try {
|
||||
const size_t total = (size_t) n * (size_t) blob;
|
||||
void* p = nullptr;
|
||||
/*
|
||||
DPCT1048: The original value cudaHostAllocDefault is not meaningful in
|
||||
the migrated code and was removed or replaced with 0. You may need to check
|
||||
the migrated code.
|
||||
DPCT1048: The original value cudaHostAllocDefault is not meaningful in the
|
||||
migrated code and was removed or replaced with 0. You may need to check the
|
||||
migrated code.
|
||||
*/
|
||||
if (DPCT_CHECK_ERROR(p = (void *)sycl::malloc_host(
|
||||
total, dpct::get_in_order_queue())) == 0 &&
|
||||
@@ -1563,7 +1804,7 @@ const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
|
||||
}
|
||||
}
|
||||
if (from_files) {
|
||||
if (!role_ptr_.empty()) {
|
||||
if (staged()) {
|
||||
result = staged_blob(layer, expert); // counts its bytes
|
||||
} else {
|
||||
result = mapped_blob(layer, expert);
|
||||
@@ -1778,7 +2019,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
|
||||
if (first_of[i] == i) {
|
||||
distinct[nd++] = i;
|
||||
const int32_t e = ids[i];
|
||||
if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0) ++nmiss;
|
||||
if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 &&
|
||||
!(d.peer != nullptr && d.peer->has(d.layers, e))) ++nmiss;
|
||||
}
|
||||
}
|
||||
const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers);
|
||||
@@ -1798,6 +2040,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
|
||||
kd = 0;
|
||||
ptr = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot]
|
||||
: (size_t) slot * (size_t) d.cache_blob));
|
||||
} else if (d.peer != nullptr && d.peer->has(d.layers, e)) {
|
||||
kd = 2; // multi-GPU: the second GPU computes it
|
||||
} else {
|
||||
if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) {
|
||||
const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr;
|
||||
@@ -1852,7 +2096,18 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int32_t e = ids[i];
|
||||
kind[i] = (e >= 0 && e < d.n_expert && d.host_res != nullptr &&
|
||||
d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0 : -1;
|
||||
d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0
|
||||
: (e >= 0 && e < d.n_expert && d.peer != nullptr && d.peer->has(d.layers, e)) ? 2 : -1;
|
||||
}
|
||||
}
|
||||
if (d.peer != nullptr) { // multi-GPU: start the second GPU's share before the CPU's own work
|
||||
std::string perr;
|
||||
if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, out)) {
|
||||
std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);
|
||||
d.failed = true;
|
||||
d.fail = "the peer GPU's experts could not be launched";
|
||||
d.fail_layer = d.layers;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (d.remote_count > 0) {
|
||||
@@ -1895,9 +2150,12 @@ 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, or a remote/peer result staged into this row below
|
||||
if (kind[i] == 0) ++d.cache_hits;
|
||||
std::memset(row, 0, (size_t) H * sizeof(float));
|
||||
else if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries;
|
||||
// multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it
|
||||
if (!(kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()))
|
||||
std::memset(row, 0, (size_t) H * sizeof(float));
|
||||
continue;
|
||||
}
|
||||
++d.cache_refused;
|
||||
@@ -1935,6 +2193,16 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
|
||||
d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
|
||||
}
|
||||
}
|
||||
if (d.peer != nullptr) { // multi-GPU: the second GPU's rows, into the same mapped rows
|
||||
std::string perr;
|
||||
if (!d.peer->finish(out, perr)) {
|
||||
std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);
|
||||
d.failed = true;
|
||||
d.fail = "the peer GPU's experts failed";
|
||||
d.fail_layer = d.layers;
|
||||
return;
|
||||
}
|
||||
}
|
||||
const auto c4 = std::chrono::steady_clock::now();
|
||||
pt("ran");
|
||||
auto ms = [](auto a, auto b) { return std::chrono::duration<double, std::milli>(b - a).count(); };
|
||||
@@ -2259,13 +2527,104 @@ bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::Exp
|
||||
// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. Each role
|
||||
// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in
|
||||
// #255, gopinath87607). The caller checks the spans first (check_experts_gguf).
|
||||
// `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into
|
||||
// an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway.
|
||||
LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,
|
||||
int threads) {
|
||||
int threads, bool unbuffered) {
|
||||
LoadStats st;
|
||||
st.layers = (uint64_t) lay.n_layers;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
std::atomic<int64_t> next{0};
|
||||
std::atomic<bool> bad{false};
|
||||
#if defined(_WIN32)
|
||||
if (unbuffered) {
|
||||
uint64_t max_chunk = 0;
|
||||
for (int64_t l = 0; l < lay.n_layers; ++l) {
|
||||
const auto& fm = lay.fmt[(size_t) l];
|
||||
max_chunk = std::max<uint64_t>(max_chunk, std::max<uint64_t>(fm.up_off, lay.bytes[(size_t) l] - fm.down_off) * 16);
|
||||
}
|
||||
std::mutex err_mu;
|
||||
std::string err;
|
||||
auto worker = [&]() {
|
||||
constexpr uint64_t kSector = 4096;
|
||||
const uint64_t cap = (max_chunk + 2 * kSector + kSector - 1) / kSector * kSector;
|
||||
uint8_t* buf = (uint8_t*) VirtualAlloc(nullptr, (size_t) cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
HANDLE h = INVALID_HANDLE_VALUE;
|
||||
std::string open_name;
|
||||
auto fail = [&](const std::string& what) {
|
||||
std::lock_guard<std::mutex> g(err_mu);
|
||||
if (err.empty()) err = what;
|
||||
bad = true;
|
||||
};
|
||||
if (buf == nullptr) fail("cannot allocate a read buffer");
|
||||
for (;;) {
|
||||
const int64_t l = next.fetch_add(1);
|
||||
if (l >= lay.n_layers || bad) break;
|
||||
const auto& fm = lay.fmt[(size_t) l];
|
||||
const uint64_t blob = lay.bytes[(size_t) l];
|
||||
const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
|
||||
const uint64_t at[3] = {0, fm.up_off, fm.down_off};
|
||||
for (int r = 0; r < 3 && !bad; ++r) {
|
||||
// the handle is kept while consecutive roles share a file (every layer of a v3 pack)
|
||||
const std::string name = expert_gguf_file(gguf, lay, l, r);
|
||||
if (name != open_name) {
|
||||
if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
|
||||
const int wide = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, nullptr, 0);
|
||||
std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');
|
||||
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, w.data(), wide);
|
||||
h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
|
||||
if (h == INVALID_HANDLE_VALUE) {
|
||||
fail("cannot open " + name + " (error " + std::to_string((unsigned long long) GetLastError()) + ")");
|
||||
break;
|
||||
}
|
||||
open_name = name;
|
||||
}
|
||||
const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)];
|
||||
const uint64_t total = per[r] * (uint64_t) lay.n_expert;
|
||||
const uint64_t chunk = per[r] * 16; // 16 experts per read
|
||||
for (uint64_t done = 0; done < total; done += chunk) {
|
||||
const uint64_t n = std::min<uint64_t>(chunk, total - done);
|
||||
const uint64_t a0 = (src + done) / kSector * kSector;
|
||||
const uint64_t a1 = (src + done + n + kSector - 1) / kSector * kSector;
|
||||
OVERLAPPED ov{};
|
||||
ov.Offset = (DWORD) a0;
|
||||
ov.OffsetHigh = (DWORD) (a0 >> 32);
|
||||
DWORD got = 0;
|
||||
// the window may run past the end of the file: only the tensor's own bytes have to arrive
|
||||
if (!ReadFile(h, buf, (DWORD) (a1 - a0), &got, &ov) || (uint64_t) got < src + done - a0 + n) {
|
||||
fail("short unbuffered read of layer " + std::to_string(l) + " in " + name + " (error " +
|
||||
std::to_string((unsigned long long) GetLastError()) + ")");
|
||||
break;
|
||||
}
|
||||
const uint8_t* q = buf + (src + done - a0);
|
||||
for (uint64_t k = 0; k < n / per[r]; ++k) {
|
||||
const uint64_t e = done / per[r] + k;
|
||||
std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], q + k * per[r], (size_t) per[r]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
|
||||
if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE);
|
||||
};
|
||||
std::vector<std::thread> pool;
|
||||
for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
|
||||
worker();
|
||||
for (auto& t : pool) t.join();
|
||||
if (bad) {
|
||||
st.seconds = -1.0;
|
||||
st.ok = false;
|
||||
st.error = err.empty() ? "unreadable shard while reading the experts from the GGUF" : err;
|
||||
return st;
|
||||
}
|
||||
st.bytes = lay.total;
|
||||
st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
return st;
|
||||
}
|
||||
#else
|
||||
(void) unbuffered;
|
||||
#endif
|
||||
auto worker = [&]() {
|
||||
// #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request
|
||||
// into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin.
|
||||
@@ -2390,8 +2749,31 @@ bool ArenaExpertSource::open(const std::string &pack_dir, int64_t n_layers,
|
||||
(why.empty() ? std::string{} : ": " + why);
|
||||
return false;
|
||||
}
|
||||
const LoadStats st = from_gguf ? load_experts_gguf(gguf_, a->data(), lay, threads)
|
||||
: load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20);
|
||||
// #285: unbuffered when the drive is read anyway and the file cache could not keep the experts for the next
|
||||
// start either (a 64 GB PC); otherwise the buffered readers, which a warm restart serves from the cache
|
||||
std::vector<std::string> files;
|
||||
if (from_gguf) {
|
||||
for (int64_t l = 0; l < n_layers; ++l)
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
const std::string f = expert_gguf_file(gguf_, lay, l, r);
|
||||
if (std::find(files.begin(), files.end(), f) == files.end()) files.push_back(f);
|
||||
}
|
||||
} else {
|
||||
files.push_back(path);
|
||||
}
|
||||
std::string why;
|
||||
const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why);
|
||||
const int readers = unbuffered ? std::max(threads, 16) : threads; // 16 keep a PCIe 5 drive's queue full
|
||||
LoadStats st;
|
||||
if (from_gguf) {
|
||||
st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered);
|
||||
} else {
|
||||
if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20);
|
||||
if (!unbuffered || (!st.ok && st.error.empty())) // unaligned ranges: the buffered reader
|
||||
st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20);
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache",
|
||||
why.c_str());
|
||||
if (!st.ok) {
|
||||
delete a;
|
||||
err = "ArenaExpertSource: the expert load was refused: " + (st.error.empty() ? std::string("unknown") : st.error);
|
||||
|
||||
+58
-2
@@ -6,6 +6,7 @@
|
||||
#include "strata/core/on_device.hpp"
|
||||
|
||||
#include "strata/core/native_head.hpp"
|
||||
#include "strata/core/peer_experts.hpp"
|
||||
#include "strata/kernels/bf16_gemv.hpp"
|
||||
#include "strata/kernels/cpu/expert.hpp"
|
||||
#include "strata/kernels/elementwise.hpp"
|
||||
@@ -32,6 +33,7 @@
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <fstream>
|
||||
@@ -458,6 +460,46 @@ void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t
|
||||
coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h));
|
||||
}
|
||||
|
||||
namespace {
|
||||
// #474: what to change when the draft head's token subset does not fit the VRAM left - a smaller subset that setup
|
||||
// ships (data/draft_vocab_*.bin; their token counts below), and how to pick it. The start used to stop at "the draft
|
||||
// head does not fit" with no hint. Text only, after the failure: nothing changes for a start that fits.
|
||||
void draft_head_hint(int64_t n_tokens, int64_t row_bytes) {
|
||||
size_t free_b = 0, total_b = 0;
|
||||
bool have_free = true; // SYCL port: the device's own free-memory figure
|
||||
try { dpct::get_current_device().get_memory_info(free_b, total_b); } catch (...) { have_free = false; }
|
||||
auto mib = [&](int64_t n) { return (double) (n * row_bytes) / 1048576.0; };
|
||||
std::string free_s;
|
||||
if (have_free) {
|
||||
char b[64];
|
||||
std::snprintf(b, sizeof(b), " and %.0f MiB is free", (double) free_b / 1048576.0);
|
||||
free_s = b;
|
||||
}
|
||||
std::fprintf(stderr, "strata mtp: the draft head over %lld tokens needs %.0f MiB of VRAM%s.\n",
|
||||
(long long) n_tokens, mib(n_tokens), free_s.c_str());
|
||||
struct Subset { const char* name; int64_t tokens; const char* what; };
|
||||
static const Subset smaller[] = {{"cyrillic", 58963, "English, code and the Cyrillic script"},
|
||||
{"en", 40525, "English and code"}};
|
||||
std::string opts;
|
||||
for (const Subset& s : smaller)
|
||||
if (s.tokens < n_tokens) {
|
||||
char b[160];
|
||||
std::snprintf(b, sizeof(b), "%s--draft-vocab %s (%s, ~%.0f MiB)", opts.empty() ? "" : " or ", s.name,
|
||||
s.what, mib(s.tokens));
|
||||
opts += b;
|
||||
}
|
||||
if (!opts.empty())
|
||||
std::fprintf(stderr, "strata mtp: hint: a smaller draft vocabulary needs less VRAM: %s. Start once with it - "
|
||||
"START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model "
|
||||
"keeps it (\"draft_vocab\" in its strata-*.json config); or a smaller --context in "
|
||||
"setup.\n",
|
||||
opts.c_str());
|
||||
else
|
||||
std::fprintf(stderr, "strata mtp: hint: this is already the smallest shipped draft vocabulary: a smaller "
|
||||
"--context (or closing what else uses the GPU) leaves it room.\n");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,
|
||||
const float *window_R, std::string &err) try {
|
||||
const OnDevice on_device(device_);
|
||||
@@ -488,6 +530,7 @@ bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,
|
||||
(size_t)(n_dvocab_ * row_bytes),
|
||||
dpct::get_in_order_queue())) != 0) {
|
||||
err = "mtp: the draft head does not fit";
|
||||
draft_head_hint(n_dvocab_, row_bytes);
|
||||
return false;
|
||||
}
|
||||
dpct::get_in_order_queue()
|
||||
@@ -847,8 +890,21 @@ bool MtpDrafter::prefill(const float *R_rows, const int32_t *next_tokens,
|
||||
// E-4: every group's token / step / position records uploaded at once; each group is then device copies and a
|
||||
// graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped
|
||||
// memory and synced before the next: ~5,500 host round trips on a 32K prompt). The same work in the same
|
||||
// order. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop.
|
||||
static const bool per_group_sync = std::getenv("STRATA_MTP_PREFILL_SYNC") != nullptr;
|
||||
// order. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop, =0 forces E-4.
|
||||
// HIP defaults to the old loop. This pass runs whenever E-9 (Prefill::draft_kv) declines, which it does for the
|
||||
// drafter's ring (KV streaming, --kv-resident), and on gfx1201 / ROCm 7.2.4 the E-4 queue (a graph launch and four
|
||||
// device copies per group, ~2,000 groups per 8192-token chunk, no sync) sometimes never completes: the prompt hangs
|
||||
// in hipGraphLaunch or the final sync until the watchdog ends the engine. R9700, full IQ3_XXS, --kv-resident
|
||||
// 32768, mixed load (chats, 32K and 7K prompts, deep follow-ups): E-4 hung in the first round on 2 of 2 tries,
|
||||
// the old loop ran 30 of 30 rounds clean, prompt speed unchanged.
|
||||
static const bool per_group_sync = [] {
|
||||
if (const char* v = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(v) != 0;
|
||||
#if defined(STRATA_USE_HIP)
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}();
|
||||
const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp;
|
||||
if (!per_group_sync && n > 0) {
|
||||
if (pf_cap_ < n * per_row) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// src/core/peer_experts.cpp (SYCL port) - upstream's --peer-device tier (a second GPU as an expert-cache tier, 0.1.36+)
|
||||
// is CUDA-only for now: this build answers "no peer". open() refuses with a message, so --peer-device fails clearly,
|
||||
// and every other entry point is the state a run without --peer-device has. Upstream's file: src/core/peer_experts.cpp.
|
||||
#include "strata/core/peer_experts.hpp"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace strata::core {
|
||||
|
||||
namespace {
|
||||
std::atomic<bool> g_portable{false};
|
||||
} // namespace
|
||||
|
||||
void set_peer_portable(bool on) { g_portable.store(on); }
|
||||
bool peer_portable() { return g_portable.load(); }
|
||||
|
||||
PeerExperts::~PeerExperts() { close(); }
|
||||
|
||||
bool PeerExperts::open(int, const std::vector<std::pair<int32_t, int32_t>>&, const ExpertCache&, ExpertSource&, int64_t,
|
||||
int64_t, int, int64_t, std::string& err) {
|
||||
err = "--peer-device: the second-GPU expert tier is not ported to SYCL yet";
|
||||
return false;
|
||||
}
|
||||
|
||||
void PeerExperts::close() { device_ = -1; }
|
||||
|
||||
bool PeerExperts::launch(int64_t, const float*, const int32_t*, int64_t, int64_t, const int32_t*, std::string& err,
|
||||
float*) {
|
||||
err = "--peer-device: not available in the SYCL build";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PeerExperts::finish(float*, std::string& err) {
|
||||
err = "--peer-device: not available in the SYCL build";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PeerExperts::adapt(const float*, const int32_t*, int, std::string&) { return true; }
|
||||
void PeerExperts::apply_pending(bool) {}
|
||||
|
||||
} // namespace strata::core
|
||||
+162
-10
@@ -200,15 +200,32 @@ void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::st
|
||||
return (uint8_t*) map + kSharedArenaHeaderBytes;
|
||||
}
|
||||
|
||||
void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0);
|
||||
if (p != MAP_FAILED) {
|
||||
got = PageBacking::LargePages;
|
||||
note = "hugetlb 2 MB pages";
|
||||
return p;
|
||||
// STRATA_NO_LARGEPAGES=1 is the same-run A/B switch the Windows branch documents; honor it
|
||||
// here too, so the large-page path can be compared without changing the pool or rebooting.
|
||||
if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) {
|
||||
note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages";
|
||||
} else {
|
||||
void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0);
|
||||
if (p != MAP_FAILED) {
|
||||
got = PageBacking::LargePages;
|
||||
note = "hugetlb 2 MB pages";
|
||||
return p;
|
||||
}
|
||||
// MAP_HUGETLB is all-or-nothing: a pool smaller than the mapping fails exactly like an absent
|
||||
// one, and the old message guessed "no hugetlb pool configured" either way. Name the shortfall:
|
||||
// how many 2 MiB pages the mapping needs against what vm.nr_hugepages actually holds.
|
||||
const unsigned long long need = ((unsigned long long) bytes + (1ull << 21) - 1) / (1ull << 21);
|
||||
unsigned long long pool = 0;
|
||||
bool have_pool = false;
|
||||
if (std::FILE* f = std::fopen("/proc/sys/vm/nr_hugepages", "r")) {
|
||||
have_pool = std::fscanf(f, "%llu", &pool) == 1;
|
||||
std::fclose(f);
|
||||
}
|
||||
note = "MAP_HUGETLB unavailable (needed " + std::to_string(need) + " 2 MiB pages, vm.nr_hugepages=" +
|
||||
(have_pool ? std::to_string(pool) : std::string("?")) + "); using 4 KB pages";
|
||||
}
|
||||
note = "MAP_HUGETLB unavailable (no hugetlb pool configured?); using 4 KB pages";
|
||||
p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
got = PageBacking::NormalPages;
|
||||
return p == MAP_FAILED ? nullptr : p;
|
||||
#endif
|
||||
@@ -378,8 +395,8 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,
|
||||
std::to_string(cap >> 30) + " GiB " + cap_why + "; "
|
||||
:
|
||||
/*
|
||||
DPCT1009: SYCL reports errors using exceptions and does
|
||||
not use error codes. Please replace the
|
||||
DPCT1009: SYCL reports errors using exceptions and
|
||||
does not use error codes. Please replace the
|
||||
"get_error_string_dummy(...)" with a real error-handling
|
||||
function.
|
||||
*/
|
||||
@@ -481,6 +498,141 @@ LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_byte
|
||||
return load_experts_ranges(path, dst, off, n, threads, chunk);
|
||||
}
|
||||
|
||||
LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
|
||||
const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk) {
|
||||
LoadStats st;
|
||||
st.ok = false;
|
||||
#ifdef _WIN32
|
||||
constexpr uint64_t kAlign = 4096;
|
||||
if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st;
|
||||
struct Piece { uint64_t off, n; };
|
||||
std::vector<Piece> pieces;
|
||||
uint64_t bytes = 0;
|
||||
for (size_t L = 0; L < layer_off.size(); ++L) {
|
||||
if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st;
|
||||
for (uint64_t p = 0; p < layer_bytes[L]; p += chunk)
|
||||
pieces.push_back({layer_off[L] + p, std::min<uint64_t>(chunk, layer_bytes[L] - p)});
|
||||
bytes += layer_bytes[L];
|
||||
}
|
||||
if (threads < 1) threads = 1;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
std::atomic<size_t> next{0};
|
||||
std::mutex err_mu;
|
||||
std::string err;
|
||||
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
|
||||
std::vector<wchar_t> wpath((size_t) std::max(wide, 1), L'\0');
|
||||
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
|
||||
auto worker = [&]() {
|
||||
HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
|
||||
if (h == INVALID_HANDLE_VALUE) {
|
||||
std::lock_guard<std::mutex> g(err_mu);
|
||||
if (err.empty())
|
||||
err = "cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) + ")";
|
||||
next = pieces.size();
|
||||
return;
|
||||
}
|
||||
for (;;) {
|
||||
const size_t i = next.fetch_add(1);
|
||||
if (i >= pieces.size()) break;
|
||||
OVERLAPPED ov{};
|
||||
ov.Offset = (DWORD) pieces[i].off;
|
||||
ov.OffsetHigh = (DWORD) (pieces[i].off >> 32);
|
||||
DWORD got = 0;
|
||||
if (!ReadFile(h, dst + pieces[i].off, (DWORD) pieces[i].n, &got, &ov) || got != pieces[i].n) {
|
||||
std::lock_guard<std::mutex> g(err_mu);
|
||||
if (err.empty())
|
||||
err = "short unbuffered read at offset " + std::to_string(pieces[i].off) + ": got " + std::to_string(got) +
|
||||
" of " + std::to_string(pieces[i].n) + " B (error " +
|
||||
std::to_string((unsigned long long) GetLastError()) + ")";
|
||||
next = pieces.size();
|
||||
break;
|
||||
}
|
||||
}
|
||||
CloseHandle(h);
|
||||
};
|
||||
std::vector<std::thread> pool;
|
||||
for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
|
||||
worker();
|
||||
for (auto& t : pool) t.join();
|
||||
st.layers = layer_off.size();
|
||||
if (!err.empty()) {
|
||||
st.seconds = -1.0;
|
||||
st.error = err;
|
||||
return st;
|
||||
}
|
||||
st.ok = true;
|
||||
st.bytes = bytes;
|
||||
st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
#else
|
||||
(void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk;
|
||||
#endif
|
||||
return st;
|
||||
}
|
||||
|
||||
bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_bytes, std::string& why,
|
||||
bool cache_counts) {
|
||||
const char* env = std::getenv("STRATA_UNBUFFERED_LOAD");
|
||||
if (env != nullptr && env[0] != '\0') {
|
||||
why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
|
||||
return env[0] != '0';
|
||||
}
|
||||
#ifdef _WIN32
|
||||
LARGE_INTEGER freq{}, a{}, b{};
|
||||
QueryPerformanceFrequency(&freq);
|
||||
constexpr DWORD kRead = 64 << 10;
|
||||
constexpr int kSamples = 16;
|
||||
std::vector<uint8_t> buf(kRead);
|
||||
uint64_t total_bytes = 0;
|
||||
int fast = 0, n = 0;
|
||||
uint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull;
|
||||
for (const std::string& f : files) {
|
||||
const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0);
|
||||
std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');
|
||||
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide);
|
||||
HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,
|
||||
nullptr);
|
||||
if (h == INVALID_HANDLE_VALUE) continue;
|
||||
LARGE_INTEGER size{};
|
||||
GetFileSizeEx(h, &size);
|
||||
total_bytes += (uint64_t) size.QuadPart;
|
||||
// random offsets: a probe must not find the blocks an earlier probe put into the cache
|
||||
for (int i = 0; i < kSamples && (uint64_t) size.QuadPart > 2ull * kRead; ++i) {
|
||||
seed = seed * 6364136223846793005ull + 1442695040888963407ull;
|
||||
const uint64_t off = ((seed >> 17) % ((uint64_t) size.QuadPart - kRead)) / kRead * kRead;
|
||||
OVERLAPPED ov{};
|
||||
ov.Offset = (DWORD) off;
|
||||
ov.OffsetHigh = (DWORD) (off >> 32);
|
||||
DWORD got = 0;
|
||||
QueryPerformanceCounter(&a);
|
||||
const BOOL ok = ReadFile(h, buf.data(), kRead, &got, &ov);
|
||||
QueryPerformanceCounter(&b);
|
||||
if (!ok) continue;
|
||||
++n;
|
||||
fast += (double) (b.QuadPart - a.QuadPart) * 1e6 / (double) freq.QuadPart < 30.0;
|
||||
}
|
||||
CloseHandle(h);
|
||||
}
|
||||
const bool cached = n > 0 && fast * 4 >= n * 3;
|
||||
MEMORYSTATUSEX ms{};
|
||||
ms.dwLength = sizeof ms;
|
||||
GlobalMemoryStatusEx(&ms);
|
||||
const uint64_t avail = ms.ullAvailPhys;
|
||||
// what the cache could keep beside the arena (~4 GiB for everything else)
|
||||
const uint64_t room = avail > arena_bytes + (4ull << 30) ? avail - arena_bytes - (4ull << 30) : 0;
|
||||
const bool keepable = room >= total_bytes;
|
||||
char msg[200];
|
||||
std::snprintf(msg, sizeof msg, "%d of %d probe reads from the file cache; %.1f GiB available, %.1f GiB of files",
|
||||
fast, n, (double) avail / (1ull << 30), (double) total_bytes / (1ull << 30));
|
||||
why = msg;
|
||||
return (!cached || !cache_counts) && !keepable;
|
||||
#else
|
||||
(void) files; (void) arena_bytes; (void) cache_counts;
|
||||
why = "buffered (not Windows)";
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
|
||||
const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk) {
|
||||
LoadStats st;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
#include "strata/core/native_head.hpp"
|
||||
#include "strata/core/on_device.hpp"
|
||||
#include "strata/core/peer_experts.hpp"
|
||||
#include "strata/kernels/iq_kernels.hpp"
|
||||
#include "strata/kernels/cpu/expert_layout.hpp"
|
||||
#include "strata/kernels/bf16_gemv.hpp"
|
||||
@@ -235,7 +236,9 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,
|
||||
}
|
||||
if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) {
|
||||
err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with "
|
||||
"--expert-cache auto, no VRAM was left for it: lower --max-context, use --kv k8v4 or images on the CPU";
|
||||
"--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above "
|
||||
"says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, "
|
||||
"images on the CPU)";
|
||||
return false;
|
||||
}
|
||||
std::string why;
|
||||
|
||||
@@ -465,6 +465,47 @@ __dpct_inline__ void copy_rows_from_mapped_kernel(
|
||||
d[i] = const_cast<const sycl::float4 *>(sr)[i];
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
__dpct_inline__ void scatter_rows_kernel(const sycl::float4 *__restrict__ src,
|
||||
sycl::float4 *dst,
|
||||
const int32_t *__restrict__ rows,
|
||||
int64_t w4) {
|
||||
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
||||
const int64_t r = item_ct1.get_group(2);
|
||||
const sycl::float4 *s = src + r * w4;
|
||||
sycl::float4 *d = dst + (int64_t)rows[r] * w4;
|
||||
#pragma unroll
|
||||
for (int64_t i = item_ct1.get_local_id(2); i < w4;
|
||||
i += item_ct1.get_local_range(2)) d[i] = s[i];
|
||||
}
|
||||
} // namespace
|
||||
void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream) {
|
||||
if (n <= 0) return;
|
||||
if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {
|
||||
std::fprintf(stderr, "scatter_rows_f32: width must be a multiple of 4 and both pointers 16-byte aligned\n");
|
||||
std::exit(1);
|
||||
}
|
||||
{
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
strata::q_of(stream)
|
||||
->submit([&](sycl::handler &cgh) {
|
||||
auto width_ct3 = width / 4;
|
||||
|
||||
cgh.parallel_for<
|
||||
dpct_kernel_name<class scatter_rows_kernel_7d83a1>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n) *
|
||||
sycl::range(1, 1, 128),
|
||||
sycl::range(1, 1, 128)),
|
||||
exp_props, [=](sycl::nd_item<3> item_ct1) {
|
||||
scatter_rows_kernel((const sycl::float4 *)src,
|
||||
(sycl::float4 *)dst, rows,
|
||||
width_ct3);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,
|
||||
const int32_t* count, void* stream) {
|
||||
if (rows <= 0) return;
|
||||
|
||||
@@ -389,7 +389,7 @@ bool gr_norm_split() { // default; STRATA_GR_NORM_SPLIT=0: one work-group per
|
||||
// which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held
|
||||
// for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks
|
||||
// of four tokens instead of one on sm_75.
|
||||
template <int TILEV>
|
||||
template <int TILEV, int MAX_T = kFusedGrMaxT>
|
||||
/*
|
||||
DPCT1110: The total declared local variable size in device function
|
||||
gr_down_multi_kernel exceeds 128 bytes and may cause high register pressure.
|
||||
@@ -409,9 +409,9 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
|
||||
const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC));
|
||||
const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
|
||||
const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(wrow);
|
||||
float acc[kFusedGrMaxT];
|
||||
float acc[MAX_T];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
|
||||
for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f;
|
||||
for (int base = inject_block ? 0 : split * TILEV; base < D; base += inject_block ? TILEV : TILEV * DOWN_SPLIT) {
|
||||
sycl::uint4 wv[TQ];
|
||||
if (active) {
|
||||
@@ -456,17 +456,17 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
|
||||
for (int q = 0; q < TQ; ++q) {
|
||||
const int j = lane + 32 * q;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k)
|
||||
for (int k = 0; k < MAX_T; ++k)
|
||||
if (k < T) acc[k] += dot8(wv[q], tile + k * TILEV + j * 8);
|
||||
}
|
||||
}
|
||||
if (!active) return;
|
||||
float s[kFusedGrMaxT];
|
||||
float s[MAX_T];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
|
||||
for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
|
||||
// lane k writes token k (every lane holds every sum after the xor reduction)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) {
|
||||
for (int k = 0; k < MAX_T; ++k) {
|
||||
if (k >= T || lane != k) continue;
|
||||
if (inject_block) {
|
||||
m.a[k].inject_out[row] = s[k];
|
||||
@@ -1143,6 +1143,7 @@ __dpct_inline__ void stage_htile(const GrMulti &m, int T, int h,
|
||||
}
|
||||
}
|
||||
|
||||
template <int MAX_T = kFusedGrMaxT>
|
||||
/*
|
||||
DPCT1110: The total declared local variable size in device function
|
||||
gr_down_staged_kernel exceeds 128 bytes and may cause high register pressure.
|
||||
@@ -1160,9 +1161,9 @@ __dpct_inline__ void gr_down_staged_kernel(GrMulti m, uint8_t *dpct_local) {
|
||||
const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
|
||||
const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(wrow);
|
||||
const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first)
|
||||
float acc[kFusedGrMaxT];
|
||||
float acc[MAX_T];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
|
||||
for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f;
|
||||
sycl::uint4 wv[HQ], wnext[HQ];
|
||||
if (active) {
|
||||
#pragma unroll
|
||||
@@ -1208,7 +1209,7 @@ __dpct_inline__ void gr_down_staged_kernel(GrMulti m, uint8_t *dpct_local) {
|
||||
for (int q = 0; q < HQ; ++q) {
|
||||
const int j = lane + 32 * q;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) {
|
||||
for (int k = 0; k < MAX_T; ++k) {
|
||||
if (k < T) {
|
||||
const sycl::float4 *pk = cur + (size_t)k * (H_TILE / 4);
|
||||
acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]);
|
||||
@@ -1234,12 +1235,12 @@ __dpct_inline__ void gr_down_staged_kernel(GrMulti m, uint8_t *dpct_local) {
|
||||
}
|
||||
}
|
||||
if (!active) return;
|
||||
float s[kFusedGrMaxT];
|
||||
float s[MAX_T];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
|
||||
for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
|
||||
// lane k writes token k (every lane holds every sum after the xor reduction)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kFusedGrMaxT; ++k) {
|
||||
for (int k = 0; k < MAX_T; ++k) {
|
||||
if (k >= T || lane != k) continue;
|
||||
if (inject_block) {
|
||||
m.a[k].inject_out[row] = s[k];
|
||||
@@ -1392,74 +1393,172 @@ void launch_multi(const GrMulti &m, int variant, dpct::queue_ptr st,
|
||||
for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k];
|
||||
}
|
||||
const size_t smem = (size_t) ct * per_tok;
|
||||
// #443, opt-in STRATA_GR_DOWN_MAX4=1: launches of up to 4 tokens hold 4 tokens' sums per thread instead of
|
||||
// kFusedGrMaxT - the same tile, block size, accumulation order and plain/split/staged path, so the same bits
|
||||
// (read once: this runs per layer when decode is not captured)
|
||||
static const bool max4_on = [] { const char* v = std::getenv("STRATA_GR_DOWN_MAX4"); return v && std::atoi(v) != 0; }();
|
||||
const bool max4 = max4_on && ct <= 4;
|
||||
if (staged) {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
if (max4) {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
|
||||
cgh.parallel_for<
|
||||
dpct_kernel_name<class gr_down_staged_kernel_41b428>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
|
||||
32)]] {
|
||||
gr_down_staged_kernel(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
cgh.parallel_for<
|
||||
dpct_kernel_name<class gr_down_staged_kernel_41b428,
|
||||
dpct_kernel_scalar<4>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1)
|
||||
[[sycl::reqd_sub_group_size(32)]] {
|
||||
gr_down_staged_kernel<4>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<
|
||||
sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
} else {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
|
||||
/*
|
||||
DPCT1050: The template argument of the dpct_kernel_name
|
||||
could not be deduced. You need to update this code.
|
||||
*/
|
||||
cgh.parallel_for<dpct_kernel_name<
|
||||
class gr_down_staged_kernel_41b428>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1)
|
||||
[[sycl::reqd_sub_group_size(32)]] {
|
||||
gr_down_staged_kernel(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<
|
||||
sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
}
|
||||
} else if (tv == 1280) {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
if (max4) {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
|
||||
cgh.parallel_for<
|
||||
dpct_kernel_name<class gr_down_multi_kernel_fa80e0,
|
||||
dpct_kernel_scalar<1280>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
|
||||
32)]] {
|
||||
gr_down_multi_kernel<1280>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
cgh.parallel_for<dpct_kernel_name<
|
||||
class gr_down_multi_kernel_4a9670,
|
||||
dpct_kernel_scalar<1280>, dpct_kernel_scalar<4>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1)
|
||||
[[sycl::reqd_sub_group_size(32)]] {
|
||||
gr_down_multi_kernel<1280, 4>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<
|
||||
sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
} else {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
|
||||
/*
|
||||
DPCT1050: The template argument of the dpct_kernel_name
|
||||
could not be deduced. You need to update this code.
|
||||
*/
|
||||
cgh.parallel_for<dpct_kernel_name<
|
||||
class gr_down_multi_kernel_6a749c,
|
||||
dpct_kernel_scalar<1280>, dpct_kernel_scalar<1280>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1)
|
||||
[[sycl::reqd_sub_group_size(32)]] {
|
||||
gr_down_multi_kernel<1280>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<
|
||||
sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
}
|
||||
} else {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
if (max4) {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
|
||||
cgh.parallel_for<
|
||||
dpct_kernel_name<class gr_down_multi_kernel_41414e,
|
||||
dpct_kernel_scalar<2560>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
|
||||
32)]] {
|
||||
gr_down_multi_kernel<2560>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
cgh.parallel_for<dpct_kernel_name<
|
||||
class gr_down_multi_kernel_2d8885,
|
||||
dpct_kernel_scalar<2560>, dpct_kernel_scalar<4>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1)
|
||||
[[sycl::reqd_sub_group_size(32)]] {
|
||||
gr_down_multi_kernel<2560, 4>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<
|
||||
sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
} else {
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
st->submit([&](sycl::handler &cgh) {
|
||||
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
|
||||
sycl::range(smem), cgh);
|
||||
|
||||
/*
|
||||
DPCT1050: The template argument of the dpct_kernel_name
|
||||
could not be deduced. You need to update this code.
|
||||
*/
|
||||
cgh.parallel_for<dpct_kernel_name<
|
||||
class gr_down_multi_kernel_df2ead,
|
||||
dpct_kernel_scalar<2560>, dpct_kernel_scalar<2560>>>(
|
||||
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) *
|
||||
sycl::range(1, 1, THREADS),
|
||||
sycl::range(1, 1, THREADS)),
|
||||
exp_props,
|
||||
[=](sycl::nd_item<3> item_ct1)
|
||||
[[sycl::reqd_sub_group_size(32)]] {
|
||||
gr_down_multi_kernel<2560>(
|
||||
c, dpct_local_acc_ct1
|
||||
.get_multi_ptr<
|
||||
sycl::access::decorated::no>()
|
||||
.get());
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);
|
||||
|
||||
@@ -427,7 +427,7 @@ __dpct_inline__ float vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq,
|
||||
// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the
|
||||
// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,
|
||||
// gopinath87607), which agree with llama.cpp and with each other.
|
||||
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q8_0 = 2;
|
||||
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2;
|
||||
|
||||
__dpct_inline__ float vec_dot_q4_K_q8_1_impl_vmmq(
|
||||
const int *__restrict__ v, const int *__restrict__ u,
|
||||
@@ -544,6 +544,38 @@ __dpct_inline__ float vec_dot_q5_K_q8_1(const void *__restrict__ vbq,
|
||||
// of the ORIGINAL activations. That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant
|
||||
// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2%
|
||||
// against 1.9% relative error per expert). Result: sumi * (d5 * d8) + sumu * (m5 * d8).
|
||||
// Q5_0: llama.cpp's integer chain verbatim (vecdotq.cuh vec_dot_q5_0_q8_1_impl) -- symmetric (one delta, no
|
||||
// learned min), so unlike Q5_1 there is no min-term rounding choice to make: the constant -16 per-weight offset
|
||||
// is accounted for via the q8_1 block's `ds.y` (sum of the ORIGINAL activations), exactly as upstream.
|
||||
__dpct_inline__ float vec_dot_q5_0_q8_1(const void *__restrict__ vbq,
|
||||
const block_q8_1 *__restrict__ bq8_1,
|
||||
const int &kbx, const int &iqs) {
|
||||
const block_q5_0* bq5_0 = (const block_q5_0*) vbq + kbx;
|
||||
int sumi = 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < VDR_Q5_0; ++i) {
|
||||
const int vl = get_int_b2(bq5_0->qs, iqs + i);
|
||||
const int vh = get_int_b2(bq5_0->qh, 0) >> (4 * (iqs + i));
|
||||
const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_0);
|
||||
int vi0 = (vl >> 0) & 0x0F0F0F0F;
|
||||
vi0 |= (vh << 4) & 0x00000010;
|
||||
vi0 |= (vh << 11) & 0x00001000;
|
||||
vi0 |= (vh << 18) & 0x00100000;
|
||||
vi0 |= (vh << 25) & 0x10000000;
|
||||
sumi = ggml_cuda_dp4a(vi0, u0, sumi);
|
||||
int vi1 = (vl >> 4) & 0x0F0F0F0F;
|
||||
vi1 |= (vh >> 12) & 0x00000010;
|
||||
vi1 |= (vh >> 5) & 0x00001000;
|
||||
vi1 |= (vh << 2) & 0x00100000;
|
||||
vi1 |= (vh << 9) & 0x10000000;
|
||||
sumi = ggml_cuda_dp4a(vi1, u1, sumi);
|
||||
}
|
||||
const float d5 = sycl::vec<sycl::half, 1>(bq5_0->d)
|
||||
.convert<float, sycl::rounding_mode::automatic>()[0];
|
||||
const float d8 = bq8_1->ds[0];
|
||||
const float s8 = bq8_1->ds[1];
|
||||
return d5 * (sumi * d8 - (16.0f * VDR_Q5_0 / QI5_0) * s8);
|
||||
}
|
||||
__dpct_inline__ float vec_dot_q5_1_q8_1(const void *__restrict__ vbq,
|
||||
const block_q8_1 *__restrict__ bq8_1,
|
||||
const int &kbx, const int &iqs) {
|
||||
@@ -615,14 +647,16 @@ template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_
|
||||
static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };
|
||||
template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;
|
||||
static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };
|
||||
template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0;
|
||||
static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } };
|
||||
template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0;
|
||||
static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } };
|
||||
|
||||
// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every
|
||||
// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
|
||||
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(8)
|
||||
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(8)
|
||||
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(8)
|
||||
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8)
|
||||
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8)
|
||||
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8)
|
||||
|
||||
__dpct_inline__ float warp_sum(float v) {
|
||||
#pragma unroll
|
||||
@@ -1576,10 +1610,10 @@ __dpct_inline__ void swiglu_q8_1_entries_kernel(
|
||||
const float h = (g / (1.0f + __expf(-g))) * up[i];
|
||||
#else
|
||||
/*
|
||||
DPCT1013: The rounding mode could not be specified and the generated
|
||||
code may have different accuracy than the original code. Verify the
|
||||
correctness. SYCL math built-in function rounding mode is aligned with
|
||||
OpenCL C 1.2 standard.
|
||||
DPCT1013: The rounding mode could not be specified and the
|
||||
generated code may have different accuracy than the original code.
|
||||
Verify the correctness. SYCL math built-in function rounding mode is
|
||||
aligned with OpenCL C 1.2 standard.
|
||||
*/
|
||||
const float h = (g / (1.0f + sycl::native::exp(-g))) * up[i];
|
||||
#endif
|
||||
@@ -1841,6 +1875,24 @@ inline void dq_q5_k(const void *vx, int64_t ibs, dst_t *yy, int tid) {
|
||||
}
|
||||
}
|
||||
template <typename dst_t>
|
||||
inline void dq_q5_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
|
||||
// symmetric: one delta (no min), the high bit folded in then centered by the format's fixed -16 offset
|
||||
const block_q5_0* x = (const block_q5_0*) vx + ibs * (QK_K / QK5_0);
|
||||
const int ib = tid % 8, il = tid / 8;
|
||||
const float d = sycl::vec<sycl::half, 1>(x[ib].d)
|
||||
.convert<float, sycl::rounding_mode::automatic>()[0];
|
||||
uint32_t qh;
|
||||
memcpy(&qh, x[ib].qh, sizeof(qh));
|
||||
dst_t* y = yy + 32 * ib;
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
const int iqs = 4 * il + j;
|
||||
const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
|
||||
const int xh_1 = ((qh >> (iqs + 12))) & 0x10;
|
||||
y[iqs] = cvt<dst_t>(((float) ((x[ib].qs[iqs] & 0xf) | xh_0) - 16.0f) * d);
|
||||
y[iqs + 16] = cvt<dst_t>(((float) ((x[ib].qs[iqs] >> 4) | xh_1) - 16.0f) * d);
|
||||
}
|
||||
}
|
||||
template <typename dst_t>
|
||||
inline void dq_q5_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {
|
||||
const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1);
|
||||
const int ib = tid % 8, il = tid / 8;
|
||||
@@ -1902,6 +1954,7 @@ dq_dispatch(int ty, const void *vx, int64_t ibs, dst_t *y, int tid) {
|
||||
case 12: dq_q4_k(vx, ibs, y, tid); break;
|
||||
case 13: dq_q5_k(vx, ibs, y, tid); break;
|
||||
case 7: dq_q5_1(vx, ibs, y, tid); break;
|
||||
case 6: dq_q5_0(vx, ibs, y, tid); break;
|
||||
case 8: dq_q8_0(vx, ibs, y, tid); break;
|
||||
case 30: dq_bf16(vx, ibs, y, tid); break;
|
||||
default: break;
|
||||
@@ -1932,7 +1985,7 @@ __dpct_inline__ void dequant_gu_kernel(
|
||||
// the types dq_dispatch dequantizes
|
||||
bool is_iq(int t) {
|
||||
return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
|
||||
t == 12 || t == 13 || t == 7 || t == 8;
|
||||
t == 12 || t == 13 || t == 7 || t == 6 || t == 8;
|
||||
}
|
||||
// values per block of the types the grouped expert kernels take (0 = none)
|
||||
int gu_qk(int t) {
|
||||
@@ -2253,6 +2306,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {
|
||||
case 12: return (size_t) (n / 256) * sizeof(block_q4_K);
|
||||
case 13: return (size_t) (n / 256) * sizeof(block_q5_K);
|
||||
case 7: return (size_t) (n / 32) * sizeof(block_q5_1);
|
||||
case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
|
||||
case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
|
||||
case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
|
||||
default: return 0;
|
||||
@@ -2501,7 +2555,7 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
s->parallel_for<
|
||||
dpct_kernel_name<class quantize_q8_1_kernel_2f9312>>(
|
||||
dpct_kernel_name<class quantize_q8_1_kernel_cfb6c5>>(
|
||||
sycl::nd_range<3>(
|
||||
sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *
|
||||
sycl::range(1, 1, 256),
|
||||
|
||||
@@ -103,20 +103,24 @@ __dpct_inline__ uint32_t pack_h2(float lo_k,
|
||||
// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1).
|
||||
// KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at
|
||||
// gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output.
|
||||
// KV_MODE 4 (Q4_0 K and V, `--kv q4_0`): mode 1 with a scale per 32 values - each q4_0 block's codes enter as exact
|
||||
// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the
|
||||
// output (kv_q4.hpp).
|
||||
template <int KV_MODE>
|
||||
struct Smem {
|
||||
using KElem =
|
||||
typename std::conditional<KV_MODE == 0, sycl::half, int8_t>::type;
|
||||
using VElem =
|
||||
typename std::conditional<KV_MODE == 1, int8_t, sycl::half>::type;
|
||||
using VElem = typename std::conditional<KV_MODE == 1 || KV_MODE == 4,
|
||||
int8_t, sycl::half>::type;
|
||||
static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16; // elements; 16-byte aligned rows, banks spread
|
||||
static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8;
|
||||
static constexpr int VROW = (KV_MODE == 1 || KV_MODE == 4) ? HD + 16 : HD + 8;
|
||||
static constexpr int NG = KV_MODE == 4 ? HD / QK4_0 : 4; // scale groups per row (q4_0: 8 of 32, else 4 of 64)
|
||||
sycl::half qh[16][QS];
|
||||
sycl::half ql[16][QS];
|
||||
KElem k[CH][KROW];
|
||||
VElem v[CH][VROW];
|
||||
float ks[CH][4];
|
||||
float vs[CH][4];
|
||||
float ks[CH][NG];
|
||||
float vs[CH][NG];
|
||||
float s[16][CH + 1];
|
||||
float qmax[THREADS / 32];
|
||||
float alpha[16];
|
||||
@@ -235,7 +239,71 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
|
||||
// k, v, s
|
||||
// gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
|
||||
// and their scales
|
||||
{
|
||||
if constexpr (KV_MODE == 4) {
|
||||
// q4_0 K and V: one (K or V, cell, block) per item - the block's 16 code bytes (2-byte aligned: eight
|
||||
// 16-bit loads) become 32 exact int8 codes (element j in the low nibble of byte j, j + 16 in the high
|
||||
// one), its fp16 scale goes to ks/vs
|
||||
constexpr int BLKS = HD / QK4_0;
|
||||
constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
|
||||
for (int i = t; i < 2 * CH * BLKS; i += THREADS) {
|
||||
const int kv = i / (CH * BLKS), rem = i % (CH * BLKS), c = rem / BLKS, b = rem % BLKS;
|
||||
const long long r = S.row[c];
|
||||
sycl::uint4 lo = sycl::uint4(0, 0, 0, 0),
|
||||
hi = sycl::uint4(0, 0, 0, 0);
|
||||
float d = 0.0f;
|
||||
if (r >= 0) {
|
||||
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((kv == 0 ? p.k_q4 : p.v_q4) + r * BYTES) + b;
|
||||
/*
|
||||
DPCT1098: The '*' expression is used instead of the
|
||||
__ldg call. These two expressions do not provide the exact
|
||||
same functionality. Check the generated code for potential
|
||||
precision and/or performance issues.
|
||||
*/
|
||||
d = sycl::vec<sycl::half, 1>(
|
||||
sycl::bit_cast<sycl::half, unsigned short>(blk->d))
|
||||
.convert<float,
|
||||
sycl::rounding_mode::automatic>()[0];
|
||||
const uint16_t* q16 = reinterpret_cast<const uint16_t*>(blk->qs);
|
||||
uint32_t w[4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
/*
|
||||
DPCT1098: The '*' expression is used instead of the
|
||||
__ldg call. These two expressions do not provide the
|
||||
exact same functionality. Check the generated code for
|
||||
potential precision and/or performance issues.
|
||||
*/
|
||||
w[j] = (uint32_t)*(q16 + 2 * j) |
|
||||
((uint32_t)*(q16 + 2 * j + 1) << 16);
|
||||
// per byte: the low nibble minus 8 is element j, the high one minus 8 element j + 16
|
||||
lo = sycl::uint4(
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
w[0] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()),
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
w[1] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()),
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
w[2] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()),
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
w[3] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()));
|
||||
hi = sycl::uint4(dpct::vectorized_binary<sycl::uchar4>(
|
||||
(w[0] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
|
||||
std::minus<>()),
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
(w[1] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
|
||||
std::minus<>()),
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
(w[2] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
|
||||
std::minus<>()),
|
||||
dpct::vectorized_binary<sycl::uchar4>(
|
||||
(w[3] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
|
||||
std::minus<>()));
|
||||
}
|
||||
int8_t* dst = kv == 0 ? &S.k[c][b * QK4_0] : &S.v[c][b * QK4_0];
|
||||
reinterpret_cast<sycl::uint4 *>(dst)[0] = lo;
|
||||
reinterpret_cast<sycl::uint4 *>(dst)[1] = hi;
|
||||
(kv == 0 ? S.ks : S.vs)[c][b] = d;
|
||||
}
|
||||
} else {
|
||||
constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16; // per K row
|
||||
for (int i = t; i < CH * KPIECES; i += THREADS) {
|
||||
const int c = i / KPIECES, pc = i % KPIECES;
|
||||
@@ -375,17 +443,18 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
|
||||
better performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
// scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per 64-dim scale group
|
||||
// scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32)
|
||||
constexpr int NG = Smem<KV_MODE>::NG, KPG = HD / 16 / NG; // groups per row, 16-dim MMA steps per group
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < CH / 32; ++nt) {
|
||||
const int cb = (warp + 4 * nt) * 8;
|
||||
float sc[4] = {0.f, 0.f, 0.f, 0.f};
|
||||
#pragma unroll
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
for (int g = 0; g < NG; ++g) {
|
||||
float tg[4] = {0.f, 0.f, 0.f, 0.f};
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < 4; ++kk) {
|
||||
const int k0 = (g * 4 + kk) * 16;
|
||||
for (int kk = 0; kk < KPG; ++kk) {
|
||||
const int k0 = (g * KPG + kk) * 16;
|
||||
uint32_t ah[4], al[4], b[2];
|
||||
ah[0] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig]);
|
||||
ah[1] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig]);
|
||||
@@ -489,14 +558,23 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
|
||||
better performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
// p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w. The scale is folded into p relative to
|
||||
// the chunk's largest, times 2^14 (p' <= 2^14: its lo half stays out of FP16's subnormal range); the chunk's
|
||||
// sum is then added to the running one in FP32 with the factor taken back out
|
||||
// p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w (q4_0: groups 2w and 2w+1, four n-tiles
|
||||
// each). A group's scale is folded into p relative to the chunk's largest magnitude (q4_0's scales are signed:
|
||||
// ggml's d = max / -8), times 2^14 (|p'| <= 2^14: inside FP16's range, its lo half out of the subnormals); the
|
||||
// chunk's sum is then added to the running one in FP32 with the factor taken back out
|
||||
{
|
||||
constexpr int GPW = NG / 4, JPG = 8 / GPW; // scale groups per warp, n-tiles per group
|
||||
float vdown_g[GPW];
|
||||
float tmp[8][4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int gi = 0; gi < GPW; ++gi) {
|
||||
const int vg = warp * GPW + gi;
|
||||
float vmax = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = lane; c < CH; c += 32)
|
||||
vmax = sycl::fmax(vmax, S.vs[c][warp]);
|
||||
vmax = sycl::fmax(vmax, sycl::fabs(S.vs[c][vg]));
|
||||
#pragma unroll
|
||||
/*
|
||||
DPCT1108: '__shfl_xor_sync' was migrated with the experimental
|
||||
@@ -508,15 +586,13 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
|
||||
0xffffffffu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(),
|
||||
vmax, o));
|
||||
const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
|
||||
float tmp[8][4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
|
||||
const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f;
|
||||
vdown_g[gi] = vmax * (1.0f / 16384.0f);
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < CH / 16; ++ks) {
|
||||
const int cA = ks * 16 + 2 * tig, cB = cA + 8;
|
||||
const float w0 = S.vs[cA][warp] * vup, w1 = S.vs[cA + 1][warp] * vup, w2 = S.vs[cB][warp] * vup,
|
||||
w3 = S.vs[cB + 1][warp] * vup;
|
||||
const float w0 = S.vs[cA][vg] * vup, w1 = S.vs[cA + 1][vg] * vup, w2 = S.vs[cB][vg] * vup,
|
||||
w3 = S.vs[cB + 1][vg] * vup;
|
||||
const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1;
|
||||
const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1;
|
||||
const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3;
|
||||
@@ -544,10 +620,11 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
|
||||
al[3] = pack_h2(p12 - f.x(), p13 - f.y());
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
for (int jj = 0; jj < JPG; ++jj) {
|
||||
const int j = gi * JPG + jj;
|
||||
const int d = warp * 64 + j * 8 + gid;
|
||||
uint32_t b[2];
|
||||
if constexpr (KV_MODE == 1) {
|
||||
if constexpr (KV_MODE == 1 || KV_MODE == 4) {
|
||||
const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8);
|
||||
const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8);
|
||||
b[0] = i8x2_to_h2(x0);
|
||||
@@ -566,9 +643,11 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const float vdown = vdown_g[j / JPG];
|
||||
acc[j][0] = sycl::fma(acc[j][0], (float)a0, tmp[j][0] * vdown);
|
||||
acc[j][1] = sycl::fma(acc[j][1], (float)a0, tmp[j][1] * vdown);
|
||||
acc[j][2] = sycl::fma(acc[j][2], (float)a1, tmp[j][2] * vdown);
|
||||
@@ -1458,10 +1537,8 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,
|
||||
|
||||
} // namespace
|
||||
|
||||
bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
|
||||
const int32_t *ids, const int32_t *steps,
|
||||
int64_t cap, const QsaShapes &s, float *attn,
|
||||
int64_t n_q, void *stream) try {
|
||||
bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
|
||||
int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
|
||||
if (n_q <= 0) return true;
|
||||
bool turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
|
||||
{ // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has
|
||||
@@ -1511,10 +1588,18 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
|
||||
return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
|
||||
return false;
|
||||
#endif
|
||||
if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids ||
|
||||
!steps || !pools.page_table)
|
||||
if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table)
|
||||
return false;
|
||||
dpct::queue_ptr st = strata::q_of(stream);
|
||||
if (pools.k_q4 != nullptr) { // Q4_0 K and V (--kv q4_0): mode 4. STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B)
|
||||
static const bool q4_off = [] {
|
||||
const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4");
|
||||
return v != nullptr && v[0] == '0';
|
||||
}();
|
||||
// sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet
|
||||
if (q4_off || turing || pools.v_q4 == nullptr) return false;
|
||||
return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V
|
||||
if (!pools.k_scale) return false;
|
||||
return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
@@ -1531,10 +1616,5 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
|
||||
if (!pools.k_pool || !pools.v_pool) return false;
|
||||
return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
|
||||
}
|
||||
catch (sycl::exception const &exc) {
|
||||
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
||||
<< ", line:" << __LINE__ << std::endl;
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
} // namespace strata::kernels
|
||||
@@ -925,6 +925,362 @@ auto &qs = *sycl::ext::oneapi::group_local_memory_for_overwrite<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or
|
||||
// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to
|
||||
// 65,538 blocks on ONE SM while the rest of the GPU idles - a decode window has 1-5 queries. Here a cluster of CL_N
|
||||
// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit
|
||||
// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster
|
||||
// barrier each CTA sums the CL_N slots itself, so all of them take the same digit. The emit pass needs each CTA's
|
||||
// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it.
|
||||
// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K,
|
||||
// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass).
|
||||
//
|
||||
// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with
|
||||
// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer
|
||||
// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d
|
||||
// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with
|
||||
// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut),
|
||||
// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr
|
||||
// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there.
|
||||
//
|
||||
// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared
|
||||
// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store
|
||||
// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads
|
||||
// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads
|
||||
// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at
|
||||
// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier.
|
||||
constexpr int CL_N = 8; // CTAs per query (the portable cluster size)
|
||||
constexpr int CL_T = 1024; // threads per CTA
|
||||
constexpr int CL_MAXQ = 16; // larger calls (prefill sub-batches) fill the GPU with one CTA per query already
|
||||
#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 900
|
||||
#define STRATA_SEL_CLUSTER 1
|
||||
#else
|
||||
#define STRATA_SEL_CLUSTER 0 // an older target's code is a trap; qsa_block_topk_cluster never launches it there
|
||||
#endif
|
||||
|
||||
#if STRATA_SEL_CLUSTER
|
||||
__dpct_inline__ void cl_arrive_relaxed() {
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
|
||||
}
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
__dpct_inline__ void cl_arrive() {
|
||||
asm volatile("barrier.cluster.arrive.release.aligned;\n" :: : "memory");
|
||||
}
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
__dpct_inline__ void cl_wait() {
|
||||
asm volatile("barrier.cluster.wait.acquire.aligned;\n" :: : "memory");
|
||||
}
|
||||
__dpct_inline__ unsigned cl_rank() {
|
||||
unsigned r;
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(r));
|
||||
return r;
|
||||
}
|
||||
template <typename T>
|
||||
__dpct_inline__ T *cl_map(T *p,
|
||||
unsigned rank) { // p in CTA `rank`'s shared memory
|
||||
uint64_t o;
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("mapa.u64 %0, %1, %2;\n"
|
||||
: "=l"(o)
|
||||
: "l"((uint64_t)p), "r"(rank));
|
||||
return reinterpret_cast<T*>(o);
|
||||
}
|
||||
// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum
|
||||
__dpct_inline__ unsigned long long cl_excl_scan64(unsigned long long v,
|
||||
unsigned long long *s_warp,
|
||||
unsigned long long &total) {
|
||||
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
||||
const int lane = item_ct1.get_local_id(2) & 31,
|
||||
warp = item_ct1.get_local_id(2) >> 5;
|
||||
unsigned long long x = v;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
/*
|
||||
DPCT1108: '__shfl_up_sync' was migrated with the experimental feature
|
||||
masked sub_group function which may not be supported by all compilers or
|
||||
runtimes. You may need to adjust the code.
|
||||
*/
|
||||
const unsigned long long y = dpct::experimental::shift_sub_group_right(
|
||||
0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
|
||||
o);
|
||||
if (lane >= o) x += y;
|
||||
}
|
||||
if (lane == 31) s_warp[warp] = x;
|
||||
/*
|
||||
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
||||
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
||||
performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
if (warp == 0) {
|
||||
const unsigned long long w = s_warp[lane];
|
||||
unsigned long long z = w;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
/*
|
||||
DPCT1108: '__shfl_up_sync' was migrated with the experimental
|
||||
feature masked sub_group function which may not be supported by all
|
||||
compilers or runtimes. You may need to adjust the code.
|
||||
*/
|
||||
const unsigned long long y =
|
||||
dpct::experimental::shift_sub_group_right(
|
||||
0xffffffffu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(), z, o);
|
||||
if (lane >= o) z += y;
|
||||
}
|
||||
s_warp[lane] = z - w;
|
||||
if (lane == 31) s_warp[32] = z;
|
||||
}
|
||||
/*
|
||||
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
||||
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
||||
performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
total = s_warp[32];
|
||||
return s_warp[warp] + x - v;
|
||||
}
|
||||
#endif
|
||||
|
||||
// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys
|
||||
/*
|
||||
DPCT1110: The total declared local variable size in device function
|
||||
block_topk_cluster_kernel exceeds 128 bytes and may cause high register
|
||||
pressure. Consult with your hardware vendor to find the total register size
|
||||
available and adjust the code, or use smaller sub-group size to avoid high
|
||||
register pressure.
|
||||
*/
|
||||
void block_topk_cluster_kernel(const float *__restrict__ scores,
|
||||
const int32_t *__restrict__ steps,
|
||||
int64_t max_blocks, int64_t cap,
|
||||
int32_t *__restrict__ ids, uint8_t *dpct_local) {
|
||||
#if STRATA_SEL_CLUSTER
|
||||
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
||||
auto keys = (uint32_t *)dpct_local; // this CTA's blocks' keys
|
||||
auto &hin =
|
||||
*sycl::ext::oneapi::group_local_memory_for_overwrite<int[2][CL_N][256]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<
|
||||
3>()); // the cluster's histograms, slot = the pushing rank
|
||||
auto &hloc =
|
||||
*sycl::ext::oneapi::group_local_memory_for_overwrite<int[2][256]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<
|
||||
3>()); // this CTA's histogram
|
||||
auto &cnt = *sycl::ext::oneapi::group_local_memory_for_overwrite<
|
||||
unsigned long long[CL_N]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<
|
||||
3>()); // per rank: its cells above thr (low 32 bits) and at it
|
||||
// (high)
|
||||
auto &s_warp = *sycl::ext::oneapi::group_local_memory_for_overwrite<
|
||||
unsigned long long[33]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
||||
auto &s_prefix =
|
||||
*sycl::ext::oneapi::group_local_memory_for_overwrite<uint32_t>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
||||
auto &s_above = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
||||
const unsigned rank = cl_rank();
|
||||
const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
|
||||
cl_arrive_relaxed(); // phase 0: this CTA runs
|
||||
const int64_t qi = item_ct1.get_group(1);
|
||||
const int32_t* st = steps + qi * kStepCount;
|
||||
const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
|
||||
int32_t* out = ids + qi * cap;
|
||||
if (n_kv <= width) { // the identity, split over the cluster; no remote access
|
||||
#pragma unroll
|
||||
for (int64_t j = (int64_t)rank * CL_T + t; j < n_kv;
|
||||
j += (int64_t)CL_N * CL_T) out[j] = (int32_t)j;
|
||||
return;
|
||||
}
|
||||
// the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0)
|
||||
const int wtail = (int) (n_kv - n_bid * R);
|
||||
const int64_t nbe = n_bid + (wtail > 0 ? 1 : 0);
|
||||
const int64_t per = (nbe + CL_N - 1) / CL_N; // <= ceil(max_blocks / CL_N), the keys the host sized
|
||||
const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe;
|
||||
const int64_t hi = lo + per < nbe ? lo + per : nbe;
|
||||
const int n = (int) (hi - lo);
|
||||
const int tail_i = (wtail > 0 && n_bid >= lo && n_bid < hi) ? (int) (n_bid - lo) : -1;
|
||||
const float* sc = scores + qi * max_blocks + lo;
|
||||
#pragma unroll
|
||||
for (int i = t; i < n; i += CL_T) keys[i] = order_key(sc[i]);
|
||||
#pragma unroll
|
||||
for (int i = t; i < 2 * 256; i += CL_T)(&hloc[0][0])[i] = 0;
|
||||
/*
|
||||
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
||||
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
|
||||
performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
uint32_t prefix = 0;
|
||||
int above = 0; // cells strictly above the digits fixed so far
|
||||
for (int pass = 0; pass < 4; ++pass) {
|
||||
const int shift = 24 - 8 * pass;
|
||||
const uint32_t hmask = pass == 0 ? 0u : (0xffffffffu << (shift + 8));
|
||||
int* hl = hloc[pass & 1];
|
||||
// warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins
|
||||
for (int i0 = 0; i0 < n; i0 += CL_T) {
|
||||
const int i = i0 + t;
|
||||
int bin = -1;
|
||||
if (i < n) {
|
||||
const uint32_t k = keys[i];
|
||||
if ((k & hmask) == prefix) bin = (int) ((k >> shift) & 255);
|
||||
}
|
||||
const unsigned same = dpct::match_any_over_sub_group(
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(), 0xffffffffu,
|
||||
bin);
|
||||
if (bin >= 0 && lane == dpct::ffs<int>(same) - 1)
|
||||
dpct::atomic_fetch_add<
|
||||
sycl::access::address_space::generic_space>(
|
||||
&hl[bin], sycl::popcount(same) * R);
|
||||
if (bin >= 0 && i == tail_i) dpct::atomic_fetch_add<
|
||||
sycl::access::address_space::generic_space>(&hl[bin],
|
||||
wtail - R);
|
||||
}
|
||||
/*
|
||||
DPCT1118: SYCL group functions and algorithms must be encountered in
|
||||
converged control flow. You may need to adjust the code.
|
||||
*/
|
||||
/*
|
||||
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
||||
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
|
||||
better performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
if (pass == 0) cl_wait(); // phase 0 done: every CTA's shared memory is there
|
||||
for (int i = t; i < CL_N * 64; i += CL_T) { // the histogram into slot `rank` of every CTA, as int4
|
||||
const int dst = i >> 6, c = i & 63;
|
||||
*cl_map(reinterpret_cast<sycl::int4 *>(&hin[pass & 1][rank][0]) + c,
|
||||
(unsigned)dst) =
|
||||
reinterpret_cast<const sycl::int4 *>(hl)[c];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = t; i < 256; i += CL_T) hloc[(pass + 1) & 1][i] = 0;
|
||||
cl_arrive();
|
||||
cl_wait();
|
||||
if (warp == 0) {
|
||||
// lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top
|
||||
const int need = (int) width - above;
|
||||
int tot[8], part = 0;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const int d = 255 - 8 * lane - k;
|
||||
int v = 0;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < CL_N; ++r) v += hin[pass & 1][r][d];
|
||||
tot[k] = v;
|
||||
part += v;
|
||||
}
|
||||
int incl = part;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
/*
|
||||
DPCT1108: '__shfl_up_sync' was migrated with the experimental
|
||||
feature masked sub_group function which may not be supported by
|
||||
all compilers or runtimes. You may need to adjust the code.
|
||||
*/
|
||||
const int y = dpct::experimental::shift_sub_group_right(
|
||||
0xffffffffu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(), incl,
|
||||
o);
|
||||
if (lane >= o) incl += y;
|
||||
}
|
||||
const int excl = incl - part;
|
||||
const unsigned hit = sycl::reduce_over_group(
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(),
|
||||
(0xffffffffu &
|
||||
(0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
|
||||
.get_local_linear_id())) &&
|
||||
excl < need && incl >= need
|
||||
? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
|
||||
.get_local_linear_id())
|
||||
: 0,
|
||||
sycl::ext::oneapi::plus<>());
|
||||
// no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0
|
||||
const int who = hit ? dpct::ffs<int>(hit) - 1 : 31;
|
||||
if (lane == who) {
|
||||
int acc = excl, k = 0;
|
||||
#pragma unroll
|
||||
for (; k < 7; ++k) {
|
||||
if (acc + tot[k] >= need) break;
|
||||
acc += tot[k];
|
||||
}
|
||||
s_prefix = prefix | ((uint32_t) (255 - 8 * lane - k) << shift);
|
||||
s_above = above + acc;
|
||||
}
|
||||
}
|
||||
/*
|
||||
DPCT1118: SYCL group functions and algorithms must be encountered in
|
||||
converged control flow. You may need to adjust the code.
|
||||
*/
|
||||
/*
|
||||
DPCT1065: Consider replacing sycl::nd_item::barrier() with
|
||||
sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
|
||||
better performance if there is no access to global memory.
|
||||
*/
|
||||
item_ct1.barrier();
|
||||
prefix = s_prefix;
|
||||
above = s_above;
|
||||
}
|
||||
const uint32_t thr = prefix;
|
||||
const int64_t eq_budget = width - above; // cells at thr that fit, lowest index first
|
||||
// each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free
|
||||
int seg = (n + CL_T - 1) / CL_T;
|
||||
if ((seg & 1) == 0 && seg > 0) ++seg;
|
||||
const int s0 = t * seg < n ? t * seg : n, s1 = s0 + seg < n ? s0 + seg : n;
|
||||
uint32_t gt = 0, eq = 0;
|
||||
for (int i = s0; i < s1; ++i) {
|
||||
const uint32_t k = keys[i], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R;
|
||||
if (k > thr) gt += w;
|
||||
else if (k == thr) eq += w;
|
||||
}
|
||||
unsigned long long cta;
|
||||
const unsigned long long before =
|
||||
cl_excl_scan64((unsigned long long) gt | ((unsigned long long) eq << 32), s_warp, cta);
|
||||
if (t < CL_N) *cl_map(&cnt[rank], (unsigned) t) = cta;
|
||||
cl_arrive();
|
||||
cl_wait();
|
||||
int64_t gt_off = 0, eq_off = 0;
|
||||
#pragma unroll
|
||||
for (unsigned r = 0; r < rank; ++r) {
|
||||
gt_off += (int64_t) (cnt[r] & 0xffffffffu);
|
||||
eq_off += (int64_t) (cnt[r] >> 32);
|
||||
}
|
||||
const int64_t eq_before = eq_off + (int64_t) (before >> 32);
|
||||
int64_t wpos = gt_off + (int64_t) (before & 0xffffffffu) + (eq_before < eq_budget ? eq_before : eq_budget);
|
||||
int64_t eq_left = eq_budget - eq_before;
|
||||
if (eq_left < 0) eq_left = 0;
|
||||
for (int i = s0; i < s1; ++i) {
|
||||
const uint32_t k = keys[i];
|
||||
const int w = i == tail_i ? wtail : R;
|
||||
const int64_t b = lo + i;
|
||||
if (k > thr) {
|
||||
#pragma unroll
|
||||
for (int c = 0; c < w; ++c) out[wpos++] = (int32_t)(b * R + c);
|
||||
} else if (k == thr) {
|
||||
#pragma unroll
|
||||
for (int c = 0; c < w && eq_left > 0; ++c, --eq_left)
|
||||
out[wpos++] = (int32_t)(b * R + c);
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void) scores; (void) steps; (void) max_blocks; (void) cap; (void) ids;
|
||||
/* unreachable on SYCL: the launcher refuses this device */
|
||||
#endif
|
||||
}
|
||||
#endif // !__HIPCC__
|
||||
} // namespace
|
||||
|
||||
void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
|
||||
@@ -1173,21 +1529,171 @@ void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, i
|
||||
*/
|
||||
}
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
// Only Turing has a retained model measurement for this CUDA dispatch. Other CUDA devices keep the capacity rule
|
||||
// (the RTX 5070 regression below). Cache the properties per calling thread; layer-split device switches are checked.
|
||||
static bool topk_active_turing_device() try {
|
||||
int dev = 0;
|
||||
if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) !=
|
||||
0) return false;
|
||||
static thread_local int cached_device = -1;
|
||||
static thread_local bool turing = false;
|
||||
if (dev != cached_device) {
|
||||
dpct::device_info prop{};
|
||||
if (DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(prop)) !=
|
||||
0) return false;
|
||||
/*
|
||||
DPCT1005: The SYCL device version is different from CUDA Compute
|
||||
Compatibility. You may need to rewrite this code.
|
||||
*/
|
||||
turing = prop.get_major_version() == 7 && prop.get_minor_version() == 5;
|
||||
cached_device = dev;
|
||||
}
|
||||
return turing;
|
||||
}
|
||||
catch (sycl::exception const &exc) {
|
||||
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
||||
<< ", line:" << __LINE__ << std::endl;
|
||||
std::exit(1);
|
||||
}
|
||||
#endif
|
||||
|
||||
bool qsa_block_topk_cluster(const float *scores, const int32_t *steps,
|
||||
int64_t nq, int64_t max_blocks, int64_t cap,
|
||||
const QsaShapes &s, int32_t *ids,
|
||||
void *stream) try {
|
||||
#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain top-k
|
||||
(void) scores; (void) steps; (void) nq; (void) max_blocks; (void) cap; (void) s; (void) ids; (void) stream;
|
||||
return false;
|
||||
#else
|
||||
if (nq <= 0) return true;
|
||||
if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s) || nq > 65535 || max_blocks <= 0) return false;
|
||||
const size_t smem = (size_t) ((max_blocks + CL_N - 1) / CL_N) * sizeof(uint32_t);
|
||||
// Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not. It needs sm_90+ (the
|
||||
// card's, or STRATA_EMULATE_CC's) AND code built for it: a build with only older code JIT-compiles their PTX, whose
|
||||
// copy of this kernel is a trap - the function's PTX version says which. `opt`: the dynamic shared memory opted in.
|
||||
static int ok[64] = {};
|
||||
static size_t opt[64] = {};
|
||||
int dev = 0;
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 || dev < 0 ||
|
||||
dev >= 64) {
|
||||
; return false;
|
||||
}
|
||||
if (ok[dev] == 0) {
|
||||
int major = 0;
|
||||
dpct::kernel_function_info fa{};
|
||||
const bool code =
|
||||
DPCT_CHECK_ERROR(
|
||||
major = dpct::get_device(dev).get_major_version()) == 0 &&
|
||||
strata::cc_major_of(major) >= 9 &&
|
||||
DPCT_CHECK_ERROR(dpct::get_kernel_function_info(
|
||||
&fa, (const void *)block_topk_cluster_kernel)) == 0 &&
|
||||
fa.ptxVersion >= 90 && fa.binaryVersion >= 90;
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
ok[dev] = code ? 1 : 2;
|
||||
}
|
||||
if (ok[dev] != 1) return false;
|
||||
if (smem > opt[dev]) { // a larger capacity: opt in, and check that a cluster of CL_N such CTAs can be resident
|
||||
int clusters = 0;
|
||||
cudaLaunchConfig_t q{};
|
||||
cudaLaunchAttribute qa[1];
|
||||
qa[0].id = cudaLaunchAttributeClusterDimension;
|
||||
qa[0].val.clusterDim.x = CL_N;
|
||||
qa[0].val.clusterDim.y = 1;
|
||||
qa[0].val.clusterDim.z = 1;
|
||||
q.gridDim = dpct::dim3(CL_N, 1, 1);
|
||||
q.blockDim = dpct::dim3(CL_T, 1, 1);
|
||||
q.dynamicSmemBytes = smem;
|
||||
q.attrs = qa;
|
||||
q.numAttrs = 1;
|
||||
/*
|
||||
DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
|
||||
because SYCL currently does not support corresponding setting.
|
||||
*/
|
||||
if (0 != 0 ||
|
||||
/*
|
||||
DPCT1007: Migration of cudaOccupancyMaxActiveClusters is not
|
||||
supported.
|
||||
*/
|
||||
cudaOccupancyMaxActiveClusters(&clusters, block_topk_cluster_kernel,
|
||||
&q) != 0 ||
|
||||
clusters < 1) {
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
return false; // this capacity takes the one-CTA kernels; a smaller
|
||||
// one may still fit
|
||||
}
|
||||
opt[dev] = smem;
|
||||
}
|
||||
cudaLaunchConfig_t cfg{};
|
||||
cudaLaunchAttribute at[1];
|
||||
at[0].id = cudaLaunchAttributeClusterDimension;
|
||||
at[0].val.clusterDim.x = CL_N;
|
||||
at[0].val.clusterDim.y = 1;
|
||||
at[0].val.clusterDim.z = 1;
|
||||
cfg.gridDim = dpct::dim3(CL_N, (unsigned)nq, 1);
|
||||
cfg.blockDim = dpct::dim3(CL_T, 1, 1);
|
||||
cfg.dynamicSmemBytes = smem;
|
||||
cfg.stream = strata::q_of(stream);
|
||||
cfg.attrs = at;
|
||||
cfg.numAttrs = 1;
|
||||
const dpct::err0 e = cudaLaunchKernelEx(
|
||||
&cfg, block_topk_cluster_kernel, scores, steps, max_blocks, cap, ids);
|
||||
/*
|
||||
DPCT1009: SYCL reports errors using exceptions and does not use error
|
||||
codes. Please replace the "get_error_string_dummy(...)" with a real
|
||||
error-handling function.
|
||||
*/
|
||||
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
catch (sycl::exception const &exc) {
|
||||
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
||||
<< ", line:" << __LINE__ << std::endl;
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
|
||||
const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {
|
||||
// keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1:
|
||||
// the kernel that reads them from memory on every pass
|
||||
static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;
|
||||
if (nq <= 0) return;
|
||||
#if !defined(__HIPCC__)
|
||||
// sm_90+: a cluster of CL_N CTAs per query for the calls of a few queries (decode windows); the same ids.
|
||||
// STRATA_QSA_CLUSTER=0: the one-CTA kernels below
|
||||
static const bool cluster = [] {
|
||||
const char* v = std::getenv("STRATA_QSA_CLUSTER");
|
||||
return !v || std::atoi(v) != 0;
|
||||
}();
|
||||
if (cluster && !old && nq <= CL_MAXQ && qsa_block_topk_cluster(scores, steps, nq, max_blocks, cap, s, ids, stream))
|
||||
return;
|
||||
#endif
|
||||
// the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity.
|
||||
// Decode (no count) keeps the capacity rule and the original register width: nothing changes there.
|
||||
#if defined(__HIPCC__)
|
||||
const bool counted = active_blocks > 0;
|
||||
#else
|
||||
// CUDA keeps 0.1.32's capacity rule: #337's dispatch was measured on RDNA4 only, and on the RTX 5070 the 64K
|
||||
// prompts read 1-3% slower with it
|
||||
const bool counted = false;
|
||||
(void) active_blocks;
|
||||
// Turing: --max-context 262144 makes the stride 65538, even while a 131K prompt's active blocks fit in
|
||||
// TK_T * TK_PER registers. Use the prefill bound on sm_75, keeping max_blocks as the score-row stride.
|
||||
// Other CUDA devices keep 0.1.32's capacity rule: #337 was measured on RDNA4, and RTX 5070 64K prompts were
|
||||
// 1-3% slower. Decode/captured graphs omit the bound and never query the device here.
|
||||
static const bool capacity_guard = std::getenv("STRATA_TOPK_CAPACITY_GUARD") != nullptr;
|
||||
// STRATA_TOPK_ACTIVE_ANY=1 (tests): the Turing dispatch on any CUDA card, so qsa_topk_active_parity checks it
|
||||
// on whatever card runs the tests (the kernels are the same on every architecture)
|
||||
static const bool any_card = [] { const char* v = std::getenv("STRATA_TOPK_ACTIVE_ANY"); return v && v[0] == '1'; }();
|
||||
const bool counted = !capacity_guard && active_blocks > 0 && active_blocks <= max_blocks &&
|
||||
(any_card || topk_active_turing_device());
|
||||
#endif
|
||||
const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks;
|
||||
const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER);
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test
|
||||
// does that against an independently computed distribution.
|
||||
//
|
||||
// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has
|
||||
// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary (on sm_90+ without penalties,
|
||||
// `sampler_greedy_cluster_kernel`: the same token from a cluster of 8 CTAs per row). The sampled chain has
|
||||
// three implementations that pick the same token, bit for bit:
|
||||
// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole
|
||||
// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail;
|
||||
@@ -24,6 +25,7 @@
|
||||
#include "strata/sycl_queue.hpp"
|
||||
#include "strata/kernels/sampler.hpp"
|
||||
#include "strata/core/coupled_draft.hpp"
|
||||
#include "strata/core/emulate.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -222,6 +224,175 @@ sampler_greedy_kernel(const float *__restrict__ logits, int n_vocab,
|
||||
}
|
||||
}
|
||||
|
||||
#if !defined(__HIPCC__)
|
||||
/// **THE SAME ARGMAX ON A THREAD-BLOCK CLUSTER (sm_90+, S19), FOR THE CALLS WITHOUT PENALTIES.** One block per
|
||||
/// token reads its 1 MB row (248,320 logits) on one SM with one load in flight per thread: latency-bound, 40 us per
|
||||
/// call on an RTX 5070, for every verify window and every draft step. Here a cluster of `kAmCtas` CTAs shares the
|
||||
/// row, each thread keeps four loads in flight, and the CTAs' results meet in CTA 0's shared memory (distributed
|
||||
/// shared memory): 6 us (decode_cluster_parity --bench).
|
||||
///
|
||||
/// The answer is a function of the row alone, so it is the one-block kernel's bit for bit: the LOWEST index whose value
|
||||
/// is the largest non-NaN value above -inf (each thread walks its elements in ascending order with a strict `>`, and
|
||||
/// every merge takes the larger value or, on equality, the smaller index - an order-free rule), and 0 when there is
|
||||
/// none (all -inf / NaN), as there. NaN never wins a `>`.
|
||||
///
|
||||
/// Barriers: a relaxed cluster arrive at entry, waited before the remote store (CTA 0 must be running); each CTA's
|
||||
/// result goes to slot `rank` of CTA 0, released by the next arrive; CTAs 1.. then exit (a cluster wait counts the
|
||||
/// threads that have not exited) and CTA 0 waits, reads its own slots, and writes the token.
|
||||
constexpr int kAmCtas = 8; // CTAs per token (the portable cluster size)
|
||||
constexpr int kAmThreads = 1024;
|
||||
#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 900
|
||||
#define STRATA_AM_CLUSTER 1
|
||||
#else
|
||||
#define STRATA_AM_CLUSTER 0 // older targets: a trap, never launched (sample_greedy_cluster checks)
|
||||
#endif
|
||||
#if STRATA_AM_CLUSTER
|
||||
__dpct_inline__ void am_take(float s, int v, float &bv, int &best) {
|
||||
if (s > bv) { bv = s; best = v; }
|
||||
}
|
||||
__dpct_inline__ void am_merge(float ov, int oi, float &bv, int &best) {
|
||||
if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
|
||||
}
|
||||
#endif
|
||||
// grid (kAmCtas, n_tokens), cluster (kAmCtas, 1, 1), kAmThreads threads
|
||||
void sampler_greedy_cluster_kernel(const float* __restrict__ logits,
|
||||
int n_vocab, int* __restrict__ out) {
|
||||
#if STRATA_AM_CLUSTER
|
||||
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
||||
auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
||||
auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
||||
auto &cv =
|
||||
*sycl::ext::oneapi::group_local_memory_for_overwrite<float[kAmCtas]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<
|
||||
3>()); // on CTA 0: each CTA's result
|
||||
auto &ci =
|
||||
*sycl::ext::oneapi::group_local_memory_for_overwrite<int[kAmCtas]>(
|
||||
sycl::ext::oneapi::this_work_item::get_work_group<3>());
|
||||
unsigned rank;
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(rank));
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
|
||||
const float *l = logits + (size_t)item_ct1.get_group(1) * n_vocab;
|
||||
float bv = sycl::bit_cast<float, int>(
|
||||
0xff800000); // -inf; `n_vocab` is "no candidate", as in
|
||||
// sampler_greedy_kernel
|
||||
int best = n_vocab;
|
||||
constexpr int S = kAmCtas * kAmThreads;
|
||||
int v = (int)rank * kAmThreads + (int)item_ct1.get_local_id(2);
|
||||
for (; v + 3 * S < n_vocab; v += 4 * S) { // four independent loads, then taken in ascending order
|
||||
const float x0 = l[v], x1 = l[v + S], x2 = l[v + 2 * S], x3 = l[v + 3 * S];
|
||||
am_take(x0, v, bv, best);
|
||||
am_take(x1, v + S, bv, best);
|
||||
am_take(x2, v + 2 * S, bv, best);
|
||||
am_take(x3, v + 3 * S, bv, best);
|
||||
}
|
||||
#pragma unroll
|
||||
for (; v < n_vocab; v += S) am_take(l[v], v, bv, best);
|
||||
#pragma unroll
|
||||
for (int off = 16; off > 0; off >>= 1)
|
||||
/*
|
||||
DPCT1108: '__shfl_down_sync' was migrated with the experimental
|
||||
feature masked sub_group function which may not be supported by all
|
||||
compilers or runtimes. You may need to adjust the code.
|
||||
*/
|
||||
am_merge(
|
||||
dpct::experimental::shift_sub_group_left(
|
||||
0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
|
||||
bv, off),
|
||||
dpct::experimental::shift_sub_group_left(
|
||||
0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
|
||||
best, off),
|
||||
bv, best);
|
||||
const int warp = (int)(item_ct1.get_local_id(2) >> 5),
|
||||
lane = (int)(item_ct1.get_local_id(2) & 31);
|
||||
if (lane == 0) { sv[warp] = bv; si[warp] = best; }
|
||||
item_ct1.barrier(sycl::access::fence_space::local_space);
|
||||
if (warp == 0) {
|
||||
bv = sv[lane];
|
||||
best = si[lane];
|
||||
#pragma unroll
|
||||
for (int off = 16; off > 0; off >>= 1)
|
||||
/*
|
||||
DPCT1108: '__shfl_down_sync' was migrated with the experimental
|
||||
feature masked sub_group function which may not be supported by all
|
||||
compilers or runtimes. You may need to adjust the code.
|
||||
*/
|
||||
am_merge(dpct::experimental::shift_sub_group_left(
|
||||
0xFFFFFFFFu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
|
||||
off),
|
||||
dpct::experimental::shift_sub_group_left(
|
||||
0xFFFFFFFFu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(),
|
||||
best, off),
|
||||
bv, best);
|
||||
}
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::
|
||||
: "memory"); // CTA 0 runs
|
||||
if (item_ct1.get_local_id(2) == 0) {
|
||||
uint64_t a;
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("mapa.u64 %0, %1, %2;\n"
|
||||
: "=l"(a)
|
||||
: "l"((uint64_t)&cv[rank]), "r"(0u));
|
||||
*reinterpret_cast<float*>(a) = bv;
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("mapa.u64 %0, %1, %2;\n"
|
||||
: "=l"(a)
|
||||
: "l"((uint64_t)&ci[rank]), "r"(0u));
|
||||
*reinterpret_cast<int*>(a) = best;
|
||||
}
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory");
|
||||
if (rank != 0) return;
|
||||
/*
|
||||
DPCT1053: Migration of device assembly code is not supported.
|
||||
*/
|
||||
asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory");
|
||||
if (warp == 0) {
|
||||
bv = lane < kAmCtas ? cv[lane] : sycl::bit_cast<float, int>(0xff800000);
|
||||
best = lane < kAmCtas ? ci[lane] : n_vocab;
|
||||
#pragma unroll
|
||||
for (int off = 16; off > 0; off >>= 1)
|
||||
/*
|
||||
DPCT1108: '__shfl_down_sync' was migrated with the experimental
|
||||
feature masked sub_group function which may not be supported by all
|
||||
compilers or runtimes. You may need to adjust the code.
|
||||
*/
|
||||
am_merge(dpct::experimental::shift_sub_group_left(
|
||||
0xFFFFFFFFu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
|
||||
off),
|
||||
dpct::experimental::shift_sub_group_left(
|
||||
0xFFFFFFFFu,
|
||||
sycl::ext::oneapi::this_work_item::get_sub_group(),
|
||||
best, off),
|
||||
bv, best);
|
||||
if (lane == 0) out[item_ct1.get_group(1)] = (best < n_vocab) ? best : 0;
|
||||
}
|
||||
#else
|
||||
(void) logits; (void) n_vocab; (void) out;
|
||||
__trap();
|
||||
#endif
|
||||
}
|
||||
#endif // !__HIPCC__
|
||||
|
||||
/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.** The kernel below replaced a version that ran the whole chain
|
||||
/// in ONE THREAD per token (`<<<ceil(T/64), 64>>>`, so a 4-token window fielded four threads): `top_k` alone
|
||||
/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320
|
||||
@@ -1129,9 +1300,9 @@ bool stream_capturing(void *stream) try {
|
||||
if (DPCT_CHECK_ERROR(
|
||||
(st = strata::q_of(stream)->ext_oneapi_get_state())) != 0) {
|
||||
/*
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use the
|
||||
error codes. The cudaGetLastError function call was replaced with 0. You
|
||||
need to rewrite this code.
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use
|
||||
the error codes. The cudaGetLastError function call was replaced with 0.
|
||||
You need to rewrite this code.
|
||||
*/
|
||||
(void)0;
|
||||
return true;
|
||||
@@ -1166,9 +1337,9 @@ sycl::int2 *split_scratch(void *stream, size_t entries) {
|
||||
int device = 0;
|
||||
if (DPCT_CHECK_ERROR(device = dpct::get_current_device_id()) != 0) {
|
||||
/*
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use the
|
||||
error codes. The cudaGetLastError function call was replaced with 0. You
|
||||
need to rewrite this code.
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use
|
||||
the error codes. The cudaGetLastError function call was replaced with 0.
|
||||
You need to rewrite this code.
|
||||
*/
|
||||
(void)0;
|
||||
return nullptr;
|
||||
@@ -1190,17 +1361,17 @@ sycl::int2 *split_scratch(void *stream, size_t entries) {
|
||||
if (DPCT_CHECK_ERROR(ptr = sycl::malloc_device<sycl::int2>(
|
||||
want, dpct::get_in_order_queue())) != 0) {
|
||||
/*
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use the
|
||||
error codes. The cudaGetLastError function call was replaced with 0. You
|
||||
need to rewrite this code.
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use
|
||||
the error codes. The cudaGetLastError function call was replaced with 0.
|
||||
You need to rewrite this code.
|
||||
*/
|
||||
(void)0;
|
||||
want = entries;
|
||||
if (DPCT_CHECK_ERROR(ptr = sycl::malloc_device<sycl::int2>(
|
||||
want, dpct::get_in_order_queue())) != 0) {
|
||||
/*
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use
|
||||
the error codes. The cudaGetLastError function call was replaced
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not
|
||||
use the error codes. The cudaGetLastError function call was replaced
|
||||
with 0. You need to rewrite this code.
|
||||
*/
|
||||
(void)0;
|
||||
@@ -1216,6 +1387,76 @@ sycl::int2 *split_scratch(void *stream, size_t entries) {
|
||||
|
||||
} // namespace
|
||||
|
||||
bool sample_greedy_cluster(const float *logits, int n_tokens, int n_vocab,
|
||||
int *out, void *stream) try {
|
||||
#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain greedy kernel
|
||||
(void) logits; (void) n_tokens; (void) n_vocab; (void) out; (void) stream;
|
||||
return false;
|
||||
#else
|
||||
if (n_tokens <= 0 || n_vocab <= 0) return true;
|
||||
if (n_tokens > 65535) return false;
|
||||
// Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not - sm_90+ (the card's,
|
||||
// or STRATA_EMULATE_CC's), code built for it (an older build's PTX holds a trap: the PTX version says which), and
|
||||
// room for one cluster of kAmCtas CTAs.
|
||||
static int ok[64] = {};
|
||||
int dev = 0;
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 || dev < 0 ||
|
||||
dev >= 64) {
|
||||
; return false;
|
||||
}
|
||||
cudaLaunchConfig_t cfg{};
|
||||
cudaLaunchAttribute at[1];
|
||||
at[0].id = cudaLaunchAttributeClusterDimension;
|
||||
at[0].val.clusterDim.x = kAmCtas;
|
||||
at[0].val.clusterDim.y = 1;
|
||||
at[0].val.clusterDim.z = 1;
|
||||
cfg.gridDim = dpct::dim3(kAmCtas, 1, 1);
|
||||
cfg.blockDim = dpct::dim3(kAmThreads, 1, 1);
|
||||
cfg.dynamicSmemBytes = 0;
|
||||
cfg.stream = strata::q_of(stream);
|
||||
cfg.attrs = at;
|
||||
cfg.numAttrs = 1;
|
||||
if (ok[dev] == 0) {
|
||||
int major = 0, clusters = 0;
|
||||
dpct::kernel_function_info fa{};
|
||||
const bool runs =
|
||||
DPCT_CHECK_ERROR(
|
||||
major = dpct::get_device(dev).get_major_version()) == 0 &&
|
||||
strata::cc_major_of(major) >= 9 &&
|
||||
DPCT_CHECK_ERROR(dpct::get_kernel_function_info(
|
||||
&fa, (const void *)sampler_greedy_cluster_kernel)) == 0 &&
|
||||
fa.ptxVersion >= 90 && fa.binaryVersion >= 90 &&
|
||||
/*
|
||||
DPCT1007: Migration of cudaOccupancyMaxActiveClusters is not
|
||||
supported.
|
||||
*/
|
||||
cudaOccupancyMaxActiveClusters(
|
||||
&clusters, sampler_greedy_cluster_kernel, &cfg) == 0 &&
|
||||
clusters >= 1;
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
ok[dev] = runs ? 1 : 2;
|
||||
}
|
||||
if (ok[dev] != 1) return false;
|
||||
cfg.gridDim = dpct::dim3(kAmCtas, (unsigned)n_tokens, 1);
|
||||
const dpct::err0 e = cudaLaunchKernelEx(&cfg, sampler_greedy_cluster_kernel,
|
||||
logits, n_vocab, out);
|
||||
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
catch (sycl::exception const &exc) {
|
||||
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
||||
<< ", line:" << __LINE__ << std::endl;
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
|
||||
const SamplerParams& p, int* out, void* stream) {
|
||||
if (n_tokens <= 0 || n_vocab <= 0) return;
|
||||
@@ -1235,13 +1476,21 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
|
||||
sizeof(unsigned) // the penalty bitmap
|
||||
: 0;
|
||||
if (p.greedy || p.temperature <= 0.0f) {
|
||||
// Without penalties (shmem == 0: no window) on sm_90+, a cluster of CTAs per token - the same token; see
|
||||
// `sampler_greedy_cluster_kernel`. STRATA_ARGMAX_MULTI=0: always the one-block kernel.
|
||||
static const bool multi = [] {
|
||||
const char* v = std::getenv("STRATA_ARGMAX_MULTI");
|
||||
return !v || std::atoi(v) != 0;
|
||||
}();
|
||||
// One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`.
|
||||
const int gthreads = 1024;
|
||||
/*
|
||||
DPCT1049: The work-group size passed to the SYCL kernel may exceed
|
||||
the limit. To get the device limit, query
|
||||
info::device::max_work_group_size. Adjust the work-group size if needed.
|
||||
*/
|
||||
if (!(multi && shmem == 0 && sample_greedy_cluster(logits, n_tokens, n_vocab, out, stream)))
|
||||
/*
|
||||
DPCT1049: The work-group size passed to the SYCL kernel may
|
||||
exceed the limit. To get the device limit, query
|
||||
info::device::max_work_group_size. Adjust the work-group size if
|
||||
needed.
|
||||
*/
|
||||
{
|
||||
auto exp_props = sycl::ext::oneapi::experimental::properties{
|
||||
sycl::ext::oneapi::experimental::use_root_sync};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp)
|
||||
// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model).
|
||||
//
|
||||
// Int8 and FP16 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051
|
||||
// Int8, FP16 and Q4_0 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051
|
||||
// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most
|
||||
// of them as they do in a real prompt; short contexts take every cell). Checks:
|
||||
// 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math);
|
||||
@@ -15,6 +15,7 @@
|
||||
#include "strata/kernels/qsa.hpp"
|
||||
#include "strata/kernels/qsa_decode_attn.hpp"
|
||||
#include "strata/kernels/qsa_prompt_attn.hpp"
|
||||
#include "strata/kernels/kv_q4.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -63,7 +64,7 @@ uint16_t f2h(float f) {
|
||||
return *reinterpret_cast<uint16_t *>(&h);
|
||||
}
|
||||
|
||||
int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 q4_0
|
||||
const k::QsaShapes s = k::qsa_real_shapes();
|
||||
const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
|
||||
const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
|
||||
@@ -74,7 +75,22 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
// pools; page table a shuffled permutation (the readers must follow it)
|
||||
std::vector<int8_t> kq, vq;
|
||||
std::vector<uint16_t> ks, vs, kh, vh;
|
||||
if (fmt == 1) {
|
||||
std::vector<uint8_t> k4, v4; // q4_0: 8 blocks of {fp16 d, 16 code bytes} per row (kv_q4.hpp)
|
||||
constexpr int64_t B4 = 18, ROW4 = 8 * B4;
|
||||
if (fmt == 2) {
|
||||
std::uniform_int_distribution<int> byte(0, 255);
|
||||
// the scales as a q4_0 pool holds them: signed (ggml's d = max / -8) and spread over two decades, so a chunk's
|
||||
// cells mix signs and magnitudes (a positive-only bound on them overflowed FP16 on real K/V)
|
||||
std::uniform_real_distribution<float> lg(std::log(0.01f), std::log(1.0f));
|
||||
auto sc4 = [&](std::mt19937& r) { return std::exp(lg(r)) * (byte(r) & 1 ? -1.0f : 1.0f); };
|
||||
k4.resize(rows * ROW4); v4.resize(rows * ROW4);
|
||||
for (auto* pool : {&k4, &v4})
|
||||
for (int64_t b = 0; b < rows * 8; ++b) {
|
||||
const uint16_t d = f2h(sc4(rng));
|
||||
std::memcpy(pool->data() + b * B4, &d, 2);
|
||||
for (int j = 0; j < 16; ++j) (*pool)[b * B4 + 2 + j] = (uint8_t) byte(rng);
|
||||
}
|
||||
} else if (fmt == 1) {
|
||||
kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4);
|
||||
for (auto& x : kq) x = (int8_t) code(rng);
|
||||
for (auto& x : vq) x = (int8_t) code(rng);
|
||||
@@ -122,8 +138,19 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
std::copy(v.begin(), v.end(), sel);
|
||||
}
|
||||
k::QsaAttnPools pl;
|
||||
if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
|
||||
if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); }
|
||||
else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
|
||||
else { pl.k_pool = up(kh); pl.v_pool = up(vh); }
|
||||
// a q4_0 value: block d / 32 of the row, element j = d % 32 in the low nibble of byte j (j < 16), else the high
|
||||
// nibble of byte j - 16, minus 8, times the block's scale
|
||||
auto q4v = [&](const std::vector<uint8_t>& pool, int64_t row, int64_t d) {
|
||||
const uint8_t* blk = pool.data() + row * ROW4 + (d / 32) * B4;
|
||||
uint16_t sc;
|
||||
std::memcpy(&sc, blk, 2);
|
||||
const int j = (int) (d % 32);
|
||||
const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4);
|
||||
return (double) (code - 8) * h2f(sc);
|
||||
};
|
||||
pl.page_table = up(table);
|
||||
const int32_t* d_ids = up(ids);
|
||||
const int32_t* d_steps = up(steps);
|
||||
@@ -178,7 +205,8 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
|
||||
double a = 0;
|
||||
for (int64_t d = 0; d < HD; ++d) {
|
||||
const double kv = fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]);
|
||||
const double kv = fmt == 2 ? q4v(k4, row, d)
|
||||
: fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]);
|
||||
a += (double) q[(i * NH + h) * HD + d] * kv;
|
||||
}
|
||||
sco[c] = a / 16.0;
|
||||
@@ -190,7 +218,8 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
double a = 0;
|
||||
for (int64_t c = 0; c < w; ++c) {
|
||||
const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
|
||||
const double vv = fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]);
|
||||
const double vv = fmt == 2 ? q4v(v4, row, d)
|
||||
: fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]);
|
||||
a += sco[c] * vv;
|
||||
}
|
||||
const double r = a / l;
|
||||
@@ -232,7 +261,7 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
const bool ok2 = diff <= 1e-4 * scale;
|
||||
std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of "
|
||||
"scale); %.3f -> %.3f ms per chunk (%.2fx)\n",
|
||||
ok1 && ok2 ? "PASS" : "FAIL", fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,
|
||||
ok1 && ok2 ? "PASS" : "FAIL", fmt == 2 ? "q4_0" : fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,
|
||||
err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new);
|
||||
sycl::free((void *)d_ids, dpct::get_in_order_queue());
|
||||
sycl::free((void *)d_steps, dpct::get_in_order_queue());
|
||||
@@ -247,6 +276,8 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
|
||||
sycl::free((void *)pl.k_pool, dpct::get_in_order_queue());
|
||||
sycl::free((void *)pl.v_pool, dpct::get_in_order_queue());
|
||||
sycl::free((void *)pl.page_table, dpct::get_in_order_queue());
|
||||
sycl::free((void *)pl.k_q4, dpct::get_in_order_queue());
|
||||
sycl::free((void *)pl.v_q4, dpct::get_in_order_queue());
|
||||
return ok1 && ok2 ? 0 : 1;
|
||||
}
|
||||
} // namespace
|
||||
@@ -277,6 +308,8 @@ int main(int argc, char** argv) {
|
||||
fails += run(1, ctx, nq, reps);
|
||||
#if !defined(__HIP_PLATFORM_AMD__)
|
||||
fails += run(0, ctx, nq, reps); // FP16 KV: the RDNA4 kernel takes int8 KV only
|
||||
fails += run(2, ctx, nq, reps); // Q4_0 KV (mode 4)
|
||||
fails += run(2, 1500, std::min<int64_t>(nq, 1500), reps);
|
||||
#endif
|
||||
fails += run(1, 1500, std::min<int64_t>(nq, 1500), reps); // short context: the selection is every cell
|
||||
fails += run(1, 2100, std::min<int64_t>(nq, 256), reps); // the identity-to-sparse edge
|
||||
|
||||
@@ -774,7 +774,7 @@ __dpct_inline__ void gdn_rec_cols_pipe_kernel(float *__restrict__ state,
|
||||
// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro
|
||||
// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same
|
||||
// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).
|
||||
// sm_80+ with 32 to 47 or 64 and more SMs (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
|
||||
// sm_80+ cards that hold its 64 blocks at once (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
|
||||
#if 1 // SYCL port: plain copies (no cp.async)
|
||||
#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)
|
||||
#else
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// src/prefill/moe_fused_stub.cpp (SYCL port) - upstream's fused int8 prompt kernels (moe_fused.cu, moe_fused_iq.cu, #136)
|
||||
// belong to its MMQ library, which this build does not have (the prompt path's MMQ plan is empty here, so prefill.cpp
|
||||
// never takes the fused branch). These are the "not built" answers, so the prompt path links and keeps its own path.
|
||||
#include "strata/prefill/moe_fused.hpp"
|
||||
#include "strata/prefill/moe_fused_iq.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace strata::prefill::fused {
|
||||
|
||||
namespace {
|
||||
[[noreturn]] void unreachable(const char* what) {
|
||||
std::fprintf(stderr, "prefill: %s called in a build without the fused kernels\n", what);
|
||||
std::abort();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool built() { return false; }
|
||||
bool available() { return false; }
|
||||
bool enabled() { return false; }
|
||||
bool requested() { return false; }
|
||||
size_t act_bytes(int64_t, int64_t) { return 0; }
|
||||
size_t group_bytes(int64_t, int) { return 0; }
|
||||
void quantize_act(const float*, int64_t, int64_t, void*, void*) { unreachable("fused::quantize_act"); }
|
||||
void group(const int32_t*, int64_t, int, int, void*, int32_t*, int32_t*, void*) { unreachable("fused::group"); }
|
||||
void experts(const Batch&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {
|
||||
unreachable("fused::experts");
|
||||
}
|
||||
bool native_supported(int, int) { return false; }
|
||||
void quantize_act_native(const float*, int64_t, int64_t, void*, void*) { unreachable("fused::quantize_act_native"); }
|
||||
void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, float*,
|
||||
void*) {
|
||||
unreachable("fused::experts_native");
|
||||
}
|
||||
|
||||
} // namespace strata::prefill::fused
|
||||
+1292
-309
File diff suppressed because it is too large.
Load diff
+468
-124
@@ -1,18 +1,25 @@
|
||||
#define DPCT_COMPAT_RT_VERSION 12080
|
||||
// src/program/generate.cpp - P2.S6: `strata generate`.
|
||||
//
|
||||
// THE DRIVER, and the first program in this project that answers a question. Everything below it is a
|
||||
// component; this is the thing that composes them into a token:
|
||||
// THE DRIVER, and the first program in this project that answers a question.
|
||||
// Everything below it is a component; this is the thing that composes them into
|
||||
// a token:
|
||||
//
|
||||
// embed_row(token) -> 48 captured layer graphs (the CPU expert pool behind the doorbell) ->
|
||||
// lm_head(R) -> sample -> embed_row(next) -> ...
|
||||
// embed_row(token) -> 48 captured layer graphs (the CPU expert pool
|
||||
// behind the doorbell) -> lm_head(R) -> sample ->
|
||||
// embed_row(next) -> ...
|
||||
//
|
||||
// WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and `tools/strata_tokenizer.py` exist,
|
||||
// and a C++ BPE is Phase 1's deliverable rather than this program's, so the prompt arrives as IDS via
|
||||
// `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs, because C1 compares logits against
|
||||
// llama.cpp on the SAME ids, and a tokenizer on only one side of that comparison is a second variable.
|
||||
// WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and
|
||||
// `tools/strata_tokenizer.py` exist, and a C++ BPE is Phase 1's deliverable
|
||||
// rather than this program's, so the prompt arrives as IDS via
|
||||
// `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs,
|
||||
// because C1 compares logits against llama.cpp on the SAME ids, and a tokenizer
|
||||
// on only one side of that comparison is a second variable.
|
||||
//
|
||||
// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose
|
||||
// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump.
|
||||
// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on
|
||||
// purpose
|
||||
// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure
|
||||
// and the logit dump.
|
||||
|
||||
#define DPCT_PROFILING_ENABLED
|
||||
#include <sycl/sycl.hpp>
|
||||
@@ -29,6 +36,7 @@
|
||||
#include "strata/core/pinned.hpp"
|
||||
#include "strata/core/remote_experts.hpp"
|
||||
#include "strata/core/on_device.hpp"
|
||||
#include "strata/core/peer_experts.hpp"
|
||||
#include "strata/core/layer.hpp"
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/core/session.hpp"
|
||||
@@ -81,6 +89,7 @@
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <future>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
@@ -314,6 +323,16 @@ struct Options {
|
||||
/// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and
|
||||
/// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default.
|
||||
bool expert_cache_per_layer = false;
|
||||
/// Multi-GPU: a second expert tier on CUDA device `peer_device` (-1 = off), `peer_reserve_mib` left free
|
||||
/// there, `peer_slots` caps its size (0 = as many as fit), `peer_adapt_swaps` per adaptive round
|
||||
/// (-1 = adapt_swaps).
|
||||
int peer_device = -1;
|
||||
int peer_reserve_mib = 600;
|
||||
int64_t peer_slots = 0;
|
||||
int peer_adapt_swaps = -1;
|
||||
/// the prompt path's rows per layer the peer computes: -1 = half of chunk x top-k, 0 = the prompt path stays on
|
||||
/// the primary
|
||||
int64_t peer_prefill_rows = -1;
|
||||
/// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen
|
||||
/// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`.
|
||||
bool no_ple_prefetch = false;
|
||||
@@ -322,6 +341,11 @@ struct Options {
|
||||
/// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills
|
||||
/// with whatever the prompt touched FIRST. Empty means no profile.
|
||||
std::string expert_profile;
|
||||
/// #477 (--serve, opt-in): where to save what the adaptive tier learned, as a profile `--expert-profile` reads
|
||||
/// (the resident experts first, then the routing counted since the start); on QUIT and every
|
||||
/// `expert_profile_save_min` minutes between requests. Empty (the default): nothing is counted or written.
|
||||
std::string expert_profile_save;
|
||||
double expert_profile_save_min = 10.0;
|
||||
/// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken.
|
||||
/// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The
|
||||
/// A/B arm is `--no-hit-poke`.
|
||||
@@ -341,6 +365,7 @@ struct Options {
|
||||
/// Plan v0.3 P4: `--expert-cache auto` sizes the VRAM tier from what is free after the weights, the session
|
||||
/// and the KV state, minus this reserve for the graphs, the hit scratch and the head.
|
||||
int vram_reserve_mib = 700;
|
||||
bool vram_reserve_given = false; ///< --vram-reserve-mib on the command line (#496: no smaller automatic reserve)
|
||||
/// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path).
|
||||
int64_t prefill_chunk = 0;
|
||||
/// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk
|
||||
@@ -377,10 +402,6 @@ struct Options {
|
||||
/// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency.
|
||||
int adapt_every = 4;
|
||||
float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay)
|
||||
/// --adapt-tuned (STRATA_ADAPT_TUNED=1): every 2 rounds, up to 192 swaps, x0.92 - where that was measured to help
|
||||
/// (see where it is applied); explicit --adapt-* flags win
|
||||
bool adapt_tuned = false;
|
||||
bool adapt_given = false;
|
||||
/// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least
|
||||
/// this probability under the draft layer; 0 = always --spec-1 drafts.
|
||||
double spec_min_p = 0.0;
|
||||
@@ -554,6 +575,10 @@ void usage() {
|
||||
" real graph that --stage-timing cannot give. Prints and exits.\n"
|
||||
" --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n"
|
||||
" tools/make_profile.py) instead of admitting on first use.\n"
|
||||
" --expert-profile-save P --serve, #477: save what the adaptive tier learned (the experts in\n"
|
||||
" VRAM, then the routing counted since the start) as a profile at P, on\n"
|
||||
" QUIT and every --expert-profile-save-every MIN minutes (default 10;\n"
|
||||
" 0 = on QUIT only) between requests; start from it with --expert-profile P\n"
|
||||
" --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n"
|
||||
" launch so the GPU starts while the CPU pool runs; without it the work\n"
|
||||
" waits for the next driver entry and does not overlap at all.\n"
|
||||
@@ -568,6 +593,14 @@ void usage() {
|
||||
" --expert-cache-device3 N pre-fill N more experts on CUDA3\n"
|
||||
" --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n"
|
||||
" layers across CUDA1..3 (default: stripe)\n"
|
||||
" --peer-device N a second GPU as an adaptive expert-cache tier (rows over P2P; it also\n"
|
||||
" computes its experts' prompt rows). Not with --layer-split or\n"
|
||||
" --expert-cache-device1..3. Default output unchanged without it.\n"
|
||||
" --peer-reserve-mib N VRAM the peer tier leaves free on its card (default 600)\n"
|
||||
" --peer-slots N expert slots on the peer (default: what fits)\n"
|
||||
" --peer-adapt-swaps N peer cache swaps per adaptation step (default: --adapt-swaps)\n"
|
||||
" --peer-prefill-rows N prompt rows per layer the peer computes (default half of chunk x top-k;\n"
|
||||
" 0 = the prompt path stays on the primary)\n"
|
||||
" --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n"
|
||||
" position take all of them. The default policy fills in arrival order\n"
|
||||
" from one shared counter, so 256 slots went to ~26 layers of position 0\n"
|
||||
@@ -846,6 +879,12 @@ void mem_mark(const char* where) {
|
||||
std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where);
|
||||
}
|
||||
|
||||
/// #463's A/B: STRATA_ADAPT_NOWAIT=1 lets a verify window start before the adaptive tier's copies have landed (0.1.37)
|
||||
bool adapt_nowait() {
|
||||
static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_NOWAIT"); return e && e[0] == '1'; }();
|
||||
return v;
|
||||
}
|
||||
|
||||
int argmax(const std::vector<float>& v) {
|
||||
int best = 0;
|
||||
for (size_t i = 1; i < v.size(); ++i)
|
||||
@@ -978,18 +1017,22 @@ bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g
|
||||
// The effective host->device bandwidth of the PCIe link: copies from pinned host memory, as the expert arena's
|
||||
// reads are. The native default share (0.55) was measured on x16 links (~26-28 GB/s); a x8 card in a x8 slot
|
||||
// carries about half of that. Returns < 0 when the probe cannot run (then the caller keeps the default).
|
||||
double probe_pcie_h2d_gbps() try {
|
||||
//
|
||||
// #485: a single timed burst read an x16 PCIe 4 link (RTX A3000 laptop) at 18.5, 6.9 and 5.8 GB/s in three starts -
|
||||
// a link still in a low-power state, other DMA, a context not yet up to speed - and the low reading set the share.
|
||||
// Such a disturbance only ever slows a copy: nothing makes a correctly timed copy faster than the link carries. So
|
||||
// the same 1 GiB is now copied as four bursts of 256 MiB, timed one by one, and the fastest is the link's figure (the
|
||||
// median would still follow a disturbance that lasts through half the bursts). Each burst takes ~10 ms on an x16
|
||||
// PCIe 4 link, so the probe takes no longer than the one 1 GiB burst did. `samples`, when given, gets every
|
||||
// burst's reading for the log.
|
||||
double probe_pcie_h2d_gbps(std::string *samples = nullptr) try {
|
||||
constexpr size_t kBytes = 256ull << 20;
|
||||
constexpr int kIters = 4;
|
||||
constexpr int kBursts = 4;
|
||||
void* h = nullptr;
|
||||
void* d = nullptr;
|
||||
dpct::event_ptr ev0, ev1;
|
||||
if (DPCT_CHECK_ERROR(h = (void *)malloc(kBytes)) != 0) return -1.0;
|
||||
if (DPCT_CHECK_ERROR(d = (void *)sycl::malloc_device(
|
||||
kBytes, dpct::get_in_order_queue())) != 0 ||
|
||||
DPCT_CHECK_ERROR(ev0 = new sycl::event()) != 0 ||
|
||||
DPCT_CHECK_ERROR(ev1 = new sycl::event()) != 0) {
|
||||
if (d != nullptr) sycl::free(d, dpct::get_in_order_queue());
|
||||
kBytes, dpct::get_in_order_queue())) != 0) {
|
||||
free(h);
|
||||
return -1.0;
|
||||
}
|
||||
@@ -1002,30 +1045,68 @@ double probe_pcie_h2d_gbps() try {
|
||||
*/
|
||||
dpct::get_in_order_queue().memcpy(
|
||||
d, h, kBytes).wait(); // warmup: context up, copy engine primed
|
||||
dpct::sync_barrier(ev0);
|
||||
float ms[kBursts] = {};
|
||||
#if defined(STRATA_USE_HIP) && defined(_WIN32)
|
||||
// Windows HIP: the events do not bracket the copies there (an RX 6800 read 3,300-26,000 GB/s, so every link kept
|
||||
// the x16 share), so each burst is timed on the host between two synchronizes: 256 MiB takes ~10 ms, so the
|
||||
// synchronize around it hardly matters
|
||||
bool ok = cudaDeviceSynchronize() == cudaSuccess;
|
||||
for (int b = 0; b < kBursts && ok; ++b) {
|
||||
const Clock::time_point t0 = Clock::now();
|
||||
cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice);
|
||||
ok = cudaDeviceSynchronize() == cudaSuccess;
|
||||
ms[b] = (float) std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
||||
}
|
||||
#else
|
||||
// the bursts run back to back on the stream, an event between each two
|
||||
dpct::event_ptr ev[kBursts + 1];
|
||||
int n_ev = 0;
|
||||
while (n_ev <= kBursts &&
|
||||
DPCT_CHECK_ERROR(ev[n_ev] = new sycl::event()) == 0)++ n_ev;
|
||||
bool ok = n_ev == kBursts + 1;
|
||||
if (ok) {
|
||||
dpct::sync_barrier(ev[0]);
|
||||
for (int b = 0; b < kBursts; ++b) {
|
||||
/*
|
||||
DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
|
||||
API. While the origin API might be synchronous, it depends on the
|
||||
type of operand memory, so you may need to call wait() on event
|
||||
return by memcpy API to ensure synchronization behavior.
|
||||
*/
|
||||
dpct::get_in_order_queue().memcpy(d, h, kBytes).wait();
|
||||
dpct::sync_barrier(ev[b + 1]);
|
||||
}
|
||||
ok = DPCT_CHECK_ERROR(ev[kBursts]->wait_and_throw()) == 0;
|
||||
for (int b = 0; b < kBursts && ok; ++b) ok =
|
||||
DPCT_CHECK_ERROR(
|
||||
ms[b] =
|
||||
(ev[b + 1]
|
||||
->get_profiling_info<
|
||||
sycl::info::event_profiling::command_end>() -
|
||||
ev[b]
|
||||
->get_profiling_info<
|
||||
sycl::info::event_profiling::command_start>()) /
|
||||
1000000.0f) == 0;
|
||||
}
|
||||
for (int i = 0; i < n_ev; ++i) dpct::destroy_event(ev[i]);
|
||||
#endif
|
||||
double bw = -1.0;
|
||||
if (samples != nullptr) samples->clear();
|
||||
for (int b = 0; b < kBursts && ok; ++b) {
|
||||
const double s = ms[b] > 0.01f ? (double) kBytes / (ms[b] * 1e-3) / 1e9 : -1.0;
|
||||
bw = std::max(bw, s);
|
||||
if (samples != nullptr) {
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "%s%.1f", b == 0 ? "" : " ", s);
|
||||
*samples += buf;
|
||||
}
|
||||
}
|
||||
/*
|
||||
DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
|
||||
the origin API might be synchronous, it depends on the type of operand
|
||||
memory, so you may need to call wait() on event return by memcpy API to
|
||||
ensure synchronization behavior.
|
||||
DPCT1010: SYCL uses exceptions to report errors and does not use the
|
||||
error codes. The cudaGetLastError function call was replaced with 0. You
|
||||
need to rewrite this code.
|
||||
*/
|
||||
for (int i = 0; i < kIters; ++i) dpct::get_in_order_queue().memcpy(d, h,
|
||||
kBytes).wait();
|
||||
dpct::sync_barrier(ev1);
|
||||
const bool ok = DPCT_CHECK_ERROR(ev1->wait_and_throw()) == 0;
|
||||
float ms = 0.f;
|
||||
const bool timed =
|
||||
ok &&
|
||||
DPCT_CHECK_ERROR(
|
||||
ms = (ev1->get_profiling_info<
|
||||
sycl::info::event_profiling::command_end>() -
|
||||
ev0->get_profiling_info<
|
||||
sycl::info::event_profiling::command_start>()) /
|
||||
1000000.0f) == 0 &&
|
||||
ms > 0.01f;
|
||||
const double bw = timed ? ((double) kIters * (double) kBytes / (ms * 1e-3)) / 1e9 : -1.0;
|
||||
dpct::destroy_event(ev0);
|
||||
dpct::destroy_event(ev1);
|
||||
if (!ok)(void) 0;
|
||||
sycl::free(d, dpct::get_in_order_queue());
|
||||
free(h);
|
||||
return bw;
|
||||
@@ -1036,6 +1117,15 @@ catch (sycl::exception const &exc) {
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
// The PCIe share of the missed experts for a link measured at `gbps`: `base` (the share measured on x16 links) from
|
||||
// 20 GB/s up, and below that in proportion to the bandwidth, so the time the link spends on its share stays about
|
||||
// what the x16 share costs. Continuous (#485): before, 19.9 GB/s gave 0.42 and 20.0 the full 0.55 (and 4.0 GB/s
|
||||
// gave 0.08, 3.9 none), so a reading near either edge moved the share by a quarter of its range. From 20 GB/s up
|
||||
// (an x16 PCIe 4/5 link: ~26-28 GB/s) the share is unchanged.
|
||||
double pcie_frac_for_gbps(double gbps, double base) {
|
||||
return gbps <= 0.0 ? base : base * std::min(1.0, gbps / 20.0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) try {
|
||||
@@ -1176,7 +1266,7 @@ int main(int argc, char **argv) try {
|
||||
else if (a == "--expert-cache-device3") o.expert_cache_remote[2] = std::atoi(next("--expert-cache-device3"));
|
||||
else if (a == "--expert-cache-remote-placement")
|
||||
o.expert_cache_remote_placement = next("--expert-cache-remote-placement");
|
||||
else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib"));
|
||||
else if (a == "--vram-reserve-mib") { o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); o.vram_reserve_given = true; }
|
||||
else if (a == "--prefill") {
|
||||
const std::string v = next("--prefill");
|
||||
o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0;
|
||||
@@ -1198,9 +1288,8 @@ int main(int argc, char **argv) try {
|
||||
else if (a == "--mtp") o.mtp = next("--mtp");
|
||||
else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));
|
||||
else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac"));
|
||||
else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_given = true; }
|
||||
else if (a == "--adapt-decay") { o.adapt_decay = (float) std::atof(next("--adapt-decay")); o.adapt_given = true; }
|
||||
else if (a == "--adapt-tuned") o.adapt_tuned = true;
|
||||
else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every"));
|
||||
else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay"));
|
||||
else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p"));
|
||||
else if (a == "--stop-eos") o.stop_eos = true;
|
||||
else if (a == "--spec-split") o.spec_split = true;
|
||||
@@ -1269,11 +1358,19 @@ int main(int argc, char **argv) try {
|
||||
if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; }
|
||||
o.stop_eos = true;
|
||||
}
|
||||
else if (a == "--adapt-swaps") { o.adapt_swaps = std::atoi(next("--adapt-swaps")); o.adapt_given = true; }
|
||||
else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps"));
|
||||
else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true;
|
||||
else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true;
|
||||
else if (a == "--peer-device") o.peer_device = std::atoi(next("--peer-device"));
|
||||
else if (a == "--peer-reserve-mib") o.peer_reserve_mib = std::atoi(next("--peer-reserve-mib"));
|
||||
else if (a == "--peer-slots") o.peer_slots = std::atoll(next("--peer-slots"));
|
||||
else if (a == "--peer-adapt-swaps") o.peer_adapt_swaps = std::atoi(next("--peer-adapt-swaps"));
|
||||
else if (a == "--peer-prefill-rows") o.peer_prefill_rows = std::atoll(next("--peer-prefill-rows"));
|
||||
else if (a == "--no-hit-poke") o.no_hit_poke = true;
|
||||
else if (a == "--expert-profile") o.expert_profile = next("--expert-profile");
|
||||
else if (a == "--expert-profile-save") o.expert_profile_save = next("--expert-profile-save");
|
||||
else if (a == "--expert-profile-save-every")
|
||||
o.expert_profile_save_min = std::atof(next("--expert-profile-save-every"));
|
||||
else if (a == "--gpu-stages") o.gpu_stages = true;
|
||||
else if (a == "--mmap-experts") o.mmap_experts = true;
|
||||
else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena");
|
||||
@@ -1319,6 +1416,7 @@ int main(int argc, char **argv) try {
|
||||
}
|
||||
}
|
||||
strata::core::set_coupled_draft(o.coupled_draft);
|
||||
strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation)
|
||||
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");
|
||||
@@ -1330,6 +1428,8 @@ int main(int argc, char **argv) try {
|
||||
// the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). Across
|
||||
// GPUs, not yet: KV streaming, images, control vectors, the helper caches (--expert-cache-remote), and lending
|
||||
// cache slots to the prompt path (each stage's prompt path has its own buffers).
|
||||
// --pcie-frac given: that one share is every stage's (the stages' own link probes are skipped), so a split over
|
||||
// a fast and a slow link cannot set the two apart from the command line (#485)
|
||||
const bool pcie_given = o.pcie_frac >= 0.0;
|
||||
std::vector<int64_t> split_at;
|
||||
std::vector<int> split_devs;
|
||||
@@ -1708,6 +1808,14 @@ int main(int argc, char **argv) try {
|
||||
std::fprintf(stderr, "strata generate: --expert-cache-remote-placement must be stripe or layer\n");
|
||||
return 2;
|
||||
}
|
||||
// the peer tier is the second card's only user: a layer split or a remote expert cache would put a second engine
|
||||
// part (and a second copy of the same experts) on it
|
||||
if (o.peer_device >= 1 && (!o.layer_split.empty() || o.expert_cache_remote[0] > 0)) {
|
||||
std::fprintf(stderr, "strata generate: --peer-device cannot be combined with %s\n",
|
||||
!o.layer_split.empty() ? "--layer-split (use one or the other)"
|
||||
: "--expert-cache-device1..3 (the peer tier already caches experts there)");
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (o.native_flash_attn_short && o.max_context > 256) {
|
||||
std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n");
|
||||
@@ -1810,15 +1918,14 @@ int main(int argc, char **argv) try {
|
||||
// pack's 0.2 was never measured against the link, so it is left alone. `--calibrate` measures it outright.
|
||||
if (o.pcie_frac < 0.0) {
|
||||
const double base = native_pack ? 0.55 : 0.2;
|
||||
const double bw = native_pack ? probe_pcie_h2d_gbps() : -1.0;
|
||||
std::string bursts;
|
||||
const double bw = native_pack ? probe_pcie_h2d_gbps(&bursts) : -1.0;
|
||||
if (!native_pack) {
|
||||
o.pcie_frac = base;
|
||||
} else if (bw > 0.0) {
|
||||
// below ~4 GB/s (an x1 link: ~0.9 GB/s) a missed expert's 1.4 MB takes longer to cross than the CPU
|
||||
// pool takes to compute it, so none of them go over the link
|
||||
o.pcie_frac = bw >= 20.0 ? base : bw < 4.0 ? 0.0 : std::min(base, std::max(0.05, base * (bw / 26.0)));
|
||||
std::fprintf(stderr, "strata generate: PCIe probe: %.1f GB/s host->device -> pcie_frac %.2f (default %.2f)\n",
|
||||
bw, o.pcie_frac, base);
|
||||
o.pcie_frac = pcie_frac_for_gbps(bw, base);
|
||||
std::fprintf(stderr, "strata generate: PCIe probe: %.1f GB/s host->device (best of %s) -> pcie_frac %.2f "
|
||||
"(default %.2f)\n", bw, bursts.c_str(), o.pcie_frac, base);
|
||||
} else {
|
||||
o.pcie_frac = base;
|
||||
std::fprintf(stderr, "strata generate: PCIe probe failed -> pcie_frac default %.2f\n", base);
|
||||
@@ -1978,10 +2085,47 @@ int main(int argc, char **argv) try {
|
||||
return 1;
|
||||
}
|
||||
void* arena = nullptr;
|
||||
if (DPCT_CHECK_ERROR(arena = (void *)sycl::malloc_device(
|
||||
pool_bytes, dpct::get_in_order_queue())) != 0) {
|
||||
std::fprintf(stderr, "strata generate: cudaMalloc(%llu) for the weight arena failed\n",
|
||||
(unsigned long long) pool_bytes);
|
||||
/*
|
||||
DPCT1000: Error handling if-stmt was detected but could not be
|
||||
rewritten.
|
||||
*/
|
||||
if (const dpct::err0 ce =
|
||||
DPCT_CHECK_ERROR(arena = (void *)sycl::malloc_device(
|
||||
pool_bytes, dpct::get_in_order_queue()));
|
||||
ce != 0) {
|
||||
// #486: the arena is the first large allocation and its size does not depend on the context, so what is
|
||||
// missing is held by something else: say how much was free
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
/*
|
||||
DPCT1001: The statement could not be removed.
|
||||
*/
|
||||
size_t free_b = 0, total_b = 0;
|
||||
/*
|
||||
DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
|
||||
for device information which may not be supported by all compilers or
|
||||
runtimes. You may need to adjust the code.
|
||||
*/
|
||||
dpct::get_current_device().get_memory_info(free_b, total_b);
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"strata generate: cudaMalloc(%llu) for the weight arena failed "
|
||||
"(%s): %llu MiB of %llu "
|
||||
"MiB VRAM free on this GPU. The arena is allocated first, before "
|
||||
"the KV and expert "
|
||||
"caches: another program (or an engine that is still exiting) "
|
||||
"holds the rest - "
|
||||
"nvidia-smi / rocm-smi lists them\n",
|
||||
/*
|
||||
DPCT1009: SYCL reports errors using exceptions and does not use
|
||||
error codes. Please replace the "get_error_string_dummy(...)" with a
|
||||
real error-handling function.
|
||||
*/
|
||||
(unsigned long long)pool_bytes, dpct::get_error_string_dummy(ce),
|
||||
(unsigned long long)(free_b >> 20),
|
||||
(unsigned long long)(total_b >> 20));
|
||||
return 1;
|
||||
}
|
||||
strata::core::WeightTable wt;
|
||||
@@ -2335,8 +2479,22 @@ int main(int argc, char **argv) try {
|
||||
0 ||
|
||||
!st.wt.load(o.pack, arena_s, pool_bytes, err,
|
||||
skip.empty() ? nullptr : &skip)) {
|
||||
std::fprintf(stderr, "strata generate: layer split, CUDA%d weights: %s\n", st.dev,
|
||||
err.empty() ? "the weight arena does not fit" : err.c_str());
|
||||
/*
|
||||
DPCT1026: The call to cudaGetLastError was removed because this
|
||||
functionality is redundant in SYCL.
|
||||
*/
|
||||
size_t free_b = 0, total_b = 0; // #486: what that card had free
|
||||
/*
|
||||
DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
|
||||
extensions for device information which may not be supported by all
|
||||
compilers or runtimes. You may need to adjust the code.
|
||||
*/
|
||||
dpct::get_current_device().get_memory_info(free_b, total_b);
|
||||
std::fprintf(stderr, "strata generate: layer split, CUDA%d weights: %s (%llu MiB needed, %llu MiB of %llu "
|
||||
"MiB free on that card)\n", st.dev,
|
||||
err.empty() ? "the weight arena does not fit" : err.c_str(),
|
||||
(unsigned long long) (pool_bytes >> 20), (unsigned long long) (free_b >> 20),
|
||||
(unsigned long long) (total_b >> 20));
|
||||
return 1;
|
||||
}
|
||||
if (!o.native_dense_gguf.empty() && !st.dense.load(o.native_dense_gguf, st.wt, err, o.native_ple_key)) {
|
||||
@@ -2390,13 +2548,15 @@ int main(int argc, char **argv) try {
|
||||
}
|
||||
strata::kernels::mrope_table_set(st.mrope);
|
||||
}
|
||||
// its own PCIe share of the missed experts (the same rule as CUDA0's above: its link is probed)
|
||||
// its own PCIe share of the missed experts (the same rule as CUDA0's above: its link is probed). A given
|
||||
// --pcie-frac is every stage's share and skips these probes (pcie_given); there is no per-stage setting yet.
|
||||
st.pcie_frac = o.pcie_frac;
|
||||
if (!pcie_given && native_pack) {
|
||||
const double bw = probe_pcie_h2d_gbps();
|
||||
if (bw > 0.0) st.pcie_frac = bw >= 20.0 ? 0.55 : bw < 4.0 ? 0.0 : std::min(0.55, std::max(0.05, 0.55 * (bw / 26.0)));
|
||||
std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s -> pcie_frac %.2f\n", st.dev,
|
||||
bw, st.pcie_frac);
|
||||
std::string bursts;
|
||||
const double bw = probe_pcie_h2d_gbps(&bursts);
|
||||
if (bw > 0.0) st.pcie_frac = pcie_frac_for_gbps(bw, 0.55);
|
||||
std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s (best of %s) -> pcie_frac "
|
||||
"%.2f\n", st.dev, bw, bursts.c_str(), st.pcie_frac);
|
||||
}
|
||||
size_t fb = 0, tb = 0;
|
||||
/*
|
||||
@@ -2421,9 +2581,43 @@ int main(int argc, char **argv) try {
|
||||
// file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks
|
||||
// every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto.
|
||||
if (o.expert_cache == 0) o.expert_cache = -1;
|
||||
// Multi-GPU: STRATA_PEER_HOT=<f> gives the peer card a share f of the HOT pairs, so both cards
|
||||
// compute routed experts every layer (the primary alone did ~25 of ~30 per layer-window). Of the first
|
||||
// STRATA_PEER_HOT_AT (default 8700, ~ the primary's slots) ranks, every pair with floor((r+1)f) > floor(rf)
|
||||
// moves to just after that point: the primary fills past them, the peer (which takes what the primary does
|
||||
// not hold, in order) gets them first.
|
||||
if (o.peer_device >= 1) { // default 0.45 (measured: 0.3-0.6 all better than 0; 0 = off, e.g. for the gate)
|
||||
const char* ph = std::getenv("STRATA_PEER_HOT");
|
||||
const double f = ph ? std::atof(ph) : 0.45;
|
||||
const char* pa = std::getenv("STRATA_PEER_HOT_AT");
|
||||
const size_t at = std::min(profile.size(), (size_t) (pa ? std::atoll(pa) : 8700));
|
||||
if (f > 0.0 && f < 1.0 && at > 0) {
|
||||
std::vector<std::pair<int32_t, int32_t>> keep, moved;
|
||||
for (size_t r = 0; r < at; ++r) {
|
||||
const bool to_peer = (int64_t) ((double) (r + 1) * f) > (int64_t) ((double) r * f);
|
||||
(to_peer ? moved : keep).push_back(profile[r]);
|
||||
}
|
||||
const size_t n_moved = moved.size();
|
||||
// the primary's share continues with the ranks after `at` until it is full; then the moved ones
|
||||
std::vector<std::pair<int32_t, int32_t>> out;
|
||||
out.reserve(profile.size());
|
||||
out.insert(out.end(), keep.begin(), keep.end());
|
||||
const size_t fill = std::min(profile.size(), at + n_moved); // what the primary still takes
|
||||
out.insert(out.end(), profile.begin() + (long) at, profile.begin() + (long) fill);
|
||||
out.insert(out.end(), moved.begin(), moved.end());
|
||||
out.insert(out.end(), profile.begin() + (long) fill, profile.end());
|
||||
profile.swap(out);
|
||||
std::fprintf(stderr, "strata generate: STRATA_PEER_HOT %.2f: %zu of the first %zu ranked pairs moved "
|
||||
"behind rank %zu (the peer's)\n", f, n_moved, at, fill);
|
||||
}
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n",
|
||||
o.expert_profile.c_str(), profile.size(), (long long) pslots);
|
||||
}
|
||||
// #477: the whole ranking as loaded, the prior of --expert-profile-save's order (a layer split keeps only
|
||||
// CUDA0's pairs in `profile` below). Empty without --expert-profile-save.
|
||||
std::vector<std::pair<int32_t, int32_t>> profile_loaded;
|
||||
if (!o.expert_profile_save.empty()) profile_loaded = profile;
|
||||
// ---- layer split across GPUs: "auto" places the split points by a cost model of one decode window, measured on
|
||||
// the 5080 + 3090 rig (bench/results/2026-09-29-layer-split):
|
||||
// - every layer costs its GPU a time inversely proportional to SMs x clock (0.33 ms on an RTX 5080, 0.50 on a
|
||||
@@ -2779,6 +2973,29 @@ int main(int argc, char **argv) try {
|
||||
strata::emulated_cc()
|
||||
? " (STRATA_EMULATE_CC: a test mode, the card is emulated)"
|
||||
: "");
|
||||
{ // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that
|
||||
// CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowly
|
||||
int rt = 0;
|
||||
/*
|
||||
DPCT1043: The version-related API is different in SYCL. An
|
||||
initial code was generated, but you need to adjust it.
|
||||
*/
|
||||
if (DPCT_CHECK_ERROR(rt = dpct::get_major_version(
|
||||
dpct::get_current_device())) == 0 &&
|
||||
rt / 1000 != DPCT_COMPAT_RT_VERSION / 1000)
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"strata generate: WARNING: this engine was compiled with "
|
||||
"CUDA %d.%d headers but "
|
||||
"loaded a CUDA %d.%d runtime (libcudart): GPU properties "
|
||||
"can read wrong and some "
|
||||
"kernels go unused. Rebuild it against one toolkit (cmake "
|
||||
"-DCUDAToolkit_ROOT=<the "
|
||||
"toolkit>, with its libcudart.so present) (#542)\n",
|
||||
DPCT_COMPAT_RT_VERSION / 1000,
|
||||
DPCT_COMPAT_RT_VERSION % 1000 / 10, rt / 1000,
|
||||
rt % 1000 / 10);
|
||||
}
|
||||
#endif
|
||||
const std::string e = strata::core::device_code_error();
|
||||
if (!e.empty()) {
|
||||
@@ -2829,6 +3046,15 @@ int main(int argc, char **argv) try {
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n",
|
||||
src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1");
|
||||
// #286: with a RAM budget the hottest experts live in it, and the rest are read from the drive unbuffered
|
||||
// when the file cache could not keep them beside the budget anyway (a 32 GB PC) - the mapped reads' page
|
||||
// faults are small requests on the critical path, and their pages take the RAM the budget was sized for
|
||||
if (o.resident_budget > 0 || std::getenv("STRATA_UNBUFFERED_LOAD") != nullptr) {
|
||||
std::string why;
|
||||
const bool ub = src.set_unbuffered(o.resident_budget, why);
|
||||
std::fprintf(stderr, "strata generate: the file tier reads %s (%s)\n",
|
||||
ub ? "unbuffered" : "through the file cache", why.c_str());
|
||||
}
|
||||
srcp = &src;
|
||||
} else {
|
||||
arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1
|
||||
@@ -2910,6 +3136,7 @@ int main(int argc, char **argv) try {
|
||||
return 1;
|
||||
}
|
||||
const bool auto_cache = o.expert_cache < 0;
|
||||
bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits
|
||||
if (o.expert_cache < 0) {
|
||||
size_t free_b = 0, total_b = 0;
|
||||
/*
|
||||
@@ -2928,15 +3155,63 @@ int main(int argc, char **argv) try {
|
||||
const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())
|
||||
? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;
|
||||
const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind;
|
||||
int64_t slots = ((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob;
|
||||
const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
|
||||
int64_t slots = ((int64_t) free_b - reserve) / blob;
|
||||
if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size());
|
||||
o.expert_cache = (int) std::max<int64_t>(slots, 0);
|
||||
std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the "
|
||||
"draft head) -> %d slots\n",
|
||||
(double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache);
|
||||
if (o.expert_cache == 0) // the verify window cannot start without it (#174): say what makes room
|
||||
std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: lower --max-context, use "
|
||||
"--kv k8v4, run images on the CPU, or close other programs that use the GPU\n");
|
||||
// #496: the verify window cannot start without a cache (#174), and a cache too small to lend the prompt path
|
||||
// a 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it
|
||||
// allocate its own on top - more than the reserve. When the default reserve leaves less than that (a 6 GB
|
||||
// card), the reserve shrinks to what leaves exactly that cache, down to kSmallReserveMib: what is allocated
|
||||
// after the cache - the prompt path's own part, the verify buffers, the draft head - comes out of the reserve,
|
||||
// and below ~550 MiB a card ends with less than the 256 MiB the serve check calls LOW (IQ3_XXS, 32K, a 300 MiB
|
||||
// reserve: 5 MiB left), so the cache gets no more than it needs, and the serve check says so plainly when it
|
||||
// ends LOW (`reserve_adapted`). A reserve given on the command line is kept. No slot at all: the start
|
||||
// stops, saying what is short and what makes room. A card the default reserve leaves that much is sized as
|
||||
// before.
|
||||
constexpr int kSmallReserveMib = 300;
|
||||
const int64_t min_slots = (o.prefill_chunk > 0 && pf_borrow)
|
||||
? ((int64_t) strata::prefill::Prefill::bytes_needed(g, ss, 256) + blob - 1) / blob + 128 : 1;
|
||||
if (o.expert_cache < min_slots && !o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib) {
|
||||
// the largest reserve (in MiB) that still leaves min_slots
|
||||
const int64_t fit_mib = ((int64_t) free_b - mtp_bind - min_slots * blob) / (1 << 20) - prefill_mib;
|
||||
if (fit_mib >= kSmallReserveMib) {
|
||||
const int r = (int) std::min<int64_t>(fit_mib, o.vram_reserve_mib);
|
||||
int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind)) / blob;
|
||||
if (!profile.empty()) s2 = std::min<int64_t>(s2, (int64_t) profile.size());
|
||||
std::fprintf(stderr, "strata generate: expert cache auto: the %d MiB reserve leaves too few slots on "
|
||||
"this card (a working cache needs %lld): a %d MiB reserve instead -> %lld slots\n",
|
||||
o.vram_reserve_mib, (long long) min_slots, r, (long long) s2);
|
||||
o.vram_reserve_mib = r;
|
||||
o.expert_cache = (int) s2;
|
||||
reserve_adapted = true;
|
||||
}
|
||||
}
|
||||
if (o.expert_cache == 0) {
|
||||
// what is short, and what makes room: the numbers a small card picks from
|
||||
const int64_t at_reserve = o.vram_reserve_given ? o.vram_reserve_mib
|
||||
: std::min(o.vram_reserve_mib, kSmallReserveMib);
|
||||
const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + min_slots * blob;
|
||||
const int64_t short_mib = std::max<int64_t>(1, (need_b - (int64_t) free_b + (1 << 20) - 1) >> 20);
|
||||
const int64_t session_mib =
|
||||
(int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20);
|
||||
const std::string reserve_tip =
|
||||
o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib
|
||||
? ", a smaller --vram-reserve-mib (" + std::to_string(o.vram_reserve_mib) + " now; " +
|
||||
std::to_string(kSmallReserveMib) + " is enough on a small card)"
|
||||
: std::string();
|
||||
std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: it needs at least %lld slots "
|
||||
"(%lld MiB), about %lld MiB more than this card has free. To make room: a smaller "
|
||||
"--max-context (the session, mostly its KV cache, takes %lld MiB at %lld tokens), "
|
||||
"--kv q4_0, the English draft subset (setup --draft-vocab en; the draft head takes "
|
||||
"%lld MiB now)%s, images on the CPU, or close other programs that use the GPU\n",
|
||||
(long long) min_slots, (long long) ((min_slots * blob) >> 20), (long long) short_mib,
|
||||
(long long) session_mib, (long long) o.max_context, (long long) (mtp_bind >> 20),
|
||||
reserve_tip.c_str());
|
||||
}
|
||||
} else if (multi_gpu && o.expert_cache > 0) {
|
||||
// an explicit cache size leaves room for the prompt path's buffers and the reserve, or the first prompt
|
||||
// fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends
|
||||
@@ -3185,7 +3460,15 @@ int main(int argc, char **argv) try {
|
||||
}
|
||||
prefilled = (int64_t) fills.size();
|
||||
}
|
||||
// #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copied
|
||||
std::future<void> ahead;
|
||||
auto read_batch = [&](int64_t at) { src.prefetch_pairs(profile.data() + at, std::min<int64_t>(64, want - at)); };
|
||||
for (int64_t i = 0; i < want && !piped; ++i) {
|
||||
if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) {
|
||||
if (ahead.valid()) ahead.get();
|
||||
else read_batch(i);
|
||||
if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64);
|
||||
}
|
||||
const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second);
|
||||
if (slot == strata::core::kNotResident) {
|
||||
if (per_layer) continue;
|
||||
@@ -3404,9 +3687,29 @@ int main(int argc, char **argv) try {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Multi-GPU: the second GPU's expert tier, filled with the ranked pairs the primary does not hold
|
||||
strata::core::PeerExperts peer;
|
||||
if (o.peer_device >= 1) {
|
||||
if (profile.empty() || srcp == nullptr || o.expert_cache <= 0) {
|
||||
std::fprintf(stderr, "strata generate: --peer-device needs --expert-profile and the expert cache\n");
|
||||
return 1;
|
||||
}
|
||||
const auto tp0 = Clock::now();
|
||||
if (!peer.open(o.peer_device, profile, xcache, *srcp, g.n_layers, g.n_expert, o.peer_reserve_mib, o.peer_slots,
|
||||
err)) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: peer GPU %d: %lld experts, %.2f GiB (filled in %.1f s); with the primary's "
|
||||
"%lld that is %lld of %lld on the GPUs\n", o.peer_device, (long long) peer.resident(), peer.gib(),
|
||||
std::chrono::duration<double>(Clock::now() - tp0).count(), (long long) xcache.slots(),
|
||||
(long long) (peer.resident() + xcache.slots()), (long long) (g.n_layers * g.n_expert));
|
||||
}
|
||||
|
||||
Drive drive;
|
||||
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.peer = peer.valid() ? &peer : nullptr;
|
||||
drive.d.hit_cpu_order = o.expert_cache_cpu_order;
|
||||
drive.d.split_rows = !o.no_split_rows;
|
||||
drive.d.pool = &pool;
|
||||
@@ -4184,7 +4487,7 @@ int main(int argc, char **argv) try {
|
||||
// and each generated token is written to stdout as `T <id>` as soon as its verify window is done, followed by
|
||||
//
|
||||
// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <stop|length|cancel> <drafts accepted>
|
||||
// <drafts offered> <prompt tokens reused>
|
||||
// <drafts offered> <prompt tokens reused> ... <prompt tokens read> (see the DONE line below; #471)
|
||||
//
|
||||
// Before that, `RESUME <n>` (n prompt tokens are not read again), `PP <position> <prompt_tokens> <ms> <tok/s>`
|
||||
// after every prompt chunk, and `REUSED <n>` once the prompt is read. (`ERR <message>` instead when a request
|
||||
@@ -4322,28 +4625,6 @@ int main(int argc, char **argv) try {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
// --adapt-tuned: a longer memory and more frequent, larger steps for the adaptive tier, where they were measured
|
||||
// to help - a cache that holds 20-60% of the experts, with every expert outside VRAM in RAM. With fewer, a swap
|
||||
// evicts experts that are needed again; with more, nearly everything hits already; with experts on the drive, a
|
||||
// swap can read it. It pays where the CPU's share of the misses is the round's critical path (large experts).
|
||||
if (const char* v = std::getenv("STRATA_ADAPT_TUNED"); v != nullptr) o.adapt_tuned = v[0] != '0';
|
||||
if (o.adapt_tuned && !o.adapt_given && o.expert_cache > 0 && !host_res.empty()) {
|
||||
const double cover = (double) xcache.slots() / (double) (g.n_layers * g.n_expert);
|
||||
bool in_ram = !(o.mmap_experts && !o.resident_cpu_experts);
|
||||
if (o.resident_cpu_experts) // the RAM budget must hold every expert the GPU cache does not
|
||||
for (int64_t i = 0; i < g.n_layers * g.n_expert && in_ram; ++i)
|
||||
if (host_res[(size_t) i] < 0 && !src.has_resident(i / g.n_expert, i % g.n_expert)) in_ram = false;
|
||||
const bool fits = cover >= 0.2 && cover <= 0.6 && in_ram;
|
||||
if (fits) {
|
||||
o.adapt_every = 2;
|
||||
o.adapt_swaps = 192;
|
||||
o.adapt_decay = 0.92f;
|
||||
}
|
||||
std::fprintf(stderr, "strata generate: --adapt-tuned: the cache holds %.0f%% of the experts%s -> adaptive tier "
|
||||
"every %d rounds, %d swaps, x%.2f%s\n", 100.0 * cover,
|
||||
in_ram ? "" : ", some only on the drive", o.adapt_every, o.adapt_swaps, o.adapt_decay,
|
||||
fits ? "" : " (the defaults)");
|
||||
}
|
||||
if (o.serve) {
|
||||
if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 ||
|
||||
(graph_hits && (thits.d_res == nullptr || host_res.empty()))) {
|
||||
@@ -4709,6 +4990,13 @@ int main(int argc, char **argv) try {
|
||||
"context, or read prompts in smaller chunks (--prefill 512)\n");
|
||||
return 1;
|
||||
}
|
||||
if (peer.valid() && o.peer_prefill_rows != 0) {
|
||||
const int64_t rows = o.peer_prefill_rows > 0 ? o.peer_prefill_rows : o.prefill_chunk * K / 2;
|
||||
if (!sp.set_peer(&peer, rows, err)) {
|
||||
std::fprintf(stderr, "strata serve: %s - the prompt path stays on the primary GPU\n", err.c_str());
|
||||
err.clear();
|
||||
}
|
||||
}
|
||||
mem_mark("the head and the prompt path");
|
||||
// #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an
|
||||
// S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache):
|
||||
@@ -4964,6 +5252,9 @@ int main(int argc, char **argv) try {
|
||||
return true;
|
||||
};
|
||||
int64_t pp_total = 0, pp_from = 0, pp_next_check = 0;
|
||||
// #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled
|
||||
// mid-read reports as read, instead of the whole prompt
|
||||
int64_t pp_reached = 0;
|
||||
Clock::time_point pp_t0 = Clock::now();
|
||||
auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
|
||||
std::vector<ImgKey> v;
|
||||
@@ -5040,6 +5331,7 @@ int main(int argc, char **argv) try {
|
||||
batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T);
|
||||
// progress for the server window: PP <position reached> <prompt tokens> <ms> <fresh tokens/s>
|
||||
const int64_t done = p0 + T;
|
||||
pp_reached = done;
|
||||
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();
|
||||
std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) pp_total, ms,
|
||||
ms > 0.0 ? 1000.0 * (double) (done - pp_from) / ms : 0.0);
|
||||
@@ -5090,6 +5382,17 @@ int main(int argc, char **argv) try {
|
||||
drive.d.plan = ver.plan_sink();
|
||||
drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5)));
|
||||
if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
|
||||
// #477 --expert-profile-save: what the adaptive tier learned, kept across restarts (opt-in; off: `heat` stays
|
||||
// empty and nothing below runs). It needs the adaptive tier's counts and the residency table.
|
||||
std::vector<double> heat;
|
||||
if (!o.expert_profile_save.empty()) {
|
||||
if (drive.d.usage.empty() || host_res.empty())
|
||||
std::fprintf(stderr, "strata serve: --expert-profile-save needs the adaptive tier (--adapt-every and "
|
||||
"--adapt-swaps above 0) and --expert-profile: nothing will be saved\n");
|
||||
else
|
||||
heat.assign(drive.d.usage.size(), 0.0);
|
||||
}
|
||||
Clock::time_point profile_saved_at = Clock::now();
|
||||
dpct::queue_ptr adapt_stream = &dpct::get_in_order_queue();
|
||||
/*
|
||||
DPCT1025: The SYCL queue is created ignoring the flag and priority
|
||||
@@ -5133,7 +5436,8 @@ int main(int argc, char **argv) try {
|
||||
};
|
||||
auto apply_pending = [&](bool wait) {
|
||||
try {
|
||||
if (pending.empty()) return;
|
||||
if (peer.valid()) peer.apply_pending(wait);
|
||||
if (pending.empty()) return;
|
||||
if (wait) adapt_ev->wait_and_throw();
|
||||
else if (adapt_ev->get_info<
|
||||
sycl::info::event::command_execution_status>() !=
|
||||
@@ -5170,7 +5474,7 @@ int main(int argc, char **argv) try {
|
||||
const float* u = drive.d.usage.data() + l * g.n_expert;
|
||||
const int32_t* r = host_res.data() + l * g.n_expert;
|
||||
for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {
|
||||
if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); }
|
||||
if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e))) cand.emplace_back(u[e], e); }
|
||||
else vict.emplace_back(u[e], e);
|
||||
}
|
||||
if (cand.empty() || vict.empty()) continue;
|
||||
@@ -5222,9 +5526,40 @@ int main(int argc, char **argv) try {
|
||||
const strata::core::OnDevice on(st->dev);
|
||||
dpct::sync_barrier(st->adapt_ev, st->adapt_stream);
|
||||
}
|
||||
// #477: the routing counted since the start (each count adds up to 1 / (1 - --adapt-decay) over its
|
||||
// decays: the sum is proportional to the routing itself) - only with --expert-profile-save, else `heat`
|
||||
// is empty
|
||||
for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i];
|
||||
if (peer.valid()) { // multi-GPU: the peer takes the next most-routed CPU misses
|
||||
std::vector<int32_t> r0 = host_res;
|
||||
for (const auto& [i, slot] : pending) r0[(size_t) i] = slot; // swapped into the primary already
|
||||
std::string perr;
|
||||
if (!peer.adapt(drive.d.usage.data(), r0.data(),
|
||||
o.peer_adapt_swaps >= 0 ? o.peer_adapt_swaps : o.adapt_swaps, perr)) {
|
||||
std::fprintf(stderr, "strata serve: %s\n", perr.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (float& v : drive.d.usage) v *= o.adapt_decay;
|
||||
return true;
|
||||
};
|
||||
// #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then).
|
||||
// A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log.
|
||||
auto save_profile = [&](const char* why) {
|
||||
if (heat.empty()) return;
|
||||
std::vector<uint8_t> resident(host_res.size(), 0);
|
||||
for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0;
|
||||
for (const auto& p : pending) resident[(size_t) p.first] = 1;
|
||||
std::string e;
|
||||
const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat,
|
||||
profile_loaded);
|
||||
if (strata::core::write_expert_profile(o.expert_profile_save, g.n_layers, g.n_expert, ranked, e))
|
||||
std::fprintf(stderr, "strata serve: expert profile saved to %s (%s)\n", o.expert_profile_save.c_str(),
|
||||
why);
|
||||
else
|
||||
std::fprintf(stderr, "strata serve: the expert profile was not saved: %s\n", e.c_str());
|
||||
profile_saved_at = Clock::now();
|
||||
};
|
||||
// stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went
|
||||
// away, or pressed Esc): the flag is checked between prompt chunks and between verify windows.
|
||||
std::atomic<bool> stop_req{false};
|
||||
@@ -5303,6 +5638,12 @@ int main(int argc, char **argv) try {
|
||||
const int64_t free_mib = (int64_t) (free_b >> 20);
|
||||
if (free_mib >= 256) {
|
||||
std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded\n", (long long) free_mib);
|
||||
} else if (reserve_adapted) {
|
||||
// #496: the reserve was already lowered to make the cache fit - a bigger one would leave it no room
|
||||
std::fprintf(stderr, "strata serve: WARNING: %lld MiB of VRAM free with everything loaded - this card "
|
||||
"only just fits the model (the VRAM reserve was lowered to %d MiB so the expert "
|
||||
"cache fits): requests may stall. Close other programs that use the GPU, or lower "
|
||||
"--max-context\n", (long long) free_mib, o.vram_reserve_mib);
|
||||
} else {
|
||||
std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded - LOW: requests may stall;"
|
||||
" add --vram-reserve-mib %lld to the config's args (or lower --max-context)\n",
|
||||
@@ -5397,6 +5738,10 @@ int main(int argc, char **argv) try {
|
||||
std::vector<float> img_rows;
|
||||
std::vector<const float*> row_ptr;
|
||||
while (next_line(line)) {
|
||||
// #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop)
|
||||
if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 &&
|
||||
Clock::now() - profile_saved_at >= std::chrono::duration<double>(o.expert_profile_save_min * 60.0))
|
||||
save_profile("periodic");
|
||||
if (line == "QUIT") break;
|
||||
// the watchdog watches a request from here until this iteration ends, whichever way it ends
|
||||
struct BusyScope {
|
||||
@@ -5744,6 +6089,7 @@ int main(int argc, char **argv) try {
|
||||
conversations.limit_reuse(read_from);
|
||||
pp_total = n;
|
||||
pp_from = read_from;
|
||||
pp_reached = read_from;
|
||||
pp_t0 = r0;
|
||||
pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every;
|
||||
{
|
||||
@@ -5809,6 +6155,7 @@ int main(int argc, char **argv) try {
|
||||
return false;
|
||||
if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false;
|
||||
q += T;
|
||||
pp_reached = q; // #471
|
||||
}
|
||||
// the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first
|
||||
if (!ver.wait_commit(e)) return false;
|
||||
@@ -6102,13 +6449,10 @@ int main(int argc, char **argv) try {
|
||||
drive.d.layers = 0;
|
||||
drive.d.experts = 0;
|
||||
drive.d.failed = false;
|
||||
// THE WAIT IS THE FIX. A non-blocking query here left the next window's residency table to
|
||||
// depend on whether the previous round's expert copies had landed: an expert that is resident
|
||||
// runs the GPU kernel and one that is not is computed on the CPU, and the two round
|
||||
// differently enough to move a logit by ~0.26. Waiting costs the copies' remaining time on a
|
||||
// window that follows one that issued them, and buys a residency table that is a function of
|
||||
// what was actually copied - which is what makes greedy decode reproducible.
|
||||
apply_pending(true);
|
||||
// #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in
|
||||
// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing
|
||||
// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)
|
||||
apply_pending(!adapt_nowait());
|
||||
if (hist_n > 0) {
|
||||
// the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the
|
||||
// fed-back head `x` (it joins `consumed` only after this window commits), then the drafts
|
||||
@@ -6366,20 +6710,30 @@ int main(int argc, char **argv) try {
|
||||
}
|
||||
const int64_t req_hits = drive.d.cache_hits - decode_hits0;
|
||||
const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;
|
||||
// #471: the prompt tokens this request read - all the fresh ones, or as far as the prompt pass got when a
|
||||
// cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all)
|
||||
const int64_t fresh = n - resume;
|
||||
const int64_t read_n = cancelled ? std::clamp<int64_t>(pp_reached - resume, 0, fresh) : fresh;
|
||||
// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]
|
||||
// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)
|
||||
std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f\n", (long long) produced_n,
|
||||
// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)
|
||||
std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld\n", (long long) produced_n,
|
||||
(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,
|
||||
(long long) resume, (long long) req_hits, (long long) req_look,
|
||||
(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),
|
||||
(double) (src.file_read_bytes() - file_bytes0) / 1e6);
|
||||
(double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n);
|
||||
std::fflush(stdout);
|
||||
if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session
|
||||
const int64_t fresh = n - resume;
|
||||
std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %lld read in %.0f ms (%.1f tok/s), "
|
||||
// "12288 of 98179" when cancelled mid-read (#471), the rate from what was read
|
||||
char read_txt[64];
|
||||
if (cancelled)
|
||||
std::snprintf(read_txt, sizeof(read_txt), "%lld of %lld", (long long) read_n, (long long) fresh);
|
||||
else
|
||||
std::snprintf(read_txt, sizeof(read_txt), "%lld", (long long) fresh);
|
||||
std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %s read in %.0f ms (%.1f tok/s), "
|
||||
"%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld, %zu checkpoints%s\n",
|
||||
(long long) n, (long long) resume, (long long) fresh, prompt_ms,
|
||||
prompt_ms > 0 ? 1000.0 * fresh / prompt_ms : 0.0, (long long) produced_n, decode_ms,
|
||||
(long long) n, (long long) resume, read_txt, prompt_ms,
|
||||
prompt_ms > 0 ? 1000.0 * read_n / prompt_ms : 0.0, (long long) produced_n, decode_ms,
|
||||
decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted,
|
||||
(long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : "");
|
||||
// the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU
|
||||
@@ -6441,6 +6795,7 @@ int main(int argc, char **argv) try {
|
||||
remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r],
|
||||
remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]);
|
||||
}
|
||||
save_profile("exit"); // #477: QUIT, or the server closed stdin
|
||||
// SYCL port: the requests are done and their output written; leave without unwinding the GPU objects (the OS
|
||||
// reclaims them). Their destructors ran against a runtime already shutting down and aborted (exit 139).
|
||||
try { dpct::get_current_device().queues_wait_and_throw(); } catch (...) {}
|
||||
@@ -6733,11 +7088,7 @@ int main(int argc, char **argv) try {
|
||||
(long long) n_vocab, (long long) pos);
|
||||
return 1;
|
||||
}
|
||||
// THE HEADER IS WRITTEN WITH THE FIRST ROW, NOT AT OPEN. A native pack leaves the per-token
|
||||
// loop at `if (native_pack) { spec_pos = pos; break; }` and never reaches this site, so a header
|
||||
// written at open promised 64 or 66 rows for a file that would contain none - and a reader that
|
||||
// trusted it reported "0 differing positions" from a file with no positions in it. Written here,
|
||||
// a run that dumps nothing leaves an empty file, which is what actually happened.
|
||||
// the header with the first row (see `hdr`): a run that dumps nothing leaves an empty file
|
||||
if (emit_logits && !hdr_written && std::fwrite(hdr, sizeof hdr, 1, dump) != 1) {
|
||||
std::fprintf(stderr, "strata generate: cannot write logits header\n");
|
||||
std::fclose(dump);
|
||||
@@ -6923,11 +7274,7 @@ int main(int argc, char **argv) try {
|
||||
auto apply_pending = [&](bool wait) {
|
||||
try {
|
||||
if (pending.empty()) return;
|
||||
if (wait) adapt_ev->wait_and_throw();
|
||||
// STRATA_TRACE_ADAPT: a non-blocking query means the next window reads the residency table
|
||||
// with whatever the copy has achieved. Whether the incoming experts are RESIDENT for that
|
||||
// window depends on copy latency, and a resident expert runs a different kernel than a
|
||||
// CPU-computed one - a far bigger numerical difference than a rounding wobble.
|
||||
// STRATA_TRACE_ADAPT=1: whether a round's copies had landed when the next window read the table
|
||||
static const bool trace_pending = std::getenv("STRATA_TRACE_ADAPT") != nullptr;
|
||||
if (wait) adapt_ev->wait_and_throw();
|
||||
else if (adapt_ev->get_info<
|
||||
@@ -7113,13 +7460,10 @@ int main(int argc, char **argv) try {
|
||||
drive.d.layers = 0;
|
||||
drive.d.experts = 0;
|
||||
drive.d.failed = false;
|
||||
// THE WAIT IS THE FIX. A non-blocking query here left the next window's residency table to
|
||||
// depend on whether the previous round's expert copies had landed: an expert that is resident
|
||||
// runs the GPU kernel and one that is not is computed on the CPU, and the two round
|
||||
// differently enough to move a logit by ~0.26. Waiting costs the copies' remaining time on a
|
||||
// window that follows one that issued them, and buys a residency table that is a function of
|
||||
// what was actually copied - which is what makes greedy decode reproducible.
|
||||
apply_pending(true);
|
||||
// #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in
|
||||
// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing
|
||||
// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)
|
||||
apply_pending(!adapt_nowait());
|
||||
if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) {
|
||||
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
||||
return 1;
|
||||
|
||||
@@ -111,6 +111,20 @@ def gdn_plain_copies(s):
|
||||
return s.replace("*reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);",
|
||||
"*reinterpret_cast<sycl::float4*>(smem) = *reinterpret_cast<const sycl::float4*>(gmem);")
|
||||
edit("src/prefill/kernels.dp.cpp", gdn_plain_copies)
|
||||
# 0.1.38: upstream's sm_90 thread-block-cluster greedy sampler (cudaLaunchKernelEx with a cluster dimension) has no
|
||||
# SYCL counterpart: the HIP branch's "not available" answer, so the caller takes the plain greedy kernel
|
||||
edit("src/kernels/cuda/sampler.dp.cpp", lambda s: s.replace(
|
||||
" int *out, void *stream) try {\n#if defined(__HIPCC__)\n",
|
||||
" int *out, void *stream) try {\n#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain greedy kernel\n"))
|
||||
edit("src/kernels/cuda/qsa_select.dp.cpp", lambda s: s.replace(
|
||||
" void *stream) try {\n#if defined(__HIPCC__)\n",
|
||||
" void *stream) try {\n#if 1 // SYCL port: no thread-block clusters (sm_90): the caller takes the plain top-k\n"))
|
||||
# 0.1.38: dpct could not deduce fused_gr's templated kernel names (the staged read and the MAX_T down kernels)
|
||||
def gr_kernel_names(s):
|
||||
pat = re.compile(r",\s*dpct_placeholder /\*Fix the type mannually\*/>>\((.{0,900}?)\b(gr_down_staged_kernel|gr_down_multi_kernel<(\d+)>)\(", re.S)
|
||||
return pat.sub(lambda m: (">>(" if m.group(2) == "gr_down_staged_kernel" else f", dpct_kernel_scalar<{m.group(3)}>>>(")
|
||||
+ m.group(1) + m.group(2) + "(", s)
|
||||
edit("src/kernels/cuda/fused_gr.dp.cpp", gr_kernel_names)
|
||||
edit("src/kernels/cuda/elementwise.dp.cpp", doorbell)
|
||||
edit("src/kernels/cuda/verify_kernels.dp.cpp", doorbell)
|
||||
|
||||
|
||||
Reference in new issue
Block a user