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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
116 changes: 116 additions & 0 deletions .github/workflows/public-roads-firewall.yml
Original file line number Diff line number Diff line change
@@ -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 = "<diff>"
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
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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
Expand Down
59 changes: 59 additions & 0 deletions aot-guard/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)

if(CMAKE_C_COMPILER_ID MATCHES "Clang|GNU")
target_compile_options(freetpu_aot_guard PRIVATE
$<$<COMPILE_LANGUAGE:C>:-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()
75 changes: 75 additions & 0 deletions aot-guard/Makefile
Original file line number Diff line number Diff line change
@@ -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 <cstdint>' \
'#include <vector>' \
'int main() {' \
' std::vector<uint8_t> 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<const freetpu::OpSpec>{});' \
' 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)
78 changes: 78 additions & 0 deletions aot-guard/README.md
Original file line number Diff line number Diff line change
@@ -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).
Loading
Loading