Merge branch 'f-131-fix' into r131-fix

This commit is contained in:
Niko1221 committed 2026-09-30 22:03:31 +02:00
commit c67c90fa03
15 files changed
+385 -34

No files matched your search

+16 -5
View File
@@ -68,6 +68,7 @@ if(STRATA_ENABLE_CUDA)
# `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to
# be brought in explicitly for the host-side tests that call cudaMalloc themselves.
find_package(CUDAToolkit REQUIRED)
option(STRATA_EXPERIMENTAL_SM60 "community build for GPUs below compute capability 7.5: Pascal sm_60, Volta sm_70 (#236)" OFF)
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures" FORCE)
endif()
@@ -79,16 +80,22 @@ if(STRATA_ENABLE_CUDA)
if(_base STREQUAL "native" OR _base STREQUAL "all" OR _base STREQUAL "all-major")
continue()
endif()
# STRATA_EXPERIMENTAL_SM60: a Pascal (sm_60, GP100-class) build. It sits below every architecture
# these kernels were written for, so two intrinsics are replaced for it - `__dp4a` (6.1+) and
# `__nanosleep` (7.0+) - in include/strata/kernels/dp4a.hpp, which is bit-exact for the first and
# merely a shorter pause for the second. RTX 20/30/40/50 cards must use the release engine instead.
# STRATA_EXPERIMENTAL_SM60: a Pascal (sm_60, GP100-class) or Volta (sm_70, V100 / Titan V, #236) build.
# These sit below every architecture the kernels were written for, so two intrinsics are replaced below
# their arch - `__dp4a` (6.1+) and `__nanosleep` (7.0+) - in include/strata/kernels/dp4a.hpp, which is
# bit-exact for the first and merely a shorter pause for the second (sm_70 has both). Community-tested,
# not in the ready-made engine; RTX 20/30/40/50 cards must use the release engine instead. It needs a CUDA
# 12.x toolkit: CUDA 13 dropped sm_60 and sm_70 (nvcc fails CMake's compiler test with "compute_70").
if(_base LESS 75 AND NOT STRATA_EXPERIMENTAL_SM60)
message(FATAL_ERROR
"Strata needs an NVIDIA GPU of compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series), but "
"CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal build is "
"CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is "
"-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)")
endif()
if(_base LESS 60)
message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build "
"needs compute capability 6.0 (sm_60) or newer")
endif()
# #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not)
if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0)
message(WARNING "Building for sm_${_base} (RTX 50) with CUDA ${CMAKE_CUDA_COMPILER_VERSION}: engines built with "
@@ -166,6 +173,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp src/core/weights.cpp
src/core/layout.cpp)
target_include_directories(strata_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60)
# the runtime device check (src/core/device.cu) admits the cards this build was made for (#236)
target_compile_definitions(strata_core PRIVATE STRATA_EXPERIMENTAL_SM60=1)
endif()
# The selected runtime is PUBLIC because graph.cpp is a HOST translation unit that calls cudaGraphLaunch and
# cudaEventQuery: the .cu sources get cudart through the CUDA language rules, a .cpp does not, and the
# linker error ("unresolved external symbol cudaGraphInstantiate") names the function rather than the cause.
+4
View File
@@ -22,6 +22,10 @@ namespace strata::core {
enum class PageBacking { LargePages, NormalPages, PinnedByCuda };
/// #243: STRATA_ARENA_PIN_GIB, the cap on the expert arena's CUDA registration in GiB. -1 when unset (the engine
/// decides), 0 = no cap (the whole arena, or as many slices as the driver takes), N > 0 = at most N GiB.
int arena_pin_cap_gib();
struct PinnedArena {
void* base = nullptr;
uint64_t capacity = 0;
+9 -1
View File
@@ -19,6 +19,7 @@ struct Progress {
std::atomic<bool> busy{false};
std::atomic<const char*> where{"idle"};
std::atomic<int64_t> detail{-1};
std::atomic<int64_t> chunk{-1}; ///< #251: the prompt chunk (its first position) a batched-read stage is in
std::atomic<int64_t> since_ms{0}; ///< when `where` was set (steady clock): how long a stage has lasted
std::atomic<uint64_t> ticks{0}; ///< layers served: a window that still moves, slowly, against one that stopped
};
@@ -32,16 +33,23 @@ inline int64_t progress_now_ms() {
using DiagFn = void (*)(std::FILE*);
inline std::atomic<DiagFn>& diag_pool_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
inline std::atomic<DiagFn>& diag_verify_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
/// #267: what a path that ends the engine runs first - it releases the GPU's spin waits on host flags (the verify
/// window's), so no kernel stays resident while the process goes away (on Windows that left the GPU "lost").
inline std::atomic<DiagFn>& release_gpu_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
inline void release_gpu_waits(std::FILE* f) {
if (auto fn = release_gpu_fn().load()) fn(f);
}
inline Progress& progress() {
static Progress p;
return p;
}
inline void progress_at(const char* where, int64_t detail = -1) {
inline void progress_at(const char* where, int64_t detail = -1, int64_t chunk = -1) {
Progress& p = progress();
p.where.store(where, std::memory_order_relaxed);
p.detail.store(detail, std::memory_order_relaxed);
p.chunk.store(chunk, std::memory_order_relaxed);
p.since_ms.store(progress_now_ms(), std::memory_order_relaxed);
}
+8
View File
@@ -30,6 +30,7 @@
#include <cuda_runtime.h>
#include <atomic>
#include <cstdint>
#include <string>
#include <vector>
@@ -60,6 +61,12 @@ public:
/// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags.
void diag(std::FILE* f) const;
/// #267: raise every flag the window's spin kernels wait on past any ring (UINT32_MAX), so a window the GPU
/// cannot finish drains instead of staying resident, then wait up to `timeout_ms` for its streams. For the
/// paths that give up on the engine (a timed-out window, the serve watchdog): the window then ran on whatever
/// the flags guarded, so this verifier refuses every later window. True when the streams finished.
bool release_gpu_waits(int timeout_ms);
/// `max_t` <= kVerifyMaxT. `head` may be null (the canonical head is then run per token).
bool init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits,
const NativeHead* head, int max_t, std::string& err);
@@ -154,6 +161,7 @@ private:
int hist_len_ = 0;
bool head_sampling_ = true; ///< set_head_sampling
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows
bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN)
uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's)
unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device
@@ -41,6 +41,11 @@ struct ExpertLayout {
/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a
/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests).
bool cpu_avx512_ok();
/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel
/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it.
bool cpu_avx2_ok();
/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none.
std::string cpu_name();
/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has.
void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
int r0, int r1);
+9
View File
@@ -23,4 +23,13 @@ LockResult lock_resident(void* p, uint64_t bytes);
/// Undo lock_resident for the same region (best effort).
void unlock_resident(void* p, uint64_t bytes);
/// #243, Windows: the GPU's shared (non-local) memory budget and this process's use of it, from DXGI
/// (IDXGIAdapter3::QueryVideoMemoryInfo, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) for the adapter whose LUID is the
/// 8 bytes at `luid` (cudaDeviceProp::luid). Page-locked host memory the GPU maps is charged there. False (and
/// `why` says so) when the query is not possible - always elsewhere than Windows.
bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why);
/// The machine's physical RAM in bytes (0 when unknown).
uint64_t total_physical_memory();
} // namespace strata::platform
+11 -3
View File
@@ -135,10 +135,18 @@ DeviceInfo device_info(int ordinal) {
d.arch = base_arch(p.gcnArchName);
if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1);
#else
if (d.cc_major * 10 + d.cc_minor < 75) {
// #236: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON: Pascal sm_60, Volta sm_70) runs on the cards it
// was built for - refusing them below 7.5 there made the flag useless; the release engine keeps 7.5
#if defined(STRATA_EXPERIMENTAL_SM60)
constexpr int kMinCc = 60;
const char* const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)";
#else
constexpr int kMinCc = 75;
const char* const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)";
#endif
if (d.cc_major * 10 + d.cc_minor < kMinCc) {
throw CudaError("device " + d.name + " reports compute capability " + std::to_string(d.cc_major) +
"." + std::to_string(d.cc_minor) +
"; Strata needs compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series)",
"." + std::to_string(d.cc_minor) + "; Strata needs compute capability " + kNeed,
-1);
}
#endif
+23 -8
View File
@@ -39,6 +39,15 @@
#include <unistd.h>
#endif
// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform
#ifndef STRATA_FSEEK64
#ifdef _WIN32
#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
#else
#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
#endif
#endif
namespace strata::core {
namespace detail {
@@ -1418,7 +1427,13 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:
return dir + lay.gguf_file[(size_t) l];
};
auto worker = [&]() {
std::ifstream f;
// #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.
// The guard closes the handle on every return.
struct Closer {
FILE* f = nullptr;
~Closer() { if (f != nullptr) std::fclose(f); }
} file;
std::string open_name;
std::vector<uint8_t> buf;
for (;;) {
@@ -1426,12 +1441,12 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:
if (l >= lay.n_layers || bad) break;
const std::string name = file_of(l);
if (name != open_name) {
f.close();
f.clear();
f.open(name, std::ios::binary);
if (!f) { bad = true; return; }
if (file.f != nullptr) std::fclose(file.f);
file.f = std::fopen(name.c_str(), "rb");
if (file.f == nullptr) { bad = true; return; }
open_name = name;
}
FILE* const f = file.f;
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};
@@ -1443,9 +1458,9 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:
buf.resize((size_t) chunk);
for (uint64_t done = 0; done < total; done += chunk) {
const uint64_t n = std::min<uint64_t>(chunk, total - done);
f.seekg((std::streamoff) (src + done));
f.read((char*) buf.data(), (std::streamsize) n);
if ((uint64_t) f.gcount() != n) { bad = true; return; }
// 64-bit seek: a shard is tens of GB
if (STRATA_FSEEK64(f, src + done) != 0) { bad = true; return; }
if (std::fread(buf.data(), 1, (size_t) n, f) != (size_t) n) { bad = true; return; }
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], buf.data() + k * per[r], (size_t) per[r]);
+64 -5
View File
@@ -238,6 +238,46 @@ namespace {
bool clear_error() { (void) cudaGetLastError(); return true; }
} // namespace
int arena_pin_cap_gib() {
const char* e = std::getenv("STRATA_ARENA_PIN_GIB");
if (e == nullptr || *e == '\0') return -1;
const int v = std::atoi(e);
return v < 0 ? -1 : v;
}
namespace {
#ifdef _WIN32
// #243: how much of the arena the sliced registration may pin on Windows when the whole arena was refused.
// Page-locked memory the GPU maps is charged to its shared (non-local) WDDM segment; pinned slice by slice until
// the driver refused one (28 GiB of a 63 GB PC), that segment was left full and every later cudaMalloc failed
// "out of memory". 4 GiB of the budget stay free for what the engine allocates after the arena; without the DXGI
// numbers, RAM/2 - 8 GiB (the budget is about half the RAM). False: no limit could be worked out.
bool sliced_pin_limit(uint64_t& limit, std::string& why) {
constexpr uint64_t GiB = 1ull << 30;
char buf[256];
int dev = 0;
cudaDeviceProp p{};
uint64_t budget = 0, usage = 0;
std::string err = "no CUDA device properties";
if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) {
limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0;
std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB",
(double) budget / GiB, (double) usage / GiB);
why = buf;
return true;
}
(void) cudaGetLastError();
const uint64_t ram = strata::platform::total_physical_memory();
if (ram == 0) return false;
limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0;
std::snprintf(buf, sizeof buf, "%s: RAM/2 - 8 GiB of %.1f GiB", err.c_str(), (double) ram / GiB);
why = buf;
return true;
}
#endif
} // namespace
namespace {
std::vector<uint64_t> uniform_bounds(uint64_t bytes, uint64_t slice) {
std::vector<uint64_t> b;
@@ -265,7 +305,15 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds,
// Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region
// that has already been faulted in page by page is far more expensive to register and may fail outright.
if (base) {
const bool capped = max_pinned_bytes > 0 && max_pinned_bytes < bytes && bounds.size() >= 2;
// #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap
const int env_gib = arena_pin_cap_gib();
uint64_t cap = max_pinned_bytes;
std::string cap_why = "for CUDA1";
if (cap == 0 && env_gib > 0) {
cap = (uint64_t) env_gib << 30;
cap_why = "by STRATA_ARENA_PIN_GIB";
}
const bool capped = cap > 0 && cap < bytes && bounds.size() >= 2;
const cudaError_t e = capped ? cudaSuccess :
cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped);
if (!capped && e == cudaSuccess) {
@@ -275,9 +323,17 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds,
// Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start. The rest stays
// resident through the working-set lock below. (P6: slices may differ in size, one per layer.)
slice_bytes = 1; // sliced; the uniform constructor records the size
bool limited = capped;
uint64_t limit = cap;
std::string limit_why;
#ifdef _WIN32
// #243: not up to the driver's refusal - that leaves WDDM refusing every later allocation (unless
// STRATA_ARENA_PIN_GIB says otherwise; 0 is the old behaviour)
if (!capped && env_gib < 0) limited = sliced_pin_limit(limit, limit_why);
#endif
for (size_t i = 0; i + 1 < bounds.size(); ++i) {
const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i];
if (capped && (off > max_pinned_bytes || n > max_pinned_bytes - off)) break;
if (limited && (off > limit || n > limit - off)) break;
if (cudaHostRegister((uint8_t*) base + off, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) {
(void) cudaGetLastError();
break;
@@ -286,9 +342,12 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds,
registered_bytes = off + n;
++registered_slices;
}
note = (capped ? "cudaHostRegister limited to " + std::to_string(max_pinned_bytes >> 30) +
" GiB for CUDA1; " :
"cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); ") +
char gib[32];
std::snprintf(gib, sizeof gib, "%.1f", (double) limit / (double) (1ull << 30));
note = (capped ? "cudaHostRegister limited to " + std::to_string(cap >> 30) + " GiB " + cap_why + "; " :
"cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); " +
(limited ? "slices capped at " + std::string(gib) + " GiB (" + limit_why +
"; STRATA_ARENA_PIN_GIB=N sets it, 0 = none; #243); " : std::string())) +
std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) +
" GiB); " + note;
if (registered_bytes < bytes) {
+89 -7
View File
@@ -39,6 +39,7 @@
#include <atomic>
#include <map>
#include <string>
#include <thread>
#include <vector>
#include <chrono>
#include <cmath>
@@ -105,18 +106,71 @@ std::atomic<const Verifier*> g_diag_verifier{nullptr};
void diag_active_verifier(std::FILE* f) {
if (const Verifier* v = g_diag_verifier.load()) v->diag(f);
}
// #267: every live verifier (a layer split has one per stage), for the release before the engine ends
constexpr int kLiveMax = 16;
std::atomic<Verifier*> g_live[kLiveMax];
void release_live_verifiers(std::FILE* f) {
for (auto& slot : g_live)
if (Verifier* v = slot.load()) {
const Clock::time_point t0 = Clock::now();
const bool done = v->release_gpu_waits(5000);
if (f != nullptr)
std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n",
done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str()
: "did not finish within 5 s");
}
if (f != nullptr) std::fflush(f);
}
std::string released_note(bool drained) {
return drained ? "; its GPU waits were released and the GPU finished (#267)"
: "; its GPU waits were released but the GPU did not finish within 5 s (#267)";
}
// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the
// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never.
const int64_t g_test_stall = [] {
const char* e = std::getenv("STRATA_TEST_VERIFY_STALL");
return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
}();
} // namespace
bool Verifier::release_gpu_waits(int timeout_ms) {
released_.store(true);
// the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here
// reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but
// wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises.
for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_})
if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX;
std::atomic_thread_fence(std::memory_order_seq_cst);
_mm_sfence();
const OnDevice on_device(device_);
const Clock::time_point t0 = Clock::now();
for (cudaStream_t s : {cs_, copy_}) {
if (s == nullptr) continue;
while (cudaStreamQuery(s) == cudaErrorNotReady) {
if (ms_since(t0) > timeout_ms) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
return true;
}
void Verifier::diag(std::FILE* f) const {
auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
std::fprintf(f, " verify window: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
"served %u, plan (A) %u, copies (B) %u\n", last_t_, (long long) last_pos0_, cur_layer_ + 1,
rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
// #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's
const char* where = progress().where.load();
const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0;
std::fprintf(f, " verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
"served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)",
last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
}
Verifier::~Verifier() {
const Verifier* self = this;
g_diag_verifier.compare_exchange_strong(self, nullptr);
for (auto& slot : g_live) {
Verifier* me = this;
slot.compare_exchange_strong(me, nullptr);
}
if (cs_) cudaStreamSynchronize(cs_);
for (auto& e : exec_)
if (e) cudaGraphExecDestroy(e);
@@ -134,6 +188,11 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
const NativeHead* head, int max_t, std::string& err) {
g_diag_verifier.store(this);
diag_verify_fn().store(&diag_active_verifier);
for (auto& slot : g_live) {
Verifier* none = nullptr;
if (slot.load() == this || slot.compare_exchange_strong(none, this)) break;
}
release_gpu_fn().store(&release_live_verifiers);
cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there
wt_ = &wt;
g_ = &g;
@@ -952,6 +1011,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
using namespace strata::kernels;
const OnDevice on_device(device_);
if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
const ModelGeometry& g = *g_;
SessionState& ss = *ss_;
if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
@@ -996,7 +1056,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
volatile uint32_t* const flag = h_flag_;
const int G = groups_[T] > 0 ? groups_[T] : 1;
const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
for (int64_t k = 0; k < (le_ - lb_) * G; ++k) {
const int64_t steps = (le_ - lb_) * G;
const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false)
for (int64_t k = 0; k < steps; ++k) {
const int64_t l = lb_ + k / G;
const int grp = (int) (k % G);
const uint32_t want = (uint32_t) (k + 1);
@@ -1017,7 +1079,11 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
return false;
}
}
if (now - a > std::chrono::seconds(20)) { err = "verify: timed out at layer " + std::to_string(l); return false; }
if (now - a > std::chrono::seconds(20)) {
// #267: the caller ends the engine; no spin kernel may outlive it
err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
return false;
}
}
const Clock::time_point b = Clock::now();
VDBG("layer %lld rang\n", (long long) l);
@@ -1042,12 +1108,28 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
*(volatile uint32_t*) h_flagA_ = want;
raise_flag(h_flagB_, want);
}
*flag = want;
if (!(test_stall && k + 1 == steps)) *flag = want;
ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
ms_pool += ms_since(b);
}
progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);
const cudaError_t se = cudaStreamSynchronize(cs_);
// #267: polled with a bound instead of cudaStreamSynchronize. A window the GPU never finishes (a spin kernel
// that never sees its flag) held the host here for good, and the process then ended with that kernel still
// resident - on Windows the GPU was left "lost" until a power cycle. Until then it is the same wait: the
// stream idle, or its error.
cudaError_t se;
{
const Clock::time_point a = Clock::now();
uint32_t spins = 0;
while ((se = cudaStreamQuery(cs_)) == cudaErrorNotReady) {
_mm_pause();
if ((++spins & 1023u) != 0 || Clock::now() - a <= std::chrono::seconds(20)) continue;
const bool drained = release_gpu_waits(5000);
err = "verify: timed out waiting for the GPU to finish the window (layer steps " + std::to_string(steps) +
", the GPU rang " + std::to_string(*seq) + ")" + released_note(drained);
return false;
}
}
if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
progress_at("verify window: waiting for the expert copies", (int64_t) T);
cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one
+57
View File
@@ -3,6 +3,8 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#if defined(_MSC_VER)
#include <intrin.h>
#include <immintrin.h>
@@ -51,6 +53,61 @@ bool cpu_avx512_ok() {
return ok;
}
bool cpu_avx2_ok() {
static const bool ok = [] {
unsigned r[4] = {0, 0, 0, 0};
auto cpuid = [&](unsigned leaf, unsigned sub) {
#if defined(_MSC_VER)
int x[4];
__cpuidex(x, (int) leaf, (int) sub);
for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i];
#else
__cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]);
#endif
};
cpuid(0, 0);
if (r[0] < 7) return false;
cpuid(1, 0);
const unsigned ecx1 = r[2];
// FMA (12), OSXSAVE (27), AVX (28), F16C (29)
if (!((ecx1 >> 12) & 1u) || !((ecx1 >> 27) & 1u) || !((ecx1 >> 28) & 1u) || !((ecx1 >> 29) & 1u)) return false;
#if defined(_MSC_VER)
const unsigned long long xcr0 = _xgetbv(0);
#else
unsigned lo = 0, hi = 0;
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo;
#endif
if ((xcr0 & 0x6) != 0x6) return false; // the OS saves the SSE and AVX state
cpuid(7, 0);
return ((r[1] >> 5) & 1u) != 0; // AVX2
}();
return ok;
}
std::string cpu_name() {
unsigned r[12] = {};
#if defined(_MSC_VER)
int x[4];
__cpuid(x, (int) 0x80000000u);
if ((unsigned) x[0] < 0x80000004u) return "unknown";
for (unsigned i = 0; i < 3; ++i) {
__cpuid(x, (int) (0x80000002u + i));
for (int j = 0; j < 4; ++j) r[i * 4 + j] = (unsigned) x[j];
}
#else
unsigned a = 0, b = 0, c = 0, d = 0;
__cpuid(0x80000000u, a, b, c, d);
if (a < 0x80000004u) return "unknown";
for (unsigned i = 0; i < 3; ++i) __cpuid(0x80000002u + i, r[i * 4], r[i * 4 + 1], r[i * 4 + 2], r[i * 4 + 3]);
#endif
char s[49] = {};
std::memcpy(s, r, 48);
std::string name(s);
const size_t b0 = name.find_first_not_of(' '), b1 = name.find_last_not_of(' ');
return b0 == std::string::npos ? std::string("unknown") : name.substr(b0, b1 - b0 + 1);
}
void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out,
int r0, int r1) {
if (cpu_avx512_ok()) q2_0_gguf_rows_multi(w, row_bytes, nblocks, a, nt, out, r0, r1);
+2
View File
@@ -308,6 +308,7 @@ void ExpertPool::wait_parked(const char* what) {
std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked) - stopping the engine "
"so the server can start it again (issue #29)\n",
what, parked_.load(), n_);
strata::core::release_gpu_waits(stderr); // #267: the GPU may be spinning on this layer's flag
std::fflush(stderr);
std::abort();
}
@@ -330,6 +331,7 @@ void ExpertPool::wait_done(int n) {
std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked - "
"stopping the engine so the server can start it again (issue #29)\n",
d, n, parked_.load(), n_);
strata::core::release_gpu_waits(stderr); // #267
std::fflush(stderr);
std::abort();
}
+62
View File
@@ -5,8 +5,11 @@
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <dxgi1_4.h>
#include <cstring>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif
namespace strata::platform {
@@ -57,6 +60,54 @@ void unlock_resident(void* p, uint64_t bytes) {
for (uint64_t off = 0; off < bytes; off += chunk)
VirtualUnlock((uint8_t*) p + off, (SIZE_T) (bytes - off < chunk ? bytes - off : chunk));
}
bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why) {
budget = usage = 0;
// dxgi.dll is loaded when asked, not linked: a start that never needs this keeps the imports it had
HMODULE dxgi = LoadLibraryA("dxgi.dll");
if (dxgi == nullptr) { why = "dxgi.dll not found"; return false; }
using CreateFactory = HRESULT(WINAPI*)(REFIID, void**);
const auto create = (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1");
IDXGIFactory1* factory = nullptr;
if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), (void**) &factory)) || factory == nullptr) {
why = "CreateDXGIFactory1 failed";
FreeLibrary(dxgi);
return false;
}
bool ok = false;
why = "no DXGI adapter has the CUDA device's LUID";
for (UINT i = 0; !ok; ++i) {
IDXGIAdapter1* a = nullptr;
if (factory->EnumAdapters1(i, &a) == DXGI_ERROR_NOT_FOUND || a == nullptr) break;
DXGI_ADAPTER_DESC1 d{};
if (SUCCEEDED(a->GetDesc1(&d)) && std::memcmp(&d.AdapterLuid, luid, sizeof d.AdapterLuid) == 0) {
IDXGIAdapter3* a3 = nullptr;
DXGI_QUERY_VIDEO_MEMORY_INFO info{};
if (SUCCEEDED(a->QueryInterface(__uuidof(IDXGIAdapter3), (void**) &a3)) && a3 != nullptr &&
SUCCEEDED(a3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &info))) {
budget = info.Budget;
usage = info.CurrentUsage;
ok = budget > 0;
why = ok ? "" : "the adapter reports no shared-memory budget";
} else {
why = "QueryVideoMemoryInfo failed";
}
if (a3 != nullptr) a3->Release();
a->Release();
break;
}
a->Release();
}
factory->Release();
FreeLibrary(dxgi);
return ok;
}
uint64_t total_physical_memory() {
MEMORYSTATUSEX ms{};
ms.dwLength = sizeof ms;
return GlobalMemoryStatusEx(&ms) ? (uint64_t) ms.ullTotalPhys : 0;
}
#else
LockResult lock_resident(void* p, uint64_t bytes) {
LockResult r;
@@ -71,6 +122,17 @@ LockResult lock_resident(void* p, uint64_t bytes) {
void unlock_resident(void* p, uint64_t bytes) {
if (p != nullptr && bytes != 0) munlock(p, bytes);
}
bool gpu_shared_memory_budget(const void*, uint64_t& budget, uint64_t& usage, std::string& why) {
budget = usage = 0;
why = "DXGI is Windows-only";
return false;
}
uint64_t total_physical_memory() {
const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE);
return pages > 0 && page > 0 ? (uint64_t) pages * (uint64_t) page : 0;
}
#endif
} // namespace strata::platform
+3
View File
@@ -994,6 +994,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
if (should_stop && should_stop()) { err = "cancelled"; return false; }
if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); }
const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0;
core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251
++stats_.chunks;
pt.mark(kPfStart, cs);
const auto tsetup = Clock::now();
@@ -1198,6 +1199,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16)
for (int64_t l = LB; l < LE; ++l) {
core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving
core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk
const core::LayerView v(*m.wt, l);
// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
if (l == 1 && ple_on && ple_batch) {
@@ -1784,6 +1786,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
stats_.experts_dma += iss_dma;
}
stats_.tokens += T;
core::progress_at("reading the prompt (batched): finishing the chunk from token", p0);
pt.mark(kPfStart, cs);
if (next_ != nullptr) {
// the rows to the host buffer the next stage read two chunks ago (it has finished: waited below)
+23 -5
View File
@@ -722,11 +722,19 @@ MemSample mem_sample() {
return m;
}
// the stage the watchdog names: "<where> <detail>", and the prompt chunk a batched read is in (#251)
std::string stage_text() {
const strata::core::Progress& p = strata::core::progress();
std::string s = std::string(p.where.load()) + " " + std::to_string((long long) p.detail.load());
if (const int64_t c = p.chunk.load(); c >= 0) s += " of the prompt chunk from token " + std::to_string((long long) c);
return s;
}
void stall_report(std::FILE* f, uint64_t layers_during) {
strata::core::Progress& p = strata::core::progress();
std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s %lld\" for %lld s; %llu layers served since the "
"last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, p.where.load(),
(long long) p.detail.load(), (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000),
std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the "
"last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(),
(long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000),
(unsigned long long) layers_during);
for (int pass = 0; pass < 2; ++pass) {
if (pass == 1) {
@@ -1493,6 +1501,15 @@ int main(int argc, char** argv) {
// compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal
// instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check.
strata::kernels::cpu::expert_set_oracle_q8_0(o.cpu_oracle_q8_0);
// ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are
// chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes
// next. Refused here, by name, rather than an illegal instruction in the first expert.
if (!strata::kernels::cpu::cpu_avx2_ok()) {
std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which every CPU "
"expert kernel needs; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer\n",
strata::kernels::cpu::cpu_name().c_str());
return 2;
}
std::string err;
if (!o.native_head_gguf.empty() && !o.stream_token) {
@@ -4102,10 +4119,11 @@ int main(int argc, char** argv) {
const uint64_t b = p.beats.load();
if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; }
if (now - since < std::chrono::seconds(limit)) continue;
std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s %lld) - stopping "
std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping "
"the engine so the server starts it again (issue #29)\n",
limit, p.where.load(), (long long) p.detail.load());
limit, stage_text().c_str());
stall_report(stderr, p.ticks.load() - ticks_at);
strata::core::release_gpu_waits(stderr); // #267: no spin kernel outlives the process
std::fflush(stderr);
std::abort();
}