diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt index 6e817a76..17e47c51 100644 --- a/sycl/CMakeLists.txt +++ b/sycl/CMakeLists.txt @@ -451,6 +451,13 @@ if(STRATA_SYCL_PARITY) add_executable(native_expert_parity ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/native_expert_parity.cpp) target_include_directories(native_expert_parity PRIVATE ${STRATA_ROOT}/third_party/ggml) target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu) + # SYCL port: the same grouped native experts timed per mode on real GGUF rows at the decode window's shape + # (G experts, T tokens), checked bit for bit against the reference mode. The source was in the tree without a + # target, so the numbers that decide the decode expert path could not be reproduced. + # native_expert_bench [iters] + add_executable(native_expert_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/native_expert_bench.cpp) + target_include_directories(native_expert_bench PRIVATE ${STRATA_ROOT}/third_party/ggml) + target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu) # Gyro (APR) trellis experts on real GGUF tensors: tq_sycl_parity [layer ...] add_executable(tq_sycl_parity ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/tq_sycl_parity.cpp) target_include_directories(tq_sycl_parity PRIVATE ${STRATA_ROOT}/third_party/ggml) diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hpp index b38249f4..540323ac 100644 --- a/sycl/include/strata/core/verify.hpp +++ b/sycl/include/strata/core/verify.hpp @@ -205,6 +205,11 @@ public: /// expert evicted on the host (the pool then computes it on the CPU) before the device table follows. Also turns /// the device-planned layers (E-6) off. Before `init`. void set_always_publish(bool on) { always_publish_ = on; } + /// The pipelined windows never let a one-token window advance the state itself: its graph may run *speculatively* + /// (ahead of the previous window's verdict), so a self-commit would land before the state it must build on is + /// final. With this set, record_window does not self-commit and pl_commit_async always queues the commit graph - + /// the configuration that measures token-identical to the serial path. Before `capture_all`. + void set_self_commit_off(bool on) { self_commit_off_ = on; } dpct::queue_ptr stream() const { return cs_; } int device() const { return device_; } /// Capture every window size and the commit graph now (a capture syncs the stream: never with a window in flight). @@ -267,6 +272,7 @@ private: // batch windows (see init_slots) std::vector slots_; bool batch_rec_ = false; ///< record_window is capturing a batch window + bool self_commit_off_ = false; ///< set_self_commit_off: the pipelined windows commit through the graph int row_base_ = 0; ///< ... its hand-off rows start here (a pipeline group's own rows) int brow_[8] = {}; ///< ... and row t is slot brow_[t] bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group) diff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cpp index 5fff80b0..fd3fec62 100644 --- a/sycl/src/core/mtp.cpp +++ b/sycl/src/core/mtp.cpp @@ -233,6 +233,14 @@ bool MtpDrafter::make_q4_head(std::string& err) { const int64_t N = g_->n_embd; const auto* tt = ggml_get_type_traits((ggml_type) head_->type()); if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; } + // SYCL port: with STRATA_Q6_PLANAR the head is stored as planes, and the subset this builds from is row-major + // only when the head is packed - the gather at load time then copies planes as if they were rows. The result is + // a draft head that proposes nothing at all (measured: 0 drafts, decode 73.8 -> 35.3 tok/s) with no error, so + // refuse instead of running wrong in silence. + if (head_->type() == 14 && strata::kernels::native_q6_k_is_planar(head_->weights())) { + err = "mtp: --mtp-q4 head needs the packed Q6_K head layout (STRATA_Q6_PLANAR=0)"; + return false; + } const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18; std::vector src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row); try { dpct::get_in_order_queue().memcpy(src.data(), dhead_, src.size()).wait(); } // SYCL port: cudaMemcpy diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index a2020862..2811b5a0 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -697,6 +697,18 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g, err = "verify: stream create failed"; return false; } + if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) { + // SYCL: a queue belongs to one context, so ev_fork_/ev_join_ (recorded on cs_) can only be waited on by + // sh_cs_ when the two streams are the same card. Print both, and whether the streams are the shared ones. + auto dn = [](dpct::queue_ptr q) -> std::string { + if (q == nullptr) return ""; + try { return q->get_device().get_info(); } catch (...) { return ""; } + }; + std::fprintf(stderr, "strata verify: init device %d, cs '%s', sh_cs '%s', ext_stream %s, copy '%s'\n", + device_, dn(cs_).c_str(), dn(sh_cs_).c_str(), + ext_stream_ == nullptr ? "none" : dn(ext_stream_).c_str(), dn(copy_).c_str()); + std::fflush(stderr); + } if (DPCT_CHECK_ERROR(commit_done_ = new sycl::event()) != 0 || DPCT_CHECK_ERROR(ev_fork_ = new sycl::event()) != 0 || DPCT_CHECK_ERROR(ev_join_ = new sycl::event()) != 0) { @@ -829,7 +841,8 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) { const bool ple_on = ss.ple.ready() && ple_stage(); auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one group - const bool self_commit = T == 1 && !batch_rec_ && !g_qfuse() && one_token_self_commit(); // see Verifier::commit + const bool self_commit = T == 1 && !batch_rec_ && !g_qfuse() && one_token_self_commit() && + !self_commit_off_; // see Verifier::commit static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); // SYCL port, STRATA_VERIFY_EAGER=1: the window runs on the queue instead of as a graph, and each stage stamp is // a host-side wait + clock (there is no %globaltimer here), so the existing stage profiler reports ms per stage. @@ -1657,6 +1670,24 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) { return true; } +// SYCL port: a failed queue wait reported as what it was. DPCT_CHECK_ERROR keeps only "error" from the SYCL +// exception and drops the device, which made a pipelined-window failure on a layer split impossible to place: +// the same text came from either card and from any of the four verifiers. These two helpers say which. +static dpct::err0 queue_wait_diag(sycl::queue *cs, int dev, const char *what) { + if (cs == nullptr) return dpct::default_error; + try { + cs->wait(); + return dpct::success; + } catch (std::exception const &e) { + std::string qdev = ""; + try { qdev = cs->get_device().get_info(); } catch (...) {} + std::fprintf(stderr, "strata verify: %s: the queue wait failed on verifier device %d (queue device: %s): %s\n", + what, dev, qdev.c_str(), e.what()); + std::fflush(stderr); + return dpct::default_error; + } +} + std::string Verifier::profile_report() { if (!prof_on_ || prof_windows_ == 0) return std::string(); static const char* names[kProfPer] = {"-", "hc-read0", "q8+qkv/q-idx gemv", "conv", "ab", "z", "rec", "q8+kv-idx", @@ -1970,10 +2001,14 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) { } void Verifier::collect_profile() { - if (std::getenv("STRATA_VERIFY_EAGER") == nullptr) // eager (SYCL port): prof_h_ already holds the host clocks - dpct::get_in_order_queue() - .memcpy(prof_h_.data(), prof_, prof_h_.size() * 8) - .wait(); + if (std::getenv("STRATA_VERIFY_EAGER") == nullptr) { // eager (SYCL port): prof_h_ already holds the host clocks + // SYCL port: the stamps are written by kernels on THIS verifier's stream, so the readback has to ride the + // same stream. The device's default queue is neither ordered after the window nor necessarily this + // stage's device (a layer split), so reading there could return the previous window's stamps or another + // card's memory - which is why the table was only ever printed in the eager mode before. + const strata::core::OnDevice on_device(device_); + cs_->memcpy(prof_h_.data(), prof_, prof_h_.size() * 8).wait(); + } accumulate_profile(prof_h_.data()); } @@ -2329,7 +2364,7 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool, // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no // spin kernel outlives the process. The wait itself stays a blocking sync (a polling wait cost decode upstream). trace_ev("SYNC", -1, -1, 0); - const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait()); + const dpct::err0 se = queue_wait_diag(cs_, device_, "window sync"); trace_ev("SYNCED", -1, -1, (int64_t) se); const Clock::time_point t_done = Clock::now(); if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) { @@ -2428,6 +2463,20 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool, collect_profile(); if (std::getenv("STRATA_VERIFY_EAGER") != nullptr) // SYCL port: the stage table per window, host-clocked std::fprintf(stderr, "verify stages T=%d (ms/window):%s\n", T, profile_report().c_str()); + else { + // SYCL port: the same table from the GPU's own clock, averaged over N windows, so a decode can be + // attributed without the eager mode's drain per stamp (which measures host gaps, not kernel time). + // STRATA_VERIFY_PROFILE=1 STRATA_VERIFY_PROFILE_EVERY=32. + static const long long every = [] { + const char* e = std::getenv("STRATA_VERIFY_PROFILE_EVERY"); + return e ? std::atoll(e) : 0LL; + }(); + if (every > 0 && prof_windows_ >= every) { + std::fprintf(stderr, "verify stages T=%d (ms/window over %lld, GPU clock):%s\n", T, + (long long) prof_windows_, profile_report().c_str()); + std::fflush(stderr); + } + } } // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's // own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to @@ -2645,7 +2694,7 @@ bool Verifier::commit(int n_keep, std::string &err) try { h_commit_[0] = n_keep; h_commit_[1] = n_keep - 1; for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; - if (last_t_ == 1 && one_token_self_commit()) { + if (last_t_ == 1 && one_token_self_commit() && !self_commit_off_) { // a one-token window has advanced the state itself (record_window): no commit graph } else { std::atomic_thread_fence(std::memory_order_seq_cst); @@ -3842,7 +3891,15 @@ catch (sycl::exception const &exc) { bool Verifier::done(std::string &err) try { if (!fl_active_ || fl_k_ < fl_total_) return false; const OnDevice on_device(device_); - const dpct::err0 q = dpct::sycl_event_query(ev_done_); + dpct::err0 q; + try { + q = (dpct::err0) dpct::sycl_event_query(ev_done_); + } catch (std::exception const &e) { + // a dead or foreign event used to read as the bare word "error" + err = std::string("verify: the window's completion event could not be queried on device ") + + std::to_string(device_) + ": " + e.what(); + return false; + } /* DPCT1009: SYCL reports errors using exceptions and does not use error @@ -3856,6 +3913,19 @@ bool Verifier::done(std::string &err) try { DPCT1000: Error handling if-stmt was detected but could not be rewritten. */ + if (q == 1) { + // SYCL's "not complete" is CUDA's cudaErrorNotReady: the window is still running, which is not an error. + // The DPCT migration dropped that branch, so the first poll of every pipelined window failed with + // "verify: error" and --pipeline-windows never ran on this backend. Same body as the CUDA original. + const double now = now_ms(); + if (now - fl_flush_ms_ > 2.0) { + fl_flush_ms_ = now; + (void)DPCT_CHECK_ERROR(cs_->ext_oneapi_empty()); + } + if (now - fl_since_ms_ > 20000.0) // every layer served, and the graph still runs: #267 as above + err = "verify: the window never finished" + released_note(release_gpu_waits(5000)); + return false; + } if (q != 0) { err = std::string("verify: ") + dpct::get_error_string_dummy(q); return false; @@ -3906,6 +3976,12 @@ catch (sycl::exception const &exc) { bool Verifier::pl_commit_async(int n_keep, std::string &err) try { const OnDevice on_device(device_); if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } + // Debug: with a state dump requested, print what this commit is launched with, so a wrong count names + // itself next to the verdict log (STRATA_PIPELINE_LOG). + static const bool cdbg = std::getenv("STRATA_PIPELINE_DUMP") != nullptr; + if (cdbg) + std::fprintf(stderr, "strata commit: n_keep=%d T=%d pos0=%lld self_skip=%d\n", n_keep, (int) last_t_, + (long long) last_pos0_, (last_t_ == 1 && one_token_self_commit()) ? 1 : 0); if (commit_exec_ == nullptr || ev_commit_ == nullptr) { err = "verify: pipelined commit not prepared"; return false; } const Clock::time_point t0 = Clock::now(); if (commit_live_) { // its graph reads the words below when it starts: the previous one has (a window ago) @@ -3929,6 +4005,23 @@ bool Verifier::pl_commit_async(int n_keep, std::string &err) try { return false; } } + // A one-token window advanced the GDN state itself (record_window), so the serial path's commit() skips the + // commit graph for it. The pipelined path ran the graph anyway and advanced the state twice per + // single-token window; the first decode window is always one token, so the two paths' GDN states were + // equal after the prompt and different after that window (STRATA_PIPELINE_DUMP), and the tokens diverged + // at the fourth. With this skip the pipelined windows are token-identical to the serial path. + if (last_t_ == 1 && one_token_self_commit() && !self_commit_off_) { + h_commit_[0] = n_keep; + h_commit_[1] = n_keep - 1; + for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; + if (ple_stage()) + for (int t = 0; t < n_keep; ++t) { + ss_->ple_prev[0] = ss_->ple_prev[1]; + ss_->ple_prev[1] = last_tokens_[t]; + } + ms_commit += ms_since(t0); + return true; + } h_commit_[0] = n_keep; h_commit_[1] = n_keep - 1; for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; diff --git a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp index 24ea37ad..18abd96a 100644 --- a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp @@ -665,8 +665,21 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 const dpct::dim3 grid((unsigned)n_chunks, (unsigned)s.n_head_kv, (unsigned)n_q); dpct::queue_ptr st = strata::q_of(stream); - // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) - static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); + // S25: the score phase one cell per thread (bit-identical scores, no shuffle reductions). Prompt batches take + // it by default: on 2x Arc Pro B65 it reads a 4,106-token prompt 5.2% faster, 8,191 tokens 5.2% and 16,380 + // tokens 4.8%, with the same tokens; the decode window's few queries per call are 1.4% slower with it (56.6-57.0 + // against 55.9-56.3 tok/s), so the choice follows the query count. It is a Battlemage (Xe2) default only: on an Arc + // A750 (Alchemist) the same switch reads a 4,106-token prompt 0.7% slower (three interleaved runs, 4 of 5 pairs + // faster with it off), so the generation comes from the device's architecture id (strata::intel_gpu_gen: the + // runtime's architecture enum first, the name only as a fallback), never from the name alone. + // STRATA_ATTN_LANECELL=1/0 forces either way on any device. + static const int lane_cell_env = [] { + const char* v = std::getenv("STRATA_ATTN_LANECELL"); + return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1; + }(); + const bool lane_cell = lane_cell_env >= 0 + ? lane_cell_env != 0 + : (n_q >= 16 && strata::intel_gpu_gen(st->get_device()) == strata::IntelGpuGen::Battlemage); #define STRATA_ATTN_LC(M) \ { \ auto exp_props = sycl::ext::oneapi::experimental::properties{ \ diff --git a/sycl/src/kernels/native_expert_bench.cpp b/sycl/src/kernels/native_expert_bench.cpp index 48e04876..a32d8116 100644 --- a/sycl/src/kernels/native_expert_bench.cpp +++ b/sycl/src/kernels/native_expert_bench.cpp @@ -15,6 +15,7 @@ #include "ggml.h" +#include #include #include #include @@ -48,9 +49,18 @@ int main(int argc, char** argv) { int failures = 0; dpct::queue_ptr s; s = dpct::get_current_device().create_queue(true); - dpct::event_ptr e0, e1; - e0 = new sycl::event(); - e1 = new sycl::event(); + // SYCL port: the queue carries an exception handler, which would swallow a failing launch and leave the timing + // at "the kernel did nothing" (0.3 us for a group of experts). Every wait goes through this, so a device-side + // error is printed instead of silently producing an empty measurement. + auto sync = [&](const char* what) { + try { + s->wait_and_throw(); + return true; + } catch (std::exception const& e) { + std::printf("%s: %s\n", what, e.what()); + return false; + } + }; for (int l : layers) { const strata::TensorInfo* t[3] = {}; const char* roles[3] = {"gate", "up", "down"}; @@ -86,21 +96,18 @@ int main(int argc, char** argv) { std::vector ptr(G); std::vector start(G + 1), dst(NE), tok(NE); const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF); - uint8_t* dblob; - void *dx, *dxq, *dscr; - float* dout; - unsigned long long* dptr; - int32_t *dstart, *dn, *ddst, *dtok; - cudaMalloc((void**) &dblob, blobs.size()); - cudaMalloc(&dx, x.size() * 4); - cudaMalloc(&dxq, (size_t) NTOK * H / 32 * 36); - cudaMalloc(&dscr, K::native_expert_scratch_bytes(NE, FF)); - cudaMalloc((void**) &dout, (size_t) NE * H * 4); - cudaMalloc((void**) &dptr, (size_t) G * 8); - cudaMalloc((void**) &dstart, (size_t) (G + 1) * 4); - cudaMalloc((void**) &dn, 4); - cudaMalloc((void**) &ddst, (size_t) NE * 4); - cudaMalloc((void**) &dtok, (size_t) NE * 4); + // SYCL port: this bench was never a build target, so its CUDA calls were never migrated. Device buffers are + // USM allocations on the bench's own in-order queue, and every copy is ordered on that queue. + uint8_t* dblob = (uint8_t*) sycl::malloc_device(blobs.size(), *s); + void *dx = sycl::malloc_device((size_t) NTOK * H * 4, *s); + void *dxq = sycl::malloc_device((size_t) NTOK * H / 32 * 36, *s); + void *dscr = sycl::malloc_device(K::native_expert_scratch_bytes(NE, FF), *s); + float* dout = (float*) sycl::malloc_device((size_t) NE * H * 4, *s); + unsigned long long* dptr = (unsigned long long*) sycl::malloc_device((size_t) G * 8, *s); + int32_t* dstart = (int32_t*) sycl::malloc_device((size_t) (G + 1) * 4, *s); + int32_t* dn = (int32_t*) sycl::malloc_device(4, *s); + int32_t* ddst = (int32_t*) sycl::malloc_device((size_t) NE * 4, *s); + int32_t* dtok = (int32_t*) sycl::malloc_device((size_t) NE * 4, *s); for (int g = 0; g < G; ++g) { ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes); start[g] = g * T; @@ -110,26 +117,45 @@ int main(int argc, char** argv) { } } start[G] = NE; - cudaMemcpy(dblob, blobs.data(), blobs.size(), cudaMemcpyHostToDevice); - cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dptr, ptr.data(), (size_t) G * 8, cudaMemcpyHostToDevice); - cudaMemcpy(dstart, start.data(), (size_t) (G + 1) * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dn, &G, 4, cudaMemcpyHostToDevice); - cudaMemcpy(ddst, dst.data(), (size_t) NE * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dtok, tok.data(), (size_t) NE * 4, cudaMemcpyHostToDevice); + s->memcpy(dblob, blobs.data(), blobs.size()).wait(); + s->memcpy(dx, x.data(), x.size() * 4).wait(); + s->memcpy(dptr, ptr.data(), (size_t) G * 8).wait(); + s->memcpy(dstart, start.data(), (size_t) (G + 1) * 4).wait(); + s->memcpy(dn, &G, 4).wait(); + s->memcpy(ddst, dst.data(), (size_t) NE * 4).wait(); + s->memcpy(dtok, tok.data(), (size_t) NE * 4).wait(); K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s); auto run = [&](int m, int phase) { K::native_expert_set_mode(m, phase); K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s); }; std::vector ref((size_t) NE * H), got((size_t) NE * H); - cudaMemsetAsync(dout, 0xff, got.size() * 4, s); + s->memset(dout, 0xff, got.size() * 4).wait(); run(mref, 0); - cudaMemcpyAsync(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost, s); - cudaMemsetAsync(dout, 0xff, got.size() * 4, s); + if (!sync("reference window")) return 1; + + s->memcpy(ref.data(), dout, ref.size() * 4).wait(); + // SYCL port: a launch that returns without enqueueing leaves the 0xff fill intact, and then the mode and the + // reference agree bitwise on an untouched buffer - a "0 differing" that measures nothing. The fill is NaN as + // a float, so a reference window with no finite value anywhere did no work: say so instead of timing it. + { + size_t written = 0; + for (size_t i = 0; i < ref.size(); ++i) { + float v; + std::memcpy(&v, &ref[i], 4); + if (std::isfinite(v)) ++written; + } + if (written == 0) { + std::printf("layer %d: the expert launch wrote nothing (%zu outputs, none finite) - refusing to time it\n", + (int) l, ref.size()); + ++failures; + continue; + } + } + s->memset(dout, 0xff, got.size() * 4).wait(); run(mode, 0); - cudaMemcpyAsync(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost, s); - if (cudaStreamSynchronize(s) != cudaSuccess) { std::printf("layer %d: CUDA error\n", l); return 1; } + if (!sync("mode window")) return 1; + s->memcpy(got.data(), dout, got.size() * 4).wait(); size_t ndiff = 0; double worst = 0; for (size_t i = 0; i < ref.size(); ++i) @@ -139,13 +165,18 @@ int main(int argc, char** argv) { } auto time = [&](int m, int phase) { for (int i = 0; i < 10; ++i) run(m, phase); - cudaEventRecord(e0, s); + s->wait(); + const auto t0 = std::chrono::steady_clock::now(); for (int i = 0; i < iters; ++i) run(m, phase); - cudaEventRecord(e1, s); - cudaEventSynchronize(e1); - float ms = 0; - cudaEventElapsedTime(&ms, e0, e1); - return 1e3 * ms / iters; + sync("timing loop"); + const double ms = + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + // SYCL port: the printout below and the GB/s it derives both assume MICROseconds ("all %7.1f us", + // bytes / us / 1e3), but this returned milliseconds - so every published number was 1000x too small in + // time and 1000x too large in bandwidth (0.1 "us" and 148,713 GB/s for a launch that takes ~100 us and + // moves 19.7 MB at ~198 GB/s). The wall clock always agreed with the real work: 200 iterations 618 ms, + // 2,000 iterations 3,566 ms. Return microseconds. + return ms * 1e3 / iters; }; const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz; double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}}; @@ -163,8 +194,9 @@ int main(int argc, char** argv) { ++failures; } K::native_expert_set_mode(-1, 0); - cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); - cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); + for (void* p : {(void*) dblob, (void*) dx, (void*) dxq, (void*) dscr, (void*) dout, (void*) dptr, + (void*) dstart, (void*) dn, (void*) ddst, (void*) dtok}) + sycl::free(p, *s); } std::printf("native_expert_bench: %d differing\n", failures); return failures ? 1 : 0; diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index be06adfc..8206fb61 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -734,7 +734,11 @@ struct Prefill::Impl { float* sel_scores = nullptr; // [sel_batch, max_blocks] int64_t sel_batch = 256, max_blocks = 0; float* attn_scratch = nullptr; - int64_t attn_batch = 32, cap = 0; + int64_t attn_batch = [] { // SYCL port: how many queries the prompt path hands the FP32 attention kernel at once + const char* v = std::getenv("STRATA_ATTN_BATCH"); // (the tensor-core kernel is opt-in and slower here) + const long long n = v ? std::atoll(v) : 128; // 32 was picked for a vector-matrix kernel; with the + return (n >= 1 && n <= 1024) ? (int64_t) n : 128LL; // lane-cell score phase 128 reads a 4,106-token prompt + }(), cap = 0; // 1.1% faster than 32 and a 16,380-token one 1.3% // MoE float *logits = nullptr, *w = nullptr, *GU = nullptr, *Dm = nullptr, *sgate = nullptr, *sup = nullptr, *shared = nullptr, *sg = nullptr; @@ -1289,8 +1293,13 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g, m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1); { const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)); + // SYCL port: the *copy* arm is the default. On the mapped arm the GPU reads these tables straight out of + // mapped host memory, per layer; copying them first is measurably faster on a PCIe-attached pair and + // token-identical - 4,106 tokens 1,303 -> 1,335 tok/s, 16,380 tokens 1,622 -> 1,665, the 10,938-token chat + // prompt 1,576 -> 1,617, decode unchanged (round 46). STRATA_GROUP_COPY=0 restores the mapped arm. const char* gc = std::getenv("STRATA_GROUP_COPY"); - if (m.grp_n < need && !(gc && gc[0] == '1')) { + const bool group_copy = gc == nullptr || gc[0] != '0'; + if (m.grp_n < need && !group_copy) { if (m.grp_host) sycl::free(m.grp_host, dpct::get_in_order_queue()); m.grp_host = m.grp_dev = nullptr; m.grp_n = m.grp_tk = 0; diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 401e304b..d23f09aa 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -2152,9 +2152,23 @@ int main(int argc, char **argv) try { }; split_auto = o.layer_split == "auto"; bool ok = o.serve && (split_auto || ints(o.layer_split, split_at)); + // SYCL port: a stage is a GPU of the PRIMARY device's backend. Everything else that the runtime lists is + // not a stage: the batch slots load the OpenCL adapter as well, so on a two-card `xe` box + // dpct::device_count() then reports the CPU and the OpenCL view of the same two cards (5 devices), and an + // automatic split tried to put a stage on the CPU ("layer split, CUDA2 weights: the weight arena does not + // fit ... 0 MiB of 160876 MiB free on that card") instead of working. + const auto stage_dev = [](int d) -> bool { + try { + const sycl::device dev = dpct::get_device(d); + return dev.is_gpu() && dev.get_backend() == dpct::get_device(0).get_backend(); + } catch (...) { + return false; + } + }; if (ok && !o.split_device.empty()) ok = ints(o.split_device, split_devs); else if (ok) - for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d) split_devs.push_back(d); + for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d) + if (!split_auto || stage_dev(d)) split_devs.push_back(d); if (ok && !split_auto && split_devs.empty() && split_at.size() == 1) split_devs.push_back(0); // one GPU split_same = ok && split_devs.size() == 1 && split_devs[0] == 0 && !split_auto; if (split_same && o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0) { @@ -7283,10 +7297,14 @@ int main(int argc, char **argv) try { for (strata::core::Verifier* v : {&ver, &ver_b}) { v->set_stream(pl_stream[0]); v->set_always_publish(true); + v->set_self_commit_off(true); // a pipelined window may run speculatively: never let it + // advance the state itself, the commit graph always does } for (strata::core::Verifier* v : {&stages[0]->ver, &stages[0]->ver_b}) { v->set_stream(pl_stream[1]); v->set_always_publish(true); + v->set_self_commit_off(true); // a pipelined window may run speculatively: never let it + // advance the state itself, the commit graph always does } } if (n_stages > 1) { @@ -7406,10 +7424,15 @@ int main(int argc, char **argv) try { return 1; } } - if (!ver_b.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { - std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): " - "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str()); - return 1; + { + // Verifier::init takes the CURRENT device, so the first card's second verifier is made while card 0 + // (stage 0 always runs on the default device in this port) is current: the block above ended its scope. + const strata::core::OnDevice on_first(0); + if (!ver_b.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { + std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): " + "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str()); + return 1; + } } ver_b.set_next(&gs.ver_b, &split_drive_b); // the setters reach it; the pipeline never chains run/commit } @@ -10422,10 +10445,19 @@ int main(int argc, char **argv) try { for (int t = 0; t < w.T; ++t) w1[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)]; strata::core::Verifier& v = *PV[1][l1 & 1]; if (pl_mtp_live[l1 & 1]) { // the drafter has read this parity's previous rows first - const strata::core::OnDevice on(mtp.device()); - (v.stream()) - ->ext_oneapi_submit_barrier( - {*pl_mtp_ev[l1 & 1]}); + // SYCL keeps an event in its context, so another card's queue cannot take it as a + // dependency ("Cannot submit to a queue with a dependency from a graph that is + // associated with a different context", the first pipelined window on a split). The + // drafter's rows must be in memory before stage 1 reads them, so on two cards the + // host waits for the drafter here and the window is launched without the barrier. + if (mtp.device() == v.device()) { + const strata::core::OnDevice on(mtp.device()); + (v.stream()) + ->ext_oneapi_submit_barrier( + {*pl_mtp_ev[l1 & 1]}); + } else if (DPCT_CHECK_ERROR(pl_mtp_ev[l1 & 1]->wait()) != 0) { + return fail("the drafter's rows did not land before the window"); + } } if (!v.pl_launch(w.T, w1.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e); ++l1; @@ -11530,6 +11562,47 @@ int main(int argc, char **argv) try { B.launched ? "launched" : B.ready ? "ready" : "none", on ? " ON" : ""); x = outp[(size_t) a]; p = A.p + a + 1; + // STRATA_PIPELINE_DUMP=: after every window, append a hash and the sum of the first stage's + // sequence state (its GDN rows: the recurrence state plus the conv history). Two arms that ran + // the same tokens must agree here; the first position where they do not is the state that + // escapes. Debug only: it waits for the stage's stream, so it distorts the timing. + static const char* pl_dump = std::getenv("STRATA_PIPELINE_DUMP"); // read once + if (pl_dump != nullptr) { + const int64_t gdn_floats = g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + g.ssm_conv_channels * (g.ssm_d_conv - 1); + const size_t n = (size_t) ss.gdn_alloc * (size_t) gdn_floats; + std::vector h(n); + (void) DPCT_CHECK_ERROR(s0->memcpy(h.data(), ss.gdn_state, n * sizeof(float)).wait()); + // the recurrence state and the conv history hashed apart: a wrong row shows which half it is + const size_t n_rec = (size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; + const size_t n_cnv = (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); + double rec_sum = 0.0, cnv_sum = 0.0; + uint64_t rec_hash = 1469598103934665603ull, cnv_hash = 1469598103934665603ull; + for (int64_t l = 0; l < ss.gdn_alloc; ++l) { + const size_t base = (size_t) l * (size_t) gdn_floats; + uint64_t rh = 1469598103934665603ull, ch = 1469598103934665603ull; + for (size_t i = 0; i < n_rec; ++i) { + uint64_t b = 0; + std::memcpy(&b, &h[base + i], sizeof(float)); + rh = (rh ^ b) * 1099511628211ull; + rec_sum += (double) h[base + i]; + } + for (size_t i = 0; i < n_cnv; ++i) { + uint64_t b = 0; + std::memcpy(&b, &h[base + n_rec + i], sizeof(float)); + ch = (ch ^ b) * 1099511628211ull; + cnv_sum += (double) h[base + n_rec + i]; + } + rec_hash = (rec_hash ^ rh) * 1099511628211ull; + cnv_hash = (cnv_hash ^ ch) * 1099511628211ull; + } + if (std::FILE* df = std::fopen(pl_dump, "a")) { + std::fprintf(df, "pos %lld windows %lld rec %.9g %016llx cnv %.9g %016llx\n", (long long) p, + (long long) dec_windows, rec_sum, (unsigned long long) rec_hash, cnv_sum, + (unsigned long long) cnv_hash); + std::fclose(df); + } + } if (!last && !pl_adapt()) return die("an adaptive refill failed"); if (on && !last) { ++pl_on; @@ -11736,6 +11809,46 @@ int main(int argc, char **argv) try { return 1; } // the window's first a + 1 tokens are in the session now (the last output is not: it is next x) + // STRATA_PIPELINE_DUMP=: the serial half of the pipelined window's state diff (see the same block + // in the pipelined loop): the first stage's GDN state after every committed window. + { + static const char* sd = std::getenv("STRATA_PIPELINE_DUMP"); + if (sd != nullptr) { + const int64_t gf = g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + g.ssm_conv_channels * (g.ssm_d_conv - 1); + const size_t n = (size_t) ss.gdn_alloc * (size_t) gf; + std::vector h(n); + (void) DPCT_CHECK_ERROR(ver.stream()->memcpy(h.data(), ss.gdn_state, n * sizeof(float)).wait()); + const size_t n_rec = (size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; + const size_t n_cnv = (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); + double rec_sum = 0.0, cnv_sum = 0.0; + uint64_t rec_hash = 1469598103934665603ull, cnv_hash = 1469598103934665603ull; + for (int64_t l = 0; l < ss.gdn_alloc; ++l) { + const size_t base = (size_t) l * (size_t) gf; + uint64_t rh = 1469598103934665603ull, ch = 1469598103934665603ull; + for (size_t i = 0; i < n_rec; ++i) { + uint64_t bb = 0; + std::memcpy(&bb, &h[base + i], sizeof(float)); + rh = (rh ^ bb) * 1099511628211ull; + rec_sum += (double) h[base + i]; + } + for (size_t i = 0; i < n_cnv; ++i) { + uint64_t bb = 0; + std::memcpy(&bb, &h[base + n_rec + i], sizeof(float)); + ch = (ch ^ bb) * 1099511628211ull; + cnv_sum += (double) h[base + n_rec + i]; + } + rec_hash = (rec_hash ^ rh) * 1099511628211ull; + cnv_hash = (cnv_hash ^ ch) * 1099511628211ull; + } + if (std::FILE* df = std::fopen(sd, "a")) { + std::fprintf(df, "pos %lld serial rec %.9g %016llx cnv %.9g %016llx\n", (long long) (p + a + 1), + rec_sum, (unsigned long long) rec_hash, cnv_sum, + (unsigned long long) cnv_hash); + std::fclose(df); + } + } + } for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]); draft_offered += T - 1; draft_accepted += a;