diff --git a/docs/libfreetpu/README.md b/docs/libfreetpu/README.md index f46307de..16d366e0 100644 --- a/docs/libfreetpu/README.md +++ b/docs/libfreetpu/README.md @@ -1,8 +1,8 @@ -# `libopenbuenos` — Zero-Google-`.so` Bare-Metal Tensor G5 TPU Runtime +# `libfreetpu` — Zero-Google-`.so` Bare-Metal Tensor G5 TPU Runtime -Reusable C/C++ runtime library (`libopenbuenos.a`) driving Pixel 10 Pro Fold (`rango`, Tensor G5 / `buenos.ko`) directly over `/dev/edgetpu-soc` (Litebuf VII) and `/dev/dma_heap/system` (`EDGETPU_MAP_DMABUF`), built specifically to power the `llama.cpp` (`ggml-edgetpu`) backend and standalone native TPU runners. +Reusable C/C++ runtime library (`libfreetpu.a`) driving Pixel 10 (`rango`, Tensor G5 / `buenos.ko`) directly over `/dev/edgetpu-soc` (Litebuf VII) and `/dev/dma_heap/system` (`EDGETPU_MAP_DMABUF`), built specifically to power the `llama.cpp` (`ggml-edgetpu`) backend and standalone native TPU runners. -- **Public C11/C++17 ABI header**: [`libopenbuenos/include/openbuenos.h`](../../libopenbuenos/include/openbuenos.h) +- **Public C11/C++17 ABI header**: [`libfreetpu/include/freetpu.h`](../../libfreetpu/include/freetpu.h) - **Wire & kernel ABI inputs** (read-only): - [`docs/baremetal-vii/litebuf_vii_wire.h`](../baremetal-vii/litebuf_vii_wire.h) - [`docs/kernel-abi/edgetpu_buenos_uapi.h`](../kernel-abi/edgetpu_buenos_uapi.h) @@ -28,6 +28,7 @@ Reusable C/C++ runtime library (`libopenbuenos.a`) driving Pixel 10 Pro Fold (`r - **DVFS Power Profiles (`0..5`, default `5`) & Firmware WakeLock (`ob_context_set_perf_mode`)**: Corrected `+0x1c..+0x20` Litebuf wire mapping (`fw_priority`, `tpu_core_power_state`, `memory_power_state`, `qos_class`, `cluster_id`) + Litebuf `AcquireWakeLock` (`union_type=4`, `bitset=0x04`) / `ReleaseWakeLock` (`union_type=5`). Unlocks full **`1,286.4 MHz`** OPP (`27.59 GB/s` sustained weight BW on `1x2048x2048` at `152 us hw`, **`983.6 INT8 GOPS` @ `177.2 mW` = `5.55 TOPS/W`** on `64x1536x1536`). See [`docs/baremetal-vii/dvfs_power_states.md`](../baremetal-vii/dvfs_power_states.md). - **Built-in Clean-Room C++17 VLIW Emitter (`ob_gemm_register_builtin_emitter`)**: Synthesizes multi-tile (`81/81`), `M=1` hardware-looped `lt_1x*` (`6/6`, up to `2048x2048`), `M=64` batched prefill `lt_64x*` (`5/5`, up to `64x1536x1536`), and Mode-A zero-overhead (`+0 B`) fused `GEMM + SiLU/GELU` kernels directly in C++17 (**92/92 bit-exact** parity). - **Native `Q8_0` & `Q4_0` + Shared-`A` Batched Async Dispatch (`ob_gemm_matmul_f32_quant_batch`)**: Dispatches sibling `Q/K/V` and `gate/up` projections with a single activation quantization pass, `O(1)` strided-hash weight DMA-BUF caching (FD-capped at `<= 4096` weight tiles + `<= 256` pooled slabs), outlier channel peeling + RMS `D`-downshift + `{1.25x, 1.5x, 2.0x, 4.0x, 4.0x}` saturation retry. + - **Auto-Sized `ext[2]` Weight Cache & Telemetry (`#40`)**: Dynamically auto-sizes the `ext[2]` DMA-BUF weight cache from system available memory (`/proc/meminfo` `MemAvailable` on Linux/Android; `vm_statistics64` on macOS): `MemAvailable / 3` below `2 GiB` and `min(1536 MiB, MemAvailable / 2)` at `>= 2 GiB` (e.g., `1344 MiB` at `2.6 GiB` and `1536 MiB` on `4..16+ GiB` hosts — eliminating eviction thrashing on `916 MiB` working sets). Supports explicit overrides (`>= 1.5 GiB`, up to `8192 MiB`) via canonical `FREETPU_WEIGHT_CACHE_MB` / `FREETPU_CACHE_CAP` / `FREETPU_WEIGHT_CACHE_ENTRIES` (with legacy `OPENBUENOS_*` fallback) and `freetpu_context_set_weight_cache_cap()` / `freetpu_context_get_weight_cache_stats()` (`ob_context_*`), clamped whenever a system memory sample is available to preserve safe OOM headroom (`512 MiB`, or half of `MemAvailable` when `<= 1024 MiB`, with a `1 MiB` floor). - `ob_gemm_pack_weights_int8` emits exact `ext[2]` layout (`int32[n_pad]` LE bias + `uint8[k_pad/4, n_pad, 4]` `(w + 128) & 0xff`, padded channels raw `0x00`). --- diff --git a/libfreetpu/Makefile b/libfreetpu/Makefile index 358118a7..f163b621 100644 --- a/libfreetpu/Makefile +++ b/libfreetpu/Makefile @@ -54,6 +54,7 @@ ANDROID_OBJS := $(patsubst $(THIS_DIR)/src/%.cpp,$(ANDROID_DIR)/obj/%.o,$(SRCS)) HOST_LIB := $(HOST_DIR)/libfreetpu.a HOST_TEST := $(HOST_DIR)/openbuenos_host_test +ADVERSARIAL_TEST := $(HOST_DIR)/openbuenos_adversarial_test QUANT_TEST := $(HOST_DIR)/ob_quant_unpack_test POOL_GUARDS_TEST := $(HOST_DIR)/openbuenos_pool_guards_test ANDROID_LIB := $(ANDROID_DIR)/libfreetpu.a @@ -63,7 +64,7 @@ ANDROID_TEST := $(ANDROID_DIR)/openbuenos_selftest all: host android -host: $(HOST_LIB) $(HOST_TEST) $(QUANT_TEST) $(POOL_GUARDS_TEST) +host: $(HOST_LIB) $(HOST_TEST) $(ADVERSARIAL_TEST) $(QUANT_TEST) $(POOL_GUARDS_TEST) android: $(ANDROID_LIB) $(ANDROID_TEST) @@ -83,6 +84,10 @@ $(HOST_TEST): $(THIS_DIR)/tests/openbuenos_host_test.cpp $(HOST_LIB) $(HDRS) @mkdir -p $(dir $@) $(HOST_CXX) $(HOST_CXXFLAGS) $< $(HOST_LIB) -o $@ $(HOST_LDFLAGS) +$(ADVERSARIAL_TEST): $(THIS_DIR)/tests/openbuenos_adversarial_test.cpp $(HOST_LIB) $(HDRS) + @mkdir -p $(dir $@) + $(HOST_CXX) $(HOST_CXXFLAGS) $< $(HOST_LIB) -o $@ $(HOST_LDFLAGS) + $(QUANT_TEST): $(THIS_DIR)/tests/ob_quant_unpack_test.cpp $(HOST_LIB) $(HDRS) @mkdir -p $(dir $@) $(HOST_CXX) $(HOST_CXXFLAGS) $< $(HOST_LIB) -o $@ $(HOST_LDFLAGS) @@ -107,8 +112,9 @@ $(ANDROID_TEST): $(THIS_DIR)/tests/openbuenos_selftest.cpp $(ANDROID_LIB) $(HDRS @mkdir -p $(dir $@) $(ANDROID_CXX) $(ANDROID_CXXFLAGS) $< $(ANDROID_LIB) -o $@ $(ANDROID_LDFLAGS) -test: $(HOST_TEST) $(QUANT_TEST) $(POOL_GUARDS_TEST) +test: $(HOST_TEST) $(ADVERSARIAL_TEST) $(QUANT_TEST) $(POOL_GUARDS_TEST) $(HOST_TEST) + $(ADVERSARIAL_TEST) $(QUANT_TEST) $(POOL_GUARDS_TEST) diff --git a/libfreetpu/include/freetpu.h b/libfreetpu/include/freetpu.h index f44caf7e..b1e3e9d4 100644 --- a/libfreetpu/include/freetpu.h +++ b/libfreetpu/include/freetpu.h @@ -310,14 +310,21 @@ ob_status_t ob_context_reset_profile(ob_context_t* ctx); /* * ext[2] weight-cache byte cap. 0 restores MemAvailable auto-size. - * Environment (wins over this setter): - * 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). + * Auto-size defaults to MemAvailable/3 below 2 GiB and min(1536 MiB, MemAvailable/2) + * at >= 2 GiB (e.g. 1344 MiB at 2.6 GiB, 1536 MiB on 4..16+ GiB systems). + * Environment (wins over this setter; canonical FREETPU_* wins over OPENBUENOS_*): + * FREETPU_WEIGHT_CACHE_MB / OPENBUENOS_WEIGHT_CACHE_MB — MiB cap (16..8192). + * 0 / negative / non-numeric is ignored. + * FREETPU_CACHE_CAP / OPENBUENOS_CACHE_CAP — values <= 1048576 stay the ggml + * graph-entry count; values above that are an explicit weight-cache byte cap + * (supports >= 1.5 GiB). + * FREETPU_WEIGHT_CACHE_ENTRIES / OPENBUENOS_WEIGHT_CACHE_ENTRIES — FD-safe + * entry count cap (64..32768). * Explicit caps are clamped to leave MemAvailable headroom (512 MiB, or half * when MemAvailable is at most 1024 MiB), subject to a 1 MiB minimum cache floor. */ #define OB_HAS_WEIGHT_CACHE_STATS 1 +#define FREETPU_HAS_WEIGHT_CACHE_STATS OB_HAS_WEIGHT_CACHE_STATS 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. */ @@ -334,9 +341,14 @@ typedef struct ob_weight_cache_stats { uint32_t reserved; } ob_weight_cache_stats_t; +typedef ob_weight_cache_stats_t freetpu_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); +#define freetpu_context_set_weight_cache_cap ob_context_set_weight_cache_cap +#define freetpu_context_get_weight_cache_stats ob_context_get_weight_cache_stats + /* * Opt-in / defaultable FreeTile BUENOS_A0 VLIW/DGC0 emitter switch. * diff --git a/libfreetpu/src/ob_gemm.cpp b/libfreetpu/src/ob_gemm.cpp index 6b6236dc..124980fe 100644 --- a/libfreetpu/src/ob_gemm.cpp +++ b/libfreetpu/src/ob_gemm.cpp @@ -472,10 +472,11 @@ size_t clamp_explicit_request(uint64_t bytes) { return static_cast(bytes); } -// OPENBUENOS_WEIGHT_CACHE_MB. 0, negative and non-numeric values are not an override. -bool parse_weight_cache_mb_env(size_t* out_bytes) { +// FREETPU_WEIGHT_CACHE_MB / legacy OPENBUENOS_WEIGHT_CACHE_MB. +// 0, negative and non-numeric values are not an override. +bool parse_weight_cache_mb_env_var(const char* name, size_t* out_bytes) { uint64_t mb = 0ull; - if (!out_bytes || !parse_env_u64("OPENBUENOS_WEIGHT_CACHE_MB", &mb) || mb == 0ull) { + if (!out_bytes || !parse_env_u64(name, &mb) || mb == 0ull) { return false; } uint64_t clamped = mb; @@ -485,11 +486,11 @@ bool parse_weight_cache_mb_env(size_t* out_bytes) { 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) { +// FREETPU_CACHE_CAP / legacy OPENBUENOS_CACHE_CAP. Values <= 1048576 remain the +// graph-entry count; larger values are an explicit weight-cache byte cap (>= 1.5 GiB). +bool parse_cache_cap_bytes_env_var(const char* name, size_t* out_bytes) { uint64_t parsed = 0ull; - if (!out_bytes || !parse_env_u64("OPENBUENOS_CACHE_CAP", &parsed) || + if (!out_bytes || !parse_env_u64(name, &parsed) || parsed <= kGraphCacheCapMax) { return false; } @@ -497,6 +498,31 @@ bool parse_cache_cap_bytes_env(size_t* out_bytes) { return true; } +bool parse_weight_cache_cap_env(size_t* out_bytes) { + if (!out_bytes) return false; + // Canonical FREETPU_* overrides win over legacy OPENBUENOS_* fallbacks. + // Resolve FREETPU_CACHE_CAP before interpreting units so a valid canonical + // graph-entry count (<= 1048576) never falls through to a legacy byte cap. + if (parse_weight_cache_mb_env_var("FREETPU_WEIGHT_CACHE_MB", out_bytes)) { + return true; + } + uint64_t canonical_cap = 0ull; + const bool has_canonical_cap = + parse_env_u64("FREETPU_CACHE_CAP", &canonical_cap) && canonical_cap > 0ull; + if (has_canonical_cap && canonical_cap > kGraphCacheCapMax) { + *out_bytes = clamp_explicit_request(canonical_cap); + return true; + } + if (parse_weight_cache_mb_env_var("OPENBUENOS_WEIGHT_CACHE_MB", out_bytes)) { + return true; + } + if (!has_canonical_cap && + parse_cache_cap_bytes_env_var("OPENBUENOS_CACHE_CAP", out_bytes)) { + return true; + } + return false; +} + // 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 @@ -609,9 +635,7 @@ size_t compute_weight_cache_budget_bytes_impl(ob_context* ctx, if (!ctx) return 0u; size_t requested = 0u; bool explicit_cap = false; - if (parse_weight_cache_mb_env(&requested)) { - explicit_cap = true; - } else if (parse_cache_cap_bytes_env(&requested)) { + if (parse_weight_cache_cap_env(&requested)) { explicit_cap = true; } else if (ctx->weight_cache_cap_bytes > 0u) { requested = clamp_explicit_request(ctx->weight_cache_cap_bytes); @@ -672,9 +696,15 @@ void ensure_weight_cache_budget(ob_context* ctx, } if (ctx->weight_cache_max_entries == 0u) { uint64_t lim = 0ull; - if (parse_env_u64("OPENBUENOS_WEIGHT_CACHE_ENTRIES", &lim)) { + if (parse_env_u64("FREETPU_WEIGHT_CACHE_ENTRIES", &lim) || + parse_env_u64("OPENBUENOS_WEIGHT_CACHE_ENTRIES", &lim)) { if (lim < 64ull) lim = 64ull; - if (lim > 32768ull) lim = 32768ull; + uint64_t max_lim = 32768ull; + if (ctx->weight_cache_default_max_entries < ob::kDefaultWeightCacheMaxEntries) { + // Low RLIMIT_NOFILE safeguard set during context creation: never exceed device FD ceiling. + max_lim = static_cast(ctx->weight_cache_default_max_entries); + } + if (lim > max_lim) lim = max_lim; ctx->weight_cache_max_entries = static_cast(lim); } else { ctx->weight_cache_max_entries = ctx->weight_cache_default_max_entries; diff --git a/libfreetpu/src/ob_internal.h b/libfreetpu/src/ob_internal.h index 7575d874..c508b955 100644 --- a/libfreetpu/src/ob_internal.h +++ b/libfreetpu/src/ob_internal.h @@ -845,7 +845,7 @@ struct ob_context { size_t weight_cache_peak_entries = 0; 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 weight_cache_max_entries = 0; // FD-safe cap (default 16384, env FREETPU_/OPENBUENOS_WEIGHT_CACHE_ENTRIES) size_t outlier_cache_bytes = 0; // Separate tracked total of cached FP32 outlier columns std::vector immutable_weight_regions; uint64_t next_immutable_region_gen = 1u; diff --git a/libfreetpu/tests/ob_quant_unpack_test.cpp b/libfreetpu/tests/ob_quant_unpack_test.cpp index bf0a7f32..0641517b 100644 --- a/libfreetpu/tests/ob_quant_unpack_test.cpp +++ b/libfreetpu/tests/ob_quant_unpack_test.cpp @@ -1027,6 +1027,16 @@ void test_swiglu_modern_quants() { } // namespace int main() { + for (const char* env_name : { + "FREETPU_WEIGHT_CACHE_MB", + "FREETPU_CACHE_CAP", + "FREETPU_WEIGHT_CACHE_ENTRIES", + "OPENBUENOS_WEIGHT_CACHE_MB", + "OPENBUENOS_CACHE_CAP", + "OPENBUENOS_WEIGHT_CACHE_ENTRIES", + }) { + ::unsetenv(env_name); + } test_abi_and_validation(); test_bit_exact_dequant_and_column_extract(); test_q4_k_algebraic_dmin_centering(); diff --git a/libfreetpu/tests/openbuenos_adversarial_test.cpp b/libfreetpu/tests/openbuenos_adversarial_test.cpp index 5972fb23..524f84cb 100644 --- a/libfreetpu/tests/openbuenos_adversarial_test.cpp +++ b/libfreetpu/tests/openbuenos_adversarial_test.cpp @@ -68,6 +68,9 @@ CtxGuard make_ctx(FixedProbe* mem) { } void unset_cache_env() { + ::unsetenv("FREETPU_WEIGHT_CACHE_MB"); + ::unsetenv("FREETPU_CACHE_CAP"); + ::unsetenv("FREETPU_WEIGHT_CACHE_ENTRIES"); ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); ::unsetenv("OPENBUENOS_CACHE_CAP"); ::unsetenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); @@ -133,15 +136,72 @@ void test_env_extremes() { 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. + // Canonical FREETPU_* overrides: hostile values, >= 1.5 GiB support, entry cap, and precedence. + for (const char* v : bad_mb) { + ::setenv("FREETPU_WEIGHT_CACHE_MB", v, 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + } + ::unsetenv("FREETPU_WEIGHT_CACHE_MB"); + for (const char* v : small_cap) { + ::setenv("FREETPU_CACHE_CAP", v, 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + } + ::setenv("FREETPU_CACHE_CAP", "1610612736", 1); // 1.5 GiB + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + ::setenv("FREETPU_CACHE_CAP", "2147483648", 1); // 2 GiB + if (sizeof(size_t) >= 8u) { + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 2ull * kGiB); + } + // Canonical FREETPU_CACHE_CAP beats legacy OPENBUENOS_WEIGHT_CACHE_MB and OPENBUENOS_CACHE_CAP. + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "512", 1); + ::setenv("OPENBUENOS_CACHE_CAP", "1073741824", 1); + if (sizeof(size_t) >= 8u) { + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 2ull * kGiB); + } + // Canonical FREETPU_WEIGHT_CACHE_MB beats FREETPU_CACHE_CAP and all legacy/API caps. + ::setenv("FREETPU_WEIGHT_CACHE_MB", "1700", 1); + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1700ull * kMiB); + // Cross-unit canonical alias precedence: valid canonical graph-entry count + // (<= 1048576) must NOT fall through to a legacy OPENBUENOS_CACHE_CAP byte cap. + unset_cache_env(); + ::setenv("FREETPU_CACHE_CAP", "4096", 1); + ::setenv("OPENBUENOS_CACHE_CAP", "939524096", 1); // 896 MiB legacy byte cap + CHECK(ob::compute_weight_cache_budget_bytes(g.ctx) == 1536ull * kMiB); + unset_cache_env(); + + // Canonical FREETPU_WEIGHT_CACHE_ENTRIES beats OPENBUENOS_WEIGHT_CACHE_ENTRIES, + // and respects low-FD ceiling when device RLIMIT_NOFILE narrowed default_max_entries. + ::setenv("OPENBUENOS_WEIGHT_CACHE_ENTRIES", "128", 1); + ::setenv("FREETPU_WEIGHT_CACHE_ENTRIES", "256", 1); + g.ctx->weight_cache_max_entries = 0u; + (void)ob::weight_cache_sim_access(g.ctx, 9998u, 1ull * kMiB, nullptr); + CHECK(g.ctx->weight_cache_max_entries == 256u); + const size_t saved_default_entries = g.ctx->weight_cache_default_max_entries; + g.ctx->weight_cache_default_max_entries = 256u; + ::setenv("FREETPU_WEIGHT_CACHE_ENTRIES", "4096", 1); + g.ctx->weight_cache_max_entries = 0u; + (void)ob::weight_cache_sim_access(g.ctx, 9997u, 1ull * kMiB, nullptr); + CHECK(g.ctx->weight_cache_max_entries == 256u); + g.ctx->weight_cache_default_max_entries = saved_default_entries; + g.ctx->weight_cache_max_entries = 0u; + unset_cache_env(); + + // Precedence: legacy MB env beats legacy 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(freetpu_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); + // Canonical API alias telemetry check. +#if !defined(FREETPU_HAS_WEIGHT_CACHE_STATS) || !FREETPU_HAS_WEIGHT_CACHE_STATS +#error "FREETPU_HAS_WEIGHT_CACHE_STATS must be defined and non-zero" +#endif + freetpu_weight_cache_stats_t ft_stats{}; + CHECK(freetpu_context_get_weight_cache_stats(g.ctx, &ft_stats) == OB_OK); + CHECK(ft_stats.budget_bytes == 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); diff --git a/libfreetpu/tests/openbuenos_host_test.cpp b/libfreetpu/tests/openbuenos_host_test.cpp index fee8e04b..b46b7ea2 100644 --- a/libfreetpu/tests/openbuenos_host_test.cpp +++ b/libfreetpu/tests/openbuenos_host_test.cpp @@ -6572,8 +6572,12 @@ void test_weight_cache_cap_autosize_and_telemetry() { EnvGuard(const char* n) : name(n) { ::unsetenv(name); } ~EnvGuard() { ::unsetenv(name); } }; + EnvGuard guard_ft_mb("FREETPU_WEIGHT_CACHE_MB"); + EnvGuard guard_ft_cap("FREETPU_CACHE_CAP"); + EnvGuard guard_ft_entries("FREETPU_WEIGHT_CACHE_ENTRIES"); EnvGuard guard_mb("OPENBUENOS_WEIGHT_CACHE_MB"); EnvGuard guard_cap("OPENBUENOS_CACHE_CAP"); + EnvGuard guard_entries("OPENBUENOS_WEIGHT_CACHE_ENTRIES"); struct FixedProbe { size_t bytes = 0; @@ -6651,6 +6655,27 @@ void test_weight_cache_cap_autosize_and_telemetry() { #endif ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + // Canonical FREETPU_CACHE_CAP / FREETPU_WEIGHT_CACHE_MB (>= 1.5 GiB + headroom clamp + precedence). + ::setenv("FREETPU_CACHE_CAP", "1610612736", 1); // 1.5 GiB + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("FREETPU_CACHE_CAP", "2147483648", 1); // 2 GiB + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 2ull * kGiB); + ::setenv("FREETPU_CACHE_CAP", "2048", 1); // graph-entry count passthrough + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1536ull * kMiB); + ::setenv("OPENBUENOS_WEIGHT_CACHE_MB", "512", 1); + ::setenv("FREETPU_CACHE_CAP", "2147483648", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 2ull * kGiB); + ::setenv("FREETPU_WEIGHT_CACHE_MB", "1792", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == 1792ull * kMiB); +#if UINTPTR_MAX == UINT64_MAX + mem.bytes = static_cast(4ull * kGiB); + ::setenv("FREETPU_WEIGHT_CACHE_MB", "4096", 1); + CHECK(ob::compute_weight_cache_budget_bytes(ctx) == (4ull * kGiB - 512ull * kMiB)); +#endif + ::unsetenv("FREETPU_WEIGHT_CACHE_MB"); + ::unsetenv("FREETPU_CACHE_CAP"); + ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); + // Explicit byte cap is clamped to MemAvailable - 512 MiB. #if UINTPTR_MAX == UINT64_MAX mem.bytes = static_cast(4ull * kGiB); @@ -6739,6 +6764,28 @@ void test_weight_cache_cap_autosize_and_telemetry() { CHECK(cold_evict == 0u); CHECK(steady_evict == 0u); + // Pixel 10 pocket (2688 MiB): auto-size lands at 1344 MiB (0 evictions at 916 MiB); + // explicit FREETPU_CACHE_CAP=1536 MiB is distinct from 1344 MiB auto and also 0 evictions. + const size_t kPixelPocketMem = static_cast(896ull * 3ull * kMiB); + cold_evict = 1u; + steady_evict = 1u; + budget = 0u; + run_working_set(kPixelPocketMem, nullptr, &cold_evict, &steady_evict, &budget); + CHECK(budget == 1344ull * kMiB); + CHECK(cold_evict == 0u); + CHECK(steady_evict == 0u); + + const std::string cap_1536 = std::to_string(1536ull * kMiB); + ::setenv("FREETPU_CACHE_CAP", cap_1536.c_str(), 1); + cold_evict = 1u; + steady_evict = 1u; + budget = 0u; + run_working_set(kPixelPocketMem, nullptr, &cold_evict, &steady_evict, &budget); + CHECK(budget == 1536ull * kMiB); + CHECK(cold_evict == 0u); + CHECK(steady_evict == 0u); + ::unsetenv("FREETPU_CACHE_CAP"); + const std::string cap_896 = std::to_string(896ull * kMiB); cold_evict = 0u; steady_evict = 0u; @@ -6747,6 +6794,8 @@ void test_weight_cache_cap_autosize_and_telemetry() { CHECK(budget == 896ull * kMiB); CHECK(cold_evict > 0u); CHECK(steady_evict > 0u); + ::unsetenv("FREETPU_CACHE_CAP"); + ::unsetenv("FREETPU_WEIGHT_CACHE_MB"); ::unsetenv("OPENBUENOS_CACHE_CAP"); ::unsetenv("OPENBUENOS_WEIGHT_CACHE_MB"); @@ -7152,6 +7201,9 @@ int main() { "OPENBUENOS_SWIGLU_EXACT_CLIP_CHECK", "OPENBUENOS_SWIGLU_MAX_CREST", "OPENBUENOS_STRICT_WEIGHT_HASH", + "FREETPU_WEIGHT_CACHE_MB", + "FREETPU_WEIGHT_CACHE_ENTRIES", + "FREETPU_CACHE_CAP", "OPENBUENOS_WEIGHT_CACHE_MB", "OPENBUENOS_WEIGHT_CACHE_ENTRIES", "OPENBUENOS_CACHE_CAP", diff --git a/llama-cpp-edgetpu/ggml-edgetpu.cpp b/llama-cpp-edgetpu/ggml-edgetpu.cpp index 73834673..23d7c803 100644 --- a/llama-cpp-edgetpu/ggml-edgetpu.cpp +++ b/llama-cpp-edgetpu/ggml-edgetpu.cpp @@ -180,9 +180,11 @@ 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. + auto parse_cache_cap_u64 = [](const char * name, unsigned long long * out_val) -> bool { + const char * v = std::getenv(name); + if (!v || !out_val) { + return false; + } const char * first = v; while (*first && std::isspace(static_cast(*first))) { ++first; @@ -190,18 +192,32 @@ static edgetpu_env_config load_env_config() { if (*first == '+') { ++first; } - if (std::isdigit(static_cast(*first))) { - errno = 0; - char * end = nullptr; - const unsigned long long parsed = std::strtoull(first, &end, 10); - if (errno == 0 && end != first) { - while (*end && std::isspace(static_cast(*end))) { - ++end; - } - if (*end == '\0' && parsed > 0ULL && parsed <= 1048576ULL) { - cfg.cache_cap = static_cast(parsed); - } - } + if (!std::isdigit(static_cast(*first))) { + return false; + } + errno = 0; + char * end = nullptr; + const unsigned long long parsed = std::strtoull(first, &end, 10); + if (errno != 0 || end == first) { + return false; + } + while (*end && std::isspace(static_cast(*end))) { + ++end; + } + if (*end == '\0' && parsed > 0ULL) { + *out_val = parsed; + return true; + } + return false; + }; + // Resolve canonical FREETPU_CACHE_CAP before interpreting units so a valid canonical + // weight-cache byte cap (> 1048576) never falls through to a legacy graph-entry count. + unsigned long long cache_cap_val = 0ULL; + if (parse_cache_cap_u64("FREETPU_CACHE_CAP", &cache_cap_val) || + parse_cache_cap_u64("OPENBUENOS_CACHE_CAP", &cache_cap_val)) { + // 1..1048576 is the graph-entry count; larger values belong to libfreetpu's weight-cache cap. + if (cache_cap_val <= 1048576ULL) { + cfg.cache_cap = static_cast(cache_cap_val); } } if (const char * v = std::getenv("OPENBUENOS_POOL_MB")) { diff --git a/proof/libfreetpu-weight-cache-cap/PROOF.md b/proof/libfreetpu-weight-cache-cap/PROOF.md new file mode 100644 index 00000000..d74507b6 --- /dev/null +++ b/proof/libfreetpu-weight-cache-cap/PROOF.md @@ -0,0 +1,52 @@ +# Proof: `libfreetpu` Canonical Weight-Cache Cap & Auto-Sizing (Refs #40) + +## Scope & Issue Context + +This PR completes the canonical `libfreetpu` weight-cache cap surface for +[freesilicon/freetpu#40](https://github.com/freesilicon/freetpu/issues/40) +following the `libopenbuenos` -> `libfreetpu` rename in `#54` / `#55` +(`Refs #40` — does **not** close `#40`; live Pixel 10 solo + DSpark silicon +re-benchmark proof remains open on `#40`). + +Core `MemAvailable`-guarded auto-sizing (`MemAvailable/3` below `2 GiB`, +`min(1536 MiB, MemAvailable/2)` at `>= 2 GiB`, `512 MiB` explicit OOM headroom +guard, `1 MiB` floor) and telemetry (`ob_weight_cache_stats_t`, +`ob_context_set_weight_cache_cap`, `ob_context_get_weight_cache_stats`) landed +in `#45`. This PR wires the canonical `FREETPU_*` environment variables and +C11/C++17 aliases across `libfreetpu` and `llama-cpp-edgetpu`, extends host and +adversarial coverage, and enables `openbuenos_adversarial_test` in the `Make` +test target as well as CMake/CTest. + +## What Shipped + +| Surface | Location | Summary | +|---|---|---| +| Canonical env vars & precedence | `libfreetpu/src/ob_gemm.cpp`, `llama-cpp-edgetpu/ggml-edgetpu.cpp` | Adds `FREETPU_WEIGHT_CACHE_MB`, `FREETPU_CACHE_CAP` (`> 1048576` byte cap >= 1.5 GiB; `<= 1048576` graph-entry count), and `FREETPU_WEIGHT_CACHE_ENTRIES` with canonical-first precedence and backwards-compatible `OPENBUENOS_*` fallback. | +| Canonical C11/C++17 aliases (ABI-neutral) | `libfreetpu/include/freetpu.h` | Exposes `FREETPU_HAS_WEIGHT_CACHE_STATS`, `freetpu_weight_cache_stats_t`, `freetpu_context_set_weight_cache_cap`, and `freetpu_context_get_weight_cache_stats` without altering `ob_config_t` (48 B LP64) or `ob_profile_stats_t` (216 B LP64). | +| Build, tests & docs | `libfreetpu/Makefile`, `libfreetpu/tests/openbuenos_host_test.cpp`, `libfreetpu/tests/openbuenos_adversarial_test.cpp`, `docs/libfreetpu/README.md` | Wires `openbuenos_adversarial_test` into `make -C libfreetpu test`, verifies `FREETPU_*` hostile inputs, precedence, `w_peak = 916 MiB` zero steady-state evictions, and OOM headroom clamping. | + +## Host-Verified Proof (Observed) + +| Check | Result | +|---|---| +| `make -C libfreetpu verify-header-host host test` (`-Wall -Wextra -Wpedantic -Werror`) | PASS (`28/28` host suites + `openbuenos_adversarial_test` + `ob_quant_unpack_test` + `openbuenos_pool_guards_test`) | +| `clang -x c -std=c11 -fsyntax-only -Wall -Wextra -Werror -Ilibfreetpu/include llama-cpp-edgetpu/openbuenos_shim.c` | PASS | +| ASan + UBSan (`-fsanitize=address,undefined -fno-sanitize-recover=all`) on `openbuenos_adversarial_test` | PASS (`0` errors) | +| TSan (`-fsanitize=thread -fno-sanitize-recover=all`) on `openbuenos_adversarial_test` | PASS (`0` warnings) | +| `w_peak = 916 MiB` steady-state eviction check (`16 GiB` auto `1536 MiB`, Pixel 10 `2688 MiB -> 1344 MiB`, explicit `FREETPU_CACHE_CAP=1610612736`) | `0` cold evictions, `0` steady-state evictions (`896 MiB` control triggers `> 0` evictions) | +| OOM headroom clamp (`4 GiB` available + `FREETPU_WEIGHT_CACHE_MB=4096` / `OPENBUENOS_CACHE_CAP=4294967296`) | Clamped to `3584 MiB` (`MemAvailable - 512 MiB`) | + +Reproduce (host, no device required): + +```bash +make -C libfreetpu verify-header-host host test +clang -x c -std=c11 -fsyntax-only -Wall -Wextra -Werror -Ilibfreetpu/include llama-cpp-edgetpu/openbuenos_shim.c +``` + +## Remaining Human-Gated Hardware Proof (Open on #40) + +Live Pixel 10 (`Tensor G5`) silicon re-benchmark comparing the `896 MiB` cap +baseline (`0.60 t/s` solo / `1.05 t/s` with DSpark speculative decode) against +the zero-thrash `libfreetpu` auto-sized / `FREETPU_WEIGHT_CACHE_MB=1536` cap on +`PocketCoder-13B-A3B-Q4_0.gguf` was intentionally **not** run in this host PR +and remains open as a human-gated device proof step on `#40`.