fix(engine): harden hy4 vcache headroom, inkling2 Metal/HIP/SYCL/CUDA guards, GGUF layout, and CMake checks

This commit is contained in:
Niko1221 committed 2026-11-23 01:10:33 +01:00
1 parent 923e2df4d0
commit 759ccf6c68
25 files changed
+332 -67

No files matched your search

+4
View File
@@ -311,6 +311,10 @@ if(STRATA_BUILD_TESTS)
add_executable(kv_grow_rules_test tests/core/kv_grow_rules_test.cpp)
target_include_directories(kv_grow_rules_test PRIVATE include)
add_test(NAME kv_grow_rules_test COMMAND kv_grow_rules_test)
# #6681: KV dtype guard truth table for HIP/Metal/SYCL pools (no GPU)
add_executable(kv_dtype_guard_test tests/core/kv_dtype_guard_test.cpp)
target_include_directories(kv_dtype_guard_test PRIVATE src/inkling2)
add_test(NAME kv_dtype_guard_test COMMAND kv_dtype_guard_test)
# how the prompt path's K/V append reaches the host copy under KV streaming: the switch both ways, the backend defaults, no pool (no GPU)
add_executable(kv_host_dma_test tests/core/kv_host_dma_test.cpp)
target_include_directories(kv_host_dma_test PRIVATE include)
+3
View File
@@ -5,6 +5,9 @@
# which ggml tree the engine builds from: the vendored third_party/strata-ggml, or the -DSTRATA_GGML_DIR override (repo_root: the checkout)
macro(strata_ggml_resolve repo_root)
if(DEFINED CACHE{GGML_CCACHE})
option(GGML_CCACHE "ggml: use ccache if available" ON)
endif()
set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from instead of the vendored third_party/strata-ggml (empty: the vendored tree)")
if(STRATA_GGML_DIR)
set(_strata_ggml_root "${STRATA_GGML_DIR}")
@@ -5,6 +5,7 @@
#pragma once
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace strata::core {
@@ -20,4 +21,17 @@ inline int64_t gfx12_chunk_ceiling(const char* env) noexcept {
/// The RAM guard (#2090) steps the ceiling down when the extra loan does not fit: 32768 -> 16384 -> 8192.
inline int64_t gfx12_chunk_step_down(int64_t ceiling) noexcept { return ceiling > 16384 ? 16384 : 8192; }
/// Host RAM reserve (MiB) kept free by the #2090 prompt-chunk RAM guard (#6687).
/// - STRATA_PREFILL_RAM_RESERVE_MIB: explicit override in MiB (>= 0) when set.
/// - Default: 6144 MiB when --resident-experts will pin experts after this check (#2090),
/// or 3072 MiB when experts are not pinned in RAM so 64 GB desktops keep 16K/32K chunks safely (#6687).
inline uint64_t prefill_ram_reserve_mib(const char* env, bool resident_cpu_experts) noexcept {
if (env != nullptr && env[0] != '\0') {
char* end = nullptr;
const long long v = std::strtoll(env, &end, 10);
if (end != env && *end == '\0' && v >= 0) return static_cast<uint64_t>(v);
}
return resident_cpu_experts ? 6144ull : 3072ull;
}
} // namespace strata::core
+7
View File
@@ -109,6 +109,13 @@ int main() {
CHECK(gfx12_chunk_step_down(32768) == 16384);
CHECK(gfx12_chunk_step_down(16384) == 8192);
CHECK(gfx12_chunk_step_down(12288) == 8192);
// #6687: STRATA_PREFILL_RAM_RESERVE_MIB override and resident vs non-resident defaults
CHECK(prefill_ram_reserve_mib(nullptr, true) == 6144);
CHECK(prefill_ram_reserve_mib(nullptr, false) == 3072);
CHECK(prefill_ram_reserve_mib("2048", true) == 2048);
CHECK(prefill_ram_reserve_mib("0", false) == 0);
CHECK(prefill_ram_reserve_mib("-100", false) == 3072);
CHECK(prefill_ram_reserve_mib("bad", true) == 6144);
if (fails == 0) std::printf("gfx12_extra_test: OK\n");
return fails == 0 ? 0 : 1;
}
+29 -8
View File
@@ -413,13 +413,19 @@ inline void hy4_setenv(const char* k, const char* v, int) {
inline double wddm_vram_floor_gb(size_t total_bytes) {
const double tot_gib = (double)total_bytes / 1073741824.0;
#ifdef _WIN32
// Hard Windows WDDM free-VRAM floor so desktop compositor, cuBLAS, and driver context never page or OOM (#6528):
// >= 12 GB cards keep >= 1.0 GiB free; 6-8 GB cards keep >= 600 MiB; 4 GB cards keep >= 450 MiB.
// Hard Windows WDDM free-VRAM floor so desktop compositor, cuBLAS, CUDA Graph, and KV growth never page or OOM (#6528, #6693):
// >= 30 GiB cards keep >= 2.00 GiB free; 20-30 GiB keep >= 1.50 GiB; 12-16 GiB keep >= 1.00 GiB; 6-8 GiB keep >= 600 MiB; 4 GiB keep >= 450 MiB.
if (tot_gib >= 30.0) return 2.15; // 2.00 GiB
if (tot_gib >= 20.0) return 1.61; // 1.50 GiB
if (tot_gib >= 11.0) return 1.074; // 1.00 GiB
if (tot_gib >= 5.5) return 0.644; // 600 MiB
return 0.483; // 450 MiB
#else
if (tot_gib >= 11.0) return 0.50;
// Reserve safe VRAM headroom for cuBLAS workspaces, CUDA Graph capture, and KV growth (#6693):
// >= 30 GiB cards (e.g. 48 GB RTX 4090) keep >= 2.00 GiB free; 20-30 GiB keep >= 1.00 GiB; 12-16 GiB keep >= 0.65 GB.
if (tot_gib >= 30.0) return 2.15; // 2.00 GiB
if (tot_gib >= 20.0) return 1.074; // 1.00 GiB
if (tot_gib >= 11.0) return 0.65;
if (tot_gib >= 5.5) return 0.35;
return 0.25;
#endif
@@ -450,12 +456,13 @@ inline int plan_memory(int max_ctx, int chunk, size_t total, const std::string&
kv_q8 = atoi(getenv("HY4_KV_Q8")) != 0;
}
const double kv_row_b = kv_q8 ? 656.0 : 1152.0;
// Elastic KV initial sizing on single discrete cards (< 48 GB) so idle KV never starves hot experts on 4-12 GB cards:
// Elastic KV initial sizing on single discrete cards (< 44 GiB, i.e. <= 32 GB cards) so idle KV never starves hot experts on 4-32 GB cards:
// <= 8 GB -> init 4096 (step 4096); 12 GB -> init 8192 (step 8192); 16..32 GB -> init 16384 (step 16384).
// 48 GB cards (47.4 GiB >= 44 GiB) allocate full max_ctx KV directly without under-reserving (#6693).
const double per_pos = 12.0 * kv_row_b + 12.0 * 512.0 + 12.0 * 64.0;
int init_slots = max_ctx;
int kv_step = 16384;
if (!multi_gpu && !getenv("HY4_KV_NO_GROW") && total < (48ull << 30)) {
if (!multi_gpu && !getenv("HY4_KV_NO_GROW") && total < (44ull << 30)) {
const int target_init = (tot <= 9.0) ? 4096 : (tot <= 13.5 ? 8192 : 16384);
kv_step = target_init;
if (max_ctx > target_init) {
@@ -536,8 +543,13 @@ inline int plan_memory(int max_ctx, int chunk, size_t total, const std::string&
hy4_setenv("HY4_HOST_NEED_GB", b, 1);
}
if (!getenv("HY4_RESERVE_GB")) {
const double kv_res = (mask & 1) ? 0.0 : (init_slots < max_ctx ? kv_init_gb : (dev_pos ? dev_pos * per_pos / GB : (rows + pivg)));
// Compact double-buffered d_scratch[0..1]: 2x96 MiB on 8 GB, 2x160 MiB on 10-12 GB, 2x256 MiB on 16 GB, 2x384 MiB on 24-32 GB!
// Reserve full --max-context KV+IndexPool on >= 30 GB cards (e.g. 32/48/96 GB) so KV growth never starves VRAM or OOMs (#6693);
// on smaller cards with elastic KV, reserve initial KV (kv_grow_to reclaims vcache slabs on demand).
const double full_kv_gb = rows + pivg;
const double kv_res = (mask & 1) ? 0.0
: (dev_pos ? (dev_pos * per_pos / GB)
: ((init_slots < max_ctx && tot < 30.0) ? kv_init_gb : full_kv_gb));
// Compact double-buffered d_scratch[0..1]: 2x96 MiB on 8 GB, 2x160 MiB on 10-12 GB, 2x256 MiB on 16 GB, 2x384 MiB on 24-48 GB!
const double pf_res = (mask != 0 || tot >= 64.0) ? 0.0
: (tot >= 21.5 ? 0.82 : (tot >= 14.5 ? 0.56 : (tot >= 10.0 ? 0.34 : 0.22)));
const double vis_res = (multi_gpu && has_vision) ? 1.15 : 0.0;
@@ -1110,10 +1122,19 @@ inline bool load_experts_tiered(GpuModel& g, const std::string& path, size_t vra
g.vcache_slots_per_slab = vcache_slot_sz > 0 ? std::max(1, (int)(slab_bytes / vcache_slot_sz)) : 1;
}
int actual_dyn = 0;
const double keep_res_gb = getenv("HY4_RESERVE_GB") ? std::max(0.0, atof(getenv("HY4_RESERVE_GB"))) : 0.0;
const size_t keep_res_bytes = (keep_res_gb > 0.0 && !gpu_is_uma()) ? (size_t)(keep_res_gb * 1073741824.0) : 0u;
while (actual_dyn < dyn_slots) {
const int take = std::min(g.vcache_slots_per_slab, dyn_slots - actual_dyn);
const size_t slab_b = (size_t)take * vcache_slot_sz;
if (keep_res_bytes > 0) {
size_t cur_fr = 0, cur_tot = 0;
if (hipMemGetInfo(&cur_fr, &cur_tot) == hipSuccess && cur_fr <= slab_b + keep_res_bytes) {
break; // Never eat into reserved KV + workspace + VRAM safety headroom (#6693)
}
}
uint8_t* slab = nullptr;
if (hipMalloc((void**)&slab, (size_t)take * vcache_slot_sz) != hipSuccess) { (void)hipGetLastError(); break; }
if (hipMalloc((void**)&slab, slab_b) != hipSuccess) { (void)hipGetLastError(); break; }
g.vcache_slabs.push_back(slab);
actual_dyn += take;
}
+7 -5
View File
@@ -26,15 +26,16 @@
#include <cstdlib>
#include <cstring>
#include <chrono>
#include "strata/core/device_error_exit.hpp"
#include "strata/platform/cgroup_mem.hpp"
#define INK_CK(call) \
do { \
cudaError_t _e = (call); \
if (_e != cudaSuccess) { \
std::fprintf(stderr, "strata-inkling CUDA error %d (%s) at %s:%d\n", (int)_e, cudaGetErrorString(_e), \
__FILE__, __LINE__); \
std::exit(3); \
char _what[256]; \
std::snprintf(_what, sizeof(_what), "strata-inkling CUDA error %d at %s:%d", (int)_e, __FILE__, __LINE__);\
strata::core::exit_device_error(_what, cudaGetErrorString(_e)); \
} \
} while (0)
@@ -42,8 +43,9 @@
do { \
cublasStatus_t _s = (call); \
if (_s != CUBLAS_STATUS_SUCCESS) { \
std::fprintf(stderr, "strata-inkling cuBLAS error %d at %s:%d\n", (int)_s, __FILE__, __LINE__); \
std::exit(3); \
char _what[256]; \
std::snprintf(_what, sizeof(_what), "strata-inkling cuBLAS error %d at %s:%d", (int)_s, __FILE__, __LINE__); \
strata::core::exit_device_error(_what, "cublas error"); \
} \
} while (0)
+7 -6
View File
@@ -179,18 +179,19 @@ public:
const size_t min_kv_bytes = (size_t)40 * max_slots_ * swa_r * per_visit_pos
+ (size_t)strata::ink::kInkVisits * max_slots_ * 3 * strata::ink::kInkSconvCh * 4
+ (size_t)8 * max_slots_ * init_glob * per_visit_pos;
// Include O(1) prefill ws (~114 MiB) + compact DSpark (~160 MiB) + activation ws (WDDM floor added inside loader!)
const size_t ws_pad = (max_slots_ >= 8) ? (1280ull << 20)
: ((prop.totalGlobalMem >= (20ull << 30)) ? (960ull << 20)
: (prop.totalGlobalMem <= (13ull << 30)) ? (512ull << 20)
: (640ull << 20));
// Include O(1) prefill ws (~114 MiB) + DSpark (~224 MiB when enabled) + activation ws (WDDM floor added inside loader!)
const bool build_screen = opts.enable_dspark && mf.m.dspark.present;
const size_t dspark_pad = build_screen ? (224ull << 20) : 0ull;
const size_t ws_pad = ((max_slots_ >= 8) ? (1280ull << 20)
: ((prop.totalGlobalMem >= (20ull << 30)) ? (960ull << 20)
: (prop.totalGlobalMem <= (13ull << 30)) ? (512ull << 20)
: (832ull << 20))) + dspark_pad;
size_t min_reserve_bytes = min_kv_bytes + ws_pad;
if (opts.vram_reserve_mib >= 0) {
min_reserve_bytes = std::max(min_reserve_bytes, (size_t)opts.vram_reserve_mib << 20);
}
// Load .strata v1.1 / .gguf (Unsloth + ggml-org) / HF safetensors trunk + experts (Single-GPU, EP2, Layer-Split, or 4-tier GPU+RAM+SSD!)
const bool build_screen = opts.enable_dspark && mf.m.dspark.present;
if (!model_.load_from_model_file(mf, gpu_id_, peer_gpu_id, (float)opts.ep_split, build_screen, err,
min_reserve_bytes, gguf_detail::gguf_dequant_row_f32, gguf_detail::gguf_row_bytes,
opts.vram_experts_gb, opts.ram_experts_gb, opts.ssd_experts,
+2 -2
View File
@@ -1949,8 +1949,8 @@ struct InkCudaRunner {
const size_t swa_kv_bytes = (size_t)n_swa_g0 * max_slots * swa_ring * per_visit_pos;
const size_t sconv_bytes = (size_t)(n_swa_g0 + n_glob_g0) * max_slots * 3 * kInkSconvCh * 4;
const size_t wddm_fl = InkCudaModel::wddm_safety_floor(vtot);
const size_t ws_reserve = ((max_slots >= 8) ? (1280ull << 20) : (640ull << 20))
+ (m.man.has_dspark ? (160ull << 20) : 0ull)
const size_t ws_reserve = ((max_slots >= 8) ? (1280ull << 20) : (768ull << 20))
+ (m.man.has_dspark ? (256ull << 20) : 0ull)
+ (wddm_fl / 2);
const size_t avail_glob = (vfree > swa_kv_bytes + sconv_bytes + ws_reserve)
? (vfree - swa_kv_bytes - sconv_bytes - ws_reserve) : 0u;
+22 -13
View File
@@ -1518,19 +1518,23 @@ public:
const int n_want = static_cast<int>(want_idx.size());
const int V = c_.vocab_unpadded;
if (n_want > 0) {
if (d_unembed_bf16_ != nullptr && n_want <= kMaxParallelSlots) {
std::vector<float> h_want(static_cast<size_t>(n_want) * D);
for (int wi = 0; wi < n_want; ++wi) {
std::memcpy(h_want.data() + static_cast<size_t>(wi) * D,
h_norm.data() + static_cast<size_t>(want_idx[wi]) * D, D * 4);
}
if (d_unembed_bf16_ != nullptr) {
EP_CK(cudaSetDevice(gpu_ids_[0]));
EP_CK(cudaMemcpyAsync(d_dense_x_, h_want.data(), h_want.size() * 4, cudaMemcpyHostToDevice, streams_[0]));
dim3 grid((V + 7) / 8, n_want);
k_unembed_softcap_bf16<<<grid, 256, 0, streams_[0]>>>(
d_dense_x_, d_unembed_bf16_, d_dense_y_, n_want, V, D, c_.logit_softcap);
EP_CK(cudaMemcpyAsync(logits_out, d_dense_y_, static_cast<size_t>(n_want) * V * 4, cudaMemcpyDeviceToHost, streams_[0]));
EP_CK(cudaStreamSynchronize(streams_[0]));
std::vector<float> h_want(static_cast<size_t>(std::min(n_want, kMaxParallelSlots)) * D);
for (int w0 = 0; w0 < n_want; w0 += kMaxParallelSlots) {
const int cw = std::min(kMaxParallelSlots, n_want - w0);
for (int wi = 0; wi < cw; ++wi) {
std::memcpy(h_want.data() + static_cast<size_t>(wi) * D,
h_norm.data() + static_cast<size_t>(want_idx[w0 + wi]) * D, D * 4);
}
EP_CK(cudaMemcpyAsync(d_dense_x_, h_want.data(), static_cast<size_t>(cw) * D * 4, cudaMemcpyHostToDevice, streams_[0]));
dim3 grid((V + 7) / 8, cw);
k_unembed_softcap_bf16<<<grid, 256, 0, streams_[0]>>>(
d_dense_x_, d_unembed_bf16_, d_dense_y_, cw, V, D, c_.logit_softcap);
EP_CK(cudaMemcpyAsync(logits_out + static_cast<size_t>(w0) * V, d_dense_y_,
static_cast<size_t>(cw) * V * 4, cudaMemcpyDeviceToHost, streams_[0]));
EP_CK(cudaStreamSynchronize(streams_[0]));
}
} else {
const auto& unemb_pk = packed_trunk_.at("model.llm.unembed.weight");
const float cap = c_.logit_softcap, inv_cap = 1.0f / cap;
@@ -1743,7 +1747,12 @@ private:
const int max_k = std::max(c_.hidden, c_.n_head * c_.head_dim);
const int max_n = std::max(std::max(c_.vocab_unpadded, c_.n_head * c_.head_dim), std::max(c_.hidden, c_.n_experts));
if (it == d_mats_bf16_.end() || K > max_k || N > max_n) {
cpu_matmul(x, trunk_f32_.at(wname).data(), y, M, N, K);
auto tf = trunk_f32_.find(wname);
if (tf == trunk_f32_.end()) {
err = "cuda-ep: missing dense weight " + wname + " for CPU fallback";
return false;
}
cpu_matmul(x, tf->second.data(), y, M, N, K);
return true;
}
EP_CK(cudaSetDevice(gpu_ids_[0]));
@@ -563,6 +563,10 @@ public:
c_ = model.m.c;
dspark_cfg_ = model.m.dspark;
if (kv_dtype_is_int_quant(opts.kv_dtype)) {
err = "[ink-hip] --kv k8v4/k8v8 is not supported on the HIP backend (allocates fp16-sized pages); use --kv fp8 or fp16";
return false;
}
int dev_count = 0;
if (hipGetDeviceCount(&dev_count) != hipSuccess || dev_count < 1) {
err = "[ink-hip] no HIP devices visible";
+4 -3
View File
@@ -11,6 +11,7 @@
#include <cstdlib>
#include <cstring>
#include "strata/core/device_error_exit.hpp"
#include "strata/hip_uma_guard.hpp"
// ---- Compile-time architecture guards (strictly zero WMMA intrinsics on RDNA2 gfx103x!) ----
@@ -50,9 +51,9 @@
do { \
hipError_t _e = (expr); \
if (_e != hipSuccess) { \
std::fprintf(stderr, "[ink-hip] HIP error %d (%s) at %s:%d\n", (int)_e, hipGetErrorString(_e), __FILE__, \
__LINE__); \
std::exit(3); \
char _what[256]; \
std::snprintf(_what, sizeof(_what), "[ink-hip] HIP error %d at %s:%d", (int)_e, __FILE__, __LINE__); \
strata::core::exit_device_error(_what, hipGetErrorString(_e)); \
} \
} while (0)
+2 -2
View File
@@ -144,7 +144,7 @@ std::unique_ptr<InkBackend> make_hip_backend();
std::unique_ptr<InkBackend> make_metal_backend();
#endif
#ifdef INKLING_ENABLE_SYCL
std::unique_ptr<InkBackend> make_sycl_backend();
std::unique_ptr<InkBackend> make_sycl_backend(const BackendOpts* opts = nullptr);
#endif
inline std::unique_ptr<InkBackend> make_default_backend(bool force_cpu = false, const BackendOpts* opts = nullptr) {
@@ -161,7 +161,7 @@ inline std::unique_ptr<InkBackend> make_default_backend(bool force_cpu = false,
#elif defined(INKLING_ENABLE_METAL)
return make_metal_backend();
#elif defined(INKLING_ENABLE_SYCL)
return make_sycl_backend();
return make_sycl_backend(opts);
#endif
}
return make_cpu_backend();
+6
View File
@@ -30,6 +30,12 @@ inline const char* kv_dtype_name(KvDtype dt) noexcept {
}
}
// Integer quantized KV modes (K8V8/K8V4) have dedicated storage on CPU and CUDA;
// HIP, Metal, and SYCL pools currently allocate FP16/FP8 pages only and reject integer modes at init (#6681).
inline bool kv_dtype_is_int_quant(KvDtype dt) noexcept {
return dt == KvDtype::K8V8 || dt == KvDtype::K8V4;
}
// ---- Scalar FP16 / BF16 / FP8 E4M3FN conversion helpers (portable across CPU & GPU host prep) ----
inline float bf16_to_f32(uint16_t b) noexcept {
uint32_t u = static_cast<uint32_t>(b) << 16;
+6 -4
View File
@@ -260,6 +260,7 @@ struct GgufAdapter {
bool has_dspark_st = false;
SafetensorsShard dspark_st;
bool is_rewrite_layout = false; // true = llama.cpp master / Unsloth (blk.0.ffn_gate_up_exps.weight)
bool is_merged_layout = false; // true = merged mainline (#32694): rewrite names + per-block loop_msg_query & loop_*_ctrl_*
std::vector<uint8_t> sec1_arena; // Assembled canonical Section 1 trunk + DSpark bytes
std::vector<strata::artifact::StrataExpertEntry> expert_dir;
@@ -332,6 +333,7 @@ struct GgufAdapter {
}
is_rewrite_layout = (model->find("blk.0.ffn_gate_up_exps.weight") != nullptr);
is_merged_layout = is_rewrite_layout && (model->find("loop_res_query.weight") == nullptr);
// 1. Parse InkCfg from GGUF metadata (supports BOTH llama.cpp master & PR #32187 keys)
m = ManifestT{};
@@ -382,9 +384,9 @@ struct GgufAdapter {
if (const auto* eos = meta.get("tokenizer.ggml.eos_token_id")) c.eos_token_id = static_cast<int>(eos->u);
const int core_len = (c.num_passes > 1) ? (c.core_end - c.core_start) : 0;
// ggml-org GGUFs (`general.architecture = "inkling2_loop"`) store physical block_count=24 directly;
// Unsloth GGUFs (`general.architecture = "inkling2"`) store virtual block_count=48.
if (arch_v->s == "inkling2_loop" || n_visits_meta <= c.core_end + 6) {
// Merged mainline (#32694, ggml-org/Inkling-2-Mini-GGUF) stores physical block_count=24 directly;
// Unsloth / pre-merge GGUFs store virtual visit count=48.
if (is_merged_layout || arch_v->s == "inkling2_loop" || n_visits_meta <= c.core_end + 6) {
c.n_phys = n_visits_meta;
} else {
c.n_phys = n_visits_meta - (c.num_passes - 1) * core_len;
@@ -394,7 +396,7 @@ struct GgufAdapter {
c.is_swa.assign(c.n_phys, 1);
if (const auto* pat = meta.get(ap + "attention.sliding_window_pattern");
pat && pat->type == strata::MetaType::ARRAY && static_cast<int>(pat->items.size()) >= c.n_phys) {
const bool phys_indexed = (static_cast<int>(pat->items.size()) == c.n_phys);
const bool phys_indexed = is_merged_layout || (static_cast<int>(pat->items.size()) == c.n_phys);
for (int l = 0; l < c.n_phys; ++l) {
int v = phys_indexed ? l : ((l < c.core_end) ? l : (l + (c.num_passes - 1) * core_len));
bool swa_v = false;
+13 -4
View File
@@ -17,6 +17,7 @@
#include "ink_manifest.h"
#include "ink_serve.h"
#include "ink_vision.h"
#include "strata/core/device_error_exit.hpp"
#include "strata/core/volta_forever.hpp"
#if defined(__linux__) && defined(INKLING_ENABLE_HIP)
#include "strata/platform/numa_balancing.hpp"
@@ -417,7 +418,11 @@ int main(int argc, char** argv) {
else if (kv == "fp16" || kv == "f16") { cfg.bopts.kv_dtype = KvDtype::FP16; cfg.bopts.kv_dtype_auto = false; }
else if (kv == "k8v8" || kv == "i8" || kv == "q8") { cfg.bopts.kv_dtype = KvDtype::K8V8; cfg.bopts.kv_dtype_auto = false; }
else if (kv == "k8v4") { cfg.bopts.kv_dtype = KvDtype::K8V4; cfg.bopts.kv_dtype_auto = false; }
else { cfg.bopts.kv_dtype_auto = true; }
else if (kv == "auto") { cfg.bopts.kv_dtype_auto = true; }
else {
fprintf(stderr, "unknown --kv value '%s' (expected: auto, fp8, fp16, k8v8, k8v4)\n", kv.c_str());
std::exit(2);
}
} else if (a == "--kv-offload") {
cfg.bopts.kv_offload = next();
} else if (a == "--draft") {
@@ -485,10 +490,10 @@ int main(int argc, char** argv) {
" --version\n"
" --info PATH [--vision VISION] [--dspark PATH]\n"
" --export-tokenizer PATH OUT_DIR\n"
" --selfcheck [--native PATH] [--verify-hash] [--cpu] [--gpus 1|2] [--kv fp16|fp8|k8v8|k8v4]\n"
" --bench --native PATH [--parallel 1..64] [--gpus 1..4] [--layer-split auto|K1,K2,...] [--ep-split F] [--vram-experts-gb F] [--ram-experts-gb F] [--ssd-experts] [--vram-reserve-mib N] [--cpu-threads N] [--kv auto|fp16|fp8|k8v8|k8v4] [--kv-offload auto|on|off] [--prompt-len N] [--gen N]\n"
" --selfcheck [--native PATH] [--verify-hash] [--cpu] [--gpu N] [--gpus 1|2] [--kv auto|fp16|fp8|k8v8|k8v4]\n"
" --bench --native PATH [--parallel 1..64] [--gpu N] [--gpus 1..4] [--layer-split auto|K1,K2,...] [--ep-split F] [--vram-experts-gb F] [--ram-experts-gb F] [--ssd-experts] [--vram-reserve-mib N] [--cpu-threads N] [--kv auto|fp16|fp8|k8v8|k8v4] [--kv-offload auto|on|off] [--prompt-len N] [--gen N]\n"
" --kld-eval REF.bin --native PATH\n"
" --serve --native PATH [--vision VISION] [--dspark PATH] [--max-context N] [--parallel 1..64] [--gpus 1..4] [--layer-split auto|K1,K2,...] [--kv auto|fp16|fp8|k8v8|k8v4] [--kv-offload auto|on|off] [--draft auto|dspark|off]\n",
" --serve --native PATH [--vision VISION] [--dspark PATH] [--max-context N] [--parallel 1..64] [--gpu N] [--gpus 1..4] [--layer-split auto|K1,K2,...] [--kv auto|fp16|fp8|k8v8|k8v4] [--kv-offload auto|on|off] [--draft auto|dspark|off]\n",
INKLING_VERSION);
return 0;
} else {
@@ -532,6 +537,10 @@ int main(int argc, char** argv) {
cfg.bopts.kv_dtype = KvDtype::FP8_E4M3;
}
if (mode_serve) {
strata::core::set_serve_error_line(true);
}
if (mode_info) return cmd_info(info_file, cfg.vision_path, cfg.bopts.dspark_path);
if (mode_export) return cmd_export_tokenizer(export_file, export_dir);
if (mode_selfcheck) return cmd_selfcheck(cfg.model_path, cfg.force_cpu, verify_hash, cfg.bopts);
@@ -90,6 +90,10 @@ public:
}
bool init(const InkModelFile& model, const BackendOpts& opts, std::string& err) override {
if (kv_dtype_is_int_quant(opts.kv_dtype)) {
err = "metal: --kv k8v4/k8v8 is not supported on the Metal backend (allocates fp16-sized pages); use --kv fp8 or fp16";
return false;
}
kv_dtype_ = opts.kv_dtype;
const char* force_mf = std::getenv("INK_METAL_FORCE_MODEL_FILE");
if (model.kind == ModelSourceKind::Strata && !(force_mf && force_mf[0] == '1')) {
@@ -438,6 +442,9 @@ public:
}
bool selfcheck(std::string& err) override {
if (runner_.mod == nullptr) {
return selfcheck_device(err);
}
StepBatch b;
b.push(0, 0, 1, true);
std::vector<float> lg((size_t)mod_.man.c.vocab_unpadded);
@@ -450,6 +457,58 @@ public:
return true;
}
bool selfcheck_device(std::string& err) {
runner_.cx = &cx_;
if (runner_.lib_codecs < 0) {
if (!runner_.compile_shaders("", err)) return false;
}
// Verify M1/M2 S3_K/S5_K gate-up pipelines compile cleanly (#6608) alongside ink_linear_f32!
auto p_f32 = cx_.pipeline(runner_.lib_codecs, "ink_linear_f32");
(void)cx_.pipeline(runner_.lib_codecs, "ink_moe_gu_situ");
(void)cx_.pipeline(runner_.lib_codecs, "ink_moe_gu_sk23");
(void)cx_.pipeline(runner_.lib_codecs, "ink_moe_gu_sk3");
(void)cx_.pipeline(runner_.lib_codecs, "ink_moe_gu_sk5");
constexpr int N = 32, K = 64, M = 2;
mtl::Buffer bw = cx_.alloc((size_t)N * K * sizeof(float));
mtl::Buffer bx = cx_.alloc((size_t)M * K * sizeof(float));
mtl::Buffer by = cx_.alloc((size_t)M * N * sizeof(float));
float* wp = bw.as<float>();
float* xp = bx.as<float>();
float* yp = by.as<float>();
for (size_t i = 0; i < (size_t)N * K; ++i) wp[i] = std::sin((float)(i % 97)) * 0.5f - 0.25f;
for (size_t i = 0; i < (size_t)M * K; ++i) xp[i] = std::cos((float)(i % 89)) * 0.5f;
std::memset(yp, 0, (size_t)M * N * sizeof(float));
mtl::Dispatch d;
d.p = &p_f32;
d.grid[0] = (uint32_t)((N + 3) / 4);
d.grid[1] = (uint32_t)((M + 3) / 4);
d.tg[0] = 128;
d.args = {mtl::Arg::B(bw), mtl::Arg::B(bx), mtl::Arg::B(by),
mtl::Arg::V(N), mtl::Arg::V(K), mtl::Arg::V(M)};
cx_.run({d});
bool ok = true;
for (int m = 0; m < M && ok; ++m) {
for (int n = 0; n < N; ++n) {
float ref = 0.0f;
for (int k = 0; k < K; ++k) ref += wp[(size_t)n * K + k] * xp[(size_t)m * K + k];
const float got = yp[(size_t)m * N + n];
if (!std::isfinite(got) || std::fabs(ref - got) > 1e-4f * std::max(1.0f, std::fabs(ref))) {
err = "metal selfcheck F32 linear mismatch at (" + std::to_string(m) + "," + std::to_string(n) +
"): ref=" + std::to_string(ref) + " got=" + std::to_string(got);
ok = false;
break;
}
}
}
cx_.free(bw);
cx_.free(bx);
cx_.free(by);
return ok;
}
private:
mtl::Context cx_;
ink_metal::InkMetalModel mod_;
@@ -187,7 +187,8 @@ static inline void sk_w8(device const uchar* pl, int j, thread float4& w0, threa
w1 = float4(kS2Lut[p[1]]);
} else if (F == 3) {
device const uchar* p = pl + (j >> 2);
const uint h = uint(pl[64 + (j >> 3)]);
device const uchar* hp = pl + 64;
const uint h = uint(hp[j >> 3]);
w0 = float4(kS2Lut[p[0]] + kS3Hi[h & 15u]);
w1 = float4(kS2Lut[p[1]] + kS3Hi[h >> 4]);
} else if (F == 4) {
@@ -196,7 +197,8 @@ static inline void sk_w8(device const uchar* pl, int j, thread float4& w0, threa
w1 = float4(half4(kS4Lut[p[2]], kS4Lut[p[3]]));
} else if (F == 5) {
device const uchar* p = pl + (j >> 1);
const uint h = uint(pl[128 + (j >> 3)]);
device const uchar* hp = pl + 128;
const uint h = uint(hp[j >> 3]);
w0 = float4(half4(kS4Lut[p[0]], kS4Lut[p[1]]) + kS5Hi[h & 15u]);
w1 = float4(half4(kS4Lut[p[2]], kS4Lut[p[3]]) + kS5Hi[h >> 4]);
} else if (F == 6) {
@@ -166,7 +166,8 @@ static inline void mpp_sk_w8(device const uchar* pl, int j, thread float4& o0, t
o1 = float4(kMppS2Lut[p[1]]);
} else if constexpr (F == 3) {
device const uchar* p = pl + (j >> 2);
const uint h = uint(pl[64 + (j >> 3)]);
device const uchar* hp = pl + 64;
const uint h = uint(hp[j >> 3]);
o0 = float4(kMppS2Lut[p[0]] + kMppS3Hi[h & 15u]);
o1 = float4(kMppS2Lut[p[1]] + kMppS3Hi[h >> 4]);
} else if constexpr (F == 4) {
@@ -175,7 +176,8 @@ static inline void mpp_sk_w8(device const uchar* pl, int j, thread float4& o0, t
o1 = float4(half4(kMppS4Lut[p[2]], kMppS4Lut[p[3]]));
} else if constexpr (F == 5) {
device const uchar* p = pl + (j >> 1);
const uint h = uint(pl[128 + (j >> 3)]);
device const uchar* hp = pl + 128;
const uint h = uint(hp[j >> 3]);
o0 = float4(half4(kMppS4Lut[p[0]], kMppS4Lut[p[1]]) + kMppS5Hi[h & 15u]);
o1 = float4(half4(kMppS4Lut[p[2]], kMppS4Lut[p[3]]) + kMppS5Hi[h >> 4]);
} else if constexpr (F == 6) {
+5 -3
View File
@@ -776,7 +776,7 @@ struct InkMetalRunner {
// Reset ShortConv state for a slot (called before starting a fresh sequence in slot `s`)
void reset_slot(int s) {
if (s < 0 || s >= max_slots) return;
if (s < 0 || s >= max_slots || !mod || sc_hist_k.empty()) return;
const auto& c = mod->man.c;
const size_t sc_kv = 3ul * (c.n_kv * c.head_dim) * sizeof(float);
const size_t sc_d = 3ul * c.hidden * sizeof(float);
@@ -793,6 +793,7 @@ struct InkMetalRunner {
std::vector<float> k, v, attn, mlp;
};
void snapshot_slot(int s, SlotSconvSnap& snap) const {
if (s < 0 || s >= max_slots || !mod || sc_hist_k.empty()) return;
const auto& c = mod->man.c;
const size_t nkv = 3ul * (c.n_kv * c.head_dim);
const size_t nd = 3ul * c.hidden;
@@ -808,6 +809,7 @@ struct InkMetalRunner {
}
}
void restore_slot(int s, const SlotSconvSnap& snap) {
if (s < 0 || s >= max_slots || !mod || sc_hist_k.empty()) return;
const auto& c = mod->man.c;
const size_t nkv = 3ul * (c.n_kv * c.head_dim);
const size_t nd = 3ul * c.hidden;
@@ -3091,10 +3093,10 @@ struct InkMetalRunner {
return out.M;
}
bool compile_shaders(const std::string& kernel_dir, std::string& err);
private:
mtl::Pipeline p_copy_f32;
bool compile_shaders(const std::string& kernel_dir, std::string& err);
};
} // namespace ink_metal
+21 -4
View File
@@ -28,6 +28,7 @@
#include "../ink_json.h"
#include "strata/artifact/strata_reader.hpp"
#include "strata/core/device_error_exit.hpp"
#ifdef INK_SYCL_WITH_MODEL_FILE
#include "../ink_gguf_transcode.h"
#endif
@@ -76,6 +77,20 @@ inline void set_primary_gpu_index(int idx) {
primary_gpu_index() = idx < 0 ? 0 : idx;
}
// Pin SYCL device selection via ONEAPI_DEVICE_SELECTOR before first Q()/dev_caps() touch when --gpu N > 0
// is requested on a single-GPU run and the user did not already export ONEAPI_DEVICE_SELECTOR.
inline void apply_gpu_index(int gpu_index, int gpus = 1) {
ensure_l0_v1_default();
if (gpu_index > 0 && gpus < 2 && !std::getenv("ONEAPI_DEVICE_SELECTOR")) {
const char* be = std::getenv("INK_SYCL_BACKEND");
const std::string sel = ((be && std::string(be) == "opencl") ? "opencl:" : "level_zero:") + std::to_string(gpu_index);
sy_setenv("ONEAPI_DEVICE_SELECTOR", sel.c_str(), 1);
set_primary_gpu_index(0);
} else {
set_primary_gpu_index(gpu_index);
}
}
inline std::vector<sycl::device> enum_gpu_devices() {
ensure_l0_v1_default();
if (!std::getenv("ONEAPI_DEVICE_SELECTOR")) {
@@ -215,8 +230,9 @@ inline T* dalloc(size_t n) {
size_t cnt = n ? n : 1;
T* p = sycl::malloc_device<T>(cnt, Q());
if (!p) {
fprintf(stderr, "[ink_sycl] dalloc OOM (%zu bytes, total=%zu)\n", cnt * sizeof(T), dev_bytes_allocated());
std::exit(3);
char what[160];
std::snprintf(what, sizeof(what), "[ink_sycl] dalloc (%zu bytes, total=%zu)", cnt * sizeof(T), dev_bytes_allocated());
strata::core::exit_device_error(what, "out of device memory");
}
dev_bytes_allocated() += cnt * sizeof(T);
return p;
@@ -227,8 +243,9 @@ inline T* halloc(size_t n) {
size_t cnt = n ? n : 1;
T* p = sycl::malloc_host<T>(cnt, Q());
if (!p) {
fprintf(stderr, "[ink_sycl] halloc OOM (%zu bytes)\n", cnt * sizeof(T));
std::exit(3);
char what[160];
std::snprintf(what, sizeof(what), "[ink_sycl] halloc (%zu bytes)", cnt * sizeof(T));
strata::core::exit_device_error(what, "out of host USM memory");
}
return p;
}
+3 -3
View File
@@ -336,7 +336,7 @@ struct InkSyRunner {
}
void reset_slot(int s) {
if (s < 0 || s >= max_slots) return;
if (s < 0 || s >= max_slots || !mod || sc_hist_k.empty()) return;
const size_t sc_kv = 3ul * 1024 * 4, sc_d = 3ul * INK_D * 4;
for (int v = 0; v < mod->man.c.n_visits; ++v) {
dzero(sc_hist_k[v] + (size_t)s * 3 * 1024, sc_kv);
@@ -348,7 +348,7 @@ struct InkSyRunner {
}
void snapshot_slot(int s) {
if (s < 0 || s >= max_slots) return;
if (s < 0 || s >= max_slots || !mod || sc_hist_k.empty()) return;
const size_t sc_kv = 3ul * 1024 * 4, sc_d = 3ul * INK_D * 4;
for (int v = 0; v < mod->man.c.n_visits; ++v) {
d2d(sc_snap_k[v] + (size_t)s * 3 * 1024, sc_hist_k[v] + (size_t)s * 3 * 1024, sc_kv);
@@ -359,7 +359,7 @@ struct InkSyRunner {
}
void rollback_slot(int s, int keep_len) {
if (s < 0 || s >= max_slots) return;
if (s < 0 || s >= max_slots || !mod || sc_hist_k.empty()) return;
const size_t sc_kv = 3ul * 1024 * 4, sc_d = 3ul * INK_D * 4;
if (s == last_ver_slot && keep_len > last_ver_pos0 && keep_len <= last_ver_pos0 + last_ver_m) {
const int step_idx = keep_len - last_ver_pos0 - 1;
+59 -3
View File
@@ -63,7 +63,11 @@ public:
}
bool init(const InkModelFile& model, const BackendOpts& opts, std::string& err) override {
ink_sycl::set_primary_gpu_index(opts.gpu_index);
if (kv_dtype_is_int_quant(opts.kv_dtype)) {
err = "sycl: --kv k8v4/k8v8 is not supported on the SYCL backend (allocates fp16-sized pages); use --kv fp8 or fp16";
return false;
}
ink_sycl::apply_gpu_index(opts.gpu_index, opts.gpus);
kv_dtype_ = opts.kv_dtype;
const int par = std::max(1, std::min(64, opts.parallel));
const int ctx = std::max(256, opts.max_ctx);
@@ -189,6 +193,10 @@ public:
}
bool selfcheck(std::string& err) override {
ink_sycl::apply_gpu_index(pending_gpu_index_, pending_gpus_);
if (mod_.path.empty() && runner_.mod == nullptr) {
return selfcheck_device(err);
}
StepBatch b;
b.push(0, 0, 1, true);
std::vector<float> lg((size_t)mod_.man.c.vocab_unpadded);
@@ -201,16 +209,64 @@ public:
return true;
}
bool selfcheck_device(std::string& err) {
constexpr int N = 32, K = 64, M = 2;
std::vector<float> w((size_t)N * K), x((size_t)M * K);
for (size_t i = 0; i < w.size(); ++i) w[i] = std::sin((float)(i % 97)) * 0.5f - 0.25f;
for (size_t i = 0; i < x.size(); ++i) x[i] = std::cos((float)(i % 89)) * 0.5f;
float* wd = sycl::malloc_device<float>(w.size(), ink_sycl::Q());
float* xd = sycl::malloc_device<float>(x.size(), ink_sycl::Q());
float* yd = sycl::malloc_device<float>((size_t)M * N, ink_sycl::Q());
if (!wd || !xd || !yd) {
if (wd) sycl::free(wd, ink_sycl::Q());
if (xd) sycl::free(xd, ink_sycl::Q());
if (yd) sycl::free(yd, ink_sycl::Q());
err = "sycl selfcheck: device USM allocation failed";
return false;
}
ink_sycl::h2d_sync(wd, w.data(), w.size() * sizeof(float));
ink_sycl::h2d_sync(xd, x.data(), x.size() * sizeof(float));
ink_sycl::dzero(yd, (size_t)M * N * sizeof(float));
ink_sycl::k_linear_f32_sg16(wd, N, K, xd, yd, M);
std::vector<float> y((size_t)M * N, 0.0f);
ink_sycl::d2h(y.data(), yd, y.size() * sizeof(float));
ink_sycl::wait();
sycl::free(wd, ink_sycl::Q());
sycl::free(xd, ink_sycl::Q());
sycl::free(yd, ink_sycl::Q());
for (int m = 0; m < M; ++m) {
for (int n = 0; n < N; ++n) {
float ref = 0.0f;
for (int k = 0; k < K; ++k) ref += w[(size_t)n * K + k] * x[(size_t)m * K + k];
const float got = y[(size_t)m * N + n];
if (!std::isfinite(got) || std::fabs(ref - got) > 1e-4f * std::max(1.0f, std::fabs(ref))) {
err = "sycl selfcheck F32 SG16 linear mismatch at (" + std::to_string(m) + "," + std::to_string(n) +
"): ref=" + std::to_string(ref) + " got=" + std::to_string(got);
return false;
}
}
}
return true;
}
private:
friend std::unique_ptr<InkBackend> make_sycl_backend(const BackendOpts* opts);
ink_sycl::InkSyModel mod_;
ink_sycl::InkSyRunner runner_;
std::vector<uint8_t> slot_used_;
int active_slots_ = 0;
KvDtype kv_dtype_ = KvDtype::FP16;
int pending_gpu_index_ = 0;
int pending_gpus_ = 1;
};
std::unique_ptr<InkBackend> make_sycl_backend() {
return std::make_unique<SyclInkBackend>();
std::unique_ptr<InkBackend> make_sycl_backend(const BackendOpts* opts) {
auto b = std::make_unique<SyclInkBackend>();
if (opts) {
b->pending_gpu_index_ = opts->gpu_index;
b->pending_gpus_ = opts->gpus;
}
return b;
}
} // namespace ink2
+5 -3
View File
@@ -11204,16 +11204,18 @@ int main(int argc, char** argv) {
pin_mib = ((total > cached ? total - cached : 0) +
(uint64_t) std::max<int64_t>(0, lend_slots(8192)) * strata::kernels::cpu::expert_layout().max_blob) >> 20;
}
if (avail_mib > 0 && avail_mib < pin_mib + extra_mib + 6144 && !(force16 != nullptr && std::strcmp(force16, "1") == 0)) {
const uint64_t ram_reserve_mib = strata::core::prefill_ram_reserve_mib(
std::getenv("STRATA_PREFILL_RAM_RESERVE_MIB"), o.resident_cpu_experts);
if (avail_mib > 0 && avail_mib < pin_mib + extra_mib + ram_reserve_mib && !(force16 != nullptr && std::strcmp(force16, "1") == 0)) {
const int64_t next = strata::core::gfx12_chunk_step_down(cand);
auto_ceiling = std::min<int64_t>(auto_ceiling, next);
o.prefill_auto_max = std::min<int64_t>(o.prefill_auto_max, next);
o.prefill_chunk = std::min<int64_t>(o.prefill_chunk, next);
std::fprintf(stderr, "strata generate: %s: prompt chunks stay at %lld: %lld would lend %lld more cache slots "
"(%llu MiB more held in RAM during a prompt), and %llu MiB of RAM is available for %llu MiB "
"of resident experts plus that (#2090; %s=1 takes the default ceiling anyway)\n",
"of resident experts plus that and %llu MiB reserve (#2090/#6687; %s=1 or STRATA_PREFILL_RAM_RESERVE_MIB=N overrides)\n",
o.prefill_raise_who, (long long) next, (long long) cand, (long long) extra_slots, (unsigned long long) extra_mib,
(unsigned long long) avail_mib, (unsigned long long) pin_mib, chunk_env_name);
(unsigned long long) avail_mib, (unsigned long long) pin_mib, (unsigned long long) ram_reserve_mib, chunk_env_name);
cand = next;
continue;
}
+38
View File
@@ -0,0 +1,38 @@
// engine/tests/core/kv_dtype_guard_test.cpp - Unit test for #6681 KV dtype guard truth table (no GPU required)
// MIT License - Copyright (c) 2026 Strata contributors
#include "ink_batch.h"
#include <cstdio>
#include <string>
using namespace ink2;
namespace {
int failed = 0;
#define CHECK(expr) \
do { \
if (!(expr)) { \
std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \
++failed; \
} \
} while (0)
} // namespace
int main() {
CHECK(!kv_dtype_is_int_quant(KvDtype::FP16));
CHECK(!kv_dtype_is_int_quant(KvDtype::FP8_E4M3));
CHECK(kv_dtype_is_int_quant(KvDtype::K8V8));
CHECK(kv_dtype_is_int_quant(KvDtype::K8V4));
CHECK(std::string(kv_dtype_name(KvDtype::FP16)) == "fp16");
CHECK(std::string(kv_dtype_name(KvDtype::FP8_E4M3)) == "fp8");
CHECK(std::string(kv_dtype_name(KvDtype::K8V8)) == "k8v8");
CHECK(std::string(kv_dtype_name(KvDtype::K8V4)) == "k8v4");
if (failed != 0) {
std::fprintf(stderr, "kv_dtype_guard_test: %d check(s) failed\n", failed);
return 1;
}
std::printf("kv_dtype_guard_test: OK\n");
return 0;
}
+4
View File
@@ -17,6 +17,10 @@ cmake_minimum_required(VERSION 3.21)
set(CMAKE_OSX_DEPLOYMENT_TARGET "15.0" CACHE STRING "the oldest macOS the binaries run on")
project(strata_vision C CXX)
if(DEFINED CACHE{GGML_CCACHE})
option(GGML_CCACHE "ggml: use ccache if available" ON)
endif()
set(LLAMA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../engine/third_party/strata-llama" CACHE PATH "llama.cpp tree for the test oracles only (STRATA_VISION_ORACLES)")
option(STRATA_VISION_CUDA "run the vision encoder on an NVIDIA GPU (our tower with cuBLAS)" OFF)
option(STRATA_VISION_HIP "run the vision encoder on an AMD GPU (our tower with hipBLAS); the program is named strata-vision-hip" OFF)