From cfc30100fd890a11a9e61824fb3f1849a8951305 Mon Sep 17 00:00:00 2001 From: Ryan S <159389674+saariuslystoned@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:19:17 -0500 Subject: [PATCH 1/2] feat(libopenbuenos): auto-size weight cache cap (>916 MB) and add cache telemetry (#40) --- libopenbuenos/include/openbuenos.h | 35 +++ libopenbuenos/src/ob_device.cpp | 38 +++- libopenbuenos/src/ob_gemm.cpp | 202 ++++++++++++++--- libopenbuenos/src/ob_internal.h | 18 +- libopenbuenos/tests/openbuenos_host_test.cpp | 214 ++++++++++++++++++- libopenbuenos/tests/openbuenos_selftest.cpp | 6 +- llama-cpp-edgetpu/ggml-edgetpu.cpp | 2 + llama-cpp-edgetpu/openbuenos_shim.c | 12 ++ 8 files changed, 478 insertions(+), 49 deletions(-) diff --git a/libopenbuenos/include/openbuenos.h b/libopenbuenos/include/openbuenos.h index 31e8562e..4dd3443a 100644 --- a/libopenbuenos/include/openbuenos.h +++ b/libopenbuenos/include/openbuenos.h @@ -190,6 +190,17 @@ typedef struct ob_config { uint8_t priority; /* VII queue priority (default 0) */ uint8_t perf_mode; /* 0 = default, 1..5 = DVFS perf tier (5 = max clocks) */ uint8_t reserved[2]; + /* + * Explicit ext[2] weight-cache byte cap. 0 selects MemAvailable auto-size. + * Honored only when struct_size covers this field. + * Environment (wins over this field): + * OPENBUENOS_WEIGHT_CACHE_MB — MiB cap (16..8192). 0 / non-numeric is ignored. + * OPENBUENOS_CACHE_CAP — values <= 1048576 stay the ggml graph-entry count. + * Values above that are an explicit weight-cache byte cap (>= 1.5 GiB). + * Explicit caps are clamped to leave MemAvailable headroom (512 MiB, or half + * when MemAvailable is at most 640 MiB) so a request cannot exhaust RAM. + */ + uint64_t weight_cache_cap_bytes; } ob_config_t; /* Execution telemetry returned by invoke / wait / matmul */ @@ -230,6 +241,7 @@ typedef struct ob_profile_stats { uint64_t weight_cache_peak_bytes; /* Peak resident ext[2] DMA-BUF bytes */ uint64_t weight_cache_budget_bytes; /* Effective LMKD-safe ext[2] DMA-BUF byte cap */ uint64_t weight_cache_evictions; /* Cumulative weight cache LRU evictions */ + uint64_t weight_pack_count; /* Cold ext[2] pack/repack operations */ uint64_t swiglu_calls; /* Number of ob_gemm_swiglu_* calls executed */ uint64_t swiglu_chunks_chained; /* Single-VII in-SRAM SwiGLU chunks dispatched */ uint64_t swiglu_fallbacks; /* SwiGLU calls routed via M7A batched fallback */ @@ -308,6 +320,29 @@ ob_status_t ob_context_set_profile(ob_context_t* ctx, int enable); ob_status_t ob_context_get_profile(const ob_context_t* ctx, ob_profile_stats_t* out_profile); ob_status_t ob_context_reset_profile(ob_context_t* ctx); +/* + * ext[2] weight-cache byte cap. 0 restores MemAvailable auto-size. + * OPENBUENOS_WEIGHT_CACHE_MB and a byte-sized OPENBUENOS_CACHE_CAP still win. + */ +ob_status_t ob_context_set_weight_cache_cap(ob_context_t* ctx, uint64_t cap_bytes); + +/* Hit/miss/eviction + repack telemetry for the ext[2] weight cache. */ +typedef struct ob_weight_cache_stats { + uint64_t hits; + uint64_t misses; + uint64_t evictions; + uint64_t bytes_resident; + uint64_t peak_bytes; + uint64_t budget_bytes; + uint64_t pack_count; + uint64_t pack_us; + uint32_t entries; + uint32_t reserved; +} ob_weight_cache_stats_t; + +ob_status_t ob_context_get_weight_cache_stats(const ob_context_t* ctx, + ob_weight_cache_stats_t* out_stats); + /* * Opt-in / defaultable FreeTile BUENOS_A0 VLIW/DGC0 emitter switch. * diff --git a/libopenbuenos/src/ob_device.cpp b/libopenbuenos/src/ob_device.cpp index 2cb98b85..34be87ac 100644 --- a/libopenbuenos/src/ob_device.cpp +++ b/libopenbuenos/src/ob_device.cpp @@ -1458,6 +1458,10 @@ ob_status_t ob_context_create(const ob_config_t* config, ob_context_t** out_ctx) ctx->mock_mode = (eff.mock_mode != 0); ctx->cache_capacity = eff.graph_cache_capacity; ctx->pool_max_bytes = static_cast(eff.buffer_pool_max_bytes); + if (config && + config->struct_size >= offsetof(ob_config_t, weight_cache_cap_bytes) + sizeof(uint64_t)) { + ctx->weight_cache_cap_bytes = config->weight_cache_cap_bytes; + } #if defined(__linux__) if (!ctx->mock_mode) { struct rlimit rl {}; @@ -1510,7 +1514,7 @@ void ob_context_destroy(ob_context_t* ctx) { "submit_us=%llu wait_us=%llu dequant_us=%llu sat_retries=%llu spin_hits=%llu " "poll_waits=%llu pool_hits=%llu pool_misses=%llu w_hits=%llu w_misses=%llu " "w_evict=%llu w_bytes=%llu w_peak_bytes=%llu w_budget_bytes=%llu " - "w_entries=%llu w_peak_entries=%llu\n", + "w_entries=%llu w_peak_entries=%llu w_pack=%llu\n", static_cast(ps.calls), static_cast(ps.tiles_dispatched), static_cast(ps.horiz_fusions), @@ -1539,7 +1543,8 @@ void ob_context_destroy(ob_context_t* ctx) { static_cast(ps.weight_cache_peak_bytes), static_cast(ps.weight_cache_budget_bytes), static_cast(ctx->weight_cache_map.size()), - static_cast(ctx->weight_cache_peak_entries)); + static_cast(ctx->weight_cache_peak_entries), + static_cast(ps.weight_pack_count)); } } ctx->async_dequant.shutdown(); @@ -1629,6 +1634,7 @@ ob_status_t ob_context_get_profile(const ob_context_t* ctx, ob_profile_stats_t* out_profile->weight_cache_peak_bytes = mctx->weight_cache_peak_bytes; out_profile->weight_cache_budget_bytes = ob::compute_weight_cache_budget_bytes(mctx); out_profile->weight_cache_evictions = mctx->weight_cache_evictions; + out_profile->weight_pack_count = mctx->weight_pack_count; out_profile->swiglu_calls = mctx->prof.swiglu_calls; out_profile->swiglu_chunks_chained = mctx->prof.swiglu_chunks_chained; out_profile->swiglu_fallbacks = mctx->prof.swiglu_fallbacks; @@ -1646,6 +1652,34 @@ ob_status_t ob_context_get_profile(const ob_context_t* ctx, ob_profile_stats_t* return OB_OK; } +ob_status_t ob_context_set_weight_cache_cap(ob_context_t* ctx, uint64_t cap_bytes) { + if (!ctx) return OB_ERR_INVALID_ARG; + std::lock_guard lk(ctx->gemm_mu); + ctx->weight_cache_cap_bytes = cap_bytes; + ctx->weight_cache_max_bytes = 0u; + return OB_OK; +} + +ob_status_t ob_context_get_weight_cache_stats(const ob_context_t* ctx, + ob_weight_cache_stats_t* out_stats) { + if (!ctx || !out_stats) return OB_ERR_INVALID_ARG; + std::memset(out_stats, 0, sizeof(*out_stats)); + ob_context* mctx = const_cast(ctx); + std::lock_guard lk(mctx->gemm_mu); + out_stats->hits = mctx->weight_cache_hits; + out_stats->misses = mctx->weight_cache_misses; + out_stats->evictions = mctx->weight_cache_evictions; + out_stats->bytes_resident = mctx->weight_cache_bytes; + out_stats->peak_bytes = mctx->weight_cache_peak_bytes; + out_stats->budget_bytes = ob::compute_weight_cache_budget_bytes(mctx); + out_stats->pack_count = mctx->weight_pack_count; + out_stats->pack_us = mctx->prof.weight_pack_ns / 1000ULL; + const size_t entries = mctx->weight_cache_map.size(); + out_stats->entries = static_cast( + std::min(entries, static_cast(std::numeric_limits::max()))); + return OB_OK; +} + ob_status_t ob_context_reset_profile(ob_context_t* ctx) { if (!ctx) return OB_ERR_INVALID_ARG; std::lock_guard glk(ctx->gemm_mu); diff --git a/libopenbuenos/src/ob_gemm.cpp b/libopenbuenos/src/ob_gemm.cpp index 77f55878..16e68205 100644 --- a/libopenbuenos/src/ob_gemm.cpp +++ b/libopenbuenos/src/ob_gemm.cpp @@ -8,6 +8,10 @@ #include #include #include +#include +#if defined(__APPLE__) +#include +#endif #if defined(__ARM_NEON) && defined(__aarch64__) #include @@ -420,6 +424,83 @@ uint64_t hash_shape_key(uint32_t hw_m, uint32_t hw_k, uint32_t hw_n, return h == 0u ? 1u : h; } +constexpr size_t kMiB = 1024u * 1024u; +constexpr size_t kAutoCeilingBytes = 1536u * kMiB; // 1.5 GiB on large devices +constexpr size_t kTightMemBytes = 2u * 1024u * kMiB; // below this, keep MemAvailable/3 +constexpr size_t kHeadroomBytes = 512u * kMiB; +constexpr size_t kHeadroomThresholdBytes = 640u * kMiB; +constexpr unsigned long kExplicitMinMb = 16ul; +constexpr unsigned long kExplicitMaxMb = 8192ul; +constexpr long long kGraphCacheCapMax = 1048576LL; // ggml OPENBUENOS_CACHE_CAP entry limit + +bool env_span_ok(const char* end) { + if (!end) return false; + while (*end == ' ' || *end == '\t') ++end; + return *end == '\0'; +} + +// OPENBUENOS_WEIGHT_CACHE_MB. 0 and non-numeric values are not an override. +bool parse_weight_cache_mb_env(size_t* out_bytes) { + const char* env = std::getenv("OPENBUENOS_WEIGHT_CACHE_MB"); + if (!env || !env[0] || !out_bytes) return false; + char* end = nullptr; + const unsigned long mb = std::strtoul(env, &end, 10); + if (end == env || !env_span_ok(end) || mb == 0ul) return false; + unsigned long clamped = mb; + if (clamped < kExplicitMinMb) clamped = kExplicitMinMb; + if (clamped > kExplicitMaxMb) clamped = kExplicitMaxMb; + *out_bytes = static_cast(clamped) * kMiB; + return true; +} + +// OPENBUENOS_CACHE_CAP. Values <= 1048576 remain the graph-entry count. +// Larger values are an explicit weight-cache byte cap (supports >= 1.5 GiB). +bool parse_cache_cap_bytes_env(size_t* out_bytes) { + const char* env = std::getenv("OPENBUENOS_CACHE_CAP"); + if (!env || !env[0] || !out_bytes) return false; + char* end = nullptr; + const long long parsed = std::strtoll(env, &end, 10); + if (end == env || !env_span_ok(end) || parsed <= kGraphCacheCapMax) return false; + const long long kMaxBytes = static_cast(kExplicitMaxMb) * static_cast(kMiB); + long long bytes = parsed; + if (bytes > kMaxBytes) bytes = kMaxBytes; + *out_bytes = static_cast(bytes); + return true; +} + +size_t clamp_explicit_request(uint64_t bytes) { + const uint64_t kMaxBytes = static_cast(kExplicitMaxMb) * kMiB; + if (bytes > kMaxBytes) bytes = kMaxBytes; + return static_cast(bytes); +} + +// Auto cap from a MemAvailable sample. +// < 2 GiB: MemAvailable/3 (historical LMKD fraction; small-device tests). +// >= 2 GiB: min(1536 MiB, MemAvailable/2). A ~2.6 GiB sample (the Pixel 10 +// pocket that produced an 896 MiB cap) lands at 1344 MiB, above the 916 MiB +// PocketCoder working set. 4/8/12/16 GiB samples hit the 1536 MiB ceiling +// and still keep at least half of MemAvailable free. +size_t auto_cap_from_mem(size_t mem_avail) { + if (mem_avail < kTightMemBytes) { + return mem_avail / 3u; + } + const size_t half = mem_avail / 2u; + const size_t reserve_cap = (mem_avail > kHeadroomThresholdBytes) + ? (mem_avail - kHeadroomBytes) + : half; + size_t safe = std::min(half, reserve_cap); + if (safe > kAutoCeilingBytes) safe = kAutoCeilingBytes; + return safe; +} + +size_t explicit_headroom_cap(size_t mem_avail) { + const size_t lmkd_cap = mem_avail / 3u; + const size_t headroom_cap = (mem_avail > kHeadroomThresholdBytes) + ? (mem_avail - kHeadroomBytes) + : (mem_avail / 2u); + return std::max(lmkd_cap, headroom_cap); +} + bool read_system_mem_available_bytes(size_t* out_bytes) { if (!out_bytes) return false; *out_bytes = 0u; @@ -437,7 +518,24 @@ bool read_system_mem_available_bytes(size_t* out_bytes) { } } std::fclose(f); - return found; + return found && *out_bytes > 0u; +#elif defined(__APPLE__) + vm_statistics64_data_t vm{}; + mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + const kern_return_t kr = host_statistics64( + mach_host_self(), HOST_VM_INFO64, + reinterpret_cast(&vm), &count); + if (kr != KERN_SUCCESS) return false; + const long page = ::sysconf(_SC_PAGESIZE); + if (page <= 0) return false; + const uint64_t pages = static_cast(vm.free_count) + + static_cast(vm.inactive_count) + + static_cast(vm.speculative_count) + + static_cast(vm.purgeable_count); + const uint64_t bytes = pages * static_cast(page); + if (bytes == 0u) return false; + *out_bytes = static_cast(bytes); + return true; #else return false; #endif @@ -445,56 +543,58 @@ bool read_system_mem_available_bytes(size_t* out_bytes) { size_t compute_weight_cache_budget_bytes_impl(ob_context* ctx) { if (!ctx) return 0u; - size_t base_cap = 0u; + size_t requested = 0u; bool explicit_cap = false; - const char* env = std::getenv("OPENBUENOS_WEIGHT_CACHE_MB"); - if (env && env[0]) { - unsigned long mb = std::strtoul(env, nullptr, 10); - if (mb < 16ul) mb = 16ul; - if (mb > 8192ul) mb = 8192ul; - base_cap = static_cast(mb) * 1024u * 1024u; + if (parse_weight_cache_mb_env(&requested)) { + explicit_cap = true; + } else if (parse_cache_cap_bytes_env(&requested)) { + explicit_cap = true; + } else if (ctx->weight_cache_cap_bytes > 0u) { + requested = clamp_explicit_request(ctx->weight_cache_cap_bytes); explicit_cap = true; + } + + size_t base_cap = 0u; + if (explicit_cap) { + base_cap = requested; } else { - // 256 MiB on host mock; up to 2048 MiB on live Android device (bounded below MemAvailable/3). - base_cap = ctx->mock_mode - ? (256u * 1024u * 1024u) - : (2048u * 1024u * 1024u); + // No sample yet: 256 MiB host mock, 1536 MiB device ceiling. + base_cap = ctx->mock_mode ? (256u * kMiB) : kAutoCeilingBytes; } + bool have_mem_avail = false; size_t mem_avail = 0u; if (ctx->simulated_mem_available_bytes > 0u || ctx->simulated_mem_available_set) { have_mem_avail = true; mem_avail = ctx->simulated_mem_available_bytes; - } else if (!ctx->mock_mode) { - if (read_system_mem_available_bytes(&mem_avail)) { - have_mem_avail = true; - // /proc/meminfo MemAvailable excludes our own unswappable DMA-BUF cache; - // add weight_cache_bytes back so our own cache cannot self-ratchet downward. - mem_avail += ctx->weight_cache_bytes; - } + } else if (ctx->mem_probe.fn && ctx->mem_probe.fn(&mem_avail, ctx->mem_probe.user)) { + have_mem_avail = true; + } else if (!ctx->mock_mode && read_system_mem_available_bytes(&mem_avail)) { + have_mem_avail = true; + // /proc/meminfo MemAvailable excludes our own unswappable DMA-BUF cache; + // add weight_cache_bytes back so our own cache cannot self-ratchet downward. + mem_avail += ctx->weight_cache_bytes; } if (have_mem_avail) { - // Auto mode uses LMKD-safe MemAvailable / 3 ceiling; explicit OPENBUENOS_WEIGHT_CACHE_MB - // honors higher budgets on Linux hosts while reserving >= 512 MiB OS/KV headroom (>= 450 MiB). - const size_t lmkd_cap = mem_avail / 3u; - size_t safe_cap = lmkd_cap; if (explicit_cap) { - constexpr size_t kReserveBytes = 512u * 1024u * 1024u; - const size_t headroom_cap = (mem_avail > 640u * 1024u * 1024u) - ? (mem_avail - kReserveBytes) - : (mem_avail / 2u); - safe_cap = std::max(lmkd_cap, headroom_cap); - } - if (safe_cap < base_cap) { - base_cap = safe_cap; + const size_t safe_cap = explicit_headroom_cap(mem_avail); + if (safe_cap < base_cap) base_cap = safe_cap; + } else { + base_cap = auto_cap_from_mem(mem_avail); } } - return std::max(base_cap, 1u * 1024u * 1024u); + return std::max(base_cap, 1u * kMiB); +} + +bool weight_cache_budget_is_dynamic(const ob_context* ctx) { + return ctx->simulated_mem_available_set || + ctx->simulated_mem_available_bytes > 0u || + ctx->mem_probe.fn != nullptr; } void ensure_weight_cache_budget(ob_context* ctx, bool refresh_meminfo = false) { if (ctx->weight_cache_max_bytes == 0u || refresh_meminfo || - ctx->simulated_mem_available_bytes > 0u || ctx->simulated_mem_available_set) { + weight_cache_budget_is_dynamic(ctx)) { ctx->weight_cache_max_bytes = compute_weight_cache_budget_bytes_impl(ctx); } if (ctx->weight_cache_max_entries == 0u) { @@ -515,7 +615,7 @@ void weight_cache_evict_locked(ob_context* ctx, const CachedWeightTile* keep = nullptr, size_t incoming_entries = 1u) { const bool periodic_refresh = - (ctx->simulated_mem_available_bytes > 0u || ctx->simulated_mem_available_set) || + weight_cache_budget_is_dynamic(ctx) || (!ctx->mock_mode && ((ctx->weight_cache_misses & 31u) == 0u || ctx->weight_cache_bytes + incoming_bytes > ctx->weight_cache_max_bytes)); ensure_weight_cache_budget(ctx, periodic_refresh); @@ -550,7 +650,7 @@ CachedWeightTile* weight_cache_find_locked(ob_context* ctx, const WeightTileKey& ctx->weight_cache_lru.splice(ctx->weight_cache_lru.begin(), ctx->weight_cache_lru, t->lru_it); } ctx->weight_cache_hits += 1u; - if ((ctx->simulated_mem_available_bytes > 0u || ctx->simulated_mem_available_set) || + if (weight_cache_budget_is_dynamic(ctx) || (!ctx->mock_mode && (ctx->weight_cache_hits & 63u) == 0u)) { ensure_weight_cache_budget(ctx, true); if (ctx->weight_cache_bytes > ctx->weight_cache_max_bytes || @@ -2272,6 +2372,34 @@ size_t compute_weight_cache_budget_bytes(ob_context* ctx) { return compute_weight_cache_budget_bytes_impl(ctx); } +bool probe_platform_mem_available(size_t* out_bytes) { + return read_system_mem_available_bytes(out_bytes); +} + +bool weight_cache_sim_access(ob_context* ctx, uint64_t tag, size_t bytes, bool* out_hit) { + if (out_hit) *out_hit = false; + if (!ctx || bytes == 0u) return false; + std::lock_guard lk(ctx->gemm_mu); + WeightTileKey key; + key.h1 = tag; + key.h2 = tag ^ 0x9e3779b97f4a7c15ULL; + key.bytes = bytes; + CachedWeightTile* existing = weight_cache_find_locked(ctx, key); + if (existing && existing->in_cache) { + if (out_hit) *out_hit = true; + return true; + } + CachedWeightTile* tile = new (std::nothrow) CachedWeightTile(); + if (!tile) return false; + tile->key = key; + tile->ext2_bytes = bytes; + if (!weight_cache_insert_locked(ctx, tile)) { + delete tile; + return false; + } + return true; +} + uint32_t quant_scale_D_grid(double raw_d) { return quant_scale_D_grid_impl(raw_d); } @@ -2751,6 +2879,7 @@ ob_status_t pack_quant_group_tile_locked(ob_context* ctx, if (wbuf) ob_buffer_free(wbuf); return wst; } + ctx->weight_pack_count += 1u; CachedWeightTile* tile = new (std::nothrow) CachedWeightTile(); if (!tile) { @@ -3189,6 +3318,7 @@ ob_status_t ob_gemm_matmul_int8(ob_context_t* ctx, drain_all_cleanup(); return wst; } + ctx->weight_pack_count += 1u; w_tile = new (std::nothrow) ob::CachedWeightTile(); if (!w_tile) { ob_buffer_free(wbuf); @@ -4874,6 +5004,7 @@ ob_status_t ob_gemm_swiglu_int8(ob_context_t* ctx, ob_buffer_free(wbuf); return st; } + ctx->weight_pack_count += 1u; // Unique graph cache key binding shape + all 9 exact float scales (weight-agnostic Probe-A!) uint64_t gkey = ctx->freetile_enabled ? 0x46545F5357493831ULL : 0x535749385F303031ULL; @@ -6033,6 +6164,7 @@ ob_status_t ob_gemm_swiglu_f32_quant(ob_context_t* ctx, drain_all_cleanup(); return wst; } + ctx->weight_pack_count += 1u; w_tile = new (std::nothrow) ob::CachedWeightTile(); if (!w_tile) { ob_buffer_free(wbuf); diff --git a/libopenbuenos/src/ob_internal.h b/libopenbuenos/src/ob_internal.h index ca7614f0..76d76acc 100644 --- a/libopenbuenos/src/ob_internal.h +++ b/libopenbuenos/src/ob_internal.h @@ -346,9 +346,22 @@ ob_status_t graph_register_dgc0_internal(ob_context* ctx, CachedGraph** out_entry, bool* out_cache_hit); +// Platform MemAvailable (Linux /proc/meminfo, macOS vm stats). False if unknown. +bool probe_platform_mem_available(size_t* out_bytes); + // Compute Android LMKD-safe ext[2] weight-cache byte budget (ob_gemm.cpp). size_t compute_weight_cache_budget_bytes(ob_context* ctx); +// Admit or touch one synthetic resident tile (no DMA). Host tests only. +// *out_hit is set when `tag` was already cached. False if the tile is not resident. +bool weight_cache_sim_access(ob_context* ctx, uint64_t tag, size_t bytes, bool* out_hit); + +// Injectable MemAvailable probe. nullptr uses the platform probe (non-mock only). +struct MemAvailableProbe { + bool (*fn)(size_t* out_bytes, void* user) = nullptr; + void* user = nullptr; +}; + // Submit async Execute with an optional runtime param_slice DMA-BUF override // (Probe-A weight-agnostic graph reuse: single model_handle per (M,K,N,D)). ob_status_t graph_submit_async_with_params(ob_graph_t* graph, @@ -809,7 +822,7 @@ struct ob_context { size_t weight_cache_bytes = 0; size_t weight_cache_peak_bytes = 0; size_t weight_cache_peak_entries = 0; - size_t weight_cache_max_bytes = 0; // lazily initialized (auto up to 1536 MiB with 512 MiB reserve) + size_t weight_cache_max_bytes = 0; // lazily initialized (auto ceiling 1536 MiB, >= 512 MiB headroom) size_t weight_cache_default_max_entries = ob::kDefaultWeightCacheMaxEntries; size_t weight_cache_max_entries = 0; // FD-safe cap (default 16384, env OPENBUENOS_WEIGHT_CACHE_ENTRIES) size_t outlier_cache_bytes = 0; // Separate tracked total of cached FP32 outlier columns @@ -817,9 +830,12 @@ struct ob_context { uint64_t next_immutable_region_gen = 1u; size_t simulated_mem_available_bytes = 0; // Optional test override for LMKD budget verification bool simulated_mem_available_set = false; // Allows explicitly simulating MemAvailable == 0 kB + ob::MemAvailableProbe mem_probe{}; // Test/host injection; wins over the platform probe + uint64_t weight_cache_cap_bytes = 0; // 0 = auto. Explicit byte cap from API/config uint64_t weight_cache_hits = 0; uint64_t weight_cache_misses = 0; uint64_t weight_cache_evictions = 0; + uint64_t weight_pack_count = 0; // Persistent pthread worker pool (opt-in via OPENBUENOS_THREADS>1) + // lock-free 1-helper SPSC async dequant worker (OPENBUENOS_ASYNC_DEQUANT=1). diff --git a/libopenbuenos/tests/openbuenos_host_test.cpp b/libopenbuenos/tests/openbuenos_host_test.cpp index 516ea577..6bdcd547 100644 --- a/libopenbuenos/tests/openbuenos_host_test.cpp +++ b/libopenbuenos/tests/openbuenos_host_test.cpp @@ -3001,16 +3001,16 @@ void test_phase7a_neon_horiz_fusion_profiler_and_lmkd() { // 17c. Android LMKD-Safe Single-Copy Memory Budgeting (simulated 7B-14B streaming sweep) { - // Verify MemAvailable / 3 dynamic cap arithmetic + // Verify large-device auto ceiling (min(1536 MiB, MemAvailable/2)). ob_config_t cfg = ob_config_default(); cfg.mock_mode = 1; ob_context_t* bctx = nullptr; CHECK(ob_context_create(&cfg, &bctx) == OB_OK); - bctx->simulated_mem_available_bytes = 3ULL * 1024u * 1024u * 1024u; // 3 GiB -> LMKD cap 1 GiB - bctx->mock_mode = false; // test Android HW path (2048 MiB base cap) - CHECK(ob::compute_weight_cache_budget_bytes(bctx) == 1024ULL * 1024u * 1024u); - bctx->simulated_mem_available_bytes = 12ULL * 1024u * 1024u * 1024u; // 12 GiB -> capped at 2048 MiB - CHECK(ob::compute_weight_cache_budget_bytes(bctx) == 2048ULL * 1024u * 1024u); + bctx->simulated_mem_available_bytes = 3ULL * 1024u * 1024u * 1024u; // 3 GiB -> 1536 MiB ceiling + bctx->mock_mode = false; + CHECK(ob::compute_weight_cache_budget_bytes(bctx) == 1536ULL * 1024u * 1024u); + bctx->simulated_mem_available_bytes = 12ULL * 1024u * 1024u * 1024u; // 12 GiB -> 1536 MiB ceiling + CHECK(ob::compute_weight_cache_budget_bytes(bctx) == 1536ULL * 1024u * 1024u); bctx->mock_mode = true; ob_context_destroy(bctx); @@ -6366,6 +6366,13 @@ void test_zero_repack_weight_cache_and_prepack() { CHECK(ob_context_set_profile(ctx, 1) == OB_OK); ob_profile_stats_t prof_before{}; CHECK(ob_context_get_profile(ctx, &prof_before) == OB_OK); + ob_weight_cache_stats_t cache_before{}; + CHECK(ob_context_get_weight_cache_stats(ctx, &cache_before) == OB_OK); + CHECK(cache_before.pack_count > 0u); + CHECK(cache_before.pack_count == prof_before.weight_pack_count); + CHECK(cache_before.hits == prof_before.weight_cache_hits); + CHECK(cache_before.misses == prof_before.weight_cache_misses); + CHECK(cache_before.evictions == prof_before.weight_cache_evictions); ob_invoke_stats_t ist1{}; CHECK(ob_gemm_matmul_f32_quant_batch(ctx, a_f32.data(), M, K, jobs, 3u, &ist1) == OB_OK); @@ -6374,10 +6381,19 @@ void test_zero_repack_weight_cache_and_prepack() { ob_profile_stats_t prof_after{}; CHECK(ob_context_get_profile(ctx, &prof_after) == OB_OK); + ob_weight_cache_stats_t cache_after{}; + CHECK(ob_context_get_weight_cache_stats(ctx, &cache_after) == OB_OK); CHECK(prof_after.weight_cache_misses == prof_before.weight_cache_misses); CHECK(prof_after.weight_cache_evictions == prof_before.weight_cache_evictions); CHECK(prof_after.weight_pack_us == prof_before.weight_pack_us); + CHECK(prof_after.weight_pack_count == prof_before.weight_pack_count); CHECK(prof_after.weight_cache_hits > prof_before.weight_cache_hits); + CHECK(cache_after.pack_count == cache_before.pack_count); + CHECK(cache_after.pack_us == cache_before.pack_us); + CHECK(cache_after.hits == prof_after.weight_cache_hits); + CHECK(cache_after.misses == prof_after.weight_cache_misses); + CHECK(cache_after.evictions == prof_after.weight_cache_evictions); + CHECK(cache_after.hits > cache_before.hits); // Numerical sanity vs CPU dequant reference for Q job. std::vector ref_row(K); @@ -6437,7 +6453,7 @@ void test_zero_repack_weight_cache_and_prepack() { } // 3. Budget guard & FD-entry cap: - // - auto uses LMKD-safe MemAvailable/3 (2200 MiB -> ~733 MiB) + // - auto above 2 GiB is min(1536 MiB, MemAvailable/2) (2200 MiB -> 1100 MiB) // - explicit OPENBUENOS_WEIGHT_CACHE_MB=1200 is honored // - oversized explicit OPENBUENOS_WEIGHT_CACHE_MB=2048 honors 512 MiB headroom reserve (2200 -> 1688 MiB) // - default kDefaultWeightCacheMaxEntries = 16384 and OPENBUENOS_WEIGHT_CACHE_ENTRIES honors up to 32768 @@ -6452,8 +6468,9 @@ void test_zero_repack_weight_cache_and_prepack() { ctx->mock_mode = false; ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ::unsetenv("OPENBUENOS_CACHE_CAP"); ctx->simulated_mem_available_bytes = 2200ULL * 1024u * 1024u; - CHECK(ob::compute_weight_cache_budget_bytes(ctx) == (2200ULL * 1024u * 1024u) / 3u); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1100ULL * 1024u * 1024u); ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "1200", 1); CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1200ULL * 1024u * 1024u); @@ -6528,6 +6545,183 @@ void test_external_dmabuf_map_unmap() { std::printf("[PASS] test_external_dmabuf_map_unmap\n"); } +void test_weight_cache_cap_autosize_and_telemetry() { + struct EnvGuard { + const char* name; + EnvGuard(const char* n) : name(n) { ::unsetenv(name); } + ~EnvGuard() { ::unsetenv(name); } + }; + EnvGuard guard_mb("OPENBUENOS_WEIGHT_CACHE_MB"); + EnvGuard guard_cap("OPENBUENOS_CACHE_CAP"); + + struct FixedProbe { + size_t bytes = 0; + bool fail = false; + }; + auto probe = [](size_t* out, void* user) -> bool { + auto* p = static_cast(user); + if (!out || !p || p->fail) return false; + *out = p->bytes; + return true; + }; + + constexpr uint64_t kMiB = 1024ull * 1024ull; + constexpr uint64_t kGiB = 1024ull * kMiB; + + size_t live_bytes = 0u; + const bool live_ok = ob::probe_platform_mem_available(&live_bytes); + if (live_ok) { + CHECK(live_bytes > 0u); + } + CHECK(ob::probe_platform_mem_available(nullptr) == false); + + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 1; + ob_context_t* ctx = nullptr; + CHECK(ob_context_create(&cfg, &ctx) == OB_OK); + FixedProbe mem; + ctx->mem_probe.fn = probe; + ctx->mem_probe.user = &mem; + + const uint64_t tiers[] = {4ull * kGiB, 8ull * kGiB, 12ull * kGiB, 16ull * kGiB, 24ull * kGiB}; + for (uint64_t avail : tiers) { + mem.bytes = static_cast(avail); + const size_t cap = ob::compute_weight_cache_budget_bytes(ctx); + CHECK(cap == 1536ull * kMiB); + CHECK(cap <= avail / 2u); + CHECK(avail - cap >= 512ull * kMiB); + } + + // Pixel 10 pocket: MemAvailable/3 was 896 MiB and thrashed a 916 MiB working set. + mem.bytes = static_cast(896ull * 3ull * kMiB); + const size_t pixel_cap = ob::compute_weight_cache_budget_bytes(ctx); + CHECK(pixel_cap == 1344ull * kMiB); + CHECK(pixel_cap >= 1280ull * kMiB && pixel_cap <= 1536ull * kMiB); + CHECK(pixel_cap > 916ull * kMiB); + + mem.bytes = static_cast(16ull * kGiB); + ::setenv("OPENBUENOS_CACHE_CAP", "1610612736", 1); // 1.5 GiB + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("OPENBUENOS_CACHE_CAP", "2147483648", 1); // 2 GiB + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 2ull * kGiB); + ::setenv("OPENBUENOS_CACHE_CAP", "0", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("OPENBUENOS_CACHE_CAP", "nope", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("OPENBUENOS_CACHE_CAP", "2048", 1); // historical graph-entry count + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::unsetenv("OPENBUENOS_CACHE_CAP"); + + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "0", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "abc", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "1600", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1600ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "99999", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 8192ull * kMiB); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + + // Explicit byte cap is clamped to MemAvailable - 512 MiB. + mem.bytes = static_cast(4ull * kGiB); + ::setenv("OPENBUENOS_CACHE_CAP", "4294967296", 1); // 4 GiB + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == (4ull * kGiB - 512ull * kMiB)); + ::unsetenv("OPENBUENOS_CACHE_CAP"); + + mem.fail = true; + mem.bytes = 0u; + CHECK(ob_context_set_weight_cache_cap(ctx, 1792ull * kMiB) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1792ull * kMiB); + ::setenv("OPENBUENOS_CACHE_CAP", "2147483648", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 2ull * kGiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "1600", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1600ull * kMiB); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ::unsetenv("OPENBUENOS_CACHE_CAP"); + CHECK(ob_context_set_weight_cache_cap(ctx, 0u) == OB_OK); + CHECK(ob_context_get_weight_cache_stats(nullptr, nullptr) == OB_ERR_INVALID_ARG); + ob_context_destroy(ctx); + + auto run_working_set = [&](size_t avail, const char* cap_env, uint64_t* cold_evict, + uint64_t* steady_evict, size_t* budget_out) { + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + if (cap_env) { + ::setenv("OPENBUENOS_CACHE_CAP", cap_env, 1); + } else { + ::unsetenv("OPENBUENOS_CACHE_CAP"); + } + ob_config_t c = ob_config_default(); + c.mock_mode = 1; + ob_context_t* sctx = nullptr; + CHECK(ob_context_create(&c, &sctx) == OB_OK); + FixedProbe sample; + sample.bytes = avail; + sctx->mem_probe.fn = probe; + sctx->mem_probe.user = &sample; + const size_t budget = ob::compute_weight_cache_budget_bytes(sctx); + constexpr size_t kTile = 2u * 1024u * 1024u; + constexpr size_t kWorking = 916ull * 1024ull * 1024ull; + constexpr uint32_t kTiles = static_cast(kWorking / kTile); + CHECK(static_cast(kTiles) * kTile == kWorking); + uint64_t hits = 0u; + uint64_t misses = 0u; + for (uint32_t i = 1u; i <= kTiles; ++i) { + bool hit = true; + CHECK(ob::weight_cache_sim_access(sctx, i, kTile, &hit)); + if (hit) ++hits; + else ++misses; + } + ob_weight_cache_stats_t cold{}; + CHECK(ob_context_get_weight_cache_stats(sctx, &cold) == OB_OK); + CHECK(cold.misses == misses); + CHECK(cold.hits == hits); + CHECK(cold.evictions == sctx->weight_cache_evictions); + CHECK(cold.bytes_resident == sctx->weight_cache_bytes); + CHECK(cold.bytes_resident <= budget); + CHECK(cold.budget_bytes == budget); + CHECK(cold.entries == sctx->weight_cache_map.size()); + const uint64_t evict_cold = cold.evictions; + uint64_t steady_hits = 0u; + for (uint32_t i = 1u; i <= kTiles; ++i) { + bool hit = false; + CHECK(ob::weight_cache_sim_access(sctx, i, kTile, &hit)); + if (hit) ++steady_hits; + } + ob_weight_cache_stats_t steady{}; + CHECK(ob_context_get_weight_cache_stats(sctx, &steady) == OB_OK); + CHECK(steady.hits == cold.hits + steady_hits); + CHECK(steady.evictions >= evict_cold); + CHECK(steady.bytes_resident <= budget); + CHECK(steady.pack_count == 0u); + *cold_evict = evict_cold; + *steady_evict = steady.evictions - evict_cold; + *budget_out = budget; + ob_context_destroy(sctx); + }; + + uint64_t cold_evict = 1u; + uint64_t steady_evict = 1u; + size_t budget = 0u; + run_working_set(static_cast(16ull * kGiB), nullptr, &cold_evict, &steady_evict, &budget); + CHECK(budget == 1536ull * kMiB); + CHECK(budget >= 916ull * kMiB); + CHECK(cold_evict == 0u); + CHECK(steady_evict == 0u); + + const std::string cap_896 = std::to_string(896ull * kMiB); + cold_evict = 0u; + steady_evict = 0u; + budget = 0u; + run_working_set(static_cast(16ull * kGiB), cap_896.c_str(), &cold_evict, &steady_evict, &budget); + CHECK(budget == 896ull * kMiB); + CHECK(cold_evict > 0u); + CHECK(steady_evict > 0u); + + ::unsetenv("OPENBUENOS_CACHE_CAP"); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + std::printf("[PASS] test_weight_cache_cap_autosize_and_telemetry (16 GiB -> 1536 MiB, 916 MiB working set steady evict=0, 896 MiB thrash)\n"); +} + } // namespace int main() { @@ -6544,6 +6738,7 @@ int main() { "OPENBUENOS_STRICT_WEIGHT_HASH", "OPENBUENOS_WEIGHT_CACHE_MB", "OPENBUENOS_WEIGHT_CACHE_ENTRIES", + "OPENBUENOS_CACHE_CAP", "OPENBUENOS_PARAM_SWAP_SLOTS", "OPENBUENOS_SPIN_US", "OPENBUENOS_THREADS", @@ -6584,9 +6779,10 @@ int main() { test_roundtable_s1_state_machine_hardening(); test_zero_repack_weight_cache_and_prepack(); test_external_dmabuf_map_unmap(); + test_weight_cache_cap_autosize_and_telemetry(); if (g_failures == 0) { - std::printf("ALL LIBOPENBUENOS HOST TESTS PASSED (27/27 suites)\n"); + std::printf("ALL LIBOPENBUENOS HOST TESTS PASSED (28/28 suites)\n"); return 0; } std::fprintf(stderr, "LIBOPENBUENOS HOST TESTS FAILED (%d failures)\n", g_failures); diff --git a/libopenbuenos/tests/openbuenos_selftest.cpp b/libopenbuenos/tests/openbuenos_selftest.cpp index 0916a8fc..58622fd4 100644 --- a/libopenbuenos/tests/openbuenos_selftest.cpp +++ b/libopenbuenos/tests/openbuenos_selftest.cpp @@ -37,7 +37,8 @@ void print_profile_line(const char* tag, const ob_context_t* ctx) { "hw_us=%llu wall_us=%llu quant_us=%llu hash_us=%llu pack_us=%llu " "dma_sync_us=%llu submit_us=%llu wait_us=%llu dequant_us=%llu " "sat_retries=%llu spin_hits=%llu poll_waits=%llu pool_hits=%llu pool_misses=%llu " - "w_hits=%llu w_misses=%llu w_evict=%llu w_bytes=%llu w_peak_bytes=%llu w_budget_bytes=%llu\n", + "w_hits=%llu w_misses=%llu w_evict=%llu w_bytes=%llu w_peak_bytes=%llu w_budget_bytes=%llu " + "w_pack=%llu\n", tag, static_cast(ps.calls), static_cast(ps.tiles_dispatched), @@ -65,7 +66,8 @@ void print_profile_line(const char* tag, const ob_context_t* ctx) { static_cast(ps.weight_cache_evictions), static_cast(ps.weight_cache_bytes), static_cast(ps.weight_cache_peak_bytes), - static_cast(ps.weight_cache_budget_bytes)); + static_cast(ps.weight_cache_budget_bytes), + static_cast(ps.weight_pack_count)); } bool read_file(const char* path, std::vector* out) { diff --git a/llama-cpp-edgetpu/ggml-edgetpu.cpp b/llama-cpp-edgetpu/ggml-edgetpu.cpp index 1e38fdb2..36a33856 100644 --- a/llama-cpp-edgetpu/ggml-edgetpu.cpp +++ b/llama-cpp-edgetpu/ggml-edgetpu.cpp @@ -179,6 +179,8 @@ static edgetpu_env_config load_env_config() { } } if (const char * v = std::getenv("OPENBUENOS_CACHE_CAP")) { + // 1..1048576 is the graph-entry count. Larger values are a weight-cache + // byte cap consumed by libopenbuenos (supports >= 1.5 GiB) and are ignored here. const long long parsed = std::atoll(v); if (parsed > 0 && parsed <= 1048576LL) { cfg.cache_cap = static_cast(parsed); diff --git a/llama-cpp-edgetpu/openbuenos_shim.c b/llama-cpp-edgetpu/openbuenos_shim.c index cf953739..97a70c85 100644 --- a/llama-cpp-edgetpu/openbuenos_shim.c +++ b/llama-cpp-edgetpu/openbuenos_shim.c @@ -146,6 +146,18 @@ ob_status_t ob_context_reset_profile(ob_context_t * ctx) { return ctx ? OB_OK : OB_ERR_INVALID_ARG; } +ob_status_t ob_context_set_weight_cache_cap(ob_context_t * ctx, uint64_t cap_bytes) { + (void)cap_bytes; + return ctx ? OB_OK : OB_ERR_INVALID_ARG; +} + +ob_status_t ob_context_get_weight_cache_stats(const ob_context_t * ctx, + ob_weight_cache_stats_t * out_stats) { + if (!ctx || !out_stats) return OB_ERR_INVALID_ARG; + memset(out_stats, 0, sizeof(*out_stats)); + return OB_OK; +} + int ob_context_get_freetile(const ob_context_t * ctx) { (void)ctx; return 0; From 4ab7b1d20bdc4383b0409805c24fe0ca13c3a338 Mon Sep 17 00:00:00 2001 From: Ryan S <159389674+saariuslystoned@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:37:53 -0500 Subject: [PATCH 2/2] harden(libopenbuenos): adversarial fixes for weight-cache cap path - Reject negative/malformed env values instead of letting strtoul wrap to ULONG_MAX and clamp to 8 GiB (OPENBUENOS_WEIGHT_CACHE_MB=-16 was accepted as a massive explicit cap). - Saturating size_t arithmetic for cache accounting adds, meminfo add-back, and platform MemAvailable conversion (SIZE_MAX guards). - Reclaim orphaned tiles in weight_cache_sim_access when find_locked self-evicts an oversized entry (object leak). - Fix byte accounting: evict/detach/find now credit weight_cache_bytes for ext2 bytes only and decrement outlier_cache_bytes separately. - Deallocate macOS mach host port in the MemAvailable probe. - Guard ob_gemm_emitter op640 mask shift for n_c32 >= 64 (UBSan hit). - Add openbuenos_adversarial_test (env extremes, churn/shrink, SIZE_MAX, oversize, concurrent stats/cap churn); wire into CMake. --- libopenbuenos/CMakeLists.txt | 11 + libopenbuenos/src/ob_gemm.cpp | 86 +++-- libopenbuenos/src/ob_gemm_emitter.cpp | 2 +- .../tests/openbuenos_adversarial_test.cpp | 298 ++++++++++++++++++ 4 files changed, 376 insertions(+), 21 deletions(-) create mode 100644 libopenbuenos/tests/openbuenos_adversarial_test.cpp diff --git a/libopenbuenos/CMakeLists.txt b/libopenbuenos/CMakeLists.txt index 37ab5307..942b98f6 100644 --- a/libopenbuenos/CMakeLists.txt +++ b/libopenbuenos/CMakeLists.txt @@ -128,6 +128,17 @@ if (OPENBUENOS_BUILD_TESTS) add_test(NAME openbuenos_host_test COMMAND openbuenos_host_test) add_test(NAME tpu_soc_probe_mock COMMAND tpu_soc_probe --mock) + add_executable(openbuenos_adversarial_test tests/openbuenos_adversarial_test.cpp) + target_link_libraries(openbuenos_adversarial_test PRIVATE openbuenos) + target_include_directories(openbuenos_adversarial_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${OPENBUENOS_ROOT}/docs/baremetal-vii + ${OPENBUENOS_ROOT}/docs/kernel-abi + ) + target_compile_features(openbuenos_adversarial_test PRIVATE cxx_std_17) + target_compile_options(openbuenos_adversarial_test PRIVATE ${OPENBUENOS_COMPILE_FLAGS}) + add_test(NAME openbuenos_adversarial_test COMMAND openbuenos_adversarial_test) + add_executable(ob_quant_unpack_test tests/ob_quant_unpack_test.cpp) target_link_libraries(ob_quant_unpack_test PRIVATE openbuenos) target_include_directories(ob_quant_unpack_test PRIVATE diff --git a/libopenbuenos/src/ob_gemm.cpp b/libopenbuenos/src/ob_gemm.cpp index 16e68205..11a616bd 100644 --- a/libopenbuenos/src/ob_gemm.cpp +++ b/libopenbuenos/src/ob_gemm.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #if defined(__APPLE__) @@ -370,8 +371,9 @@ void detach_timed_out_buffers_locked(ob_context* ctx, ctx, handle, {w_tile ? w_tile->ext2_buf : nullptr, in_buf, out_buf})) { if (w_tile && w_tile->in_cache) { ctx->weight_cache_map.erase(w_tile->key); - const size_t total_b = w_tile->ext2_bytes + w_tile->outlier_cols_bytes; - ctx->weight_cache_bytes -= std::min(ctx->weight_cache_bytes, total_b); + ctx->weight_cache_bytes -= std::min(ctx->weight_cache_bytes, w_tile->ext2_bytes); + ctx->outlier_cache_bytes -= + std::min(ctx->outlier_cache_bytes, w_tile->outlier_cols_bytes); ctx->weight_cache_lru.erase(w_tile->lru_it); w_tile->in_cache = false; } @@ -439,10 +441,13 @@ bool env_span_ok(const char* end) { return *end == '\0'; } -// OPENBUENOS_WEIGHT_CACHE_MB. 0 and non-numeric values are not an override. +// OPENBUENOS_WEIGHT_CACHE_MB. 0, negative and non-numeric values are not an override. bool parse_weight_cache_mb_env(size_t* out_bytes) { const char* env = std::getenv("OPENBUENOS_WEIGHT_CACHE_MB"); if (!env || !env[0] || !out_bytes) return false; + const char* first = env; + while (*first == ' ' || *first == '\t') ++first; + if (*first == '-') return false; // strtoul wraps negatives to ULONG_MAX-ish. char* end = nullptr; const unsigned long mb = std::strtoul(env, &end, 10); if (end == env || !env_span_ok(end) || mb == 0ul) return false; @@ -468,9 +473,17 @@ bool parse_cache_cap_bytes_env(size_t* out_bytes) { return true; } +size_t sat_add_size_t(size_t a, size_t b) { + const size_t kSizeMax = std::numeric_limits::max(); + if (a > kSizeMax - b) return kSizeMax; + return a + b; +} + size_t clamp_explicit_request(uint64_t bytes) { const uint64_t kMaxBytes = static_cast(kExplicitMaxMb) * kMiB; if (bytes > kMaxBytes) bytes = kMaxBytes; + const uint64_t kSizeMax = static_cast(std::numeric_limits::max()); + if (bytes > kSizeMax) bytes = kSizeMax; return static_cast(bytes); } @@ -512,7 +525,11 @@ bool read_system_mem_available_bytes(size_t* out_bytes) { while (std::fgets(line, sizeof(line), f)) { unsigned long long kb = 0ULL; if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { - *out_bytes = static_cast(kb) * 1024u; + const uint64_t kSizeMax = static_cast(std::numeric_limits::max()); + const uint64_t bytes = kb > kSizeMax / 1024u + ? kSizeMax + : kb * 1024u; + *out_bytes = static_cast(bytes); found = true; break; } @@ -522,17 +539,25 @@ bool read_system_mem_available_bytes(size_t* out_bytes) { #elif defined(__APPLE__) vm_statistics64_data_t vm{}; mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + const mach_port_t host = mach_host_self(); const kern_return_t kr = host_statistics64( - mach_host_self(), HOST_VM_INFO64, + host, HOST_VM_INFO64, reinterpret_cast(&vm), &count); + ::mach_port_deallocate(mach_task_self(), host); if (kr != KERN_SUCCESS) return false; const long page = ::sysconf(_SC_PAGESIZE); if (page <= 0) return false; - const uint64_t pages = static_cast(vm.free_count) + - static_cast(vm.inactive_count) + - static_cast(vm.speculative_count) + - static_cast(vm.purgeable_count); - const uint64_t bytes = pages * static_cast(page); + const uint64_t kSizeMax = static_cast(std::numeric_limits::max()); + const uint64_t page_sz = static_cast(page); + const uint64_t free_p = + static_cast(vm.free_count) + static_cast(vm.inactive_count); + const uint64_t pages = (free_p > kSizeMax / 4096ull) + ? (kSizeMax / 4096ull) + : (free_p + static_cast(vm.speculative_count) + + static_cast(vm.purgeable_count)); + const uint64_t bytes = (pages > kSizeMax / page_sz) + ? kSizeMax + : pages * page_sz; if (bytes == 0u) return false; *out_bytes = static_cast(bytes); return true; @@ -573,7 +598,7 @@ size_t compute_weight_cache_budget_bytes_impl(ob_context* ctx) { have_mem_avail = true; // /proc/meminfo MemAvailable excludes our own unswappable DMA-BUF cache; // add weight_cache_bytes back so our own cache cannot self-ratchet downward. - mem_avail += ctx->weight_cache_bytes; + mem_avail = sat_add_size_t(mem_avail, ctx->weight_cache_bytes); } if (have_mem_avail) { if (explicit_cap) { @@ -599,8 +624,18 @@ void ensure_weight_cache_budget(ob_context* ctx, bool refresh_meminfo = false) { } if (ctx->weight_cache_max_entries == 0u) { const char* env_e = std::getenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); + char* end = nullptr; + unsigned long lim = 0ul; + bool env_ok = false; if (env_e && env_e[0]) { - unsigned long lim = std::strtoul(env_e, nullptr, 10); + const char* first = env_e; + while (*first == ' ' || *first == '\t') ++first; + if (*first != '-') { + lim = std::strtoul(env_e, &end, 10); + env_ok = (end != env_e) && env_span_ok(end); + } + } + if (env_ok) { if (lim < 64ul) lim = 64ul; if (lim > 32768ul) lim = 32768ul; ctx->weight_cache_max_entries = static_cast(lim); @@ -617,10 +652,12 @@ void weight_cache_evict_locked(ob_context* ctx, const bool periodic_refresh = weight_cache_budget_is_dynamic(ctx) || (!ctx->mock_mode && ((ctx->weight_cache_misses & 31u) == 0u || - ctx->weight_cache_bytes + incoming_bytes > ctx->weight_cache_max_bytes)); + sat_add_size_t(ctx->weight_cache_bytes, incoming_bytes) > + ctx->weight_cache_max_bytes)); ensure_weight_cache_budget(ctx, periodic_refresh); auto it = ctx->weight_cache_lru.end(); - while ((ctx->weight_cache_bytes + incoming_bytes > ctx->weight_cache_max_bytes || + while ((sat_add_size_t(ctx->weight_cache_bytes, incoming_bytes) > + ctx->weight_cache_max_bytes || ctx->weight_cache_map.size() + incoming_entries > ctx->weight_cache_max_entries) && it != ctx->weight_cache_lru.begin()) { --it; @@ -628,8 +665,7 @@ void weight_cache_evict_locked(ob_context* ctx, if (victim == keep || victim->in_use > 0u) continue; auto erase_it = it; ctx->weight_cache_map.erase(victim->key); - const size_t victim_total = victim->ext2_bytes + victim->outlier_cols_bytes; - ctx->weight_cache_bytes -= std::min(ctx->weight_cache_bytes, victim_total); + ctx->weight_cache_bytes -= std::min(ctx->weight_cache_bytes, victim->ext2_bytes); ctx->outlier_cache_bytes -= std::min(ctx->outlier_cache_bytes, victim->outlier_cols_bytes); victim->in_cache = false; it = ctx->weight_cache_lru.erase(erase_it); @@ -661,7 +697,7 @@ CachedWeightTile* weight_cache_find_locked(ob_context* ctx, const WeightTileKey& if (t->in_cache && t_total > ctx->weight_cache_max_bytes) { ctx->weight_cache_map.erase(t->key); ctx->weight_cache_lru.erase(t->lru_it); - ctx->weight_cache_bytes -= std::min(ctx->weight_cache_bytes, t_total); + ctx->weight_cache_bytes -= std::min(ctx->weight_cache_bytes, t->ext2_bytes); t->in_cache = false; ctx->weight_cache_evictions += 1u; } @@ -671,7 +707,8 @@ CachedWeightTile* weight_cache_find_locked(ob_context* ctx, const WeightTileKey& bool weight_cache_insert_locked(ob_context* ctx, CachedWeightTile* tile) { weight_cache_evict_locked(ctx, tile->ext2_bytes); - if (ctx->weight_cache_bytes + tile->ext2_bytes > ctx->weight_cache_max_bytes || + if (sat_add_size_t(ctx->weight_cache_bytes, tile->ext2_bytes) > + ctx->weight_cache_max_bytes || ctx->weight_cache_map.size() >= ctx->weight_cache_max_entries) { tile->in_cache = false; return false; @@ -707,7 +744,8 @@ ob_status_t weight_cache_prepare_space_locked(ob_context* ctx, return OB_OK; } weight_cache_evict_locked(ctx, incoming_bytes); - while ((ctx->weight_cache_bytes + incoming_bytes > ctx->weight_cache_max_bytes || + while ((sat_add_size_t(ctx->weight_cache_bytes, incoming_bytes) > + ctx->weight_cache_max_bytes || ctx->weight_cache_map.size() >= ctx->weight_cache_max_entries) && ring_count > 0u) { ob_status_t dst = drain_one(); @@ -715,7 +753,8 @@ ob_status_t weight_cache_prepare_space_locked(ob_context* ctx, weight_cache_evict_locked(ctx, incoming_bytes); } *out_cacheable = - (ctx->weight_cache_bytes + incoming_bytes <= ctx->weight_cache_max_bytes) && + (sat_add_size_t(ctx->weight_cache_bytes, incoming_bytes) <= + ctx->weight_cache_max_bytes) && (ctx->weight_cache_map.size() < ctx->weight_cache_max_entries); return OB_OK; } @@ -2389,6 +2428,13 @@ bool weight_cache_sim_access(ob_context* ctx, uint64_t tag, size_t bytes, bool* if (out_hit) *out_hit = true; return true; } + // find_locked hands back a self-evicted (oversized) tile that production + // callers consume under PinnedWeightTile. This host-only helper holds no + // pin, so reclaim it here instead of leaking it. + if (existing) { + if (existing->ext2_buf) ob_buffer_free(existing->ext2_buf); + delete existing; + } CachedWeightTile* tile = new (std::nothrow) CachedWeightTile(); if (!tile) return false; tile->key = key; diff --git a/libopenbuenos/src/ob_gemm_emitter.cpp b/libopenbuenos/src/ob_gemm_emitter.cpp index bebe1539..3789d3d1 100644 --- a/libopenbuenos/src/ob_gemm_emitter.cpp +++ b/libopenbuenos/src/ob_gemm_emitter.cpp @@ -739,7 +739,7 @@ Pkt build_op640(uint32_t d, float scale, int32_t zp) { Pkt fl(std::begin(kBaseOp640), std::end(kBaseOp640)); uint32_t n_c32 = (d + 31u) / 32u; if (n_c32 > 1u) { - uint64_t mask = (1ULL << n_c32) - 1ULL; + uint64_t mask = (n_c32 >= 64u) ? ~0ULL : ((1ULL << n_c32) - 1ULL); fl[0].lo = (fl[0].lo & 0xFFFFFFFFFFFF0FFFULL) | (mask << 12); fl[0].hi = 0x0000043000000000ULL; } diff --git a/libopenbuenos/tests/openbuenos_adversarial_test.cpp b/libopenbuenos/tests/openbuenos_adversarial_test.cpp new file mode 100644 index 00000000..c1f5c3a3 --- /dev/null +++ b/libopenbuenos/tests/openbuenos_adversarial_test.cpp @@ -0,0 +1,298 @@ +// Adversarial hardening tests for libopenbuenos weight-cache cap path. +// Covers: extreme env vars, cap values, churn, shrink, concurrent access, +// oversized tiles, SIZE_MAX/overflow guards. Built standalone with +// ASan+UBSan (and TSan for the concurrency suite) against the host sources. +#include "openbuenos.h" +#include "ob_internal.h" +#include "litebuf_vii_wire.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "[FAIL] %s:%d: CHECK(%s)\n", __FILE__, __LINE__, \ + #cond); \ + ++g_failures; \ + } \ + } while (0) + +constexpr uint64_t kMiB = 1024ull * 1024ull; +constexpr uint64_t kGiB = 1024ull * kMiB; + +struct FixedProbe { + size_t bytes = 0; + bool fail = false; +}; + +bool probe_fn(size_t* out, void* user) { + auto* p = static_cast(user); + if (!out || !p || p->fail) return false; + *out = p->bytes; + return true; +} + +struct CtxGuard { + ob_context_t* ctx = nullptr; + ~CtxGuard() { + if (ctx) ob_context_destroy(ctx); + } +}; + +CtxGuard make_ctx(FixedProbe* mem) { + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 1; + ob_context_t* raw = nullptr; + if (ob_context_create(&cfg, &raw) != OB_OK) return CtxGuard{}; + if (mem) { + raw->mem_probe.fn = probe_fn; + raw->mem_probe.user = mem; + } + return CtxGuard{raw}; +} + +void unset_cache_env() { + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ::unsetenv("OPENBUENOS_CACHE_CAP"); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); +} + +void test_env_extremes() { + unset_cache_env(); + FixedProbe mem; + mem.bytes = static_cast(16ull * kGiB); + auto g = make_ctx(&mem); + CHECK(g.ctx != nullptr); + + // OPENBUENOS_WEIGHT_CACHE_MB hostile values. + const char* bad_mb[] = {"", "abc", "-16", "-8192", "0", "16.5", "100abc", + "0x40", "1e3", " -5", "+"}; + for (const char* v : bad_mb) { + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", v, 1); + // All must be ignored -> auto 1536 MiB at 16 GiB. + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + } + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "1", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 16ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "15", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 16ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "8193", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 8192ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "99999999999999999999999999", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 8192ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", " 100 ", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 100ull * kMiB); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + + // OPENBUENOS_CACHE_CAP hostile values. + const char* small_cap[] = {"0", "1", "1048576", "-5", "-1048577", "nope", ""}; + for (const char* v : small_cap) { + ::setenv("OPENBUENOS_CACHE_CAP", v, 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + } + ::setenv("OPENBUENOS_CACHE_CAP", "1048577", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1048577ull); + ::setenv("OPENBUENOS_CACHE_CAP", "9223372036854775807", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 8192ull * kMiB); + ::setenv("OPENBUENOS_CACHE_CAP", "18446744073709551615", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 8192ull * kMiB); + ::setenv("OPENBUENOS_CACHE_CAP", "1610612736", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + ::unsetenv("OPENBUENOS_CACHE_CAP"); + + // Precedence: MB env beats CACHE_CAP env beats API cap. + ::setenv("OPENBUENOS_CACHE_CAP", "2147483648", 1); + CHECK(ob_context_set_weight_cache_cap(g.ctx, 1024ull * kMiB) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 2ull * kGiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "1600", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1600ull * kMiB); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + ::unsetenv("OPENBUENOS_CACHE_CAP"); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1024ull * kMiB); + // API caps 0 / 1 / UINT64_MAX. + CHECK(ob_context_set_weight_cache_cap(g.ctx, 0u) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + CHECK(ob_context_set_weight_cache_cap(g.ctx, 1u) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1ull * kMiB); + CHECK(ob_context_set_weight_cache_cap(g.ctx, + std::numeric_limits::max()) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 8192ull * kMiB); + // >4 GiB API cap with headroom clamp. + mem.bytes = static_cast(4ull * kGiB); + CHECK(ob_context_set_weight_cache_cap(g.ctx, 8ull * kGiB) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 4ull * kGiB - 512ull * kMiB); + unset_cache_env(); +} + +void test_mem_tiers() { + unset_cache_env(); + FixedProbe mem; + auto g = make_ctx(&mem); + CHECK(g.ctx != nullptr); + const struct { + uint64_t avail; + uint64_t cap; + } tiers[] = {{0, 1ull * kMiB}, + {1ull * kMiB, 1ull * kMiB}, + {640ull * kMiB, (640ull * kMiB) / 3u}, + {641ull * kMiB, (641ull * kMiB) / 3u}, + {2ull * kGiB, 1ull * kGiB}, + {4ull * kGiB, 1536ull * kMiB}, + {16ull * kGiB, 1536ull * kMiB}, + {64ull * kGiB, 1536ull * kMiB}}; + for (size_t i = 0; i < sizeof(tiers) / sizeof(tiers[0]); ++i) { + mem.bytes = static_cast(tiers[i].avail); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == tiers[i].cap); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) <= + tiers[i].avail || tiers[i].cap == 1ull * kMiB); + } + // Probe failure with no sample falls back to mock default. + mem.fail = true; + mem.bytes = 0u; + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 256ull * kMiB); + CHECK(ob_context_set_weight_cache_cap(g.ctx, 1792ull * kMiB) == OB_OK); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1792ull * kMiB); + CHECK(ob_context_set_weight_cache_cap(g.ctx, 0u) == OB_OK); + unset_cache_env(); +} + +void test_churn_shrink_oversize() { + unset_cache_env(); + // Churn: 200k random-ish insert/evict ops with shrinking budget. + FixedProbe mem; + mem.bytes = static_cast(16ull * kGiB); + auto g = make_ctx(&mem); + CHECK(g.ctx != nullptr); + uint64_t calls = 0; + for (uint32_t i = 0; i < 200000u; ++i) { + if (i == 100000u) { + // Shrink budget mid-stream: resident tiles become oversized. + CHECK(ob_context_set_weight_cache_cap(g.ctx, 32ull * kMiB) == OB_OK); + mem.fail = true; // keep explicit API cap exact + } + const size_t tile_bytes = + static_cast(1ull + (i * 2654435761u % 4096u)) * 1024u; + bool hit = true; + ob::weight_cache_sim_access(g.ctx, i % 50000u, tile_bytes, &hit); + ++calls; + if ((i & 0xFFFFu) == 0u) { + ob_weight_cache_stats_t s{}; + CHECK(ob_context_get_weight_cache_stats(g.ctx, &s) == OB_OK); + CHECK(s.bytes_resident <= s.budget_bytes); + CHECK(s.bytes_resident == g.ctx->weight_cache_bytes); + CHECK(g.ctx->weight_cache_map.size() <= 16384u); + } + } + ob_weight_cache_stats_t s{}; + CHECK(ob_context_get_weight_cache_stats(g.ctx, &s) == OB_OK); + CHECK(s.hits + s.misses == calls); + CHECK(s.bytes_resident <= s.budget_bytes); + CHECK(s.entries == g.ctx->weight_cache_map.size()); + + // Oversized single tile: must not be resident, must not corrupt accounting. + FixedProbe mem2; + mem2.bytes = static_cast(16ull * kGiB); + auto g2 = make_ctx(&mem2); + CHECK(ob_context_set_weight_cache_cap(g2.ctx, 64ull * kMiB) == OB_OK); + mem2.fail = true; + bool hit = true; + CHECK(!ob::weight_cache_sim_access(g2.ctx, 999u, 128ull * kMiB, &hit)); + CHECK(!hit); + ob_weight_cache_stats_t s2{}; + CHECK(ob_context_get_weight_cache_stats(g2.ctx, &s2) == OB_OK); + CHECK(s2.bytes_resident == 0u); + // SIZE_MAX tile: saturating adds must reject without wrapping accounting. + CHECK(!ob::weight_cache_sim_access(g2.ctx, 1000u, + std::numeric_limits::max(), &hit)); + CHECK(!hit); + CHECK(ob_context_get_weight_cache_stats(g2.ctx, &s2) == OB_OK); + CHECK(s2.bytes_resident == 0u); + // Cache still functional after hostile inputs. + CHECK(ob::weight_cache_sim_access(g2.ctx, 1001u, 8ull * kMiB, &hit)); + CHECK(!hit); + CHECK(ob_context_get_weight_cache_stats(g2.ctx, &s2) == OB_OK); + CHECK(s2.bytes_resident == 8ull * kMiB); + // Shrink below a resident tile, then hit it: find self-evicts and the + // host helper must reclaim the orphan (no leak, miss reported). + CHECK(ob_context_set_weight_cache_cap(g2.ctx, 1ull * kMiB) == OB_OK); + CHECK(!ob::weight_cache_sim_access(g2.ctx, 1001u, 8ull * kMiB, &hit)); + CHECK(!hit); + CHECK(ob_context_get_weight_cache_stats(g2.ctx, &s2) == OB_OK); + CHECK(s2.bytes_resident == 0u); + // Zero-byte access rejected. + CHECK(!ob::weight_cache_sim_access(g2.ctx, 1002u, 0u, &hit)); + // Null-arg stats rejected. + CHECK(ob_context_get_weight_cache_stats(nullptr, nullptr) == OB_ERR_INVALID_ARG); + CHECK(ob_context_get_weight_cache_stats(g2.ctx, nullptr) == OB_ERR_INVALID_ARG); + CHECK(ob_context_set_weight_cache_cap(nullptr, 1u) == OB_ERR_INVALID_ARG); + unset_cache_env(); +} + +void test_concurrent() { + unset_cache_env(); + FixedProbe mem; + mem.bytes = static_cast(16ull * kGiB); + auto g = make_ctx(&mem); + CHECK(g.ctx != nullptr); + constexpr int kThreads = 8; + constexpr int kIters = 20000; + std::atomic calls{0}; + std::atomic stop_caps{false}; + std::vector ts; + for (int t = 0; t < kThreads; ++t) { + ts.emplace_back([&] { + for (int i = 0; i < kIters; ++i) { + bool hit = false; + ob::weight_cache_sim_access(g.ctx, static_cast(i % 1000), + static_cast(256u * 1024u), &hit); + calls.fetch_add(1u, std::memory_order_relaxed); + ob_weight_cache_stats_t s{}; + ob_context_get_weight_cache_stats(g.ctx, &s); + ob_profile_stats_t p{}; + ob_context_get_profile(g.ctx, &p); + CHECK(s.bytes_resident <= s.budget_bytes); + } + }); + } + std::thread cap_churn([&] { + uint64_t v = 256ull * kMiB; + while (!stop_caps.load(std::memory_order_relaxed)) { + ob_context_set_weight_cache_cap(g.ctx, v); + v = v > 256ull * kMiB ? 256ull * kMiB : 512ull * kMiB; + } + }); + for (auto& th : ts) th.join(); + stop_caps.store(true); + cap_churn.join(); + ob_weight_cache_stats_t s{}; + CHECK(ob_context_get_weight_cache_stats(g.ctx, &s) == OB_OK); + CHECK(s.hits + s.misses >= calls.load()); + unset_cache_env(); +} + +} // namespace + +int main() { + unset_cache_env(); + test_env_extremes(); + test_mem_tiers(); + test_churn_shrink_oversize(); + test_concurrent(); + if (g_failures == 0) { + std::printf("[PASS] adversarial weight-cache hardening suite\n"); + return 0; + } + std::fprintf(stderr, "ADVERSARIAL SUITE FAILED (%d failures)\n", g_failures); + return 1; +}