Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
229 changes: 229 additions & 0 deletions engine/metal/poly_tests/memory_growth.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "strata/gpu/metal.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <stdexcept>
Expand All @@ -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<uint64_t> host = uint64_t(64) << 30;
std::optional<uint64_t> small_host;
uint64_t total_ram = uint64_t(64) << 30;
std::optional<size_t> 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<uint8_t> dummy_exp_backing;

explicit MemoryEngine(bool balanced = true, bool whole = false) {
opt_.metal_balanced = balanced;
Expand All @@ -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<uint64_t> eval_small_ram_vm(std::optional<uint64_t> 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<const char*>(header), sizeof(header)); }
try { gg_ = std::make_unique<strata::poly::Shards>(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<g::Stream>(st_)));
ck(g::stream_synchronize(static_cast<g::Stream>(st_)));
Expand Down Expand Up @@ -109,6 +155,11 @@ class MemoryEngine final : public strata::poly::Engine {
}
protected:
std::optional<uint64_t> metal_host_available() const override { return host; }
std::optional<uint64_t> 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;
Expand Down Expand Up @@ -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<std::string> 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");
Expand Down
Loading
Loading