Merge f-latency into f-144-rel

This commit is contained in:
Niko1221 committed 2026-10-13 09:17:44 +02:00
commit 0b8d31013a
9 files changed
+636 -5

No files matched your search

@@ -49,4 +49,21 @@ void native_qsa_indexer_append_steps(const float* raw, const int32_t* relative_p
const QsaIndexerBuffers& buffers, const QsaShapes& shapes,
int64_t max_cells, const RopeScaling& scaling, void* stream);
// engine-latency: the commit's append of the same window rows into several QSA layers in one launch. Layer i reads
// raw0 + i * raw_stride and its own gamma/buffers; with tail_src[i] set its tail is first restored from there (the
// commit's snapshot, mapped memory), as copy_from_mapped did before the per-layer append. Bitwise the per-layer calls.
struct QsaIndexerLayers {
static constexpr int kMax = 16;
const float* gamma[kMax] = {};
const float* tail_src[kMax] = {};
float* tail[kMax] = {};
float* dead[kMax] = {};
float* pooled[kMax] = {};
int32_t* block_pos[kMax] = {};
};
void native_qsa_indexer_append_steps_layers(const float* raw0, int64_t raw_stride, const int32_t* relative_pos_device,
int pos_stride, int n_steps, int32_t pos_base, float epsilon,
const QsaIndexerLayers& layers, int n_layers, const QsaShapes& shapes,
int64_t max_cells, const RopeScaling& scaling, void* stream);
} // namespace strata::kernels
@@ -41,6 +41,15 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
const int32_t* n_keep, void* stream, int t_out_begin = 0, void* xq_out = nullptr);
/// The commit of `n_layers` GDN layers in two launches (engine-latency): layer i's conv history is
/// `state + i * state_stride + conv_off` and its qkv rows `qkv + i * qkv_stride`, as gdn_conv_commit; its recurrence
/// state `state + i * state_stride` over the first *n_keep rows of `h + i * h_stride` / `gate|beta + i * gb_stride`, as
/// gdn_step_norm_multi's commit (n_keep set, no outputs). Every layer's arithmetic is the per-layer call's, so the result
/// is bitwise the loop of per-layer calls. Returns false (nothing launched) when the per-layer commit would not take the
/// state-only kernel (STRATA_GDN_SPLIT=1, STRATA_GDN_COMMIT_SPLIT=0, STRATA_DBG_GDN=1): the caller then keeps the loop.
bool gdn_commit_layers(float* state, int64_t state_stride, int64_t conv_off, const float* qkv, int64_t qkv_stride,
const float* h, int64_t h_stride, const float* gate, const float* beta, int64_t gb_stride,
int conv_channels, int h_k, int h_v, int n_max, int n_layers, const int32_t* n_keep, void* stream);
/// (xq_out, S26 STRATA_QFUSE: also write the q8_1 image of output rows [t_out_begin, n_tok) there - the bytes
/// native_quantize_q8_1(y + t_out_begin * value_dim, xq_out, value_dim, n_tok - t_out_begin) would write.)
/// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be
+39 -1
View File
@@ -431,6 +431,34 @@ def start_log_tail(log: str | None, offset: int, n: int = 20) -> str:
return "\nthe engine log's last lines:\n" + "\n".join(" " + x for x in lines)
# A start that ends at once with the GPU runtime's own failure and none of the engine's lines: on ROCm, a start right
# after the previous engine exited can fail inside the runtime's device/queue set-up while the old process's queues are
# still being torn down ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'", or an exit with
# nothing in the log). Such a start is tried again after a short wait (STRATA_START_RETRIES, default 3; 0: never).
TRANSIENT_START_MARKS = ("hsa_exception", "HSA_STATUS_ERROR", "hsaKmt")
START_RETRIES = max(0, int(os.environ.get("STRATA_START_RETRIES", "3") or 0))
def transient_start_failure(log: str | None, offset: int, elapsed_s: float, rc: int | None = None) -> bool:
"""True when the start that wrote the log from `offset` failed the transient way above: within 30 s, and its lines
are only the launcher's own "engine started" line plus (optionally) a GPU runtime failure. An exit with no line
at all counts only when it was not the engine's own error exit (1: it said why on stdout)."""
if not log or elapsed_s > 30.0:
return False
try:
with open(log, "rb") as f:
f.seek(offset)
text = f.read(64 * 1024).decode("utf-8", "replace")
except (OSError, ValueError):
return False
lines = [x.strip() for x in text.splitlines() if x.strip()]
engine_lines = [x for x in lines if not x.startswith("[strata]")]
if any(m in text for m in TRANSIENT_START_MARKS):
return all(x.startswith("terminate called") or x.startswith("what()") or
any(m in x for m in TRANSIENT_START_MARKS) for x in engine_lines)
return not engine_lines and rc != 1 # it exited without writing a single line of its own
def echo_requests(log_path: str, offset: int) -> None:
"""STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log.
@@ -647,7 +675,7 @@ class StrataEngine:
tl.last = value
def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,
env: dict | None = None, lazy: bool = False, cpus: list[int] | None = None):
env: dict | None = None, lazy: bool = False, cpus: list[int] | None = None, _attempt: int = 0):
self.spawn = (exe, list(args), cwd, log, env, False, cpus) # to start it again after it died (issue #27)
self.session_save_reclaim = '--session-save-reclaim' in args
paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")}
@@ -694,6 +722,7 @@ class StrataEngine:
pin = {}
if cpus and hasattr(os, "sched_setaffinity"): # replicas: this engine's own physical cores (serve/replicas.py)
pin["preexec_fn"] = lambda: os.sched_setaffinity(0, cpus)
spawned_at = time.monotonic()
self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, **pin)
contain(self.proc) # ends with the server, however it ends (Windows)
@@ -738,6 +767,15 @@ class StrataEngine:
self.log.close()
except (OSError, subprocess.TimeoutExpired):
pass
if not timed_out and _attempt < START_RETRIES and \
transient_start_failure(log, log_start, time.monotonic() - spawned_at, self.proc.returncode):
wait_s = 2.0 * (2 ** _attempt) # 2, 4, 8 s: the previous process's GPU queues go away
print(f"[strata] the engine stopped while the GPU runtime was starting (most often right after another "
f"engine exited, whose GPU queues were still being released): starting it again in {wait_s:.0f} s "
f"(try {_attempt + 2} of {START_RETRIES + 1})", flush=True)
time.sleep(wait_s)
StrataEngine.__init__(self, exe, args, cwd, log, env, lazy, cpus, _attempt + 1)
return
why = (f"the engine did not report READY within {ENGINE_READY_S:.0f} s" if timed_out else
"the engine exited before it was ready")
# EngineDied, not bare RuntimeError: a request waiting on this load must end with a 503
+231
View File
@@ -30,6 +30,7 @@
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include "strata/kernels/ngram.hpp"
#include "strata/kernels/gfx_arch.hpp"
#include <algorithm>
#include <atomic>
@@ -421,6 +422,26 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
if (force_on_ && hi_prio && cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi) == cudaSuccess)
prio = cudaStreamCreateWithPriority(&cs_, cudaStreamNonBlocking, prio_hi) == cudaSuccess;
cudaGetLastError();
#endif
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
// engine-latency, STRATA_MTP_HIP_PRIO (default on gfx1200/gfx1201, =1 elsewhere opt-in, =0 off): the draft stream at the
// highest priority. ROCm hands out hardware queues per priority (GPU_MAX_HW_QUEUES per level), so the drafter gets a
// queue of its own: its round no longer waits behind the commit graph that the verifier's stream launched just before
// it (the commit is only needed by the next window, and now runs beside the draft). R9700, UD-Q4_K_XL: draft wall
// 5.8 -> 3.5 ms a window (notes-latency.md).
{
static const bool hip_prio = [] {
if (const char* v = std::getenv("STRATA_MTP_HIP_PRIO"); v != nullptr && *v != 0) return std::atoi(v) != 0;
int dev = 0;
cudaDeviceProp prop{};
return cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
strata::kernels::gfx_arch_is_gfx12(prop.gcnArchName);
}();
int lo = 0, hi = 0;
if (hip_prio && hipDeviceGetStreamPriorityRange(&lo, &hi) == hipSuccess)
prio = hipStreamCreateWithPriority(&cs_, hipStreamNonBlocking, hi) == hipSuccess;
(void) cudaGetLastError();
}
#endif
if (!prio && cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; }
#if !defined(STRATA_USE_HIP)
@@ -702,6 +723,120 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float
return true;
}
// STRATA_MTP_PROFILE=1 (measurement only): GPU stamps between the draft layer's stages in the round graph and in every
// step graph (each stamp is one more node, so the totals run a little high); the per-stage averages are printed every
// 300 rounds with STRATA_DRAFT_TIMING's line. Off: no stamp is recorded and nothing changes.
namespace {
constexpr int kMpSlots = 24;
constexpr int kMpGraphs = 17; // the round graph (0) and the steps 1..16
const char* const kMpNames[kMpSlots] = {"-", "embed+fc_emb", "hnorm+fc_hidden+add", "hc-read attn", "k/v+append",
"q+norm-rope", "attention", "gate+o_proj", "hc-read mlp", "router",
"experts", "shared", "combine+write", "hc-read mixer", "head gemv",
"argmax+prob", "select", "", "", "", "", "", "", ""};
struct MtpProf {
bool on = false;
unsigned long long* d = nullptr;
std::vector<unsigned long long> h;
int base = -1; // the graph being captured (-1: none, no stamps)
double sum[2][kMpSlots] = {};
int64_t n[2] = {0, 0};
MtpProf() {
const char* e = std::getenv("STRATA_MTP_PROFILE");
on = e != nullptr && e[0] == '1';
}
void init() {
if (!on || d != nullptr) return;
if (cudaMalloc((void**) &d, (size_t) kMpSlots * kMpGraphs * 8) != cudaSuccess) { on = false; d = nullptr; (void) cudaGetLastError(); return; }
cudaMemset(d, 0, (size_t) kMpSlots * kMpGraphs * 8);
h.assign((size_t) kMpSlots * kMpGraphs, 0);
}
void stamp(int i, cudaStream_t cs) const {
if (on && d != nullptr && base >= 0) strata::kernels::gpu_stamp(d, base * kMpSlots + i, cs);
}
void collect(int n_steps_run) { // after the round's sync: the round graph and steps 1..n_steps_run-1
if (!on || d == nullptr) return;
cudaMemcpy(h.data(), d, h.size() * 8, cudaMemcpyDeviceToHost);
for (int gi = 0; gi < n_steps_run && gi < kMpGraphs; ++gi) {
const unsigned long long* s = h.data() + (size_t) gi * kMpSlots;
const int k = gi == 0 ? 0 : 1;
unsigned long long prev = s[0];
if (prev == 0) continue;
for (int i = 1; i < kMpSlots; ++i) {
if (s[i] == 0 || s[i] < prev) continue;
sum[k][i] += (double) (s[i] - prev);
prev = s[i];
}
++n[k];
}
}
void report() {
for (int k = 0; k < 2; ++k) {
if (n[k] == 0) continue;
std::string out;
char b[96];
double tot = 0;
for (int i = 1; i < kMpSlots; ++i) {
if (sum[k][i] <= 0) continue;
tot += sum[k][i];
std::snprintf(b, sizeof b, " %s %.3f", kMpNames[i], sum[k][i] / 1e6 / (double) n[k]);
out += b;
}
std::fprintf(stderr, "strata mtp profile (%s, ms per graph over %lld):%s | total %.3f\n", k == 0 ? "round" : "step",
(long long) n[k], out.c_str(), tot / 1e6 / (double) n[k]);
for (double& x : sum[k]) x = 0;
n[k] = 0;
}
}
};
MtpProf g_mp;
// STRATA_VERIFY_NODES=1 also lists the draft graphs' nodes (kernel names on HIP; counts on CUDA)
void mtp_list_nodes(cudaGraph_t graph, const char* what) {
if (std::getenv("STRATA_VERIFY_NODES") == nullptr || graph == nullptr) return;
#if defined(STRATA_USE_HIP)
using NodeT = hipGraphNode_t;
using NodeTypeT = hipGraphNodeType;
#define MTP_GET_NODES hipGraphGetNodes
#define MTP_NODE_TYPE hipGraphNodeGetType
#else
using NodeT = cudaGraphNode_t;
using NodeTypeT = cudaGraphNodeType;
#define MTP_GET_NODES cudaGraphGetNodes
#define MTP_NODE_TYPE cudaGraphNodeGetType
#endif
size_t nn = 0;
MTP_GET_NODES(graph, nullptr, &nn);
std::vector<NodeT> nodes(nn);
MTP_GET_NODES(graph, nodes.data(), &nn);
std::vector<std::pair<std::string, int>> kinds;
for (NodeT nd : nodes) {
NodeTypeT ty;
MTP_NODE_TYPE(nd, &ty);
std::string name = "type" + std::to_string((int) ty);
#if defined(STRATA_USE_HIP)
if (ty == hipGraphNodeTypeKernel) {
hipKernelNodeParams kp{};
if (hipGraphKernelNodeGetParams(nd, &kp) == hipSuccess && kp.func != nullptr) {
const char* fn = hipKernelNameRefByPtr(kp.func, nullptr);
if (fn != nullptr) name = fn;
}
}
#else
if (ty == cudaGraphNodeTypeKernel) name = "kernel";
#endif
bool found = false;
for (auto& k : kinds)
if (k.first == name) { ++k.second; found = true; break; }
if (!found) kinds.push_back({name, 1});
}
#undef MTP_GET_NODES
#undef MTP_NODE_TYPE
std::fprintf(stderr, "strata mtp: the %s graph has %zu nodes:", what, nn);
for (auto& k : kinds) std::fprintf(stderr, "\n %4d x %.110s", k.second, k.first.c_str());
std::fprintf(stderr, "\n");
}
} // namespace
// The layer for T rows. full = false stops after the K/V append (the prompt only needs the cache).
bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::string& err) {
// step_row0 >= 0: the full layer on step rows [step_row0, +T); step_row0 < 0: K/V only on rows [-1 - step_row0, +T)
@@ -728,6 +863,7 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err
// ---- the two input branches
const WeightRef* we = wt_->find("token_embd.weight");
if (!we) { err = "mtp: token_embd.weight is missing"; return false; }
g_mp.stamp(0, cs);
if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table
ne->gather_dev(tok_, T, emb_, cs);
} else {
@@ -740,6 +876,7 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err
native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs);
native_quantize_q8_1(en_, xq_, (int) N, T, cs);
native_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs);
g_mp.stamp(1, cs);
if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight
native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs);
else
@@ -750,6 +887,7 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err
native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);
}
add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs);
g_mp.stamp(2, cs);
// ---- the attention hyper-connection
{
FusedGrArgs fa[kFusedGrMaxT];
@@ -764,6 +902,7 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err
}
fused_gr_read_multi(fa, T, xn_, cs);
}
g_mp.stamp(3, cs);
// ---- attention: K/V into the layer's own cache
native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);
@@ -811,6 +950,7 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err
kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
vcur_ + t * NKV * HD, s, cs, &st_.host);
}
g_mp.stamp(4, cs);
} catch (const std::exception& e) {
err = std::string("mtp: ") + e.what();
return false;
@@ -857,13 +997,16 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
norm_rope(qcur_, f32("self_attn.q_norm.weight"), (int) (T * NH), (int) HD, pos, cs);
}
if (st_.kv_rot) fwht256_inplace_cuda(qcur_, (int64_t) T * NH, cs);
g_mp.stamp(5, cs);
const QsaAttnPools pools = qsa_attn_pools(st_);
if (window_ > 0) window_ids(const_cast<int32_t*>(step), T, (int) window_, ident_, cap_, cs);
qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs);
if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);
g_mp.stamp(6, cs);
native_qsa_gate_apply(attn_, qfull_, attn32_, (int) (T * NH), (int) HD, cs);
native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);
native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs);
g_mp.stamp(7, cs);
// ---- the MLP hyper-connection (the attention write folded in)
{
FusedGrArgs fa[kFusedGrMaxT];
@@ -879,6 +1022,7 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
}
fused_gr_read_multi(fa, T, xn_, cs);
}
g_mp.stamp(8, cs);
// ---- MoE: router, the 512 resident experts, the shared expert (on a branch beside them on CUDA), the
// combine, the write
NativeSharedWeights nsw;
@@ -948,16 +1092,19 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
native_route_resident(logits_, ids_, w_, rr_res_, T, rr_margin_, rr_lo_, rr_hi_, nullptr, cs);
} catch (const std::exception& e) { err = std::string("mtp route-resident: ") + e.what(); return false; }
}
g_mp.stamp(9, cs);
moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_,
grp_start_, grp_counts_, hit_dst_, hit_slot_, cs);
quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs);
moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,
hit_xs_, hit_scratch_, parts_, cs);
g_mp.stamp(10, cs);
if (branch_on) {
if (cudaStreamWaitEvent(cs, sh_join_, 0) != cudaSuccess) { err = "mtp: the shared expert's join"; return false; }
} else {
shared_rows();
}
g_mp.stamp(11, cs);
static const bool no_multi_gr = [] { // #783 PR-g: STRATA_NO_MULTI_GR=1 keeps the per-token GR calls
const char* v = std::getenv("STRATA_NO_MULTI_GR");
return v != nullptr && v[0] != '\0' && v[0] != '0';
@@ -978,6 +1125,7 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
// its own, so doing them after the loop changes nothing)
if (!fuse_head_gr && !no_multi_gr)
gr_write_multi(R_, y_, inj2_, gs, R_, T, cs);
g_mp.stamp(12, cs);
// ---- the final mixer and the main model's head
if (fuse_head_gr) {
FusedGrArgs fa[kFusedGrMaxT];
@@ -1010,11 +1158,13 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, own_gr_,
sample_ + t * N, dummy_inj_, cs);
}
g_mp.stamp(13, cs);
native_quantize_q8_1(sample_, xq_, (int) N, T, cs);
const bool sub = dhead_ != nullptr;
const int64_t nv = sub ? n_dvocab_ : n_vocab_;
native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N,
(int) nv, T, cs);
g_mp.stamp(14, cs);
if (coupled_rec_) {
// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
@@ -1038,6 +1188,7 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
if (multi_block_head_ops()) row_top_prob_split(head_logits_, T, (int) nv, out_ids_, probs_, top_scratch_, cs);
else row_top_prob(head_logits_, T, (int) nv, out_ids_, probs_, cs);
if (sub) map_ids(out_ids_, dvocab_, T, cs);
g_mp.stamp(15, cs);
} catch (const std::exception& e) {
err = std::string("mtp: ") + e.what();
return false;
@@ -1058,6 +1209,7 @@ bool finish_capture(cudaStream_t cs, bool ok, cudaGraphExec_t& exec, const char*
err = std::string("mtp: ") + what + " capture: " + cudaGetErrorString(ce);
return false;
}
mtp_list_nodes(graph, what);
cudaGraphDestroy(graph);
// an explicit upload: the first launch's implicit one blocked behind a device-side spin (verify.cpp)
cudaGraphUpload(exec, cs);
@@ -1089,7 +1241,9 @@ bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) {
if (exec) return true;
using namespace strata::kernels;
const int64_t HCN = g_->hc * g_->n_embd;
g_mp.init(); // (its allocation before the capture)
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; }
g_mp.base = 0;
bool ok = true;
// coupled: the request's chain and the penalty history's base, for this round's drafts
if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_);
@@ -1124,6 +1278,8 @@ bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) {
coupled_rec_ = false;
}
if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_);
if (ok) g_mp.stamp(16, cs_);
g_mp.base = -1;
if (ok && force_on_ && !coupled) force_token(tok_, m_force_, 0, cs_); // chain_launch: step 1's input
return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err);
}
@@ -1136,6 +1292,7 @@ bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) {
using namespace strata::kernels;
const int64_t HCN = g_->hc * g_->n_embd;
const int row = max_t_ + j - 1;
g_mp.init();
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; }
#if defined(STRATA_USE_HIP)
copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_);
@@ -1147,9 +1304,12 @@ bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) {
#endif
coupled_rec_ = coupled;
coupled_j_ = j;
g_mp.base = j < kMpGraphs ? j : -1;
bool ok = record_forward(1, row, cs_, err);
coupled_rec_ = false;
if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_);
if (ok) g_mp.stamp(16, cs_);
g_mp.base = -1;
if (ok && force_on_ && !coupled) force_token(tok_, m_force_, j, cs_); // chain_launch: step j+1's input
return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err);
}
@@ -1290,6 +1450,39 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_
return true;
}
// STRATA_DRAFT_TIMING=1: where a draft round's time goes, from cudaEvent pairs around each graph launch (GPU time of the round
// graph and of each step, and the idle gap the host's decision leaves between two steps) and the host's own wall time.
namespace {
struct DraftTiming {
bool on = false;
cudaEvent_t eb[16] = {}, ea[16] = {};
double round_ms = 0, step_ms = 0, gap_ms = 0, wall_ms = 0, tail_ms = 0;
double pre_ms = 0, launch_ms = 0, ple_ms = 0, wait0_ms = 0, waitj_ms = 0; // host: staging, graph launch calls, PLE prefetch, spins
int64_t rounds = 0, steps = 0;
DraftTiming() {
const char* e = std::getenv("STRATA_DRAFT_TIMING");
on = e != nullptr && e[0] == '1';
}
void init() {
if (!on || eb[0] != nullptr) return;
for (int i = 0; i < 16; ++i)
if (cudaEventCreate(&eb[i]) != cudaSuccess || cudaEventCreate(&ea[i]) != cudaSuccess) { on = false; (void) cudaGetLastError(); return; }
}
void report() const {
if (rounds == 0) return;
const double r = (double) rounds;
std::fprintf(stderr, "strata mtp draft timing: %lld rounds, %.2f steps/round: wall %.3f ms = round graph %.3f + steps %.3f GPU "
"(%.3f per step) + host gaps between graphs %.3f + tail %.3f (per round)\n",
(long long) rounds, (double) steps / r, wall_ms / r, round_ms / r, step_ms / r,
steps > 0 ? step_ms / (double) steps : 0.0, gap_ms / r, tail_ms / r);
std::fprintf(stderr, "strata mtp draft timing (host, per round): staging %.3f, graph launch calls %.3f, PLE prefetch %.3f, "
"wait for draft 0 %.3f, waits for the steps %.3f\n",
pre_ms / r, launch_ms / r, ple_ms / r, wait0_ms / r, waitj_ms / r);
}
};
DraftTiming g_dt;
} // namespace
bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err,
float* probs, float min_p, int* n_drafts) {
const OnDevice on_device(device_);
@@ -1331,8 +1524,12 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
SessionState* const pss = ple_ss_ ? ple_ss_ : ss_;
const bool do_ple = pss != nullptr && pss->ple.ready() && pss->ple.table != nullptr;
int32_t ple_prev[2] = {do_ple ? pss->ple_prev[0] : 0, do_ple ? pss->ple_prev[1] : 0};
const bool dth = g_dt.on;
auto hms = [](Clock::time_point a0) { return std::chrono::duration<double, std::milli>(Clock::now() - a0).count(); };
auto prefetch_ple = [&](int32_t tok) {
if (!do_ple || tok < 0) return;
const Clock::time_point tp = Clock::now();
struct PleT { bool on; double& acc; Clock::time_point t; ~PleT() { if (on) acc += std::chrono::duration<double, std::milli>(Clock::now() - t).count(); } } ple_t{dth, g_dt.ple_ms, tp};
uint32_t rows16[strata::kernels::PLE_N_HEADS];
strata::kernels::ngram_rows(&tok, ple_prev, 1, pss->ple.consts, rows16);
ple_prev[0] = ple_prev[1];
@@ -1377,10 +1574,17 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
prefetch_ple(drafts[last]);
n = max_steps;
} else if (max_steps > 0) {
g_dt.init();
const bool dt = g_dt.on;
if (dt) g_dt.pre_ms += hms(t0);
if (dt) cudaEventRecord(g_dt.eb[0], cs_);
Clock::time_point tl = Clock::now();
if (cudaGraphLaunch(cp ? round_exec_c_[T] : round_exec_[T], cs_) != cudaSuccess) {
err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
if (dt) g_dt.launch_ms += hms(tl);
if (dt) cudaEventRecord(g_dt.ea[0], cs_);
(void) cudaStreamQuery(cs_);
prefetch_ple(tokens[a]);
progress_at("mtp draft: waiting for the GPU"); // #2065: a stall here read as "decode", the verify window before it
@@ -1393,29 +1597,56 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
if ((++spins & 1023u) == 0 && cudaStreamQuery(cs_) != cudaErrorNotReady) break;
}
};
tl = Clock::now();
wait_step(0);
if (dt) g_dt.wait0_ms += hms(tl);
drafts[0] = ((volatile int32_t*) h_out_)[0];
float pj = ((volatile float*) h_prob_)[0];
if (probs) probs[0] = pj;
n = 1;
for (int j = 1; j < max_steps && pj >= min_p; ++j) {
if (dt) cudaEventRecord(g_dt.eb[j], cs_);
tl = Clock::now();
if (cudaGraphLaunch(cp ? step_exec_c_[j] : step_exec_[j], cs_) != cudaSuccess) {
err = std::string("mtp draft step: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
if (dt) g_dt.launch_ms += hms(tl);
if (dt) cudaEventRecord(g_dt.ea[j], cs_);
(void) cudaStreamQuery(cs_);
prefetch_ple(drafts[j - 1]);
tl = Clock::now();
wait_step(j);
if (dt) g_dt.waitj_ms += hms(tl);
drafts[j] = ((volatile int32_t*) h_out_)[j];
pj = ((volatile float*) h_prob_)[j];
if (probs) probs[j] = pj;
++n;
}
prefetch_ple(drafts[n - 1]);
const Clock::time_point t_pre_sync = Clock::now();
if (cudaStreamSynchronize(cs_) != cudaSuccess) {
err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
if (dt) {
float ms = 0;
double r = 0, s = 0, gp = 0;
if (cudaEventElapsedTime(&ms, g_dt.eb[0], g_dt.ea[0]) == cudaSuccess) r = ms;
for (int j = 1; j < n; ++j) {
if (cudaEventElapsedTime(&ms, g_dt.eb[j], g_dt.ea[j]) == cudaSuccess) s += ms;
if (cudaEventElapsedTime(&ms, g_dt.ea[j - 1], g_dt.eb[j]) == cudaSuccess) gp += ms;
}
g_dt.round_ms += r; g_dt.step_ms += s; g_dt.gap_ms += gp;
g_dt.steps += n - 1; ++g_dt.rounds;
g_dt.wall_ms += ms_since(t0);
g_dt.tail_ms += std::chrono::duration<double, std::milli>(Clock::now() - t_pre_sync).count();
if (g_dt.rounds % 300 == 0) g_dt.report();
}
if (g_mp.on) {
g_mp.collect(n);
if (g_mp.n[0] % 300 == 0) g_mp.report();
}
}
for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; }
if (n_drafts) *n_drafts = n;
+89 -2
View File
@@ -726,7 +726,20 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
sink_.staging = (unsigned long long) staging_;
sink_.staging_cap = kStagingBlobs;
(void) TS;
if (cudaStreamCreateWithFlags(&copy_, cudaStreamNonBlocking) != cudaSuccess) {
bool copy_made = false;
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
// engine-latency, STRATA_COPY_HIP_PRIO=1 (opt-in): the copy stream at high priority, so it gets a hardware queue of
// its own (ROCm hands queues out per priority). Sharing one with the window's stream, --pcie-mode dma's copies and
// their host function queue behind the window's graph, which spins on the flag they raise (a timeout at layer 1).
{
static const bool cp = [] { const char* v = std::getenv("STRATA_COPY_HIP_PRIO"); return v != nullptr && std::atoi(v) != 0; }();
int lo = 0, hi = 0;
if (cp && hipDeviceGetStreamPriorityRange(&lo, &hi) == hipSuccess)
copy_made = hipStreamCreateWithPriority(&copy_, hipStreamNonBlocking, hi) == hipSuccess;
(void) cudaGetLastError();
}
#endif
if (!copy_made && cudaStreamCreateWithFlags(&copy_, cudaStreamNonBlocking) != cudaSuccess) {
err = "verify: copy stream create failed";
return false;
}
@@ -1996,9 +2009,62 @@ bool Verifier::capture_commit(std::string& err) {
copy_i32_from_mapped(commit_, m_commit_, 2 + MT, cs_);
int64_t qsa_index = 0, gdn_index = 0;
for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
// engine-latency (STRATA_COMMIT_BATCH, default on; =0 keeps the per-layer loop): every GDN layer's conv history and
// state in two launches instead of two per layer (~70 graph nodes fewer; the same arithmetic per layer, bitwise).
// The commit runs between a window and the draft round, which on HIP waits for it.
static const bool commit_batch = [] { const char* e = std::getenv("STRATA_COMMIT_BATCH"); return !e || e[0] != '0'; }();
bool gdn_batched = false;
if (commit_batch) {
int64_t n_gdn = 0;
bool norms_ok = true; // the per-layer loop checks each layer's ssm_norm.weight: keep that check
for (int64_t l = lb_; l < le_ && norms_ok; ++l)
if (!is_qsa_layer(g, l)) {
++n_gdn;
norms_ok = need(LayerView(*wt_, l), "ssm_norm.weight", err) != nullptr;
}
if (!norms_ok) ok = false;
else if (n_gdn > 0)
gdn_batched = gdn_commit_layers(
ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats, (int64_t) gdn_floats,
(int64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size, qkv_L_ + (size_t) gdn_index * MT * C,
MT * C, h_L_ + (size_t) gdn_index * MT * C, MT * C, gate_L_ + (size_t) gdn_index * MT * HV,
beta_L_ + (size_t) gdn_index * MT * HV, MT * HV, (int) C, (int) g.ssm_k_heads, (int) HV, (int) MT,
(int) n_gdn, commit_, cs_);
}
// the QSA layers' tail restore + indexer append, one launch for all of them (one block per layer)
bool qsa_batched = false;
if (commit_batch && ok && !g_no_batch_kv) {
QsaIndexerLayers il;
int nq = 0;
int64_t mc = -1;
bool fits = true;
for (int64_t l = lb_, qi = qsa_index; l < le_ && fits; ++l) {
if (!is_qsa_layer(g, l)) continue;
const WeightRef* wikn = need(LayerView(*wt_, l), "indexer.k_norm.weight", err);
if (!wikn) { ok = false; fits = false; break; }
const QsaState& st = ss.qsa_states[qi];
if (nq >= QsaIndexerLayers::kMax || (mc >= 0 && st.max_cells != mc)) { fits = false; break; }
mc = st.max_cells;
il.gamma[nq] = (const float*) wikn->data;
il.tail_src[nq] = tail_snap_ + (size_t) qi * TS;
il.tail[nq] = st.idx_tail; il.dead[nq] = st.idx_dead; il.pooled[nq] = st.idx_pooled;
il.block_pos[nq] = st.idx_block_pos;
++nq;
++qi;
}
if (ok && fits && nq > 0) {
native_qsa_indexer_append_steps_layers(idx_raw_L_ + (size_t) qsa_index * MT * ID, MT * ID, commit_ + 2, 1,
(int) MT, 0, EPS, il, nq, s, mc, rope_scaling(), cs_);
qsa_batched = true;
}
}
for (int64_t l = lb_; l < le_ && ok; ++l) {
const LayerView v(*wt_, l);
if (!is_qsa_layer(g, l)) {
if (is_qsa_layer(g, l) && qsa_batched) {
++qsa_index;
} else if (!is_qsa_layer(g, l) && gdn_batched) {
++gdn_index;
} else if (!is_qsa_layer(g, l)) {
const WeightRef* wnm = need(v, "ssm_norm.weight", err);
if (!wnm) { ok = false; break; }
float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
@@ -2541,7 +2607,28 @@ bool Verifier::commit(int n_keep, std::string& err) {
// a one-token window has advanced the state itself (record_window): no commit graph
} else {
std::atomic_thread_fence(std::memory_order_seq_cst);
// STRATA_COMMIT_TIMING=1 (measurement only): the commit graph's GPU time, from an event pair around it (read at the
// next commit, when the pair has long completed); printed every 300 commits
static struct CommitTiming {
bool on = false, pending = false;
cudaEvent_t b = nullptr, e = nullptr;
double ms = 0;
int64_t n = 0;
CommitTiming() { const char* v = std::getenv("STRATA_COMMIT_TIMING"); on = v != nullptr && v[0] == '1'; }
} ct;
if (ct.on && ct.b == nullptr &&
(cudaEventCreate(&ct.b) != cudaSuccess || cudaEventCreate(&ct.e) != cudaSuccess)) { ct.on = false; (void) cudaGetLastError(); }
if (ct.on && ct.pending) {
float ms = 0;
if (cudaEventSynchronize(ct.e) == cudaSuccess && cudaEventElapsedTime(&ms, ct.b, ct.e) == cudaSuccess) { ct.ms += ms; ++ct.n; }
ct.pending = false;
if (ct.n > 0 && ct.n % 300 == 0)
std::fprintf(stderr, "strata verify: commit graph %.3f ms GPU on average over %lld commits\n", ct.ms / (double) ct.n,
(long long) ct.n);
}
if (ct.on) cudaEventRecord(ct.b, cs_);
const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_);
if (ct.on) { cudaEventRecord(ct.e, cs_); ct.pending = true; }
if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; }
// set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own
// stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's
+66 -2
View File
@@ -46,14 +46,14 @@ __device__ float warp_sum(float x) {
// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
// with it merely skipped at run time, the compiled default path changed its results).
template <bool TAB>
__global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev,
__device__ __forceinline__ void append_body(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev,
int pos_stride, int n_steps,
int pos_base, const float* __restrict__ gamma, float epsilon,
float* __restrict__ tail, float* __restrict__ dead,
float* __restrict__ pooled, int32_t* __restrict__ block_pos,
int max_cells, float theta_scale, float freq_scale, float corr_low,
float corr_high, float ext_factor, float mscale,
const int32_t* __restrict__ mtab, RopeTab rt) {
const int32_t* __restrict__ mtab, const RopeTab& rt) {
__shared__ float values[D];
__shared__ float partials[32];
const int d = threadIdx.x;
@@ -116,6 +116,35 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_
if (n_steps > 1) __syncthreads();
}
}
template <bool TAB>
__global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev,
int pos_stride, int n_steps,
int pos_base, const float* __restrict__ gamma, float epsilon,
float* __restrict__ tail, float* __restrict__ dead,
float* __restrict__ pooled, int32_t* __restrict__ block_pos,
int max_cells, float theta_scale, float freq_scale, float corr_low,
float corr_high, float ext_factor, float mscale,
const int32_t* __restrict__ mtab, RopeTab rt) {
append_body<TAB>(raw, pos_dev, pos_stride, n_steps, pos_base, gamma, epsilon, tail, dead, pooled, block_pos, max_cells,
theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, mtab, rt);
}
// engine-latency: the commit's appends of several QSA layers in one launch, one block per layer (blockIdx.x); each block
// first restores its layer's tail from the window's snapshot (the commit's copy_from_mapped), then runs append's body
template <bool TAB>
__global__ void append_layers(const float* __restrict__ raw0, long long raw_stride, const int32_t* __restrict__ pos_dev,
int pos_stride, int n_steps, int pos_base, float epsilon, QsaIndexerLayers L, int max_cells,
float theta_scale, float freq_scale, float corr_low, float corr_high, float ext_factor,
float mscale, const int32_t* __restrict__ mtab, RopeTab rt) {
const int i = blockIdx.x;
float* tail = L.tail[i];
if (L.tail_src[i] != nullptr) {
for (int j = threadIdx.x; j < (R - 1) * D; j += blockDim.x) tail[j] = L.tail_src[i][j];
__syncthreads();
}
append_body<TAB>(raw0 + (long long) i * raw_stride, pos_dev, pos_stride, n_steps, pos_base, L.gamma[i], epsilon, tail,
L.dead[i], L.pooled[i], L.block_pos[i], max_cells, theta_scale, freq_scale, corr_low, corr_high,
ext_factor, mscale, mtab, rt);
}
// ---- C-2: the batched append. The pooled key of a completed block b (its last cell pos = 4b+3), computed with
// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order,
// the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch
@@ -268,6 +297,41 @@ void native_qsa_indexer_append_steps(const float* raw, const int32_t* relative_p
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_qsa_indexer_append_steps_layers(const float* raw0, int64_t raw_stride, const int32_t* relative_pos_device,
int pos_stride, int n_steps, int32_t pos_base, float epsilon,
const QsaIndexerLayers& layers, int n_layers, const QsaShapes& s,
int64_t max_cells, const RopeScaling& scaling, void* stream) {
if (n_steps <= 0 || n_layers <= 0) return;
if (!stream || n_layers > QsaIndexerLayers::kMax || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT ||
max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R ||
int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f ||
rope_scaling_invalid(scaling) != nullptr)
throw std::invalid_argument("native QSA indexer (layers): bad geometry, layer count or parameters");
for (int i = 0; i < n_layers; ++i) { // the per-layer append's span checks, layer by layer
const std::size_t pos_span = (n_steps == 1 || pos_stride <= 0) ? 4 : (std::size_t(n_steps - 1) * pos_stride + 1) * 4;
const Span spans[] = {{raw0 + (std::size_t) i * (std::size_t) raw_stride, std::size_t(n_steps)*D*4},
{relative_pos_device,pos_span},{layers.gamma[i],D*4},{layers.tail[i],(R-1)*D*4},{layers.dead[i],D*4},
{layers.pooled[i],std::size_t(max_cells/R+1)*D*4},{layers.block_pos[i],4}};
for (const auto& span : spans) validate(span);
for (int a = 0; a < 7; ++a) for (int b = a + 1; b < 7; ++b)
if (overlaps(spans[a], spans[b])) throw std::invalid_argument("native QSA indexer buffers overlap");
}
const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT);
const RopeKernelArgs k = scaling.kernel_args(ROT);
const RopeTab rt = rope_table_for(scaling);
const cudaStream_t st = static_cast<cudaStream_t>(stream);
if (rt.cos != nullptr)
append_layers<true><<<n_layers, THREADS, 0, st>>>(raw0, (long long) raw_stride, relative_pos_device, pos_stride, n_steps,
pos_base, epsilon, layers, int(max_cells), theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor,
k.attn_factor, mrope_table(), rt);
else
append_layers<false><<<n_layers, THREADS, 0, st>>>(raw0, (long long) raw_stride, relative_pos_device, pos_stride, n_steps,
pos_base, epsilon, layers, int(max_cells), theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor,
k.attn_factor, mrope_table(), rt);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base,
const float* gamma, float epsilon, const QsaIndexerBuffers& b,
const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
+67
View File
@@ -172,6 +172,10 @@ __global__ void __launch_bounds__(S) gdn_conv_ab_kernel(int conv_blocks, float*
// (48 * 4 = 192 blocks of 128 threads across all SMs, vs 48 blocks of 512 threads), with no sq/o/norm/z/y work.
// DBG (STRATA_DBG_GDN=1, #937): a window count the launch never allowed (n_keep is read from device memory; n_max is the
// rows the window holds) is reported and the commit skipped, where the fault would be a memory-aperture violation
__device__ __forceinline__ void gdn_step_commit_body(float* __restrict__ state, const float* __restrict__ hbuf, int C,
const float* __restrict__ gate, const float* __restrict__ beta,
int h_k, int h_v, int n);
template <bool DBG>
__global__ void __launch_bounds__(32 * RG) gdn_step_commit_kernel(float* __restrict__ state,
const float* __restrict__ hbuf, int C,
@@ -186,6 +190,46 @@ __global__ void __launch_bounds__(32 * RG) gdn_step_commit_kernel(float* __restr
printf("strata DBG: gdn_step_commit: n_keep %d is past the window's %d rows: commit skipped (#937)\n", n, n_max);
return;
}
gdn_step_commit_body(state, hbuf, C, gate, beta, h_k, h_v, n);
}
// engine-latency: gdn_step_commit_kernel for every GDN layer of the commit in one launch (blockIdx.z = the layer); each
// layer's blocks run gdn_step_commit_body on that layer's state and rows, exactly as its own launch did
__global__ void __launch_bounds__(32 * RG) gdn_step_commit_layers_kernel(float* __restrict__ state, long long state_stride,
const float* __restrict__ hbuf, long long h_stride,
int C, const float* __restrict__ gate,
const float* __restrict__ beta, long long gb_stride,
int h_k, int h_v, const int32_t* __restrict__ n_keep) {
const int n = *n_keep;
if (n <= 0) return;
const long long z = blockIdx.z;
gdn_step_commit_body(state + z * state_stride, hbuf + z * h_stride, C, gate + z * gb_stride, beta + z * gb_stride, h_k,
h_v, n);
}
// engine-latency: gdn_conv_commit_kernel for every GDN layer in one launch (blockIdx.y = the layer)
__global__ void gdn_conv_commit_layers_kernel(float* __restrict__ hist0, long long hist_stride, const float* __restrict__ qkv0,
long long qkv_stride, int C, const int32_t* __restrict__ n_keep) {
const int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= C) return;
const int n = *n_keep;
if (n <= 0) return;
float* hist = hist0 + (long long) blockIdx.y * hist_stride;
const float* qkv = qkv0 + (long long) blockIdx.y * qkv_stride;
float seq[3];
#pragma unroll
for (int j = 0; j < 3; ++j) {
const int src = n + j; // the last three of [hist(3) | x_0..x_{n-1}]
seq[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];
}
hist[c * 3] = seq[0];
hist[c * 3 + 1] = seq[1];
hist[c * 3 + 2] = seq[2];
}
__device__ __forceinline__ void gdn_step_commit_body(float* __restrict__ state, const float* __restrict__ hbuf, int C,
const float* __restrict__ gate, const float* __restrict__ beta,
int h_k, int h_v, int n) {
__shared__ float sk[S];
__shared__ float red[RG][32];
const int head = blockIdx.x;
@@ -972,6 +1016,29 @@ void gdn_conv_commit(float* history, const float* qkv, int channels, const int32
check("gdn_conv_commit");
}
bool gdn_commit_layers(float* state, int64_t state_stride, int64_t conv_off, const float* qkv, int64_t qkv_stride,
const float* h, int64_t h_stride, const float* gate, const float* beta, int64_t gb_stride,
int conv_channels, int h_k, int h_v, int n_max, int n_layers, const int32_t* n_keep, void* stream) {
// the per-layer commit's kernel choice (gdn_step_norm_multi below): only its state-only kernel is batched here
static const bool per_layer = [] {
const char* sp = std::getenv("STRATA_GDN_SPLIT");
const char* cs = std::getenv("STRATA_GDN_COMMIT_SPLIT");
const char* dbg = std::getenv("STRATA_DBG_GDN");
return (sp && sp[0] == '1') || (cs && cs[0] == '0') || (dbg && dbg[0] == '1');
}();
if (per_layer || n_layers <= 0 || n_layers > 65535 || n_max < 1 || n_max > kVerifyMaxT || n_keep == nullptr ||
h_v <= 0 || h_k <= 0 || h_v % h_k != 0)
return false;
cudaStream_t st = (cudaStream_t) stream;
gdn_conv_commit_layers_kernel<<<dim3((unsigned) ((conv_channels + 255) / 256), (unsigned) n_layers), 256, 0, st>>>(
state + conv_off, (long long) state_stride, qkv, (long long) qkv_stride, conv_channels, n_keep);
gdn_step_commit_layers_kernel<<<dim3((unsigned) h_v, 4u, (unsigned) n_layers), dim3(32, RG), 0, st>>>(
state, (long long) state_stride, h, (long long) h_stride, conv_channels, gate, beta, (long long) gb_stride, h_k, h_v,
n_keep);
check("gdn_commit_layers");
return true;
}
void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream) {
if (n_embd % 8 != 0 || n_tok < 1 || n_tok > kVerifyMaxT) {
+64
View File
@@ -520,6 +520,70 @@ int main(int argc, char** argv) {
bad += ab_bad + sn_bad;
}
// ================= 6. the layer-batched commit (engine-latency), bitwise against the per-layer calls =================
// gdn_commit_layers runs every layer's conv-history commit and state commit in one launch each; the per-layer loop
// (gdn_conv_commit + gdn_step_norm_multi with n_keep, no outputs) is the reference. Several layers with their own
// state, rows and gate/beta; n_keep 1..T; memcmp on the whole state arena (states and conv histories).
{
const int qk = S * h_k, C = 2 * qk + S * h_v, L = 5, MT = strata::kernels::kVerifyMaxT;
const int64_t conv_off = (int64_t) S * h_v * S, stride = conv_off + (int64_t) C * 3;
std::vector<float> st0((size_t) (stride * L)), hb((size_t) L * MT * C), qkv((size_t) L * MT * C),
gt((size_t) L * MT * h_v), bt((size_t) L * MT * h_v), zdummy((size_t) MT * S * h_v), gm(S, 1.0f);
for (auto& x : st0) x = gauss(rng) * 0.1f;
for (auto& x : hb) x = gauss(rng) * 0.1f;
for (auto& x : qkv) x = gauss(rng);
for (auto& x : gt) x = -(0.5f + (float) (rng() % 100) / 50.0f);
for (auto& x : bt) x = (float) (rng() % 100) / 100.0f;
float *d_a = nullptr, *d_b = nullptr, *d_h = nullptr, *d_qkv = nullptr, *d_g = nullptr, *d_bt = nullptr,
*d_z = nullptr, *d_y = nullptr, *d_gm = nullptr;
int32_t* d_nk = nullptr;
check(cudaMalloc(&d_a, st0.size() * 4), "la"); check(cudaMalloc(&d_b, st0.size() * 4), "lb");
check(cudaMalloc(&d_h, hb.size() * 4), "lh"); check(cudaMalloc(&d_qkv, qkv.size() * 4), "lq");
check(cudaMalloc(&d_g, gt.size() * 4), "lg"); check(cudaMalloc(&d_bt, bt.size() * 4), "lbt");
check(cudaMalloc(&d_z, zdummy.size() * 4), "lz"); check(cudaMalloc(&d_y, zdummy.size() * 4), "ly");
check(cudaMalloc(&d_gm, gm.size() * 4), "lgm"); check(cudaMalloc(&d_nk, 4), "lnk");
check(cudaMemcpy(d_h, hb.data(), hb.size() * 4, cudaMemcpyHostToDevice), "lch");
check(cudaMemcpy(d_qkv, qkv.data(), qkv.size() * 4, cudaMemcpyHostToDevice), "lcq");
check(cudaMemcpy(d_g, gt.data(), gt.size() * 4, cudaMemcpyHostToDevice), "lcg");
check(cudaMemcpy(d_bt, bt.data(), bt.size() * 4, cudaMemcpyHostToDevice), "lcb");
check(cudaMemcpy(d_gm, gm.data(), gm.size() * 4, cudaMemcpyHostToDevice), "lcm");
check(cudaMemset(d_z, 0, zdummy.size() * 4), "lz0");
int lb_bad = 0, lb_n = 0;
bool launched = true;
for (int nk = 1; nk <= MT && launched; ++nk) {
check(cudaMemcpy(d_nk, &nk, 4, cudaMemcpyHostToDevice), "lnk1");
check(cudaMemcpy(d_a, st0.data(), st0.size() * 4, cudaMemcpyHostToDevice), "lca");
check(cudaMemcpy(d_b, st0.data(), st0.size() * 4, cudaMemcpyHostToDevice), "lcb2");
for (int l = 0; l < L; ++l) { // the reference: the per-layer calls
float* stl = d_a + (size_t) l * stride;
strata::kernels::gdn_conv_commit(stl + conv_off, d_qkv + (size_t) l * MT * C, C, d_nk, nullptr);
strata::kernels::gdn_step_norm_multi(stl, d_h + (size_t) l * MT * C, C, d_g + (size_t) l * MT * h_v,
d_bt + (size_t) l * MT * h_v, d_z, d_gm, 1e-6f, d_y, h_k, h_v, MT, d_nk,
nullptr, MT);
}
launched = strata::kernels::gdn_commit_layers(d_b, stride, conv_off, d_qkv, (int64_t) MT * C, d_h, (int64_t) MT * C,
d_g, d_bt, (int64_t) MT * h_v, C, h_k, h_v, MT, L, d_nk, nullptr);
if (!launched) break;
check(cudaDeviceSynchronize(), "lsync");
std::vector<float> a(st0.size()), b(st0.size());
check(cudaMemcpy(a.data(), d_a, a.size() * 4, cudaMemcpyDeviceToHost), "lda");
check(cudaMemcpy(b.data(), d_b, b.size() * 4, cudaMemcpyDeviceToHost), "ldb");
++lb_n;
if (std::memcmp(a.data(), b.data(), a.size() * 4) != 0 || std::memcmp(a.data(), st0.data(), a.size() * 4) == 0) {
std::printf(" *** gdn_commit_layers n_keep=%d differs from the per-layer commit (or wrote nothing) ***\n", nk);
++lb_bad;
}
}
cudaFree(d_a); cudaFree(d_b); cudaFree(d_h); cudaFree(d_qkv); cudaFree(d_g); cudaFree(d_bt); cudaFree(d_z);
cudaFree(d_y); cudaFree(d_gm); cudaFree(d_nk);
if (launched)
std::printf(" %-42s %s (%d cases, %d layers)\n", "gdn_commit_layers == per-layer commit", lb_bad ? "*** NO ***" : "bitwise",
lb_n, L);
else
std::printf(" %-42s skipped (the per-layer commit is not the state-only kernel here)\n", "gdn_commit_layers");
bad += lb_bad;
}
std::printf("\ngdn: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("gdn_parity OK\n");
+54
View File
@@ -1455,6 +1455,60 @@ int main(int argc, char** argv) {
same ? "bit-identical" : "*** WRONG ***");
if (!same) ++g_bad;
}
// engine-latency: native_qsa_indexer_append_steps_layers - the commit's tail restore + append for several
// layers in one launch - against the per-layer copy + append_steps (3 layers, each its own raw rows, tail
// snapshot and buffers; cells 2..NB+1 so the first completed block reads the restored tail)
{
constexpr int NL = 3;
Dev<float> pr[NL], dr[NL], tr[NL], pl[NL], dl[NL], tl[NL], src[NL];
Dev<int32_t> br[NL], bl[NL];
for (int i = 0; i < NL; ++i) {
pr[i].alloc(prows); dr[i].alloc((size_t) IDXD); tr[i].alloc(trows);
pl[i].alloc(prows); dl[i].alloc((size_t) IDXD); tl[i].alloc(trows);
br[i].alloc(1); bl[i].alloc(1);
std::vector<float> ts(trows);
for (auto& x : ts) x = (float) gauss(rng);
src[i].put(ts);
}
for (int i = 0; i < NL; ++i) {
check(cudaMemset(pr[i].p, 0, prows * 4), "z"); check(cudaMemset(pl[i].p, 0, prows * 4), "z");
check(cudaMemset(dr[i].p, 0, IDXD * 4), "z"); check(cudaMemset(dl[i].p, 0, IDXD * 4), "z");
check(cudaMemset(tr[i].p, 0, trows * 4), "z"); check(cudaMemset(tl[i].p, 0, trows * 4), "z");
check(cudaMemset(br[i].p, 0, 4), "z"); check(cudaMemset(bl[i].p, 0, 4), "z");
}
std::vector<float> rawL((size_t) NL * NB * IDXD);
for (auto& x : rawL) x = (float) gauss(rng);
Dev<float> drawL;
drawL.put(rawL);
Dev<int32_t> dposL((size_t) NB);
std::vector<int32_t> hp((size_t) NB);
for (int64_t t = 0; t < NB; ++t) hp[(size_t) t] = (int32_t) (2 + t);
check(cudaMemcpy(dposL.p, hp.data(), hp.size() * 4, cudaMemcpyHostToDevice), "pos");
strata::kernels::QsaIndexerLayers il;
for (int i = 0; i < NL; ++i) { // the reference: copy + append_steps, layer by layer
check(cudaMemcpyAsync(tr[i].p, src[i].p, trows * 4, cudaMemcpyDeviceToDevice, cs), "cp");
strata::kernels::QsaIndexerBuffers b{tr[i].p, dr[i].p, pr[i].p, br[i].p};
strata::kernels::native_qsa_indexer_append_steps(drawL.p + (size_t) i * NB * IDXD, dposL.p, 1, (int) NB, BASE,
dw_kn.p, EPS, b, S, MC, sc, cs);
il.gamma[i] = dw_kn.p; il.tail_src[i] = src[i].p; il.tail[i] = tl[i].p; il.dead[i] = dl[i].p;
il.pooled[i] = pl[i].p; il.block_pos[i] = bl[i].p;
}
strata::kernels::native_qsa_indexer_append_steps_layers(drawL.p, (int64_t) NB * IDXD, dposL.p, 1, (int) NB, BASE,
EPS, il, NL, S, MC, sc, cs);
check(cudaStreamSynchronize(cs), "sync");
bool same = true;
for (int i = 0; i < NL; ++i) {
const std::vector<float> a1 = pr[i].get(prows), b1 = pl[i].get(prows), a2 = dr[i].get((size_t) IDXD),
b2 = dl[i].get((size_t) IDXD), a3 = tr[i].get(trows), b3 = tl[i].get(trows);
const std::vector<int32_t> a4 = br[i].get(1), b4 = bl[i].get(1);
same = same && std::memcmp(a1.data(), b1.data(), a1.size() * 4) == 0 &&
std::memcmp(a2.data(), b2.data(), a2.size() * 4) == 0 &&
std::memcmp(a3.data(), b3.data(), a3.size() * 4) == 0 && a4[0] == b4[0];
}
std::printf(" %-44s %s\n", (std::string("append_steps_layers (3) vs per layer, ") + var.name).c_str(),
same ? "bit-identical" : "*** WRONG ***");
if (!same) ++g_bad;
}
check(cudaStreamSynchronize(cs), "sync");
const std::vector<float> pa = pooledA.get(prows), pb = pooledB.get(prows);
const std::vector<float> da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD);