diff --git a/engine/metal/poly_tests/memory_growth.cpp b/engine/metal/poly_tests/memory_growth.cpp index af6403d536..cf14d20bba 100644 --- a/engine/metal/poly_tests/memory_growth.cpp +++ b/engine/metal/poly_tests/memory_growth.cpp @@ -3,6 +3,7 @@ #include "strata/gpu/metal.hpp" #include #include +#include #include #include #include @@ -13,17 +14,22 @@ namespace g = strata::gpu; using strata::poly::Layer; static void ck(g::Error e) { if (e != g::kSuccess) throw std::runtime_error(g::error_string(e)); } static void require(bool ok, const char* what) { if (!ok) throw std::runtime_error(what); } +static constexpr uint32_t kTestQ8_0 = 8; // GGML_TYPE_Q8_0 // Exercise the real engine allocation, sequence and graph machinery without a model or memory-pressure // dependency. Only the host-memory reading and architecture-specific operations are replaced. class MemoryEngine final : public strata::poly::Engine { public: std::optional host = uint64_t(64) << 30; + std::optional small_host; + uint64_t total_ram = uint64_t(64) << 30; + std::optional mock_metal_used; bool fail_rebind = false; bool mock_cache = false; unsigned resizes = 0; size_t resized_to = 0; void *key = nullptr, *value = nullptr, *ring = nullptr; + std::vector dummy_exp_backing; explicit MemoryEngine(bool balanced = true, bool whole = false) { opt_.metal_balanced = balanced; @@ -41,12 +47,52 @@ class MemoryEngine final : public strata::poly::Engine { size_t allocations() const { return dev_allocs_.size(); } int64_t covered() const { return kv_rows_; } size_t headroom() { return metal_host_headroom(); } + size_t host_reserve() const { return metal_host_reserve(); } + size_t small_cap() const { return metal_small_ram_cap(); } + static std::optional eval_small_ram_vm(std::optional file_backed, + uint64_t total, + uint64_t wired, + uint64_t reclaim) { + return metal_small_ram_avail_from_vm(file_backed, total, wired, reclaim); + } + void set_cache_bytes(size_t b) { metal_cache_bytes_ = b; } void policy_fixture() { mock_cache = true; opt_.gpu_experts = true; n_moe_ = 1; n_expert_ = 2; cached_ = 0; metal_cache_bytes_ = size_t(1) << 20; } bool mind() { return metal_mind_memory(); } void freeze_policy() { freeze_experts_ = true; } + void small_cache_fill_fixture(int n_exp, size_t mat_bytes) { + const auto path = std::filesystem::temp_directory_path() / + ("poly-metal-small-cache-" + std::to_string(getpid()) + ".gguf"); + const uint64_t header[] = {(uint64_t(3) << 32) | 0x46554747, 0, 0, 0}; + { std::ofstream out(path, std::ios::binary); out.write(reinterpret_cast(header), sizeof(header)); } + try { gg_ = std::make_unique(path.string()); } + catch (...) { std::filesystem::remove(path); throw; } + std::filesystem::remove(path); + opt_.gpu_experts = true; + opt_.expert_swaps = 0; + n_moe_ = 1; + n_expert_ = n_exp; + cached_ = 0; + exp_at_ = 0; + scratch_at_ = 0; + recorded_ = false; + metal_cache_limit_ = SIZE_MAX; + metal_cache_bytes_ = 0; + dummy_exp_backing.assign((size_t) n_exp * mat_bytes, 0); + Layer& L = layers_[0]; + L.moe = true; + L.gu_type = L.u_type = L.d_type = kTestQ8_0; + L.gu_bytes = L.u_bytes = L.d_bytes = mat_bytes; + L.gu_stride = L.u_stride = mat_bytes; + L.exp_gate = dummy_exp_backing.data(); + L.exp_up = dummy_exp_backing.data(); + L.exp_down = dummy_exp_backing.data(); + L.slot.assign((size_t) n_exp, nullptr); + use_.assign((size_t) n_exp, 0); + fill_expert_cache(); + } void fill(unsigned char byte) { for (const auto& b : bufs_) ck(g::memset_async(b.p, byte, b.capacity, static_cast(st_))); ck(g::stream_synchronize(static_cast(st_))); @@ -109,6 +155,11 @@ class MemoryEngine final : public strata::poly::Engine { } protected: std::optional metal_host_available() const override { return host; } + std::optional metal_small_ram_host_avail() const override { return small_host ? small_host : host; } + uint64_t metal_host_total_bytes() const override { return total_ram; } + size_t metal_current_allocated_bytes() const override { + return mock_metal_used ? *mock_metal_used : Engine::metal_current_allocated_bytes(); + } void metal_resize_cache(size_t limit) override { if (!mock_cache) { Engine::metal_resize_cache(limit); return; } ++resizes; resized_to = limit; metal_cache_bytes_ = limit; @@ -207,6 +258,184 @@ int main() { e.freeze_policy(); e.host = 0; require(!e.mind() && e.resizes == 2, "memory pressure resized frozen experts"); } + { + // Adaptive <= 24 GiB balanced Metal budget: 1.5 GiB reserve on <= 16 GiB, total_ram/8 on (16, 24] GiB, + // 48% hard Metal working-set cap on <= 24 GiB, and 100% unchanged 4 GiB / no cap above 24 GiB or unknown. + constexpr uint64_t kGiB = uint64_t(1) << 30; + constexpr uint64_t kMiB = uint64_t(1) << 20; + MemoryEngine e; + e.total_ram = 0; + require(e.host_reserve() == 4 * kGiB && e.small_cap() == SIZE_MAX, + "unknown RAM did not keep 4 GiB reserve and uncapped working set"); + e.total_ram = 24 * kGiB + 1; + require(e.host_reserve() == 4 * kGiB && e.small_cap() == SIZE_MAX, + ">24 GiB RAM did not keep 4 GiB reserve and uncapped working set"); + + // 16 GiB Apple Silicon Mac + const size_t cap16 = size_t((16 * kGiB / 100) * 48 + ((16 * kGiB % 100) * 48) / 100); + e.total_ram = 16 * kGiB; + require(e.host_reserve() == 1536 * kMiB, "16 GiB Mac host reserve is not 1.5 GiB"); + require(e.small_cap() == cap16, "16 GiB Mac working-set cap is not 48% of RAM"); + + // Busy 16 GB desktop (~2.6 GiB dense+KV used, ~3.5 GiB available host): gets 2.0 GiB headroom (not 0!) + const size_t used_dense = size_t(2600) * kMiB; + e.mock_metal_used = used_dense; + e.host = 3584 * kMiB; + require(e.headroom() == 3584 * kMiB - 1536 * kMiB, + "16 GiB busy desktop did not apply 1.5 GiB host reserve"); + + // Quiet 16 GB desktop (~9 GiB available host): clamped to 48% hard Metal cap (7.68 GiB - 2.6 GiB) + e.host = 9 * kGiB; + require(e.headroom() == cap16 - used_dense, + "16 GiB quiet desktop was not clamped by 48% Metal working-set cap"); + + // Over-cap Metal usage: 0 headroom even with ample host RAM + e.mock_metal_used = 8 * kGiB; + e.host = 6 * kGiB; + require(e.headroom() == 0, "16 GiB over-cap Metal usage did not yield 0 headroom"); + + // Host reading unavailable on 16 GiB Mac still enforces the 48% cap + e.mock_metal_used = used_dense; + e.host.reset(); + require(e.headroom() == cap16 - used_dense, + "16 GiB unknown host memory did not enforce 48% Metal working-set cap"); + + // metal_mind_memory() on 16 GiB Mac: host-reserve shrink, 48%-cap shrink, and capped 2-sample growth + MemoryEngine p16; + p16.total_ram = 16 * kGiB; + p16.policy_fixture(); + p16.mock_metal_used = used_dense + (size_t(1) << 20); + p16.host = 1536 * kMiB - (uint64_t(512) << 10); + require(p16.mind() && p16.resizes == 1 && p16.resized_to == (size_t(512) << 10), + "16 GiB pressure did not shrink by 1.5 GiB host-reserve deficit"); + + // Exceeding 48% cap shrinks cache immediately even when host memory looks plentiful + const size_t over_cache = size_t(5500) * kMiB; + p16.set_cache_bytes(over_cache); + p16.mock_metal_used = used_dense + over_cache; + p16.host = 6 * kGiB; + require(p16.mind() && p16.resizes == 2 && p16.resized_to == cap16 - used_dense, + "16 GiB metal_mind_memory did not shrink cache to 48% cap"); + + // Growing from 1 GiB cache on quiet 16 GiB Mac respects 2-sample hysteresis and stops at 48% cap + const size_t small_cache = size_t(1) * kGiB; + p16.set_cache_bytes(small_cache); + p16.mock_metal_used = used_dense + small_cache; + p16.host = 8 * kGiB; + require(!p16.mind() && p16.resizes == 2, "16 GiB cache grew on first high-headroom sample"); + require(p16.mind() && p16.resizes == 3 && p16.resized_to == cap16 - used_dense, + "16 GiB cache did not grow cleanly to 48% cap on second sample"); + + // 24 GiB Apple Silicon Mac: host reserve = 24 / 8 = 3 GiB, cap = 48% of 24 GiB (~11.52 GiB) + const size_t cap24 = size_t((24 * kGiB / 100) * 48 + ((24 * kGiB % 100) * 48) / 100); + e.total_ram = 24 * kGiB; + e.mock_metal_used = 3 * kGiB; + require(e.host_reserve() == 3 * kGiB, "24 GiB Mac host reserve is not 3 GiB"); + require(e.small_cap() == cap24, "24 GiB Mac working-set cap is not 48% of RAM"); + e.host = 5 * kGiB; + require(e.headroom() == 2 * kGiB, "24 GiB Mac did not apply 3 GiB host reserve"); + e.host = 14 * kGiB; + require(e.headroom() == cap24 - 3 * kGiB, "24 GiB Mac was not clamped by 48% cap"); + + // STRATA_METAL_HOST_RESERVE_MIB override + struct EnvGuard { + const char* key; + std::optional prev; + explicit EnvGuard(const char* k) : key(k) { + if (const char* v = std::getenv(k)) prev = std::string(v); + } + ~EnvGuard() { + if (prev) setenv(key, prev->c_str(), 1); + else unsetenv(key); + } + } env_guard("STRATA_METAL_HOST_RESERVE_MIB"); + e.total_ram = 16 * kGiB; + setenv("STRATA_METAL_HOST_RESERVE_MIB", "2048", 1); + require(e.host_reserve() == 2 * kGiB, "STRATA_METAL_HOST_RESERVE_MIB override was ignored"); + unsetenv("STRATA_METAL_HOST_RESERVE_MIB"); + require(e.host_reserve() == 1536 * kMiB, "unsetting STRATA_METAL_HOST_RESERVE_MIB did not restore 1.5 GiB"); + } + { + // <= 24 GiB balanced Metal small-RAM availability helper (wired <= 55% vs > 55% guard), + // fill_expert_cache() reduced 128 MiB initial cushion, and metal_mind_memory() consistency. + constexpr uint64_t kGiB = uint64_t(1) << 30; + constexpr uint64_t kMiB = uint64_t(1) << 20; + const uint64_t total16 = 16 * kGiB; + const uint64_t wired55 = (total16 / 100) * 55 + ((total16 % 100) * 55) / 100; + + // Healthy 16 GiB Mac (wired 18% <= 55%): uses reclaimable (free + purgeable + inactive). + const auto healthy = MemoryEngine::eval_small_ram_vm(1200 * kMiB, total16, 2932 * kMiB, 4062 * kMiB); + require(healthy && *healthy == 4062 * kMiB, + "healthy <= 24 GiB Mac did not count reclaimable inactive pages"); + + // Exact 55% boundary still allows reclaimable; 55% + 1 byte triggers strict file-backed fallback. + const auto at55 = MemoryEngine::eval_small_ram_vm(1200 * kMiB, total16, wired55, 4062 * kMiB); + require(at55 && *at55 == 4062 * kMiB, "wired == 55% wrongly triggered fallback"); + const auto over55 = MemoryEngine::eval_small_ram_vm(1200 * kMiB, total16, wired55 + 1, 4062 * kMiB); + require(over55 && *over55 == 1200 * kMiB, + "wired > 55% did not fall back strictly to conservative file-backed availability"); + + // Overlapping reclaimable pages cannot exceed non_wired (total - wired). + const auto clamped = MemoryEngine::eval_small_ram_vm(1200 * kMiB, total16, 8 * kGiB, 10 * kGiB); + require(clamped && *clamped == 8 * kGiB, "reclaimable was not bounded by non_wired"); + + // Unknown conservative availability stays unknown (triggers 48% cap fallback). + const auto unknown = MemoryEngine::eval_small_ram_vm(std::nullopt, total16, 2 * kGiB, 4 * kGiB); + require(!unknown.has_value(), "unknown file-backed availability did not stay unknown"); + + // Consistency between metal_host_headroom() and metal_mind_memory() on 16 GiB Mac: + // conservative file-backed is below 1.5 GiB reserve (would have given 0 headroom / shrunk cache), + // while small-RAM reclaimable is healthy (4,062 MiB). + MemoryEngine s16; + s16.total_ram = total16; + s16.mock_metal_used = 2939 * kMiB; + s16.host = 1200 * kMiB; + s16.small_host = 4062 * kMiB; + require(s16.headroom() == 4062 * kMiB - 1536 * kMiB, + "16 GiB headroom did not use metal_small_ram_host_avail()"); + + MemoryEngine m16; + m16.total_ram = total16; + m16.policy_fixture(); + const size_t held = 2000 * kMiB; + m16.set_cache_bytes(held); + m16.mock_metal_used = 2939 * kMiB + held; + m16.host = 300 * kMiB; // conservative file-backed would demand immediate shrink! + m16.small_host = 1600 * kMiB; // reclaimable stays above 1,536 MiB reserve + require(!m16.mind() && m16.resizes == 0, + "16 GiB metal_mind_memory() inconsistently shrank cache using conservative host_available()"); + + // If small-RAM availability drops (e.g. wired > 55% falls back to conservative 1,200 MiB), shrink immediately. + m16.small_host = 1200 * kMiB; + require(m16.mind() && m16.resizes == 1 && m16.resized_to == (1200 * kMiB + held - 1536 * kMiB), + "16 GiB metal_mind_memory() did not shrink under small-RAM pressure"); + + // > 24 GiB Macs stay 100% unchanged: ignore small_host and use metal_host_available() strictly. + MemoryEngine big; + big.total_ram = 32 * kGiB; + big.host = 5 * kGiB; + big.small_host = 12 * kGiB; + require(big.headroom() == 1 * kGiB, "> 24 GiB Mac wrongly used small-RAM availability"); + + // fill_expert_cache() reduced 128 MiB initial cushion on <= 24 GiB vs unchanged 512 MiB on > 24 GiB: + // with 200 MiB headroom and 384 MiB total experts (above 128 MiB, below 512 MiB, triggering arena < all), + // 16 GiB caches experts (~72 MiB arena -> 1 expert) while 32 GiB leaves 0. + MemoryEngine f16; + f16.total_ram = total16; + f16.mock_metal_used = 2 * kGiB; + f16.host = 1000 * kMiB; + f16.small_host = (1536 + 200) * kMiB; // headroom = 200 MiB + f16.small_cache_fill_fixture(/*n_exp=*/8, /*mat_bytes=*/size_t(16) << 20); + require(f16.cached_experts() == 1, + "16 GiB fill_expert_cache() did not apply reduced 128 MiB initial cushion"); + + MemoryEngine f32; + f32.total_ram = 32 * kGiB; + f32.host = (4096 + 200) * kMiB; // headroom = 200 MiB (< 512 MiB >24 GiB cushion) + f32.small_cache_fill_fixture(/*n_exp=*/8, /*mat_bytes=*/size_t(16) << 20); + require(f32.cached_experts() == 0, + "> 24 GiB fill_expert_cache() did not preserve 512 MiB initial cushion"); + } { MemoryEngine legacy(false), whole(true, true); require(legacy.capacity() == 12288 * 8 && whole.capacity() == 12288 * 8, "legacy/whole KV changed"); diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 0da6fe0bfd..2afb3cd42e 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -75,7 +75,9 @@ #include #endif #if defined(__APPLE__) +#include #include +#include #endif namespace strata::poly { @@ -1774,22 +1776,121 @@ void Engine::vmm_free(Mapped& m) { #if defined(STRATA_GPU_METAL) namespace { constexpr size_t kMetalHostReserve = size_t(4) << 30; +constexpr uint64_t kMetalSmallRamBytes = uint64_t(24) << 30; +constexpr uint64_t kMetal16GbRamBytes = uint64_t(16) << 30; +constexpr size_t kMetal16GbHostReserve = size_t(1536) << 20; +constexpr size_t kMetalSmallInitCushion = size_t(128) << 20; constexpr size_t kMetalGrowthMargin = size_t(512) << 20; constexpr size_t kMetalRefillCushion = size_t(256) << 20; } +uint64_t Engine::metal_system_ram_bytes() { + static const uint64_t ram = [] { +#if defined(__APPLE__) + uint64_t mem = 0; + size_t len = sizeof(mem); + if (sysctlbyname("hw.memsize", &mem, &len, nullptr, 0) == 0 && len == sizeof(mem)) return mem; +#endif + return uint64_t(0); + }(); + return ram; +} + +std::optional Engine::metal_small_ram_avail_from_vm( + std::optional file_backed_avail, + uint64_t total_ram, + uint64_t wired_bytes, + uint64_t reclaimable_bytes) { + if (!file_backed_avail || total_ram == 0) return file_backed_avail; + // Hard OOM / external-GPU-pressure guard: if wired pages exceed 55% of RAM, stay strictly on conservative + // free + file-backed availability so balanced Metal backs off before hitting IOGPU OOM. + const uint64_t wired_limit = (total_ram / 100) * 55 + ((total_ram % 100) * 55) / 100; + if (wired_bytes > wired_limit) return file_backed_avail; + const uint64_t non_wired = total_ram > wired_bytes ? total_ram - wired_bytes : 0; + const uint64_t reclaim = std::min(reclaimable_bytes, non_wired); + return std::min(non_wired, std::max(*file_backed_avail, reclaim)); +} + std::optional Engine::metal_host_available() const { return strata::core::available_host_bytes(); } +std::optional Engine::metal_small_ram_host_avail() const { + const auto file_backed = metal_host_available(); + const uint64_t total_ram = metal_host_total_bytes(); + if (!file_backed || total_ram == 0 || strata::core::memory_limit_bytes() > 0) return file_backed; +#if defined(__APPLE__) + vm_statistics64_data_t vs{}; + mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &count) != KERN_SUCCESS) + return file_backed; + const uint64_t pg = (uint64_t) vm_page_size; + const uint64_t wired = (uint64_t) vs.wire_count * pg; + // Note: XNU already includes speculative_count inside free_count (). + const uint64_t reclaimable = + ((uint64_t) vs.free_count + vs.purgeable_count + vs.inactive_count) * pg; + return metal_small_ram_avail_from_vm(file_backed, total_ram, wired, reclaimable); +#else + return file_backed; +#endif +} + +uint64_t Engine::metal_host_total_bytes() const { + return metal_system_ram_bytes(); +} + +size_t Engine::metal_current_allocated_bytes() const { + size_t free_b = 0, total_b = 0; + ck(cudaMemGetInfo(&free_b, &total_b), "balanced Metal budget"); + return total_b > free_b ? total_b - free_b : 0; +} + +size_t Engine::metal_host_reserve() const { + if (const char* v = std::getenv("STRATA_METAL_HOST_RESERVE_MIB"); v && *v) { + char* end = nullptr; + const long long parsed = std::strtoll(v, &end, 10); + if (end != v && *end == '\0' && parsed >= 0 && uint64_t(parsed) <= (SIZE_MAX >> 20)) + return size_t(parsed) << 20; + } + const uint64_t total_ram = metal_host_total_bytes(); + if (total_ram == 0 || total_ram > kMetalSmallRamBytes) return kMetalHostReserve; + if (total_ram <= kMetal16GbRamBytes) return kMetal16GbHostReserve; + return std::clamp(size_t(total_ram / 8), kMetal16GbHostReserve, kMetalHostReserve); +} + +size_t Engine::metal_small_ram_cap() const { + const uint64_t total_ram = metal_host_total_bytes(); + if (total_ram == 0 || total_ram > kMetalSmallRamBytes) return SIZE_MAX; + return size_t((total_ram / 100) * 48 + ((total_ram % 100) * 48) / 100); +} + size_t Engine::metal_host_headroom() { - const auto memory = metal_host_available(); - if (memory) return *memory > kMetalHostReserve ? size_t(*memory - kMetalHostReserve) : 0; - if (!metal_host_warning_) { + const size_t host_reserve = metal_host_reserve(); + const size_t small_cap = metal_small_ram_cap(); + size_t room = SIZE_MAX; + const auto memory = small_cap != SIZE_MAX ? metal_small_ram_host_avail() : metal_host_available(); + if (memory) { + room = *memory > host_reserve ? size_t(*memory - host_reserve) : 0; + } else if (!metal_host_warning_) { std::fprintf(stderr, "strata-poly: host memory is unavailable; balanced Metal uses the Metal budget only\n"); metal_host_warning_ = true; } - return SIZE_MAX; + if (small_cap != SIZE_MAX) { + const size_t used = metal_current_allocated_bytes(); + const size_t cap_room = small_cap > used ? small_cap - used : 0; + if (cap_room < room) { + if (!metal_small_cap_logged_) { + std::fprintf(stderr, + "strata-poly: <= 24 GiB balanced Metal budget: capping total Metal working set at " + "%zu MiB (48%% of %zu MiB RAM; %zu MiB used, %zu MiB headroom, %zu MiB host reserve)\n", + small_cap >> 20, size_t(metal_host_total_bytes() >> 20), used >> 20, + cap_room >> 20, host_reserve >> 20); + metal_small_cap_logged_ = true; + } + room = cap_room; + } + } + return room; } void Engine::metal_sync_memory() { @@ -1847,16 +1948,34 @@ bool Engine::metal_mind_memory() { size_t free_b = 0, total_b = 0; ck(cudaMemGetInfo(&free_b, &total_b), "balanced Metal budget"); const size_t reserve = size_t(std::max(reserve_mib_, 256)) << 20; + const size_t host_reserve = metal_host_reserve(); + const size_t small_cap = metal_small_ram_cap(); const size_t held = metal_cache_bytes_; const size_t available = free_b > SIZE_MAX - held ? SIZE_MAX : free_b + held; size_t target = available > reserve ? available - reserve : 0; - const auto host = metal_host_available(); + const auto host = small_cap != SIZE_MAX ? metal_small_ram_host_avail() : metal_host_available(); if (host) { const size_t host_total = *host > SIZE_MAX - held ? SIZE_MAX : size_t(*host) + held; - target = std::min(target, host_total > kMetalHostReserve ? host_total - kMetalHostReserve : 0); + target = std::min(target, host_total > host_reserve ? host_total - host_reserve : 0); } else { (void) metal_host_headroom(); // issue the one-time fallback diagnostic } + if (small_cap != SIZE_MAX) { + const size_t used = metal_current_allocated_bytes(); + const size_t used_non_cache = used > held ? used - held : 0; + const size_t cap_target = small_cap > used_non_cache ? small_cap - used_non_cache : 0; + if (cap_target < target) { + if (!metal_small_cap_logged_) { + std::fprintf(stderr, + "strata-poly: <= 24 GiB balanced Metal budget: capping total Metal working set at " + "%zu MiB (48%% of %zu MiB RAM; %zu MiB non-cache, %zu MiB max cache, %zu MiB host reserve)\n", + small_cap >> 20, size_t(metal_host_total_bytes() >> 20), used_non_cache >> 20, + cap_target >> 20, host_reserve >> 20); + metal_small_cap_logged_ = true; + } + target = cap_target; + } + } if (target < held) { metal_growth_samples_ = 0; metal_resize_cache(target); @@ -1864,7 +1983,7 @@ bool Engine::metal_mind_memory() { } // A refill leaves its own cushion. Require a useful net increase before rereading the whole cache. if (all_cached() || target - held < kMetalGrowthMargin + kMetalRefillCushion || - (host && *host < kMetalHostReserve + kMetalGrowthMargin)) { + (host && *host < host_reserve + kMetalGrowthMargin)) { metal_growth_samples_ = 0; return false; } @@ -3004,8 +3123,10 @@ void Engine::fill_expert_cache() { if (mmq_ && !stage_) metal_stage_need += stage_bytes_ + 256 + kTail + 2 * chunk_bytes_; if (!swap_ && opt_.expert_swaps != 0) // -1 is decided after the cache is filled: as many as it can be metal_stage_need += (size_t) (opt_.expert_swaps < 0 ? default_swaps() : opt_.expert_swaps) * slot_max_; + const size_t init_cushion = + metal_small_ram_cap() != SIZE_MAX ? kMetalSmallInitCushion : (size_t(512) << 20); if (metal_cache_limit_ == SIZE_MAX && !recorded_) - metal_stage_need += size_t(scratch_at_) * sizeof(float) + state_n_ * sizeof(float) + (size_t(512) << 20); + metal_stage_need += size_t(scratch_at_) * sizeof(float) + state_n_ * sizeof(float) + init_cushion; else if (arena > (size_t(512) << 20)) metal_stage_need += kMetalRefillCushion; arena = arena > metal_stage_need ? arena - metal_stage_need : 0; diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index 546ea67f42..afa605b38b 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -1072,7 +1072,18 @@ class Engine { void settle_swaps(); virtual void clear_arch_graphs() {} #if defined(STRATA_GPU_METAL) + static uint64_t metal_system_ram_bytes(); + static std::optional metal_small_ram_avail_from_vm( + std::optional file_backed_avail, + uint64_t total_ram, + uint64_t wired_bytes, + uint64_t reclaimable_bytes); virtual std::optional metal_host_available() const; + virtual std::optional metal_small_ram_host_avail() const; + virtual uint64_t metal_host_total_bytes() const; + virtual size_t metal_current_allocated_bytes() const; + size_t metal_host_reserve() const; + size_t metal_small_ram_cap() const; size_t metal_host_headroom(); void metal_invalidate_graphs(); void metal_sync_memory(); @@ -1084,6 +1095,7 @@ class Engine { size_t metal_warm_bytes_ = 0; unsigned metal_growth_samples_ = 0; bool metal_host_warning_ = false; + bool metal_small_cap_logged_ = false; #endif Options opt_; diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 71439bf662..a55d4bea07 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -22260,6 +22260,39 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_METAL_HOST_RESERVE_MIB", + "backends": [ + "metal" + ], + "reads": [ + { + "file": "engine/src/poly/engine.cpp", + "line": 1849, + "backend": "metal", + "fn": "getenv" + } + ], + "parse": "int", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "opt-in", + "owner": "poly/metal", + "note": "Override balanced Metal host memory reserve in MiB (default: 4096 MiB on >24 GiB or unknown RAM, 1536 MiB on <=16 GiB, clamp(RAM/8, 1536 MiB, 4096 MiB) on (16, 24] GiB; engine/src/poly/engine.cpp)", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_METAL_ICB", "backends": [