diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70917b3..62c4b08 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,17 @@ jobs: cmake --build build-freetile -j"$(nproc)" ctest --test-dir build-freetile --output-on-failure + - name: Configure & test aot-guard (CMake + -fno-exceptions + Make + ASan/UBSan) + run: | + cmake -S aot-guard -B build-aot-guard -G Ninja -DCMAKE_BUILD_TYPE=Release -DFREETPU_AOT_GUARD_BUILD_TESTS=ON + cmake --build build-aot-guard -j"$(nproc)" + ctest --test-dir build-aot-guard --output-on-failure + make -C aot-guard clean + make -C aot-guard test + make -C aot-guard clean + make -C aot-guard test CFLAGS="-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer" CXXFLAGS="-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer" + make -C aot-guard clean + - name: Configure & test llama-cpp-cloudtpu (Host Mock PJRT) run: | cmake -S llama-cpp-cloudtpu -B build-cloudtpu -G Ninja -DCMAKE_BUILD_TYPE=Release diff --git a/.github/workflows/public-roads-firewall.yml b/.github/workflows/public-roads-firewall.yml new file mode 100644 index 0000000..7d243e8 --- /dev/null +++ b/.github/workflows/public-roads-firewall.yml @@ -0,0 +1,116 @@ +# Clean-room release hygiene and PR diff / aot-guard firewall +name: Public Roads Firewall + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + public-roads-firewall: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Verify aot-guard SPDX headers and PR diff clean-room hygiene + shell: bash + env: + FIREWALL_DENYLIST_REGEX: ${{ secrets.FIREWALL_DENYLIST_REGEX }} + EVENT_NAME: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref }} + BEFORE_SHA: ${{ github.event.before }} + HEAD_SHA: ${{ github.sha }} + run: | + python3 - <<'PY' + import os + import re + import subprocess + import sys + + host_path_re = re.compile("/" + r"(?:Users|home)/[^/\s]+/") + device_tmp_re = re.compile("/" + r"data/local/tmp/") + secret_re = re.compile( + r"(?:" + "BEGIN " + r"[A-Z0-9 ]*PRIVATE KEY|" + + r"\b(?:ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|sk-[A-Za-z0-9]{20,})\b)" + ) + adb_serial_re = re.compile( + r"(?:\badb\s+-s\s+[A-Za-z0-9:._-]{6,}|" + + r"ANDROID_SERIAL\s*=\s*['\"]?[A-Za-z0-9]{6,})" + ) + + raw_denylist = os.environ.get("FIREWALL_DENYLIST_REGEX", "").strip() + denylist_re = re.compile(raw_denylist, re.IGNORECASE) if raw_denylist else None + + failures = [] + source_exts = (".c", ".h", ".hpp", ".cpp") + + if not os.path.isfile("LICENSE"): + failures.append("Missing LICENSE file") + else: + with open("LICENSE", "r", encoding="utf-8") as lf: + lic_text = lf.read() + if len(lic_text) <= 10000 or "Apache License" not in lic_text or "Version 2.0, January 2004" not in lic_text: + failures.append("LICENSE is not complete Apache-2.0 text (>10 KB)") + + def check_line(label, line, check_device_tmp=False): + if host_path_re.search(line): + failures.append(f"Local machine path in {label}") + if check_device_tmp and device_tmp_re.search(line): + failures.append(f"Device tmp path in {label}") + if secret_re.search(line): + failures.append(f"Secret or private key marker in {label}") + if adb_serial_re.search(line): + failures.append(f"Raw ADB serial reference in {label}") + if denylist_re is not None and denylist_re.search(line): + failures.append(f"Denylist content match in {label}") + + for root, dirs, files in os.walk("aot-guard"): + dirs[:] = [d for d in dirs if d not in (".git", "build", "build-cmake")] + for fname in sorted(files): + rel = os.path.join(root, fname) + if denylist_re is not None and denylist_re.search(rel): + failures.append(f"Denylist filename match: {rel}") + try: + with open(rel, "r", encoding="utf-8") as fh: + content = fh.read() + except UnicodeDecodeError: + continue + for lineno, line in enumerate(content.splitlines(), 1): + check_line(f"{rel}:{lineno}", line, check_device_tmp=True) + if rel.endswith(source_exts): + if "SPDX-License-Identifier: Apache-2.0" not in content: + failures.append(f"Missing SPDX Apache-2.0 header in {rel}") + + event_name = os.environ.get("EVENT_NAME", "") + diff_range = None + if event_name == "pull_request" and os.environ.get("BASE_REF"): + diff_range = f"origin/{os.environ['BASE_REF']}...HEAD" + elif event_name == "push": + before = os.environ.get("BEFORE_SHA", "") + if before and set(before) != {"0"}: + diff_range = f"{before}..{os.environ['HEAD_SHA']}" + + if diff_range: + diff_text = subprocess.check_output( + ["git", "diff", "--unified=0", "--no-color", diff_range], + text=True, + errors="replace", + ) + cur_file = "" + for raw_line in diff_text.splitlines(): + if raw_line.startswith("+++ b/"): + cur_file = raw_line[6:] + if denylist_re is not None and denylist_re.search(cur_file): + failures.append(f"Denylist filename match in diff: {cur_file}") + elif raw_line.startswith("+") and not raw_line.startswith("+++"): + check_line(f"diff:{cur_file}", raw_line[1:], check_device_tmp=False) + + if failures: + for item in failures: + print(f"FIREWALL FAIL: {item}", file=sys.stderr) + sys.exit(1) + print("Public roads firewall passed with 0 violations.") + PY diff --git a/README.md b/README.md index 10051e2..e004393 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ | --- | --- | --- | | **LLM Inference** | [`llama-cpp-edgetpu/`](llama-cpp-edgetpu/README.md) | `EDGETPU` GGML `ACCEL` backend (`MUL_MAT` & MoE `MUL_MAT_ID` `Q8_0`/`Q4_0`/`F32`, chained SwiGLU, `ROPE`/`GLU`, QKV `3->1` horizontal fusion, 1D bias `ADD`) | | **Open Runtime** | [`libopenbuenos/`](libopenbuenos/include/openbuenos.h) | C11/C++17 static library: `1,286.4 MHz` DVFS + FW WakeLock, perf-core-pinned SPSC async dequant, clean-room 7-chunk PT `W8A16(FP16)` (`FP32` acc), adaptive spin, 2-tier DMA-BUF pool & LMKD single-copy weight cache, `M=1`/`M=64` GEMM + 11-chunk chained SwiGLU emitter | +| **AOT Guard & SRAM** | [`aot-guard/`](aot-guard/README.md) | Zero-dep C11/C++17 5-input SHA-256 AOT cache key/container validator (`aot_cache_guard`) & `< 4 MiB` on-chip SRAM tail subgraph partitioner (`sram_partitioner`) | | **Kernel Transport** | [`runtime/`](runtime/src/tpu_baremetal_runner.cpp) | Standalone bare-metal runner & UAPI/Litebuf VII headers (`0x0008 -> 0x00fe`, `/dev/edgetpu-soc` `0xED`) | | **ISA Tooling** | [`tools/`](tools/emit_custom_gemm.py) | Pure-Python `DGC0` dissector/patcher, multi-tile `(M, K, N)` VLIW synthesizer, `0x640` minimax spline codec, `0xa40` chained fusion verifier, `INT4` packer | | **Cloud TPU Ops** | [`ops/`](docs/cloud-tpu/ops-container-telemetry.md) | Zero-dep Prometheus [`tpu-exporter`](ops/tpu-exporter/README.md) (`0x1ae0` + VFIO + `tpu-info`) & CNCF CDI `v0.6.0` [`freetpu-cdi`](ops/tpu-cdi/README.md) Docker/K8s passthrough | @@ -62,7 +63,10 @@ cmake -S libopenbuenos -B libopenbuenos/build/cmake-host -DCMAKE_BUILD_TYPE=Rele cmake --build libopenbuenos/build/cmake-host -j ctest --test-dir libopenbuenos/build/cmake-host --output-on-failure -# 2. Run clean-room Python VLIW ISA & 0x640 minimax spline self-tests +# 2. Build & test aot-guard (5-input AOT cache guard & <4 MiB SRAM partitioner) +make -C aot-guard test + +# 3. Run clean-room Python VLIW ISA & 0x640 minimax spline self-tests python3 tools/emit_custom_gemm.py --self-test python3 tools/spline_0x640.py --self-test --no-emit python3 tools/pack_int4.py diff --git a/aot-guard/CMakeLists.txt b/aot-guard/CMakeLists.txt new file mode 100644 index 0000000..1c4fb75 --- /dev/null +++ b/aot-guard/CMakeLists.txt @@ -0,0 +1,59 @@ +cmake_minimum_required(VERSION 3.16) + +project(freetpu_aot_guard + VERSION 0.2.0 + DESCRIPTION "Clean-room C11/C++17 5-input AOT cache key guard and <4 MiB SRAM subgraph partitioner for FreeTPU" + LANGUAGES C CXX +) + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_C_EXTENSIONS OFF) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +option(FREETPU_AOT_GUARD_BUILD_TESTS "Build the freetpu-aot-guard test suite" ON) + +add_library(freetpu_aot_guard STATIC + src/sha256.c + src/aot_cache_guard.c + src/sram_partitioner.c +) + +add_library(freetpu::aot_guard ALIAS freetpu_aot_guard) + +target_include_directories(freetpu_aot_guard + PUBLIC + $ + $ +) + +if(CMAKE_C_COMPILER_ID MATCHES "Clang|GNU") + target_compile_options(freetpu_aot_guard PRIVATE + $<$:-Wall -Wextra -Werror -Wpedantic> + ) +endif() + +if(FREETPU_AOT_GUARD_BUILD_TESTS) + enable_testing() + add_executable(test_aot_guard tests/test_aot_guard.cpp) + target_link_libraries(test_aot_guard PRIVATE freetpu_aot_guard) + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") + target_compile_options(test_aot_guard PRIVATE + -Wall -Wextra -Werror -Wpedantic + ) + endif() + add_test(NAME freetpu_aot_guard_tests COMMAND test_aot_guard) + + add_executable(test_aot_guard_no_exceptions tests/test_aot_guard.cpp) + target_link_libraries(test_aot_guard_no_exceptions PRIVATE freetpu_aot_guard) + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") + target_compile_options(test_aot_guard_no_exceptions PRIVATE + -fno-exceptions -Wall -Wextra -Werror -Wpedantic + ) + endif() + add_test(NAME freetpu_aot_guard_no_exceptions_tests + COMMAND test_aot_guard_no_exceptions) +endif() diff --git a/aot-guard/Makefile b/aot-guard/Makefile new file mode 100644 index 0000000..9525d0f --- /dev/null +++ b/aot-guard/Makefile @@ -0,0 +1,75 @@ +ifeq ($(origin CC),default) +CC := clang +endif +ifeq ($(origin CXX),default) +CXX := clang++ +endif +ifeq ($(origin AR),default) +ifeq ($(shell uname -s),Darwin) +AR := /usr/bin/ar +else +AR := ar +endif +endif + +CFLAGS ?= -O2 +CXXFLAGS ?= -O2 + +C11_FLAGS := -std=c11 -Wall -Wextra -Werror -Wpedantic -Iinclude $(CFLAGS) +CXX17_FLAGS := -std=c++17 -Wall -Wextra -Werror -Wpedantic -Iinclude $(CXXFLAGS) +CXX17_NOEXC_FLAGS := -std=c++17 -fno-exceptions -Wall -Wextra -Werror -Wpedantic -Iinclude $(CXXFLAGS) + +BUILD_DIR := build +OBJ_DIR := $(BUILD_DIR)/obj +LIB := $(BUILD_DIR)/libfreetpu_aot_guard.a +TEST_BIN := $(BUILD_DIR)/test_aot_guard +SMOKE_NOEXC_BIN := $(BUILD_DIR)/smoke_no_exceptions + +C_SRCS := src/sha256.c src/aot_cache_guard.c src/sram_partitioner.c +C_OBJS := $(OBJ_DIR)/sha256.o $(OBJ_DIR)/aot_cache_guard.o $(OBJ_DIR)/sram_partitioner.o + +.PHONY: all test smoke-no-exceptions clean + +all: $(LIB) $(TEST_BIN) $(SMOKE_NOEXC_BIN) + +$(OBJ_DIR): + mkdir -p $(OBJ_DIR) + +$(OBJ_DIR)/sha256.o: src/sha256.c include/freetpu/aot_cache_guard.h | $(OBJ_DIR) + $(CC) $(C11_FLAGS) -c src/sha256.c -o $@ + +$(OBJ_DIR)/aot_cache_guard.o: src/aot_cache_guard.c include/freetpu/aot_cache_guard.h | $(OBJ_DIR) + $(CC) $(C11_FLAGS) -c src/aot_cache_guard.c -o $@ + +$(OBJ_DIR)/sram_partitioner.o: src/sram_partitioner.c include/freetpu/sram_partitioner.h | $(OBJ_DIR) + $(CC) $(C11_FLAGS) -c src/sram_partitioner.c -o $@ + +$(LIB): $(C_OBJS) + $(AR) rcs $@ $(C_OBJS) + +$(TEST_BIN): tests/test_aot_guard.cpp $(LIB) include/freetpu/aot_guard.hpp include/freetpu/aot_cache_guard.h include/freetpu/sram_partitioner.h + $(CXX) $(CXX17_FLAGS) tests/test_aot_guard.cpp $(LIB) -o $@ + +$(SMOKE_NOEXC_BIN): $(LIB) include/freetpu/aot_guard.hpp include/freetpu/aot_cache_guard.h include/freetpu/sram_partitioner.h + printf '%s\n' \ + '#include "freetpu/aot_guard.hpp"' \ + '#include ' \ + '#include ' \ + 'int main() {' \ + ' std::vector g{1, 2, 3}, w{4, 5, 6};' \ + ' freetpu::CompileOptions opts{2U, 100, 1U, "smoke"};' \ + ' auto k = freetpu::AotCacheGuard::compute_key_from_buffers(g, w, "edgetpu-compiler-1.0", "tensor-g6-v1", opts);' \ + ' freetpu::SramPartitioner p(FTPU_DEFAULT_SRAM_BUDGET_BYTES, true);' \ + ' auto plan = p.partition(freetpu::Span{});' \ + ' return (k.ok() && plan.ok()) ? 0 : 1;' \ + '}' \ + | $(CXX) $(CXX17_NOEXC_FLAGS) -x c++ - -x none $(LIB) -o $@ + +smoke-no-exceptions: $(SMOKE_NOEXC_BIN) + ./$(SMOKE_NOEXC_BIN) + +test: $(TEST_BIN) smoke-no-exceptions + ./$(TEST_BIN) + +clean: + rm -rf $(BUILD_DIR) diff --git a/aot-guard/README.md b/aot-guard/README.md new file mode 100644 index 0000000..144d8d5 --- /dev/null +++ b/aot-guard/README.md @@ -0,0 +1,78 @@ +# freetpu-aot-guard + +Standalone, zero-dependency clean-room C11 / C++17 module and test suite in [`freesilicon/freetpu`](https://github.com/freesilicon/freetpu). + +`freetpu-aot-guard` provides two defensive runtime components for EdgeTPU / NNAPI / LiteRT compilation pipelines: + +1. **`aot_cache_guard` — 5-Input Content-Addressed AOT Cache Keyer & Envelope Validator:** + - Eliminates false cache hits when compilation callers reuse an opaque 32-byte token across modified graphs, edited weights, compiler updates, target changes, or option changes. + - Computes a domain-separated, length-prefixed FIPS 180-4 SHA-256 cache key over all **5 inputs**: + 1. `graph_digest[32]` (SHA-256 of serialized graph topology / op list) + 2. `weights_digest[32]` (SHA-256 of model weights) + 3. `compiler_version` (non-empty compiler/runtime version string) + 4. `target_profile` (non-empty EdgeTPU hardware target profile string, e.g. `"tensor-g6-v1"`) + 5. `compile_options` (`execution_preference`, `priority`, `flags`, optional `extra_options`) + - Provides constant-time digest comparison and a clean-room bounds/version validator for `[uint32_le hdr_len][header_bytes][payload_bytes][metadata_bytes]` AOT cache containers, catching truncated blobs, malformed headers, compiler/profile mismatches, key mismatches, and policy mismatches before reuse. + +2. **`sram_partitioner` — `< 4 MiB` On-Chip SRAM Subgraph Partitioner:** + - Prevents `~60 s` HAL compiler watchdog stalls (which ignore caller `setTimeout` values) triggered when over-eager EdgeTPU delegation includes oversize FP32 tail operators. + - Performs overflow-safe tensor byte footprint calculation across `INT8`, `FP16`, `BF16`, `INT32`, `FP32`, and `INT64`/`FP64`. + - Enforces a strict `< 4 MiB` (`4,194,304 B`) on-chip SRAM working-set budget (configurable), explicitly catching oversize tail ops such as `[1, 19206, 90]` `INT8 -> FP32 DEQUANTIZE` (`6,914,160 B > 4 MiB`) and peeling back immediately preceding wide tail `CONCATENATION` + `LOGISTIC` cascades. + - Cuts the EdgeTPU delegate prefix cleanly (e.g., ops `0..259`) and routes the tail subgraph (`CONCATENATION + LOGISTIC + DEQUANTIZE + TFLite_Detection_PostProcess`) to `CPU/SME2` (when `has_sme2 = true`) or `CPU/NEON`. + +## Repository Layout + +```text +include/freetpu/ + aot_cache_guard.h # C11 SHA-256, 5-input cache keyer & container envelope validator + sram_partitioner.h # C11 overflow-safe tensor sizing & <4 MiB SRAM graph partitioner + aot_guard.hpp # Idiomatic C++17 RAII / Span wrapper (exception-free) +src/ + sha256.c # Zero-dependency FIPS 180-4 SHA-256 implementation + aot_cache_guard.c # 5-input content-addressed key derivation & container checks + sram_partitioner.c # <4 MiB SRAM working-set partitioning & tail cascade peeling +tests/ + test_aot_guard.cpp # C++17 unit test suite (NIST SHA-256, 5-input keyer, warm hit, SRAM) +``` + +## Building & Testing + +### Make (GNU Make 3.81+ / Clang) + +```bash +make -C aot-guard test +``` + +This builds `src/*.c` with `clang -std=c11 -Wall -Wextra -Werror -Wpedantic`, runs a `-fno-exceptions` C++17 header smoke test, compiles `tests/test_aot_guard.cpp` with `clang++ -std=c++17 -Wall -Wextra -Werror -Wpedantic`, and executes all tests. + +### CMake + +```bash +cmake -S aot-guard -B build-aot-guard +cmake --build build-aot-guard +ctest --test-dir build-aot-guard --output-on-failure +``` + +## Quick Usage (C++17) + +```cpp +#include "freetpu/aot_guard.hpp" + +freetpu::CompileOptions opts{}; +opts.execution_preference = 2U; +opts.priority = 100; +opts.flags = 0x01U; +opts.extra_options = "opt_level=3"; + +auto key = freetpu::AotCacheGuard::compute_key_from_buffers( + graph_span, weights_span, "edgetpu-compiler-2026.05.11-0.5", + "tensor-g6-v1", opts); + +freetpu::SramPartitioner partitioner( + FTPU_DEFAULT_SRAM_BUDGET_BYTES, /*has_sme2=*/true); +auto plan = partitioner.partition(ops); +``` + +## License + +Licensed under the [Apache License, Version 2.0](../LICENSE). diff --git a/aot-guard/include/freetpu/aot_cache_guard.h b/aot-guard/include/freetpu/aot_cache_guard.h new file mode 100644 index 0000000..18f5158 --- /dev/null +++ b/aot-guard/include/freetpu/aot_cache_guard.h @@ -0,0 +1,264 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef FREETPU_AOT_CACHE_GUARD_H +#define FREETPU_AOT_CACHE_GUARD_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** SHA-256 digest length in bytes. */ +#define FTPU_SHA256_DIGEST_SIZE 32U + +/** Hex-encoded SHA-256 buffer size in bytes (64 hex chars + NUL). */ +#define FTPU_SHA256_HEX_SIZE 65U + +/** Clean-room AOT cache container header magic ("FTAC" little-endian). */ +#define FTPU_AOT_CACHE_MAGIC 0x43415446U + +/** Current clean-room AOT cache container header format version. */ +#define FTPU_AOT_CACHE_FORMAT_VERSION 2U + +/** Maximum compiler/runtime version string length (excluding NUL). */ +#define FTPU_AOT_MAX_VERSION_LEN 127U + +/** Maximum EdgeTPU hardware target profile string length (excluding NUL). */ +#define FTPU_AOT_MAX_PROFILE_LEN 127U + +/** Maximum extra compile-options string length (excluding NUL). */ +#define FTPU_AOT_MAX_EXTRA_OPTIONS_LEN 1024U + +/** Maximum serialized header length accepted by the bounds validator. */ +#define FTPU_AOT_MAX_HEADER_LEN 4096U + +/** Fixed encoded size of header fields preceding variable-length strings. */ +#define FTPU_AOT_HEADER_FIXED_SIZE 72U + +/** + * Streaming FIPS 180-4 SHA-256 context. + */ +typedef struct ftpu_sha256_ctx { + uint32_t state[8]; + uint64_t total_bytes; + uint8_t buffer[64]; + size_t buf_len; +} ftpu_sha256_ctx_t; + +/** + * Status codes returned by aot_cache_guard functions. + */ +typedef enum ftpu_aot_status { + FTPU_AOT_OK = 0, + FTPU_AOT_ERR_INVALID_ARG = -1, + FTPU_AOT_ERR_TRUNCATED = -2, + FTPU_AOT_ERR_BOUNDS = -3, + FTPU_AOT_ERR_BAD_MAGIC = -4, + FTPU_AOT_ERR_UNSUPPORTED_VERSION = -5, + FTPU_AOT_ERR_MALFORMED_HEADER = -6, + FTPU_AOT_ERR_COMPILER_MISMATCH = -7, + FTPU_AOT_ERR_PROFILE_MISMATCH = -8, + FTPU_AOT_ERR_KEY_MISMATCH = -9, + FTPU_AOT_ERR_POLICY_MISMATCH = -10, + FTPU_AOT_ERR_BUFFER_TOO_SMALL = -11 +} ftpu_aot_status_t; + +/** + * Canonical compilation options hashed into the 5-input AOT cache key. + */ +typedef struct ftpu_aot_compile_options { + uint32_t execution_preference; + int32_t priority; + uint32_t flags; + const char *extra_options; +} ftpu_aot_compile_options_t; + +/** + * Inputs for computing a 5-input content-addressed EdgeTPU AOT cache key: + * 1. graph_digest[32] (SHA-256 of serialized graph topology / op list) + * 2. weights_digest[32] (SHA-256 of model weights) + * 3. compiler_version (non-empty compiler/runtime version string) + * 4. target_profile (non-empty EdgeTPU target profile, e.g. "tensor-g6-v1") + * 5. compile_options (execution_preference, priority, flags, extra_options) + */ +typedef struct ftpu_aot_cache_key_spec { + uint8_t graph_digest[FTPU_SHA256_DIGEST_SIZE]; + uint8_t weights_digest[FTPU_SHA256_DIGEST_SIZE]; + const char *compiler_version; + const char *target_profile; + ftpu_aot_compile_options_t compile_options; +} ftpu_aot_cache_key_spec_t; + +/** + * Clean-room decoded metadata header for an AOT cache container: + * [uint32_le hdr_len][header_bytes][payload_bytes][metadata_bytes] + */ +typedef struct ftpu_aot_cache_header { + uint32_t magic; + uint16_t format_version; + uint16_t compiler_version_len; + uint16_t target_profile_len; + uint16_t reserved; + char compiler_version[FTPU_AOT_MAX_VERSION_LEN + 1U]; + char target_profile[FTPU_AOT_MAX_PROFILE_LEN + 1U]; + uint8_t cache_key[FTPU_SHA256_DIGEST_SIZE]; + uint32_t execution_preference; + int32_t priority; + uint32_t flags; + uint64_t payload_size; + uint64_t metadata_size; +} ftpu_aot_cache_header_t; + +/** + * Optional runtime policy expectations enforced during container validation. + */ +typedef struct ftpu_aot_cache_expectation { + const char *expected_compiler_version; + const char *expected_target_profile; + const uint8_t *expected_cache_key; + bool check_execution_preference; + uint32_t expected_execution_preference; + bool check_priority; + int32_t expected_priority; + bool check_flags; + uint32_t expected_flags; +} ftpu_aot_cache_expectation_t; + +/** + * Validated offsets and header metadata inside an AOT cache container. + */ +typedef struct ftpu_aot_container_view { + ftpu_aot_cache_header_t header; + uint32_t hdr_len; + size_t payload_offset; + size_t payload_size; + size_t metadata_offset; + size_t metadata_size; +} ftpu_aot_container_view_t; + +/* ---- FIPS 180-4 SHA-256 ---- */ + +void ftpu_sha256_init(ftpu_sha256_ctx_t *ctx); +void ftpu_sha256_update(ftpu_sha256_ctx_t *ctx, const void *data, size_t len); +void ftpu_sha256_final(ftpu_sha256_ctx_t *ctx, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]); +void ftpu_sha256_hash(const void *data, + size_t len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]); +void ftpu_sha256_hex(const uint8_t digest[FTPU_SHA256_DIGEST_SIZE], + char out_hex[FTPU_SHA256_HEX_SIZE]); + +/* ---- Content-Addressed 5-Input AOT Cache Keying ---- */ + +/** + * Returns a human-readable static string for a status code. + */ +const char *ftpu_aot_status_str(ftpu_aot_status_t status); + +/** + * Returns default canonical compilation options (pref=0, prio=100, flags=0). + */ +ftpu_aot_compile_options_t ftpu_aot_compile_options_default(void); + +/** + * Digests an arbitrary byte buffer into a 32-byte SHA-256 digest. + */ +ftpu_aot_status_t ftpu_aot_digest_bytes( + const void *data, + size_t data_len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]); + +/** + * Digests raw model weights into a 32-byte SHA-256 digest. + */ +ftpu_aot_status_t ftpu_aot_digest_weights( + const void *weights, + size_t weights_len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]); + +/** + * Digests serialized graph topology / op list into a 32-byte SHA-256 digest. + */ +ftpu_aot_status_t ftpu_aot_digest_graph( + const void *graph, + size_t graph_len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]); + +/** + * Computes a domain-separated, length-prefixed 32-byte SHA-256 cache key over + * all 5 inputs: (graph_digest, weights_digest, compiler_version, + * target_profile, compile_options). + */ +ftpu_aot_status_t ftpu_aot_compute_cache_key( + const ftpu_aot_cache_key_spec_t *spec, + uint8_t out_token[FTPU_SHA256_DIGEST_SIZE]); + +/** + * Convenience helper: digests raw graph and weights buffers and computes the + * 5-input 32-byte cache key. + */ +ftpu_aot_status_t ftpu_aot_compute_cache_key_from_buffers( + const void *graph, + size_t graph_len, + const void *weights, + size_t weights_len, + const char *compiler_version, + const char *target_profile, + const ftpu_aot_compile_options_t *compile_options, + uint8_t out_token[FTPU_SHA256_DIGEST_SIZE]); + +/** + * Constant-time comparison of two 32-byte SHA-256 digests. + * Returns false if either pointer is NULL. + */ +bool ftpu_aot_digest_equal(const uint8_t a[FTPU_SHA256_DIGEST_SIZE], + const uint8_t b[FTPU_SHA256_DIGEST_SIZE]); + +/* ---- Clean-Room Container Envelope Encoding & Validation ---- */ + +/** + * Computes total encoded byte size for a clean-room AOT cache container, + * checking for integer overflow. + */ +ftpu_aot_status_t ftpu_aot_container_encoded_size(size_t compiler_version_len, + size_t target_profile_len, + size_t payload_size, + size_t metadata_size, + size_t *out_total_size); + +/** + * Encodes [uint32_le hdr_len][header_bytes][payload_bytes][metadata_bytes] + * into out_buf. payload_size / metadata_size inside header are populated from + * the explicit size arguments. + */ +ftpu_aot_status_t ftpu_aot_encode_container( + const ftpu_aot_cache_header_t *header, + const void *payload, + size_t payload_size, + const void *metadata, + size_t metadata_size, + uint8_t *out_buf, + size_t out_cap, + size_t *out_written); + +/** + * Validates bounds, magic, format version, string syntax, and optional + * runtime expectations on a clean-room AOT cache container. + */ +ftpu_aot_status_t ftpu_aot_validate_container( + const void *container, + size_t container_size, + const ftpu_aot_cache_expectation_t *expectation, + ftpu_aot_container_view_t *out_view); + +#ifdef __cplusplus +} +#endif + +#endif /* FREETPU_AOT_CACHE_GUARD_H */ diff --git a/aot-guard/include/freetpu/aot_guard.hpp b/aot-guard/include/freetpu/aot_guard.hpp new file mode 100644 index 0000000..924f3af --- /dev/null +++ b/aot-guard/include/freetpu/aot_guard.hpp @@ -0,0 +1,560 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef FREETPU_AOT_GUARD_HPP +#define FREETPU_AOT_GUARD_HPP + +#include "freetpu/aot_cache_guard.h" +#include "freetpu/sram_partitioner.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace freetpu { + +using Digest = std::array; + +/** + * Lightweight C++17 non-owning contiguous span view. + */ +template +class Span { +public: + using element_type = T; + using value_type = std::remove_cv_t; + using size_type = std::size_t; + using pointer = T*; + using const_pointer = const T*; + using iterator = T*; + using const_iterator = const T*; + + constexpr Span() noexcept : data_(nullptr), size_(0U) {} + constexpr Span(pointer ptr, size_type count) noexcept + : data_(ptr), size_(count) {} + + template + constexpr Span(T (&arr)[N]) noexcept : data_(arr), size_(N) {} + + template >> + constexpr Span(std::array& arr) noexcept + : data_(arr.data()), size_(N) {} + + template >> + constexpr Span(const std::array& arr) noexcept + : data_(arr.data()), size_(N) {} + + template >> + Span(std::vector& vec) noexcept + : data_(vec.data()), size_(vec.size()) {} + + template >> + Span(const std::vector& vec) noexcept + : data_(vec.data()), size_(vec.size()) {} + + [[nodiscard]] constexpr pointer data() const noexcept { return data_; } + [[nodiscard]] constexpr size_type size() const noexcept { return size_; } + [[nodiscard]] constexpr bool empty() const noexcept { return size_ == 0U; } + [[nodiscard]] constexpr iterator begin() const noexcept { return data_; } + [[nodiscard]] constexpr iterator end() const noexcept { + return data_ + size_; + } + + [[nodiscard]] constexpr T& operator[](size_type index) const noexcept { + return data_[index]; + } + + [[nodiscard]] constexpr Span subspan(size_type offset, + size_type count) const noexcept { + if (offset > size_) { + return Span(); + } + size_type avail = size_ - offset; + return Span(data_ + offset, count < avail ? count : avail); + } + +private: + pointer data_; + size_type size_; +}; + +[[nodiscard]] inline Span as_bytes( + std::string_view text) noexcept { + return Span( + reinterpret_cast(text.data()), text.size()); +} + +/** + * RAII streaming FIPS 180-4 SHA-256 hasher that scrubs its state on scope exit. + */ +class Sha256Hasher { +public: + Sha256Hasher() noexcept : finalized_(false) { ftpu_sha256_init(&ctx_); } + + Sha256Hasher(const Sha256Hasher&) = delete; + Sha256Hasher& operator=(const Sha256Hasher&) = delete; + + Sha256Hasher(Sha256Hasher&& other) noexcept + : ctx_(other.ctx_), finalized_(other.finalized_) { + other.finalized_ = true; + ftpu_sha256_init(&other.ctx_); + } + + Sha256Hasher& operator=(Sha256Hasher&& other) noexcept { + if (this != &other) { + scrub(); + ctx_ = other.ctx_; + finalized_ = other.finalized_; + other.finalized_ = true; + ftpu_sha256_init(&other.ctx_); + } + return *this; + } + + ~Sha256Hasher() noexcept { scrub(); } + + Sha256Hasher& update(Span bytes) noexcept { + if (!finalized_ && !bytes.empty()) { + ftpu_sha256_update(&ctx_, bytes.data(), bytes.size()); + } + return *this; + } + + Sha256Hasher& update(std::string_view text) noexcept { + return update(as_bytes(text)); + } + + [[nodiscard]] Digest finalize() noexcept { + Digest out{}; + if (!finalized_) { + ftpu_sha256_final(&ctx_, out.data()); + finalized_ = true; + } + return out; + } + + [[nodiscard]] static Digest hash(Span bytes) noexcept { + Digest out{}; + ftpu_sha256_hash(bytes.data(), bytes.size(), out.data()); + return out; + } + + [[nodiscard]] static Digest hash(std::string_view text) noexcept { + return hash(as_bytes(text)); + } + + [[nodiscard]] static std::string to_hex(const Digest& digest) { + std::array buf{}; + ftpu_sha256_hex(digest.data(), buf.data()); + return std::string(buf.data(), FTPU_SHA256_HEX_SIZE - 1U); + } + +private: + void scrub() noexcept { + if (!finalized_) { + Digest scratch{}; + ftpu_sha256_final(&ctx_, scratch.data()); + finalized_ = true; + } + } + + ftpu_sha256_ctx_t ctx_{}; + bool finalized_; +}; + +struct CompileOptions { + uint32_t execution_preference = 0U; + int32_t priority = 100; + uint32_t flags = 0U; + std::string extra_options; +}; + +struct AotCacheKeySpec { + Digest graph_digest{}; + Digest weights_digest{}; + std::string compiler_version; + std::string target_profile; + CompileOptions compile_options{}; +}; + +struct DigestResult { + ftpu_aot_status_t status = FTPU_AOT_OK; + Digest value{}; + + [[nodiscard]] bool ok() const noexcept { return status == FTPU_AOT_OK; } +}; + +struct EncodeResult { + ftpu_aot_status_t status = FTPU_AOT_OK; + std::vector bytes; + + [[nodiscard]] bool ok() const noexcept { return status == FTPU_AOT_OK; } +}; + +struct ContainerView { + ftpu_aot_status_t status = FTPU_AOT_OK; + std::string compiler_version; + std::string target_profile; + Digest cache_key{}; + uint32_t execution_preference = 0U; + int32_t priority = 0; + uint32_t flags = 0U; + Span payload; + Span metadata; + + [[nodiscard]] bool ok() const noexcept { return status == FTPU_AOT_OK; } +}; + +/** + * C++17 wrapper for 5-input content-addressed AOT cache keying and container validation. + */ +class AotCacheGuard { +public: + [[nodiscard]] static DigestResult digest_bytes( + Span bytes) noexcept { + DigestResult res{}; + res.status = ftpu_aot_digest_bytes(bytes.data(), bytes.size(), + res.value.data()); + return res; + } + + [[nodiscard]] static DigestResult digest_weights( + Span weights) noexcept { + DigestResult res{}; + res.status = ftpu_aot_digest_weights(weights.data(), weights.size(), + res.value.data()); + return res; + } + + [[nodiscard]] static DigestResult digest_graph( + Span graph) noexcept { + DigestResult res{}; + res.status = ftpu_aot_digest_graph(graph.data(), graph.size(), + res.value.data()); + return res; + } + + [[nodiscard]] static DigestResult compute_key( + const AotCacheKeySpec& spec) noexcept { + DigestResult res{}; + ftpu_aot_cache_key_spec_t c_spec{}; + std::memcpy(c_spec.graph_digest, spec.graph_digest.data(), + FTPU_SHA256_DIGEST_SIZE); + std::memcpy(c_spec.weights_digest, spec.weights_digest.data(), + FTPU_SHA256_DIGEST_SIZE); + c_spec.compiler_version = spec.compiler_version.c_str(); + c_spec.target_profile = spec.target_profile.c_str(); + c_spec.compile_options.execution_preference = + spec.compile_options.execution_preference; + c_spec.compile_options.priority = spec.compile_options.priority; + c_spec.compile_options.flags = spec.compile_options.flags; + c_spec.compile_options.extra_options = + spec.compile_options.extra_options.empty() + ? nullptr + : spec.compile_options.extra_options.c_str(); + res.status = ftpu_aot_compute_cache_key(&c_spec, res.value.data()); + return res; + } + + [[nodiscard]] static DigestResult compute_key_from_buffers( + Span graph, + Span weights, + const std::string& compiler_version, + const std::string& target_profile, + const CompileOptions& options = {}) noexcept { + DigestResult res{}; + ftpu_aot_compile_options_t c_opts{}; + c_opts.execution_preference = options.execution_preference; + c_opts.priority = options.priority; + c_opts.flags = options.flags; + c_opts.extra_options = options.extra_options.empty() + ? nullptr + : options.extra_options.c_str(); + res.status = ftpu_aot_compute_cache_key_from_buffers( + graph.data(), graph.size(), weights.data(), weights.size(), + compiler_version.c_str(), target_profile.c_str(), &c_opts, + res.value.data()); + return res; + } + + [[nodiscard]] static bool digests_equal(const Digest& a, + const Digest& b) noexcept { + return ftpu_aot_digest_equal(a.data(), b.data()); + } + + [[nodiscard]] static EncodeResult encode_container( + std::string_view compiler_version, + std::string_view target_profile, + const Digest& cache_key, + const CompileOptions& options, + Span payload, + Span metadata) { + EncodeResult res{}; + if (compiler_version.empty() || + compiler_version.size() > FTPU_AOT_MAX_VERSION_LEN || + target_profile.empty() || + target_profile.size() > FTPU_AOT_MAX_PROFILE_LEN) { + res.status = FTPU_AOT_ERR_MALFORMED_HEADER; + return res; + } + + size_t total_size = 0U; + res.status = ftpu_aot_container_encoded_size( + compiler_version.size(), target_profile.size(), payload.size(), + metadata.size(), &total_size); + if (!res.ok()) { + return res; + } + + ftpu_aot_cache_header_t hdr{}; + hdr.magic = FTPU_AOT_CACHE_MAGIC; + hdr.format_version = FTPU_AOT_CACHE_FORMAT_VERSION; + hdr.compiler_version_len = + static_cast(compiler_version.size()); + hdr.target_profile_len = static_cast(target_profile.size()); + hdr.reserved = 0U; + std::memcpy(hdr.compiler_version, compiler_version.data(), + compiler_version.size()); + hdr.compiler_version[compiler_version.size()] = '\0'; + std::memcpy(hdr.target_profile, target_profile.data(), + target_profile.size()); + hdr.target_profile[target_profile.size()] = '\0'; + std::memcpy(hdr.cache_key, cache_key.data(), FTPU_SHA256_DIGEST_SIZE); + hdr.execution_preference = options.execution_preference; + hdr.priority = options.priority; + hdr.flags = options.flags; + + res.bytes.resize(total_size); + size_t written = 0U; + res.status = ftpu_aot_encode_container( + &hdr, payload.data(), payload.size(), metadata.data(), + metadata.size(), res.bytes.data(), res.bytes.size(), &written); + if (!res.ok()) { + res.bytes.clear(); + } else { + res.bytes.resize(written); + } + return res; + } + + [[nodiscard]] static ContainerView validate_container( + Span container, + std::optional expected_compiler_version = std::nullopt, + std::optional expected_target_profile = std::nullopt, + std::optional expected_cache_key = std::nullopt, + std::optional expected_execution_preference = std::nullopt, + std::optional expected_priority = std::nullopt, + std::optional expected_flags = std::nullopt) { + ContainerView out{}; + ftpu_aot_cache_expectation_t exp{}; + bool has_exp = false; + + if (expected_compiler_version.has_value()) { + exp.expected_compiler_version = expected_compiler_version->c_str(); + has_exp = true; + } + if (expected_target_profile.has_value()) { + exp.expected_target_profile = expected_target_profile->c_str(); + has_exp = true; + } + if (expected_cache_key.has_value()) { + exp.expected_cache_key = expected_cache_key->data(); + has_exp = true; + } + if (expected_execution_preference.has_value()) { + exp.check_execution_preference = true; + exp.expected_execution_preference = *expected_execution_preference; + has_exp = true; + } + if (expected_priority.has_value()) { + exp.check_priority = true; + exp.expected_priority = *expected_priority; + has_exp = true; + } + if (expected_flags.has_value()) { + exp.check_flags = true; + exp.expected_flags = *expected_flags; + has_exp = true; + } + + ftpu_aot_container_view_t c_view{}; + out.status = ftpu_aot_validate_container( + container.data(), container.size(), has_exp ? &exp : nullptr, + &c_view); + if (!out.ok()) { + return out; + } + + out.compiler_version.assign(c_view.header.compiler_version, + c_view.header.compiler_version_len); + out.target_profile.assign(c_view.header.target_profile, + c_view.header.target_profile_len); + std::memcpy(out.cache_key.data(), c_view.header.cache_key, + FTPU_SHA256_DIGEST_SIZE); + out.execution_preference = c_view.header.execution_preference; + out.priority = c_view.header.priority; + out.flags = c_view.header.flags; + out.payload = container.subspan(c_view.payload_offset, c_view.payload_size); + out.metadata = + container.subspan(c_view.metadata_offset, c_view.metadata_size); + return out; + } +}; + +/** + * C++17 tensor specification for SRAM footprint analysis. + */ +struct TensorSpec { + std::vector dims; + ftpu_dtype_t dtype = FTPU_DTYPE_INT8; + + [[nodiscard]] static TensorSpec make(std::initializer_list shape, + ftpu_dtype_t element_dtype) { + return TensorSpec{std::vector(shape), element_dtype}; + } + + [[nodiscard]] ftpu_sram_status_t to_c_desc( + ftpu_tensor_desc_t* out) const noexcept { + if (out == nullptr || dims.size() > FTPU_MAX_TENSOR_DIMS) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + *out = ftpu_tensor_desc_t{}; + out->rank = static_cast(dims.size()); + out->dtype = dtype; + for (std::size_t i = 0U; i < dims.size(); ++i) { + out->dims[i] = dims[i]; + } + return FTPU_SRAM_OK; + } + + [[nodiscard]] std::optional byte_size() const noexcept { + ftpu_tensor_desc_t desc{}; + if (to_c_desc(&desc) != FTPU_SRAM_OK) { + return std::nullopt; + } + uint64_t bytes = 0U; + if (ftpu_tensor_byte_size(&desc, &bytes) != FTPU_SRAM_OK) { + return std::nullopt; + } + return bytes; + } +}; + +struct OpSpec { + uint32_t op_index = 0U; + ftpu_op_kind_t kind = FTPU_OP_GENERIC; + bool hal_supported = true; + std::vector inputs; + std::vector outputs; +}; + +struct PartitionResult { + ftpu_sram_status_t status = FTPU_SRAM_OK; + ftpu_partition_plan_t plan{}; + std::vector op_targets; + + [[nodiscard]] bool ok() const noexcept { return status == FTPU_SRAM_OK; } +}; + +/** + * C++17 wrapper for < 4 MiB EdgeTPU on-chip SRAM subgraph partitioning. + */ +class SramPartitioner { +public: + explicit SramPartitioner( + uint64_t sram_budget_bytes = FTPU_DEFAULT_SRAM_BUDGET_BYTES, + bool has_sme2 = false, + bool peel_tail_cascades = true) noexcept { + config_.sram_budget_bytes = sram_budget_bytes; + config_.has_sme2 = has_sme2; + config_.peel_tail_cascades = peel_tail_cascades; + } + + [[nodiscard]] const ftpu_partition_config_t& config() const noexcept { + return config_; + } + + [[nodiscard]] PartitionResult partition( + Span ops) const { + PartitionResult res{}; + res.op_targets.resize(ops.size()); + res.status = ftpu_partition_graph( + ops.data(), ops.size(), &config_, &res.plan, + ops.empty() ? nullptr : res.op_targets.data(), + res.op_targets.size()); + if (!res.ok()) { + res.op_targets.clear(); + } + return res; + } + + [[nodiscard]] PartitionResult partition(Span ops) const { + PartitionResult res{}; + std::vector> input_storage(ops.size()); + std::vector> output_storage(ops.size()); + std::vector c_ops(ops.size()); + + for (std::size_t i = 0U; i < ops.size(); ++i) { + input_storage[i].resize(ops[i].inputs.size()); + for (std::size_t j = 0U; j < ops[i].inputs.size(); ++j) { + ftpu_sram_status_t rc = + ops[i].inputs[j].to_c_desc(&input_storage[i][j]); + if (rc != FTPU_SRAM_OK) { + res.status = rc; + return res; + } + } + output_storage[i].resize(ops[i].outputs.size()); + for (std::size_t j = 0U; j < ops[i].outputs.size(); ++j) { + ftpu_sram_status_t rc = + ops[i].outputs[j].to_c_desc(&output_storage[i][j]); + if (rc != FTPU_SRAM_OK) { + res.status = rc; + return res; + } + } + + c_ops[i].op_index = ops[i].op_index; + c_ops[i].kind = ops[i].kind; + c_ops[i].hal_supported = ops[i].hal_supported; + c_ops[i].inputs = input_storage[i].empty() + ? nullptr + : input_storage[i].data(); + c_ops[i].num_inputs = input_storage[i].size(); + c_ops[i].outputs = output_storage[i].empty() + ? nullptr + : output_storage[i].data(); + c_ops[i].num_outputs = output_storage[i].size(); + } + + return partition(Span(c_ops)); + } + +private: + ftpu_partition_config_t config_{}; +}; + +} // namespace freetpu + +#endif // FREETPU_AOT_GUARD_HPP diff --git a/aot-guard/include/freetpu/sram_partitioner.h b/aot-guard/include/freetpu/sram_partitioner.h new file mode 100644 index 0000000..d16d7bd --- /dev/null +++ b/aot-guard/include/freetpu/sram_partitioner.h @@ -0,0 +1,187 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef FREETPU_SRAM_PARTITIONER_H +#define FREETPU_SRAM_PARTITIONER_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** Default EdgeTPU on-chip SRAM working-set budget (4 MiB strict ceiling). */ +#define FTPU_DEFAULT_SRAM_BUDGET_BYTES (4ULL * 1024ULL * 1024ULL) + +/** Maximum supported tensor rank. */ +#define FTPU_MAX_TENSOR_DIMS 8U + +/** + * Status codes returned by sram_partitioner functions. + */ +typedef enum ftpu_sram_status { + FTPU_SRAM_OK = 0, + FTPU_SRAM_ERR_INVALID_ARG = -1, + FTPU_SRAM_ERR_OVERFLOW = -2, + FTPU_SRAM_ERR_BUFFER_TOO_SMALL = -3 +} ftpu_sram_status_t; + +/** + * Supported tensor element data types. + */ +typedef enum ftpu_dtype { + FTPU_DTYPE_UINT8 = 0, + FTPU_DTYPE_INT8 = 1, + FTPU_DTYPE_BOOL = 2, + FTPU_DTYPE_INT16 = 3, + FTPU_DTYPE_FP16 = 4, + FTPU_DTYPE_BF16 = 5, + FTPU_DTYPE_INT32 = 6, + FTPU_DTYPE_FP32 = 7, + FTPU_DTYPE_INT64 = 8, + FTPU_DTYPE_FP64 = 9 +} ftpu_dtype_t; + +/** + * High-level operator classes used for tail cascade detection and routing. + */ +typedef enum ftpu_op_kind { + FTPU_OP_GENERIC = 0, + FTPU_OP_QUANTIZE = 1, + FTPU_OP_DEQUANTIZE = 2, + FTPU_OP_CONCATENATION = 3, + FTPU_OP_LOGISTIC = 4, + FTPU_OP_RESHAPE = 5, + FTPU_OP_DETECTION_POSTPROCESS = 6 +} ftpu_op_kind_t; + +/** + * Target execution backend selected by the partitioner. + */ +typedef enum ftpu_target_backend { + FTPU_TARGET_EDGETPU = 0, + FTPU_TARGET_CPU_SME2 = 1, + FTPU_TARGET_CPU_NEON = 2 +} ftpu_target_backend_t; + +/** + * Reason why EdgeTPU delegation was cut at a partition boundary. + */ +typedef enum ftpu_cut_reason { + FTPU_CUT_NONE = 0, + FTPU_CUT_SRAM_EXCEEDED = 1, + FTPU_CUT_TAIL_CASCADE_BEFORE_SRAM = 2, + FTPU_CUT_UNSUPPORTED_OP = 3 +} ftpu_cut_reason_t; + +/** + * Tensor shape and element type descriptor. + */ +typedef struct ftpu_tensor_desc { + uint32_t rank; + uint64_t dims[FTPU_MAX_TENSOR_DIMS]; + ftpu_dtype_t dtype; +} ftpu_tensor_desc_t; + +/** + * Operator descriptor in topological execution order. + */ +typedef struct ftpu_op_desc { + uint32_t op_index; + ftpu_op_kind_t kind; + bool hal_supported; + const ftpu_tensor_desc_t *inputs; + size_t num_inputs; + const ftpu_tensor_desc_t *outputs; + size_t num_outputs; +} ftpu_op_desc_t; + +/** + * Partitioner configuration. + */ +typedef struct ftpu_partition_config { + /** Strict upper bound (< sram_budget_bytes). 0 selects 4 MiB default. */ + uint64_t sram_budget_bytes; + /** True on ARM64 targets with SME2; otherwise routes CPU ops to NEON. */ + bool has_sme2; + /** Peel wide CONCATENATION/LOGISTIC cascades immediately preceding an + * SRAM-exceeding tail op so the entire tail executes on CPU. */ + bool peel_tail_cascades; +} ftpu_partition_config_t; + +/** + * Partition plan summarizing the EdgeTPU prefix and CPU tail split. + */ +typedef struct ftpu_partition_plan { + uint32_t total_ops; + uint32_t edgetpu_start_op; + uint32_t edgetpu_end_op_exclusive; + uint32_t delegated_op_count; + uint32_t tail_start_op; + ftpu_target_backend_t tail_backend; + uint32_t trigger_op_index; + uint64_t trigger_op_bytes; + uint64_t peak_delegated_working_set_bytes; + uint64_t effective_budget_bytes; + ftpu_cut_reason_t reason; +} ftpu_partition_plan_t; + +/** + * Returns byte width for dtype, or 0 for unknown dtype. + */ +size_t ftpu_dtype_byte_width(ftpu_dtype_t dtype); + +/** + * Returns a human-readable backend string ("EdgeTPU", "CPU/SME2", "CPU/NEON"). + */ +const char *ftpu_target_backend_name(ftpu_target_backend_t backend); + +/** + * Returns a human-readable status string. + */ +const char *ftpu_sram_status_str(ftpu_sram_status_t status); + +/** + * Builds the default partitioner config (4 MiB SRAM budget, peel_tail_cascades=true). + */ +ftpu_partition_config_t ftpu_partition_config_default(bool has_sme2); + +/** + * Computes tensor byte footprint with strict uint64_t overflow checks. + * A rank-0 scalar has 1 element (dtype_byte_width bytes). + */ +ftpu_sram_status_t ftpu_tensor_byte_size(const ftpu_tensor_desc_t *tensor, + uint64_t *out_bytes); + +/** + * Computes combined input+output working-set bytes and max single output tensor + * bytes for an operator, failing closed on uint64_t overflow. + */ +ftpu_sram_status_t ftpu_op_working_set_bytes(const ftpu_op_desc_t *op, + uint64_t *out_working_set_bytes, + uint64_t *out_max_output_bytes); + +/** + * Partitions an operator sequence into a safe EdgeTPU prefix (each delegated + * op strictly < sram_budget_bytes) and a CPU tail routed to CPU/SME2 or + * CPU/NEON. + * + * If out_op_targets is non-NULL, out_op_targets_len must be >= num_ops and + * receives per-op backend assignments. + */ +ftpu_sram_status_t ftpu_partition_graph(const ftpu_op_desc_t *ops, + size_t num_ops, + const ftpu_partition_config_t *config, + ftpu_partition_plan_t *out_plan, + ftpu_target_backend_t *out_op_targets, + size_t out_op_targets_len); + +#ifdef __cplusplus +} +#endif + +#endif /* FREETPU_SRAM_PARTITIONER_H */ diff --git a/aot-guard/src/aot_cache_guard.c b/aot-guard/src/aot_cache_guard.c new file mode 100644 index 0000000..a0f2adc --- /dev/null +++ b/aot-guard/src/aot_cache_guard.c @@ -0,0 +1,622 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "freetpu/aot_cache_guard.h" + +#include + +static void write_le16(uint8_t *dst, uint16_t v) +{ + dst[0] = (uint8_t)(v & 0xFFU); + dst[1] = (uint8_t)((v >> 8) & 0xFFU); +} + +static void write_le32(uint8_t *dst, uint32_t v) +{ + dst[0] = (uint8_t)(v & 0xFFU); + dst[1] = (uint8_t)((v >> 8) & 0xFFU); + dst[2] = (uint8_t)((v >> 16) & 0xFFU); + dst[3] = (uint8_t)((v >> 24) & 0xFFU); +} + +static void write_le64(uint8_t *dst, uint64_t v) +{ + size_t i; + for (i = 0U; i < 8U; ++i) { + dst[i] = (uint8_t)((v >> (8U * i)) & 0xFFU); + } +} + +static uint16_t read_le16(const uint8_t *src) +{ + return (uint16_t)((uint16_t)src[0] | ((uint16_t)src[1] << 8)); +} + +static uint32_t read_le32(const uint8_t *src) +{ + return ((uint32_t)src[0]) | + ((uint32_t)src[1] << 8) | + ((uint32_t)src[2] << 16) | + ((uint32_t)src[3] << 24); +} + +static uint64_t read_le64(const uint8_t *src) +{ + uint64_t v = 0U; + size_t i; + for (i = 0U; i < 8U; ++i) { + v |= ((uint64_t)src[i]) << (8U * i); + } + return v; +} + +static void sha256_update_le32(ftpu_sha256_ctx_t *ctx, uint32_t v) +{ + uint8_t buf[4]; + write_le32(buf, v); + ftpu_sha256_update(ctx, buf, sizeof(buf)); +} + +static void sha256_update_lp_bytes(ftpu_sha256_ctx_t *ctx, + const void *data, + uint32_t len) +{ + sha256_update_le32(ctx, len); + if (len > 0U) { + ftpu_sha256_update(ctx, data, (size_t)len); + } +} + +static void sha256_update_lp_u32(ftpu_sha256_ctx_t *ctx, uint32_t value) +{ + uint8_t buf[4]; + write_le32(buf, value); + sha256_update_lp_bytes(ctx, buf, sizeof(buf)); +} + +static bool is_valid_utf8_label(const uint8_t *bytes, size_t len, size_t max_len) +{ + size_t i = 0U; + + if (bytes == NULL || len == 0U || len > max_len) { + return false; + } + + while (i < len) { + uint8_t b = bytes[i]; + /* Reject NUL and ASCII control characters (0x00..0x1F, 0x7F). */ + if (b < 0x20U || b == 0x7FU) { + return false; + } + if (b < 0x80U) { + i += 1U; + continue; + } + /* Validate UTF-8 multi-byte sequences strictly. */ + if ((b & 0xE0U) == 0xC0U) { + if (i + 1U >= len || b < 0xC2U || (bytes[i + 1U] & 0xC0U) != 0x80U) { + return false; + } + i += 2U; + } else if ((b & 0xF0U) == 0xE0U) { + uint8_t b1; + if (i + 2U >= len) { + return false; + } + b1 = bytes[i + 1U]; + if ((b1 & 0xC0U) != 0x80U || (bytes[i + 2U] & 0xC0U) != 0x80U) { + return false; + } + if ((b == 0xE0U && b1 < 0xA0U) || (b == 0xEDU && b1 >= 0xA0U)) { + return false; + } + i += 3U; + } else if ((b & 0xF8U) == 0xF0U) { + uint8_t b1; + if (i + 3U >= len || b > 0xF4U) { + return false; + } + b1 = bytes[i + 1U]; + if ((b1 & 0xC0U) != 0x80U || (bytes[i + 2U] & 0xC0U) != 0x80U || + (bytes[i + 3U] & 0xC0U) != 0x80U) { + return false; + } + if ((b == 0xF0U && b1 < 0x90U) || (b == 0xF4U && b1 >= 0x90U)) { + return false; + } + i += 4U; + } else { + return false; + } + } + + return true; +} + +static size_t bounded_cstr_len(const char *buf, size_t max_len) +{ + size_t len = 0U; + while (len <= max_len && buf[len] != '\0') { + ++len; + } + return len; +} + +const char *ftpu_aot_status_str(ftpu_aot_status_t status) +{ + switch (status) { + case FTPU_AOT_OK: + return "OK"; + case FTPU_AOT_ERR_INVALID_ARG: + return "INVALID_ARG"; + case FTPU_AOT_ERR_TRUNCATED: + return "TRUNCATED"; + case FTPU_AOT_ERR_BOUNDS: + return "BOUNDS"; + case FTPU_AOT_ERR_BAD_MAGIC: + return "BAD_MAGIC"; + case FTPU_AOT_ERR_UNSUPPORTED_VERSION: + return "UNSUPPORTED_VERSION"; + case FTPU_AOT_ERR_MALFORMED_HEADER: + return "MALFORMED_HEADER"; + case FTPU_AOT_ERR_COMPILER_MISMATCH: + return "COMPILER_MISMATCH"; + case FTPU_AOT_ERR_PROFILE_MISMATCH: + return "PROFILE_MISMATCH"; + case FTPU_AOT_ERR_KEY_MISMATCH: + return "KEY_MISMATCH"; + case FTPU_AOT_ERR_POLICY_MISMATCH: + return "POLICY_MISMATCH"; + case FTPU_AOT_ERR_BUFFER_TOO_SMALL: + return "BUFFER_TOO_SMALL"; + default: + return "UNKNOWN"; + } +} + +ftpu_aot_compile_options_t ftpu_aot_compile_options_default(void) +{ + ftpu_aot_compile_options_t opts; + opts.execution_preference = 0U; + opts.priority = 100; + opts.flags = 0U; + opts.extra_options = NULL; + return opts; +} + +ftpu_aot_status_t ftpu_aot_digest_bytes( + const void *data, + size_t data_len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]) +{ + if (out_digest == NULL) { + return FTPU_AOT_ERR_INVALID_ARG; + } + if (data == NULL && data_len > 0U) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + ftpu_sha256_hash(data, data_len, out_digest); + return FTPU_AOT_OK; +} + +ftpu_aot_status_t ftpu_aot_digest_weights( + const void *weights, + size_t weights_len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]) +{ + return ftpu_aot_digest_bytes(weights, weights_len, out_digest); +} + +ftpu_aot_status_t ftpu_aot_digest_graph( + const void *graph, + size_t graph_len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]) +{ + return ftpu_aot_digest_bytes(graph, graph_len, out_digest); +} + +ftpu_aot_status_t ftpu_aot_compute_cache_key( + const ftpu_aot_cache_key_spec_t *spec, + uint8_t out_token[FTPU_SHA256_DIGEST_SIZE]) +{ + static const char domain_tag[] = "freetpu.aot.cache_key.v2"; + ftpu_sha256_ctx_t ctx; + size_t compiler_len; + size_t profile_len; + size_t extra_len = 0U; + const char *extra_opts; + + if (spec == NULL || out_token == NULL || + spec->compiler_version == NULL || spec->target_profile == NULL) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + compiler_len = strlen(spec->compiler_version); + profile_len = strlen(spec->target_profile); + if (!is_valid_utf8_label((const uint8_t *)spec->compiler_version, + compiler_len, FTPU_AOT_MAX_VERSION_LEN) || + !is_valid_utf8_label((const uint8_t *)spec->target_profile, + profile_len, FTPU_AOT_MAX_PROFILE_LEN)) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + extra_opts = spec->compile_options.extra_options; + if (extra_opts != NULL) { + extra_len = strlen(extra_opts); + if (extra_len > FTPU_AOT_MAX_EXTRA_OPTIONS_LEN) { + return FTPU_AOT_ERR_INVALID_ARG; + } + } + + ftpu_sha256_init(&ctx); + + /* Explicit domain separation tag including trailing NUL byte. */ + ftpu_sha256_update(&ctx, domain_tag, sizeof(domain_tag)); + + /* 1. Length-prefixed graph topology digest (32 bytes). */ + sha256_update_lp_bytes(&ctx, spec->graph_digest, FTPU_SHA256_DIGEST_SIZE); + + /* 2. Length-prefixed model weights digest (32 bytes). */ + sha256_update_lp_bytes(&ctx, spec->weights_digest, FTPU_SHA256_DIGEST_SIZE); + + /* 3. Length-prefixed compiler/runtime version string. */ + sha256_update_lp_bytes(&ctx, spec->compiler_version, + (uint32_t)compiler_len); + + /* 4. Length-prefixed EdgeTPU hardware target profile string. */ + sha256_update_lp_bytes(&ctx, spec->target_profile, (uint32_t)profile_len); + + /* 5. Length-prefixed canonical compile options. */ + sha256_update_lp_u32(&ctx, spec->compile_options.execution_preference); + sha256_update_lp_u32(&ctx, (uint32_t)spec->compile_options.priority); + sha256_update_lp_u32(&ctx, spec->compile_options.flags); + sha256_update_lp_bytes(&ctx, (extra_len > 0U) ? extra_opts : "", + (uint32_t)extra_len); + + ftpu_sha256_final(&ctx, out_token); + return FTPU_AOT_OK; +} + +ftpu_aot_status_t ftpu_aot_compute_cache_key_from_buffers( + const void *graph, + size_t graph_len, + const void *weights, + size_t weights_len, + const char *compiler_version, + const char *target_profile, + const ftpu_aot_compile_options_t *compile_options, + uint8_t out_token[FTPU_SHA256_DIGEST_SIZE]) +{ + ftpu_aot_cache_key_spec_t spec; + ftpu_aot_status_t rc; + + if (compiler_version == NULL || target_profile == NULL || + out_token == NULL) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + memset(&spec, 0, sizeof(spec)); + rc = ftpu_aot_digest_graph(graph, graph_len, spec.graph_digest); + if (rc != FTPU_AOT_OK) { + return rc; + } + + rc = ftpu_aot_digest_weights(weights, weights_len, spec.weights_digest); + if (rc != FTPU_AOT_OK) { + return rc; + } + + spec.compiler_version = compiler_version; + spec.target_profile = target_profile; + spec.compile_options = (compile_options != NULL) + ? *compile_options + : ftpu_aot_compile_options_default(); + return ftpu_aot_compute_cache_key(&spec, out_token); +} + +bool ftpu_aot_digest_equal(const uint8_t a[FTPU_SHA256_DIGEST_SIZE], + const uint8_t b[FTPU_SHA256_DIGEST_SIZE]) +{ + const volatile uint8_t *va = (const volatile uint8_t *)a; + const volatile uint8_t *vb = (const volatile uint8_t *)b; + uint8_t diff = 0U; + size_t i; + + if (a == NULL || b == NULL) { + return false; + } + + for (i = 0U; i < FTPU_SHA256_DIGEST_SIZE; ++i) { + diff |= (uint8_t)(va[i] ^ vb[i]); + } + return diff == 0U; +} + +ftpu_aot_status_t ftpu_aot_container_encoded_size(size_t compiler_version_len, + size_t target_profile_len, + size_t payload_size, + size_t metadata_size, + size_t *out_total_size) +{ + size_t hdr_len; + size_t total; + + if (out_total_size == NULL) { + return FTPU_AOT_ERR_INVALID_ARG; + } + if (compiler_version_len == 0U || + compiler_version_len > FTPU_AOT_MAX_VERSION_LEN || + target_profile_len == 0U || + target_profile_len > FTPU_AOT_MAX_PROFILE_LEN) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + hdr_len = FTPU_AOT_HEADER_FIXED_SIZE + compiler_version_len + + target_profile_len; + if (hdr_len > FTPU_AOT_MAX_HEADER_LEN) { + return FTPU_AOT_ERR_BOUNDS; + } + + total = 4U + hdr_len; + if (payload_size > SIZE_MAX - total) { + return FTPU_AOT_ERR_BOUNDS; + } + total += payload_size; + + if (metadata_size > SIZE_MAX - total) { + return FTPU_AOT_ERR_BOUNDS; + } + total += metadata_size; + + *out_total_size = total; + return FTPU_AOT_OK; +} + +ftpu_aot_status_t ftpu_aot_encode_container( + const ftpu_aot_cache_header_t *header, + const void *payload, + size_t payload_size, + const void *metadata, + size_t metadata_size, + uint8_t *out_buf, + size_t out_cap, + size_t *out_written) +{ + size_t compiler_len; + size_t profile_len; + size_t hdr_len; + size_t total_size; + ftpu_aot_status_t rc; + uint8_t *hdr_ptr; + size_t offset; + + if (header == NULL || out_buf == NULL || out_written == NULL) { + return FTPU_AOT_ERR_INVALID_ARG; + } + if ((payload == NULL && payload_size > 0U) || + (metadata == NULL && metadata_size > 0U)) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + compiler_len = + bounded_cstr_len(header->compiler_version, FTPU_AOT_MAX_VERSION_LEN); + profile_len = + bounded_cstr_len(header->target_profile, FTPU_AOT_MAX_PROFILE_LEN); + + if (!is_valid_utf8_label((const uint8_t *)header->compiler_version, + compiler_len, FTPU_AOT_MAX_VERSION_LEN) || + !is_valid_utf8_label((const uint8_t *)header->target_profile, + profile_len, FTPU_AOT_MAX_PROFILE_LEN)) { + return FTPU_AOT_ERR_MALFORMED_HEADER; + } + + rc = ftpu_aot_container_encoded_size(compiler_len, profile_len, + payload_size, metadata_size, + &total_size); + if (rc != FTPU_AOT_OK) { + return rc; + } + if (out_cap < total_size) { + return FTPU_AOT_ERR_BUFFER_TOO_SMALL; + } + + hdr_len = FTPU_AOT_HEADER_FIXED_SIZE + compiler_len + profile_len; + + /* [uint32_le hdr_len] */ + write_le32(out_buf, (uint32_t)hdr_len); + + /* [header_bytes] */ + hdr_ptr = out_buf + 4U; + write_le32(hdr_ptr + 0U, FTPU_AOT_CACHE_MAGIC); + write_le16(hdr_ptr + 4U, FTPU_AOT_CACHE_FORMAT_VERSION); + write_le16(hdr_ptr + 6U, (uint16_t)compiler_len); + write_le16(hdr_ptr + 8U, (uint16_t)profile_len); + write_le16(hdr_ptr + 10U, 0U); + memcpy(hdr_ptr + 12U, header->cache_key, FTPU_SHA256_DIGEST_SIZE); + write_le32(hdr_ptr + 44U, header->execution_preference); + write_le32(hdr_ptr + 48U, (uint32_t)header->priority); + write_le32(hdr_ptr + 52U, header->flags); + write_le64(hdr_ptr + 56U, (uint64_t)payload_size); + write_le64(hdr_ptr + 64U, (uint64_t)metadata_size); + memcpy(hdr_ptr + FTPU_AOT_HEADER_FIXED_SIZE, header->compiler_version, + compiler_len); + memcpy(hdr_ptr + FTPU_AOT_HEADER_FIXED_SIZE + compiler_len, + header->target_profile, profile_len); + + /* [payload_bytes] */ + offset = 4U + hdr_len; + if (payload_size > 0U) { + memcpy(out_buf + offset, payload, payload_size); + offset += payload_size; + } + + /* [metadata_bytes] */ + if (metadata_size > 0U) { + memcpy(out_buf + offset, metadata, metadata_size); + offset += metadata_size; + } + + *out_written = offset; + return FTPU_AOT_OK; +} + +ftpu_aot_status_t ftpu_aot_validate_container( + const void *container, + size_t container_size, + const ftpu_aot_cache_expectation_t *expectation, + ftpu_aot_container_view_t *out_view) +{ + const uint8_t *buf = (const uint8_t *)container; + const uint8_t *hdr_ptr; + uint32_t hdr_len; + uint32_t magic; + uint16_t format_version; + uint16_t compiler_len; + uint16_t profile_len; + uint16_t reserved; + uint64_t payload_u64; + uint64_t metadata_u64; + size_t remaining; + size_t payload_offset; + size_t metadata_offset; + ftpu_aot_container_view_t view; + + if (container == NULL || out_view == NULL) { + return FTPU_AOT_ERR_INVALID_ARG; + } + + if (container_size < 4U) { + return FTPU_AOT_ERR_TRUNCATED; + } + + hdr_len = read_le32(buf); + if (hdr_len < FTPU_AOT_HEADER_FIXED_SIZE || hdr_len > FTPU_AOT_MAX_HEADER_LEN) { + return FTPU_AOT_ERR_BOUNDS; + } + + if ((size_t)hdr_len > container_size - 4U) { + return FTPU_AOT_ERR_TRUNCATED; + } + + hdr_ptr = buf + 4U; + magic = read_le32(hdr_ptr + 0U); + if (magic != FTPU_AOT_CACHE_MAGIC) { + return FTPU_AOT_ERR_BAD_MAGIC; + } + + format_version = read_le16(hdr_ptr + 4U); + if (format_version != FTPU_AOT_CACHE_FORMAT_VERSION) { + return FTPU_AOT_ERR_UNSUPPORTED_VERSION; + } + + compiler_len = read_le16(hdr_ptr + 6U); + profile_len = read_le16(hdr_ptr + 8U); + reserved = read_le16(hdr_ptr + 10U); + if (reserved != 0U || compiler_len == 0U || + compiler_len > FTPU_AOT_MAX_VERSION_LEN || profile_len == 0U || + profile_len > FTPU_AOT_MAX_PROFILE_LEN) { + return FTPU_AOT_ERR_MALFORMED_HEADER; + } + if ((uint32_t)FTPU_AOT_HEADER_FIXED_SIZE + (uint32_t)compiler_len + + (uint32_t)profile_len != hdr_len) { + return FTPU_AOT_ERR_MALFORMED_HEADER; + } + if (!is_valid_utf8_label(hdr_ptr + FTPU_AOT_HEADER_FIXED_SIZE, + (size_t)compiler_len, FTPU_AOT_MAX_VERSION_LEN) || + !is_valid_utf8_label( + hdr_ptr + FTPU_AOT_HEADER_FIXED_SIZE + (size_t)compiler_len, + (size_t)profile_len, FTPU_AOT_MAX_PROFILE_LEN)) { + return FTPU_AOT_ERR_MALFORMED_HEADER; + } + + payload_u64 = read_le64(hdr_ptr + 56U); + metadata_u64 = read_le64(hdr_ptr + 64U); + if (payload_u64 > (uint64_t)SIZE_MAX || metadata_u64 > (uint64_t)SIZE_MAX) { + return FTPU_AOT_ERR_BOUNDS; + } + + remaining = container_size - 4U - (size_t)hdr_len; + if ((size_t)payload_u64 > remaining) { + return FTPU_AOT_ERR_TRUNCATED; + } + if ((size_t)metadata_u64 > remaining - (size_t)payload_u64) { + return FTPU_AOT_ERR_TRUNCATED; + } + if ((size_t)metadata_u64 < remaining - (size_t)payload_u64) { + return FTPU_AOT_ERR_BOUNDS; + } + + memset(&view, 0, sizeof(view)); + view.hdr_len = hdr_len; + view.header.magic = magic; + view.header.format_version = format_version; + view.header.compiler_version_len = compiler_len; + view.header.target_profile_len = profile_len; + view.header.reserved = reserved; + memcpy(view.header.compiler_version, hdr_ptr + FTPU_AOT_HEADER_FIXED_SIZE, + (size_t)compiler_len); + view.header.compiler_version[compiler_len] = '\0'; + memcpy(view.header.target_profile, + hdr_ptr + FTPU_AOT_HEADER_FIXED_SIZE + (size_t)compiler_len, + (size_t)profile_len); + view.header.target_profile[profile_len] = '\0'; + memcpy(view.header.cache_key, hdr_ptr + 12U, FTPU_SHA256_DIGEST_SIZE); + view.header.execution_preference = read_le32(hdr_ptr + 44U); + view.header.priority = (int32_t)read_le32(hdr_ptr + 48U); + view.header.flags = read_le32(hdr_ptr + 52U); + view.header.payload_size = payload_u64; + view.header.metadata_size = metadata_u64; + + payload_offset = 4U + (size_t)hdr_len; + metadata_offset = payload_offset + (size_t)payload_u64; + view.payload_offset = payload_offset; + view.payload_size = (size_t)payload_u64; + view.metadata_offset = metadata_offset; + view.metadata_size = (size_t)metadata_u64; + + if (expectation != NULL) { + if (expectation->expected_compiler_version != NULL) { + size_t exp_len = strlen(expectation->expected_compiler_version); + if (exp_len != (size_t)compiler_len || + memcmp(view.header.compiler_version, + expectation->expected_compiler_version, + (size_t)compiler_len) != 0) { + return FTPU_AOT_ERR_COMPILER_MISMATCH; + } + } + if (expectation->expected_target_profile != NULL) { + size_t exp_len = strlen(expectation->expected_target_profile); + if (exp_len != (size_t)profile_len || + memcmp(view.header.target_profile, + expectation->expected_target_profile, + (size_t)profile_len) != 0) { + return FTPU_AOT_ERR_PROFILE_MISMATCH; + } + } + if (expectation->expected_cache_key != NULL) { + if (!ftpu_aot_digest_equal(view.header.cache_key, + expectation->expected_cache_key)) { + return FTPU_AOT_ERR_KEY_MISMATCH; + } + } + if (expectation->check_execution_preference && + view.header.execution_preference != + expectation->expected_execution_preference) { + return FTPU_AOT_ERR_POLICY_MISMATCH; + } + if (expectation->check_priority && + view.header.priority != expectation->expected_priority) { + return FTPU_AOT_ERR_POLICY_MISMATCH; + } + if (expectation->check_flags && + view.header.flags != expectation->expected_flags) { + return FTPU_AOT_ERR_POLICY_MISMATCH; + } + } + + *out_view = view; + return FTPU_AOT_OK; +} diff --git a/aot-guard/src/sha256.c b/aot-guard/src/sha256.c new file mode 100644 index 0000000..514e0e5 --- /dev/null +++ b/aot-guard/src/sha256.c @@ -0,0 +1,241 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "freetpu/aot_cache_guard.h" + +#include + +static uint32_t load_be32(const uint8_t *p) +{ + return ((uint32_t)p[0] << 24) | + ((uint32_t)p[1] << 16) | + ((uint32_t)p[2] << 8) | + (uint32_t)p[3]; +} + +static void store_be32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +static void store_be64(uint8_t *p, uint64_t v) +{ + p[0] = (uint8_t)(v >> 56); + p[1] = (uint8_t)(v >> 48); + p[2] = (uint8_t)(v >> 40); + p[3] = (uint8_t)(v >> 32); + p[4] = (uint8_t)(v >> 24); + p[5] = (uint8_t)(v >> 16); + p[6] = (uint8_t)(v >> 8); + p[7] = (uint8_t)v; +} + +static uint32_t rotr32(uint32_t x, uint32_t n) +{ + return (x >> n) | (x << (32U - n)); +} + +static void sha256_compress(uint32_t state[8], const uint8_t block[64]) +{ + static const uint32_t k[64] = { + 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, + 0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U, + 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, + 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, + 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, + 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, + 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, + 0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U, + 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U, + 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, + 0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U, + 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, + 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, + 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U, + 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, + 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U + }; + + uint32_t w[64]; + size_t i; + + for (i = 0U; i < 16U; ++i) { + w[i] = load_be32(block + (i * 4U)); + } + for (i = 16U; i < 64U; ++i) { + uint32_t s0 = rotr32(w[i - 15U], 7U) ^ rotr32(w[i - 15U], 18U) ^ + (w[i - 15U] >> 3); + uint32_t s1 = rotr32(w[i - 2U], 17U) ^ rotr32(w[i - 2U], 19U) ^ + (w[i - 2U] >> 10); + w[i] = w[i - 16U] + s0 + w[i - 7U] + s1; + } + + uint32_t a = state[0]; + uint32_t b = state[1]; + uint32_t c = state[2]; + uint32_t d = state[3]; + uint32_t e = state[4]; + uint32_t f = state[5]; + uint32_t g = state[6]; + uint32_t h = state[7]; + + for (i = 0U; i < 64U; ++i) { + uint32_t S1 = rotr32(e, 6U) ^ rotr32(e, 11U) ^ rotr32(e, 25U); + uint32_t ch = (e & f) ^ ((~e) & g); + uint32_t temp1 = h + S1 + ch + k[i] + w[i]; + uint32_t S0 = rotr32(a, 2U) ^ rotr32(a, 13U) ^ rotr32(a, 22U); + uint32_t maj = (a & b) ^ (a & c) ^ (b & c); + uint32_t temp2 = S0 + maj; + + h = g; + g = f; + f = e; + e = d + temp1; + d = c; + c = b; + b = a; + a = temp1 + temp2; + } + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + state[5] += f; + state[6] += g; + state[7] += h; +} + +static void secure_zero(void *ptr, size_t len) +{ + volatile uint8_t *p = (volatile uint8_t *)ptr; + size_t i; + for (i = 0U; i < len; ++i) { + p[i] = 0U; + } +} + +void ftpu_sha256_init(ftpu_sha256_ctx_t *ctx) +{ + if (ctx == NULL) { + return; + } + ctx->state[0] = 0x6a09e667U; + ctx->state[1] = 0xbb67ae85U; + ctx->state[2] = 0x3c6ef372U; + ctx->state[3] = 0xa54ff53aU; + ctx->state[4] = 0x510e527fU; + ctx->state[5] = 0x9b05688cU; + ctx->state[6] = 0x1f83d9abU; + ctx->state[7] = 0x5be0cd19U; + ctx->total_bytes = 0U; + ctx->buf_len = 0U; + memset(ctx->buffer, 0, sizeof(ctx->buffer)); +} + +void ftpu_sha256_update(ftpu_sha256_ctx_t *ctx, const void *data, size_t len) +{ + const uint8_t *bytes = (const uint8_t *)data; + size_t offset = 0U; + + if (ctx == NULL || len == 0U || bytes == NULL) { + return; + } + + ctx->total_bytes += (uint64_t)len; + + if (ctx->buf_len > 0U) { + size_t need = 64U - ctx->buf_len; + if (len < need) { + memcpy(ctx->buffer + ctx->buf_len, bytes, len); + ctx->buf_len += len; + return; + } + memcpy(ctx->buffer + ctx->buf_len, bytes, need); + sha256_compress(ctx->state, ctx->buffer); + ctx->buf_len = 0U; + offset += need; + } + + while (offset + 64U <= len) { + sha256_compress(ctx->state, bytes + offset); + offset += 64U; + } + + if (offset < len) { + size_t rem = len - offset; + memcpy(ctx->buffer, bytes + offset, rem); + ctx->buf_len = rem; + } +} + +void ftpu_sha256_final(ftpu_sha256_ctx_t *ctx, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]) +{ + uint64_t total_bits; + size_t i; + + if (ctx == NULL || out_digest == NULL) { + return; + } + + total_bits = ctx->total_bytes << 3; + ctx->buffer[ctx->buf_len++] = 0x80U; + + if (ctx->buf_len > 56U) { + while (ctx->buf_len < 64U) { + ctx->buffer[ctx->buf_len++] = 0x00U; + } + sha256_compress(ctx->state, ctx->buffer); + ctx->buf_len = 0U; + } + + while (ctx->buf_len < 56U) { + ctx->buffer[ctx->buf_len++] = 0x00U; + } + + store_be64(ctx->buffer + 56U, total_bits); + sha256_compress(ctx->state, ctx->buffer); + + for (i = 0U; i < 8U; ++i) { + store_be32(out_digest + (i * 4U), ctx->state[i]); + } + + secure_zero(ctx, sizeof(*ctx)); +} + +void ftpu_sha256_hash(const void *data, + size_t len, + uint8_t out_digest[FTPU_SHA256_DIGEST_SIZE]) +{ + ftpu_sha256_ctx_t ctx; + if (out_digest == NULL) { + return; + } + ftpu_sha256_init(&ctx); + ftpu_sha256_update(&ctx, data, len); + ftpu_sha256_final(&ctx, out_digest); +} + +void ftpu_sha256_hex(const uint8_t digest[FTPU_SHA256_DIGEST_SIZE], + char out_hex[FTPU_SHA256_HEX_SIZE]) +{ + static const char hex_digits[] = "0123456789abcdef"; + size_t i; + + if (digest == NULL || out_hex == NULL) { + return; + } + + for (i = 0U; i < FTPU_SHA256_DIGEST_SIZE; ++i) { + out_hex[i * 2U] = hex_digits[(digest[i] >> 4) & 0x0FU]; + out_hex[(i * 2U) + 1U] = hex_digits[digest[i] & 0x0FU]; + } + out_hex[FTPU_SHA256_HEX_SIZE - 1U] = '\0'; +} diff --git a/aot-guard/src/sram_partitioner.c b/aot-guard/src/sram_partitioner.c new file mode 100644 index 0000000..a1afa37 --- /dev/null +++ b/aot-guard/src/sram_partitioner.c @@ -0,0 +1,319 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "freetpu/sram_partitioner.h" + +#include + +size_t ftpu_dtype_byte_width(ftpu_dtype_t dtype) +{ + switch (dtype) { + case FTPU_DTYPE_UINT8: + case FTPU_DTYPE_INT8: + case FTPU_DTYPE_BOOL: + return 1U; + case FTPU_DTYPE_INT16: + case FTPU_DTYPE_FP16: + case FTPU_DTYPE_BF16: + return 2U; + case FTPU_DTYPE_INT32: + case FTPU_DTYPE_FP32: + return 4U; + case FTPU_DTYPE_INT64: + case FTPU_DTYPE_FP64: + return 8U; + default: + return 0U; + } +} + +const char *ftpu_target_backend_name(ftpu_target_backend_t backend) +{ + switch (backend) { + case FTPU_TARGET_EDGETPU: + return "EdgeTPU"; + case FTPU_TARGET_CPU_SME2: + return "CPU/SME2"; + case FTPU_TARGET_CPU_NEON: + return "CPU/NEON"; + default: + return "UNKNOWN"; + } +} + +const char *ftpu_sram_status_str(ftpu_sram_status_t status) +{ + switch (status) { + case FTPU_SRAM_OK: + return "OK"; + case FTPU_SRAM_ERR_INVALID_ARG: + return "INVALID_ARG"; + case FTPU_SRAM_ERR_OVERFLOW: + return "OVERFLOW"; + case FTPU_SRAM_ERR_BUFFER_TOO_SMALL: + return "BUFFER_TOO_SMALL"; + default: + return "UNKNOWN"; + } +} + +ftpu_partition_config_t ftpu_partition_config_default(bool has_sme2) +{ + ftpu_partition_config_t cfg; + cfg.sram_budget_bytes = FTPU_DEFAULT_SRAM_BUDGET_BYTES; + cfg.has_sme2 = has_sme2; + cfg.peel_tail_cascades = true; + return cfg; +} + +ftpu_sram_status_t ftpu_tensor_byte_size(const ftpu_tensor_desc_t *tensor, + uint64_t *out_bytes) +{ + size_t width; + uint64_t elements = 1U; + uint32_t i; + + if (tensor == NULL || out_bytes == NULL) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + if (tensor->rank > FTPU_MAX_TENSOR_DIMS) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + + width = ftpu_dtype_byte_width(tensor->dtype); + if (width == 0U) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + + for (i = 0U; i < tensor->rank; ++i) { + uint64_t d = tensor->dims[i]; + if (d == 0U) { + *out_bytes = 0U; + return FTPU_SRAM_OK; + } + if (elements > UINT64_MAX / d) { + return FTPU_SRAM_ERR_OVERFLOW; + } + elements *= d; + } + + if (elements > UINT64_MAX / (uint64_t)width) { + return FTPU_SRAM_ERR_OVERFLOW; + } + + *out_bytes = elements * (uint64_t)width; + return FTPU_SRAM_OK; +} + +static ftpu_sram_status_t add_u64_checked(uint64_t a, uint64_t b, uint64_t *out) +{ + if (a > UINT64_MAX - b) { + return FTPU_SRAM_ERR_OVERFLOW; + } + *out = a + b; + return FTPU_SRAM_OK; +} + +ftpu_sram_status_t ftpu_op_working_set_bytes(const ftpu_op_desc_t *op, + uint64_t *out_working_set_bytes, + uint64_t *out_max_output_bytes) +{ + uint64_t total = 0U; + uint64_t max_out = 0U; + size_t i; + ftpu_sram_status_t rc; + + if (op == NULL || out_working_set_bytes == NULL) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + if ((op->inputs == NULL && op->num_inputs > 0U) || + (op->outputs == NULL && op->num_outputs > 0U)) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + + for (i = 0U; i < op->num_inputs; ++i) { + uint64_t sz = 0U; + rc = ftpu_tensor_byte_size(&op->inputs[i], &sz); + if (rc != FTPU_SRAM_OK) { + return rc; + } + rc = add_u64_checked(total, sz, &total); + if (rc != FTPU_SRAM_OK) { + return rc; + } + } + + for (i = 0U; i < op->num_outputs; ++i) { + uint64_t sz = 0U; + rc = ftpu_tensor_byte_size(&op->outputs[i], &sz); + if (rc != FTPU_SRAM_OK) { + return rc; + } + if (sz > max_out) { + max_out = sz; + } + rc = add_u64_checked(total, sz, &total); + if (rc != FTPU_SRAM_OK) { + return rc; + } + } + + *out_working_set_bytes = total; + if (out_max_output_bytes != NULL) { + *out_max_output_bytes = max_out; + } + return FTPU_SRAM_OK; +} + +static bool is_tail_cascade_op(ftpu_op_kind_t kind) +{ + return kind == FTPU_OP_CONCATENATION || kind == FTPU_OP_LOGISTIC; +} + +ftpu_sram_status_t ftpu_partition_graph(const ftpu_op_desc_t *ops, + size_t num_ops, + const ftpu_partition_config_t *config, + ftpu_partition_plan_t *out_plan, + ftpu_target_backend_t *out_op_targets, + size_t out_op_targets_len) +{ + ftpu_partition_config_t eff_cfg; + ftpu_target_backend_t cpu_backend; + ftpu_partition_plan_t plan; + size_t i; + size_t start_op = 0U; + size_t cut_op; + size_t trigger_op = SIZE_MAX; + uint64_t trigger_bytes = 0U; + uint64_t peak_delegated = 0U; + ftpu_cut_reason_t cut_reason = FTPU_CUT_NONE; + + if (out_plan == NULL) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + if (ops == NULL && num_ops > 0U) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + if (num_ops > (size_t)UINT32_MAX) { + return FTPU_SRAM_ERR_INVALID_ARG; + } + if (out_op_targets != NULL && out_op_targets_len < num_ops) { + return FTPU_SRAM_ERR_BUFFER_TOO_SMALL; + } + + if (config != NULL) { + eff_cfg = *config; + if (eff_cfg.sram_budget_bytes == 0U) { + eff_cfg.sram_budget_bytes = FTPU_DEFAULT_SRAM_BUDGET_BYTES; + } + } else { + eff_cfg = ftpu_partition_config_default(false); + } + + cpu_backend = + eff_cfg.has_sme2 ? FTPU_TARGET_CPU_SME2 : FTPU_TARGET_CPU_NEON; + + memset(&plan, 0, sizeof(plan)); + plan.total_ops = (uint32_t)num_ops; + plan.tail_backend = cpu_backend; + plan.trigger_op_index = UINT32_MAX; + plan.effective_budget_bytes = eff_cfg.sram_budget_bytes; + + if (num_ops == 0U) { + *out_plan = plan; + return FTPU_SRAM_OK; + } + + /* Validate all operator footprints upfront (fail closed on overflow). */ + for (i = 0U; i < num_ops; ++i) { + uint64_t ws = 0U; + uint64_t max_out = 0U; + ftpu_sram_status_t rc = ftpu_op_working_set_bytes(&ops[i], &ws, &max_out); + if (rc != FTPU_SRAM_OK) { + return rc; + } + } + + /* Skip leading CPU-only ops (e.g. input QUANTIZE when unsupported). */ + while (start_op < num_ops && + (!ops[start_op].hal_supported || + ops[start_op].kind == FTPU_OP_DETECTION_POSTPROCESS)) { + ++start_op; + } + + cut_op = start_op; + while (cut_op < num_ops) { + uint64_t ws = 0U; + uint64_t max_out = 0U; + (void)ftpu_op_working_set_bytes(&ops[cut_op], &ws, &max_out); + + if (!ops[cut_op].hal_supported || + ops[cut_op].kind == FTPU_OP_DETECTION_POSTPROCESS) { + cut_reason = FTPU_CUT_UNSUPPORTED_OP; + trigger_op = cut_op; + trigger_bytes = ws; + break; + } + + /* Enforce strict < sram_budget_bytes working-set invariant. */ + if (ws >= eff_cfg.sram_budget_bytes) { + cut_reason = FTPU_CUT_SRAM_EXCEEDED; + trigger_op = cut_op; + trigger_bytes = ws; + break; + } + + ++cut_op; + } + + /* + * When an oversize FP32 tail op (e.g. [1, 19206, 90] DEQUANTIZE) exceeds + * the SRAM budget, peel back any immediately preceding wide tail + * CONCATENATION / LOGISTIC cascade into the CPU tail subgraph so the + * EdgeTPU prefix terminates cleanly before the tail cascade. + */ + if (cut_reason == FTPU_CUT_SRAM_EXCEEDED && eff_cfg.peel_tail_cascades) { + size_t peeled = cut_op; + while (peeled > start_op && is_tail_cascade_op(ops[peeled - 1U].kind)) { + --peeled; + } + if (peeled < cut_op) { + cut_op = peeled; + cut_reason = FTPU_CUT_TAIL_CASCADE_BEFORE_SRAM; + } + } + + for (i = start_op; i < cut_op; ++i) { + uint64_t ws = 0U; + (void)ftpu_op_working_set_bytes(&ops[i], &ws, NULL); + if (ws > peak_delegated) { + peak_delegated = ws; + } + } + + if (out_op_targets != NULL) { + for (i = 0U; i < num_ops; ++i) { + if (i >= start_op && i < cut_op) { + out_op_targets[i] = FTPU_TARGET_EDGETPU; + } else { + out_op_targets[i] = cpu_backend; + } + } + } + + plan.edgetpu_start_op = (uint32_t)start_op; + plan.edgetpu_end_op_exclusive = (uint32_t)cut_op; + plan.delegated_op_count = (uint32_t)(cut_op - start_op); + plan.tail_start_op = (uint32_t)cut_op; + plan.tail_backend = cpu_backend; + plan.trigger_op_index = + (trigger_op == SIZE_MAX) ? UINT32_MAX : (uint32_t)trigger_op; + plan.trigger_op_bytes = trigger_bytes; + plan.peak_delegated_working_set_bytes = peak_delegated; + plan.reason = cut_reason; + + *out_plan = plan; + return FTPU_SRAM_OK; +} diff --git a/aot-guard/tests/test_aot_guard.cpp b/aot-guard/tests/test_aot_guard.cpp new file mode 100644 index 0000000..a230ebd --- /dev/null +++ b/aot-guard/tests/test_aot_guard.cpp @@ -0,0 +1,872 @@ +/* + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "freetpu/aot_guard.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int g_tests_run = 0; +int g_tests_failed = 0; + +#define CHECK(expr) \ + do { \ + if (!(expr)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #expr); \ + return false; \ + } \ + } while (0) + +#define RUN_TEST(fn) \ + do { \ + ++g_tests_run; \ + if ((fn)()) { \ + std::printf("[PASS] %s\n", #fn); \ + } else { \ + ++g_tests_failed; \ + std::printf("[FAIL] %s\n", #fn); \ + } \ + } while (0) + +bool test_sha256_nist_vectors() { + struct Vector { + const char* input; + const char* expected_hex; + }; + const Vector vectors[] = { + {"", + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, + {"abc", + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}, + {"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"}, + }; + + for (const auto& vec : vectors) { + std::string input_str(vec.input); + uint8_t digest[FTPU_SHA256_DIGEST_SIZE]{}; + char hex[FTPU_SHA256_HEX_SIZE]{}; + ftpu_sha256_hash(input_str.data(), input_str.size(), digest); + ftpu_sha256_hex(digest, hex); + CHECK(std::strcmp(hex, vec.expected_hex) == 0); + + // Verify byte-by-byte streaming and C++17 RAII wrapper match. + freetpu::Sha256Hasher hasher; + for (char ch : input_str) { + const auto b = static_cast(ch); + hasher.update(freetpu::Span(&b, 1U)); + } + freetpu::Digest cpp_digest = hasher.finalize(); + CHECK(freetpu::Sha256Hasher::to_hex(cpp_digest) == vec.expected_hex); + CHECK(ftpu_aot_digest_equal(digest, cpp_digest.data())); + } + + // Verify irregular chunking across 64-byte block boundaries. + const std::string two_blocks = + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; + freetpu::Sha256Hasher chunked; + chunked.update(std::string_view(two_blocks).substr(0U, 13U)); + chunked.update(std::string_view(two_blocks).substr(13U, 42U)); + chunked.update(std::string_view(two_blocks).substr(55U)); + CHECK(freetpu::Sha256Hasher::to_hex(chunked.finalize()) == + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); + return true; +} + +bool test_5input_cache_key_prevents_false_hits() { + std::vector graph(512U); + for (std::size_t i = 0U; i < graph.size(); ++i) { + graph[i] = static_cast((i * 17U) ^ 0x5AU); + } + + std::vector weights(4096U); + for (std::size_t i = 0U; i < weights.size(); ++i) { + weights[i] = static_cast((i * 37U) ^ 0xA5U); + } + + const std::string compiler_v4 = "edgetpu-compiler-2026.05.11-0.4"; + const std::string compiler_v5 = "edgetpu-compiler-2026.05.11-0.5"; + const std::string profile_g6 = "tensor-g6-v1"; + const std::string profile_g6_rev2 = "tensor-g6-v2"; + + freetpu::CompileOptions opts_base{}; + opts_base.execution_preference = 2U; + opts_base.priority = 100; + opts_base.flags = 0x01U; + opts_base.extra_options = "sram_limit_mib=4"; + + auto key_base = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6, opts_base); + CHECK(key_base.ok()); + + // Deterministic repeatability via both convenience and explicit 5-input spec. + auto g_dig = freetpu::AotCacheGuard::digest_graph(graph); + auto w_dig = freetpu::AotCacheGuard::digest_weights(weights); + auto b_dig = freetpu::AotCacheGuard::digest_bytes(weights); + CHECK(g_dig.ok() && w_dig.ok() && b_dig.ok()); + CHECK(freetpu::AotCacheGuard::digests_equal(w_dig.value, b_dig.value)); + + freetpu::AotCacheKeySpec spec{}; + spec.graph_digest = g_dig.value; + spec.weights_digest = w_dig.value; + spec.compiler_version = compiler_v4; + spec.target_profile = profile_g6; + spec.compile_options = opts_base; + auto key_from_spec = freetpu::AotCacheGuard::compute_key(spec); + CHECK(key_from_spec.ok()); + CHECK(freetpu::AotCacheGuard::digests_equal(key_base.value, + key_from_spec.value)); + + // 1. Mutating graph[0] ^= 1 must produce a distinct key. + std::vector mutated_graph = graph; + mutated_graph[0] ^= 0x01U; + auto key_graph = freetpu::AotCacheGuard::compute_key_from_buffers( + mutated_graph, weights, compiler_v4, profile_g6, opts_base); + CHECK(key_graph.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_graph.value)); + + // 2. Mutating weights[0] ^= 1 must produce a distinct key. + std::vector mutated_weights = weights; + mutated_weights[0] ^= 0x01U; + auto key_weights = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, mutated_weights, compiler_v4, profile_g6, opts_base); + CHECK(key_weights.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_weights.value)); + + // 3. Changing compiler_version must isolate the key. + auto key_compiler = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v5, profile_g6, opts_base); + CHECK(key_compiler.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_compiler.value)); + + // 4. Changing target_profile must isolate the key. + auto key_profile = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6_rev2, opts_base); + CHECK(key_profile.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_profile.value)); + + // 5a. Changing compile_options.execution_preference must isolate the key. + freetpu::CompileOptions opts_pref = opts_base; + opts_pref.execution_preference = 0U; + auto key_pref = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6, opts_pref); + CHECK(key_pref.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_pref.value)); + + // 5b. Changing compile_options.priority must isolate the key. + freetpu::CompileOptions opts_prio = opts_base; + opts_prio.priority = 110; + auto key_prio = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6, opts_prio); + CHECK(key_prio.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_prio.value)); + + // 5c. Changing compile_options.flags must isolate the key. + freetpu::CompileOptions opts_flags = opts_base; + opts_flags.flags = 0x02U; + auto key_flags = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6, opts_flags); + CHECK(key_flags.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_flags.value)); + + // 5d. Changing compile_options.extra_options must isolate the key. + freetpu::CompileOptions opts_extra = opts_base; + opts_extra.extra_options = "sram_limit_mib=2"; + auto key_extra = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6, opts_extra); + CHECK(key_extra.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_extra.value)); + + // Swapping graph and weights digests must produce a distinct key. + freetpu::AotCacheKeySpec swapped_spec = spec; + swapped_spec.graph_digest = w_dig.value; + swapped_spec.weights_digest = g_dig.value; + auto key_swapped = freetpu::AotCacheGuard::compute_key(swapped_spec); + CHECK(key_swapped.ok()); + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, + key_swapped.value)); + + // Empty compiler_version or target_profile must fail closed. + auto empty_ver = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, "", profile_g6, opts_base); + CHECK(empty_ver.status == FTPU_AOT_ERR_INVALID_ARG); + auto empty_prof = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, "", opts_base); + CHECK(empty_prof.status == FTPU_AOT_ERR_INVALID_ARG); + + // NULL vs "" extra_options canonicalize identically. + freetpu::CompileOptions opts_null = opts_base; + opts_null.extra_options.clear(); + auto key_empty_extra = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_v4, profile_g6, opts_null); + CHECK(key_empty_extra.ok()); + uint8_t c_key[FTPU_SHA256_DIGEST_SIZE]{}; + ftpu_aot_compile_options_t c_opts{}; + c_opts.execution_preference = opts_base.execution_preference; + c_opts.priority = opts_base.priority; + c_opts.flags = opts_base.flags; + c_opts.extra_options = nullptr; + CHECK(ftpu_aot_compute_cache_key_from_buffers( + graph.data(), graph.size(), weights.data(), weights.size(), + compiler_v4.c_str(), profile_g6.c_str(), &c_opts, c_key) == + FTPU_AOT_OK); + CHECK(ftpu_aot_digest_equal(key_empty_extra.value.data(), c_key)); + + // Constant-time comparison checks NULL safety and trailing-byte diffs. + CHECK(!ftpu_aot_digest_equal(nullptr, key_base.value.data())); + CHECK(!ftpu_aot_digest_equal(key_base.value.data(), nullptr)); + freetpu::Digest tail_flip = key_base.value; + tail_flip[FTPU_SHA256_DIGEST_SIZE - 1U] ^= 0x01U; + CHECK(!freetpu::AotCacheGuard::digests_equal(key_base.value, tail_flip)); + + // Invalid C-API arguments fail cleanly. + uint8_t dummy[FTPU_SHA256_DIGEST_SIZE]{}; + CHECK(ftpu_aot_digest_bytes(nullptr, 16U, dummy) == + FTPU_AOT_ERR_INVALID_ARG); + CHECK(ftpu_aot_digest_weights(nullptr, 16U, dummy) == + FTPU_AOT_ERR_INVALID_ARG); + CHECK(ftpu_aot_digest_graph(nullptr, 16U, dummy) == + FTPU_AOT_ERR_INVALID_ARG); + CHECK(ftpu_aot_compute_cache_key_from_buffers( + graph.data(), graph.size(), weights.data(), weights.size(), + nullptr, profile_g6.c_str(), &c_opts, dummy) == + FTPU_AOT_ERR_INVALID_ARG); + CHECK(ftpu_aot_compute_cache_key_from_buffers( + graph.data(), graph.size(), weights.data(), weights.size(), + compiler_v4.c_str(), nullptr, &c_opts, dummy) == + FTPU_AOT_ERR_INVALID_ARG); + return true; +} + +bool test_container_envelope_validation() { + const std::vector graph = {0x01U, 0x02U, 0x03U, 0x04U}; + const std::vector weights = {0x10U, 0x20U, 0x30U, 0x40U}; + const std::string compiler = "edgetpu-compiler-2026.05.11-0.5"; + const std::string profile = "tensor-g6-v1"; + freetpu::CompileOptions opts{}; + opts.execution_preference = 2U; + opts.priority = 100; + opts.flags = 0x05U; + + auto key = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler, profile, opts); + CHECK(key.ok()); + + const std::vector payload = {0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02}; + const std::vector metadata = {0xAA, 0xBB, 0xCC}; + + auto encoded = freetpu::AotCacheGuard::encode_container( + compiler, profile, key.value, opts, payload, metadata); + CHECK(encoded.ok()); + CHECK(encoded.bytes.size() == + 4U + FTPU_AOT_HEADER_FIXED_SIZE + compiler.size() + profile.size() + + payload.size() + metadata.size()); + + // Valid round-trip with strict runtime expectations. + auto view = freetpu::AotCacheGuard::validate_container( + encoded.bytes, compiler, profile, key.value, opts.execution_preference, + opts.priority, opts.flags); + CHECK(view.ok()); + CHECK(view.compiler_version == compiler); + CHECK(view.target_profile == profile); + CHECK(freetpu::AotCacheGuard::digests_equal(view.cache_key, key.value)); + CHECK(view.execution_preference == opts.execution_preference); + CHECK(view.priority == opts.priority); + CHECK(view.flags == opts.flags); + CHECK(view.payload.size() == payload.size()); + CHECK(std::memcmp(view.payload.data(), payload.data(), payload.size()) == + 0); + CHECK(view.metadata.size() == metadata.size()); + CHECK(std::memcmp(view.metadata.data(), metadata.data(), metadata.size()) == + 0); + + // Compiler version mismatch caught. + auto ver_mismatch = freetpu::AotCacheGuard::validate_container( + encoded.bytes, std::string("edgetpu-compiler-2026.05.11-0.4"), profile, + key.value, opts.execution_preference, opts.priority, opts.flags); + CHECK(ver_mismatch.status == FTPU_AOT_ERR_COMPILER_MISMATCH); + + // Target profile mismatch caught. + auto prof_mismatch = freetpu::AotCacheGuard::validate_container( + encoded.bytes, compiler, std::string("tensor-g6-v2"), key.value, + opts.execution_preference, opts.priority, opts.flags); + CHECK(prof_mismatch.status == FTPU_AOT_ERR_PROFILE_MISMATCH); + + // Cache key mismatch caught. + freetpu::Digest bad_key = key.value; + bad_key[0] ^= 0x80U; + auto key_mismatch = freetpu::AotCacheGuard::validate_container( + encoded.bytes, compiler, profile, bad_key, opts.execution_preference, + opts.priority, opts.flags); + CHECK(key_mismatch.status == FTPU_AOT_ERR_KEY_MISMATCH); + + // Preference / priority / flags mismatch caught. + CHECK(freetpu::AotCacheGuard::validate_container( + encoded.bytes, compiler, profile, key.value, 0U, opts.priority, + opts.flags) + .status == FTPU_AOT_ERR_POLICY_MISMATCH); + CHECK(freetpu::AotCacheGuard::validate_container( + encoded.bytes, compiler, profile, key.value, + opts.execution_preference, 110, opts.flags) + .status == FTPU_AOT_ERR_POLICY_MISMATCH); + CHECK(freetpu::AotCacheGuard::validate_container( + encoded.bytes, compiler, profile, key.value, + opts.execution_preference, opts.priority, 0x09U) + .status == FTPU_AOT_ERR_POLICY_MISMATCH); + + // Truncated container at header / payload / metadata boundaries. + for (std::size_t trunc : {std::size_t{2U}, std::size_t{10U}, + encoded.bytes.size() - 1U}) { + auto res = freetpu::AotCacheGuard::validate_container( + freetpu::Span(encoded.bytes.data(), trunc)); + CHECK(res.status == FTPU_AOT_ERR_TRUNCATED); + } + + // Trailing unparsed bytes rejected. + std::vector with_trailing = encoded.bytes; + with_trailing.push_back(0x00U); + CHECK(freetpu::AotCacheGuard::validate_container(with_trailing).status == + FTPU_AOT_ERR_BOUNDS); + + // Corrupted magic byte rejected. + std::vector bad_magic = encoded.bytes; + bad_magic[4] ^= 0x01U; + CHECK(freetpu::AotCacheGuard::validate_container(bad_magic).status == + FTPU_AOT_ERR_BAD_MAGIC); + + // Unsupported format version rejected. + std::vector bad_ver = encoded.bytes; + bad_ver[8] = 0x09U; + CHECK(freetpu::AotCacheGuard::validate_container(bad_ver).status == + FTPU_AOT_ERR_UNSUPPORTED_VERSION); + + // Non-zero reserved header field rejected. + std::vector bad_reserved = encoded.bytes; + bad_reserved[4U + 10U] = 0x01U; + CHECK(freetpu::AotCacheGuard::validate_container(bad_reserved).status == + FTPU_AOT_ERR_MALFORMED_HEADER); + + // Embedded control byte inside compiler_version or target_profile rejected. + std::vector bad_compiler = encoded.bytes; + bad_compiler[4U + FTPU_AOT_HEADER_FIXED_SIZE] = '\n'; + CHECK(freetpu::AotCacheGuard::validate_container(bad_compiler).status == + FTPU_AOT_ERR_MALFORMED_HEADER); + + std::vector bad_profile = encoded.bytes; + bad_profile[4U + FTPU_AOT_HEADER_FIXED_SIZE + compiler.size()] = '\r'; + CHECK(freetpu::AotCacheGuard::validate_container(bad_profile).status == + FTPU_AOT_ERR_MALFORMED_HEADER); + + // Out-of-range hdr_len rejected. + std::vector bad_hdr_len = encoded.bytes; + bad_hdr_len[0] = 16U; + bad_hdr_len[1] = 0U; + bad_hdr_len[2] = 0U; + bad_hdr_len[3] = 0U; + CHECK(freetpu::AotCacheGuard::validate_container(bad_hdr_len).status == + FTPU_AOT_ERR_BOUNDS); + + // Buffer-too-small guard in C encode API. + ftpu_aot_cache_header_t c_hdr{}; + std::memcpy(c_hdr.compiler_version, compiler.data(), compiler.size()); + std::memcpy(c_hdr.target_profile, profile.data(), profile.size()); + std::memcpy(c_hdr.cache_key, key.value.data(), FTPU_SHA256_DIGEST_SIZE); + uint8_t tiny[8]{}; + size_t written = 0U; + CHECK(ftpu_aot_encode_container(&c_hdr, payload.data(), payload.size(), + metadata.data(), metadata.size(), tiny, + sizeof(tiny), &written) == + FTPU_AOT_ERR_BUFFER_TOO_SMALL); + return true; +} + +class MockAotCompilerStore { +public: + static constexpr double kColdCompileUs = 532.0; + static constexpr double kWarmCacheLoadUs = 20.0; + + struct CompileOutcome { + bool ok = false; + bool cache_hit = false; + freetpu::Digest cache_key{}; + freetpu::Digest payload_digest{}; + std::vector payload; + double modeled_latency_us = 0.0; + double measured_wall_us = 0.0; + }; + + CompileOutcome compile_or_load(freetpu::Span graph, + freetpu::Span weights, + const std::string& compiler_version, + const std::string& target_profile, + const freetpu::CompileOptions& options) { + using Clock = std::chrono::steady_clock; + const auto t0 = Clock::now(); + CompileOutcome out{}; + + auto key_res = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, weights, compiler_version, target_profile, options); + if (!key_res.ok()) { + return out; + } + out.cache_key = key_res.value; + const std::string key_hex = freetpu::Sha256Hasher::to_hex(out.cache_key); + + auto it = store_.find(key_hex); + if (it != store_.end()) { + auto view = freetpu::AotCacheGuard::validate_container( + it->second, compiler_version, target_profile, out.cache_key, + options.execution_preference, options.priority, options.flags); + if (view.ok()) { + out.ok = true; + out.cache_hit = true; + out.payload.assign(view.payload.begin(), view.payload.end()); + out.payload_digest = freetpu::Sha256Hasher::hash(out.payload); + out.modeled_latency_us = kWarmCacheLoadUs; + ++hit_count_; + const auto t1 = Clock::now(); + out.measured_wall_us = + std::chrono::duration(t1 - t0).count(); + return out; + } + // Invalid/corrupted entry triggers clean recompile. + store_.erase(it); + } + + ++miss_count_; + ++compile_count_; + + // Deterministic mock compiled executable payload bound to all 5 inputs. + freetpu::Sha256Hasher payload_hasher; + payload_hasher.update("FREETPU_COMPILED_EXECUTABLE_V2"); + payload_hasher.update(out.cache_key); + payload_hasher.update(graph); + payload_hasher.update(weights); + const freetpu::Digest body_dig = payload_hasher.finalize(); + + out.payload.resize(256U); + for (std::size_t i = 0U; i < out.payload.size(); ++i) { + out.payload[i] = static_cast( + body_dig[i % FTPU_SHA256_DIGEST_SIZE] ^ + static_cast(i * 13U)); + } + out.payload_digest = freetpu::Sha256Hasher::hash(out.payload); + + const std::string meta_str = + compiler_version + "|" + target_profile + "|" + key_hex; + auto encoded = freetpu::AotCacheGuard::encode_container( + compiler_version, target_profile, out.cache_key, options, + out.payload, freetpu::as_bytes(meta_str)); + if (!encoded.ok()) { + return out; + } + store_[key_hex] = encoded.bytes; + + out.ok = true; + out.cache_hit = false; + out.modeled_latency_us = kColdCompileUs; + const auto t1 = Clock::now(); + out.measured_wall_us = + std::chrono::duration(t1 - t0).count(); + return out; + } + + void inject_raw(const freetpu::Digest& key, + std::vector container_bytes) { + store_[freetpu::Sha256Hasher::to_hex(key)] = std::move(container_bytes); + } + + std::size_t compile_count() const noexcept { return compile_count_; } + std::size_t hit_count() const noexcept { return hit_count_; } + std::size_t miss_count() const noexcept { return miss_count_; } + std::size_t entry_count() const noexcept { return store_.size(); } + +private: + std::unordered_map> store_; + std::size_t compile_count_ = 0U; + std::size_t hit_count_ = 0U; + std::size_t miss_count_ = 0U; +}; + +bool test_warm_hit_speedup_and_changed_weight_miss() { + std::vector graph(1024U); + for (std::size_t i = 0U; i < graph.size(); ++i) { + graph[i] = static_cast((i * 29U) ^ 0x33U); + } + std::vector weights(8192U); + for (std::size_t i = 0U; i < weights.size(); ++i) { + weights[i] = static_cast((i * 53U) ^ 0xC7U); + } + + const std::string compiler = "edgetpu-compiler-2026.05.11-0.5"; + const std::string profile = "tensor-g6-v1"; + freetpu::CompileOptions opts{}; + opts.execution_preference = 2U; + opts.priority = 100; + opts.flags = 0x01U; + opts.extra_options = "opt_level=3"; + + MockAotCompilerStore store; + + // 1. Cold compile populates the AOT cache. + auto cold = store.compile_or_load(graph, weights, compiler, profile, opts); + CHECK(cold.ok); + CHECK(!cold.cache_hit); + CHECK(store.compile_count() == 1U); + CHECK(store.miss_count() == 1U); + CHECK(store.hit_count() == 0U); + CHECK(store.entry_count() == 1U); + + // 2. Warm cache hit returns identical payload & digest with ~26.6x speedup. + auto warm = store.compile_or_load(graph, weights, compiler, profile, opts); + CHECK(warm.ok); + CHECK(warm.cache_hit); + CHECK(store.compile_count() == 1U); + CHECK(store.miss_count() == 1U); + CHECK(store.hit_count() == 1U); + CHECK(freetpu::AotCacheGuard::digests_equal(cold.cache_key, warm.cache_key)); + CHECK(freetpu::AotCacheGuard::digests_equal(cold.payload_digest, + warm.payload_digest)); + CHECK(cold.payload == warm.payload); + + const double speedup = cold.modeled_latency_us / warm.modeled_latency_us; + CHECK(speedup >= 20.0); + CHECK(std::fabs(speedup - 26.6) < 0.05); + + std::printf(" [INFO] cold=%.1f us warm=%.1f us speedup=%.2fx " + "(wall cold=%.2f us warm=%.2f us)\n", + cold.modeled_latency_us, warm.modeled_latency_us, speedup, + cold.measured_wall_us, warm.measured_wall_us); + + // 3. Mutating weights[0] ^= 1 MUST force a clean cache miss and recompile + // instead of serving the stale cached executable. + std::vector mutated_weights = weights; + mutated_weights[0] ^= 0x01U; + auto weight_miss = store.compile_or_load(graph, mutated_weights, compiler, + profile, opts); + CHECK(weight_miss.ok); + CHECK(!weight_miss.cache_hit); + CHECK(store.compile_count() == 2U); + CHECK(store.miss_count() == 2U); + CHECK(store.entry_count() == 2U); + CHECK(!freetpu::AotCacheGuard::digests_equal(cold.cache_key, + weight_miss.cache_key)); + CHECK(!freetpu::AotCacheGuard::digests_equal(cold.payload_digest, + weight_miss.payload_digest)); + CHECK(cold.payload != weight_miss.payload); + + // Warm hit on the mutated weights returns the newly compiled executable. + auto weight_warm = store.compile_or_load(graph, mutated_weights, compiler, + profile, opts); + CHECK(weight_warm.ok); + CHECK(weight_warm.cache_hit); + CHECK(store.compile_count() == 2U); + CHECK(store.hit_count() == 2U); + CHECK(freetpu::AotCacheGuard::digests_equal(weight_miss.payload_digest, + weight_warm.payload_digest)); + + // 4. Mutating graph[0] ^= 1, compiler_version, target_profile, and options + // each force clean cache misses. + std::vector mutated_graph = graph; + mutated_graph[0] ^= 0x01U; + auto graph_miss = store.compile_or_load(mutated_graph, weights, compiler, + profile, opts); + CHECK(graph_miss.ok && !graph_miss.cache_hit); + CHECK(store.compile_count() == 3U); + + auto compiler_miss = store.compile_or_load( + graph, weights, "edgetpu-compiler-2026.05.11-0.6", profile, opts); + CHECK(compiler_miss.ok && !compiler_miss.cache_hit); + CHECK(store.compile_count() == 4U); + + auto profile_miss = store.compile_or_load(graph, weights, compiler, + "tensor-g6-v2", opts); + CHECK(profile_miss.ok && !profile_miss.cache_hit); + CHECK(store.compile_count() == 5U); + + freetpu::CompileOptions opts_changed = opts; + opts_changed.flags = 0x02U; + auto opts_miss = store.compile_or_load(graph, weights, compiler, profile, + opts_changed); + CHECK(opts_miss.ok && !opts_miss.cache_hit); + CHECK(store.compile_count() == 6U); + + // 5. Simulate an external stale container placed under a different key: + // strict validate_container inside store rejects it and recompiles cleanly. + std::vector stale_target_weights = weights; + stale_target_weights[1] ^= 0x80U; + auto target_key = freetpu::AotCacheGuard::compute_key_from_buffers( + graph, stale_target_weights, compiler, profile, opts); + CHECK(target_key.ok()); + auto stale_container = freetpu::AotCacheGuard::encode_container( + compiler, profile, cold.cache_key, opts, cold.payload, + freetpu::as_bytes("stale")); + CHECK(stale_container.ok()); + store.inject_raw(target_key.value, stale_container.bytes); + + auto defended = store.compile_or_load(graph, stale_target_weights, compiler, + profile, opts); + CHECK(defended.ok); + CHECK(!defended.cache_hit); + CHECK(store.compile_count() == 7U); + CHECK(!freetpu::AotCacheGuard::digests_equal(cold.payload_digest, + defended.payload_digest)); + return true; +} + +bool test_tensor_footprint_and_overflow_safety() { + CHECK(ftpu_dtype_byte_width(FTPU_DTYPE_INT8) == 1U); + CHECK(ftpu_dtype_byte_width(FTPU_DTYPE_FP16) == 2U); + CHECK(ftpu_dtype_byte_width(FTPU_DTYPE_INT32) == 4U); + CHECK(ftpu_dtype_byte_width(FTPU_DTYPE_FP32) == 4U); + + // Exact [1, 19206, 90] footprint in INT8 and FP32. + auto int8_t = freetpu::TensorSpec::make({1U, 19206U, 90U}, FTPU_DTYPE_INT8); + auto fp32_t = freetpu::TensorSpec::make({1U, 19206U, 90U}, FTPU_DTYPE_FP32); + CHECK(int8_t.byte_size() == 1728540ULL); + CHECK(fp32_t.byte_size() == 6914160ULL); + CHECK(*fp32_t.byte_size() > FTPU_DEFAULT_SRAM_BUDGET_BYTES); + + // Scalar (rank 0) and zero-dimension tensor. + auto scalar = freetpu::TensorSpec::make({}, FTPU_DTYPE_FP32); + CHECK(scalar.byte_size() == 4ULL); + auto empty_t = freetpu::TensorSpec::make({1U, 0U, 90U}, FTPU_DTYPE_FP32); + CHECK(empty_t.byte_size() == 0ULL); + + // Overflow checks in dimensions and dtype multiplication. + auto mul_overflow = freetpu::TensorSpec::make( + {UINT64_MAX / 2ULL + 1ULL, 2ULL}, FTPU_DTYPE_INT8); + ftpu_tensor_desc_t c_desc{}; + CHECK(mul_overflow.to_c_desc(&c_desc) == FTPU_SRAM_OK); + uint64_t out_bytes = 0U; + CHECK(ftpu_tensor_byte_size(&c_desc, &out_bytes) == FTPU_SRAM_ERR_OVERFLOW); + + auto width_overflow = + freetpu::TensorSpec::make({UINT64_MAX / 2ULL}, FTPU_DTYPE_FP32); + CHECK(width_overflow.to_c_desc(&c_desc) == FTPU_SRAM_OK); + CHECK(ftpu_tensor_byte_size(&c_desc, &out_bytes) == FTPU_SRAM_ERR_OVERFLOW); + + // Partitioner fails closed if any op has working-set overflow. + std::vector bad_graph = { + freetpu::OpSpec{0U, FTPU_OP_GENERIC, true, {width_overflow}, {fp32_t}}, + }; + freetpu::SramPartitioner part; + auto res = part.partition(bad_graph); + CHECK(res.status == FTPU_SRAM_ERR_OVERFLOW); + return true; +} + +bool test_sram_budget_boundaries() { + // Strictly < 4 MiB: 4,194,303 B fits; 4,194,304 B (4 MiB) triggers cut. + auto fits_in = + freetpu::TensorSpec::make({2097151ULL}, FTPU_DTYPE_INT8); // 2,097,151 + auto fits_out = + freetpu::TensorSpec::make({2097152ULL}, FTPU_DTYPE_INT8); // 2,097,152 + // Working set = 4,194,303 B < 4,194,304 B + auto exact_in = freetpu::TensorSpec::make({2097152ULL}, FTPU_DTYPE_INT8); + auto exact_out = freetpu::TensorSpec::make({2097152ULL}, FTPU_DTYPE_INT8); + // Working set = 4,194,304 B == 4 MiB (not < 4 MiB) + + std::vector ops = { + freetpu::OpSpec{0U, FTPU_OP_GENERIC, true, {fits_in}, {fits_out}}, + freetpu::OpSpec{1U, FTPU_OP_GENERIC, true, {exact_in}, {exact_out}}, + }; + + freetpu::SramPartitioner part(FTPU_DEFAULT_SRAM_BUDGET_BYTES, true); + auto res = part.partition(ops); + CHECK(res.ok()); + CHECK(res.plan.edgetpu_start_op == 0U); + CHECK(res.plan.edgetpu_end_op_exclusive == 1U); + CHECK(res.plan.delegated_op_count == 1U); + CHECK(res.plan.peak_delegated_working_set_bytes == 4194303ULL); + CHECK(res.plan.trigger_op_index == 1U); + CHECK(res.plan.trigger_op_bytes == FTPU_DEFAULT_SRAM_BUDGET_BYTES); + CHECK(res.plan.reason == FTPU_CUT_SRAM_EXCEEDED); + CHECK(res.op_targets[0] == FTPU_TARGET_EDGETPU); + CHECK(res.op_targets[1] == FTPU_TARGET_CPU_SME2); + + // Configurable tighter budget (2 MiB) catches ops that fit under 4 MiB. + freetpu::SramPartitioner tight(2ULL * 1024ULL * 1024ULL, false); + auto tight_res = tight.partition(ops); + CHECK(tight_res.ok()); + CHECK(tight_res.plan.delegated_op_count == 0U); + CHECK(tight_res.plan.tail_backend == FTPU_TARGET_CPU_NEON); + CHECK(tight_res.op_targets[0] == FTPU_TARGET_CPU_NEON); + CHECK(tight_res.op_targets[1] == FTPU_TARGET_CPU_NEON); + return true; +} + +bool test_efficientdet_tail_cascade_cut_and_routing() { + // Reconstruct the 267-op detection model topology: + // op[0]: QUANTIZE (UINT8 -> INT8, CPU-only) + // op[1..250]: backbone + BiFPN + box/class heads (INT8 < 4 MiB) + // op[251..259]: 9x RESHAPE ending in [1,40,40,810] -> [1,14400,90] INT8 + // op[260]: 5-way CONCATENATION -> [1, 19206, 90] INT8 + // op[261]: LOGISTIC [1, 19206, 90] INT8 + // op[262]: DEQUANTIZE [1, 19206, 90] INT8 -> FP32 (6,914,160 B > 4 MiB) + // op[263..265]: tail box decoding / reshape FP32 ops + // op[266]: TFLite_Detection_PostProcess + std::vector graph; + graph.reserve(267U); + + auto u8_input = + freetpu::TensorSpec::make({1U, 320U, 320U, 3U}, FTPU_DTYPE_UINT8); + auto i8_input = + freetpu::TensorSpec::make({1U, 320U, 320U, 3U}, FTPU_DTYPE_INT8); + graph.push_back( + freetpu::OpSpec{0U, FTPU_OP_QUANTIZE, false, {u8_input}, {i8_input}}); + + auto hidden_i8 = + freetpu::TensorSpec::make({1U, 40U, 40U, 64U}, FTPU_DTYPE_INT8); + for (uint32_t i = 1U; i <= 250U; ++i) { + graph.push_back( + freetpu::OpSpec{i, FTPU_OP_GENERIC, true, {hidden_i8}, {hidden_i8}}); + } + + auto reshape_in = + freetpu::TensorSpec::make({1U, 40U, 40U, 810U}, FTPU_DTYPE_INT8); + auto reshape_out = + freetpu::TensorSpec::make({1U, 14400U, 90U}, FTPU_DTYPE_INT8); + for (uint32_t i = 251U; i <= 259U; ++i) { + graph.push_back(freetpu::OpSpec{i, FTPU_OP_RESHAPE, true, {reshape_in}, + {reshape_out}}); + } + + // 5-way CONCATENATION: 14400 + 3600 + 900 + 225 + 81 = 19206 anchors. + auto c0 = freetpu::TensorSpec::make({1U, 14400U, 90U}, FTPU_DTYPE_INT8); + auto c1 = freetpu::TensorSpec::make({1U, 3600U, 90U}, FTPU_DTYPE_INT8); + auto c2 = freetpu::TensorSpec::make({1U, 900U, 90U}, FTPU_DTYPE_INT8); + auto c3 = freetpu::TensorSpec::make({1U, 225U, 90U}, FTPU_DTYPE_INT8); + auto c4 = freetpu::TensorSpec::make({1U, 81U, 90U}, FTPU_DTYPE_INT8); + auto wide_i8 = + freetpu::TensorSpec::make({1U, 19206U, 90U}, FTPU_DTYPE_INT8); + auto wide_fp32 = + freetpu::TensorSpec::make({1U, 19206U, 90U}, FTPU_DTYPE_FP32); + + graph.push_back(freetpu::OpSpec{ + 260U, FTPU_OP_CONCATENATION, true, {c0, c1, c2, c3, c4}, {wide_i8}}); + graph.push_back( + freetpu::OpSpec{261U, FTPU_OP_LOGISTIC, true, {wide_i8}, {wide_i8}}); + graph.push_back(freetpu::OpSpec{ + 262U, FTPU_OP_DEQUANTIZE, true, {wide_i8}, {wide_fp32}}); + + auto box_fp32 = freetpu::TensorSpec::make({1U, 19206U, 4U}, FTPU_DTYPE_FP32); + for (uint32_t i = 263U; i <= 265U; ++i) { + graph.push_back( + freetpu::OpSpec{i, FTPU_OP_GENERIC, true, {box_fp32}, {box_fp32}}); + } + graph.push_back(freetpu::OpSpec{ + 266U, FTPU_OP_DETECTION_POSTPROCESS, false, {box_fp32}, {box_fp32}}); + + // ARM64 with SME2: cuts before op[260], delegating ops 1..259 and routing + // ops 260..266 to CPU/SME2. + freetpu::SramPartitioner sme2_part(FTPU_DEFAULT_SRAM_BUDGET_BYTES, true); + auto sme2_res = sme2_part.partition(graph); + CHECK(sme2_res.ok()); + CHECK(sme2_res.plan.total_ops == 267U); + CHECK(sme2_res.plan.edgetpu_start_op == 1U); + CHECK(sme2_res.plan.edgetpu_end_op_exclusive == 260U); + CHECK(sme2_res.plan.delegated_op_count == 259U); + CHECK(sme2_res.plan.tail_start_op == 260U); + CHECK(sme2_res.plan.tail_backend == FTPU_TARGET_CPU_SME2); + CHECK(sme2_res.plan.trigger_op_index == 262U); + CHECK(sme2_res.plan.trigger_op_bytes == 1728540ULL + 6914160ULL); + CHECK(sme2_res.plan.peak_delegated_working_set_bytes == 2592000ULL); + CHECK(sme2_res.plan.peak_delegated_working_set_bytes < + FTPU_DEFAULT_SRAM_BUDGET_BYTES); + CHECK(sme2_res.plan.reason == FTPU_CUT_TAIL_CASCADE_BEFORE_SRAM); + CHECK(std::strcmp(ftpu_target_backend_name(sme2_res.plan.tail_backend), + "CPU/SME2") == 0); + CHECK(sme2_res.op_targets[0] == FTPU_TARGET_CPU_SME2); + CHECK(sme2_res.op_targets[1] == FTPU_TARGET_EDGETPU); + CHECK(sme2_res.op_targets[259] == FTPU_TARGET_EDGETPU); + CHECK(sme2_res.op_targets[260] == FTPU_TARGET_CPU_SME2); + CHECK(sme2_res.op_targets[261] == FTPU_TARGET_CPU_SME2); + CHECK(sme2_res.op_targets[262] == FTPU_TARGET_CPU_SME2); + CHECK(sme2_res.op_targets[266] == FTPU_TARGET_CPU_SME2); + + // ARM64 without SME2: same prefix cut, tail routed to CPU/NEON. + freetpu::SramPartitioner neon_part(FTPU_DEFAULT_SRAM_BUDGET_BYTES, false); + auto neon_res = neon_part.partition(graph); + CHECK(neon_res.ok()); + CHECK(neon_res.plan.edgetpu_end_op_exclusive == 260U); + CHECK(neon_res.plan.tail_backend == FTPU_TARGET_CPU_NEON); + CHECK(std::strcmp(ftpu_target_backend_name(neon_res.plan.tail_backend), + "CPU/NEON") == 0); + CHECK(neon_res.op_targets[260] == FTPU_TARGET_CPU_NEON); + CHECK(neon_res.op_targets[266] == FTPU_TARGET_CPU_NEON); + + // If op[0] is also EdgeTPU-supported, delegated prefix is ops 0..259. + graph[0].hal_supported = true; + auto full_prefix_res = sme2_part.partition(graph); + CHECK(full_prefix_res.ok()); + CHECK(full_prefix_res.plan.edgetpu_start_op == 0U); + CHECK(full_prefix_res.plan.edgetpu_end_op_exclusive == 260U); + CHECK(full_prefix_res.plan.delegated_op_count == 260U); + + std::printf(" [INFO] prefix=[%u..%u) delegated=%u tail_start=%u " + "peak_ws=%" PRIu64 " B trigger_ws=%" PRIu64 " B\n", + full_prefix_res.plan.edgetpu_start_op, + full_prefix_res.plan.edgetpu_end_op_exclusive, + full_prefix_res.plan.delegated_op_count, + full_prefix_res.plan.tail_start_op, + full_prefix_res.plan.peak_delegated_working_set_bytes, + full_prefix_res.plan.trigger_op_bytes); + return true; +} + +bool test_small_dequantize_stays_delegated() { + auto small_i8 = freetpu::TensorSpec::make({1U, 100U, 10U}, FTPU_DTYPE_INT8); + auto small_fp32 = + freetpu::TensorSpec::make({1U, 100U, 10U}, FTPU_DTYPE_FP32); + std::vector graph = { + freetpu::OpSpec{0U, FTPU_OP_GENERIC, true, {small_i8}, {small_i8}}, + freetpu::OpSpec{ + 1U, FTPU_OP_DEQUANTIZE, true, {small_i8}, {small_fp32}}, + }; + + freetpu::SramPartitioner part(FTPU_DEFAULT_SRAM_BUDGET_BYTES, true); + auto res = part.partition(graph); + CHECK(res.ok()); + CHECK(res.plan.delegated_op_count == 2U); + CHECK(res.plan.reason == FTPU_CUT_NONE); + CHECK(res.op_targets[0] == FTPU_TARGET_EDGETPU); + CHECK(res.op_targets[1] == FTPU_TARGET_EDGETPU); + return true; +} + +} // namespace + +int main() { + RUN_TEST(test_sha256_nist_vectors); + RUN_TEST(test_5input_cache_key_prevents_false_hits); + RUN_TEST(test_container_envelope_validation); + RUN_TEST(test_warm_hit_speedup_and_changed_weight_miss); + RUN_TEST(test_tensor_footprint_and_overflow_safety); + RUN_TEST(test_sram_budget_boundaries); + RUN_TEST(test_efficientdet_tail_cascade_cut_and_routing); + RUN_TEST(test_small_dequantize_stays_delegated); + + std::printf("Summary: %d/%d tests passed\n", + g_tests_run - g_tests_failed, g_tests_run); + return (g_tests_failed == 0) ? 0 : 1; +}