diff --git a/CMakeLists.txt b/CMakeLists.txt index 7cab7ef..bf84d79 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -131,6 +131,19 @@ if (_FREESCHED_OB_INCLUDE AND _FREESCHED_OB_LIB) target_include_directories(volcanic_tpu_dmabuf_bench PRIVATE "${_FREESCHED_OB_INCLUDE}") endif() +add_executable(volcanic_tpu_token_loop_bench tools/volcanic_tpu_token_loop_bench.cpp) +target_link_libraries(volcanic_tpu_token_loop_bench PRIVATE freesched) +target_include_directories(volcanic_tpu_token_loop_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tools) +target_compile_features(volcanic_tpu_token_loop_bench PRIVATE cxx_std_17) +target_compile_options(volcanic_tpu_token_loop_bench PRIVATE -Wall -Wextra -Werror -fno-exceptions -fno-rtti) +if (_FREESCHED_OB_INCLUDE AND _FREESCHED_OB_LIB) + target_compile_definitions(volcanic_tpu_token_loop_bench PRIVATE FREESCHED_HAVE_LIBOPENBUENOS=1) + target_include_directories(volcanic_tpu_token_loop_bench PRIVATE "${_FREESCHED_OB_INCLUDE}") +endif() +if (ANDROID) + target_link_options(volcanic_tpu_token_loop_bench PRIVATE -static-libstdc++ -Wl,-z,max-page-size=16384) +endif() + add_executable(adreno663_vk_dmabuf_probe tools/adreno663_vk_dmabuf_probe.c src/fs_vk_adreno_caps.c @@ -232,6 +245,117 @@ if (FREESCHED_BUILD_TESTS) if (FREESCHED_BUILD_TOOLS) add_test(NAME freesched_dmabuf_smoke COMMAND freesched_dmabuf_smoke --profile laguna --mock --json) add_test(NAME volcanic_tpu_dmabuf_bench_mock COMMAND volcanic_tpu_dmabuf_bench --mock --m-pre 4 --k 512 --n 512 --json) + # Token-loop bench tests rely on the exit code (0 only when the top-level + # result passes). Never use PASS_REGULAR_EXPRESSION here: it makes CTest + # ignore the exit code, and an unanchored "pass":true also matches nested arm + # objects. Content checks go through ctest_run_expect.cmake (exit 0 AND match). + set(_FS_RUN_EXPECT ${CMAKE_CURRENT_SOURCE_DIR}/tests/ctest_run_expect.cmake) + # CTest prefixes CMAKE_CROSSCOMPILING_EMULATOR (only when CMAKE_CROSSCOMPILING) + # to tests whose COMMAND names an executable target. Wrapped tests (cmake -P + # ctest_run_expect.cmake, python3 token_loop_json_check.py) launch + # $ themselves, so the emulator and its arguments are passed + # through explicitly: '|'-joined as -DEMULATOR= for the CMake wrapper, and one + # --emulator-arg= per list element for the Python checker. + set(_FS_EMU "") + if (CMAKE_CROSSCOMPILING AND CMAKE_CROSSCOMPILING_EMULATOR) + set(_FS_EMU ${CMAKE_CROSSCOMPILING_EMULATOR}) + endif() + string(JOIN "|" _FS_EMU_PIPE ${_FS_EMU}) + set(_FS_EMU_PY "") + foreach(_fs_emu_arg IN LISTS _FS_EMU) + list(APPEND _FS_EMU_PY "--emulator-arg=${_fs_emu_arg}") + endforeach() + add_test(NAME volcanic_tpu_token_loop_bench_mock + COMMAND ${CMAKE_COMMAND} + "-DCMD=$|--mock|--layers|12|--tokens|64|--d|512|--json" + "-DEXPECT_REGEX=^[{]\"pass\":true,\"mode\":\"mock\"" + "-DEMULATOR=${_FS_EMU_PIPE}" + -P ${_FS_RUN_EXPECT}) + add_test(NAME volcanic_tpu_token_loop_bench_mock_riif_d1024 + COMMAND volcanic_tpu_token_loop_bench --mock --layers 4 --tokens 8 --d 1024 --arms sync_file,r_iif --require-iif --json) + add_test(NAME volcanic_tpu_token_loop_iif_probe_absent + COMMAND ${CMAKE_COMMAND} + "-DCMD=$|--iif-probe-only|--iif-dev|/nonexistent-freesched-iif-node" + "-DEXPECT_REGEX=\"usable\":false.*\"bridge_dma_ok\":false.*\"abi\":\"google-iif-uapi\",\"ioctl_create\":\"0xc0086900\",\"ioctl_submit_signaler\":\"0x6981\",\"ioctl_signal\":\"0xc0086982\"" + "-DEMULATOR=${_FS_EMU_PIPE}" + -P ${_FS_RUN_EXPECT}) + add_test(NAME volcanic_tpu_token_loop_bench_mock_nnapi_quant8 + COMMAND ${CMAKE_COMMAND} + "-DCMD=$|--mock|--tpu-backend|nnapi|--layers|12|--tokens|32|--d|512|--json" + "-DEXPECT_REGEX=^[{]\"pass\":true,\"mode\":\"mock\",\"executor\":\"mock_cpu_nnapi_quant8\".*\"tpu_numerics\":\"quant8_asymm_conv1x1\"" + "-DEMULATOR=${_FS_EMU_PIPE}" + -P ${_FS_RUN_EXPECT}) + # d2048 smoke: exit code only (the bench exits 1 unless the top-level result passes). + add_test(NAME volcanic_tpu_token_loop_bench_mock_nnapi_quant8_d2048 + COMMAND volcanic_tpu_token_loop_bench --mock --tpu-backend nnapi --layers 8 --tokens 4 --d 2048 + --arms host_staged,sync_file_poll,r_iif --require-iif --json) + # Negative: both arms pass ("pass":true in nested arm objects) but --require-iif + # rejects the run without r_iif, so the top-level result and exit code fail. + add_test(NAME volcanic_tpu_token_loop_bench_mock_nnapi_quant8_d2048_require_iif_rejects + COMMAND volcanic_tpu_token_loop_bench --mock --tpu-backend nnapi --layers 8 --tokens 4 --d 2048 + --arms host_staged,sync_file_poll --require-iif --json) + set_tests_properties(volcanic_tpu_token_loop_bench_mock_nnapi_quant8_d2048_require_iif_rejects + PROPERTIES WILL_FAIL TRUE) + add_test(NAME volcanic_tpu_token_loop_bench_rejects_bad_backend + COMMAND volcanic_tpu_token_loop_bench --mock --tpu-backend bogus --json) + set_tests_properties(volcanic_tpu_token_loop_bench_rejects_bad_backend PROPERTIES WILL_FAIL TRUE) + add_test(NAME volcanic_tpu_token_loop_bench_rejects_bad_dims + COMMAND volcanic_tpu_token_loop_bench --mock --d 500 --json) + set_tests_properties(volcanic_tpu_token_loop_bench_rejects_bad_dims PROPERTIES WILL_FAIL TRUE) + add_test(NAME volcanic_tpu_token_loop_bench_require_iif_needs_riif + COMMAND volcanic_tpu_token_loop_bench --mock --layers 2 --tokens 2 --d 512 --arms sync_file_poll --require-iif --json) + set_tests_properties(volcanic_tpu_token_loop_bench_require_iif_needs_riif PROPERTIES WILL_FAIL TRUE) + # Strict numeric CLI parsing: each malformed value must be rejected (exit 2, see the + # badargs Python check for the exact code). The first value carries U+2212 MINUS SIGN. + foreach(_fs_bad IN ITEMS "odpm_unicode_minus|--odpm-unit-j|1e−6" "odpm_zero|--odpm-unit-j|0" + "odpm_nan|--odpm-unit-j|nan" "layers_trailing|--layers|12x") + string(REPLACE "|" ";" _fs_bad_l "${_fs_bad}") + list(GET _fs_bad_l 0 _fs_bad_name) + list(GET _fs_bad_l 1 _fs_bad_opt) + list(GET _fs_bad_l 2 _fs_bad_val) + add_test(NAME volcanic_tpu_token_loop_bench_rejects_${_fs_bad_name} + COMMAND volcanic_tpu_token_loop_bench --mock --layers 2 --tokens 2 ${_fs_bad_opt} ${_fs_bad_val} --json) + set_tests_properties(volcanic_tpu_token_loop_bench_rejects_${_fs_bad_name} PROPERTIES WILL_FAIL TRUE) + endforeach() + add_executable(test_token_loop_riif tests/test_token_loop_riif.cpp) + target_include_directories(test_token_loop_riif PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tools + ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_compile_features(test_token_loop_riif PRIVATE cxx_std_17) + target_compile_options(test_token_loop_riif PRIVATE -Wall -Wextra -Werror -fno-exceptions -fno-rtti) + add_test(NAME test_token_loop_riif COMMAND test_token_loop_riif) + find_package(Python3 COMPONENTS Interpreter QUIET) + if (Python3_FOUND) + # Strict JSON (inf/nan rejected): non-finite diagnostics become null, and the + # mock bench output parses with a true top-level pass. + add_test(NAME test_token_loop_riif_nonfinite_json + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} nonfinite + $) + add_test(NAME test_token_loop_riif_hostile_iif_dev_json + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} escape + $) + add_test(NAME volcanic_tpu_token_loop_iif_probe_hostile_dev_json + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} probe + $) + add_test(NAME volcanic_tpu_token_loop_bench_failure_recovery + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} recover + $) + add_test(NAME volcanic_tpu_token_loop_bench_mock_never_opens_iif + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} mockiif + $) + add_test(NAME volcanic_tpu_token_loop_bench_strict_args_exit2 + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} badargs + $) + add_test(NAME token_loop_proof_scripts_unit + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py scripts + ${CMAKE_CURRENT_SOURCE_DIR}/proof/tensor-g6-gpu-edgetpu-riif-token-loop) + add_test(NAME token_loop_proof_receipt_reconciled + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/scripts/token_loop_receipt.py check + ${CMAKE_CURRENT_SOURCE_DIR}/proof/tensor-g6-gpu-edgetpu-riif-token-loop) + add_test(NAME volcanic_tpu_token_loop_bench_mock_json_valid + COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_CURRENT_SOURCE_DIR}/tests/token_loop_json_check.py ${_FS_EMU_PY} bench + $ --mock --tpu-backend nnapi --layers 4 --tokens 4 --d 512 + --require-iif --json) + endif() add_test(NAME freesched_dmabuf_smoke_iq9075 COMMAND freesched_dmabuf_smoke --profile iq9075 --mock --json) add_test(NAME adreno663_vk_dmabuf_probe_mock COMMAND adreno663_vk_dmabuf_probe --mock --json) add_test(NAME pocketcoder_run_bench_synthetic COMMAND pocketcoder-run --bench-synthetic --iters 20) diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/PROOF.md b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/PROOF.md new file mode 100644 index 0000000..4648434 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/PROOF.md @@ -0,0 +1,627 @@ +# Proof: Live Tensor G6 GPU <-> EdgeTPU Multi-Layer Token Decode Loop (`host_staged` vs `sync_file_poll` vs `r_iif`) + +## Scope + +Live on-silicon run of `tools/volcanic_tpu_token_loop_bench.cpp` on a +**Pixel 11 Pro XL** (**Tensor G6**, Android 17): every transformer block runs +a Vulkan GEMV + residual/RMSNorm on the **PowerVR C-Series CXTP-48-1536 MC1** +GPU and a `TENSOR_QUANT8_ASYMM` 1x1 `CONV_2D` FFN on the **Google EdgeTPU** +(NNAPI accelerator `google-edgetpu`), sharing zero-copy `AHardwareBuffer` +BLOB tensors. Three GPU <-> EdgeTPU handoff arms are compared: + +- `host_staged`: CPU waits on each stage and copies the uint8 tensor through host memory (2L host copies/token). +- `sync_file_poll`: zero-copy; every hop exports a `sync_file` that a waiter thread `poll()`s before starting the next stage. +- `r_iif`: zero-copy; one in-kernel fence chain per token (Vulkan `SYNC_FD` -> `ANeuralNetworksEvent_createFromSyncFenceFd` -> `startComputeWithDependencies` -> `ANeuralNetworksEvent_getSyncFenceFd` -> `vkImportSemaphoreFdKHR`), gated by an AP-signaled `/dev/iif` fence bridged to a `sync_file`; zero userspace `poll()` between layers. The gate is used only when the probe reports `bridge_dma_ok` (`FS_IIF_FENCE_BRIDGE_DMA` returned a `sync_file` that signaled); otherwise the arm runs the same chain ungated and records 0 IIF fences. + +## How This Packet Is Produced (no hand-copied numbers) + +1. `scripts/token_loop_capture.py` holds one exclusive adb lock (`fcntl` `flock(LOCK_EX)`) for the whole session, + pushes one bench binary and one unit-test binary, re-hashes the device binary before **every** run and writes each + run's raw stdout plus `session.json` (argv, uid, exit code, expected exit code, device binary SHA-256, stdout + SHA-256, HAL pids, kernel-log / crash-buffer deltas, `/dev/iif` open watch, cleanup). +2. `scripts/token_loop_receipt.py host-verify` records the host checks in `host-verification.json`. +3. `scripts/token_loop_receipt.py write` generates every measured key of `receipt.json` and every + `GENERATED` block of this file from those files only. +4. `scripts/token_loop_receipt.py check` (CTest `token_loop_proof_receipt_reconciled`) fails on any stale value, any + raw-file hash mismatch, more than one bench binary, an unexpected exit code, or a measured number in hand-written + prose (here or in the `receipt.json` narrative keys). + +Files: `receipt.json`, `session.json`, `host-verification.json`, `unit-test-device.txt` and the raw `--json` outputs +listed under "Supplementary Runs" plus `bench-L12-T64-d{512,1024,2048}.json`. + +## Method + + +- Bench binary SHA-256 `556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705` (host build tree, after streaming to device, before every one of the 15 runs and at the end of the session: 1 distinct value). Unit test SHA-256 `c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9`. +- Device: Pixel 11 Pro XL (`kodiak`, Tensor G6), Android 17, security patch 2026-06-05. Session 2026-12-03T21:48:44Z -> 2026-12-03T21:49:44Z under `fcntl.flock LOCK_EX` on `/tmp/kodiak-pixel11-adb.lock`. + + +- Command (per `d`): `unset LD_LIBRARY_PATH; volcanic_tpu_token_loop_bench --live --tpu-backend nnapi --layers 12 --tokens 64 --warmup 4 --d --min-cos 0.995 --require-iif --json`. +- Build/backend: `--tpu-backend nnapi` was explicitly requested (not an automatic fallback). + +- Run as root: ODPM `energy_value` rails and `/dev/iif` are both `EACCES` for uid `shell` (the bench then runs `r_iif` without the IIF gate and reports `iif=none(EACCES)`). `LD_LIBRARY_PATH` stays unset so the APEX NNAPI and Vulkan linker namespaces resolve normally. No flash writes; only a session directory under `/data/local/tmp` was used and removed. +- Energy: ODPM `energy_value` deltas over the measured tokens (1 unit = 1 uJ, the default `--odpm-unit-j`); GPU, EdgeTPU and VSYS rails reported per token. +- Context switches: `/proc/self/status` `voluntary_ctxt_switches` deltas of the decode thread per token. +- Parity: cosine vs. `reference_token()`, an FP64 forward pass of the same weights with **unquantized float + activations**. The reference is computed before the QUANT8 parameters are derived from it and skips both activation + quantization steps (`A[l]` quantize, `Y[l]` requantize). The `cos >= 0.995` gate is therefore an end-to-end + agreement check against the float-activation baseline that *includes* the intended INT8 activation quantization + error; it does not by itself validate the QUANT8 implementation bit-for-bit. The cross-arm check does that part: + `arms_max_abs_diff` (see "Sweep Facts") compares the quantized outputs of `host_staged`, `sync_file_poll` and + `r_iif`. + +## Results (L = 12 blocks, T = 64 measured tokens, 4 warmup tokens) + +Values are the exact raw JSON numbers (energy in J/token). + + +| d | arm | tok/s | ms/tok p50 | ms/tok p99 | vol. ctx-sw/tok | userspace polls/tok | cross-thread wakeups/tok | host copies/tok | IIF fences/tok | imported sync_files/tok | NNAPI event checks/tok | cos | GPU J/tok | EdgeTPU J/tok | VSYS J/tok | +| ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 512 | `host_staged` | 35.766218 | 27.321051 | 32.869062 | 25.0 | 0.0 | 0.0 | 24.0 | 0.0 | 0.0 | 0.0 | 0.999396411 | 0.00155890625 | 0.00121809375 | 0.109674187 | +| 512 | `sync_file_poll` | 53.302744 | 18.51337 | 22.315171 | 49.0156 | 24.0 | 24.0 | 0.0 | 0.0 | 0.0 | 12.0 | 0.999396411 | 0.001231125 | 0.00093884375 | 0.0763692656 | +| 512 | `r_iif` | 56.785738 | 17.114938 | 21.663515 | 19.9531 | 0.0 | 0.0 | 0.0 | 1.0 | 13.0 | 12.0 | 0.999396411 | 0.0012400625 | 0.000886 | 0.0752817031 | +| 1024 | `host_staged` | 28.934808 | 34.749688 | 38.490922 | 25.5938 | 0.0 | 0.0 | 24.0 | 0.0 | 0.0 | 0.0 | 0.999312121 | 0.00337757812 | 0.00168639062 | 0.146782047 | +| 1024 | `sync_file_poll` | 41.193422 | 23.879411 | 28.569999 | 48.9062 | 24.0 | 24.0 | 0.0 | 0.0 | 0.0 | 12.0 | 0.999312121 | 0.00311964062 | 0.001272125 | 0.107609578 | +| 1024 | `r_iif` | 45.415103 | 21.833828 | 27.679192 | 23.0938 | 0.0 | 0.0 | 0.0 | 1.0 | 13.0 | 12.0 | 0.999312121 | 0.00294203125 | 0.00117323438 | 0.0986188594 | +| 2048 | `host_staged` | 10.49263 | 95.774816 | 106.042352 | 26.2812 | 0.0 | 0.0 | 24.0 | 0.0 | 0.0 | 0.0 | 0.999263834 | 0.0182789219 | 0.00464123437 | 0.419996125 | +| 2048 | `sync_file_poll` | 11.77054 | 84.330701 | 95.602603 | 46.0938 | 24.0 | 24.0 | 0.0 | 0.0 | 0.0 | 12.0 | 0.999263834 | 0.0179781719 | 0.00419584375 | 0.383372375 | +| 2048 | `r_iif` | 13.076028 | 76.1694 | 85.628775 | 41.8594 | 0.0 | 0.0 | 0.0 | 1.0 | 13.0 | 12.0 | 0.999263834 | 0.0177053437 | 0.003883875 | 0.354426047 | + + +Synchronization timing (us/token; the same interval definitions in every arm, see "Timing Fields" below): + + +| d | arm | `host_wait_us_per_tok` | `dispatch_submit_us_per_tok` | `nnapi_start_block_us_per_tok` | `nnapi_dep_event_create_us_per_tok` | `pipelined_chain_us_per_tok` | +| ---: | --- | ---: | ---: | ---: | ---: | ---: | +| 512 | `host_staged` | 11535.667 | 701.375 | 0.0 | 0.0 | null | +| 512 | `sync_file_poll` | 8251.997 | 9928.575 | 8903.161 | 0.0 | null | +| 512 | `r_iif` | 3207.209 | 13841.45 | 6767.988 | 16.904 | 17040.323 | +| 1024 | `host_staged` | 16274.261 | 693.066 | 0.0 | 0.0 | null | +| 1024 | `sync_file_poll` | 13468.836 | 10209.799 | 9111.11 | 0.0 | null | +| 1024 | `r_iif` | 6478.652 | 14917.961 | 6919.222 | 17.975 | 21396.186 | +| 2048 | `host_staged` | 66629.519 | 1223.696 | 0.0 | 0.0 | null | +| 2048 | `sync_file_poll` | 69793.019 | 14426.815 | 13239.781 | 0.0 | null | +| 2048 | `r_iif` | 58565.004 | 17078.08 | 9616.854 | 22.31 | 75603.246 | + + +### Sweep Facts + + +- d = 512: top-level `pass` = true, `arms_max_abs_diff` = 0, `hot_loop_map_count` = 0, `hot_loop_unmap_count` = 0, `total_submissions` = `completed_drains` = 3536 / 3536, IIF `kernel` (`gpu_gate` = true, `bridge_dma_ok` = true, `requirement_met` = true), ownership barriers recorded = 96 (`foreign_ext`), `executor_state.failure_recoveries` = 0. +- d = 1024: top-level `pass` = true, `arms_max_abs_diff` = 0, `hot_loop_map_count` = 0, `hot_loop_unmap_count` = 0, `total_submissions` = `completed_drains` = 3536 / 3536, IIF `kernel` (`gpu_gate` = true, `bridge_dma_ok` = true, `requirement_met` = true), ownership barriers recorded = 96 (`foreign_ext`), `executor_state.failure_recoveries` = 0. +- d = 2048: top-level `pass` = true, `arms_max_abs_diff` = 0, `hot_loop_map_count` = 0, `hot_loop_unmap_count` = 0, `total_submissions` = `completed_drains` = 3536 / 3536, IIF `kernel` (`gpu_gate` = true, `bridge_dma_ok` = true, `requirement_met` = true), ownership barriers recorded = 96 (`foreign_ext`), `executor_state.failure_recoveries` = 0. + + +### Derived Comparisons (computed from the table above) + + +- d = 512: `r_iif` / `host_staged` throughput = 1.59x, `r_iif` / `sync_file_poll` = 1.07x; `r_iif` VSYS J/tok vs. `host_staged` = -31.4%; host wait `r_iif` 3.2 ms vs. `sync_file_poll` 8.3 ms per token. +- d = 1024: `r_iif` / `host_staged` throughput = 1.57x, `r_iif` / `sync_file_poll` = 1.10x; `r_iif` VSYS J/tok vs. `host_staged` = -32.8%; host wait `r_iif` 6.5 ms vs. `sync_file_poll` 13.5 ms per token. +- d = 2048: `r_iif` / `host_staged` throughput = 1.25x, `r_iif` / `sync_file_poll` = 1.11x; `r_iif` VSYS J/tok vs. `host_staged` = -15.6%; host wait `r_iif` 58.6 ms vs. `sync_file_poll` 69.8 ms per token. + + +`r_iif` keeps its decode thread out of userspace fence polls between layers, while `sync_file_poll` pays one waiter +`poll()` plus one cross-thread wakeup per hop (each one also verifies `SYNC_IOC_FILE_INFO.status == 1` before the +consumer touches the buffer). Most of the remaining `r_iif` dispatch time is +`ANeuralNetworksExecution_startComputeWithDependencies` blocking inside the NNAPI runtime +(`nnapi_start_block_us_per_tok`); that runtime-side blocking also explains why `r_iif` still shows voluntary context +switches although the bench never polls between layers, and it is the remaining headroom for this arm. + +## IOVA Observation Scope + +The live NNAPI path shares the QUANT8 GPU <-> EdgeTPU tensors as `AHardwareBuffer` BLOBs +(`nnapi.shared_mem = "ahb_blob_gpu_data_buffer"`), so the JSON reports +`iova_pool.iova_observation_scope = "vulkan_pool_only_nnapi_ahb_external"`: + +- `hot_loop_map_count == 0` / `hot_loop_unmap_count == 0` prove zero hot-loop maps/unmaps on the `fs_iova_pool` + (Vulkan-imported) buffers only. +- The four QUANT8 `AHardwareBuffer`s are allocated and registered once with + `ANeuralNetworksMemory_createFromAHardwareBuffer` before hot-loop entry + (`nnapi_ahb_memories_registered_before_hot_loop`); `ahb_hot_loop_allocs` counts the + `AHardwareBuffer_allocate` calls made while the arms ran. Driver-internal gralloc/NNAPI mappings of those buffers + are outside userspace pool observation and are not covered by the map counters. +- Pool submissions/drains are recorded only on slots a device actually touches: the GPU's FP32 `mid(l)` (GEMV) and + `out(l)` (dequant of `Y`) writes. No EdgeTPU submission is attributed to an FP32 slot (Generation 3 recorded the + EdgeTPU against the FP32 `out` slot, which NNAPI never writes). Every sweep run reports + `total_submissions == completed_drains` (values: "Sweep Facts"). +- In `dmabuf_fd` mode (`iova_observation_scope = "full_pool_dmabuf"`) the QUANT8 tensors are pool slots and the + EdgeTPU submissions/drains are recorded on the actual `qmid` / `qout` slots. The `host_staged` bridge tensors are + isolated `AHardwareBuffer`s in every mode (`nnapi.host_staged_mem = "isolated_ahb_blob"`) and are never pool slots. +- On the `libopenbuenos` backend (`iova_observation_scope = "vulkan_pool_only_openbuenos_weights_external"`), every + layer's packed weight cache is pre-warmed via `ob_gemm_matmul_f32_w8a16_dmabuf` before + `fs_iova_pool_enter_hot_loop()` (`ob_prewarmed_layers = L`), while internal `libopenbuenos` weight buffers stay + outside `fs_iova_pool` observation. + +## Timing Fields + +`sync_us_per_tok` is gone: it measured different intervals in different arms. Every arm now reports: + +- `host_wait_us_per_tok`: decode-thread time blocked in host-side waits only. These are `poll()` of a `sync_file` + (inline or handed to the waiter thread), `vkWaitForFences`, `vkQueueWaitIdle` (the IIF-gate drain), + `ANeuralNetworksEvent_wait` and the `/dev/iif` wait ioctl. Submission calls are excluded. +- `dispatch_submit_us_per_tok`: time inside `vkQueueSubmit` and `ANeuralNetworksExecution_startComputeWithDependencies` + only (`nnapi_start_block_us_per_tok` is the NNAPI part). The NNAPI timer starts after the dependency event exists, + so both fenced arms time the identical submission call. +- `nnapi_dep_event_create_us_per_tok`: `ANeuralNetworksEvent_createFromSyncFenceFd` (the `r_iif` GPU -> EdgeTPU + dependency), outside both fields above; 0 for arms without a dependency fd. +- `pipelined_chain_us_per_tok`: `r_iif` NNAPI chain only, from the first chain `vkQueueSubmit` through the + token-boundary `VkFence` (it spans the two fields above); `null` for arms without a pipelined chain. + +Hardware EdgeTPU execution time is `tpu_hw_us_per_tok` only when the backend measured it (libopenbuenos). +Fenced NNAPI and synchronous NNAPI leave that field null. The synchronous `ANeuralNetworksExecution_compute` host +call is `nnapi_sync_call_us_per_tok`, and that field is null on fenced arms. + +## W8A16 Path (`--tpu-backend cpu`, L = 12, T = 16, d = 512) + +Only the GPU -> CPU hop has an asynchronous producer fence: both fenced arms report `fence_handoffs_per_tok = L` and +`synchronous_cpu_hops_per_tok = L`, and every arm counts its 2L host copies per token. `sync_file_poll` waits on each +real sync_file (`g2t != -1`) on the `FdWaiter` thread: L cross-thread wakeups per token on both the CPU backend and +the synchronous `libopenbuenos` W8A16 backend (which reports `synchronous_tpu_hops_per_tok = L` and +`fence_handoffs_per_tok = L`). `r_iif` keeps inline waits and skips `poll` when the exported Vulkan SYNC_FD is already +signaled (`g2t == -1`). Raw file `w8a16-cpu-tpu-L12-T16-d512.json`: + + +| arm | tok/s | fence handoffs/tok | synchronous CPU hops/tok | polls/tok | wakeups/tok | SYNC_FD exports/tok | IIF fences/tok | host copies/tok | cos | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `host_staged` | 21.745421 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 24.0 | 0.999999876 | +| `sync_file_poll` | 24.46914 | 12.0 | 12.0 | 12.0 | 12.0 | 12.0 | 0.0 | 24.0 | 0.999999876 | +| `r_iif` | 24.671081 | 12.0 | 12.0 | 24.0 | 0.0 | 12.0 | 12.0 | 24.0 | 0.999999876 | + + +## Supplementary Runs + +Every row is generated from the raw file and `session.json`; the expectation for each file is in +`receipt.json` (`supplementary_runs[].expected`). + + +| file | uid | exit (expected) | top-level pass | arms (ran / pass / skip) | key observation | +| --- | --- | --- | --- | --- | --- | +| `smoke-L4-T8-d512.json` | root | 0 (0) | true | `host_staged` ran/pass, `sync_file_poll` ran/pass, `r_iif` ran/pass | iif `kernel` / `ap_signaled_gate_imported_into_gpu_queue`, requirement_met true, dev_open_calls 2, exec_start_calls 80, recoveries 0, tainted false | +| `w8a16-cpu-tpu-L12-T16-d512.json` | root | 0 (0) | true | `host_staged` ran/pass, `sync_file_poll` ran/pass, `r_iif` ran/pass | iif `kernel` / `cpu_proxy`, requirement_met true, dev_open_calls 2, exec_start_calls 0, recoveries 0, tainted false | +| `neg-swfallback-require-iif-L4-T8-d512.json` | root | 1 (1) | false | `host_staged` skip: not_selected, `sync_file_poll` skip: not_selected, `r_iif` ran/pass | iif `sw_emulated` / `sw_emulated`, requirement_met false, dev_open_calls 1, exec_start_calls 40, recoveries 0, tainted false | +| `nobridge-ungated-L4-T8-d512.json` | root | 0 (0) | true | `host_staged` ran/pass, `sync_file_poll` ran/pass, `r_iif` ran/pass | iif `kernel` / `ungated_nnapi_sync_fence_chain_bridge_unavailable`, requirement_met false, dev_open_calls 2, exec_start_calls 80, recoveries 0, tainted false | +| `neg-nobridge-require-iif-L4-T8-d512.json` | root | 1 (1) | false | `host_staged` ran/pass, `sync_file_poll` ran/pass, `r_iif` ran/pass | iif `kernel` / `ungated_nnapi_sync_fence_chain_bridge_unavailable`, requirement_met false, dev_open_calls 2, exec_start_calls 80, recoveries 0, tainted false | +| `edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json` | root | 0 (0) | true | `host_staged` ran/pass, `sync_file_poll` skip: nnapi_fenced_dmabuf_unavailable_on_edgetpu, `r_iif` skip: nnapi_fenced_dmabuf_unavailable_on_edgetpu | iif `kernel` / `ap_signaled_gate_imported_into_gpu_queue`, requirement_met false, dev_open_calls 2, exec_start_calls 0, recoveries 0, tainted false | +| `iif-probe-only.json` | root | 0 (0) | - | - | dev "/dev/iif", usable true, bridge_dma_ok true, reason "ok"; inotify /dev/iif open events 1 | +| `iif-probe-only-hostile-dev.json` | shell | 0 (0) | - | - | dev "/tmp/iif\"\\test", usable false, bridge_dma_ok false, reason "ENOENT" | +| `smoke-shell-uid-L4-T8-d512.json` | shell | 0 (0) | true | `host_staged` ran/pass, `sync_file_poll` ran/pass, `r_iif` ran/pass | iif `none` / `none`, requirement_met false, dev_open_calls 1, exec_start_calls 80, recoveries 0, tainted false | +| `mock-root-L4-T8-d512.json` | root | 0 (0) | true | `host_staged` ran/pass, `sync_file_poll` ran/pass, `r_iif` ran/pass | iif `sw_emulated` / `sw_emulated`, requirement_met true, dev_open_calls 0, exec_start_calls 0, recoveries 0, tainted false; inotify /dev/iif open events 0 | +| `mock-root-fault-recovery-L4-T8-d512.json` | root | 1 (1) | false | `host_staged` skip: not_selected, `sync_file_poll` skip: error, `r_iif` ran/pass | iif `sw_emulated` / `sw_emulated`, requirement_met true, dev_open_calls 0, exec_start_calls 0, recoveries 1, tainted false; inotify /dev/iif open events 0 | +| `mock-root-fault-tainted-L4-T8-d512.json` | root | 1 (1) | false | `host_staged` skip: not_selected, `sync_file_poll` skip: error, `r_iif` skip: executor_tainted | iif `sw_emulated` / `sw_emulated`, requirement_met false, dev_open_calls 0, exec_start_calls 0, recoveries 1, tainted true; inotify /dev/iif open events 0 | + + +## Open Issue: Intermittent `r_iif` Parity Failure (not fixed by this PR) + +The receipt session above passed every run. An earlier full capture session on this branch (Generation 6; the +Generation 7 changes do not touch the live NNAPI path) had one unexpected exit: in its d = 1024 sweep run the `r_iif` +arm completed every token without an error (no failed hop, nothing to recover) but failed the parity gate, while +`host_staged` and `sync_file_poll` in the same process passed with their usual cosine. That raw output and its session +manifest are kept, hash-verified, under `observed-failures/` and summarized here (generated): + + +- `observed-failures/session3-r_iif-d1024/bench-L12-T64-d1024.json` (session 2026-12-03T03:31:36Z, archived bench SHA-256 `47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca`, exit 1, expected 0; unexpected exits in that session: `bench-L12-T64-d1024.json`): `host_staged` pass = true, cos = 0.999312121, cos_min_tok = 0.999042695, max_abs_err = 0.165879; `sync_file_poll` pass = true, cos = 0.999312121, cos_min_tok = 0.999042695, max_abs_err = 0.165879; `r_iif` pass = false, cos = 0.923857635, cos_min_tok = 0.6395106, max_abs_err = 3.60791; `executor_state` = {"tainted": false, "taint_reason": "", "failure_recoveries": 0, "submissions_retired_after_drain": 0, "ledger_inflight_at_exit": 0, "pool_inflight_slots_at_exit": 0}. + + +A follow-up loop of the same binary (d = 1024 and d = 512 sweep runs, back to back, outside this packet) did not +reproduce it. The Generation 6 changes do not touch the `r_iif` chain's synchronization (the ledger only records the +same pool submissions; recovery runs only after a failed arm), so this looks like a rare pre-existing data race in the +NNAPI fence chain or its cache maintenance, e.g. a consumer reading a tensor before the producer's writes are visible. +It needs its own root-cause investigation; the parity gate does catch it (the run exits non-zero). + +## Failure Recovery Between Arms (Generation 6) + +All arms share one executor and its buffers. Every `fs_iova_pool` submission is recorded in an executor ledger until +its fence retires. When an arm fails, `Executor::recover_after_failure()`: + +1. proves every engine idle: `vkDeviceWaitIdle` must return `VK_SUCCESS` (live), any active `libopenbuenos` context + must drain all in-flight handles (`ob_graph_wait_all == OB_OK`), every started NNAPI hop must have + been waited (`ANeuralNetworksEvent_wait`) and released, and no IIF fence may still be open (an unsignaled imported + gate is intentionally leaked, which also fails here); +2. only then retires the ledger's leftover submissions, and requires every pool slot to be IDLE again (no INFLIGHT or + CANCELED_DRAINING slot). + +If either step fails the executor is **tainted**: `run_arm()` skips every later arm (`skip_reason = +executor_tainted`) before `run_token()` uploads its embedding into `SLOT_X` or touches any other buffer. A successful +arm that would leave a submission in flight is failed and recovered the same way. The JSON reports `executor_state` +and, per failed arm, `recovery = drained_retired | tainted`. + +The mock test seam `--fault-inject-gpu-fence ARM:CALL:LAYER` fails a stage with its GPU slot left INFLIGHT, the shape +of the live bug where a rejected GPU fence short-circuited the slot retire and the next arm hit +`pool submit(chain) rejected`; `--fault-inject-quiesce-fail` makes the drain unable to prove the device idle. Both are +rejected with `--live` (exit 2). On the device, as root: + + +- `mock-root-fault-recovery-L4-T8-d512.json` (exit 1): `sync_file_poll` not run (error), recovery = `drained_retired`; `r_iif` ran, pass = true; `executor_state` = {"tainted": false, "taint_reason": "", "failure_recoveries": 1, "submissions_retired_after_drain": 1, "ledger_inflight_at_exit": 0, "pool_inflight_slots_at_exit": 0}. +- `mock-root-fault-tainted-L4-T8-d512.json` (exit 1): `sync_file_poll` not run (error), recovery = `tainted`; `r_iif` not run (executor_tainted); `executor_state` = {"tainted": true, "taint_reason": "engines not proven idle: injected quiesce failure (device idle cannot be proven)", "failure_recoveries": 1, "submissions_retired_after_drain": 0, "ledger_inflight_at_exit": 1, "pool_inflight_slots_at_exit": 1}. + + +## `--mock` Never Touches the Kernel IIF Driver (Generation 6) + +`iif_probe()` runs only for `--live` and `--iif-probe-only`; `--mock` reports a probe that was not run +(`probe.probed = false`, `reason = not_probed_mock`) and uses only the software fence backend. Every `open(2)` of the +IIF node is counted (`iif.dev_open_calls`). Independently, the capture script ran an `inotifyd` open watch on +`/dev/iif` around the root `--mock` runs and around the `--iif-probe-only` positive control: + + +- `iif-probe-only.json`: 1 open event(s) (expected nonzero) +- `mock-root-L4-T8-d512.json`: 0 open event(s) (expected zero) +- `mock-root-fault-recovery-L4-T8-d512.json`: 0 open event(s) (expected zero) +- `mock-root-fault-tainted-L4-T8-d512.json`: 0 open event(s) (expected zero) +- `mock-root-L4-T8-d512.json`: `iif.backend` = "sw_emulated", `dev_open_calls` = 0, `probe.probed` = false, `probe.reason` = "not_probed_mock"; live sweep runs report `dev_open_calls` = 2 (probe + kept device fd). + + +## Strict Numeric Options (Generation 6) + +Every numeric option is parsed by `fs_tokloop::parse_strict_*`: the whole argument must parse (no leading whitespace, +no trailing bytes, so a U+2212 minus in `--odpm-unit-j` no longer truncates to `1`), `ERANGE`, NaN and Inf are +rejected, unsigned values reject a sign, counts are decimal, `--odpm-unit-j` must be finite and > 0 and `--min-cos` +finite in (0, 1]. Any malformed value exits 2 before anything is measured. The bench no longer calls +`atoi`/`atof`/`atol`. + +## On-Device Unit Test (`unit-test-device.txt`) + + +- uid shell (adb shell), TMPDIR unset: exit 0, all checks passed = true +- uid shell, TMPDIR=: exit 0, all checks passed = true +- uid 0 (su): exit 0, all checks passed = true + + +## Fenced DMA-BUF Execution on the Tensor G6 EdgeTPU (refused before dispatch) + +History (Generation 4 session, pre-final candidate binary, not a receipt): a `--nnapi-mem dmabuf` run selected +`shared_mem = dmabuf_fd`. `host_staged` passed. The first fenced EdgeTPU hop then crashed the vendor NNAPI HAL +(`android.hardware.neuralnetworks@service-darwinn-aidl`, `SIGSEGV`, null read inside the vendor HAL library), +`startComputeWithDependencies` returned `OP_FAILED`, and `init` restarted the HAL. Retiring the crashed hop's pool +slots afterwards cannot undo a crash of a system-wide service. + +Generation 5 therefore refuses the combination **EdgeTPU device x `dmabuf_fd` memory x fenced execution before any +dispatch**. Both `--nnapi-mem dmabuf` and the automatic AHB -> `dmabuf_fd` fallback reach the same guard. The pool +DMA-BUFs are then imported for the GPU only: no `ANeuralNetworksMemory_createFromFd` and no zero-copy executions are +bound. `sync_file_poll` and `r_iif` are skipped with `nnapi_fenced_dmabuf_unavailable_on_edgetpu`, and +`NnEdgeTpu::start()` refuses before creating an event or calling `startComputeWithDependencies`. +`--allow-edgetpu-dmabuf-fenced-probe` (debug only) restores the old dispatch. It was not run. The current receipt is +`edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json` ("Supplementary Runs"; HAL pids under "Health Gate"). + +Completed QUANT8 slot drains in `dmabuf_fd` mode remain unverified on silicon. + +## Live-Silicon Fixes Made During This Run + +1. **Zero-copy tensors must never be CPU-accessed.** With all three arms in one process, + `sync_file_poll` and `r_iif` failed the parity gate by a wide margin whenever + `host_staged` ran first; each zero-copy arm alone passed. A CPU + `AHardwareBuffer_lock` + read of a shared tensor before the zero-copy arm reproduced the + corruption; a lock-only (no access) invalidate cleared it. Fix: `host_staged` copies through + its own CPU-visible AHB bridge tensors and command buffers, so the GPU <-> EdgeTPU tensors + stay device-only (`nnapi.host_staged_mem = "isolated_ahb_blob"` in the JSON). +2. **IIF fence fds are not `sync_file`s.** The `FS_IIF_CREATE_FENCE` fd is + `anon_inode:iif_file`: pollable, but `SYNC_IOC_FILE_INFO` returns `ENOTTY` and Vulkan + `SYNC_FD` import rejects it, so `r_iif` failed at layer 0 with the kernel backend. + `FS_IIF_FENCE_BRIDGE_DMA` returns a new `sync_file` fd (one pending `dma_fence` on the IIF + timeline) that signals with the IIF fence. Fix: `IifFences::bridge_sync_file()` (validated with + `SYNC_IOC_FILE_INFO`), `r_iif` imports the bridged fd, and the probe reports + `fence_is_sync_file=false`, `bridge_sync_file_ok=true`, `bridge_signaled=true`. +3. **The NNAPI runtime must stay resident.** Every live NNAPI run hit `SIGSEGV` at process exit + in a runtime worker thread (`pthread_cond_clockwait` returning into unmapped code) after + `dlclose(libneuralnetworks.so)`. Fix: the library handle is never `dlclose()`d. 0 fatal signals + across the sweep afterwards. + +## Review Repairs (Generation 1 autoreview) + +1. **Descriptor pool budget.** Each layer allocates up to 6 sets (GEMV, RMSNorm, QUANT8 quant and + dequant, isolated `host_staged` quant and dequant). The pool now reserves 6 sets and 24 + storage-buffer descriptors per layer. +2. **Queue-family ownership transfers.** Every command buffer acquires the shared tensors it touches + (`VK_QUEUE_FAMILY_FOREIGN_EXT` -> compute queue family) before its first access and releases them + back after its last one. `VK_EXT_queue_family_foreign` is enabled when the device supports it + (PowerVR does); Generation 2 removed the `VK_QUEUE_FAMILY_EXTERNAL` fallback (item 9). JSON: + `vk_shared_tensor_ownership` (queue family and recorded barriers per size: "Sweep Facts"). +3. **`--require-iif` needs measured IIF use.** The gate now needs `r_iif` to have run with + `iif_fences > 0` and, live, the kernel `/dev/iif` backend. The negative run + (`--iif-sw-fallback`, software backend, 0 IIF fences) exits 1 with `requirement_met = false`. +4. **`host_staged` fails closed.** If the isolated staging tensors cannot be allocated or imported, + the arm is reported as `host_staged_isolated_staging_unavailable`; it never falls back to CPU + access of the zero-copy tensors. +5. **NNAPI execution status.** `ANeuralNetworksEvent_wait` is checked for every fenced EdgeTPU hop: + after the `poll()` in `sync_file_poll` and at the token boundary in `r_iif`, before + `ANeuralNetworksEvent_free`. A failed execution fails the run. +6. **W8A16 `sync_file_poll` polls both hops.** The TPU -> GPU fence is exported with + `DMA_BUF_IOCTL_EXPORT_SYNC_FILE` on the pinned slot fd and `poll()`ed before the next GPU submit. + A failed export fails the hop. Live W8A16 run: 24 polls and 24 `sync_file` exports per token + (2L), 0 GPU-side imports. *(Superseded for `--tpu-backend cpu` by Generation 4, item 18: the CPU output hop has no + producer fence and is no longer exported or polled.)* + +## Review Repairs (Generation 2 autoreview) + +7. **Builds without libopenbuenos.** `LiveExecutor::run_tpu` marks its counter parameter + `(void)c`. Compile matrix under `-Wall -Wextra -Werror`: `arm64-v8a` CMake build with and + without `libopenbuenos` (Vulkan headers on), `-fsyntax-only` for non-Android Linux with and + without `FREESCHED_HAVE_LIBOPENBUENOS`, and the macOS host build. All pass. The parent head also + compiled without libopenbuenos (the fenced CPU path still used `c`), so the attribute is defensive. +8. **Fence wait covers the ownership acquire.** Every `vkQueueSubmit` wait semaphore uses + `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT`. Each recorded command buffer starts with a foreign -> + compute queue-family acquire of the EdgeTPU-written tensors, and legacy ownership acquires run + outside the defined pipeline stages, so a `COMPUTE_SHADER` wait could let the acquire run before + the EdgeTPU fence signals. +9. **Foreign queue-family ownership is required for GPU <-> EdgeTPU sharing.** + `VK_QUEUE_FAMILY_EXTERNAL` is limited to the same physical device and driver, so it cannot + represent the EdgeTPU. Without `VK_EXT_queue_family_foreign` the `openbuenos` / `nnapi` backends + now fail with `VK_EXT_queue_family_foreign unsupported ... GPU<->EdgeTPU zero-copy accelerator path + unavailable`. `--tpu-backend cpu` stays available: its CPU-emulated TPU only touches the DMA-BUFs + from the host (`DMA_BUF_IOCTL_SYNC` + HOST-stage barriers), so tensors stay owned by the compute + queue family, no transfer is recorded, and the JSON reports `queue_family = none_host_only`. + PowerVR exposes the extension, so this run reports `foreign_ext`. +10. **CPU backend counts its host copies.** With `--live --tpu-backend cpu`, the fenced arms copy + each layer's input into `stage_in_` and its result back from `stage_out_`. Both copies now count + in `inter_ip_host_copies`. Live W8A16 run (L = 12, T = 16, d = 512): 24 host copies/token (2L) + for `host_staged`, `sync_file_poll` and `r_iif` (previously reported as 0 for the fenced arms); + `sync_file_poll` 24 polls + 24 `sync_file` exports/token. *(Generation 4: 12 polls + 12 exports, see item 18; + current values: "W8A16 Path".)* + +## Review Repairs (Generation 3 autoreview) + +11. **The NNAPI IIF gate needs a working bridge.** `IifProbe::bridge_dma_ok` is true only when + `FS_IIF_FENCE_BRIDGE_DMA` returned a `sync_file` *and* that fd signaled on `poll()`; it is recorded + separately from raw `/dev/iif` usability (`usable`). Raw kernel IIF stays available for the CPU-proxy + handoffs (`iif_cpu_proxy_available`). The NNAPI arm enables its Vulkan gate only when + `iif_nnapi_gate_enabled(kernel, bridge_dma_ok)`; otherwise it runs the ungated sync-fence chain + (`signal_path = ungated_nnapi_sync_fence_chain_bridge_unavailable`, 0 IIF fences), so `--require-iif` + still rejects it. Live check with `--iif-ioctl-bridge 0x8004697f` (a request the driver does not + implement, `ENOTTY`): probe `usable = true`, `bridge_dma_ok = false`; the run passes without + `--require-iif` (exit 0) and fails with it (exit 1). Unit test `test_iif_raw_without_bridge` covers the + decision table and, as root on the device, the live probe. +12. **Cross-thread wakeup accounting.** `userspace_wakeups` counts only wakeups delivered by another thread. + Inline `poll()`/waits on the submitting thread (the CPU-proxy IIF handoff and the mock fence round trip) count + only in `userspace_fence_polls`. Generation 3 left W8A16 `sync_file_poll` on inline `poll` (0 wakeups). Generation 8 + routes that arm's real sync_files through `FdWaiter` (see item 38); the NNAPI `sync_file_poll` arm still reports + 2L wakeups/token. +13. **Parity description.** See "Method": the cosine gate is measured against the unquantized FP64 + float-activation baseline and includes the INT8 activation quantization error; `arms_max_abs_diff` + checks cross-arm agreement of the quantized outputs. +14. **CTest checks the overall result.** The token-loop tests no longer use `PASS_REGULAR_EXPRESSION`, + which makes CTest ignore the exit code (the old unanchored `"pass":true` also matched nested arms). + The bench exits non-zero unless its top-level `pass` is true. The d2048 smoke relies on that exit + code; content checks use `tests/ctest_run_expect.cmake` (exit 0 *and* match). New negative test + `..._d2048_require_iif_rejects` (both arms pass, `--require-iif` fails the run) must fail. Checked in + a scratch CTest project: the old regex test *passed* that failing run; the exit-code test and + `ctest_run_expect` both fail it. +15. **Android temp directory.** Unit-test fixtures use `fs_temp_dir()`: `$TMPDIR`, then + `/data/local/tmp` when writable, then `/tmp`. `test_token_loop_riif` passes from an unprivileged + `adb shell` (uid `shell`) with and without `TMPDIR`. +16. **Valid JSON for non-finite diagnostics.** Every floating JSON field goes through + `json_finite_or_null()`: `inf`/`nan` (e.g. `max_abs_err` after a NaN, `arms_max_abs_diff`) become + `null` and `pass` stays false. Covered by `test_json_finite_or_null` and a strict `python3` JSON CTest + (`parse_constant` rejects `Infinity`/`NaN`) on the diagnostics document and the mock bench output. + +## Review Repairs (Generation 4 autoreview) + +17. **The IOVA proof tracks the actual NNAPI handoff buffers.** The EdgeTPU is no longer recorded against the FP32 + `out` slot. Each stage submits the pool slots it actually touches: the GPU's FP32 `mid(l)` / `out(l)` writes and, + in `dmabuf_fd` mode, the EdgeTPU's QUANT8 `qmid` / `qout` slots (also in the `r_iif` chain, up to 8 INFLIGHT slots). + In AHB mode the JSON scopes the result explicitly (`iova_observation_scope`, `ahb_hot_loop_allocs`, + `nnapi_ahb_memories_registered_before_hot_loop`); see "IOVA Observation Scope". A failed NNAPI hop retires its + QUANT8 slots once drained, so the next arm reports its own result instead of `pool submit(chain) rejected`. +18. **The CPU W8A16 output hop is synchronous.** With `--tpu-backend cpu` the CPU writes `Y[l]` inside its + `DMA_BUF_IOCTL_SYNC` bracket before the handoff, so no producer fence exists. `sync_file_poll` no longer exports and + polls the DMA-BUF reservation fence (which could only be an already-signaled stub), and `r_iif` no longer creates + a CPU-proxy IIF for that hop. Both count it in `synchronous_cpu_hops_per_tok` instead of `fence_handoffs_per_tok`. + Live W8A16 receipt: `fence_handoffs_per_tok = 12` (GPU -> CPU, Vulkan `SYNC_FD`) and + `synchronous_cpu_hops_per_tok = 12` for both fenced arms (previously 24 fenced handoffs). `sync_file_poll`: 12 + polls + 12 exports/token. `r_iif`: 12 kernel IIF fences + 24 inline polls/token (current values: "W8A16 Path"). + The libopenbuenos branch, which is not exercised on Tensor G6, is unchanged. +19. **Consistent synchronization timing.** `sync_us_per_tok` is replaced by `host_wait_us_per_tok` and + `dispatch_submit_us_per_tok`, which use identical interval definitions in every arm and in the mock executor. The + `r_iif` whole-chain duration moves to its own field, `pipelined_chain_us_per_tok`. See "Timing Fields". +20. **Every JSON string is escaped.** `--iif-dev` (and the probe reason) go through `fs_tokloop::json_escape()` in the + new `iif_probe_json()`. So does every other JSON string value the bench prints (including the user-supplied + `tpu_backend_requested`); there are no raw `"%s"` string fields left in the JSON emitters. Coverage: + - `test_json_escape`, which checks the escaped form of `"/tmp/iif\"\\test"` plus control characters; + - a strict `python3` JSON CTest of that probe document; + - a bench CTest running `--iif-probe-only --iif-dev '/tmp/iif"\test'` and checking that `dev` round-trips; + - the on-device `iif-probe-only-hostile-dev.json` receipt. + +## Review Repairs (Generation 5 autoreview) + +21. **[P2] Fenced DMA-BUF execution is disabled on the affected EdgeTPU driver.** See "Fenced DMA-BUF Execution on + the Tensor G6 EdgeTPU". `nnapi_fenced_dmabuf_block_reason()` matches the device name `edgetpu` without regard to + case. Both the `LiveExecutor` arm gate and `NnEdgeTpu::start()` enforce it, and `start()` checks it before any + NNAPI call. The JSON reports `nnapi.fenced_dmabuf_policy`, `allow_edgetpu_dmabuf_fenced_probe`, + `fenced_dmabuf_refusals` and `exec_start_calls`. + + `test_nnapi_edgetpu_dmabuf_fenced_guard` drives the shared `start()` path through a host-only `NnEdgeTpu` test + seam with counting mock entry points: + - `google-edgetpu` + `dmabuf` is refused with and without a dependency fd; + - neither `exec_start_deps_` nor `event_from_fd_` is ever called; + - AHB memory and the debug probe each dispatch exactly once. +22. **[P3] Sync-file status is checked before producer output is consumed.** `poll_sync_fd()` and `FdWaiter` both + call `fs_tokloop::sync_fd_wait_handoff()`. It requires `poll(POLLIN)` without `POLLERR`/`POLLNVAL`, then + `SYNC_IOC_FILE_INFO` with `status == 1`. `status < 0` is a fence error and `0` means unsignaled; both fail the hop. + `struct sync_file_info` is 56 bytes on every ABI, so `_IOWR('>', 4, ...) = 0xc0383e04`; static_asserts check + both the size and the encoding. `ENOTTY`/`EINVAL` (not a `sync_file`) fails every live handoff. It is accepted only + in an explicit `SYNC_FD_MOCK_NON_SYNC_FILE` mode for pipe/eventfd stand-ins. On uid `shell` (SELinux `EACCES`) + the check fails closed. + + Unit coverage: `test_sync_handoff_verdict` covers `-EIO`, `-ECANCELED`, 0, `POLLERR`/`POLLNVAL`, timeout and + `ENOTTY`/`EINVAL` in kernel vs. mock mode, plus a real pipe. + + Live (root) coverage: `test_iif_errored_bridge_rejected` signals an AP IIF fence with `-EIO`. Its + `FS_IIF_FENCE_BRIDGE_DMA` `sync_file` is readable (`poll` rc = 1, `revents = POLLIN`), but + `SYNC_IOC_FILE_INFO.status = -5`, so the handoff is rejected (`fence_error_status`). The cleanly signaled bridge + reports `status = 1` and is accepted. This shows that a readable `sync_file` alone would have passed a failed + producer fence on this kernel. +23. **[P3] The NNAPI submission timer starts after dependency setup.** The `startComputeWithDependencies` timer now + starts after `ANeuralNetworksEvent_createFromSyncFenceFd`. `nnapi_start_block_us_per_tok` and + `dispatch_submit_us_per_tok` therefore time the same call in `sync_file_poll` and `r_iif`. Dependency-event + creation moves to `nnapi_dep_event_create_us_per_tok` (live values: "Synchronization timing"). + + Mock check: a mock `event_from_fd` that sleeps 30 ms reports `dep_event_create_us` of about 30 ms and + a `block_us` far below it. +24. **[P3] Wrapped CTest cases use the configured emulator.** When `CMAKE_CROSSCOMPILING` and + `CMAKE_CROSSCOMPILING_EMULATOR` are set, the emulator list is passed through to both wrappers: + - '|'-joined as `-DEMULATOR=` to `tests/ctest_run_expect.cmake`, which prepends it to `CMD`; + - one `--emulator-arg=` per element to `tests/token_loop_json_check.py`, which prepends it to every target + it launches. + + Scratch configurations used `CMAKE_SYSTEM_NAME=Darwin`: + - `"/usr/bin/env;--"`: 14/14 token-loop tests pass. + - A logging emulator (`/bin/sh;log-emu.sh;--fs-marker`, which checks its marker argument) recorded 14 launches: + 3 CMake-wrapped, 4 Python-wrapped and 7 direct. + - A rejecting emulator fails all 10 positive token-loop tests. + +## Review Repairs (Generation 6 autoreview) + +25. **[P2] Drain failed GPU work before running the next arm.** See "Failure Recovery Between Arms". Every + early-return path of `host_staged`, `sync_file_poll` and `r_iif` (NNAPI and W8A16/CPU) leaves its unretired + submissions in the ledger, so recovery covers them without per-path cleanup; `quiesce()` also fails closed on any + NNAPI hop that was never released or IIF fence that is still open. CTest `volcanic_tpu_token_loop_bench_failure_recovery`. +26. **[P3] Keep mock runs out of the kernel IIF driver.** See "`--mock` Never Touches the Kernel IIF Driver". Unit test + `test_iif_probe_not_run`; CTest `volcanic_tpu_token_loop_bench_mock_never_opens_iif`. +27. **[P3] Validate the ODPM energy conversion factor.** See "Strict Numeric Options". Unit test + `test_strict_cli_parsing`; CTest `volcanic_tpu_token_loop_bench_strict_args_exit2` (exact exit code 2) and the + `..._rejects_odpm_unicode_minus` / `_odpm_zero` / `_odpm_nan` / `_layers_trailing` cases. +28. **[P3] Reconcile the receipt with its raw results.** See "How This Packet Is Produced". The supplementary W8A16 + summary that disagreed with its raw file was hand-copied from a different run; every receipt and PROOF.md value is + now generated from the checked-in raw files and verified in CTest. + +## Review Repairs (Generation 7 autoreview) + +29. **[P2] Drain `libopenbuenos` before reusing shared tensor slots.** `LiveExecutor::quiesce()` calls + `ob_graph_wait_all(ob_, 0u)` whenever an `ob_` context is active; any non-`OB_OK` return fails the drain and taints + the executor before `recover_after_failure()` can retire in-flight pool slots. +30. **[P2] Require a newly created directory before recursive device cleanup.** `scripts/token_loop_capture.py` + normalizes `--device-dir` with `posixpath.normpath`, requires a single safe child under `/data/local/tmp`, creates + it with exclusive `mkdir --` (without `-p`), and enables `rm -rf --` cleanup only after `mkdir` exits 0. +31. **[P3] Fail health capture when device logs cannot be read.** `Device.text()` checks command exit codes by default; + pre- and post-session `dmesg` and `logcat -b crash -d` snapshot failures abort capture, and `session.json` records + both exit codes (verified by `token_loop_receipt.py check`). +32. **[P3] Fail capture when an on-device unit test exits unsuccessfully.** `session.json` records each on-device unit + test's exit code and pass banner, `overall_ok` and the process exit code require every unit test to pass, and + `token_loop_receipt.py check` reconciles them with `unit-test-device.txt`. +33. **[P3] Require raw output for each recorded unexpected exit.** `scripts/token_loop_receipt.py` requires every + archived `observed-failures/` manifest entry with an unexpected exit (or failed pass state) to have its raw file on + disk matching `stdout_sha256` in both `write` and `check`, while successful runs remain manifest-only. Unit-tested + in CTest `token_loop_proof_scripts_unit`. + +## Review Repairs (Generation 8 autoreview) + +34. **[P2] Faults fail the proof health gate.** `new_kernel_faults`, `new_crash_entries` and `hal_pids_unchanged` + (zero HAL restarts, including the DMA-BUF guard window) are part of capture `overall_ok` and of + `token_loop_receipt.py check`. SELinux denials stay classified, but a subsystem or generic kernel fault line + fails the session. +35. **[P3] Mock fence waits do not ioctl.** `SYNC_FD_MOCK_NON_SYNC_FILE` is poll readiness only. Real kernel + sync_files always run `SYNC_IOC_FILE_INFO` and require `status == 1`. The mode is explicit, so Android shell + `EACCES` on a mock pipe is not treated as a failed handoff. `test_token_loop_riif` covers both. +36. **[P3] Negative proofs are checked structurally.** `write` and `check` parse each negative run. A `--require-iif` + rejection must be an arm that itself passed with `requirement_met = false`. The `--nnapi-mem dmabuf` guard must + pass `host_staged` and skip both fenced arms with `nnapi_fenced_dmabuf_unavailable_on_edgetpu`. +37. **[P3] Validate, then replace.** `write` checks hashes, exit codes, unit tests, the health gate and those + negative-run reasons before it opens `receipt.json` or `PROOF.md`, and it publishes both through a temp file + and `os.replace`. +38. **[P3] W8A16 `sync_file_poll` uses `FdWaiter`.** `g2t != -1` and a libopenbuenos `t2g != -1` are waited on the + waiter thread (L wakeups/tok on `--tpu-backend cpu`, 2L on libopenbuenos). The W8A16 `r_iif` arm skips + `poll_sync_fd_timed` when `vkGetSemaphoreFdKHR` reports an already-signaled fence (`g2t == -1`). +39. **[P2] An imported IIF gate is released before any idle wait.** If signaling that gate fails, recovery does not + call `vkQueueWaitIdle` or `vkDeviceWaitIdle`. It uses a bounded `vkWaitForFences`, taints the executor, and + leaves in-flight slots unretired. Shutdown skips the unbounded wait in that state. +40. **[P3] A failed SYNC_FD export replaces the binary semaphore.** After `vkQueueSubmit` signals it and + `vkGetSemaphoreFdKHR` fails, the semaphore is destroyed and recreated once `vkDeviceWaitIdle` succeeds. A failed + drain or recreate taints the executor so a later arm cannot signal it again. +41. **[P3] NNAPI host time is not hardware time.** `tpu_hw_us_per_tok` is null unless hardware EdgeTPU execution was + measured. Synchronous `ANeuralNetworksExecution_compute` is `nnapi_sync_call_us_per_tok` and is null on fenced arms. +42. **[P3] Host-verify finds the NDK clang for this machine.** `darwin-arm64`, `darwin-x86_64` and `linux-x86_64` + (and any other prebuilt directory that contains `clang++`) are probed. `--ndk-cxx` overrides the probe. + +## Review Repairs (Generation 9 autoreview) + +43. **[P2] Staged capture preserves previous outputs until the session passes.** `scripts/token_loop_capture.py` + writes every run output, unit transcript and `session.json` into a fresh sibling staging directory (or + `--staging-dir` outside `--out`), and publishes into `--out` via backup + `os.replace` (with `session.json` + last) only after `overall_ok` is true. Failed captures leave pre-existing `--out` untouched and retain the + staging directory for investigation. +44. **[P3] Timestamped crash-buffer cursor survives ring-buffer rollover.** Capture reads the device wall-clock + timestamp before the session and queries `logcat -b crash -T -d` before and after (stripping + `--------- beginning of ...` headers), so new crash entries are detected even if the ring buffer rolls over. + `token_loop_receipt.py check` requires `cursor_mode = "logcat_T"`, a valid timestamp and exit code 0. +45. **[P3] HAL PID snapshots require valid non-empty numeric PIDs.** Capture records `pidof` exit codes alongside all + four snapshots, and both `token_loop_capture.py` and `token_loop_receipt.py check` require exit code 0 and a + non-empty list of positive integer PIDs for every snapshot (empty strings never pass as unchanged). +46. **[P3] Host-verify validates both arm64 CMake configurations.** `verify_arm64_matrix` requires distinct build + directories, parses each `CMakeCache.txt` (repo root, Android `arm64-v8a`, NDK, opposite `libopenbuenos` + settings), runs `cmake --build` on both targets, checks ELF64 AArch64 headers and requires distinct bench hashes. +47. **[P2] NNAPI and Vulkan fence timeout recovery stays bounded.** Timeout verdicts from `vkWaitForFences` + (`VK_TIMEOUT`), `wait_on_waiter` and `poll_sync_fd_timed` taint the executor immediately, skip unbounded + `ANeuralNetworksEvent_wait`, `vkQueueWaitIdle` and `vkDeviceWaitIdle`, and keep unproven slots and NNAPI + objects quarantined. Covered by `--fault-inject-fence-timeout` in CTest and `test_nnapi_timeout_recovery_bounded`. +48. **[P2] NNAPI completion polling is counted once in `host_wait_us`.** In live NNAPI `sync_file_poll`, the + `check_done` / `wait_done` timer now starts after `wait_on_waiter()` returns so the TPU completion poll is not + double-counted. + +## Review Repairs (Generation 10 autoreview) + +49. **[P2] Privileged capture runs only from a root-controlled directory.** `scripts/token_loop_capture.py` pushes + into an exclusive shell staging directory, copies the binaries into an exclusive root-owned private directory + under `/data/local/freesched-root-capture/` (no `-p`), immediately removes the shell push-staging + directory, verifies SHA-256 as root before execution, and runs every `su` bench, unit test and `inotifyd` watch + exclusively from that root directory. Unprivileged `shell` runs execute from a root-owned read-execute directory + copied from the verified root binaries. +50. **[P2] Staged captures run full receipt validation before publish.** Before replacing `--out`, capture invokes + `token_loop_receipt.validate_staged_capture()` on the staging directory (hashes, health gate, unit tests, IIF + open watches, positive and negative structured outcomes) and publishes only when validation returns zero errors. +51. **[P3] Archived failures without valid JSON are preserved.** The `observed-failures/` loader verifies the raw + file's SHA-256 first and handles empty or partial non-JSON stdout gracefully (`json_parsed = false`, exit code, + byte count and parse error) instead of failing `write` or `check`. +52. **[P3] Host-verify proves ASan and UBSan instrumentation.** `verify_asan_ubsan_build_dir()` requires + `--asan-build` to be distinct from `--host-build`, checks `CMakeCache.txt` for both `address` and `undefined` + sanitizer flags, and inspects the compiled test binaries for both ASan and UBSan runtime symbols before recording + an ASan + UBSan pass. +53. **[P2] Synchronous `libopenbuenos` TPU completion is not counted as a fenced handoff.** Because + `ob_gemm_matmul_f32_w8a16_dmabuf()` waits synchronously before returning, the `libopenbuenos` W8A16 path no + longer exports or polls a DMA-BUF fence (or creates a no-op proxy IIF) after it; both fenced arms report + `synchronous_tpu_hops_per_tok = L` and `fence_handoffs_per_tok = L` (GPU -> TPU only). +54. **[P2] `libopenbuenos` weight caches are pre-warmed before hot-loop entry.** `init_ob()` runs one + `ob_gemm_matmul_f32_w8a16_dmabuf()` pass across all L layers before `fs_iova_pool_enter_hot_loop()` (even when + `--warmup` is zero), records `ob_prewarmed_layers`, and reports + `iova_observation_scope = "vulkan_pool_only_openbuenos_weights_external"`. + +## Review Repairs (Generation 12 autoreview) + +55. **[P2] Keep privileged file operations out of shell-writable directories.** `scripts/token_loop_capture.py` + creates an exclusive root-owned session directory under `/data/local/freesched-root-capture/` (traversal-only + for `shell`) with a private root execution subdirectory, a root-owned read-execute `shell-exec` subdirectory and a + `shell`-owned `shell-tmp` subdirectory. Binaries are streamed from the host over stdin (`base64 -d`) directly into + the root directory and verified by SHA-256; `su` never reads, writes, `chmod`s or `chown`s inside + `/data/local/tmp`. +56. **[P2] Require the GPU-NNAPI EdgeTPU path in the proof sweep.** The live smoke and L=12 proof sweep explicitly + pin `--tpu-backend nnapi`, and `validate_capture()` / `validate_staged_capture()` enforce + `tpu_backend = "nnapi"`, `tpu_backend_requested = "nnapi"`, an EdgeTPU NNAPI device at feature level >= 30, + zero-copy AHB memory, kernel `r_iif` IIF bridge gating and zero unfenced hops. +57. **[P3] Verify sanitizer flags on compilation before recording a pass.** `verify_asan_ubsan_build_dir()` inspects + only CMake CXX compilation flags (plus `flags.make` / `compile_commands.json` when present), rejects linker-only + or negated flags, and requires actual compiler-inserted `__asan_report_` and `__ubsan_handle_` call symbols in + the compiled test binaries rather than linked runtime library names. +58. **[P2] Prevent NNAPI fallback from bypassing the `r_iif` fence timeout.** `NnEdgeTpu::init()` queries + `ANeuralNetworksDevice_getFeatureLevel` and requires an accelerator device at feature level >= 30 + (`ANEURALNETWORKS_FEATURE_LEVEL_4`) before enabling fenced execution, recording `nnapi.device_feature_level` in + JSON and refusing fenced dispatch before any NNAPI call when the feature level is below 30 or unavailable. + +## Health Gate + + +- NNAPI EdgeTPU HAL pids: before `9820 9829`, before the DMA-BUF guard run `9820 9829`, after it `9820 9829`, at the end `9820 9829`. DMA-BUF guard run: `shared_mem` = "dmabuf_fd", `fenced_dmabuf_policy` = "blocked_edgetpu_before_dispatch", `exec_start_calls` = 0. +- Kernel log (1095 new lines, every line classified): GPU / EdgeTPU / IIF / DMA-BUF fault or error lines: 0; generic kernel fault lines: 0; other subsystem lines (e.g. EdgeTPU power up/down): 352; SELinux denials: `u:r:gxp_logging:s0 -> u:object_r:traced_producer_socket:s0` x2, `u:r:hal_camera_default:s0 -> u:object_r:traced_producer_socket:s0` x6, `u:r:hal_health_default:s0 -> u:object_r:fwk_stats_service:s0` x4, `u:r:hal_neuralnetworks_darwinn:s0 -> u:object_r:traced_producer_socket:s0` x2, `u:r:mediacodec_google:s0 -> u:object_r:traced_producer_socket:s0` x2, `u:r:shell:s0 -> u:object_r:iif_device:s0` x3, `u:r:shell:s0 -> u:object_r:shell_data_file:s0` x1, `u:r:shell:s0 -> u:object_r:sysfs_iio_devices:s0` x3, `u:r:shell:s0 -> u:r:shell:s0` x2. Crash buffer (since `12-03 16:48:46.861`): 0 new entries. +- Leftover bench/test processes: "". Session directory `/data/local/freesched-root-capture/fs59g13` removed (`ls: /data/local/freesched-root-capture/fs59g13: No such file or directory`); the 15 pre-existing `/data/local/tmp` entries are unchanged: true. + + +## Host & Audit Verification (`host-verification.json`) + + +| Check | Result | +| --- | --- | +| `ctest` (host, Release; all tests except this reconciliation test, which checks the file it would be recorded in) | PASS, 67/67 | +| ASan + UBSan `ctest -R token_loop` (`halt_on_error=1`) | PASS, 22/22 | +| `./scripts/clean-room-audit.sh` | PASS, 0 errors | +| `arm64-v8a` CMake build with `libopenbuenos` (NDK `27.3.13750724`, `-Wall -Wextra -Werror`) | PASS: bench `556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705`, unit test `c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9` | +| `arm64-v8a` CMake build without `libopenbuenos` (NDK `27.3.13750724`, `-Wall -Wextra -Werror`) | PASS: bench `a0b03fcec656e1e089a9873c0c89b8421f6c504fff2e410715de086d9376902e`, unit test `6926645c9511c26f1fdd1677efa3ee62a3993823a01003677d64c910387f6dc4` | +| Non-Android Linux `-fsyntax-only` (bench; NDK clang, `__ANDROID__` undefined) | PASS | +| Non-Android Linux `-fsyntax-only` (bench + `FREESCHED_HAVE_LIBOPENBUENOS`; NDK clang, `__ANDROID__` undefined) | PASS | +| Non-Android Linux `-fsyntax-only` (unit test; NDK clang, `__ANDROID__` undefined) | PASS | + diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d1024.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d1024.json new file mode 100644 index 0000000..dac7112 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d1024.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":96},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":1632},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":12,"tokens":64,"warmup":4,"d_model":1024,"min_cos":0.995000,"handoffs_per_tok":24,"iova_pool":{"slots":34,"weight_slots":12,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":80,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":3536,"completed_drains":3536,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ap_signaled_gate_imported_into_gpu_queue","gpu_gate":true,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":28.934808,"ms_per_tok_p50":34.749688,"ms_per_tok_p99":38.490922,"ms_per_tok_mean":34.384400,"j_per_tok_gpu":0.00337757812,"j_per_tok_tpu":0.00168639062,"j_per_tok_vsys":0.146782047,"odpm_rails":32,"cpu_ctx_switches_per_tok":26.3125,"voluntary_ctxt_switches_per_tok":25.5938,"nonvoluntary_ctxt_switches_per_tok":0.7188,"ctx_switches_all_threads_per_tok":27.0156,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999312121,"cos_min_tok":0.999042695,"max_abs_err":0.165879,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":16274.261,"dispatch_submit_us_per_tok":693.066,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":16721.650,"expected_handoffs_per_tok":24},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":41.193422,"ms_per_tok_p50":23.879411,"ms_per_tok_p99":28.569999,"ms_per_tok_mean":24.100255,"j_per_tok_gpu":0.00311964062,"j_per_tok_tpu":0.001272125,"j_per_tok_vsys":0.107609578,"odpm_rails":32,"cpu_ctx_switches_per_tok":51.9219,"voluntary_ctxt_switches_per_tok":48.9062,"nonvoluntary_ctxt_switches_per_tok":3.0156,"ctx_switches_all_threads_per_tok":90.8438,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999312121,"cos_min_tok":0.999042695,"max_abs_err":0.165879,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":24.000,"userspace_wakeups_per_tok":24.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":9111.110,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":13468.836,"dispatch_submit_us_per_tok":10209.799,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":45.415103,"ms_per_tok_p50":21.833828,"ms_per_tok_p99":27.679192,"ms_per_tok_mean":21.885905,"j_per_tok_gpu":0.00294203125,"j_per_tok_tpu":0.00117323438,"j_per_tok_vsys":0.0986188594,"odpm_rails":32,"cpu_ctx_switches_per_tok":40.0156,"voluntary_ctxt_switches_per_tok":23.0938,"nonvoluntary_ctxt_switches_per_tok":16.9219,"ctx_switches_all_threads_per_tok":41.6562,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999312121,"cos_min_tok":0.999042695,"max_abs_err":0.165879,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":1.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":13.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":6919.222,"nnapi_dep_event_create_us_per_tok":17.975,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":6478.652,"dispatch_submit_us_per_tok":14917.961,"pipelined_chain_us_per_tok":21396.186,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d2048.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d2048.json new file mode 100644 index 0000000..bd6034c --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d2048.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":96},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":1632},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":12,"tokens":64,"warmup":4,"d_model":2048,"min_cos":0.995000,"handoffs_per_tok":24,"iova_pool":{"slots":34,"weight_slots":12,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":80,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":3536,"completed_drains":3536,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ap_signaled_gate_imported_into_gpu_queue","gpu_gate":true,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":10.492630,"ms_per_tok_p50":95.774816,"ms_per_tok_p99":106.042352,"ms_per_tok_mean":95.071838,"j_per_tok_gpu":0.0182789219,"j_per_tok_tpu":0.00464123437,"j_per_tok_vsys":0.419996125,"odpm_rails":32,"cpu_ctx_switches_per_tok":28.8281,"voluntary_ctxt_switches_per_tok":26.2812,"nonvoluntary_ctxt_switches_per_tok":2.5469,"ctx_switches_all_threads_per_tok":30.7188,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999263834,"cos_min_tok":0.999076329,"max_abs_err":0.191573,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":66629.519,"dispatch_submit_us_per_tok":1223.696,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":25844.419,"expected_handoffs_per_tok":24},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":11.770540,"ms_per_tok_p50":84.330701,"ms_per_tok_p99":95.602603,"ms_per_tok_mean":84.730071,"j_per_tok_gpu":0.0179781719,"j_per_tok_tpu":0.00419584375,"j_per_tok_vsys":0.383372375,"odpm_rails":32,"cpu_ctx_switches_per_tok":52.2344,"voluntary_ctxt_switches_per_tok":46.0938,"nonvoluntary_ctxt_switches_per_tok":6.1406,"ctx_switches_all_threads_per_tok":96.6250,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999263834,"cos_min_tok":0.999076329,"max_abs_err":0.191573,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":24.000,"userspace_wakeups_per_tok":24.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":13239.781,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":69793.019,"dispatch_submit_us_per_tok":14426.815,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":13.076028,"ms_per_tok_p50":76.169400,"ms_per_tok_p99":85.628775,"ms_per_tok_mean":76.269359,"j_per_tok_gpu":0.0177053437,"j_per_tok_tpu":0.003883875,"j_per_tok_vsys":0.354426047,"odpm_rails":32,"cpu_ctx_switches_per_tok":58.1406,"voluntary_ctxt_switches_per_tok":41.8594,"nonvoluntary_ctxt_switches_per_tok":16.2812,"ctx_switches_all_threads_per_tok":60.8906,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999263834,"cos_min_tok":0.999076329,"max_abs_err":0.191573,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":1.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":13.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":9616.854,"nnapi_dep_event_create_us_per_tok":22.310,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":58565.004,"dispatch_submit_us_per_tok":17078.080,"pipelined_chain_us_per_tok":75603.246,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d512.json new file mode 100644 index 0000000..a063e84 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/bench-L12-T64-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":96},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":1632},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":12,"tokens":64,"warmup":4,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":24,"iova_pool":{"slots":34,"weight_slots":12,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":80,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":3536,"completed_drains":3536,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ap_signaled_gate_imported_into_gpu_queue","gpu_gate":true,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":35.766218,"ms_per_tok_p50":27.321051,"ms_per_tok_p99":32.869062,"ms_per_tok_mean":27.795048,"j_per_tok_gpu":0.00155890625,"j_per_tok_tpu":0.00121809375,"j_per_tok_vsys":0.109674187,"odpm_rails":32,"cpu_ctx_switches_per_tok":25.1250,"voluntary_ctxt_switches_per_tok":25.0000,"nonvoluntary_ctxt_switches_per_tok":0.1250,"ctx_switches_all_threads_per_tok":25.9219,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999396411,"cos_min_tok":0.999128363,"max_abs_err":0.153796,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":11535.667,"dispatch_submit_us_per_tok":701.375,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":14849.754,"expected_handoffs_per_tok":24},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":53.302744,"ms_per_tok_p50":18.513370,"ms_per_tok_p99":22.315171,"ms_per_tok_mean":18.588934,"j_per_tok_gpu":0.001231125,"j_per_tok_tpu":0.00093884375,"j_per_tok_vsys":0.0763692656,"odpm_rails":32,"cpu_ctx_switches_per_tok":52.0938,"voluntary_ctxt_switches_per_tok":49.0156,"nonvoluntary_ctxt_switches_per_tok":3.0781,"ctx_switches_all_threads_per_tok":90.9375,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999396411,"cos_min_tok":0.999128363,"max_abs_err":0.153796,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":24.000,"userspace_wakeups_per_tok":24.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":8903.161,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":8251.997,"dispatch_submit_us_per_tok":9928.575,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":56.785738,"ms_per_tok_p50":17.114938,"ms_per_tok_p99":21.663515,"ms_per_tok_mean":17.486363,"j_per_tok_gpu":0.0012400625,"j_per_tok_tpu":0.000886,"j_per_tok_vsys":0.0752817031,"odpm_rails":32,"cpu_ctx_switches_per_tok":36.5156,"voluntary_ctxt_switches_per_tok":19.9531,"nonvoluntary_ctxt_switches_per_tok":16.5625,"ctx_switches_all_threads_per_tok":38.1094,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999396411,"cos_min_tok":0.999128363,"max_abs_err":0.153796,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":1.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":13.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":6767.988,"nnapi_dep_event_create_us_per_tok":16.904,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":3207.209,"dispatch_submit_us_per_tok":13841.450,"pipelined_chain_us_per_tok":17040.323,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json new file mode 100644 index 0000000..903603b --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":32},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"dmabuf_fd","shared_mem_fallback":"nnapi_fenced_dmabuf_unavailable_on_edgetpu (google-edgetpu): fenced dmabuf_fd execution is disabled before dispatch; pass --allow-edgetpu-dmabuf-fenced-probe to probe it","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":false,"fenced_api":true,"fenced_dmabuf_policy":"blocked_edgetpu_before_dispatch","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":0},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":80,"completed_drains":80,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"full_pool_dmabuf","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":0},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ap_signaled_gate_imported_into_gpu_queue","gpu_gate":true,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":false,"requirement_met":false,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":96.279542,"ms_per_tok_p50":10.168151,"ms_per_tok_p99":11.231770,"ms_per_tok_mean":10.195725,"j_per_tok_gpu":0.00026725,"j_per_tok_tpu":0.000144625,"j_per_tok_vsys":0.0418225,"odpm_rails":32,"cpu_ctx_switches_per_tok":9.0000,"voluntary_ctxt_switches_per_tok":9.0000,"nonvoluntary_ctxt_switches_per_tok":0.0000,"ctx_switches_all_threads_per_tok":9.3750,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":8.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":20.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":4375.331,"dispatch_submit_us_per_tok":292.449,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":5229.467,"expected_handoffs_per_tok":8},{"arm":"sync_file_poll","ran":false,"pass":false,"skip_reason":"nnapi_fenced_dmabuf_unavailable_on_edgetpu"},{"arm":"r_iif","ran":false,"pass":false,"skip_reason":"nnapi_fenced_dmabuf_unavailable_on_edgetpu"}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/host-verification.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/host-verification.json new file mode 100644 index 0000000..041751d --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/host-verification.json @@ -0,0 +1,37 @@ +{ + "schema": "freesched.proof.host_verification/v1", + "checks": [ + { + "check": "`ctest` (host, Release; all tests except this reconciliation test, which checks the file it would be recorded in)", + "result": "PASS, 67/67" + }, + { + "check": "ASan + UBSan `ctest -R token_loop` (`halt_on_error=1`)", + "result": "PASS, 22/22" + }, + { + "check": "`./scripts/clean-room-audit.sh`", + "result": "PASS, 0 errors" + }, + { + "check": "`arm64-v8a` CMake build with `libopenbuenos` (NDK `27.3.13750724`, `-Wall -Wextra -Werror`)", + "result": "PASS: bench `556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705`, unit test `c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9`" + }, + { + "check": "`arm64-v8a` CMake build without `libopenbuenos` (NDK `27.3.13750724`, `-Wall -Wextra -Werror`)", + "result": "PASS: bench `a0b03fcec656e1e089a9873c0c89b8421f6c504fff2e410715de086d9376902e`, unit test `6926645c9511c26f1fdd1677efa3ee62a3993823a01003677d64c910387f6dc4`" + }, + { + "check": "Non-Android Linux `-fsyntax-only` (bench; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" + }, + { + "check": "Non-Android Linux `-fsyntax-only` (bench + `FREESCHED_HAVE_LIBOPENBUENOS`; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" + }, + { + "check": "Non-Android Linux `-fsyntax-only` (unit test; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" + } + ] +} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/iif-probe-only-hostile-dev.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/iif-probe-only-hostile-dev.json new file mode 100644 index 0000000..e10c883 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/iif-probe-only-hostile-dev.json @@ -0,0 +1 @@ +{"dev":"/tmp/iif\"\\test","probed":true,"node_present":false,"opened":false,"create_ok":false,"submit_ok":false,"signal_ok":false,"wait_ok":false,"usable":false,"open_errno":2,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":0,"reason":"ENOENT","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/iif-probe-only.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/iif-probe-only.json new file mode 100644 index 0000000..3b88973 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/iif-probe-only.json @@ -0,0 +1 @@ +{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-L4-T8-d512.json new file mode 100644 index 0000000..34d0609 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"mock","executor":"mock_cpu","gpu":"cpu_emulated","vk_shared_tensor_ownership":{"queue_family":"none","release_acquire_barriers_recorded":0},"tpu_backend":"cpu_emulated","tpu_backend_requested":"auto","tpu_numerics":"w8a16_f32","tpu_backend_fallback":"","nnapi":{"device":"","device_feature_level":null,"shared_mem":"none","shared_mem_fallback":"","host_staged_mem":"none","host_staged_mem_fallback":"","reusable_executions":false,"fenced_api":false,"fenced_dmabuf_policy":"not_applicable","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":0},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.999900,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":240,"completed_drains":240,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"full_pool_mock","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":0},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"sw_emulated","signal_path":"sw_emulated","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":0,"probe":{"dev":"/dev/iif","probed":false,"node_present":false,"opened":false,"create_ok":false,"submit_ok":false,"signal_ok":false,"wait_ok":false,"usable":false,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":0,"reason":"not_probed_mock","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":112.714695,"ms_per_tok_p50":7.855261,"ms_per_tok_p99":13.448724,"ms_per_tok_mean":8.745192,"j_per_tok_gpu":0.000216,"j_per_tok_tpu":0,"j_per_tok_vsys":0.0216235,"odpm_rails":32,"cpu_ctx_switches_per_tok":0.0000,"voluntary_ctxt_switches_per_tok":0.0000,"nonvoluntary_ctxt_switches_per_tok":0.0000,"ctx_switches_all_threads_per_tok":0.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999960,"cos_min_tok":0.999999949,"max_abs_err":0.00105947,"inter_ip_host_copies_per_tok":8.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":20.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":0.000,"dispatch_submit_us_per_tok":0.000,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":99.762157,"ms_per_tok_p50":8.821302,"ms_per_tok_p99":14.494921,"ms_per_tok_mean":9.883742,"j_per_tok_gpu":0.000221375,"j_per_tok_tpu":0,"j_per_tok_vsys":0.02125775,"odpm_rails":32,"cpu_ctx_switches_per_tok":0.0000,"voluntary_ctxt_switches_per_tok":0.0000,"nonvoluntary_ctxt_switches_per_tok":0.0000,"ctx_switches_all_threads_per_tok":0.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999960,"cos_min_tok":0.999999949,"max_abs_err":0.00105947,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":8.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":1.239,"dispatch_submit_us_per_tok":0.000,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":154.312537,"ms_per_tok_p50":5.964141,"ms_per_tok_p99":8.359062,"ms_per_tok_mean":6.344033,"j_per_tok_gpu":0.000190375,"j_per_tok_tpu":0,"j_per_tok_vsys":0.04150175,"odpm_rails":32,"cpu_ctx_switches_per_tok":5.0000,"voluntary_ctxt_switches_per_tok":0.0000,"nonvoluntary_ctxt_switches_per_tok":5.0000,"ctx_switches_all_threads_per_tok":4.7500,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999960,"cos_min_tok":0.999999949,"max_abs_err":0.00105947,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":8.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":0.776,"dispatch_submit_us_per_tok":0.000,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-fault-recovery-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-fault-recovery-L4-T8-d512.json new file mode 100644 index 0000000..2d822fb --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-fault-recovery-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":false,"mode":"mock","executor":"mock_cpu","gpu":"cpu_emulated","vk_shared_tensor_ownership":{"queue_family":"none","release_acquire_barriers_recorded":0},"tpu_backend":"cpu_emulated","tpu_backend_requested":"auto","tpu_numerics":"w8a16_f32","tpu_backend_fallback":"","nnapi":{"device":"","device_feature_level":null,"shared_mem":"none","shared_mem_fallback":"","host_staged_mem":"none","host_staged_mem_fallback":"","reusable_executions":false,"fenced_api":false,"fenced_dmabuf_policy":"not_applicable","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":0},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.999900,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":109,"completed_drains":109,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"full_pool_mock","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":0},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":1,"submissions_retired_after_drain":1,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"sw_emulated","signal_path":"sw_emulated","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":0,"probe":{"dev":"/dev/iif","probed":false,"node_present":false,"opened":false,"create_ok":false,"submit_ok":false,"signal_ok":false,"wait_ok":false,"usable":false,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":0,"reason":"not_probed_mock","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":false,"pass":false,"skip_reason":"not_selected"},{"arm":"sync_file_poll","ran":false,"pass":false,"skip_reason":"error","error":"token 1: injected GPU fence failure at layer 2 (mid slot left INFLIGHT)","recovery":"drained_retired"},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":122.671755,"ms_per_tok_p50":7.179818,"ms_per_tok_p99":11.934375,"ms_per_tok_mean":8.057272,"j_per_tok_gpu":0.00026175,"j_per_tok_tpu":0,"j_per_tok_vsys":0.01946225,"odpm_rails":32,"cpu_ctx_switches_per_tok":0.5000,"voluntary_ctxt_switches_per_tok":0.0000,"nonvoluntary_ctxt_switches_per_tok":0.5000,"ctx_switches_all_threads_per_tok":0.5000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999960,"cos_min_tok":0.999999949,"max_abs_err":0.00105947,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":8.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":1.276,"dispatch_submit_us_per_tok":0.000,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-fault-tainted-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-fault-tainted-L4-T8-d512.json new file mode 100644 index 0000000..bf6f6cd --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/mock-root-fault-tainted-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":false,"mode":"mock","executor":"mock_cpu","gpu":"cpu_emulated","vk_shared_tensor_ownership":{"queue_family":"none","release_acquire_barriers_recorded":0},"tpu_backend":"cpu_emulated","tpu_backend_requested":"auto","tpu_numerics":"w8a16_f32","tpu_backend_fallback":"","nnapi":{"device":"","device_feature_level":null,"shared_mem":"none","shared_mem_fallback":"","host_staged_mem":"none","host_staged_mem_fallback":"","reusable_executions":false,"fenced_api":false,"fenced_dmabuf_policy":"not_applicable","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":0},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.999900,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":29,"completed_drains":28,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"full_pool_mock","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":0},"executor_state":{"tainted":true,"taint_reason":"engines not proven idle: injected quiesce failure (device idle cannot be proven)","failure_recoveries":1,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":1,"pool_inflight_slots_at_exit":1},"iif":{"backend":"sw_emulated","signal_path":"sw_emulated","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":false,"requirement_met":false,"dev_open_calls":0,"probe":{"dev":"/dev/iif","probed":false,"node_present":false,"opened":false,"create_ok":false,"submit_ok":false,"signal_ok":false,"wait_ok":false,"usable":false,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":0,"reason":"not_probed_mock","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":false,"pass":false,"skip_reason":"not_selected"},{"arm":"sync_file_poll","ran":false,"pass":false,"skip_reason":"error","error":"token 1: injected GPU fence failure at layer 2 (mid slot left INFLIGHT) [executor tainted: engines not proven idle: injected quiesce failure (device idle cannot be proven)]","recovery":"tainted"},{"arm":"r_iif","ran":false,"pass":false,"skip_reason":"executor_tainted","error":"skipped: executor tainted by an earlier arm (engines not proven idle: injected quiesce failure (device idle cannot be proven))"}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/neg-nobridge-require-iif-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/neg-nobridge-require-iif-L4-T8-d512.json new file mode 100644 index 0000000..80f4301 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/neg-nobridge-require-iif-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":false,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":32},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":80},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":200,"completed_drains":200,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ungated_nnapi_sync_fence_chain_bridge_unavailable","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":true,"requirement_met":false,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":25,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x8004697f","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":90.237623,"ms_per_tok_p50":10.345182,"ms_per_tok_p99":13.902568,"ms_per_tok_mean":10.889924,"j_per_tok_gpu":0.000547375,"j_per_tok_tpu":0.00010425,"j_per_tok_vsys":0.04533825,"odpm_rails":32,"cpu_ctx_switches_per_tok":9.0000,"voluntary_ctxt_switches_per_tok":9.0000,"nonvoluntary_ctxt_switches_per_tok":0.0000,"ctx_switches_all_threads_per_tok":9.2500,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":8.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":20.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":4293.151,"dispatch_submit_us_per_tok":279.330,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":6044.646,"expected_handoffs_per_tok":8},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":132.758280,"ms_per_tok_p50":6.621823,"ms_per_tok_p99":9.528296,"ms_per_tok_mean":7.342474,"j_per_tok_gpu":0.000323875,"j_per_tok_tpu":0.0001885,"j_per_tok_vsys":0.034852625,"odpm_rails":32,"cpu_ctx_switches_per_tok":18.2500,"voluntary_ctxt_switches_per_tok":16.5000,"nonvoluntary_ctxt_switches_per_tok":1.7500,"ctx_switches_all_threads_per_tok":31.3750,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":8.000,"userspace_wakeups_per_tok":8.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":3136.211,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":3739.347,"dispatch_submit_us_per_tok":3463.425,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":157.229778,"ms_per_tok_p50":6.099703,"ms_per_tok_p99":6.792942,"ms_per_tok_mean":6.175615,"j_per_tok_gpu":0.000113375,"j_per_tok_tpu":0.000162875,"j_per_tok_vsys":0.0268495,"odpm_rails":32,"cpu_ctx_switches_per_tok":11.3750,"voluntary_ctxt_switches_per_tok":8.0000,"nonvoluntary_ctxt_switches_per_tok":3.3750,"ctx_switches_all_threads_per_tok":11.5000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":4.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":3415.586,"nnapi_dep_event_create_us_per_tok":9.033,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":652.466,"dispatch_submit_us_per_tok":5358.737,"pipelined_chain_us_per_tok":6020.504,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/neg-swfallback-require-iif-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/neg-swfallback-require-iif-L4-T8-d512.json new file mode 100644 index 0000000..8686d48 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/neg-swfallback-require-iif-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":false,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":32},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":40},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":40,"completed_drains":40,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"sw_emulated","signal_path":"sw_emulated","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":true,"requirement_met":false,"dev_open_calls":1,"probe":{"dev":"/dev/nonexistent-iif","probed":true,"node_present":false,"opened":false,"create_ok":false,"submit_ok":false,"signal_ok":false,"wait_ok":false,"usable":false,"open_errno":2,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":0,"reason":"ENOENT","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":false,"pass":false,"skip_reason":"not_selected"},{"arm":"sync_file_poll","ran":false,"pass":false,"skip_reason":"not_selected"},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":160.213869,"ms_per_tok_p50":6.228999,"ms_per_tok_p99":7.050327,"ms_per_tok_mean":6.048295,"j_per_tok_gpu":0.000285375,"j_per_tok_tpu":0.00010975,"j_per_tok_vsys":0.029712125,"odpm_rails":32,"cpu_ctx_switches_per_tok":10.8750,"voluntary_ctxt_switches_per_tok":7.1250,"nonvoluntary_ctxt_switches_per_tok":3.7500,"ctx_switches_all_threads_per_tok":10.8750,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":4.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":3159.309,"nnapi_dep_event_create_us_per_tok":8.398,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":798.955,"dispatch_submit_us_per_tok":5077.416,"pipelined_chain_us_per_tok":5898.519,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/nobridge-ungated-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/nobridge-ungated-L4-T8-d512.json new file mode 100644 index 0000000..9102c7e --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/nobridge-ungated-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":32},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":80},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":200,"completed_drains":200,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ungated_nnapi_sync_fence_chain_bridge_unavailable","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":false,"requirement_met":false,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":25,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x8004697f","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":91.067204,"ms_per_tok_p50":10.480224,"ms_per_tok_p99":13.262422,"ms_per_tok_mean":10.786261,"j_per_tok_gpu":0.00067925,"j_per_tok_tpu":0.00032225,"j_per_tok_vsys":0.051347375,"odpm_rails":32,"cpu_ctx_switches_per_tok":9.1250,"voluntary_ctxt_switches_per_tok":9.0000,"nonvoluntary_ctxt_switches_per_tok":0.1250,"ctx_switches_all_threads_per_tok":9.3750,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":8.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":20.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":4176.217,"dispatch_submit_us_per_tok":283.896,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":6058.281,"expected_handoffs_per_tok":8},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":129.283790,"ms_per_tok_p50":6.897525,"ms_per_tok_p99":9.329035,"ms_per_tok_mean":7.533715,"j_per_tok_gpu":0.000186625,"j_per_tok_tpu":0.00031125,"j_per_tok_vsys":0.03539625,"odpm_rails":32,"cpu_ctx_switches_per_tok":17.6250,"voluntary_ctxt_switches_per_tok":16.7500,"nonvoluntary_ctxt_switches_per_tok":0.8750,"ctx_switches_all_threads_per_tok":30.2500,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":8.000,"userspace_wakeups_per_tok":8.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":3260.069,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":3695.302,"dispatch_submit_us_per_tok":3665.455,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":162.664186,"ms_per_tok_p50":6.014323,"ms_per_tok_p99":6.509557,"ms_per_tok_mean":5.971177,"j_per_tok_gpu":0.00013175,"j_per_tok_tpu":5.375e-06,"j_per_tok_vsys":0.021907125,"odpm_rails":32,"cpu_ctx_switches_per_tok":11.7500,"voluntary_ctxt_switches_per_tok":7.5000,"nonvoluntary_ctxt_switches_per_tok":4.2500,"ctx_switches_all_threads_per_tok":12.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":4.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":2680.558,"nnapi_dep_event_create_us_per_tok":7.997,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":1075.672,"dispatch_submit_us_per_tok":4735.273,"pipelined_chain_us_per_tok":5821.320,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/observed-failures/session3-r_iif-d1024/bench-L12-T64-d1024.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/observed-failures/session3-r_iif-d1024/bench-L12-T64-d1024.json new file mode 100644 index 0000000..503a68e --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/observed-failures/session3-r_iif-d1024/bench-L12-T64-d1024.json @@ -0,0 +1 @@ +{"pass":false,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":96},"tpu_backend":"nnapi","tpu_backend_requested":"auto","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"openbuenos: ob_gemm_register_builtin_emitter failed: Failed loading RV64 DIVE interpreter (/tpu_open_stack/dive_interp_rv64.bin): open(/tpu_open_stack/dive_interp_rv64.bin) failed errno=2","nnapi":{"device":"google-edgetpu","shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":1632},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":12,"tokens":64,"warmup":4,"d_model":1024,"min_cos":0.995000,"handoffs_per_tok":24,"iova_pool":{"slots":34,"weight_slots":12,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":80,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":3536,"completed_drains":3536,"ob_upfront_iova_maps":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ap_signaled_gate_imported_into_gpu_queue","gpu_gate":true,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":30.092697,"ms_per_tok_p50":33.246250,"ms_per_tok_p99":37.214489,"ms_per_tok_mean":33.054827,"j_per_tok_gpu":0.00335332812,"j_per_tok_tpu":0.00163923437,"j_per_tok_vsys":0.141376172,"odpm_rails":32,"cpu_ctx_switches_per_tok":25.2344,"voluntary_ctxt_switches_per_tok":25.0781,"nonvoluntary_ctxt_switches_per_tok":0.1562,"ctx_switches_all_threads_per_tok":25.8750,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999312121,"cos_min_tok":0.999042695,"max_abs_err":0.165879,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":14034.909,"dispatch_submit_us_per_tok":643.986,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":17665.939,"expected_handoffs_per_tok":24},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":41.842309,"ms_per_tok_p50":23.537057,"ms_per_tok_p99":25.858750,"ms_per_tok_mean":23.723643,"j_per_tok_gpu":0.00308528125,"j_per_tok_tpu":0.00134695312,"j_per_tok_vsys":0.106631984,"odpm_rails":32,"cpu_ctx_switches_per_tok":50.9062,"voluntary_ctxt_switches_per_tok":48.5625,"nonvoluntary_ctxt_switches_per_tok":2.3438,"ctx_switches_all_threads_per_tok":89.1094,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999312121,"cos_min_tok":0.999042695,"max_abs_err":0.165879,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":24.000,"userspace_wakeups_per_tok":24.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":9282.545,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":12954.637,"dispatch_submit_us_per_tok":10371.296,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":0.000,"expected_handoffs_per_tok":24},{"arm":"r_iif","ran":true,"pass":false,"tok_per_s":51.362889,"ms_per_tok_p50":19.230677,"ms_per_tok_p99":22.439270,"ms_per_tok_mean":19.303134,"j_per_tok_gpu":0.00296765625,"j_per_tok_tpu":0.00118217187,"j_per_tok_vsys":0.0929955781,"odpm_rails":32,"cpu_ctx_switches_per_tok":40.4844,"voluntary_ctxt_switches_per_tok":26.1094,"nonvoluntary_ctxt_switches_per_tok":14.3750,"ctx_switches_all_threads_per_tok":42.0625,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.923857635,"cos_min_tok":0.639510600,"max_abs_err":3.60791,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":24.000,"synchronous_cpu_hops_per_tok":0.000,"iif_fences_per_tok":1.000,"sync_files_exported_per_tok":24.000,"sync_files_imported_per_tok":13.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":7532.193,"nnapi_dep_event_create_us_per_tok":18.856,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":12.000,"host_wait_us_per_tok":6698.772,"dispatch_submit_us_per_tok":12051.580,"pipelined_chain_us_per_tok":18732.439,"tpu_hw_us_per_tok":0.000,"expected_handoffs_per_tok":24}],"arms_max_abs_diff":3.60732} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/observed-failures/session3-r_iif-d1024/session.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/observed-failures/session3-r_iif-d1024/session.json new file mode 100644 index 0000000..17cc518 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/observed-failures/session3-r_iif-d1024/session.json @@ -0,0 +1,461 @@ +{ + "binary": { + "bench_sha256_device": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "bench_sha256_device_at_end": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "bench_sha256_host": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "unit_test_sha256_device": "918b0dffad2296b40e61380355330e7f1bba900448b31f96c7eb02d5ea9a3347", + "unit_test_sha256_host": "918b0dffad2296b40e61380355330e7f1bba900448b31f96c7eb02d5ea9a3347" + }, + "cleanup": { + "ls_after": "ls: /fs59g6: No such file or directory", + "removed": "/fs59g6" + }, + "crash_buffer": { + "lines_after": 0, + "lines_before": 0, + "new_lines": 0 + }, + "device": { + "android_release": "17", + "model": "Pixel 11 Pro XL", + "product": "kodiak", + "security_patch": "2026-06-05", + "soc_model": "Tensor G6" + }, + "finished_utc": "2026-12-03T03:32:38Z", + "hal_pids": { + "after_dmabuf_guard": "9820 9829", + "before": "9820 9829", + "before_dmabuf_guard": "9820 9829", + "end": "9820 9829" + }, + "kernel_log": { + "generic_kernel_fault_lines": [], + "new_lines": 1113, + "selinux_avc_denials": { + "u:r:gxp_logging:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:hal_camera_default:s0 -> u:object_r:traced_producer_socket:s0": 6, + "u:r:hal_health_default:s0 -> u:object_r:fwk_stats_service:s0": 2, + "u:r:hal_neuralnetworks_darwinn:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:mediacodec_google:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:shell:s0 -> u:object_r:iif_device:s0": 2, + "u:r:shell:s0 -> u:object_r:shell_data_file:s0": 1, + "u:r:shell:s0 -> u:object_r:sysfs_iio_devices:s0": 5, + "u:r:shell:s0 -> u:r:shell:s0": 4 + }, + "subsystem_fault_lines": [], + "subsystem_info_line_count": 416, + "subsystem_info_lines_head": [ + "[185868.787142] edgetpu santafe: Powering up", + "[185868.793099] edgetpu santafe: R52 boot stage: 0", + "[185868.793117] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[185868.796742] edgetpu santafe: Powering down", + "[185868.903502] edgetpu santafe: Powering up", + "[185868.910205] edgetpu santafe: R52 boot stage: 0", + "[185868.910252] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[185868.913396] edgetpu santafe: Powering down", + "[185869.041714] edgetpu santafe: Powering up", + "[185869.047932] edgetpu santafe: R52 boot stage: 0", + "[185869.047953] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[185869.051912] edgetpu santafe: Powering down", + "[185869.177070] edgetpu santafe: Powering up", + "[185869.183584] edgetpu santafe: R52 boot stage: 0", + "[185869.183616] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[185869.186107] edgetpu santafe: Powering down", + "[185869.204558] edgetpu santafe: Powering up", + "[185869.209214] edgetpu santafe: R52 boot stage: 0", + "[185869.209237] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[185869.209895] edgetpu santafe: Powering down" + ] + }, + "leftover_processes": "", + "lock": { + "mode": "fcntl.flock LOCK_EX", + "path": "/tmp/kodiak-pixel11-adb.lock", + "waited_s": 0.0 + }, + "path_redaction": "device-tmp prefix redacted to / for OSS clean-room path hygiene", + "runs": [ + { + "args": [ + "--live", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "smoke-L4-T8-d512.json", + "stdout_sha256": "3ab24fd6568c65354bd12506beca3cf731e1e3a45b3a68c8d7a6bdc645bb7a35", + "uid": "root", + "wall_s": 1.5 + }, + { + "args": [ + "--live", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d512.json", + "stdout_sha256": "5c736b5410397829adfa934c887c97fd75feaaf754738ad4b5f375cf9b7b6785", + "uid": "root", + "wall_s": 6.5 + }, + { + "args": [ + "--live", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "1024", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 1, + "expected_exit_code": 0, + "file": "bench-L12-T64-d1024.json", + "raw_stdout_sha256_before_path_redaction": "155675817f227138d6a01a74452c923c08a1940f57b586a68f6ed27c23fd1156", + "stdout_sha256": "b284c2e9a30b433eb01455500105d055fc907fcff156b7f516d5bf6fa16edb9b", + "uid": "root", + "wall_s": 8.9 + }, + { + "args": [ + "--live", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "2048", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d2048.json", + "stdout_sha256": "7d48cbe4449789a8ee7fe9ccf341c441b87bf3a3b60a7edcb79f52c752cbadce", + "uid": "root", + "wall_s": 24.9 + }, + { + "args": [ + "--live", + "--tpu-backend", + "cpu", + "--layers", + "12", + "--tokens", + "16", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "w8a16-cpu-tpu-L12-T16-d512.json", + "stdout_sha256": "1eb3d44224233f4d5053452fc4e577acfaaf8062f9b0fd6e1ef9bde2c518177d", + "uid": "root", + "wall_s": 2.6 + }, + { + "args": [ + "--live", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--arms", + "r_iif", + "--iif-dev", + "/dev/nonexistent-iif", + "--iif-sw-fallback", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 1, + "expected_exit_code": 1, + "file": "neg-swfallback-require-iif-L4-T8-d512.json", + "stdout_sha256": "a6491ee87f191e34ef852f6cfd6210622ae446dfe3a14554d176d03ca8acf61c", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "nobridge-ungated-L4-T8-d512.json", + "stdout_sha256": "6128665726284adbe6581f714bf2c7c2c5699e6f7294a5f337ef28463cf42164", + "uid": "root", + "wall_s": 1.5 + }, + { + "args": [ + "--live", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 1, + "expected_exit_code": 1, + "file": "neg-nobridge-require-iif-L4-T8-d512.json", + "stdout_sha256": "15512470af01e849dcc93df19876e0e2b39a0df815d52159095ae712e0ac2565", + "uid": "root", + "wall_s": 1.5 + }, + { + "args": [ + "--live", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--nnapi-mem", + "dmabuf", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json", + "stdout_sha256": "55beb745f21362fa78875faa3121cca48c99452979d5ebb29f21d8963dabca7d", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--iif-probe-only" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "iif-probe-only.json", + "iif_dev_open_events": 1, + "iif_dev_open_watch_expect": "nonzero", + "stdout_sha256": "b047c2033a418ffaae42a981b869e84814792505c366cdd178f1c162f1adf11e", + "uid": "root", + "wall_s": 1.2 + }, + { + "args": [ + "--iif-probe-only", + "--iif-dev", + "/iif\"\\test" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "iif-probe-only-hostile-dev.json", + "stdout_sha256": "82bbd3b182bf4b5c6f979160befe6160433cdec0177b070341581db72a5520b0", + "uid": "shell", + "wall_s": 0.0 + }, + { + "args": [ + "--live", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "smoke-shell-uid-L4-T8-d512.json", + "stdout_sha256": "08aac86359504378974c9a10e68985ef1076c9789a11c79bdddc42fdf87b0b70", + "uid": "shell", + "wall_s": 1.3 + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 0, + "expected_exit_code": 0, + "file": "mock-root-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "9cc312afeaa9c0a7dda301a2c3cfc6ad9cbbe8510498105a14d45d751f019657", + "uid": "root", + "wall_s": 1.7 + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--require-iif", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 1, + "expected_exit_code": 1, + "file": "mock-root-fault-recovery-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "40fca7210a4008d73d1c135614be705847e019a6feb59977f1dfd0fb428b2c46", + "uid": "root", + "wall_s": 1.5 + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--fault-inject-quiesce-fail", + "--json" + ], + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "exit_code": 1, + "expected_exit_code": 1, + "file": "mock-root-fault-tainted-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "8f34ae7d244d72e9cc0e23c99099ddbf5e1da81af6c192aa3140ba19e00c9679", + "uid": "root", + "wall_s": 1.3 + } + ], + "schema": "freesched.proof.token_loop_session/v1", + "started_utc": "2026-12-03T03:31:36Z", + "tmp_after": { + "count": 15, + "sha256": "1bf7117b89968517d82924e40b0bca2eb8f6a8e3601f41ee1e8fe5fe98268f03" + }, + "tmp_before": { + "count": 15, + "sha256": "1bf7117b89968517d82924e40b0bca2eb8f6a8e3601f41ee1e8fe5fe98268f03" + }, + "unit_test_runs": [ + { + "title": "uid shell (adb shell), TMPDIR unset", + "uid": "shell" + }, + { + "title": "uid shell, TMPDIR=", + "uid": "shell" + }, + { + "title": "uid 0 (su)", + "uid": "root" + } + ] +} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/receipt.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/receipt.json new file mode 100644 index 0000000..4a9a7e7 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/receipt.json @@ -0,0 +1,2801 @@ +{ + "schema": "freesched.proof.receipt/v1", + "proof": "tensor-g6-gpu-edgetpu-riif-token-loop", + "date": "2026-12-03", + "build": { + "target": "arm64-v8a", + "ndk": "r27 (27.3)", + "platform": "android-35", + "build_type": "Release", + "libopenbuenos": "linked statically (freetpu 760147d5, scratch android-arm64 build); the live sweep explicitly requested --tpu-backend nnapi (tpu_backend_requested is nnapi), not an automatic NNAPI fallback", + "source": "the Generation 10 review-repair commit; the bench and unit-test sources were frozen before the device session" + }, + "run_context": { + "uid": "root for every live run except the two uid shell runs (ODPM energy_value and /dev/iif require root; uid shell gets EACCES on both)", + "LD_LIBRARY_PATH": "unset", + "flash_writes": "none", + "capture": "scripts/token_loop_capture.py (one exclusive adb lock for the whole session)" + }, + "parity_reference": "cos is measured against reference_token(): an FP64 forward pass of the same weights with UNQUANTIZED float activations (it skips both QUANT8 activation steps, A[l] quantize and Y[l] requantize). The cos >= 0.995 gate therefore checks end-to-end agreement with the float-activation baseline INCLUDING the intended INT8 activation quantization error; it does not by itself validate the QUANT8 implementation bit-for-bit. arms_max_abs_diff = 0 (identical outputs of host_staged, sync_file_poll and r_iif) checks that the three handoff paths compute the same quantized result.", + "iova_observation_scope_note": "AHB mode (the live Tensor G6 path): iova_observation_scope = vulkan_pool_only_nnapi_ahb_external. hot_loop_map_count == 0 / hot_loop_unmap_count == 0 prove zero hot-loop maps/unmaps on the fs_iova_pool (Vulkan-imported) buffers. The four QUANT8 GPU<->EdgeTPU AHardwareBuffers are allocated and registered once with ANeuralNetworksMemory_createFromAHardwareBuffer before hot-loop entry (nnapi_ahb_memories_registered_before_hot_loop and ahb_hot_loop_allocs in the generated iova_pool key); their driver-internal gralloc/NNAPI mappings are outside userspace pool observation and are NOT covered by the map counters. Pool submissions/drains record only what touches pool slots: GPU writes of FP32 mid(l) and out(l) (dequant of Y); no synthetic EdgeTPU submission is attributed to FP32 slots. In dmabuf_fd mode (full_pool_dmabuf) the EdgeTPU submissions/drains are recorded on the actual QUANT8 qmid/qout pool slots. On the libopenbuenos backend (vulkan_pool_only_openbuenos_weights_external), every layer's packed weight cache is pre-warmed before fs_iova_pool_enter_hot_loop() (ob_prewarmed_layers = L) while internal libopenbuenos weight buffers remain outside fs_iova_pool observation.", + "dmabuf_fallback_observation": "Generation 5: fenced dmabuf_fd execution on google-edgetpu is now refused before dispatch (receipt edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json). History, not a receipt: in a Generation 4 session (binary ba61746a...), --nnapi-mem dmabuf reached the first fenced EdgeTPU hop, which crashed the vendor NNAPI HAL (android.hardware.neuralnetworks@service-darwinn-aidl, SIGSEGV) and returned OP_FAILED (rc=5); init restarted the HAL. That dispatch is now only reachable with --allow-edgetpu-dmabuf-fenced-probe, which was not run. Completed QUANT8 slot drains in dmabuf_fd mode therefore remain unverified on silicon.", + "live_fixes": [ + { + "id": "zero-copy-cpu-isolation", + "symptom": "with all three arms in one process, sync_file_poll and r_iif failed the parity gate by a wide margin whenever host_staged ran first; each zero-copy arm alone passed", + "diagnosis": "a CPU lock+read/write of a shared GPU<->EdgeTPU AHB tensor (correctly bracketed by AHardwareBuffer_lock/unlock) left cache state that later device-only handoffs observed as stale data; a lock-only invalidate cleared it, a lock+read did not", + "fix": "host_staged now copies through its own CPU-visible AHB bridge tensors and command buffers; the zero-copy tensors are never CPU-accessed (JSON nnapi.host_staged_mem = isolated_ahb_blob)" + }, + { + "id": "iif-sync-file-bridge", + "symptom": "r_iif with the kernel IIF backend failed at layer 0 (GPU submit rejected the gate fence)", + "diagnosis": "the FS_IIF_CREATE_FENCE fd is anon_inode:iif_file; it is pollable but SYNC_IOC_FILE_INFO returns ENOTTY, so Vulkan SYNC_FD import rejects it. FS_IIF_FENCE_BRIDGE_DMA returns a new sync_file fd (one dma_fence on the IIF timeline) that signals when the IIF fence is signaled", + "fix": "IifFences::bridge_sync_file() validates the bridged fd with SYNC_IOC_FILE_INFO; r_iif imports the bridged sync_file; the probe reports fence_is_sync_file / bridge_sync_file_ok / bridge_signaled" + }, + { + "id": "nnapi-runtime-resident", + "symptom": "SIGSEGV in a background thread (pthread_cond_clockwait returning into unmapped code) at process exit on every live NNAPI run", + "diagnosis": "dlclose(libneuralnetworks.so) unmapped code still used by NNAPI runtime worker threads", + "fix": "the NNAPI runtime library is never dlclose()d; 0 fatal signals across the sweep" + } + ], + "review_repairs": [ + { + "id": "descriptor-pool-budget", + "change": "pool budgets 6 sets / 24 storage-buffer descriptors per layer (GEMV, RMSNorm, quant, dequant, isolated host_staged quant + dequant)" + }, + { + "id": "queue-family-ownership-transfer", + "change": "VkBufferMemoryBarrier release (qf -> VK_QUEUE_FAMILY_FOREIGN_EXT) after the last GPU access and acquire (VK_QUEUE_FAMILY_FOREIGN_EXT -> qf) before the first GPU access of every GPU<->EdgeTPU tensor. Generation 2: no VK_QUEUE_FAMILY_EXTERNAL fallback (see require-foreign-queue-family)", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "require-iif-measured", + "change": "--require-iif requires r_iif to have run with measured IIF fences > 0, and live runs need the kernel /dev/iif backend; unit-tested in tests/test_token_loop_riif.cpp" + }, + { + "id": "host-staged-fail-closed", + "change": "if the isolated staging tensors cannot be allocated/imported, host_staged is reported unavailable (host_staged_isolated_staging_unavailable); it never CPU-accesses the zero-copy tensors" + }, + { + "id": "nnapi-event-status", + "change": "ANeuralNetworksEvent_wait status is checked for every fenced hop after poll() in sync_file_poll and at the token boundary in r_iif before ANeuralNetworksEvent_free", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "w8a16-sync-file-poll", + "change": "W8A16 sync_file_poll polls the exported GPU SYNC_FD and the TPU DMA-BUF sync_file (DMA_BUF_IOCTL_EXPORT_SYNC_FILE on the pinned slot fd) in userspace before the next stage; a failed export fails the hop" + }, + { + "id": "no-openbuenos-unused-parameter", + "generation": 2, + "change": "LiveExecutor::run_tpu marks its TokenCounters parameter (void)c so builds with Vulkan headers and without FREESCHED_HAVE_LIBOPENBUENOS stay -Wextra -Werror clean", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "ownership-acquire-wait-stage", + "generation": 2, + "change": "every vkQueueSubmit wait semaphore (all recorded command buffers begin with a foreign -> qf ownership acquire of TPU-written tensors) uses VK_PIPELINE_STAGE_ALL_COMMANDS_BIT instead of COMPUTE_SHADER_BIT, so the legacy acquire cannot run before the EdgeTPU fence signals", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "require-foreign-queue-family", + "generation": 2, + "change": "the VK_QUEUE_FAMILY_EXTERNAL fallback is removed; without VK_EXT_queue_family_foreign the openbuenos/nnapi accelerator backends fail select_tpu with \"VK_EXT_queue_family_foreign unsupported ... GPU<->EdgeTPU zero-copy accelerator path unavailable\". --tpu-backend cpu stays available: the CPU-emulated TPU touches the DMA-BUFs only from the host (DMA_BUF_IOCTL_SYNC + HOST-stage barriers), so tensors remain owned by the compute queue family and no transfer is recorded (vk_shared_tensor_ownership.queue_family = none_host_only)", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "cpu-backend-host-copy-count", + "generation": 2, + "change": "with --live --tpu-backend cpu, the fenced arms count the stage_in_ read and stage_out_ write copies (+2 per layer) in inter_ip_host_copies", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "nnapi-gate-requires-bridge", + "generation": 3, + "change": "IifProbe records bridge_dma_ok (FS_IIF_FENCE_BRIDGE_DMA returned a sync_file AND it signaled on poll()) separately from raw /dev/iif usability. Raw kernel IIF stays available for CPU-proxy handoffs; the NNAPI arm enables its Vulkan IIF gate only when bridge_dma_ok, otherwise it runs the ungated sync-fence chain with 0 IIF fences (so --require-iif still rejects it). New --iif-ioctl-bridge override for live negative checks; unit-tested in tests/test_token_loop_riif.cpp", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "wakeup-accounting", + "generation": 3, + "change": "userspace_wakeups counts only cross-thread wakeups (the NNAPI sync_file_poll waiter thread). Inline poll()/waits on the submitting thread (CPU-proxy IIF handoffs, mock fence round trips, --tpu-backend cpu) count only in userspace_fence_polls", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "parity-reference-description", + "generation": 3, + "change": "PROOF.md and this receipt (parity_reference) state that cos is measured against an unquantized FP64 float-activation baseline and includes INT8 activation quantization error; arms_max_abs_diff checks cross-arm agreement" + }, + { + "id": "ctest-exit-code", + "generation": 3, + "change": "token-loop CTest entries no longer use PASS_REGULAR_EXPRESSION (which makes CTest ignore the exit code). The d2048 smoke relies on the exit code; content checks run through tests/ctest_run_expect.cmake (exit 0 AND match). New negative test: d2048 without r_iif + --require-iif (nested arms pass, top-level fails) must fail", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "android-temp-dir", + "generation": 3, + "change": "unit-test fixtures use fs_temp_dir(): $TMPDIR, then /data/local/tmp when writable, then /tmp", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "json-non-finite-null", + "generation": 3, + "change": "every floating JSON field goes through json_finite_or_null(); inf/nan diagnostics are emitted as null while pass stays false. Covered by a unit test and a strict python3 json CTest (parse_constant rejects inf/nan)" + }, + { + "id": "iova-proof-actual-nnapi-buffers", + "generation": 4, + "change": "pool submissions/drains are recorded on the slots each device actually touches: GPU writes FP32 mid(l) and out(l) (dequant of QUANT8 Y); the EdgeTPU reads/writes the QUANT8 qmid/qout tensors, recorded on their pool slots only in dmabuf_fd mode. In AHB mode no synthetic EdgeTPU submission is attributed to FP32 slots; JSON reports iova_observation_scope (vulkan_pool_only_nnapi_ahb_external | full_pool_dmabuf | full_pool_mock), ahb_hot_loop_allocs and nnapi_ahb_memories_registered_before_hot_loop. A failed NNAPI hop retires its QUANT8 slots once drained so the next arm does not inherit INFLIGHT slots", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "cpu-w8a16-output-hop-synchronous", + "generation": 4, + "change": "--tpu-backend cpu: the CPU write of Y[l] completes inside its DMA_BUF_IOCTL_SYNC bracket before the handoff, so the TPU -> GPU hop no longer exports/polls the DMA-BUF reservation fence (sync_file_poll) or creates a CPU-proxy IIF (r_iif); it counts as synchronous_cpu_hops instead of fence_handoffs", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "consistent-timing-fields", + "generation": 4, + "change": "sync_us_per_tok is replaced by host_wait_us_per_tok (poll()/waiter-thread wait, vkWaitForFences, vkQueueWaitIdle IIF-gate drain, ANeuralNetworksEvent_wait, /dev/iif wait ioctl; submission calls excluded) and dispatch_submit_us_per_tok (vkQueueSubmit + startComputeWithDependencies only), with identical definitions in every arm; the r_iif whole-chain duration moves to pipelined_chain_us_per_tok (null for arms without a pipelined chain)" + }, + { + "id": "json-escape-all-strings", + "generation": 4, + "change": "every JSON string value (including --iif-dev in print_iif_probe_json, tpu_backend_requested and the probe reason) goes through fs_tokloop::json_escape(); covered by test_json_escape, a strict python3 JSON CTest of a hostile probe document, and a bench CTest running --iif-probe-only --iif-dev '/tmp/iif\"\\test'" + }, + { + "id": "edgetpu-dmabuf-fenced-guard", + "generation": 5, + "finding": "[P2] Disable fenced DMA-BUF execution on the affected EdgeTPU driver (tools/volcanic_nnapi_edgetpu.h)", + "change": "nnapi_fenced_dmabuf_block_reason(device, dmabuf_mem, allow_probe): an EdgeTPU device (name contains 'edgetpu', case-insensitive) with dmabuf_fd shared memory is refused before ANY NNAPI call in NnEdgeTpu::start() (no execution, no dependency event, no startComputeWithDependencies) and LiveExecutor::arm_unavailable() skips sync_file_poll and r_iif with nnapi_fenced_dmabuf_unavailable_on_edgetpu. Both --nnapi-mem dmabuf and the automatic AHB -> dmabuf_fd fallback take this path: the pool DMA-BUFs are imported for the GPU only and never into NNAPI (no ANeuralNetworksMemory_createFromFd, no bind). --allow-edgetpu-dmabuf-fenced-probe (debug only) restores the old dispatch. JSON: nnapi.fenced_dmabuf_policy, allow_edgetpu_dmabuf_fenced_probe, fenced_dmabuf_refusals, exec_start_calls", + "tests": "test_nnapi_edgetpu_dmabuf_fenced_guard drives the shared start() path through a host NnEdgeTpu test seam with counting mock NNAPI entry points: google-edgetpu + dmabuf refuses with and without a dependency fd and never calls exec_start_deps_ or event_from_fd_; AHB memory and the debug probe dispatch exactly once", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "sync-file-status-check", + "generation": 5, + "finding": "[P3] Check sync-file status before consuming producer output (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "poll_sync_fd() and FdWaiter both call fs_tokloop::sync_fd_wait_handoff(): poll(POLLIN) without POLLERR/POLLNVAL, then SYNC_IOC_FILE_INFO (_IOWR('>', 4, struct sync_file_info) = 0xc0383e04; sync_file_info is 56 bytes on every ABI) must succeed with status == 1. status < 0 (fence error) and 0 (unsignaled) fail the hop; ENOTTY/EINVAL (not a sync_file) fail every live kernel handoff and are accepted only in SYNC_FD_MOCK_NON_SYNC_FILE mode for pipe/eventfd stand-ins", + "tests": "test_sync_handoff_verdict (pure verdict table incl. -EIO/-ECANCELED, POLLERR/POLLNVAL, timeout, ENOTTY/EINVAL kernel vs mock, pipe readiness); test_iif_errored_bridge_rejected (live, root)", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "nnapi-submit-timer", + "generation": 5, + "finding": "[P3] Start the NNAPI dispatch timer after dependency setup (tools/volcanic_nnapi_edgetpu.h)", + "change": "the startComputeWithDependencies timer now starts after ANeuralNetworksEvent_createFromSyncFenceFd, so nnapi_start_block_us_per_tok and dispatch_submit_us_per_tok time the identical submission call in sync_file_poll and r_iif; dependency-event creation is reported separately as nnapi_dep_event_create_us_per_tok", + "tests": "mock event_from_fd that sleeps 30 ms: dep_event_create_us reports about 30 ms and block_us stays far below it", + "verified_by": "generated receipt keys (results, iova_pool, supplementary_runs) and the raw files they are derived from" + }, + { + "id": "ctest-crosscompiling-emulator", + "generation": 5, + "finding": "[P3] Use the configured emulator in wrapped CTest cases (CMakeLists.txt)", + "change": "when CMAKE_CROSSCOMPILING and CMAKE_CROSSCOMPILING_EMULATOR are set, the emulator list is passed '|'-joined as -DEMULATOR= to tests/ctest_run_expect.cmake (prepended to CMD) and as one --emulator-arg= per element to tests/token_loop_json_check.py (prepended to every launched target)", + "tests": "scratch configurations with CMAKE_SYSTEM_NAME=Darwin: '/usr/bin/env;--' 14/14 token-loop tests pass; a logging emulator '/bin/sh;log-emu.sh;--fs-marker' records 14 launches (all 3 cmake-wrapped, all 4 python-wrapped, all 7 direct); a rejecting emulator fails all 10 positive token-loop tests" + }, + { + "id": "drain-before-next-arm", + "generation": 6, + "finding": "[P2] Drain failed GPU work before running the next arm (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "every fs_iova_pool submission is recorded in an executor ledger until its fence retires. When an arm fails (warmup, token or a successful arm that would leave work in flight), Executor::recover_after_failure() first proves every engine idle: vkDeviceWaitIdle must return VK_SUCCESS (live), every started NNAPI hop must have been waited and released, and no IIF fence may still be open. Only then are the leftover ledger submissions retired and every pool slot must be IDLE again. Otherwise the executor is tainted and run_arm() skips every later arm (skip_reason executor_tainted) before run_token() writes SLOT_X or any other buffer. JSON: executor_state {tainted, taint_reason, failure_recoveries, submissions_retired_after_drain, ledger_inflight_at_exit, pool_inflight_slots_at_exit} and per failed arm recovery = drained_retired | tainted", + "tests": "mock test seam --fault-inject-gpu-fence ARM:CALL:LAYER (fails a stage with its GPU slot left INFLIGHT, the shape of the live rejected-fence bug) and --fault-inject-quiesce-fail; CTest volcanic_tpu_token_loop_bench_failure_recovery: W8A16 and QUANT8 mocks, the next arms run and pass after drain+retire; a failed drain taints the executor and skips r_iif; the seam is rejected with --live (exit 2)", + "verified_by": "mock-root-fault-recovery-L4-T8-d512.json and mock-root-fault-tainted-L4-T8-d512.json (Pixel 11, root); executor_state of every live run" + }, + { + "id": "mock-never-opens-iif", + "generation": 6, + "finding": "[P3] Keep mock runs out of the kernel IIF driver (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "iif_probe() runs only for --live and --iif-probe-only; --mock reports iif_probe_not_run(\"not_probed_mock\") (probe.probed = false) and uses only the software fence backend. iif_dev_open_calls() counts every open(2) of the IIF node and the JSON reports iif.dev_open_calls", + "tests": "test_iif_probe_not_run; CTest volcanic_tpu_token_loop_bench_mock_never_opens_iif (a mock run with --iif-dev naming an existing file reports 0 opens; --iif-probe-only on the same file still probes it)", + "verified_by": "mock-root-*.json as root on the Pixel 11 with an inotifyd open watch on /dev/iif (iif_open_watch: 0 events for every --mock run, the --iif-probe-only positive control sees the open)" + }, + { + "id": "strict-cli-numbers", + "generation": 6, + "finding": "[P3] Validate the ODPM energy conversion factor (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "every numeric option goes through fs_tokloop::parse_strict_* (strtoull/strtoll/strtod with errno = 0, whole-argument parse, no leading whitespace or sign on unsigned values, ERANGE / NaN / Inf rejected, inclusive range). --odpm-unit-j must be finite and > 0, --min-cos finite in (0, 1], counts are decimal; any malformed value exits 2. The bench no longer calls atoi/atof/atol", + "tests": "test_strict_cli_parsing (incl. a U+2212 minus, 0, -0, nan, inf, ERANGE over/underflow, trailing bytes); CTest volcanic_tpu_token_loop_bench_strict_args_exit2 (exact exit code 2 for every malformed value) and WILL_FAIL cases for the U+2212 minus, 0 and nan conversion factors and --layers 12x", + "verified_by": "host-verification.json (ctest)" + }, + { + "id": "receipt-generated-from-raw", + "generation": 6, + "finding": "[P3] Reconcile the W8A16 receipt with its raw result (proof/tensor-g6-gpu-edgetpu-riif-token-loop/receipt.json)", + "change": "all raw files were regenerated in one exclusive-lock session from one binary by scripts/token_loop_capture.py, which writes session.json (per-run argv, uid, exit code, expected exit code, device binary SHA-256 taken right before the run, stdout SHA-256). scripts/token_loop_receipt.py write generates every measured receipt key and every PROOF.md table from those files; check (CTest token_loop_proof_receipt_reconciled) fails on any stale value, hash mismatch, second binary, unexpected exit code or measured number in hand-written prose", + "tests": "CTest token_loop_proof_receipt_reconciled", + "verified_by": "session.json, receipt.json generated keys" + }, + { + "id": "drain-libopenbuenos-on-quiesce", + "generation": 7, + "finding": "[P2] Drain libopenbuenos before reusing shared tensor slots (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "LiveExecutor::quiesce() calls ob_graph_wait_all(ob_, 0u) under FREESCHED_HAVE_LIBOPENBUENOS whenever ob_ != nullptr; any non-OB_OK status fails quiesce() and taints the executor before shared slots are retired", + "tests": "arm64-v8a and Linux/macOS compile matrix with and without FREESCHED_HAVE_LIBOPENBUENOS (-Wall -Wextra -Werror)" + }, + { + "id": "exclusive-device-dir-cleanup", + "generation": 7, + "finding": "[P2] Require a newly created directory before recursive device cleanup (scripts/token_loop_capture.py)", + "change": "validate_device_dir() normalizes --device-dir with posixpath.normpath and requires a safe child directly under /data/local/tmp; creation uses exclusive mkdir -- without -p and enables rm -rf -- cleanup only after mkdir exits 0", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "strict-health-log-reads", + "generation": 7, + "finding": "[P3] Fail the health capture when device logs cannot be read (scripts/token_loop_capture.py)", + "change": "Device.text() enforces exit-code checking by default; pre- and post-session dmesg and logcat -b crash -d read failures abort capture and session.json records their exit codes (checked by token_loop_receipt.py check)", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "unit-test-exit-codes-in-capture", + "generation": 7, + "finding": "[P3] Fail capture when an on-device unit test exits unsuccessfully (scripts/token_loop_capture.py)", + "change": "session.json records each on-device unit test exit_code and all_checks_passed, overall_ok and the capture exit code require all unit tests to pass, and token_loop_receipt.py check reconciles them with unit-test-device.txt", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "archived-unexpected-exit-raw-required", + "generation": 7, + "finding": "[P3] Require raw output for each recorded unexpected exit (scripts/token_loop_receipt.py)", + "change": "Packet requires every archived observed-failures/ manifest entry with an unexpected exit or failed pass state to have its raw file present on disk matching stdout_sha256 in both write and check; successful runs remain manifest-only", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "staged-capture-preserve-previous", + "generation": 9, + "finding": "[P2] Preserve the previous capture until the new session finishes (scripts/token_loop_capture.py)", + "change": "Stage all raw run files, unit transcript and session.json in a fresh sibling staging directory outside --out; publish atomically with backup/rollback only when overall_ok is true, leaving previous --out untouched and retaining the staging directory on failure", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "crash-buffer-logcat-cursor", + "generation": 9, + "finding": "[P3] Detect new crashes even when the crash buffer rolls over (scripts/token_loop_capture.py)", + "change": "Capture the device wall-clock cursor before the session and query logcat -b crash -T -d before and after, filtering header lines; token_loop_receipt.py check enforces cursor_mode=logcat_T, valid start_timestamp and zero exit codes", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "hal-pid-snapshots-validated", + "generation": 9, + "finding": "[P3] Require valid HAL PID snapshots before passing the health gate (scripts/token_loop_capture.py)", + "change": "Record pidof exit codes and require all four snapshots to exit 0 and parse as non-empty positive integer PID lists in both token_loop_capture.py and token_loop_receipt.py check", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "arm64-matrix-verified", + "generation": 9, + "finding": "[P3] Verify the arm64 configurations before recording build passes (scripts/token_loop_receipt.py)", + "change": "host-verify enforces distinct build directories, inspects CMakeCache.txt for repo root, Android arm64-v8a, NDK and opposite libopenbuenos configurations, runs cmake --build on both targets, checks ELF64 AArch64 headers and verifies distinct bench hashes", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "bounded-nnapi-fence-timeout-recovery", + "generation": 9, + "finding": "[P2] Keep NNAPI fence timeout recovery bounded (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "Track fence wait timeouts from vkWaitForFences, wait_on_waiter and poll_sync_fd_timed; skip unbounded ANeuralNetworksEvent_wait, vkQueueWaitIdle and vkDeviceWaitIdle, taint immediately and keep unproven slots and NNAPI objects quarantined", + "tests": "CTest volcanic_tpu_token_loop_bench_failure_recovery and test_token_loop_riif" + }, + { + "id": "nnapi-poll-counted-once", + "generation": 9, + "finding": "[P2] Count NNAPI completion polling once in host wait time (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "Start the check_done/wait_done timer after wait_on_waiter returns in live NNAPI sync_file_poll so host_wait_us counts the completion poll once", + "tests": "Live Tensor G6 re-capture and host/ASan ctest" + }, + { + "id": "root-controlled-capture-exec-dir", + "generation": 10, + "finding": "[P2] Run privileged capture binaries from a root-controlled path (scripts/token_loop_capture.py)", + "change": "Copy pushed binaries into an exclusive root-owned private directory under /data/local/freesched-root-capture/ (no -p), delete the shell push-staging directory immediately, verify SHA-256 as root before execution, and run every su bench, unit test and inotifyd watch exclusively from that root directory; unprivileged shell runs execute from a root-owned read-execute directory copied from the verified root binaries", + "tests": "CTest token_loop_proof_scripts_unit and live Tensor G6 re-capture" + }, + { + "id": "validate-staged-capture-before-publish", + "generation": 10, + "finding": "[P2] Validate proof outcomes before replacing the previous capture (scripts/token_loop_capture.py)", + "change": "Invoke token_loop_receipt.validate_staged_capture() on the staged directory (hashes, health gate, unit tests, IIF open watches, positive and negative structured outcomes) before publishing into --out", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "preserve-archived-failures-without-json", + "generation": 10, + "finding": "[P3] Preserve archived failures that produced no JSON (scripts/token_loop_receipt.py)", + "change": "After SHA-256 verification, handle empty or partial non-JSON raw files in observed-failures/ by recording json_parsed = false, exit code, stdout byte count and parse error instead of failing write or check", + "tests": "CTest token_loop_proof_scripts_unit" + }, + { + "id": "verify-asan-ubsan-instrumentation", + "generation": 10, + "finding": "[P3] Verify sanitizer instrumentation before recording an ASan and UBSan pass (scripts/token_loop_receipt.py)", + "change": "Require --asan-build != --host-build, verify both address and undefined flags in CMakeCache.txt, and inspect compiled bench and unit-test binaries for both ASan and UBSan symbols before recording a pass", + "tests": "CTest token_loop_proof_scripts_unit and host-verify" + }, + { + "id": "libopenbuenos-synchronous-tpu-hop", + "generation": 10, + "finding": "[P2] Count libopenbuenos TPU completion as a synchronous hop (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "Stop exporting/polling a DMA-BUF fence or creating a proxy IIF after synchronous ob_gemm_matmul_f32_w8a16_dmabuf(); report synchronous_tpu_hops_per_tok = L and fence_handoffs_per_tok = L (GPU -> TPU only)", + "tests": "Host/ASan/arm64 compile matrix and live re-capture" + }, + { + "id": "libopenbuenos-prewarm-weights-and-scope", + "generation": 10, + "finding": "[P2] Include libopenbuenos weight mappings in the hot-loop check (tools/volcanic_tpu_token_loop_bench.cpp)", + "change": "Pre-warm every layer's packed weight cache via ob_gemm_matmul_f32_w8a16_dmabuf() before fs_iova_pool_enter_hot_loop() (even when --warmup is zero), emit ob_prewarmed_layers and report iova_observation_scope = vulkan_pool_only_openbuenos_weights_external", + "tests": "Host/ASan/arm64 compile matrix and live re-capture" + } + ], + "device": { + "android_release": "17", + "model": "Pixel 11 Pro XL", + "product": "kodiak", + "security_patch": "2026-06-05", + "soc_model": "Tensor G6", + "gpu": "PowerVR C-Series CXTP-48-1536 MC1", + "tpu_nnapi_device": "google-edgetpu", + "iif_dev": "/dev/iif", + "iif_backend": "kernel", + "iif_signaler_ip": 3 + }, + "binary": { + "sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "unit_test_sha256": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9", + "bench_sha256_device_after_push": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "bench_sha256_device_at_end": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "unit_test_sha256_device": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9", + "distinct_bench_sha256_across_runs": [ + "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705" + ] + }, + "runs": [ + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "smoke-L4-T8-d512.json", + "stdout_sha256": "e1d1a9ce15119e4c8651bab6b4083d65c18a61339f536fb3040ea6b09da72938", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d512.json", + "stdout_sha256": "9c848616f8b672c6f93dd05918bce7e53e853e2ef0b9723eb7d8d2c9da46a4ec", + "uid": "root", + "wall_s": 6.8 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "1024", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d1024.json", + "stdout_sha256": "bffe3795bd6174fc4d40d07d21ed71e7f1652151eec7d8d1552659e08ee57000", + "uid": "root", + "wall_s": 8.8 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "2048", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d2048.json", + "stdout_sha256": "4bea06e429c88bb24bde770acdc4b2f96e68f2af774c7e0b11df927a3781f386", + "uid": "root", + "wall_s": 24.6 + }, + { + "args": [ + "--live", + "--tpu-backend", + "cpu", + "--layers", + "12", + "--tokens", + "16", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "w8a16-cpu-tpu-L12-T16-d512.json", + "stdout_sha256": "59fc03c4b0d3e68e5da3c8c195901c16ada3409ec4a1de4e0483a93958de52ca", + "uid": "root", + "wall_s": 2.7 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--arms", + "r_iif", + "--iif-dev", + "/dev/nonexistent-iif", + "--iif-sw-fallback", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "neg-swfallback-require-iif-L4-T8-d512.json", + "stdout_sha256": "e1d42d79a184fe9fe70e3c08941f17b824b14155bd37e64287db6fd7f9a7f621", + "uid": "root", + "wall_s": 1.0 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "nobridge-ungated-L4-T8-d512.json", + "stdout_sha256": "72d0e38d2fe6901aa35eb73c044a87e233d2a81fc84baa95d4b91ddd1806701c", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "neg-nobridge-require-iif-L4-T8-d512.json", + "stdout_sha256": "02960f6d761a4a7a81eaf8d5259ff5c1cf63e9a7dd5a66a67a39677e871d614d", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--nnapi-mem", + "dmabuf", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json", + "stdout_sha256": "68ab62988066d0b81b47b0c2c24e80ac5e956989dee4f7b1ef29b1f7f4509486", + "uid": "root", + "wall_s": 1.0 + }, + { + "args": [ + "--iif-probe-only" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "iif-probe-only.json", + "iif_dev_open_events": 1, + "iif_dev_open_watch_expect": "nonzero", + "stdout_sha256": "b047c2033a418ffaae42a981b869e84814792505c366cdd178f1c162f1adf11e", + "uid": "root", + "wall_s": 0.5, + "watcher_active": true + }, + { + "args": [ + "--iif-probe-only", + "--iif-dev", + "/tmp/iif\"\\test" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "iif-probe-only-hostile-dev.json", + "stdout_sha256": "c19ce112c420f7b39985d78eea3be61cb1eefee7eae57c1d782ee40fa04d431c", + "uid": "shell", + "wall_s": 0.1 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "smoke-shell-uid-L4-T8-d512.json", + "stdout_sha256": "7687ad91bcff5c17bdb02ba1c19897f205686cf5dc6dd76abf1b6ae5f0ad4d65", + "uid": "shell", + "wall_s": 1.3 + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "mock-root-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "b89b4f218bd2c961e2fb868b90e4fa5184eb8a9942467635755d8570dfe9718a", + "uid": "root", + "wall_s": 0.9, + "watcher_active": true + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "mock-root-fault-recovery-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "f688992ce383a62b830a997fcd9d559c8acae1f1f02fd0b29bcaf9a249722817", + "uid": "root", + "wall_s": 0.6, + "watcher_active": true + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--fault-inject-quiesce-fail", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "mock-root-fault-tainted-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "8cbc76ecb6c8804ac633583a490770424401f6620add9eb09b805f9ef5ab56eb", + "uid": "root", + "wall_s": 0.5, + "watcher_active": true + } + ], + "iif_probe": { + "dev": "/dev/iif", + "probed": true, + "node_present": true, + "opened": true, + "create_ok": true, + "submit_ok": true, + "signal_ok": true, + "wait_ok": true, + "usable": true, + "open_errno": 0, + "create_errno": 0, + "submit_errno": 0, + "signal_errno": 0, + "wait_errno": 0, + "remaining_after_signal": 0, + "fence_is_sync_file": false, + "bridge_sync_file_ok": true, + "bridge_signaled": true, + "bridge_dma_ok": true, + "bridge_errno": 0, + "reason": "ok", + "abi": "google-iif-uapi", + "ioctl_create": "0xc0086900", + "ioctl_submit_signaler": "0x6981", + "ioctl_signal": "0xc0086982", + "ioctl_bridge_dma": "0x80046985", + "ioctl_signaler_done": "0x6986" + }, + "nnapi": { + "512": { + "device": "google-edgetpu", + "device_feature_level": 1000008, + "shared_mem": "ahb_blob_gpu_data_buffer", + "shared_mem_fallback": "", + "host_staged_mem": "isolated_ahb_blob", + "host_staged_mem_fallback": "", + "reusable_executions": true, + "fenced_api": true, + "fenced_dmabuf_policy": "not_applicable_ahb", + "allow_edgetpu_dmabuf_fenced_probe": false, + "fenced_dmabuf_refusals": 0, + "exec_start_calls": 1632 + }, + "1024": { + "device": "google-edgetpu", + "device_feature_level": 1000008, + "shared_mem": "ahb_blob_gpu_data_buffer", + "shared_mem_fallback": "", + "host_staged_mem": "isolated_ahb_blob", + "host_staged_mem_fallback": "", + "reusable_executions": true, + "fenced_api": true, + "fenced_dmabuf_policy": "not_applicable_ahb", + "allow_edgetpu_dmabuf_fenced_probe": false, + "fenced_dmabuf_refusals": 0, + "exec_start_calls": 1632 + }, + "2048": { + "device": "google-edgetpu", + "device_feature_level": 1000008, + "shared_mem": "ahb_blob_gpu_data_buffer", + "shared_mem_fallback": "", + "host_staged_mem": "isolated_ahb_blob", + "host_staged_mem_fallback": "", + "reusable_executions": true, + "fenced_api": true, + "fenced_dmabuf_policy": "not_applicable_ahb", + "allow_edgetpu_dmabuf_fenced_probe": false, + "fenced_dmabuf_refusals": 0, + "exec_start_calls": 1632 + } + }, + "vk_shared_tensor_ownership": { + "512": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 96 + }, + "1024": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 96 + }, + "2048": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 96 + } + }, + "iova_pool": { + "512": { + "slots": 34, + "weight_slots": 12, + "cacheability": "CACHED", + "coherency": "CACHED_SYNC", + "upfront_pin_count": 80, + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "total_submissions": 3536, + "completed_drains": 3536, + "ob_upfront_iova_maps": 0, + "ob_prewarmed_layers": 0, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "ahb_hot_loop_allocs": 0, + "nnapi_ahb_memories_registered_before_hot_loop": 4 + }, + "1024": { + "slots": 34, + "weight_slots": 12, + "cacheability": "CACHED", + "coherency": "CACHED_SYNC", + "upfront_pin_count": 80, + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "total_submissions": 3536, + "completed_drains": 3536, + "ob_upfront_iova_maps": 0, + "ob_prewarmed_layers": 0, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "ahb_hot_loop_allocs": 0, + "nnapi_ahb_memories_registered_before_hot_loop": 4 + }, + "2048": { + "slots": 34, + "weight_slots": 12, + "cacheability": "CACHED", + "coherency": "CACHED_SYNC", + "upfront_pin_count": 80, + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "total_submissions": 3536, + "completed_drains": 3536, + "ob_upfront_iova_maps": 0, + "ob_prewarmed_layers": 0, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "ahb_hot_loop_allocs": 0, + "nnapi_ahb_memories_registered_before_hot_loop": 4 + } + }, + "executor_state": { + "512": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "1024": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "2048": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + } + }, + "iif_requirement": { + "512": { + "backend": "kernel", + "signal_path": "ap_signaled_gate_imported_into_gpu_queue", + "gpu_gate": true, + "bridge_dma_ok": true, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 2 + }, + "1024": { + "backend": "kernel", + "signal_path": "ap_signaled_gate_imported_into_gpu_queue", + "gpu_gate": true, + "bridge_dma_ok": true, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 2 + }, + "2048": { + "backend": "kernel", + "signal_path": "ap_signaled_gate_imported_into_gpu_queue", + "gpu_gate": true, + "bridge_dma_ok": true, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 2 + } + }, + "arms_max_abs_diff": { + "512": 0, + "1024": 0, + "2048": 0 + }, + "all_pass": true, + "min_cos_gate": [ + 0.995 + ], + "sync_fd_handoff_check": [ + "poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1" + ], + "results": [ + { + "d_model": 512, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "host_staged", + "ran": true, + "pass": true, + "tok_per_s": 35.766218, + "ms_per_tok_p50": 27.321051, + "ms_per_tok_p99": 32.869062, + "ms_per_tok_mean": 27.795048, + "j_per_tok_gpu": 0.00155890625, + "j_per_tok_tpu": 0.00121809375, + "j_per_tok_vsys": 0.109674187, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 25.125, + "voluntary_ctxt_switches_per_tok": 25.0, + "nonvoluntary_ctxt_switches_per_tok": 0.125, + "ctx_switches_all_threads_per_tok": 25.9219, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999396411, + "cos_min_tok": 0.999128363, + "max_abs_err": 0.153796, + "inter_ip_host_copies_per_tok": 24.0, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "cpu_dma_syncs_per_tok": 52.0, + "nnapi_start_block_us_per_tok": 0.0, + "nnapi_dep_event_create_us_per_tok": 0.0, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 0.0, + "host_wait_us_per_tok": 11535.667, + "dispatch_submit_us_per_tok": 701.375, + "pipelined_chain_us_per_tok": null, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 14849.754, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 512, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "sync_file_poll", + "ran": true, + "pass": true, + "tok_per_s": 53.302744, + "ms_per_tok_p50": 18.51337, + "ms_per_tok_p99": 22.315171, + "ms_per_tok_mean": 18.588934, + "j_per_tok_gpu": 0.001231125, + "j_per_tok_tpu": 0.00093884375, + "j_per_tok_vsys": 0.0763692656, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 52.0938, + "voluntary_ctxt_switches_per_tok": 49.0156, + "nonvoluntary_ctxt_switches_per_tok": 3.0781, + "ctx_switches_all_threads_per_tok": 90.9375, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999396411, + "cos_min_tok": 0.999128363, + "max_abs_err": 0.153796, + "inter_ip_host_copies_per_tok": 0.0, + "fence_handoffs_per_tok": 24.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 24.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 24.0, + "userspace_wakeups_per_tok": 24.0, + "cpu_dma_syncs_per_tok": 4.0, + "nnapi_start_block_us_per_tok": 8903.161, + "nnapi_dep_event_create_us_per_tok": 0.0, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 12.0, + "host_wait_us_per_tok": 8251.997, + "dispatch_submit_us_per_tok": 9928.575, + "pipelined_chain_us_per_tok": null, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 512, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "r_iif", + "ran": true, + "pass": true, + "tok_per_s": 56.785738, + "ms_per_tok_p50": 17.114938, + "ms_per_tok_p99": 21.663515, + "ms_per_tok_mean": 17.486363, + "j_per_tok_gpu": 0.0012400625, + "j_per_tok_tpu": 0.000886, + "j_per_tok_vsys": 0.0752817031, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 36.5156, + "voluntary_ctxt_switches_per_tok": 19.9531, + "nonvoluntary_ctxt_switches_per_tok": 16.5625, + "ctx_switches_all_threads_per_tok": 38.1094, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999396411, + "cos_min_tok": 0.999128363, + "max_abs_err": 0.153796, + "inter_ip_host_copies_per_tok": 0.0, + "fence_handoffs_per_tok": 24.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 1.0, + "sync_files_exported_per_tok": 24.0, + "sync_files_imported_per_tok": 13.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "cpu_dma_syncs_per_tok": 4.0, + "nnapi_start_block_us_per_tok": 6767.988, + "nnapi_dep_event_create_us_per_tok": 16.904, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 12.0, + "host_wait_us_per_tok": 3207.209, + "dispatch_submit_us_per_tok": 13841.45, + "pipelined_chain_us_per_tok": 17040.323, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 1024, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "host_staged", + "ran": true, + "pass": true, + "tok_per_s": 28.934808, + "ms_per_tok_p50": 34.749688, + "ms_per_tok_p99": 38.490922, + "ms_per_tok_mean": 34.3844, + "j_per_tok_gpu": 0.00337757812, + "j_per_tok_tpu": 0.00168639062, + "j_per_tok_vsys": 0.146782047, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 26.3125, + "voluntary_ctxt_switches_per_tok": 25.5938, + "nonvoluntary_ctxt_switches_per_tok": 0.7188, + "ctx_switches_all_threads_per_tok": 27.0156, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999312121, + "cos_min_tok": 0.999042695, + "max_abs_err": 0.165879, + "inter_ip_host_copies_per_tok": 24.0, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "cpu_dma_syncs_per_tok": 52.0, + "nnapi_start_block_us_per_tok": 0.0, + "nnapi_dep_event_create_us_per_tok": 0.0, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 0.0, + "host_wait_us_per_tok": 16274.261, + "dispatch_submit_us_per_tok": 693.066, + "pipelined_chain_us_per_tok": null, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 16721.65, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 1024, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "sync_file_poll", + "ran": true, + "pass": true, + "tok_per_s": 41.193422, + "ms_per_tok_p50": 23.879411, + "ms_per_tok_p99": 28.569999, + "ms_per_tok_mean": 24.100255, + "j_per_tok_gpu": 0.00311964062, + "j_per_tok_tpu": 0.001272125, + "j_per_tok_vsys": 0.107609578, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 51.9219, + "voluntary_ctxt_switches_per_tok": 48.9062, + "nonvoluntary_ctxt_switches_per_tok": 3.0156, + "ctx_switches_all_threads_per_tok": 90.8438, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999312121, + "cos_min_tok": 0.999042695, + "max_abs_err": 0.165879, + "inter_ip_host_copies_per_tok": 0.0, + "fence_handoffs_per_tok": 24.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 24.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 24.0, + "userspace_wakeups_per_tok": 24.0, + "cpu_dma_syncs_per_tok": 4.0, + "nnapi_start_block_us_per_tok": 9111.11, + "nnapi_dep_event_create_us_per_tok": 0.0, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 12.0, + "host_wait_us_per_tok": 13468.836, + "dispatch_submit_us_per_tok": 10209.799, + "pipelined_chain_us_per_tok": null, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 1024, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "r_iif", + "ran": true, + "pass": true, + "tok_per_s": 45.415103, + "ms_per_tok_p50": 21.833828, + "ms_per_tok_p99": 27.679192, + "ms_per_tok_mean": 21.885905, + "j_per_tok_gpu": 0.00294203125, + "j_per_tok_tpu": 0.00117323438, + "j_per_tok_vsys": 0.0986188594, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 40.0156, + "voluntary_ctxt_switches_per_tok": 23.0938, + "nonvoluntary_ctxt_switches_per_tok": 16.9219, + "ctx_switches_all_threads_per_tok": 41.6562, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999312121, + "cos_min_tok": 0.999042695, + "max_abs_err": 0.165879, + "inter_ip_host_copies_per_tok": 0.0, + "fence_handoffs_per_tok": 24.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 1.0, + "sync_files_exported_per_tok": 24.0, + "sync_files_imported_per_tok": 13.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "cpu_dma_syncs_per_tok": 4.0, + "nnapi_start_block_us_per_tok": 6919.222, + "nnapi_dep_event_create_us_per_tok": 17.975, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 12.0, + "host_wait_us_per_tok": 6478.652, + "dispatch_submit_us_per_tok": 14917.961, + "pipelined_chain_us_per_tok": 21396.186, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 2048, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "host_staged", + "ran": true, + "pass": true, + "tok_per_s": 10.49263, + "ms_per_tok_p50": 95.774816, + "ms_per_tok_p99": 106.042352, + "ms_per_tok_mean": 95.071838, + "j_per_tok_gpu": 0.0182789219, + "j_per_tok_tpu": 0.00464123437, + "j_per_tok_vsys": 0.419996125, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 28.8281, + "voluntary_ctxt_switches_per_tok": 26.2812, + "nonvoluntary_ctxt_switches_per_tok": 2.5469, + "ctx_switches_all_threads_per_tok": 30.7188, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999263834, + "cos_min_tok": 0.999076329, + "max_abs_err": 0.191573, + "inter_ip_host_copies_per_tok": 24.0, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "cpu_dma_syncs_per_tok": 52.0, + "nnapi_start_block_us_per_tok": 0.0, + "nnapi_dep_event_create_us_per_tok": 0.0, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 0.0, + "host_wait_us_per_tok": 66629.519, + "dispatch_submit_us_per_tok": 1223.696, + "pipelined_chain_us_per_tok": null, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 25844.419, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 2048, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "sync_file_poll", + "ran": true, + "pass": true, + "tok_per_s": 11.77054, + "ms_per_tok_p50": 84.330701, + "ms_per_tok_p99": 95.602603, + "ms_per_tok_mean": 84.730071, + "j_per_tok_gpu": 0.0179781719, + "j_per_tok_tpu": 0.00419584375, + "j_per_tok_vsys": 0.383372375, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 52.2344, + "voluntary_ctxt_switches_per_tok": 46.0938, + "nonvoluntary_ctxt_switches_per_tok": 6.1406, + "ctx_switches_all_threads_per_tok": 96.625, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999263834, + "cos_min_tok": 0.999076329, + "max_abs_err": 0.191573, + "inter_ip_host_copies_per_tok": 0.0, + "fence_handoffs_per_tok": 24.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 24.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 24.0, + "userspace_wakeups_per_tok": 24.0, + "cpu_dma_syncs_per_tok": 4.0, + "nnapi_start_block_us_per_tok": 13239.781, + "nnapi_dep_event_create_us_per_tok": 0.0, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 12.0, + "host_wait_us_per_tok": 69793.019, + "dispatch_submit_us_per_tok": 14426.815, + "pipelined_chain_us_per_tok": null, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null, + "expected_handoffs_per_tok": 24 + }, + { + "d_model": 2048, + "layers": 12, + "tokens": 64, + "warmup": 4, + "arm": "r_iif", + "ran": true, + "pass": true, + "tok_per_s": 13.076028, + "ms_per_tok_p50": 76.1694, + "ms_per_tok_p99": 85.628775, + "ms_per_tok_mean": 76.269359, + "j_per_tok_gpu": 0.0177053437, + "j_per_tok_tpu": 0.003883875, + "j_per_tok_vsys": 0.354426047, + "odpm_rails": 32, + "cpu_ctx_switches_per_tok": 58.1406, + "voluntary_ctxt_switches_per_tok": 41.8594, + "nonvoluntary_ctxt_switches_per_tok": 16.2812, + "ctx_switches_all_threads_per_tok": 60.8906, + "ctx_source": "proc_self_status", + "hot_loop_map_count": 0, + "hot_loop_unmap_count": 0, + "cos": 0.999263834, + "cos_min_tok": 0.999076329, + "max_abs_err": 0.191573, + "inter_ip_host_copies_per_tok": 0.0, + "fence_handoffs_per_tok": 24.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 1.0, + "sync_files_exported_per_tok": 24.0, + "sync_files_imported_per_tok": 13.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "cpu_dma_syncs_per_tok": 4.0, + "nnapi_start_block_us_per_tok": 9616.854, + "nnapi_dep_event_create_us_per_tok": 22.31, + "nnapi_unfenced_hops_per_tok": 0.0, + "nnapi_event_checks_per_tok": 12.0, + "host_wait_us_per_tok": 58565.004, + "dispatch_submit_us_per_tok": 17078.08, + "pipelined_chain_us_per_tok": 75603.246, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null, + "expected_handoffs_per_tok": 24 + } + ], + "supplementary_runs": [ + { + "file": "smoke-L4-T8-d512.json", + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "expected": "PASS: live smoke of the sweep binary (all three arms, --require-iif).", + "observed": { + "uid": "root", + "exit_code": 0, + "expected_exit_code": 0, + "pass": true, + "mode": "live", + "executor": "live_vulkan_nnapi", + "tpu_backend": "nnapi", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "kernel", + "signal_path": "ap_signaled_gate_imported_into_gpu_queue", + "gpu_gate": true, + "bridge_dma_ok": true, + "signaler_ip": 3, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 2 + }, + "iif_probe": { + "probed": true, + "usable": true, + "bridge_dma_ok": true, + "bridge_errno": 0, + "reason": "ok" + }, + "nnapi": { + "shared_mem": "ahb_blob_gpu_data_buffer", + "fenced_dmabuf_policy": "not_applicable_ahb", + "exec_start_calls": 80, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 32 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 96.863326, + "cos": 0.999846113, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 8.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 5564.388 + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "tok_per_s": 140.299727, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 8.0, + "userspace_wakeups_per_tok": 8.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 147.627679, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 1.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 5.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + } + } + }, + { + "file": "w8a16-cpu-tpu-L12-T16-d512.json", + "args": [ + "--live", + "--tpu-backend", + "cpu", + "--layers", + "12", + "--tokens", + "16", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "expected": "PASS: W8A16 with the CPU-emulated TPU. Only the GPU -> CPU hop has an asynchronous producer (Vulkan) fence: both fenced arms report fence_handoffs_per_tok = L and synchronous_cpu_hops_per_tok = L; every arm counts 2L host copies. sync_file_poll waits through FdWaiter (L cross-thread wakeups/tok on both the CPU and synchronous libopenbuenos W8A16 backends; libopenbuenos reports synchronous_tpu_hops_per_tok = L). r_iif skips poll when g2t == -1.", + "observed": { + "uid": "root", + "exit_code": 0, + "expected_exit_code": 0, + "pass": true, + "mode": "live", + "executor": "live_vulkan_cpu_tpu", + "tpu_backend": "cpu", + "layers": 12, + "tokens": 16, + "d_model": 512, + "iif": { + "backend": "kernel", + "signal_path": "cpu_proxy", + "gpu_gate": false, + "bridge_dma_ok": true, + "signaler_ip": 3, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 2 + }, + "iif_probe": { + "probed": true, + "usable": true, + "bridge_dma_ok": true, + "bridge_errno": 0, + "reason": "ok" + }, + "nnapi": { + "shared_mem": "none", + "fenced_dmabuf_policy": "not_applicable", + "exec_start_calls": 0, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "full_pool_dmabuf", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 48 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 21.745421, + "cos": 0.999999876, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 24.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "tok_per_s": 24.46914, + "cos": 0.999999876, + "fence_handoffs_per_tok": 12.0, + "synchronous_cpu_hops_per_tok": 12.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 12.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 12.0, + "userspace_wakeups_per_tok": 12.0, + "inter_ip_host_copies_per_tok": 24.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 24.671081, + "cos": 0.999999876, + "fence_handoffs_per_tok": 12.0, + "synchronous_cpu_hops_per_tok": 12.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 12.0, + "sync_files_exported_per_tok": 12.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 24.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 24.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + } + } + }, + { + "file": "neg-swfallback-require-iif-L4-T8-d512.json", + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--arms", + "r_iif", + "--iif-dev", + "/dev/nonexistent-iif", + "--iif-sw-fallback", + "--require-iif", + "--json" + ], + "expected": "FAIL (exit 1): software IIF fallback with 0 kernel IIF fences must not satisfy --require-iif.", + "observed": { + "uid": "root", + "exit_code": 1, + "expected_exit_code": 1, + "pass": false, + "mode": "live", + "executor": "live_vulkan_nnapi", + "tpu_backend": "nnapi", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "sw_emulated", + "signal_path": "sw_emulated", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": true, + "requirement_met": false, + "dev_open_calls": 1 + }, + "iif_probe": { + "probed": true, + "usable": false, + "bridge_dma_ok": false, + "bridge_errno": 0, + "reason": "ENOENT" + }, + "nnapi": { + "shared_mem": "ahb_blob_gpu_data_buffer", + "fenced_dmabuf_policy": "not_applicable_ahb", + "exec_start_calls": 40, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 32 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": false, + "pass": false, + "skip_reason": "not_selected" + }, + "sync_file_poll": { + "ran": false, + "pass": false, + "skip_reason": "not_selected" + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 160.213869, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 4.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + } + } + }, + { + "file": "nobridge-ungated-L4-T8-d512.json", + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--json" + ], + "expected": "PASS without --require-iif: raw kernel /dev/iif works but the bridge request fails (bridge_dma_ok = false), so the NNAPI r_iif arm runs the ungated sync-fence chain (gpu_gate = false, 0 IIF fences).", + "observed": { + "uid": "root", + "exit_code": 0, + "expected_exit_code": 0, + "pass": true, + "mode": "live", + "executor": "live_vulkan_nnapi", + "tpu_backend": "nnapi", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "kernel", + "signal_path": "ungated_nnapi_sync_fence_chain_bridge_unavailable", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": false, + "requirement_met": false, + "dev_open_calls": 2 + }, + "iif_probe": { + "probed": true, + "usable": true, + "bridge_dma_ok": false, + "bridge_errno": 25, + "reason": "ok" + }, + "nnapi": { + "shared_mem": "ahb_blob_gpu_data_buffer", + "fenced_dmabuf_policy": "not_applicable_ahb", + "exec_start_calls": 80, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 32 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 91.067204, + "cos": 0.999846113, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 8.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 6058.281 + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "tok_per_s": 129.28379, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 8.0, + "userspace_wakeups_per_tok": 8.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 162.664186, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 4.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + } + } + }, + { + "file": "neg-nobridge-require-iif-L4-T8-d512.json", + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--require-iif", + "--json" + ], + "expected": "FAIL (exit 1): the ungated chain records 0 IIF fences, so --require-iif rejects it.", + "observed": { + "uid": "root", + "exit_code": 1, + "expected_exit_code": 1, + "pass": false, + "mode": "live", + "executor": "live_vulkan_nnapi", + "tpu_backend": "nnapi", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "kernel", + "signal_path": "ungated_nnapi_sync_fence_chain_bridge_unavailable", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": true, + "requirement_met": false, + "dev_open_calls": 2 + }, + "iif_probe": { + "probed": true, + "usable": true, + "bridge_dma_ok": false, + "bridge_errno": 25, + "reason": "ok" + }, + "nnapi": { + "shared_mem": "ahb_blob_gpu_data_buffer", + "fenced_dmabuf_policy": "not_applicable_ahb", + "exec_start_calls": 80, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 32 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 90.237623, + "cos": 0.999846113, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 8.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 6044.646 + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "tok_per_s": 132.75828, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 8.0, + "userspace_wakeups_per_tok": 8.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 157.229778, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 4.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + } + } + }, + { + "file": "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json", + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--nnapi-mem", + "dmabuf", + "--json" + ], + "expected": "PASS: google-edgetpu x dmabuf_fd x fenced execution is refused before dispatch; both fenced arms are skipped (nnapi_fenced_dmabuf_unavailable_on_edgetpu), exec_start_calls = 0, host_staged passes and the EdgeTPU HAL pids are unchanged.", + "observed": { + "uid": "root", + "exit_code": 0, + "expected_exit_code": 0, + "pass": true, + "mode": "live", + "executor": "live_vulkan_nnapi", + "tpu_backend": "nnapi", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "kernel", + "signal_path": "ap_signaled_gate_imported_into_gpu_queue", + "gpu_gate": true, + "bridge_dma_ok": true, + "signaler_ip": 3, + "require_iif": false, + "requirement_met": false, + "dev_open_calls": 2 + }, + "iif_probe": { + "probed": true, + "usable": true, + "bridge_dma_ok": true, + "bridge_errno": 0, + "reason": "ok" + }, + "nnapi": { + "shared_mem": "dmabuf_fd", + "fenced_dmabuf_policy": "blocked_edgetpu_before_dispatch", + "exec_start_calls": 0, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "full_pool_dmabuf", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 32 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 96.279542, + "cos": 0.999846113, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 8.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 5229.467 + }, + "sync_file_poll": { + "ran": false, + "pass": false, + "skip_reason": "nnapi_fenced_dmabuf_unavailable_on_edgetpu" + }, + "r_iif": { + "ran": false, + "pass": false, + "skip_reason": "nnapi_fenced_dmabuf_unavailable_on_edgetpu" + } + } + } + }, + { + "file": "iif-probe-only.json", + "args": [ + "--iif-probe-only" + ], + "expected": "/dev/iif usable and the FS_IIF_FENCE_BRIDGE_DMA bridge signals (bridge_dma_ok = true); the open watch sees the probe open the node.", + "observed": { + "uid": "root", + "exit_code": 0, + "expected_exit_code": 0, + "probe": { + "dev": "/dev/iif", + "probed": true, + "node_present": true, + "opened": true, + "create_ok": true, + "submit_ok": true, + "signal_ok": true, + "wait_ok": true, + "usable": true, + "open_errno": 0, + "create_errno": 0, + "submit_errno": 0, + "signal_errno": 0, + "wait_errno": 0, + "remaining_after_signal": 0, + "fence_is_sync_file": false, + "bridge_sync_file_ok": true, + "bridge_signaled": true, + "bridge_dma_ok": true, + "bridge_errno": 0, + "reason": "ok", + "abi": "google-iif-uapi", + "ioctl_create": "0xc0086900", + "ioctl_submit_signaler": "0x6981", + "ioctl_signal": "0xc0086982", + "ioctl_bridge_dma": "0x80046985", + "ioctl_signaler_done": "0x6986" + }, + "iif_dev_open_events": 1 + } + }, + { + "file": "iif-probe-only-hostile-dev.json", + "args": [ + "--iif-probe-only", + "--iif-dev", + "/tmp/iif\"\\test" + ], + "expected": "Strict JSON: the caller-supplied path with a quote and a backslash decodes to exactly the argument; ENOENT.", + "observed": { + "uid": "shell", + "exit_code": 0, + "expected_exit_code": 0, + "probe": { + "dev": "/tmp/iif\"\\test", + "probed": true, + "node_present": false, + "opened": false, + "create_ok": false, + "submit_ok": false, + "signal_ok": false, + "wait_ok": false, + "usable": false, + "open_errno": 2, + "create_errno": 0, + "submit_errno": 0, + "signal_errno": 0, + "wait_errno": 0, + "remaining_after_signal": 0, + "fence_is_sync_file": false, + "bridge_sync_file_ok": false, + "bridge_signaled": false, + "bridge_dma_ok": false, + "bridge_errno": 0, + "reason": "ENOENT", + "abi": "google-iif-uapi", + "ioctl_create": "0xc0086900", + "ioctl_submit_signaler": "0x6981", + "ioctl_signal": "0xc0086982", + "ioctl_bridge_dma": "0x80046985", + "ioctl_signaler_done": "0x6986" + } + } + }, + { + "file": "smoke-shell-uid-L4-T8-d512.json", + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--json" + ], + "expected": "PASS as uid shell: real sync_files answer SYNC_IOC_FILE_INFO, so the status-checked sync_file_poll arm passes; /dev/iif is EACCES, so r_iif runs ungated.", + "observed": { + "uid": "shell", + "exit_code": 0, + "expected_exit_code": 0, + "pass": true, + "mode": "live", + "executor": "live_vulkan_nnapi", + "tpu_backend": "nnapi", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "none", + "signal_path": "none", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": false, + "requirement_met": false, + "dev_open_calls": 1 + }, + "iif_probe": { + "probed": true, + "usable": false, + "bridge_dma_ok": false, + "bridge_errno": 0, + "reason": "EACCES" + }, + "nnapi": { + "shared_mem": "ahb_blob_gpu_data_buffer", + "fenced_dmabuf_policy": "not_applicable_ahb", + "exec_start_calls": 80, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "vulkan_pool_only_nnapi_ahb_external", + "vk_shared_tensor_ownership": { + "queue_family": "foreign_ext", + "release_acquire_barriers_recorded": 32 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 108.499213, + "cos": 0.999846113, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 8.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": 4562.479 + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "tok_per_s": 148.465832, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 8.0, + "userspace_wakeups_per_tok": 8.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 166.263187, + "cos": 0.999846113, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 8.0, + "sync_files_imported_per_tok": 4.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 4.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + } + } + }, + { + "file": "mock-root-L4-T8-d512.json", + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "expected": "PASS as root: --mock uses only the software fence backend; the IIF node is never opened (dev_open_calls = 0, probe not run, 0 inotify open events on /dev/iif).", + "observed": { + "uid": "root", + "exit_code": 0, + "expected_exit_code": 0, + "pass": true, + "mode": "mock", + "executor": "mock_cpu", + "tpu_backend": "cpu_emulated", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "sw_emulated", + "signal_path": "sw_emulated", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 0 + }, + "iif_probe": { + "probed": false, + "usable": false, + "bridge_dma_ok": false, + "bridge_errno": 0, + "reason": "not_probed_mock" + }, + "nnapi": { + "shared_mem": "none", + "fenced_dmabuf_policy": "not_applicable", + "exec_start_calls": 0, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "full_pool_mock", + "vk_shared_tensor_ownership": { + "queue_family": "none", + "release_acquire_barriers_recorded": 0 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "tok_per_s": 112.714695, + "cos": 0.99999996, + "fence_handoffs_per_tok": 0.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 8.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "tok_per_s": 99.762157, + "cos": 0.99999996, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 0.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 8.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 154.312537, + "cos": 0.99999996, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 8.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + }, + "iif_dev_open_events": 0 + } + }, + { + "file": "mock-root-fault-recovery-L4-T8-d512.json", + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--require-iif", + "--json" + ], + "expected": "FAIL (exit 1) by design: an injected GPU fence failure leaves the sync_file_poll mid slot INFLIGHT; the executor drains and retires it (recovery = drained_retired) and r_iif then runs and passes; 0 IIF opens.", + "observed": { + "uid": "root", + "exit_code": 1, + "expected_exit_code": 1, + "pass": false, + "mode": "mock", + "executor": "mock_cpu", + "tpu_backend": "cpu_emulated", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "sw_emulated", + "signal_path": "sw_emulated", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": true, + "requirement_met": true, + "dev_open_calls": 0 + }, + "iif_probe": { + "probed": false, + "usable": false, + "bridge_dma_ok": false, + "bridge_errno": 0, + "reason": "not_probed_mock" + }, + "nnapi": { + "shared_mem": "none", + "fenced_dmabuf_policy": "not_applicable", + "exec_start_calls": 0, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "full_pool_mock", + "vk_shared_tensor_ownership": { + "queue_family": "none", + "release_acquire_barriers_recorded": 0 + }, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 1, + "submissions_retired_after_drain": 1, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": false, + "pass": false, + "skip_reason": "not_selected" + }, + "sync_file_poll": { + "ran": false, + "pass": false, + "skip_reason": "error", + "error": "token 1: injected GPU fence failure at layer 2 (mid slot left INFLIGHT)", + "recovery": "drained_retired" + }, + "r_iif": { + "ran": true, + "pass": true, + "tok_per_s": 122.671755, + "cos": 0.99999996, + "fence_handoffs_per_tok": 8.0, + "synchronous_cpu_hops_per_tok": 0.0, + "synchronous_tpu_hops_per_tok": 0.0, + "iif_fences_per_tok": 8.0, + "sync_files_exported_per_tok": 0.0, + "sync_files_imported_per_tok": 0.0, + "userspace_fence_polls_per_tok": 0.0, + "userspace_wakeups_per_tok": 0.0, + "inter_ip_host_copies_per_tok": 0.0, + "nnapi_event_checks_per_tok": 0.0, + "tpu_hw_us_per_tok": null, + "nnapi_sync_call_us_per_tok": null + } + }, + "iif_dev_open_events": 0 + } + }, + { + "file": "mock-root-fault-tainted-L4-T8-d512.json", + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--fault-inject-quiesce-fail", + "--json" + ], + "expected": "FAIL (exit 1) by design: the same failure with a drain that cannot prove the device idle taints the executor; r_iif is skipped (executor_tainted) before it runs; 0 IIF opens.", + "observed": { + "uid": "root", + "exit_code": 1, + "expected_exit_code": 1, + "pass": false, + "mode": "mock", + "executor": "mock_cpu", + "tpu_backend": "cpu_emulated", + "layers": 4, + "tokens": 8, + "d_model": 512, + "iif": { + "backend": "sw_emulated", + "signal_path": "sw_emulated", + "gpu_gate": false, + "bridge_dma_ok": false, + "signaler_ip": 3, + "require_iif": false, + "requirement_met": false, + "dev_open_calls": 0 + }, + "iif_probe": { + "probed": false, + "usable": false, + "bridge_dma_ok": false, + "bridge_errno": 0, + "reason": "not_probed_mock" + }, + "nnapi": { + "shared_mem": "none", + "fenced_dmabuf_policy": "not_applicable", + "exec_start_calls": 0, + "fenced_dmabuf_refusals": 0 + }, + "iova_observation_scope": "full_pool_mock", + "vk_shared_tensor_ownership": { + "queue_family": "none", + "release_acquire_barriers_recorded": 0 + }, + "executor_state": { + "tainted": true, + "taint_reason": "engines not proven idle: injected quiesce failure (device idle cannot be proven)", + "failure_recoveries": 1, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 1, + "pool_inflight_slots_at_exit": 1 + }, + "arms_max_abs_diff": 0, + "arms": { + "host_staged": { + "ran": false, + "pass": false, + "skip_reason": "not_selected" + }, + "sync_file_poll": { + "ran": false, + "pass": false, + "skip_reason": "error", + "error": "token 1: injected GPU fence failure at layer 2 (mid slot left INFLIGHT) [executor tainted: engines not proven idle: injected quiesce failure (device idle cannot be proven)]", + "recovery": "tainted" + }, + "r_iif": { + "ran": false, + "pass": false, + "skip_reason": "executor_tainted", + "error": "skipped: executor tainted by an earlier arm (engines not proven idle: injected quiesce failure (device idle cannot be proven))" + } + }, + "iif_dev_open_events": 0 + } + } + ], + "iif_open_watch": { + "iif-probe-only.json": { + "events": 1, + "expect": "nonzero" + }, + "mock-root-L4-T8-d512.json": { + "events": 0, + "expect": "zero" + }, + "mock-root-fault-recovery-L4-T8-d512.json": { + "events": 0, + "expect": "zero" + }, + "mock-root-fault-tainted-L4-T8-d512.json": { + "events": 0, + "expect": "zero" + } + }, + "health": { + "hal_pids": { + "after_dmabuf_guard": "9820 9829", + "before": "9820 9829", + "before_dmabuf_guard": "9820 9829", + "end": "9820 9829" + }, + "hal_pid_exit_codes": { + "after_dmabuf_guard": 0, + "before": 0, + "before_dmabuf_guard": 0, + "end": 0 + }, + "kernel_log_new_lines": 1095, + "kernel_log_selinux_avc_denials": { + "u:r:gxp_logging:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:hal_camera_default:s0 -> u:object_r:traced_producer_socket:s0": 6, + "u:r:hal_health_default:s0 -> u:object_r:fwk_stats_service:s0": 4, + "u:r:hal_neuralnetworks_darwinn:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:mediacodec_google:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:shell:s0 -> u:object_r:iif_device:s0": 3, + "u:r:shell:s0 -> u:object_r:shell_data_file:s0": 1, + "u:r:shell:s0 -> u:object_r:sysfs_iio_devices:s0": 3, + "u:r:shell:s0 -> u:r:shell:s0": 2 + }, + "kernel_log_subsystem_fault_lines": [], + "kernel_log_generic_fault_lines": [], + "kernel_log_subsystem_info_lines": 352, + "crash_buffer": { + "after_exit_code": 0, + "before_exit_code": 0, + "cursor_mode": "logcat_T", + "lines_after": 0, + "lines_before": 0, + "new_entries_head": [], + "new_lines": 0, + "start_timestamp": "12-03 16:48:46.861" + }, + "leftover_processes": "", + "cleanup": { + "ls_after": "ls: /data/local/freesched-root-capture/fs59g13: No such file or directory", + "removed": "/data/local/freesched-root-capture/fs59g13" + }, + "tmp_entries_before": 15, + "tmp_unchanged": true, + "lock": { + "mode": "fcntl.flock LOCK_EX", + "path": "/tmp/kodiak-pixel11-adb.lock", + "waited_s": 0.0 + }, + "started_utc": "2026-12-03T21:48:44Z", + "finished_utc": "2026-12-03T21:49:44Z" + }, + "on_device_unit_test": { + "transcript": "unit-test-device.txt", + "sections": [ + { + "title": "uid shell (adb shell), TMPDIR unset", + "exit_code": 0, + "all_checks_passed": true + }, + { + "title": "uid shell, TMPDIR=", + "exit_code": 0, + "all_checks_passed": true + }, + { + "title": "uid 0 (su)", + "exit_code": 0, + "all_checks_passed": true + } + ] + }, + "host_verification": { + "schema": "freesched.proof.host_verification/v1", + "checks": [ + { + "check": "`ctest` (host, Release; all tests except this reconciliation test, which checks the file it would be recorded in)", + "result": "PASS, 67/67" + }, + { + "check": "ASan + UBSan `ctest -R token_loop` (`halt_on_error=1`)", + "result": "PASS, 22/22" + }, + { + "check": "`./scripts/clean-room-audit.sh`", + "result": "PASS, 0 errors" + }, + { + "check": "`arm64-v8a` CMake build with `libopenbuenos` (NDK `27.3.13750724`, `-Wall -Wextra -Werror`)", + "result": "PASS: bench `556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705`, unit test `c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9`" + }, + { + "check": "`arm64-v8a` CMake build without `libopenbuenos` (NDK `27.3.13750724`, `-Wall -Wextra -Werror`)", + "result": "PASS: bench `a0b03fcec656e1e089a9873c0c89b8421f6c504fff2e410715de086d9376902e`, unit test `6926645c9511c26f1fdd1677efa3ee62a3993823a01003677d64c910387f6dc4`" + }, + { + "check": "Non-Android Linux `-fsyntax-only` (bench; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" + }, + { + "check": "Non-Android Linux `-fsyntax-only` (bench + `FREESCHED_HAVE_LIBOPENBUENOS`; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" + }, + { + "check": "Non-Android Linux `-fsyntax-only` (unit test; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" + } + ] + }, + "open_issues": [ + { + "id": "intermittent-r_iif-parity", + "status": "open, not fixed by this PR", + "summary": "one d = 1024 sweep run in an earlier Generation 6 capture session on this branch completed r_iif without an error but failed the parity gate while host_staged and sync_file_poll in the same process passed; raw output and session manifest are kept under observed-failures/ (generated key observed_failures). Follow-up runs did not reproduce it. Suspected rare pre-existing race in the NNAPI fence chain / cache maintenance; the parity gate fails the run" + } + ], + "observed_failures": [ + { + "dir": "observed-failures/session3-r_iif-d1024", + "file": "bench-L12-T64-d1024.json", + "session_started_utc": "2026-12-03T03:31:36Z", + "args": [ + "--live", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "1024", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "uid": "root", + "exit_code": 1, + "expected_exit_code": 0, + "binary_sha256": "47393eab7f61a72e08dfd0c9fcc7e64694931d3655136525764b60f54b6608ca", + "stdout_sha256": "b284c2e9a30b433eb01455500105d055fc907fcff156b7f516d5bf6fa16edb9b", + "session_unexpected_exits": [ + "bench-L12-T64-d1024.json" + ], + "json_parsed": true, + "pass": false, + "executor_state": { + "tainted": false, + "taint_reason": "", + "failure_recoveries": 0, + "submissions_retired_after_drain": 0, + "ledger_inflight_at_exit": 0, + "pool_inflight_slots_at_exit": 0 + }, + "arms": { + "host_staged": { + "ran": true, + "pass": true, + "cos": 0.999312121, + "cos_min_tok": 0.999042695, + "max_abs_err": 0.165879 + }, + "sync_file_poll": { + "ran": true, + "pass": true, + "cos": 0.999312121, + "cos_min_tok": 0.999042695, + "max_abs_err": 0.165879 + }, + "r_iif": { + "ran": true, + "pass": false, + "cos": 0.923857635, + "cos_min_tok": 0.6395106, + "max_abs_err": 3.60791 + } + } + } + ] +} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/session.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/session.json new file mode 100644 index 0000000..e69447e --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/session.json @@ -0,0 +1,522 @@ +{ + "binary": { + "bench_sha256_device": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "bench_sha256_device_at_end": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "bench_sha256_host": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "unit_test_sha256_device": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9", + "unit_test_sha256_host": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9" + }, + "cleanup": { + "ls_after": "ls: /data/local/freesched-root-capture/fs59g13: No such file or directory", + "removed": "/data/local/freesched-root-capture/fs59g13" + }, + "crash_buffer": { + "after_exit_code": 0, + "before_exit_code": 0, + "cursor_mode": "logcat_T", + "lines_after": 0, + "lines_before": 0, + "new_entries_head": [], + "new_lines": 0, + "start_timestamp": "12-03 16:48:46.861" + }, + "device": { + "android_release": "17", + "model": "Pixel 11 Pro XL", + "product": "kodiak", + "security_patch": "2026-06-05", + "soc_model": "Tensor G6" + }, + "execution_dirs": { + "root_exec_dir": "/data/local/freesched-root-capture/fs59g13/root-exec", + "root_exec_mode": "0700", + "session_dir": "/data/local/freesched-root-capture/fs59g13", + "session_dir_mode": "0711", + "shell_exec_dir": "/data/local/freesched-root-capture/fs59g13/shell-exec", + "shell_exec_mode": "0755", + "shell_tmp_dir": "/data/local/freesched-root-capture/fs59g13/shell-tmp", + "shell_tmp_mode": "0700" + }, + "finished_utc": "2026-12-03T21:49:44Z", + "hal_pid_exit_codes": { + "after_dmabuf_guard": 0, + "before": 0, + "before_dmabuf_guard": 0, + "end": 0 + }, + "hal_pids": { + "after_dmabuf_guard": "9820 9829", + "before": "9820 9829", + "before_dmabuf_guard": "9820 9829", + "end": "9820 9829" + }, + "health_gate": { + "hal_pids_unchanged": true, + "new_crash_entries": 0, + "new_kernel_faults": 0 + }, + "kernel_log": { + "after_exit_code": 0, + "before_exit_code": 0, + "generic_kernel_fault_lines": [], + "new_lines": 1095, + "selinux_avc_denials": { + "u:r:gxp_logging:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:hal_camera_default:s0 -> u:object_r:traced_producer_socket:s0": 6, + "u:r:hal_health_default:s0 -> u:object_r:fwk_stats_service:s0": 4, + "u:r:hal_neuralnetworks_darwinn:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:mediacodec_google:s0 -> u:object_r:traced_producer_socket:s0": 2, + "u:r:shell:s0 -> u:object_r:iif_device:s0": 3, + "u:r:shell:s0 -> u:object_r:shell_data_file:s0": 1, + "u:r:shell:s0 -> u:object_r:sysfs_iio_devices:s0": 3, + "u:r:shell:s0 -> u:r:shell:s0": 2 + }, + "subsystem_fault_lines": [], + "subsystem_info_line_count": 352, + "subsystem_info_lines_head": [ + "[251697.880145] edgetpu santafe: Powering up", + "[251697.888756] edgetpu santafe: R52 boot stage: 0", + "[251697.888805] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[251697.892477] edgetpu santafe: Powering down", + "[251698.016535] edgetpu santafe: Powering up", + "[251698.022822] edgetpu santafe: R52 boot stage: 0", + "[251698.022874] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[251698.026345] edgetpu santafe: Powering down", + "[251698.091131] edgetpu santafe: Powering up", + "[251698.097348] edgetpu santafe: R52 boot stage: 0", + "[251698.097394] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[251698.097867] edgetpu santafe: Powering down", + "[251698.154640] edgetpu santafe: Powering up", + "[251698.162399] edgetpu santafe: R52 boot stage: 0", + "[251698.162434] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[251698.165072] edgetpu santafe: Powering down", + "[251698.299746] edgetpu santafe: Powering up", + "[251698.307156] edgetpu santafe: R52 boot stage: 0", + "[251698.307194] edgetpu santafe: loaded prod firmware (1.1 929443913)", + "[251698.310762] edgetpu santafe: Powering down" + ] + }, + "leftover_processes": "", + "lock": { + "mode": "fcntl.flock LOCK_EX", + "path": "/tmp/kodiak-pixel11-adb.lock", + "waited_s": 0.0 + }, + "overall_ok": true, + "runs": [ + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "smoke-L4-T8-d512.json", + "stdout_sha256": "e1d1a9ce15119e4c8651bab6b4083d65c18a61339f536fb3040ea6b09da72938", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "512", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d512.json", + "stdout_sha256": "9c848616f8b672c6f93dd05918bce7e53e853e2ef0b9723eb7d8d2c9da46a4ec", + "uid": "root", + "wall_s": 6.8 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "1024", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d1024.json", + "stdout_sha256": "bffe3795bd6174fc4d40d07d21ed71e7f1652151eec7d8d1552659e08ee57000", + "uid": "root", + "wall_s": 8.8 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "12", + "--tokens", + "64", + "--warmup", + "4", + "--d", + "2048", + "--min-cos", + "0.995", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "bench-L12-T64-d2048.json", + "stdout_sha256": "4bea06e429c88bb24bde770acdc4b2f96e68f2af774c7e0b11df927a3781f386", + "uid": "root", + "wall_s": 24.6 + }, + { + "args": [ + "--live", + "--tpu-backend", + "cpu", + "--layers", + "12", + "--tokens", + "16", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "w8a16-cpu-tpu-L12-T16-d512.json", + "stdout_sha256": "59fc03c4b0d3e68e5da3c8c195901c16ada3409ec4a1de4e0483a93958de52ca", + "uid": "root", + "wall_s": 2.7 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--arms", + "r_iif", + "--iif-dev", + "/dev/nonexistent-iif", + "--iif-sw-fallback", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "neg-swfallback-require-iif-L4-T8-d512.json", + "stdout_sha256": "e1d42d79a184fe9fe70e3c08941f17b824b14155bd37e64287db6fd7f9a7f621", + "uid": "root", + "wall_s": 1.0 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "nobridge-ungated-L4-T8-d512.json", + "stdout_sha256": "72d0e38d2fe6901aa35eb73c044a87e233d2a81fc84baa95d4b91ddd1806701c", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--iif-ioctl-bridge", + "0x8004697f", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "neg-nobridge-require-iif-L4-T8-d512.json", + "stdout_sha256": "02960f6d761a4a7a81eaf8d5259ff5c1cf63e9a7dd5a66a67a39677e871d614d", + "uid": "root", + "wall_s": 1.3 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--nnapi-mem", + "dmabuf", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json", + "stdout_sha256": "68ab62988066d0b81b47b0c2c24e80ac5e956989dee4f7b1ef29b1f7f4509486", + "uid": "root", + "wall_s": 1.0 + }, + { + "args": [ + "--iif-probe-only" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "iif-probe-only.json", + "iif_dev_open_events": 1, + "iif_dev_open_watch_expect": "nonzero", + "stdout_sha256": "b047c2033a418ffaae42a981b869e84814792505c366cdd178f1c162f1adf11e", + "uid": "root", + "wall_s": 0.5, + "watcher_active": true + }, + { + "args": [ + "--iif-probe-only", + "--iif-dev", + "/tmp/iif\"\\test" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "iif-probe-only-hostile-dev.json", + "stdout_sha256": "c19ce112c420f7b39985d78eea3be61cb1eefee7eae57c1d782ee40fa04d431c", + "uid": "shell", + "wall_s": 0.1 + }, + { + "args": [ + "--live", + "--tpu-backend", + "nnapi", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--min-cos", + "0.995", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "smoke-shell-uid-L4-T8-d512.json", + "stdout_sha256": "7687ad91bcff5c17bdb02ba1c19897f205686cf5dc6dd76abf1b6ae5f0ad4d65", + "uid": "shell", + "wall_s": 1.3 + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 0, + "expected_exit_code": 0, + "file": "mock-root-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "b89b4f218bd2c961e2fb868b90e4fa5184eb8a9942467635755d8570dfe9718a", + "uid": "root", + "wall_s": 0.9, + "watcher_active": true + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--require-iif", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "mock-root-fault-recovery-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "f688992ce383a62b830a997fcd9d559c8acae1f1f02fd0b29bcaf9a249722817", + "uid": "root", + "wall_s": 0.6, + "watcher_active": true + }, + { + "args": [ + "--mock", + "--layers", + "4", + "--tokens", + "8", + "--warmup", + "2", + "--d", + "512", + "--arms", + "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", + "sync_file_poll:3:2", + "--fault-inject-quiesce-fail", + "--json" + ], + "binary_sha256": "556171c5ae13db8c48135152058a301112fc50976c882dc28281b9ff97cee705", + "exit_code": 1, + "expected_exit_code": 1, + "file": "mock-root-fault-tainted-L4-T8-d512.json", + "iif_dev_open_events": 0, + "iif_dev_open_watch_expect": "zero", + "stdout_sha256": "8cbc76ecb6c8804ac633583a490770424401f6620add9eb09b805f9ef5ab56eb", + "uid": "root", + "wall_s": 0.5, + "watcher_active": true + } + ], + "schema": "freesched.proof.token_loop_session/v1", + "started_utc": "2026-12-03T21:48:44Z", + "tmp_after": { + "count": 15, + "sha256": "1bf7117b89968517d82924e40b0bca2eb8f6a8e3601f41ee1e8fe5fe98268f03" + }, + "tmp_before": { + "count": 15, + "sha256": "1bf7117b89968517d82924e40b0bca2eb8f6a8e3601f41ee1e8fe5fe98268f03" + }, + "unit_test_runs": [ + { + "all_checks_passed": true, + "binary_sha256": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9", + "exit_code": 0, + "expected_exit_code": 0, + "title": "uid shell (adb shell), TMPDIR unset", + "uid": "shell" + }, + { + "all_checks_passed": true, + "binary_sha256": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9", + "exit_code": 0, + "expected_exit_code": 0, + "title": "uid shell, TMPDIR=", + "uid": "shell" + }, + { + "all_checks_passed": true, + "binary_sha256": "c739635816221b9450e83b208a15ea2d821b782fb5abb19f8cf13b10993cbcf9", + "exit_code": 0, + "expected_exit_code": 0, + "title": "uid 0 (su)", + "uid": "root" + } + ] +} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/smoke-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/smoke-L4-T8-d512.json new file mode 100644 index 0000000..fe25247 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/smoke-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":32},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":80},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":200,"completed_drains":200,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"ap_signaled_gate_imported_into_gpu_queue","gpu_gate":true,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":96.863326,"ms_per_tok_p50":9.913256,"ms_per_tok_p99":13.802327,"ms_per_tok_mean":10.142588,"j_per_tok_gpu":0.0004705,"j_per_tok_tpu":0.00014825,"j_per_tok_vsys":0.048646875,"odpm_rails":32,"cpu_ctx_switches_per_tok":9.0000,"voluntary_ctxt_switches_per_tok":9.0000,"nonvoluntary_ctxt_switches_per_tok":0.0000,"ctx_switches_all_threads_per_tok":9.2500,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":8.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":20.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":4037.769,"dispatch_submit_us_per_tok":277.005,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":5564.388,"expected_handoffs_per_tok":8},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":140.299727,"ms_per_tok_p50":6.629390,"ms_per_tok_p99":9.749922,"ms_per_tok_mean":6.934546,"j_per_tok_gpu":0.000215875,"j_per_tok_tpu":0.0003295,"j_per_tok_vsys":0.03677575,"odpm_rails":32,"cpu_ctx_switches_per_tok":17.3750,"voluntary_ctxt_switches_per_tok":16.7500,"nonvoluntary_ctxt_switches_per_tok":0.6250,"ctx_switches_all_threads_per_tok":30.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":8.000,"userspace_wakeups_per_tok":8.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":3080.122,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":3291.706,"dispatch_submit_us_per_tok":3465.776,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":147.627679,"ms_per_tok_p50":6.354844,"ms_per_tok_p99":8.717813,"ms_per_tok_mean":6.606628,"j_per_tok_gpu":0.000457625,"j_per_tok_tpu":0.000150125,"j_per_tok_vsys":0.03489525,"odpm_rails":32,"cpu_ctx_switches_per_tok":14.5000,"voluntary_ctxt_switches_per_tok":7.8750,"nonvoluntary_ctxt_switches_per_tok":6.6250,"ctx_switches_all_threads_per_tok":16.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":1.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":5.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":2696.203,"nnapi_dep_event_create_us_per_tok":9.366,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":1221.033,"dispatch_submit_us_per_tok":5046.462,"pipelined_chain_us_per_tok":6237.936,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/smoke-shell-uid-L4-T8-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/smoke-shell-uid-L4-T8-d512.json new file mode 100644 index 0000000..a0b5963 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/smoke-shell-uid-L4-T8-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_nnapi","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":32},"tpu_backend":"nnapi","tpu_backend_requested":"nnapi","tpu_numerics":"quant8_asymm_conv1x1","tpu_backend_fallback":"","nnapi":{"device":"google-edgetpu","device_feature_level":1000008,"shared_mem":"ahb_blob_gpu_data_buffer","shared_mem_fallback":"","host_staged_mem":"isolated_ahb_blob","host_staged_mem_fallback":"","reusable_executions":true,"fenced_api":true,"fenced_dmabuf_policy":"not_applicable_ahb","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":80},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":4,"tokens":8,"warmup":2,"d_model":512,"min_cos":0.995000,"handoffs_per_tok":8,"iova_pool":{"slots":18,"weight_slots":4,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":40,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":200,"completed_drains":200,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"vulkan_pool_only_nnapi_ahb_external","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":4},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"none","signal_path":"none","gpu_gate":false,"bridge_dma_ok":false,"signaler_ip":3,"require_iif":false,"requirement_met":false,"dev_open_calls":1,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":false,"create_ok":false,"submit_ok":false,"signal_ok":false,"wait_ok":false,"usable":false,"open_errno":13,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":false,"bridge_signaled":false,"bridge_dma_ok":false,"bridge_errno":0,"reason":"EACCES","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":108.499213,"ms_per_tok_p50":9.058479,"ms_per_tok_p99":9.466417,"ms_per_tok_mean":9.033144,"j_per_tok_gpu":null,"j_per_tok_tpu":null,"j_per_tok_vsys":null,"odpm_rails":0,"cpu_ctx_switches_per_tok":9.0000,"voluntary_ctxt_switches_per_tok":9.0000,"nonvoluntary_ctxt_switches_per_tok":0.0000,"ctx_switches_all_threads_per_tok":9.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":8.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":20.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":4013.931,"dispatch_submit_us_per_tok":240.007,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":4562.479,"expected_handoffs_per_tok":8},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":148.465832,"ms_per_tok_p50":6.547161,"ms_per_tok_p99":7.068177,"ms_per_tok_mean":6.542426,"j_per_tok_gpu":null,"j_per_tok_tpu":null,"j_per_tok_vsys":null,"odpm_rails":0,"cpu_ctx_switches_per_tok":18.5000,"voluntary_ctxt_switches_per_tok":17.0000,"nonvoluntary_ctxt_switches_per_tok":1.5000,"ctx_switches_all_threads_per_tok":31.7500,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":8.000,"userspace_wakeups_per_tok":8.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":2953.715,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":3013.692,"dispatch_submit_us_per_tok":3381.007,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":166.263187,"ms_per_tok_p50":5.992672,"ms_per_tok_p99":6.694495,"ms_per_tok_mean":5.835628,"j_per_tok_gpu":null,"j_per_tok_tpu":null,"j_per_tok_vsys":null,"odpm_rails":0,"cpu_ctx_switches_per_tok":11.2500,"voluntary_ctxt_switches_per_tok":6.5000,"nonvoluntary_ctxt_switches_per_tok":4.7500,"ctx_switches_all_threads_per_tok":11.5000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999846113,"cos_min_tok":0.999822630,"max_abs_err":0.058216,"inter_ip_host_copies_per_tok":0.000,"fence_handoffs_per_tok":8.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":8.000,"sync_files_imported_per_tok":4.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":4.000,"nnapi_start_block_us_per_tok":2685.068,"nnapi_dep_event_create_us_per_tok":8.015,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":4.000,"host_wait_us_per_tok":950.932,"dispatch_submit_us_per_tok":4709.916,"pipelined_chain_us_per_tok":5675.097,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":8}],"arms_max_abs_diff":0} diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/unit-test-device.txt b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/unit-test-device.txt new file mode 100644 index 0000000..867a710 --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/unit-test-device.txt @@ -0,0 +1,21 @@ +## uid shell (adb shell), TMPDIR unset +test_iif_raw_without_bridge: /dev/iif not openable (errno 13), live probe skipped +test_sync_handoff_verdict: mock pipe accepted on poll readiness (no SYNC_IOC_FILE_INFO) +test_iif_errored_bridge_rejected: /dev/iif not openable (errno 13), live check skipped +test_token_loop_riif: all checks passed +[exit code 0] + +## uid shell, TMPDIR= +test_iif_raw_without_bridge: /dev/iif not openable (errno 13), live probe skipped +test_sync_handoff_verdict: mock pipe accepted on poll readiness (no SYNC_IOC_FILE_INFO) +test_iif_errored_bridge_rejected: /dev/iif not openable (errno 13), live check skipped +test_token_loop_riif: all checks passed +[exit code 0] + +## uid 0 (su) +test_iif_raw_without_bridge: live /dev/iif bridge_dma_ok=1, without bridge usable=1 errno=25 +test_sync_handoff_verdict: mock pipe accepted on poll readiness (no SYNC_IOC_FILE_INFO) +test_iif_errored_bridge_rejected: signal(error=-5) -> poll rc=1 revents=0x1, SYNC_IOC_FILE_INFO.status=-5, handoff rejected (fence_error_status) +test_iif_errored_bridge_rejected: signal(error=0) -> poll rc=1 revents=0x1, SYNC_IOC_FILE_INFO.status=1, handoff accepted (ok) +test_token_loop_riif: all checks passed +[exit code 0] diff --git a/proof/tensor-g6-gpu-edgetpu-riif-token-loop/w8a16-cpu-tpu-L12-T16-d512.json b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/w8a16-cpu-tpu-L12-T16-d512.json new file mode 100644 index 0000000..dc14edc --- /dev/null +++ b/proof/tensor-g6-gpu-edgetpu-riif-token-loop/w8a16-cpu-tpu-L12-T16-d512.json @@ -0,0 +1 @@ +{"pass":true,"mode":"live","executor":"live_vulkan_cpu_tpu","gpu":"PowerVR C-Series CXTP-48-1536 MC1","vk_shared_tensor_ownership":{"queue_family":"foreign_ext","release_acquire_barriers_recorded":48},"tpu_backend":"cpu","tpu_backend_requested":"cpu","tpu_numerics":"w8a16_f32","tpu_backend_fallback":"","nnapi":{"device":"","device_feature_level":null,"shared_mem":"none","shared_mem_fallback":"","host_staged_mem":"none","host_staged_mem_fallback":"","reusable_executions":false,"fenced_api":false,"fenced_dmabuf_policy":"not_applicable","allow_edgetpu_dmabuf_fenced_probe":false,"fenced_dmabuf_refusals":0,"exec_start_calls":0},"sync_fd_handoff_check":"poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1","layers":12,"tokens":16,"warmup":2,"d_model":512,"min_cos":0.999900,"handoffs_per_tok":24,"iova_pool":{"slots":34,"weight_slots":12,"cacheability":"CACHED","coherency":"CACHED_SYNC","upfront_pin_count":80,"hot_loop_map_count":0,"hot_loop_unmap_count":0,"total_submissions":1296,"completed_drains":1296,"ob_upfront_iova_maps":0,"ob_prewarmed_layers":0,"iova_observation_scope":"full_pool_dmabuf","ahb_hot_loop_allocs":0,"nnapi_ahb_memories_registered_before_hot_loop":0},"executor_state":{"tainted":false,"taint_reason":"","failure_recoveries":0,"submissions_retired_after_drain":0,"ledger_inflight_at_exit":0,"pool_inflight_slots_at_exit":0},"iif":{"backend":"kernel","signal_path":"cpu_proxy","gpu_gate":false,"bridge_dma_ok":true,"signaler_ip":3,"require_iif":true,"requirement_met":true,"dev_open_calls":2,"probe":{"dev":"/dev/iif","probed":true,"node_present":true,"opened":true,"create_ok":true,"submit_ok":true,"signal_ok":true,"wait_ok":true,"usable":true,"open_errno":0,"create_errno":0,"submit_errno":0,"signal_errno":0,"wait_errno":0,"remaining_after_signal":0,"fence_is_sync_file":false,"bridge_sync_file_ok":true,"bridge_signaled":true,"bridge_dma_ok":true,"bridge_errno":0,"reason":"ok","abi":"google-iif-uapi","ioctl_create":"0xc0086900","ioctl_submit_signaler":"0x6981","ioctl_signal":"0xc0086982","ioctl_bridge_dma":"0x80046985","ioctl_signaler_done":"0x6986"}},"arms":[{"arm":"host_staged","ran":true,"pass":true,"tok_per_s":21.745421,"ms_per_tok_p50":49.813776,"ms_per_tok_p99":52.190452,"ms_per_tok_mean":45.821056,"j_per_tok_gpu":0.00244625,"j_per_tok_tpu":0,"j_per_tok_vsys":0.088286875,"odpm_rails":32,"cpu_ctx_switches_per_tok":13.2500,"voluntary_ctxt_switches_per_tok":13.0000,"nonvoluntary_ctxt_switches_per_tok":0.2500,"ctx_switches_all_threads_per_tok":13.2500,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999876,"cos_min_tok":0.999999817,"max_abs_err":0.00229756,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":0.000,"synchronous_cpu_hops_per_tok":0.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":0.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":0.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":19302.525,"dispatch_submit_us_per_tok":537.662,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24},{"arm":"sync_file_poll","ran":true,"pass":true,"tok_per_s":24.469140,"ms_per_tok_p50":40.395182,"ms_per_tok_p99":41.558046,"ms_per_tok_mean":40.687872,"j_per_tok_gpu":0.0022448125,"j_per_tok_tpu":0,"j_per_tok_vsys":0.079668125,"odpm_rails":32,"cpu_ctx_switches_per_tok":14.8125,"voluntary_ctxt_switches_per_tok":13.1250,"nonvoluntary_ctxt_switches_per_tok":1.6875,"ctx_switches_all_threads_per_tok":29.0000,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999876,"cos_min_tok":0.999999817,"max_abs_err":0.00229756,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":12.000,"synchronous_cpu_hops_per_tok":12.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":0.000,"sync_files_exported_per_tok":12.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":12.000,"userspace_wakeups_per_tok":12.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":9948.823,"dispatch_submit_us_per_tok":569.170,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24},{"arm":"r_iif","ran":true,"pass":true,"tok_per_s":24.671081,"ms_per_tok_p50":40.259906,"ms_per_tok_p99":41.516328,"ms_per_tok_mean":40.379234,"j_per_tok_gpu":0.002084625,"j_per_tok_tpu":0,"j_per_tok_vsys":0.07672375,"odpm_rails":32,"cpu_ctx_switches_per_tok":26.7500,"voluntary_ctxt_switches_per_tok":13.3125,"nonvoluntary_ctxt_switches_per_tok":13.4375,"ctx_switches_all_threads_per_tok":26.6875,"ctx_source":"proc_self_status","hot_loop_map_count":0,"hot_loop_unmap_count":0,"cos":0.999999876,"cos_min_tok":0.999999817,"max_abs_err":0.00229756,"inter_ip_host_copies_per_tok":24.000,"fence_handoffs_per_tok":12.000,"synchronous_cpu_hops_per_tok":12.000,"synchronous_tpu_hops_per_tok":0.000,"iif_fences_per_tok":12.000,"sync_files_exported_per_tok":12.000,"sync_files_imported_per_tok":0.000,"userspace_fence_polls_per_tok":24.000,"userspace_wakeups_per_tok":0.000,"cpu_dma_syncs_per_tok":52.000,"nnapi_start_block_us_per_tok":0.000,"nnapi_dep_event_create_us_per_tok":0.000,"nnapi_unfenced_hops_per_tok":0.000,"nnapi_event_checks_per_tok":0.000,"host_wait_us_per_tok":8979.271,"dispatch_submit_us_per_tok":575.812,"pipelined_chain_us_per_tok":null,"tpu_hw_us_per_tok":null,"nnapi_sync_call_us_per_tok":null,"expected_handoffs_per_tok":24}],"arms_max_abs_diff":0} diff --git a/scripts/gen_volcanic_quant8_spirv.sh b/scripts/gen_volcanic_quant8_spirv.sh new file mode 100755 index 0000000..e6c2975 --- /dev/null +++ b/scripts/gen_volcanic_quant8_spirv.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Regenerates tools/volcanic_quant8_spirv.h from shaders/volcanic/{quant_f32_u8,dequant_u8_f32}.comp +# using glslangValidator + spirv-val (Vulkan 1.1 target). +# +# Copyright 2026 FreeSilicon Contributors +# SPDX-License-Identifier: Apache-2.0 +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +OUT="$REPO_ROOT/tools/volcanic_quant8_spirv.h" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +for s in quant_f32_u8 dequant_u8_f32; do + glslangValidator -V --target-env vulkan1.1 -o "$TMP/$s.spv" "$REPO_ROOT/shaders/volcanic/$s.comp" >/dev/null + spirv-val --target-env vulkan1.1 "$TMP/$s.spv" +done + +python3 -I - "$TMP/quant_f32_u8.spv" "$TMP/dequant_u8_f32.spv" "$OUT" <<'PY' +import struct +import sys + +def words(path): + data = open(path, "rb").read() + assert len(data) % 4 == 0 and data[:4] == b"\x03\x02\x23\x07" + w = struct.unpack("<%dI" % (len(data) // 4), data) + lines = [] + for i in range(0, len(w), 8): + lines.append(" " + ", ".join("0x%08xu" % x for x in w[i:i + 8]) + ",") + return "\n".join(lines), len(w) + +q, nq = words(sys.argv[1]) +dq, ndq = words(sys.argv[2]) +hdr = """/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ Embedded SPIR-V: FP32 <-> QUANT8_ASYMM bridges. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Generated by scripts/gen_volcanic_quant8_spirv.sh from + * shaders/volcanic/quant_f32_u8.comp and shaders/volcanic/dequant_u8_f32.comp + * via glslangValidator + spirv-val. + */ +#ifndef FREESCHED_VOLCANIC_QUANT8_SPIRV_H_ +#define FREESCHED_VOLCANIC_QUANT8_SPIRV_H_ + +#include + +static const uint32_t g_volcanic_quant_f32_u8_spv[] = { +%s +}; + +static const uint32_t g_volcanic_dequant_u8_f32_spv[] = { +%s +}; + +#endif /* FREESCHED_VOLCANIC_QUANT8_SPIRV_H_ */ +""" % (q, dq) +open(sys.argv[3], "w").write(hdr) +print("wrote %s (%d + %d words)" % (sys.argv[3], nq, ndq)) +PY diff --git a/scripts/gen_volcanic_token_loop_spirv.sh b/scripts/gen_volcanic_token_loop_spirv.sh new file mode 100755 index 0000000..7b3e2dc --- /dev/null +++ b/scripts/gen_volcanic_token_loop_spirv.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Regenerates tools/volcanic_token_loop_spirv.h from shaders/volcanic/residual_rmsnorm_f32.comp +# using glslangValidator + spirv-val (Vulkan 1.1 target). +# +# Copyright 2026 FreeSilicon Contributors +# SPDX-License-Identifier: Apache-2.0 +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SRC="$REPO_ROOT/shaders/volcanic/residual_rmsnorm_f32.comp" +OUT="$REPO_ROOT/tools/volcanic_token_loop_spirv.h" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +glslangValidator -V --target-env vulkan1.1 -o "$TMP/rmsnorm.spv" "$SRC" >/dev/null +spirv-val --target-env vulkan1.1 "$TMP/rmsnorm.spv" + +python3 -I - "$TMP/rmsnorm.spv" "$OUT" <<'PY' +import struct +import sys + +spv_path, out_path = sys.argv[1], sys.argv[2] +data = open(spv_path, "rb").read() +assert len(data) % 4 == 0 and data[:4] == b"\x03\x02\x23\x07" +words = struct.unpack("<%dI" % (len(data) // 4), data) +lines = [] +for i in range(0, len(words), 8): + lines.append(" " + ", ".join("0x%08xu" % w for w in words[i:i + 8]) + ",") +hdr = """/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ Embedded SPIR-V: Residual + RMSNorm. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Generated by scripts/gen_volcanic_token_loop_spirv.sh from + * shaders/volcanic/residual_rmsnorm_f32.comp via glslangValidator + spirv-val. + */ +#ifndef FREESCHED_VOLCANIC_TOKEN_LOOP_SPIRV_H_ +#define FREESCHED_VOLCANIC_TOKEN_LOOP_SPIRV_H_ + +#include + +static const uint32_t g_volcanic_residual_rmsnorm_f32_spv[] = { +%s +}; + +#endif /* FREESCHED_VOLCANIC_TOKEN_LOOP_SPIRV_H_ */ +""" % "\n".join(lines) +open(out_path, "w").write(hdr) +print("wrote %s (%d words)" % (out_path, len(words))) +PY diff --git a/scripts/token_loop_capture.py b/scripts/token_loop_capture.py new file mode 100755 index 0000000..37355ff --- /dev/null +++ b/scripts/token_loop_capture.py @@ -0,0 +1,623 @@ +#!/usr/bin/env python3 +"""Capture the Tensor G6 token-loop proof packet from ONE device binary. + + token_loop_capture.py --serial --build --out + [--lock /tmp/kodiak-pixel11-adb.lock] [--device-dir ] + +Holds an exclusive flock on the adb lock for the whole session, creates an +exclusive root-owned session directory under /data/local/freesched-root-capture/ +(mode 0711 root:root) with root-exec (0700 root:root) for privileged su runs +and shell-exec (0755 root:root, 0555 root:root binaries) + shell-tmp (0700 +shell:shell) for unprivileged shell runs. Binaries are streamed directly from +the host over stdin (base64 -d) into root-exec so no shell-writable directory is +ever written to, copied from, chmod'd, or chown'd by su. SHA-256 is verified +before EVERY run. Each run's raw stdout is written to a host staging directory +and validated with scripts/token_loop_receipt.py before atomically publishing +into . receipt.json and the PROOF.md tables are then generated from these +files only (scripts/token_loop_receipt.py write|check); nothing is hand-copied. + +Only the exclusive session directory under /data/local/freesched-root-capture is +created and removed; pre-existing /data/local/tmp entries are never touched +(session.json keeps only their count and a SHA-256 of the sorted listing, +before and after, read unprivileged as shell). + +Copyright 2026 FreeSilicon Contributors +SPDX-License-Identifier: Apache-2.0 +""" + +from __future__ import annotations + +import argparse +import base64 +import fcntl +import hashlib +import importlib.util +import json +import os +import posixpath +import re +import shlex +import shutil +import subprocess +import sys +import tempfile +import time + +BENCH = "volcanic_tpu_token_loop_bench" +UNIT = "test_token_loop_riif" +HAL = "android.hardware.neuralnetworks@service-darwinn-aidl" +DEVICE_TMP_ROOT = posixpath.join("/data", "local", "tmp") +ROOT_EXEC_PARENT = "/data/local/freesched-root-capture" +LIVE_L4 = ["--live", "--tpu-backend", "nnapi", "--layers", "4", "--tokens", "8", "--warmup", "2", "--d", "512", + "--min-cos", "0.995"] +HOSTILE_DEV = '/tmp/iif"\\test' +SUBSYS_RE = re.compile(r"pvr|powervr|rogue|volcanic|edgetpu|darwinn|\biif\b|gxp|mali|kgsl|dma.?buf|dma_heap", + re.IGNORECASE) +FAULT_RE = re.compile(r"fault|mmu|hwr|lockup|hang|time.?out|timed out|reset|crash|error|\berr\b|fail|panic|oops|bug:|" + r"watchdog|warning:|call trace|unable to handle|internal error", re.IGNORECASE) +HAL_SNAPSHOT_KEYS = ("before", "before_dmabuf_guard", "after_dmabuf_guard", "end") +HAL_PIDS_RE = re.compile(r"^[1-9][0-9]*(?: [1-9][0-9]*)*$") +LOGCAT_TS_RE = re.compile(r"^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}$") +LOGCAT_HEADER_RE = re.compile(r"^-{5,}\s+beginning of\b") + + +def classify_kernel_log(new: list[str]) -> dict: + """Every new kernel line is classified (no cap on fault lines): SELinux denials, subsystem fault/error lines, + other subsystem lines and generic kernel fault lines.""" + avc, sub_fault, sub_info, gen_fault = {}, [], [], [] + for ln in new: + if "avc:" in ln: + m = re.search(r"scontext=(\S+).*?tcontext=(\S+)", ln) + key = f"{m.group(1)} -> {m.group(2)}" if m else "?" + avc[key] = avc.get(key, 0) + 1 + elif SUBSYS_RE.search(ln): + (sub_fault if FAULT_RE.search(ln) else sub_info).append(ln) + elif re.search(r"unable to handle|internal error|kernel panic|bug:|call trace|watchdog|lockup", ln, re.I): + gen_fault.append(ln) + return {"new_lines": len(new), "selinux_avc_denials": avc, "subsystem_fault_lines": sub_fault, + "generic_kernel_fault_lines": gen_fault, "subsystem_info_line_count": len(sub_info), + "subsystem_info_lines_head": sub_info[:20]} + +# (file, uid, args, expected exit code, /dev/iif open watch: None | "zero" | "nonzero") +RUNS = [ + ("smoke-L4-T8-d512.json", "root", [*LIVE_L4, "--require-iif", "--json"], 0, None), + *[(f"bench-L12-T64-d{d}.json", "root", + ["--live", "--tpu-backend", "nnapi", "--layers", "12", "--tokens", "64", "--warmup", "4", "--d", str(d), + "--min-cos", "0.995", "--require-iif", "--json"], 0, None) for d in (512, 1024, 2048)], + ("w8a16-cpu-tpu-L12-T16-d512.json", "root", + ["--live", "--tpu-backend", "cpu", "--layers", "12", "--tokens", "16", "--warmup", "2", "--d", "512", + "--require-iif", "--json"], 0, None), + ("neg-swfallback-require-iif-L4-T8-d512.json", "root", + [*LIVE_L4, "--arms", "r_iif", "--iif-dev", "/dev/nonexistent-iif", "--iif-sw-fallback", "--require-iif", + "--json"], 1, None), + ("nobridge-ungated-L4-T8-d512.json", "root", [*LIVE_L4, "--iif-ioctl-bridge", "0x8004697f", "--json"], 0, None), + ("neg-nobridge-require-iif-L4-T8-d512.json", "root", + [*LIVE_L4, "--iif-ioctl-bridge", "0x8004697f", "--require-iif", "--json"], 1, None), + ("edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json", "root", [*LIVE_L4, "--nnapi-mem", "dmabuf", "--json"], 0, + None), + ("iif-probe-only.json", "root", ["--iif-probe-only"], 0, "nonzero"), + ("iif-probe-only-hostile-dev.json", "shell", ["--iif-probe-only", "--iif-dev", HOSTILE_DEV], 0, None), + ("smoke-shell-uid-L4-T8-d512.json", "shell", [*LIVE_L4, "--json"], 0, None), + ("mock-root-L4-T8-d512.json", "root", + ["--mock", "--layers", "4", "--tokens", "8", "--warmup", "2", "--d", "512", "--require-iif", "--json"], 0, + "zero"), + ("mock-root-fault-recovery-L4-T8-d512.json", "root", + ["--mock", "--layers", "4", "--tokens", "8", "--warmup", "2", "--d", "512", "--arms", "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", "sync_file_poll:3:2", "--require-iif", "--json"], 1, "zero"), + ("mock-root-fault-tainted-L4-T8-d512.json", "root", + ["--mock", "--layers", "4", "--tokens", "8", "--warmup", "2", "--d", "512", "--arms", "sync_file_poll,r_iif", + "--fault-inject-gpu-fence", "sync_file_poll:3:2", "--fault-inject-quiesce-fail", "--json"], 1, "zero"), +] +UNIT_RUNS = [("uid shell (adb shell), TMPDIR unset", "shell", ""), + ("uid shell, TMPDIR=", "shell", "TMPDIR={TMP} "), + ("uid 0 (su)", "root", "unset LD_LIBRARY_PATH && TMPDIR={TMP} ")] + + +def parse_hal_pids(raw: object) -> tuple[int, ...] | None: + """Parse a space-separated list of one or more positive integer PIDs.""" + if not isinstance(raw, str) or not HAL_PIDS_RE.fullmatch(raw): + return None + pids = tuple(int(tok) for tok in raw.split(" ")) + return pids if pids and all(pid > 0 for pid in pids) else None + + +def normalize_logcat_timestamp(raw: str) -> str: + """Normalize device date '+%m-%d %H:%M:%S.%N' output to Android logcat -T MM-DD HH:MM:SS.mmm.""" + s = raw.strip() + m = re.fullmatch(r"(\d{2}-\d{2} \d{2}:\d{2}:\d{2})\.(\d{3})\d*", s) + if m: + return f"{m.group(1)}.{m.group(2)}" + m2 = re.fullmatch(r"(\d{2}-\d{2} \d{2}:\d{2}:\d{2})(?:\.%[0-9]*N)?", s) + if m2: + return f"{m2.group(1)}.000" + raise RuntimeError(f"unexpected device date output for logcat cursor: {raw!r}") + + +def filter_crash_log_lines(lines: list[str]) -> list[str]: + """Drop blank lines and '--------- beginning of ...' logcat section headers.""" + return [ln for ln in lines if ln.strip() and not LOGCAT_HEADER_RE.match(ln)] + + +def health_gate(hal: dict, kernel_log: dict, crash_buffer: dict, hal_exit_codes: dict | None = None) -> dict: + """Clean-session gate: no new kernel faults, no new crash entries, valid unchanged HAL pids.""" + faults = len(kernel_log.get("subsystem_fault_lines") or []) + len(kernel_log.get("generic_kernel_fault_lines") or []) + crashes = int((crash_buffer or {}).get("new_lines") or 0) + parsed: list[tuple[int, ...]] = [] + hal_ok = isinstance(hal, dict) + if hal_ok: + for k in HAL_SNAPSHOT_KEYS: + if k not in hal: + hal_ok = False + break + if hal_exit_codes is not None and hal_exit_codes.get(k) != 0: + hal_ok = False + break + pids = parse_hal_pids(hal[k]) + if pids is None: + hal_ok = False + break + parsed.append(tuple(sorted(pids))) + unchanged = hal_ok and len(parsed) == len(HAL_SNAPSHOT_KEYS) and all(p == parsed[0] for p in parsed) + return {"new_kernel_faults": faults, "new_crash_entries": crashes, "hal_pids_unchanged": unchanged} + + +def create_staging_dir(out_dir: str, explicit_staging: str | None = None) -> str: + """Create a fresh staging directory outside out_dir so existing captures stay untouched until publish.""" + out_abs = os.path.abspath(out_dir) + parent = os.path.dirname(out_abs) or "." + os.makedirs(parent, exist_ok=True) + if explicit_staging is not None: + stage_abs = os.path.abspath(explicit_staging) + if stage_abs == out_abs or os.path.commonpath([out_abs, stage_abs]) == out_abs: + raise ValueError(f"--staging-dir {explicit_staging!r} must be outside --out {out_dir!r}") + os.makedirs(os.path.dirname(stage_abs) or ".", exist_ok=True) + os.makedirs(stage_abs, exist_ok=False) + return stage_abs + ts = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + base = os.path.basename(out_abs) or "capture" + return tempfile.mkdtemp(prefix=f".{base}.staging-{ts}-{os.getpid()}-", dir=parent) + + +def _write_staged_bytes(path: str, data: bytes) -> None: + with open(path, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + + +def publish_staged_capture(stage_dir: str, out_dir: str, filenames: list[str]) -> None: + """Atomically replace out_dir capture artifacts from stage_dir (session.json last), rolling back on error.""" + for name in filenames: + src = os.path.join(stage_dir, name) + if not os.path.isfile(src): + raise RuntimeError(f"staged capture artifact missing before publish: {src}") + os.makedirs(out_dir, exist_ok=True) + out_abs = os.path.abspath(out_dir) + parent = os.path.dirname(out_abs) or "." + base = os.path.basename(out_abs) or "capture" + backup_dir = tempfile.mkdtemp(prefix=f".{base}.backup-{os.getpid()}-", dir=parent) + backed_up: set[str] = set() + replaced: list[str] = [] + try: + for name in filenames: + dst = os.path.join(out_dir, name) + if os.path.exists(dst): + bak = os.path.join(backup_dir, name) + try: + os.link(dst, bak) + except OSError: + shutil.copy2(dst, bak) + backed_up.add(name) + ordered = [n for n in filenames if n != "session.json"] + if "session.json" in filenames: + ordered.append("session.json") + for name in ordered: + os.replace(os.path.join(stage_dir, name), os.path.join(out_dir, name)) + replaced.append(name) + except Exception: + for name in reversed(replaced): + dst = os.path.join(out_dir, name) + bak = os.path.join(backup_dir, name) + try: + if name in backed_up and os.path.exists(bak): + os.replace(bak, dst) + elif os.path.exists(dst): + os.unlink(dst) + except OSError: + pass + shutil.rmtree(backup_dir, ignore_errors=True) + raise + shutil.rmtree(backup_dir, ignore_errors=True) + shutil.rmtree(stage_dir, ignore_errors=True) + + +def listing_digest(names: list[str]) -> dict: + """Pre-existing /data/local/tmp entries belong to other work: record only count + digest, never names.""" + names = sorted(names) + return {"count": len(names), "sha256": hashlib.sha256("\n".join(names).encode()).hexdigest()} + + +def sha256_file(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def validate_device_dir(raw: str) -> str: + """Require an exclusive single-level session directory directly under ROOT_EXEC_PARENT.""" + if not isinstance(raw, str) or not raw.startswith("/") or re.search(r"\s", raw): + raise ValueError(f"invalid --device-dir {raw!r}: must be an absolute path without whitespace") + if ".." in raw.split("/"): + raise ValueError(f"invalid --device-dir {raw!r}: '..' path segments are forbidden") + norm = posixpath.normpath(raw) + base = posixpath.basename(norm) + if (posixpath.dirname(norm) != ROOT_EXEC_PARENT or not base or base.startswith((".", "-")) + or not re.fullmatch(r"[A-Za-z0-9._-]+", base)): + raise ValueError( + f"invalid --device-dir {raw!r}: must name a direct child of {ROOT_EXEC_PARENT} ([A-Za-z0-9._-]+)") + return norm + + +def root_exec_dir_for(session_dir: str) -> str: + """Root-only 0700 execution directory inside the validated root-owned session dir.""" + return posixpath.join(session_dir, "root-exec") + + +def shell_exec_dir_for(session_dir: str) -> str: + """Root-owned 0755 execution directory for unprivileged shell runs inside session dir.""" + return posixpath.join(session_dir, "shell-exec") + + +def shell_tmp_dir_for(session_dir: str) -> str: + """Shell-owned 0700 TMPDIR inside the root-owned session dir (never written/chmod'd inside by su).""" + return posixpath.join(session_dir, "shell-tmp") + + +def shell_exec_setup_cmd(qroot: str, qshell: str, qshell_tmp: str) -> str: + """Label shell-exec and an empty root-owned shell-tmp, then hand shell-tmp to shell. + + `chcon -h` runs while root still owns every path. shell-tmp is chowned to shell only + after that non-recursive label succeeds. shell-exec and its 0555 binaries stay root:root. + """ + ctx = "u:object_r:shell_data_file:s0" + label = "chcon -h " + ctx + return ( + f"set -e; mkdir -m 0755 -- {qshell}; chown 0:0 {qshell}; " + f"cp -- {qroot}/{BENCH} {qshell}/{BENCH}; cp -- {qroot}/{UNIT} {qshell}/{UNIT}; " + f"chown 0:0 {qshell}/{BENCH} {qshell}/{UNIT}; chmod 0555 {qshell}/{BENCH} {qshell}/{UNIT}; " + f"mkdir -m 0700 -- {qshell_tmp}; chown 0:0 {qshell_tmp}; " + f"{label} {qshell}; {label} {qshell}/{BENCH}; {label} {qshell}/{UNIT}; {label} {qshell_tmp}; " + f"chown shell:shell {qshell_tmp}" + ) + + +def watched_bench_cmd(qroot: str, bench_cmd: str) -> str: + """Run inotifyd around a bench command and fail if the watcher dies or writes stderr.""" + txt = f"{qroot}/iif-watch.txt" + err = f"{qroot}/iif-watch.err" + status = f"{qroot}/iif-watch.status" + fail = f"printf '%s\\n' 'watcher_active: false' > {status}; exit 1" + return ( + "set -e; " + f"inotifyd - /dev/iif:r > {txt} 2> {err} & WPID=$!; " + "sleep 0.1; " + f"if ! kill -0 \"$WPID\" 2>/dev/null || [ -s {err} ]; then {fail}; fi; " + "set +e; " + f"({bench_cmd}); rc=$?; set -e; " + "sleep 0.1; " + f"if ! kill -0 \"$WPID\" 2>/dev/null || [ -s {err} ]; then {fail}; fi; " + f"printf '%s\\n' 'watcher_active: true' > {status}; " + "kill \"$WPID\"; exit $rc" + ) + + +def _load_receipt_module(): + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "token_loop_receipt.py") + spec = importlib.util.spec_from_file_location("token_loop_receipt", path) + if spec is None or spec.loader is None: + raise RuntimeError(f"unable to load receipt validator from {path}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class Device: + def __init__(self, serial: str, session_dir: str): + self.serial = serial + self.session_dir = session_dir + self.qsession = shlex.quote(session_dir) + self.root_d = root_exec_dir_for(session_dir) + self.qroot_d = shlex.quote(self.root_d) + self.shell_d = shell_exec_dir_for(session_dir) + self.qshell_d = shlex.quote(self.shell_d) + self.shell_tmp_d = shell_tmp_dir_for(session_dir) + self.qshell_tmp_d = shlex.quote(self.shell_tmp_d) + + def adb(self, *args: str, check: bool = True, input_bytes: bytes | None = None) -> subprocess.CompletedProcess: + p = subprocess.run(["adb", "-s", self.serial, *args], input=input_bytes, capture_output=True, check=False) + if check and p.returncode != 0: + out = (p.stderr or p.stdout).decode(errors="replace").strip() + raise RuntimeError(f"adb {args}: rc={p.returncode} {out}") + return p + + def sh(self, cmd: str, uid: str = "shell", check: bool = False, + input_bytes: bytes | None = None) -> subprocess.CompletedProcess: + remote = cmd if uid == "shell" else "su -c " + shlex.quote(cmd) + return self.adb("shell", remote, check=check, input_bytes=input_bytes) + + def text(self, cmd: str, uid: str = "shell", *, check: bool = True) -> str: + return self.sh(cmd, uid, check=check).stdout.decode(errors="replace").replace("\r", "") + + def push_root_file(self, host_path: str, dst_path: str, mode: str = "0755") -> None: + """Stream host file directly into a root-owned directory via base64 stdin (never touches /data/local/tmp).""" + with open(host_path, "rb") as f: + b64 = base64.b64encode(f.read()) + b"\n" + qdst = shlex.quote(dst_path) + self.sh( + f"set -e; umask 077; tr -d '\\r' | base64 -d > {qdst}; chown 0:0 {qdst}; chmod {mode} {qdst}", + "root", + check=True, + input_bytes=b64, + ) + + def sha(self, name: str, *, directory: str | None = None, uid: str = "root") -> str: + target_q = shlex.quote(self.root_d if directory is None else directory) + out = self.text(f"sha256sum {target_q}/{shlex.quote(name)}", uid).split() + if not out or not re.fullmatch(r"[0-9a-f]{64}", out[0]): + raise RuntimeError(f"unexpected sha256sum output for {name}: {out!r}") + return out[0] + + +def capture_hal_snapshot(dev: Device) -> tuple[str, int]: + p = dev.sh(f"pidof {HAL}", check=False) + raw = " ".join(p.stdout.decode(errors="replace").replace("\r", "").split()) + return raw, p.returncode + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--serial", required=True) + ap.add_argument("--build", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--staging-dir", default=None) + ap.add_argument("--lock", default="/tmp/kodiak-pixel11-adb.lock") + ap.add_argument("--device-dir", default=posixpath.join(ROOT_EXEC_PARENT, "fs59g12")) + a = ap.parse_args(argv[1:] if argv is not None else None) + try: + session_dir = validate_device_dir(a.device_dir) + except ValueError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + bench, unit = os.path.join(a.build, BENCH), os.path.join(a.build, UNIT) + host_bench_sha, host_unit_sha = sha256_file(bench), sha256_file(unit) + lock = open(a.lock, "a") + t_lock = time.time() + fcntl.flock(lock, fcntl.LOCK_EX) + try: + try: + stage_dir = create_staging_dir(a.out, a.staging_dir) + except (OSError, ValueError) as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + dev = Device(a.serial, session_dir) + qsession = dev.qsession + root_dir = dev.root_d + qroot = dev.qroot_d + shell_dir = dev.shell_d + qshell = dev.qshell_d + shell_tmp = dev.shell_tmp_d + qshell_tmp = dev.qshell_tmp_d + qparent = shlex.quote(ROOT_EXEC_PARENT) + qtmp_root = shlex.quote(DEVICE_TMP_ROOT) + created_session_dir = False + shell_exec_ready = False + + def ensure_shell_exec_dir() -> None: + nonlocal shell_exec_ready + if shell_exec_ready: + return + # Both shell-exec and shell-tmp live directly under the root-owned 0711 session_dir; + # su never touches any shell-writable parent directory. + dev.sh(shell_exec_setup_cmd(qroot, qshell, qshell_tmp), "root", check=True) + sh_bsha = dev.sha(BENCH, directory=shell_dir, uid="root") + sh_usha = dev.sha(UNIT, directory=shell_dir, uid="root") + if sh_bsha != host_bench_sha or sh_usha != host_unit_sha: + raise RuntimeError("shell execution binary SHA-256 mismatch before execution") + shell_exec_ready = True + + try: + m: dict = {"schema": "freesched.proof.token_loop_session/v1", + "lock": {"path": a.lock, "mode": "fcntl.flock LOCK_EX", + "waited_s": round(time.time() - t_lock, 1)}, + "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + prop = lambda k: dev.text(f"getprop {k}").strip() + m["device"] = {"model": prop("ro.product.model"), "product": prop("ro.product.device"), + "android_release": prop("ro.build.version.release"), + "security_patch": prop("ro.build.version.security_patch"), + "soc_model": prop("ro.soc.model")} + # Read-only listing as unprivileged shell to verify /data/local/tmp is never touched. + tmp_before = dev.text(f"ls {qtmp_root}", "shell").split() + m["tmp_before"] = listing_digest(tmp_before) + hal: dict[str, str] = {} + hal_rc: dict[str, int] = {} + hal["before"], hal_rc["before"] = capture_hal_snapshot(dev) + klog0 = dev.text("dmesg", "root").splitlines() + crash_start_ts = normalize_logcat_timestamp(dev.text("date '+%m-%d %H:%M:%S.%N'")) + crash_before_raw = dev.text(f"logcat -b crash -T {shlex.quote(crash_start_ts)} -d").splitlines() + crash0 = filter_crash_log_lines(crash_before_raw) + # Prepare root-owned parent (0711 root:root, traversal-only for shell) and exclusive + # session directory (no -p), then stream binaries directly into 0700 root-exec. + dev.sh( + f"set -e; test -d /data/local; test ! -L /data/local; " + f"if [ -L {qparent} ]; then exit 1; fi; " + f"if [ ! -e {qparent} ]; then mkdir -m 0711 -- {qparent}; fi; " + f'test -d {qparent}; [ "$(stat -c %u {qparent})" = 0 ]; chmod 0711 {qparent}', + "root", + check=True, + ) + dev.sh(f"mkdir -m 0711 -- {qsession}", "root", check=True) + created_session_dir = True + dev.sh(f"set -e; chown 0:0 {qsession}; mkdir -m 0700 -- {qroot}; chown 0:0 {qroot}", "root", check=True) + dev.push_root_file(bench, posixpath.join(root_dir, BENCH), "0755") + dev.push_root_file(unit, posixpath.join(root_dir, UNIT), "0755") + root_bench_sha = dev.sha(BENCH, directory=root_dir, uid="root") + root_unit_sha = dev.sha(UNIT, directory=root_dir, uid="root") + if root_bench_sha != host_bench_sha: + raise RuntimeError(f"root bench SHA-256 mismatch before execution: {root_bench_sha} != {host_bench_sha}") + if root_unit_sha != host_unit_sha: + raise RuntimeError(f"root unit-test SHA-256 mismatch before execution: {root_unit_sha} != {host_unit_sha}") + m["execution_dirs"] = { + "session_dir": session_dir, + "session_dir_mode": "0711", + "root_exec_dir": root_dir, + "root_exec_mode": "0700", + "shell_exec_dir": shell_dir, + "shell_exec_mode": "0755", + "shell_tmp_dir": shell_tmp, + "shell_tmp_mode": "0700", + } + m["binary"] = {"bench_sha256_host": host_bench_sha, "bench_sha256_device": root_bench_sha, + "unit_test_sha256_host": host_unit_sha, "unit_test_sha256_device": root_unit_sha} + runs = [] + for fname, uid, args, want, watch in RUNS: + if fname.startswith("edgetpu-dmabuf"): + hal["before_dmabuf_guard"], hal_rc["before_dmabuf_guard"] = capture_hal_snapshot(dev) + if uid == "root": + run_dir, qrun_dir = root_dir, qroot + else: + ensure_shell_exec_dir() + run_dir, qrun_dir = shell_dir, qshell + pre_sha = dev.sha(BENCH, directory=run_dir, uid="root") + if pre_sha != host_bench_sha: + raise RuntimeError(f"{fname}: bench SHA-256 mismatch before run: {pre_sha} != {host_bench_sha}") + cmd = f"cd {qrun_dir} && unset LD_LIBRARY_PATH && ./{BENCH} " + " ".join(shlex.quote(x) for x in args) + if watch: + cmd = watched_bench_cmd(qroot, cmd) + t0 = time.time() + p = dev.sh(cmd, uid) + dt = time.time() - t0 + _write_staged_bytes(os.path.join(stage_dir, fname), p.stdout) + run = {"file": fname, "uid": uid, "args": args, "exit_code": p.returncode, "expected_exit_code": want, + "binary_sha256": pre_sha, "stdout_sha256": hashlib.sha256(p.stdout).hexdigest(), + "wall_s": round(dt, 1)} + if watch: + status = dev.text(f"cat {qroot}/iif-watch.status", "root").strip() + run["watcher_active"] = status == "watcher_active: true" + ev = [ln for ln in dev.text(f"cat {qroot}/iif-watch.txt", "root").splitlines() if ln.strip()] + run["iif_dev_open_events"] = len(ev) + run["iif_dev_open_watch_expect"] = watch + dev.sh( + f"rm -f -- {qroot}/iif-watch.txt {qroot}/iif-watch.err {qroot}/iif-watch.status", + "root", + check=True, + ) + if fname.startswith("edgetpu-dmabuf"): + hal["after_dmabuf_guard"], hal_rc["after_dmabuf_guard"] = capture_hal_snapshot(dev) + print(f"{fname}: rc={p.returncode} (want {want}) {dt:.1f}s", flush=True) + runs.append(run) + m["runs"] = runs + unit_txt = [] + unit_runs = [] + for title, uid, env in UNIT_RUNS: + if uid == "root": + run_dir, qrun_dir = root_dir, qroot + tmp_q = qroot + else: + ensure_shell_exec_dir() + run_dir, qrun_dir = shell_dir, qshell + tmp_q = qshell_tmp + pre_unit_sha = dev.sha(UNIT, directory=run_dir, uid="root") + if pre_unit_sha != host_unit_sha: + raise RuntimeError(f"unit ({title}): SHA-256 mismatch before run: {pre_unit_sha} != {host_unit_sha}") + p = dev.sh(f"cd {qrun_dir} && {env.format(TMP=tmp_q)}./{UNIT} 2>&1", uid) + out_s = p.stdout.decode(errors="replace").replace("\r", "") + unit_txt.append(f"## {title}\n{out_s}[exit code {p.returncode}]\n") + passed = p.returncode == 0 and "test_token_loop_riif: all checks passed" in out_s + unit_runs.append({"title": title, "uid": uid, "exit_code": p.returncode, "expected_exit_code": 0, + "all_checks_passed": passed, "binary_sha256": pre_unit_sha}) + print(f"unit ({title}): rc={p.returncode} pass={passed}", flush=True) + _write_staged_bytes(os.path.join(stage_dir, "unit-test-device.txt"), + ("\n".join(unit_txt)).encode("utf-8")) + m["unit_test_runs"] = unit_runs + m["binary"]["bench_sha256_device_at_end"] = dev.sha(BENCH, directory=root_dir, uid="root") + hal["end"], hal_rc["end"] = capture_hal_snapshot(dev) + m["hal_pids"] = hal + m["hal_pid_exit_codes"] = hal_rc + klog1 = dev.text("dmesg", "root").splitlines() + seen = set(klog0) # the whole pre-session buffer: only lines logged during the session count as new + new = [ln for ln in klog1 if ln not in seen] + m["kernel_log"] = {**classify_kernel_log(new), "before_exit_code": 0, "after_exit_code": 0} + crash_after_raw = dev.text(f"logcat -b crash -T {shlex.quote(crash_start_ts)} -d").splitlines() + crash1 = filter_crash_log_lines(crash_after_raw) + crash_seen = set(crash0) + new_crashes = [ln for ln in crash1 if ln not in crash_seen] + m["crash_buffer"] = {"cursor_mode": "logcat_T", "start_timestamp": crash_start_ts, + "lines_before": len(crash0), "lines_after": len(crash1), + "new_lines": len(new_crashes), "new_entries_head": new_crashes[:20], + "before_exit_code": 0, "after_exit_code": 0} + m["leftover_processes"] = dev.text(f"pidof {BENCH} {UNIT}", "root", check=False).strip() + if created_session_dir: + dev.sh(f"rm -rf -- {qsession}", "root", check=True) + created_session_dir = False + p_ls = dev.sh(f"ls -d -- {qsession} 2>&1", "root", check=False) + if p_ls.returncode == 0: + raise RuntimeError(f"cleanup failed: {session_dir} still exists after rm -rf") + m["cleanup"] = { + "removed": session_dir, + "ls_after": p_ls.stdout.decode(errors="replace").replace("\r", "").strip(), + } + m["tmp_after"] = listing_digest(dev.text(f"ls {qtmp_root}", "shell").split()) + m["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + bad = [r["file"] for r in runs if r["exit_code"] != r["expected_exit_code"]] + bad_unit = [u["title"] for u in unit_runs + if u["exit_code"] != u["expected_exit_code"] or not u["all_checks_passed"]] + shas = {r["binary_sha256"] for r in runs} | {m["binary"]["bench_sha256_device"], + m["binary"]["bench_sha256_device_at_end"], host_bench_sha} + unit_shas = {u["binary_sha256"] for u in unit_runs} | {m["binary"]["unit_test_sha256_device"], + host_unit_sha} + hg = health_gate(m["hal_pids"], m["kernel_log"], m["crash_buffer"], m["hal_pid_exit_codes"]) + m["health_gate"] = hg + health_ok = (hg["new_kernel_faults"] == 0 and hg["new_crash_entries"] == 0 + and hg["hal_pids_unchanged"] is True) + basic_ok = (not bad and not bad_unit and len(shas) == 1 and len(unit_shas) == 1 + and m["tmp_before"] == m["tmp_after"] and not m["leftover_processes"] and health_ok) + m["overall_ok"] = basic_ok + _write_staged_bytes(os.path.join(stage_dir, "session.json"), + (json.dumps(m, indent=2, sort_keys=True) + "\n").encode("utf-8")) + receipt_mod = _load_receipt_module() + val_errors = receipt_mod.validate_staged_capture(stage_dir) + overall_ok = basic_ok and not val_errors + if val_errors: + m["overall_ok"] = False + m["validation_errors"] = val_errors + _write_staged_bytes(os.path.join(stage_dir, "session.json"), + (json.dumps(m, indent=2, sort_keys=True) + "\n").encode("utf-8")) + for ve in val_errors: + print(f"VALIDATION ERROR: {ve}", file=sys.stderr) + staged_files = [*[r["file"] for r in runs], "unit-test-device.txt", "session.json"] + if overall_ok: + publish_staged_capture(stage_dir, a.out, staged_files) + else: + print(f"CAPTURE FAILED: previous {a.out} preserved; failed staging retained at {stage_dir}", + file=sys.stderr) + print(json.dumps({"unexpected_exit": bad, "failed_unit_tests": bad_unit, + "distinct_bench_sha256": sorted(shas), "health_gate": hg, + "validation_errors": val_errors, + "overall_ok": overall_ok, "published": overall_ok, + "staging_dir": None if overall_ok else stage_dir})) + return 0 if overall_ok else 1 + except RuntimeError as exc: + print(f"ERROR: {exc} (failed staging retained at {stage_dir})", file=sys.stderr) + return 1 + finally: + if created_session_dir: + dev.sh(f"rm -rf -- {qsession}", "root", check=False) + finally: + fcntl.flock(lock, fcntl.LOCK_UN) + lock.close() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/token_loop_receipt.py b/scripts/token_loop_receipt.py new file mode 100644 index 0000000..c16a796 --- /dev/null +++ b/scripts/token_loop_receipt.py @@ -0,0 +1,1352 @@ +#!/usr/bin/env python3 +"""Generate / verify the token-loop proof receipt from the checked-in raw files. + + token_loop_receipt.py write + Regenerate every measured field of receipt.json and every + block of PROOF.md from the raw run outputs + (*.json), session.json (capture manifest), unit-test-device.txt and + host-verification.json. + token_loop_receipt.py check + Fail unless receipt.json and PROOF.md are exactly what `write` produces, + and: + * every raw file's SHA-256 equals its session.json stdout_sha256; + * every run used ONE bench binary (per-run device SHA-256, push-time + device SHA-256, end-of-session SHA-256 and host SHA-256 identical); + * every run's exit code equals its expected exit code; + * hand-written prose (PROOF.md outside generated blocks, receipt.json + narrative keys) carries no measured value: no decimal number, ratio, + percentage, SHA-256 or >= 3-digit integer except the allowlist. + token_loop_receipt.py host-verify --host-build D --a64-ob D --a64-noob D --ndk D [--asan-build D] + Run the host checks (ctest without this reconciliation test, ASan/UBSan + token-loop ctest, clean-room audit, arm64 compile matrix) and record them + in host-verification.json. + +Copyright 2026 FreeSilicon Contributors +SPDX-License-Identifier: Apache-2.0 +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import platform +import re +import shutil +import subprocess +import sys +import tempfile + +ARMS = ("host_staged", "sync_file_poll", "r_iif") +SWEEP = (512, 1024, 2048) +# Filename -> (layers, tokens, d_model) configured for that capture. +FILE_DIMS = { + "smoke-L4-T8-d512.json": (4, 8, 512), + "bench-L12-T64-d512.json": (12, 64, 512), + "bench-L12-T64-d1024.json": (12, 64, 1024), + "bench-L12-T64-d2048.json": (12, 64, 2048), + "w8a16-cpu-tpu-L12-T16-d512.json": (12, 16, 512), +} +GEN_KEYS = ("device", "binary", "runs", "iif_probe", "nnapi", "vk_shared_tensor_ownership", "iova_pool", + "executor_state", "iif_requirement", "arms_max_abs_diff", "all_pass", "min_cos_gate", "results", + "supplementary_runs", "iif_open_watch", "health", "on_device_unit_test", "host_verification", + "sync_fd_handoff_check", "observed_failures") +# What each run must show; expectations are structural (no measured values). +EXPECT = { + "smoke-L4-T8-d512.json": "PASS: live smoke of the sweep binary (all three arms, --require-iif).", + "bench-L12-T64-d512.json": "PASS: sweep, d = 512.", + "bench-L12-T64-d1024.json": "PASS: sweep, d = 1024.", + "bench-L12-T64-d2048.json": "PASS: sweep, d = 2048.", + "w8a16-cpu-tpu-L12-T16-d512.json": + "PASS: W8A16 with the CPU-emulated TPU. Only the GPU -> CPU hop has an asynchronous producer (Vulkan) " + "fence: both fenced arms report fence_handoffs_per_tok = L and synchronous_cpu_hops_per_tok = L; every arm " + "counts 2L host copies. sync_file_poll waits through FdWaiter (L cross-thread wakeups/tok on both the CPU " + "and synchronous libopenbuenos W8A16 backends; libopenbuenos reports synchronous_tpu_hops_per_tok = L). " + "r_iif skips poll when g2t == -1.", + "neg-swfallback-require-iif-L4-T8-d512.json": + "FAIL (exit 1): software IIF fallback with 0 kernel IIF fences must not satisfy --require-iif.", + "nobridge-ungated-L4-T8-d512.json": + "PASS without --require-iif: raw kernel /dev/iif works but the bridge request fails (bridge_dma_ok = " + "false), so the NNAPI r_iif arm runs the ungated sync-fence chain (gpu_gate = false, 0 IIF fences).", + "neg-nobridge-require-iif-L4-T8-d512.json": + "FAIL (exit 1): the ungated chain records 0 IIF fences, so --require-iif rejects it.", + "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json": + "PASS: google-edgetpu x dmabuf_fd x fenced execution is refused before dispatch; both fenced arms are " + "skipped (nnapi_fenced_dmabuf_unavailable_on_edgetpu), exec_start_calls = 0, host_staged passes and the " + "EdgeTPU HAL pids are unchanged.", + "iif-probe-only.json": "/dev/iif usable and the FS_IIF_FENCE_BRIDGE_DMA bridge signals (bridge_dma_ok = true); " + "the open watch sees the probe open the node.", + "iif-probe-only-hostile-dev.json": + "Strict JSON: the caller-supplied path with a quote and a backslash decodes to exactly the argument; ENOENT.", + "smoke-shell-uid-L4-T8-d512.json": + "PASS as uid shell: real sync_files answer SYNC_IOC_FILE_INFO, so the status-checked sync_file_poll arm " + "passes; /dev/iif is EACCES, so r_iif runs ungated.", + "mock-root-L4-T8-d512.json": + "PASS as root: --mock uses only the software fence backend; the IIF node is never opened (dev_open_calls = " + "0, probe not run, 0 inotify open events on /dev/iif).", + "mock-root-fault-recovery-L4-T8-d512.json": + "FAIL (exit 1) by design: an injected GPU fence failure leaves the sync_file_poll mid slot INFLIGHT; the " + "executor drains and retires it (recovery = drained_retired) and r_iif then runs and passes; 0 IIF opens.", + "mock-root-fault-tainted-L4-T8-d512.json": + "FAIL (exit 1) by design: the same failure with a drain that cannot prove the device idle taints the " + "executor; r_iif is skipped (executor_tainted) before it runs; 0 IIF opens.", +} +ARM_KEYS = ("ran", "pass", "skip_reason", "error", "recovery", "tok_per_s", "cos", "fence_handoffs_per_tok", + "synchronous_cpu_hops_per_tok", "synchronous_tpu_hops_per_tok", "iif_fences_per_tok", + "sync_files_exported_per_tok", + "sync_files_imported_per_tok", "userspace_fence_polls_per_tok", "userspace_wakeups_per_tok", + "inter_ip_host_copies_per_tok", "nnapi_event_checks_per_tok", "tpu_hw_us_per_tok", + "nnapi_sync_call_us_per_tok") +# Prose allowlist (never measurements): model sizes / limits, the year, the NDK version, the min-cos gates, +# "SHA-256", the U+2212 code point and the literal malformed CLI value "12x". +PROSE_ALLOW = {"512", "1024", "1536", "2048", "4096", "2026", "27.3", "0.995", "0.9999", "256", "2212", "12x"} +GEN_RE = re.compile(r"\n(.*?)\n", re.S) +NUM_RE = re.compile(r"(? None: + if not isinstance(fname, str) or os.path.basename(fname) != fname or fname in ("", ".", "..", "session.json"): + raise ValueError(f"{where}: invalid raw filename {fname!r}") + + +def parse_unit_test_sections(unit_text: str) -> list[dict]: + sections = [] + for block in unit_text.split("## ")[1:]: + title, _, body = block.partition("\n") + m = re.search(r"\[exit code (-?\d+)\]", body) + sections.append({"title": title.strip(), "exit_code": int(m.group(1)) if m else None, + "all_checks_passed": "test_token_loop_riif: all checks passed" in body}) + return sections + + +class Packet: + def __init__(self, d, *, require_host: bool = True): + self.d = d + self.session = _load(os.path.join(d, "session.json")) + for r in self.session["runs"]: + _check_plain_filename(r["file"], "session.json") + self.raw = {r["file"]: _load(os.path.join(d, r["file"])) for r in self.session["runs"]} + host_path = os.path.join(d, "host-verification.json") + if require_host or os.path.isfile(host_path): + self.host = _load(host_path) + else: + self.host = None + with open(os.path.join(d, "unit-test-device.txt"), encoding="utf-8") as f: + self.unit = f.read() + self.bench = {d_: self.raw[f"bench-L12-T64-d{d_}.json"] for d_ in SWEEP} + # Failures seen in archived sessions are kept, hash-verified and reported, never dropped. + self.failures = [] + fdir = os.path.join(d, "observed-failures") + for sub in sorted(os.listdir(fdir)) if os.path.isdir(fdir) else []: + sdir = os.path.join(fdir, sub) + if not os.path.isdir(sdir): + raise ValueError(f"observed-failures/{sub}: expected an archived session directory") + sp = os.path.join(sdir, "session.json") + if not os.path.isfile(sp): + raise ValueError(f"observed-failures/{sub}: missing session.json") + sess = _load(sp) + sess_shas = {x["binary_sha256"] for x in sess["runs"]} | { + sess["binary"][k] for k in ("bench_sha256_host", "bench_sha256_device", "bench_sha256_device_at_end") + } + if len(sess_shas) != 1: + raise ValueError(f"observed-failures/{sub}: bench binaries differ across runs: {sorted(sess_shas)}") + listed_sub = set() + for r in sess["runs"]: + _check_plain_filename(r["file"], f"observed-failures/{sub}/session.json") + listed_sub.add(r["file"]) + unexpected = (r["exit_code"] != r["expected_exit_code"] + or (r["expected_exit_code"] == 0 and r.get("pass") is False)) + path = os.path.join(sdir, r["file"]) + exists = os.path.isfile(path) + if unexpected and not exists: + raise ValueError(f"observed-failures/{sub}/{r['file']}: missing raw output for unexpected exit " + f"({r['exit_code']} != expected {r['expected_exit_code']})") + if exists: + if _sha(path) != r["stdout_sha256"]: + raise ValueError( + f"observed-failures/{sub}/{r['file']}: SHA-256 differs from its session manifest") + byte_count = os.path.getsize(path) + doc = None + json_parsed = False + parse_error = None + try: + parsed = _load(path) + if isinstance(parsed, dict): + doc = parsed + json_parsed = True + else: + parse_error = f"expected JSON object, got {type(parsed).__name__}" + except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc: + parse_error = str(exc) + if unexpected or not json_parsed or (r["expected_exit_code"] == 0 and doc.get("pass") is False): + meta = {"json_parsed": json_parsed, "byte_count": byte_count, "parse_error": parse_error} + self.failures.append((sub, sess, r, path, doc, meta)) + for fn in sorted(os.listdir(sdir)): + if fn != "session.json" and fn not in listed_sub: + raise ValueError(f"observed-failures/{sub}/{fn}: raw file not listed in archived session.json") + + def run(self, fname): + return next(r for r in self.session["runs"] if r["file"] == fname) + + # ------------------------------------------------------------------ receipt + def generated(self): + s, b512 = self.session, self.bench[512] + g = {} + g["device"] = {**s["device"], "gpu": b512["gpu"], "tpu_nnapi_device": b512["nnapi"]["device"], + "iif_dev": self.raw["iif-probe-only.json"]["dev"], "iif_backend": b512["iif"]["backend"], + "iif_signaler_ip": b512["iif"]["signaler_ip"]} + b = s["binary"] + g["binary"] = {"sha256": b["bench_sha256_host"], "unit_test_sha256": b["unit_test_sha256_host"], + "bench_sha256_device_after_push": b["bench_sha256_device"], + "bench_sha256_device_at_end": b["bench_sha256_device_at_end"], + "unit_test_sha256_device": b["unit_test_sha256_device"], + "distinct_bench_sha256_across_runs": sorted({r["binary_sha256"] for r in s["runs"]})} + g["runs"] = s["runs"] + g["iif_probe"] = self.raw["iif-probe-only.json"] + g["nnapi"] = {str(k): v["nnapi"] for k, v in self.bench.items()} + g["vk_shared_tensor_ownership"] = {str(k): v["vk_shared_tensor_ownership"] for k, v in self.bench.items()} + g["iova_pool"] = {str(k): v["iova_pool"] for k, v in self.bench.items()} + g["executor_state"] = {str(k): v["executor_state"] for k, v in self.bench.items()} + g["iif_requirement"] = {str(k): {x: v["iif"][x] for x in ("backend", "signal_path", "gpu_gate", + "bridge_dma_ok", "require_iif", + "requirement_met", "dev_open_calls")} + for k, v in self.bench.items()} + g["arms_max_abs_diff"] = {str(k): v["arms_max_abs_diff"] for k, v in self.bench.items()} + g["all_pass"] = all(v["pass"] for v in self.bench.values()) + g["min_cos_gate"] = sorted({v["min_cos"] for v in self.bench.values()}) + g["sync_fd_handoff_check"] = sorted({v["sync_fd_handoff_check"] for v in self.bench.values()}) + g["results"] = [{"d_model": k, "layers": v["layers"], "tokens": v["tokens"], "warmup": v["warmup"], + **{x: y for x, y in a.items()}} for k, v in self.bench.items() for a in v["arms"]] + sup = [] + for r in s["runs"]: + f = r["file"] + if f.startswith("bench-L12"): + continue + doc = self.raw[f] + obs = {"uid": r["uid"], "exit_code": r["exit_code"], "expected_exit_code": r["expected_exit_code"]} + if "arms" in doc: + obs.update({"pass": doc["pass"], "mode": doc["mode"], "executor": doc["executor"], + "tpu_backend": doc["tpu_backend"], "layers": doc["layers"], "tokens": doc["tokens"], + "d_model": doc["d_model"], "iif": {k: v for k, v in doc["iif"].items() if k != "probe"}, + "iif_probe": {k: doc["iif"]["probe"][k] for k in ("probed", "usable", "bridge_dma_ok", + "bridge_errno", "reason")}, + "nnapi": {k: doc["nnapi"][k] for k in ("shared_mem", "fenced_dmabuf_policy", + "exec_start_calls", "fenced_dmabuf_refusals")}, + "iova_observation_scope": doc["iova_pool"]["iova_observation_scope"], + "vk_shared_tensor_ownership": doc["vk_shared_tensor_ownership"], + "executor_state": doc["executor_state"], "arms_max_abs_diff": doc["arms_max_abs_diff"], + "arms": {a["arm"]: {k: a[k] for k in ARM_KEYS if k in a} for a in doc["arms"]}}) + else: + obs.update({"probe": doc}) + if "iif_dev_open_events" in r: + obs["iif_dev_open_events"] = r["iif_dev_open_events"] + sup.append({"file": f, "args": r["args"], "expected": EXPECT[f], "observed": obs}) + g["supplementary_runs"] = sup + g["iif_open_watch"] = {r["file"]: {"events": r["iif_dev_open_events"], "expect": r["iif_dev_open_watch_expect"]} + for r in s["runs"] if "iif_dev_open_events" in r} + kl = s["kernel_log"] + g["health"] = {"hal_pids": s["hal_pids"], "hal_pid_exit_codes": s.get("hal_pid_exit_codes"), + "kernel_log_new_lines": kl["new_lines"], + "kernel_log_selinux_avc_denials": kl["selinux_avc_denials"], + "kernel_log_subsystem_fault_lines": kl["subsystem_fault_lines"], + "kernel_log_generic_fault_lines": kl["generic_kernel_fault_lines"], + "kernel_log_subsystem_info_lines": kl["subsystem_info_line_count"], + "crash_buffer": s["crash_buffer"], "leftover_processes": s["leftover_processes"], + "cleanup": s["cleanup"], "tmp_entries_before": s["tmp_before"]["count"], + "tmp_unchanged": s["tmp_before"] == s["tmp_after"], "lock": s["lock"], + "started_utc": s["started_utc"], "finished_utc": s["finished_utc"]} + sections = parse_unit_test_sections(self.unit) + g["on_device_unit_test"] = {"transcript": "unit-test-device.txt", "sections": sections} + g["host_verification"] = self.host + obs_failures = [] + for sub, sess, r, path, doc, meta in self.failures: + entry = { + "dir": f"observed-failures/{sub}", + "file": r["file"], + "session_started_utc": sess["started_utc"], + "args": r["args"], + "uid": r["uid"], + "exit_code": r["exit_code"], + "expected_exit_code": r["expected_exit_code"], + "binary_sha256": r["binary_sha256"], + "stdout_sha256": r["stdout_sha256"], + "session_unexpected_exits": [x["file"] for x in sess["runs"] + if x["exit_code"] != x["expected_exit_code"]], + "json_parsed": meta["json_parsed"], + } + if meta["json_parsed"] and isinstance(doc, dict) and "arms" in doc: + entry["pass"] = doc.get("pass") + entry["executor_state"] = doc.get("executor_state") + entry["arms"] = { + a["arm"]: {k: a[k] for k in ("ran", "pass", "cos", "cos_min_tok", "max_abs_err", "error") + if k in a} + for a in doc["arms"] + } + else: + entry["stdout_bytes"] = meta["byte_count"] + entry["json_parse_error"] = meta["parse_error"] or "missing arms array" + entry["pass"] = False + entry["executor_state"] = None + entry["arms"] = {} + obs_failures.append(entry) + g["observed_failures"] = obs_failures + return g + + # ------------------------------------------------------------------ PROOF.md blocks + def blocks(self, *, include_host: bool = True): + s, g = self.session, self.generated() + out = {} + bn = g["binary"] + out["binary"] = ( + f"- Bench binary SHA-256 `{bn['sha256']}` (host build tree, after streaming to device, before every one of the " + f"{len(s['runs'])} runs and at the end of the session: {len(bn['distinct_bench_sha256_across_runs'])} " + f"distinct value). Unit test SHA-256 `{bn['unit_test_sha256']}`.\n" + f"- Device: {s['device']['model']} (`{s['device']['product']}`, {s['device']['soc_model']}), Android " + f"{s['device']['android_release']}, security patch {s['device']['security_patch']}. Session " + f"{s['started_utc']} -> {s['finished_utc']} under `{s['lock']['mode']}` on `{s['lock']['path']}`.\n") + out["repro"] = repro_command_block(self.run("bench-L12-T64-d512.json")["args"]) + rows = ["| d | arm | tok/s | ms/tok p50 | ms/tok p99 | vol. ctx-sw/tok | userspace polls/tok | " + "cross-thread wakeups/tok | host copies/tok | IIF fences/tok | imported sync_files/tok | " + "NNAPI event checks/tok | cos | GPU J/tok | EdgeTPU J/tok | VSYS J/tok |", + ("| ---: | --- | " + "---: | " * 14).rstrip()] + trows = ["| d | arm | `host_wait_us_per_tok` | `dispatch_submit_us_per_tok` | `nnapi_start_block_us_per_tok` | " + "`nnapi_dep_event_create_us_per_tok` | `pipelined_chain_us_per_tok` |", + "| ---: | --- | ---: | ---: | ---: | ---: | ---: |"] + for d_, doc in self.bench.items(): + for a in doc["arms"]: + rows.append(f"| {d_} | `{a['arm']}` | " + " | ".join(j(a[k]) for k in ( + "tok_per_s", "ms_per_tok_p50", "ms_per_tok_p99", "voluntary_ctxt_switches_per_tok", + "userspace_fence_polls_per_tok", "userspace_wakeups_per_tok", "inter_ip_host_copies_per_tok", + "iif_fences_per_tok", "sync_files_imported_per_tok", "nnapi_event_checks_per_tok", "cos", + "j_per_tok_gpu", "j_per_tok_tpu", "j_per_tok_vsys")) + " |") + trows.append(f"| {d_} | `{a['arm']}` | " + " | ".join(j(a[k]) for k in ( + "host_wait_us_per_tok", "dispatch_submit_us_per_tok", "nnapi_start_block_us_per_tok", + "nnapi_dep_event_create_us_per_tok", "pipelined_chain_us_per_tok")) + " |") + out["results"] = "\n".join(rows) + "\n" + out["timing"] = "\n".join(trows) + "\n" + facts = [] + for d_, doc in self.bench.items(): + facts.append(f"- d = {d_}: top-level `pass` = {j(doc['pass'])}, `arms_max_abs_diff` = " + f"{j(doc['arms_max_abs_diff'])}, `hot_loop_map_count` = {doc['iova_pool']['hot_loop_map_count']}" + f", `hot_loop_unmap_count` = {doc['iova_pool']['hot_loop_unmap_count']}, `total_submissions` = " + f"`completed_drains` = {doc['iova_pool']['total_submissions']} / " + f"{doc['iova_pool']['completed_drains']}, IIF `{doc['iif']['backend']}` (`gpu_gate` = " + f"{j(doc['iif']['gpu_gate'])}, `bridge_dma_ok` = {j(doc['iif']['bridge_dma_ok'])}, " + f"`requirement_met` = {j(doc['iif']['requirement_met'])}), ownership barriers recorded = " + f"{doc['vk_shared_tensor_ownership']['release_acquire_barriers_recorded']} " + f"(`{doc['vk_shared_tensor_ownership']['queue_family']}`), `executor_state.failure_recoveries` " + f"= {doc['executor_state']['failure_recoveries']}.") + out["sweep_facts"] = "\n".join(facts) + "\n" + obs = [] + for d_, doc in self.bench.items(): + hs, sf, ri = (arm(doc, x) for x in ARMS) + obs.append(f"- d = {d_}: `r_iif` / `host_staged` throughput = {ri['tok_per_s'] / hs['tok_per_s']:.2f}x, " + f"`r_iif` / `sync_file_poll` = {ri['tok_per_s'] / sf['tok_per_s']:.2f}x; `r_iif` VSYS J/tok vs. " + f"`host_staged` = {100.0 * (ri['j_per_tok_vsys'] / hs['j_per_tok_vsys'] - 1.0):+.1f}%; " + f"host wait `r_iif` {ri['host_wait_us_per_tok'] / 1e3:.1f} ms vs. `sync_file_poll` " + f"{sf['host_wait_us_per_tok'] / 1e3:.1f} ms per token.") + out["observations"] = "\n".join(obs) + "\n" + sup = ["| file | uid | exit (expected) | top-level pass | arms (ran / pass / skip) | key observation |", + "| --- | --- | --- | --- | --- | --- |"] + for r in s["runs"]: + f = r["file"] + if f.startswith("bench-L12"): + continue + doc = self.raw[f] + if "arms" in doc: + arms_s = ", ".join(f"`{a['arm']}` " + ("ran/" + ("pass" if a["pass"] else "FAIL") if a["ran"] + else "skip: " + a.get("skip_reason", "")) + for a in doc["arms"]) + key = (f"iif `{doc['iif']['backend']}` / `{doc['iif']['signal_path']}`, requirement_met " + f"{j(doc['iif']['requirement_met'])}, dev_open_calls {doc['iif']['dev_open_calls']}, " + f"exec_start_calls {doc['nnapi']['exec_start_calls']}, recoveries " + f"{doc['executor_state']['failure_recoveries']}, tainted {j(doc['executor_state']['tainted'])}") + top = j(doc["pass"]) + else: + arms_s, top = "-", "-" + key = (f"dev {j(doc['dev'])}, usable {j(doc['usable'])}, bridge_dma_ok {j(doc['bridge_dma_ok'])}, " + f"reason {j(doc['reason'])}") + if "iif_dev_open_events" in r: + key += f"; inotify /dev/iif open events {r['iif_dev_open_events']}" + sup.append(f"| `{f}` | {r['uid']} | {r['exit_code']} ({r['expected_exit_code']}) | {top} | {arms_s} | " + f"{key} |") + out["supplementary"] = "\n".join(sup) + "\n" + w = self.raw["w8a16-cpu-tpu-L12-T16-d512.json"] + wr = ["| arm | tok/s | fence handoffs/tok | synchronous CPU hops/tok | polls/tok | wakeups/tok | " + "SYNC_FD exports/tok | IIF fences/tok | host copies/tok | cos |", ("| --- | " + "---: | " * 9).rstrip()] + for a in w["arms"]: + wr.append(f"| `{a['arm']}` | " + " | ".join(j(a[k]) for k in ( + "tok_per_s", "fence_handoffs_per_tok", "synchronous_cpu_hops_per_tok", "userspace_fence_polls_per_tok", + "userspace_wakeups_per_tok", "sync_files_exported_per_tok", "iif_fences_per_tok", + "inter_ip_host_copies_per_tok", "cos")) + " |") + out["w8a16"] = "\n".join(wr) + "\n" + rec = [] + for f in ("mock-root-fault-recovery-L4-T8-d512.json", "mock-root-fault-tainted-L4-T8-d512.json"): + doc, r = self.raw[f], self.run(f) + st = doc["executor_state"] + rec.append(f"- `{f}` (exit {r['exit_code']}): " + "; ".join( + f"`{a['arm']}` " + (("ran, pass = " + j(a["pass"])) if a["ran"] else + (f"not run ({a.get('skip_reason')})" + + (f", recovery = `{a['recovery']}`" if "recovery" in a else ""))) + for a in doc["arms"] if a.get("skip_reason") != "not_selected") + + f"; `executor_state` = {j(st)}.") + out["recovery"] = "\n".join(rec) + "\n" + watch = [f"- `{f}`: {v['events']} open event(s) (expected {v['expect']})" for f, v in g["iif_open_watch"].items()] + m = self.raw["mock-root-L4-T8-d512.json"] + watch.append(f"- `mock-root-L4-T8-d512.json`: `iif.backend` = {j(m['iif']['backend'])}, `dev_open_calls` = " + f"{m['iif']['dev_open_calls']}, `probe.probed` = {j(m['iif']['probe']['probed'])}, " + f"`probe.reason` = {j(m['iif']['probe']['reason'])}; live sweep runs report `dev_open_calls` = " + f"{self.bench[512]['iif']['dev_open_calls']} (probe + kept device fd).") + out["mock_iif"] = "\n".join(watch) + "\n" + h = g["health"] + dm = self.raw["edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json"] + out["health"] = ( + f"- NNAPI EdgeTPU HAL pids: before `{h['hal_pids']['before']}`, before the DMA-BUF guard run " + f"`{h['hal_pids']['before_dmabuf_guard']}`, after it `{h['hal_pids']['after_dmabuf_guard']}`, at the end " + f"`{h['hal_pids']['end']}`. DMA-BUF guard run: `shared_mem` = {j(dm['nnapi']['shared_mem'])}, " + f"`fenced_dmabuf_policy` = {j(dm['nnapi']['fenced_dmabuf_policy'])}, `exec_start_calls` = " + f"{dm['nnapi']['exec_start_calls']}.\n" + f"- Kernel log ({h['kernel_log_new_lines']} new lines, every line classified): GPU / EdgeTPU / IIF / DMA-BUF " + f"fault or error lines: {len(h['kernel_log_subsystem_fault_lines'])}; generic kernel fault lines: " + f"{len(h['kernel_log_generic_fault_lines'])}; other subsystem lines (e.g. EdgeTPU power up/down): " + f"{h['kernel_log_subsystem_info_lines']}; SELinux denials: " + + (", ".join(f"`{k}` x{v}" for k, v in sorted(h["kernel_log_selinux_avc_denials"].items())) or "none") + + (f". Crash buffer (since `{h['crash_buffer']['start_timestamp']}`): " + f"{h['crash_buffer']['new_lines']} new entries.\n" + if h["crash_buffer"].get("start_timestamp") + else f". Crash buffer: {h['crash_buffer']['new_lines']} new lines.\n") + + f"- Leftover bench/test processes: {j(h['leftover_processes'])}. Session directory " + f"`{h['cleanup']['removed']}` removed (`{h['cleanup']['ls_after']}`)" + + (f"; root execution directory `{h['cleanup']['root_removed']}` removed " + f"(`{h['cleanup']['root_ls_after']}`)" + if h["cleanup"].get("root_removed") else "") + + f"; the {h['tmp_entries_before']} pre-existing `/data/local/tmp` entries are unchanged: " + f"{j(h['tmp_unchanged'])}.\n") + ut = [f"- {x['title']}: exit {x['exit_code']}, all checks passed = {j(x['all_checks_passed'])}" + for x in g["on_device_unit_test"]["sections"]] + out["unit"] = "\n".join(ut) + "\n" + if include_host: + hv = self.host + hr = ["| Check | Result |", "| --- | --- |"] + for item in hv["checks"]: + hr.append(f"| {item['check']} | {item['result']} |") + out["host"] = "\n".join(hr) + "\n" + fl = [] + for f in g["observed_failures"]: + same = "same " if f["binary_sha256"] == bn["sha256"] else "archived " + if f.get("json_parsed", True) and f.get("arms"): + arms_s = "; ".join(f"`{k}` pass = {j(v['pass'])}, cos = {j(v.get('cos'))}, cos_min_tok = " + f"{j(v.get('cos_min_tok'))}, max_abs_err = {j(v.get('max_abs_err'))}" + for k, v in f["arms"].items()) + detail = f"{arms_s}; `executor_state` = {j(f['executor_state'])}" + else: + detail = (f"no valid JSON (`json_parsed` = false, `stdout_bytes` = {f.get('stdout_bytes', 0)}, " + f"`json_parse_error` = {j(f.get('json_parse_error'))})") + fl.append(f"- `{f['dir']}/{f['file']}` (session {f['session_started_utc']}, {same}bench SHA-256 " + f"`{f['binary_sha256']}`, exit {f['exit_code']}, expected {f['expected_exit_code']}; unexpected " + f"exits in that session: {', '.join(f'`{x}`' for x in f['session_unexpected_exits'])}): " + f"{detail}.") + out["observed_failures"] = ("\n".join(fl) if fl else "- none") + "\n" + return out + + +def repro_command_block(args: list) -> str: + """Sweep reproduction command. `--tpu-backend nnapi` is an explicit request, not a fallback.""" + if not _has_cli_flag_value(args, "--tpu-backend", "nnapi"): + raise ValueError(f"sweep reproduction command must explicitly request --tpu-backend nnapi (got {args!r})") + shown: list[str] = [] + i = 0 + while i < len(args): + if args[i] == "--d" and i + 1 < len(args): + shown.extend(["--d", ""]) + i += 2 + continue + shown.append(str(args[i])) + i += 1 + body = "unset LD_LIBRARY_PATH; volcanic_tpu_token_loop_bench " + " ".join(shown) + return ( + "- Command (per `d`): `" + body + "`.\n" + "- Build/backend: `--tpu-backend nnapi` was explicitly requested (not an automatic fallback).\n" + ) + + +def dimension_errors(fname: str, doc: object) -> list[str]: + """Reported layers/tokens/d_model must match the dimensions encoded in the filename.""" + want = FILE_DIMS.get(fname) + if want is None: + return [] + if not isinstance(doc, dict): + return [f"{fname}: missing JSON object for dimension check"] + layers, tokens, d_model = want + errors = [] + for key, exp in (("layers", layers), ("tokens", tokens), ("d_model", d_model)): + got = doc.get(key) + if got != exp: + errors.append(f"{fname}: reported {key}={got!r} != configured {exp}") + return errors + + +def render_proof(text, blocks): + def sub(m): + name = m.group(1) + if name not in blocks: + raise KeyError(f"unknown generated block {name}") + return f"\n{blocks[name]}\n" + return GEN_RE.sub(sub, text) + + +def prose_violations(text): + bad = [] + for ln, line in enumerate(text.splitlines(), 1): + for tok in NUM_RE.findall(line): + if tok not in PROSE_ALLOW: + bad.append((ln, tok, line.strip()[:120])) + return bad + + +def narrative_strings(o, path=""): + if isinstance(o, dict): + for k, v in o.items(): + yield from narrative_strings(v, f"{path}.{k}") + elif isinstance(o, list): + for i, v in enumerate(o): + yield from narrative_strings(v, f"{path}[{i}]") + elif isinstance(o, str): + yield path, o + + +def parse_hal_pids(raw: object) -> tuple[int, ...] | None: + """Parse a space-separated list of one or more positive integer PIDs.""" + if not isinstance(raw, str) or not HAL_PIDS_RE.fullmatch(raw): + return None + pids = tuple(int(tok) for tok in raw.split(" ")) + return pids if pids and all(pid > 0 for pid in pids) else None + + +def session_health_gate(session: dict) -> dict: + """Same gate as token_loop_capture.health_gate: faults, crash entries, valid unchanged HAL pids.""" + kl = session.get("kernel_log") or {} + faults = len(kl.get("subsystem_fault_lines") or []) + len(kl.get("generic_kernel_fault_lines") or []) + cb = session.get("crash_buffer") or {} + raw_crashes = cb.get("new_lines") + crashes = raw_crashes if isinstance(raw_crashes, int) and not isinstance(raw_crashes, bool) else -1 + hal = session.get("hal_pids") + hal_rc = session.get("hal_pid_exit_codes") + parsed: list[tuple[int, ...]] = [] + hal_ok = isinstance(hal, dict) and isinstance(hal_rc, dict) + if hal_ok: + for k in HAL_SNAPSHOT_KEYS: + if k not in hal or hal_rc.get(k) != 0: + hal_ok = False + break + pids = parse_hal_pids(hal[k]) + if pids is None: + hal_ok = False + break + parsed.append(tuple(sorted(pids))) + unchanged = hal_ok and len(parsed) == len(HAL_SNAPSHOT_KEYS) and all(p == parsed[0] for p in parsed) + return {"new_kernel_faults": faults, "new_crash_entries": crashes, "hal_pids_unchanged": unchanged} + + +def _arm_doc(doc: dict, name: str) -> dict: + return next(a for a in doc["arms"] if a["arm"] == name) + + +def _is_finite_number(v: object) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) + + +def _has_cli_flag_value(args: object, flag: str, value: str) -> bool: + if not isinstance(args, list): + return False + for i in range(len(args) - 1): + if args[i] == flag and args[i + 1] == value: + return True + return False + + +def _validate_nnapi_edgetpu_proof_run(fname: str, run: dict, doc: dict) -> list[str]: + """Require GPU-NNAPI EdgeTPU zero-copy AHB + kernel IIF gate on the main proof sweep and smoke.""" + errors: list[str] = [] + if not _has_cli_flag_value(run.get("args"), "--tpu-backend", "nnapi"): + errors.append(f"{fname}: args must explicitly pin '--tpu-backend nnapi' (got {run.get('args')!r})") + if not isinstance(doc, dict): + return [*errors, f"{fname}: expected JSON object"] + if doc.get("tpu_backend") != "nnapi": + errors.append(f"{fname}: expected tpu_backend='nnapi', got {doc.get('tpu_backend')!r}") + if doc.get("tpu_backend_requested") != "nnapi": + errors.append(f"{fname}: expected tpu_backend_requested='nnapi', got {doc.get('tpu_backend_requested')!r}") + if doc.get("executor") != "live_vulkan_nnapi": + errors.append(f"{fname}: expected executor='live_vulkan_nnapi', got {doc.get('executor')!r}") + nn = doc.get("nnapi") + if not isinstance(nn, dict): + errors.append(f"{fname}: missing nnapi metadata object") + else: + dev_name = nn.get("device") + if not isinstance(dev_name, str) or "google-edgetpu" not in dev_name.lower(): + errors.append(f"{fname}: expected nnapi.device matching 'google-edgetpu', got {dev_name!r}") + fl = nn.get("device_feature_level") + if not isinstance(fl, int) or isinstance(fl, bool) or fl < 30: + errors.append(f"{fname}: expected nnapi.device_feature_level >= 30, got {fl!r}") + if nn.get("shared_mem") != "ahb_blob_gpu_data_buffer": + errors.append(f"{fname}: expected nnapi.shared_mem='ahb_blob_gpu_data_buffer', got {nn.get('shared_mem')!r}") + if nn.get("fenced_api") is not True: + errors.append(f"{fname}: expected nnapi.fenced_api=true, got {nn.get('fenced_api')!r}") + iif = doc.get("iif") + if not isinstance(iif, dict): + errors.append(f"{fname}: missing iif metadata object") + else: + if iif.get("backend") != "kernel": + errors.append(f"{fname}: expected iif.backend='kernel', got {iif.get('backend')!r}") + if iif.get("gpu_gate") is not True: + errors.append(f"{fname}: expected iif.gpu_gate=true, got {iif.get('gpu_gate')!r}") + if iif.get("bridge_dma_ok") is not True: + errors.append(f"{fname}: expected iif.bridge_dma_ok=true, got {iif.get('bridge_dma_ok')!r}") + if iif.get("requirement_met") is not True: + errors.append(f"{fname}: expected iif.requirement_met=true, got {iif.get('requirement_met')!r}") + arms = doc.get("arms") + if isinstance(arms, list): + ri = next((a for a in arms if isinstance(a, dict) and a.get("arm") == "r_iif"), None) + if ri is None: + errors.append(f"{fname}: missing r_iif arm") + else: + fences = ri.get("iif_fences_per_tok") + if not _is_finite_number(fences) or fences <= 0: + errors.append(f"{fname}: r_iif expected iif_fences_per_tok > 0, got {fences!r}") + unf = ri.get("nnapi_unfenced_hops_per_tok") + if not _is_finite_number(unf) or unf != 0: + errors.append(f"{fname}: r_iif expected nnapi_unfenced_hops_per_tok == 0, got {unf!r}") + return errors + + +def negative_run_errors(fname: str, doc: dict) -> list[str]: + """Structured reason for each negative / guard proof, not just the process exit code.""" + errors = [] + + def bad(msg: str) -> None: + errors.append(f"{fname}: {msg}") + + if "arms" not in doc: + bad("negative proof has no arms array") + return errors + try: + if fname == "neg-swfallback-require-iif-L4-T8-d512.json": + ri = _arm_doc(doc, "r_iif") + if doc.get("pass") is not False: + bad("overall pass must be false because requirement_met is false") + iif = doc["iif"] + if iif.get("require_iif") is not True or iif.get("requirement_met") is not False: + bad(f"require-iif gate not the failure cause: {iif.get('require_iif')}/{iif.get('requirement_met')}") + if iif.get("backend") != "sw_emulated": + bad(f"software fallback backend is {iif.get('backend')!r}") + if ri.get("ran") is not True or ri.get("pass") is not True: + bad("software r_iif arm itself must pass while --require-iif rejects the run") + elif fname == "neg-nobridge-require-iif-L4-T8-d512.json": + ri = _arm_doc(doc, "r_iif") + if doc.get("pass") is not False: + bad("overall pass must be false") + iif = doc["iif"] + if iif.get("require_iif") is not True or iif.get("requirement_met") is not False: + bad(f"require-iif gate not the failure cause: {iif.get('require_iif')}/{iif.get('requirement_met')}") + if iif.get("gpu_gate") is not False or iif.get("bridge_dma_ok") is not False: + bad("ungated run still reports a GPU IIF gate or a working bridge") + if ri.get("ran") is not True or ri.get("pass") is not True: + bad("ungated r_iif arm itself must pass") + if ri.get("iif_fences_per_tok") not in (0, 0.0): + bad(f"ungated arm recorded IIF fences: {ri.get('iif_fences_per_tok')!r}") + for a in doc["arms"]: + if a.get("ran") and a.get("pass") is not True: + bad(f"{a.get('arm')} failed; overall failure would not be the IIF requirement alone") + elif fname == "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json": + if doc.get("pass") is not True: + bad("host-staged guard run must pass") + hs = _arm_doc(doc, "host_staged") + if hs.get("ran") is not True or hs.get("pass") is not True: + bad("host_staged must pass") + for name in ("sync_file_poll", "r_iif"): + a = _arm_doc(doc, name) + if a.get("ran") is not False or a.get("skip_reason") != "nnapi_fenced_dmabuf_unavailable_on_edgetpu": + bad(f"{name} skip_reason is {a.get('skip_reason')!r}, want nnapi_fenced_dmabuf_unavailable_on_edgetpu") + nn = doc.get("nnapi") or {} + if nn.get("shared_mem") != "dmabuf_fd": + bad(f"shared_mem is {nn.get('shared_mem')!r}") + if nn.get("exec_start_calls") != 0: + bad(f"fenced arms were not skipped before dispatch (exec_start_calls={nn.get('exec_start_calls')})") + elif fname == "mock-root-fault-recovery-L4-T8-d512.json": + if doc.get("pass") is not False: + bad("injected fence failure must fail the run") + sf = _arm_doc(doc, "sync_file_poll") + ri = _arm_doc(doc, "r_iif") + if sf.get("ran") is not False or sf.get("recovery") != "drained_retired": + bad(f"sync_file_poll recovery is {sf.get('recovery')!r}") + if ri.get("ran") is not True or ri.get("pass") is not True: + bad("r_iif must run and pass after the drain") + st = doc.get("executor_state") or {} + if st.get("tainted") is not False or st.get("ledger_inflight_at_exit") != 0: + bad(f"executor was not drained clean: {st}") + elif fname == "mock-root-fault-tainted-L4-T8-d512.json": + if doc.get("pass") is not False: + bad("tainted executor must fail the run") + sf = _arm_doc(doc, "sync_file_poll") + ri = _arm_doc(doc, "r_iif") + if sf.get("recovery") != "tainted": + bad(f"sync_file_poll recovery is {sf.get('recovery')!r}") + if ri.get("ran") is not False or ri.get("skip_reason") != "executor_tainted": + bad(f"r_iif was not skipped as executor_tainted ({ri.get('skip_reason')!r})") + st = doc.get("executor_state") or {} + if st.get("tainted") is not True or st.get("submissions_retired_after_drain") != 0: + bad("in-flight slots were retired after a failed drain") + if st.get("ledger_inflight_at_exit") in (0, None): + bad("quarantined slot was dropped from the ledger") + except (KeyError, StopIteration, TypeError) as exc: + bad(f"malformed negative proof ({exc})") + return errors + + +def validate_capture(p: Packet, d: str, *, check_overall_ok: bool = True) -> list[str]: + """Hashes, exit codes, unit tests, health, and structured run outcomes. Does not touch proof files.""" + errors: list[str] = [] + s = p.session + seen_files = {r["file"] for r in s["runs"]} + missing_runs = sorted(set(EXPECT) - seen_files) + if missing_runs: + errors.append(f"session.json missing expected runs: {missing_runs}") + for r in s["runs"]: + fname = r["file"] + doc = p.raw[fname] + if _sha(os.path.join(d, fname)) != r["stdout_sha256"]: + errors.append(f"{fname}: SHA-256 differs from the captured stdout") + if r["exit_code"] != r["expected_exit_code"]: + errors.append(f"{fname}: exit {r['exit_code']} != expected {r['expected_exit_code']}") + watch_expect = r.get("iif_dev_open_watch_expect") + if watch_expect in ("zero", "nonzero") and r.get("watcher_active") is not True: + errors.append(f"{fname}: watcher_active must be true (got {r.get('watcher_active')!r})") + if watch_expect == "zero": + if r.get("iif_dev_open_events") != 0: + errors.append(f"{fname}: /dev/iif opened during a --mock run") + elif watch_expect == "nonzero": + ev = r.get("iif_dev_open_events") + if not isinstance(ev, int) or ev <= 0: + errors.append(f"{fname}: open watch positive control saw nothing") + errors.extend(dimension_errors(fname, doc)) + if fname in ( + "neg-swfallback-require-iif-L4-T8-d512.json", + "neg-nobridge-require-iif-L4-T8-d512.json", + "edgetpu-dmabuf-fenced-blocked-L4-T8-d512.json", + "mock-root-fault-recovery-L4-T8-d512.json", + "mock-root-fault-tainted-L4-T8-d512.json", + ): + errors.extend(negative_run_errors(fname, doc)) + elif fname == "iif-probe-only.json": + if doc.get("probed") is not True or doc.get("usable") is not True or doc.get("bridge_dma_ok") is not True: + errors.append(f"{fname}: probe did not confirm usable /dev/iif with bridge_dma_ok=true") + elif fname == "iif-probe-only-hostile-dev.json": + args = r.get("args") or [] + want_dev = args[args.index("--iif-dev") + 1] if "--iif-dev" in args and args.index("--iif-dev") + 1 < len(args) else None + if doc.get("probed") is not True or doc.get("usable") is not False: + errors.append(f"{fname}: hostile probe unexpected state: {doc}") + if want_dev is not None and doc.get("dev") != want_dev: + errors.append(f"{fname}: hostile probe dev {doc.get('dev')!r} != {want_dev!r}") + elif r["expected_exit_code"] == 0: + if not isinstance(doc, dict) or doc.get("pass") is not True: + errors.append(f"{fname}: expected pass=true, got {doc.get('pass') if isinstance(doc, dict) else type(doc).__name__!r}") + if "--require-iif" in (r.get("args") or []): + iif_obj = doc.get("iif") if isinstance(doc, dict) else None + if not isinstance(iif_obj, dict) or iif_obj.get("requirement_met") is not True: + errors.append(f"{fname}: --require-iif run did not report iif.requirement_met=true") + if fname == "smoke-L4-T8-d512.json" or fname in {f"bench-L12-T64-d{d_}.json" for d_ in SWEEP}: + errors.extend(_validate_nnapi_edgetpu_proof_run(fname, r, doc)) + if fname.startswith("mock-root-"): + iif_obj = doc.get("iif") if isinstance(doc, dict) else None + probe_obj = iif_obj.get("probe") if isinstance(iif_obj, dict) else None + if not isinstance(iif_obj, dict) or iif_obj.get("dev_open_calls") != 0: + errors.append(f"{fname}: --mock run reported dev_open_calls={iif_obj.get('dev_open_calls') if isinstance(iif_obj, dict) else None!r}") + if not isinstance(probe_obj, dict) or probe_obj.get("probed") is not False: + errors.append(f"{fname}: --mock run reported probe.probed != false") + shas = {r["binary_sha256"] for r in s["runs"]} | {s["binary"][k] for k in ( + "bench_sha256_host", "bench_sha256_device", "bench_sha256_device_at_end")} + if len(shas) != 1: + errors.append(f"bench binaries differ across runs: {sorted(shas)}") + if s["binary"]["unit_test_sha256_host"] != s["binary"]["unit_test_sha256_device"]: + errors.append("unit test binary hash differs host vs device") + kl, cb = s["kernel_log"], s["crash_buffer"] + if kl.get("before_exit_code") != 0 or kl.get("after_exit_code") != 0: + errors.append(f"kernel_log snapshot read failed: {kl.get('before_exit_code')}/{kl.get('after_exit_code')}") + if cb.get("before_exit_code") != 0 or cb.get("after_exit_code") != 0: + errors.append(f"crash_buffer snapshot read failed: {cb.get('before_exit_code')}/{cb.get('after_exit_code')}") + if cb.get("cursor_mode") != "logcat_T": + errors.append(f"crash_buffer must use cursor_mode='logcat_T', got {cb.get('cursor_mode')!r}") + cb_ts = cb.get("start_timestamp") + if not isinstance(cb_ts, str) or not LOGCAT_TS_RE.fullmatch(cb_ts): + errors.append(f"crash_buffer start_timestamp invalid: {cb_ts!r}") + cb_new = cb.get("new_lines") + if not isinstance(cb_new, int) or isinstance(cb_new, bool) or cb_new < 0: + errors.append(f"crash_buffer new_lines invalid: {cb_new!r}") + hal = s.get("hal_pids") + hal_rc = s.get("hal_pid_exit_codes") + if not isinstance(hal, dict) or not isinstance(hal_rc, dict): + errors.append("session.json missing hal_pids or hal_pid_exit_codes mapping") + else: + for k in HAL_SNAPSHOT_KEYS: + if hal_rc.get(k) != 0: + errors.append(f"hal_pid_exit_codes[{k!r}]={hal_rc.get(k)!r}, expected 0") + if parse_hal_pids(hal.get(k)) is None: + errors.append(f"hal_pids[{k!r}]={hal.get(k)!r} is not a non-empty numeric PID list") + hg = session_health_gate(s) + if hg["new_kernel_faults"] != 0: + errors.append(f"health gate: new_kernel_faults={hg['new_kernel_faults']}") + if hg["new_crash_entries"] != 0: + errors.append(f"health gate: new_crash_entries={hg['new_crash_entries']}") + if hg["hal_pids_unchanged"] is not True: + errors.append(f"health gate: hal_pids_unchanged={hg['hal_pids_unchanged']!r}") + recorded = s.get("health_gate") + if recorded is not None and recorded != hg: + errors.append(f"session health_gate {recorded} does not match kernel/crash/hal snapshots {hg}") + if s.get("tmp_before") != s.get("tmp_after"): + errors.append("session.json tmp_before != tmp_after") + if s.get("leftover_processes"): + errors.append(f"session.json leftover_processes={s.get('leftover_processes')!r}") + if check_overall_ok and s.get("overall_ok") is not True: + errors.append(f"session.json overall_ok is {s.get('overall_ok')!r}, expected True") + ut_manifest = s.get("unit_test_runs", []) + ut_sections = parse_unit_test_sections(p.unit) + if not ut_manifest or len(ut_manifest) != len(ut_sections): + errors.append("unit_test_runs count differs from unit-test-device.txt sections") + for ur, sec in zip(ut_manifest, ut_sections): + if "exit_code" not in ur or ur["exit_code"] != ur.get("expected_exit_code", 0) or ur["exit_code"] != 0: + errors.append(f"unit test {ur.get('title')!r}: manifest exit_code={ur.get('exit_code')!r}") + if ur.get("all_checks_passed") is not True: + errors.append(f"unit test {ur.get('title')!r}: manifest all_checks_passed is not True") + if sec["title"] != ur.get("title") or sec["exit_code"] != ur.get("exit_code") or not sec["all_checks_passed"]: + errors.append(f"unit test {sec['title']!r}: transcript disagrees with manifest or failed") + if "binary_sha256" in ur and ur["binary_sha256"] != s["binary"]["unit_test_sha256_host"]: + errors.append(f"unit test {ur.get('title')!r}: binary SHA-256 differs from host unit test binary") + for sub, sess, r, path, _doc, _meta in p.failures: + if _sha(path) != r["stdout_sha256"]: + errors.append(f"observed-failures/{sub}/{r['file']}: SHA-256 differs from its session manifest") + if r["binary_sha256"] != sess["binary"]["bench_sha256_host"]: + errors.append(f"observed-failures/{sub}/{r['file']}: produced by a different bench binary") + listed = {r["file"] for r in s["runs"]} + for f in os.listdir(d): + if f.endswith(".json") and f not in listed | {"receipt.json", "session.json", "host-verification.json"}: + errors.append(f"{f}: raw file not produced by the capture session") + if not missing_runs: + for d_ in SWEEP: + fname = f"bench-L12-T64-d{d_}.json" + doc = p.bench[d_] + arms = doc.get("arms") if isinstance(doc, dict) else None + if not isinstance(arms, list): + errors.append(f"{fname}: missing arms array") + continue + by_arm = {a.get("arm"): a for a in arms if isinstance(a, dict)} + for name in ARMS: + a = by_arm.get(name) + if a is None: + errors.append(f"{fname}: missing required arm {name!r}") + continue + if a.get("ran") is not True or a.get("pass") is not True: + errors.append(f"{fname}: arm {name!r} did not run and pass " + f"(ran={a.get('ran')!r}, pass={a.get('pass')!r}, " + f"skip_reason={a.get('skip_reason')!r})") + continue + tps = a.get("tok_per_s") + if not _is_finite_number(tps) or tps <= 0: + errors.append(f"{fname}: arm {name!r} invalid tok_per_s={tps!r}") + if name == "host_staged": + vsys = a.get("j_per_tok_vsys") + if not _is_finite_number(vsys) or vsys <= 0: + errors.append(f"{fname}: arm 'host_staged' invalid j_per_tok_vsys={vsys!r}") + elif name == "r_iif": + vsys = a.get("j_per_tok_vsys") + if not _is_finite_number(vsys): + errors.append(f"{fname}: arm 'r_iif' invalid j_per_tok_vsys={vsys!r}") + if name in ("sync_file_poll", "r_iif"): + hw = a.get("host_wait_us_per_tok") + if not _is_finite_number(hw): + errors.append(f"{fname}: arm {name!r} invalid host_wait_us_per_tok={hw!r}") + try: + gen = p.generated() + json.dumps(gen, allow_nan=False) + blks = p.blocks(include_host=p.host is not None) + tpl = "".join(f"\n\n" for k in blks) + render_proof(tpl, blks) + except (KeyError, StopIteration, TypeError, ValueError, ZeroDivisionError) as exc: + errors.append(f"receipt/proof render failed: {exc}") + return errors + + +def validate_staged_capture(stage_dir: str) -> list[str]: + """Validate a freshly staged capture directory before publishing into --out.""" + try: + p = Packet(stage_dir, require_host=False) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as exc: + return [f"staged capture load failed: {exc}"] + return validate_capture(p, stage_dir, check_overall_ok=False) + + +def _atomic_write(path: str, text: str) -> None: + directory = os.path.dirname(path) or "." + fd, tmp = tempfile.mkstemp(prefix="." + os.path.basename(path) + ".", dir=directory) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(text) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def cmd_write(d): + try: + p = Packet(d) + except (OSError, ValueError, KeyError) as exc: + print("ERROR:", exc, file=sys.stderr) + return 1 + errors = validate_capture(p, d) + if errors: + for e in errors: + print("ERROR:", e, file=sys.stderr) + return 1 + try: + gen = p.generated() + blks = p.blocks() + rp = os.path.join(d, "receipt.json") + pp = os.path.join(d, "PROOF.md") + receipt = _load(rp) + with open(pp, encoding="utf-8") as f: + rendered = render_proof(f.read(), blks) + except (OSError, ValueError, KeyError, StopIteration, TypeError, ZeroDivisionError) as exc: + print("ERROR:", exc, file=sys.stderr) + return 1 + receipt.update(gen) + body = json.dumps(receipt, indent=2) + "\n" + _atomic_write(rp, body) + _atomic_write(pp, rendered) + print("receipt.json and PROOF.md regenerated from raw files") + return cmd_check(d) + + +def cmd_check(d): + errors = [] + try: + p = Packet(d) + except (OSError, ValueError, KeyError) as exc: + print("ERROR:", exc, file=sys.stderr) + return 1 + s = p.session + errors.extend(validate_capture(p, d)) + shas = {r["binary_sha256"] for r in s["runs"]} | {s["binary"][k] for k in ( + "bench_sha256_host", "bench_sha256_device", "bench_sha256_device_at_end")} + receipt = _load(os.path.join(d, "receipt.json")) + names: list[str] = [] + try: + gen = p.generated() + blks = p.blocks() + for k in GEN_KEYS: + if receipt.get(k) != gen[k]: + errors.append(f"receipt.json[{k}] is not the value generated from the raw files") + for path, sval in narrative_strings({k: v for k, v in receipt.items() if k not in GEN_KEYS}): + for ln, tok, _ in prose_violations(sval): + errors.append(f"receipt.json{path}: hand-written measured value {tok!r}") + with open(os.path.join(d, "PROOF.md"), encoding="utf-8") as f: + text = f.read() + names = [m.group(1) for m in GEN_RE.finditer(text)] + missing = set(blks) - set(names) + if missing: + errors.append(f"PROOF.md lacks generated blocks {sorted(missing)}") + if render_proof(text, blks) != text: + errors.append("PROOF.md generated blocks are stale (run token_loop_receipt.py write)") + for ln, tok, line in prose_violations(GEN_RE.sub("", text)): + errors.append(f"PROOF.md prose (outside generated blocks): measured value {tok!r} in: {line}") + except (OSError, KeyError, StopIteration, TypeError, ValueError, ZeroDivisionError) as exc: + if not any("receipt/proof render failed:" in e for e in errors): + errors.append(f"receipt/proof render failed: {exc}") + for e in errors: + print("ERROR:", e, file=sys.stderr) + if errors: + return 1 + print(f"receipt reconciled: {len(s['runs'])} raw files, 1 bench binary {next(iter(shas))[:16]}..., " + f"{len(GEN_KEYS)} generated receipt keys, {len(names)} generated PROOF.md blocks, prose clean") + return 0 + + +def _run(cmd, cwd=None, env=None): + p = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, check=False) + return p.returncode, p.stdout + p.stderr + + +def _ctest_summary(out): + m = re.search(r"\d+% tests passed, (\d+) tests? failed out of (\d+)", out) + if m: + total, failed = int(m.group(2)), int(m.group(1)) + return total - failed, total + m = re.search(r"100% tests passed out of (\d+)", out) + if m: + return int(m.group(1)), int(m.group(1)) + raise RuntimeError("no ctest summary in output:\n" + out[-2000:]) + + +def ndk_prebuilt_name(platform_name: str, machine: str) -> str | None: + """Host triple directory under /toolchains/llvm/prebuilt.""" + mach = machine.lower() + arm = mach in ("arm64", "aarch64") + if platform_name == "darwin": + return "darwin-arm64" if arm else "darwin-x86_64" + if platform_name.startswith("linux"): + return "linux-aarch64" if arm else "linux-x86_64" + return None + + +def resolve_ndk_cxx(ndk: str, override: str | None = None, platform_name: str | None = None, + machine: str | None = None) -> str: + """clang++ for this host: --ndk-cxx, else the matching prebuilt, else any prebuilt that has one.""" + if override: + if not os.path.isfile(override): + raise RuntimeError(f"--ndk-cxx is not a file: {override}") + return override + platform_name = sys.platform if platform_name is None else platform_name + machine = platform.machine() if machine is None else machine + prebuilt = os.path.join(ndk, "toolchains", "llvm", "prebuilt") + preferred = ndk_prebuilt_name(platform_name, machine) + names: list[str] = [] + if os.path.isdir(prebuilt): + names = sorted(n for n in os.listdir(prebuilt) if os.path.isdir(os.path.join(prebuilt, n))) + ordered: list[str] = [] + if preferred: + ordered.append(preferred) + for name in names: + if name not in ordered: + ordered.append(name) + for name in ordered: + cxx = os.path.join(prebuilt, name, "bin", "clang++") + if os.path.isfile(cxx): + return cxx + raise RuntimeError(f"no NDK clang++ under {prebuilt} for host {preferred or platform_name}") + + +def parse_cmake_cache(cache_path: str) -> dict[str, str]: + entries: dict[str, str] = {} + with open(cache_path, encoding="utf-8", errors="replace") as f: + for raw in f: + line = raw.strip() + if not line or line.startswith(("//", "#")): + continue + eq = line.find("=") + if eq <= 0: + continue + lhs, val = line[:eq], line[eq + 1:] + key = lhs.split(":", 1)[0].strip() + entries[key] = val.strip() + return entries + + +def is_elf_aarch64(path: str) -> bool: + try: + with open(path, "rb") as f: + hdr = f.read(20) + except OSError: + return False + return (len(hdr) >= 20 and hdr[:4] == b"\x7fELF" and hdr[4] == 2 and hdr[5] == 1 + and int.from_bytes(hdr[18:20], "little") == 183) + + +def verify_arm64_build_dir(bdir: str, want_openbuenos: bool, ndk: str, repo: str) -> tuple[bool, str, str | None]: + cache_p = os.path.join(bdir, "CMakeCache.txt") + if not os.path.isfile(cache_p): + return False, f"FAIL: missing CMakeCache.txt in {bdir}", None + cache = parse_cmake_cache(cache_p) + home = cache.get("CMAKE_HOME_DIRECTORY", "") + if not home or os.path.realpath(home) != os.path.realpath(repo): + return False, f"FAIL: CMakeCache CMAKE_HOME_DIRECTORY {home!r} does not match repo {repo!r}", None + abi = cache.get("ANDROID_ABI", "") + sysname = cache.get("CMAKE_SYSTEM_NAME", "") + if abi != "arm64-v8a" or (sysname and sysname != "Android"): + return False, f"FAIL: expected Android arm64-v8a, got CMAKE_SYSTEM_NAME={sysname!r} ANDROID_ABI={abi!r}", None + ndk_real = os.path.realpath(ndk) + ndk_base = os.path.basename(ndk_real) + ndk_refs = [cache.get(k, "") for k in ("ANDROID_NDK", "CMAKE_TOOLCHAIN_FILE", "CMAKE_CXX_COMPILER")] + if not any(r and (os.path.realpath(r).startswith(ndk_real) or ndk_base in r) for r in ndk_refs): + return False, f"FAIL: build dir {bdir} does not reference NDK {ndk_base!r}", None + ob_dir = cache.get("FREESCHED_OPENBUENOS_DIR", "") + ob_inc = cache.get("_FREESCHED_OB_INCLUDE", "") + ob_lib = cache.get("_FREESCHED_OB_LIB", "") + has_ob = (bool(ob_dir) and bool(ob_inc) and not ob_inc.endswith("-NOTFOUND") + and bool(ob_lib) and not ob_lib.endswith("-NOTFOUND")) + if want_openbuenos and not has_ob: + return False, (f"FAIL: expected libopenbuenos enabled (FREESCHED_OPENBUENOS_DIR={ob_dir!r}, " + f"_FREESCHED_OB_LIB={ob_lib!r})"), None + if not want_openbuenos and (ob_dir or has_ob): + return False, (f"FAIL: expected libopenbuenos disabled, but FREESCHED_OPENBUENOS_DIR={ob_dir!r} " + f"_FREESCHED_OB_LIB={ob_lib!r}"), None + rc, out = _run(["cmake", "--build", bdir, "--target", "volcanic_tpu_token_loop_bench", "test_token_loop_riif"]) + if rc != 0: + return False, "FAIL: cmake --build failed: " + out.strip()[-200:], None + b, u = (os.path.join(bdir, x) for x in ("volcanic_tpu_token_loop_bench", "test_token_loop_riif")) + for label_bin, bp in (("bench", b), ("unit test", u)): + if not os.path.isfile(bp): + return False, f"FAIL: missing built {label_bin} binary {bp}", None + if not is_elf_aarch64(bp): + return False, f"FAIL: {label_bin} binary is not an ELF64 AArch64 executable: {bp}", None + bsha = _sha(b) + return True, f"PASS: bench `{bsha}`, unit test `{_sha(u)}`", bsha + + +def verify_arm64_matrix(a64_ob: str, a64_noob: str, ndk: str, repo: str) -> list[tuple[str, str]]: + if os.path.realpath(a64_ob) == os.path.realpath(a64_noob): + msg = "FAIL: --a64-ob and --a64-noob resolve to the same build directory" + return [("with", msg), ("without", msg)] + ok_ob, res_ob, sha_ob = verify_arm64_build_dir(a64_ob, True, ndk, repo) + ok_no, res_no, sha_no = verify_arm64_build_dir(a64_noob, False, ndk, repo) + if ok_ob and ok_no and sha_ob == sha_no: + msg = f"FAIL: with/without libopenbuenos produced identical bench SHA-256 {sha_ob}" + return [("with", msg), ("without", msg)] + return [("with", res_ob), ("without", res_no)] + + +# Compiler-inserted instrumentation call symbols (never linked runtime library names or bare __asan_init). +ASAN_SYM_RE = re.compile(r"__asan_report_") +UBSAN_SYM_RE = re.compile(r"__ubsan_handle_") +SANITIZER_TARGETS = ("volcanic_tpu_token_loop_bench", "test_token_loop_riif") + + +def _parse_sanitizer_flags(text: str) -> set[str]: + enabled: set[str] = set() + for m in re.finditer(r"-f(no-)?sanitize=([A-Za-z0-9_,+-]+)", text): + neg = bool(m.group(1)) + for tok in m.group(2).split(","): + tok = tok.strip() + if not tok: + continue + if neg: + enabled.discard(tok) + else: + enabled.add(tok) + return enabled + + +def _extract_sanitizers_from_cache(cache: dict[str, str]) -> set[str]: + """Extract active compilation sanitizers from CMake CXX compile flags only (never linker-only flags).""" + build_type = cache.get("CMAKE_BUILD_TYPE", "").upper() + keys = ["CMAKE_CXX_FLAGS"] + if build_type: + keys.append(f"CMAKE_CXX_FLAGS_{build_type}") + combined = " ".join(cache.get(k, "") for k in keys) + return _parse_sanitizer_flags(combined) + + +def _verify_target_compile_flags(asan_build: str, target: str) -> tuple[bool, str]: + """If flags.make or compile_commands.json is present, verify compilation flags for target carry ASan+UBSan.""" + flags_make = os.path.join(asan_build, "CMakeFiles", f"{target}.dir", "flags.make") + if os.path.isfile(flags_make): + cxx_lines: list[str] = [] + with open(flags_make, encoding="utf-8", errors="replace") as f: + for line in f: + if line.lstrip().startswith("CXX_FLAGS"): + cxx_lines.append(line) + sans = _parse_sanitizer_flags(" ".join(cxx_lines)) + missing = [s for s in ("address", "undefined") if s not in sans] + if missing: + return False, f"FAIL: {flags_make} missing compile -fsanitize for {missing} (found {sorted(sans)})" + cc_path = os.path.join(asan_build, "compile_commands.json") + if os.path.isfile(cc_path): + try: + entries = _load(cc_path) + except (OSError, ValueError, json.JSONDecodeError) as exc: + return False, f"FAIL: invalid compile_commands.json in {asan_build}: {exc}" + src_suffix = "volcanic_tpu_token_loop_bench.cpp" if target == "volcanic_tpu_token_loop_bench" else "test_token_loop_riif.cpp" + matched = [e for e in entries if isinstance(e, dict) and str(e.get("file", "")).endswith(src_suffix)] + if matched: + for e in matched: + cmd_str = e.get("command") if isinstance(e.get("command"), str) else " ".join(e.get("arguments") or []) + sans = _parse_sanitizer_flags(cmd_str) + missing = [s for s in ("address", "undefined") if s not in sans] + if missing: + return False, f"FAIL: compile_commands.json for {src_suffix} missing -fsanitize for {missing}" + return True, "ok" + + +def inspect_binary_sanitizers(bin_path: str) -> tuple[bool, bool, str]: + """Inspect compiled binary symbol tables for actual compiler-inserted ASan and UBSan instrumentation calls.""" + if not os.path.isfile(bin_path): + return False, False, f"missing binary {bin_path}" + probes: list[list[str]] = [] + if shutil.which("nm"): + probes.append(["nm", "-u", bin_path]) + probes.append(["nm", bin_path]) + if shutil.which("readelf"): + probes.append(["readelf", "-Ws", bin_path]) + if not probes: + return False, False, "no binary symbol inspector (nm/readelf) available" + combined: list[str] = [] + ran_ok = False + for cmd in probes: + rc, out = _run(cmd) + if rc == 0: + ran_ok = True + combined.append(out) + if not ran_ok: + return False, False, f"symbol inspection commands failed for {bin_path}" + blob = "\n".join(combined) + has_asan = bool(ASAN_SYM_RE.search(blob)) + has_ubsan = bool(UBSAN_SYM_RE.search(blob)) + return has_asan, has_ubsan, "" + + +def verify_asan_ubsan_build_dir(asan_build: str, host_build: str, repo: str) -> tuple[bool, str]: + """Verify --asan-build is distinct from --host-build and compiled (not merely linked) with ASan and UBSan.""" + if os.path.realpath(asan_build) == os.path.realpath(host_build): + return False, "FAIL: --asan-build resolves to the same directory as --host-build" + cache_p = os.path.join(asan_build, "CMakeCache.txt") + if not os.path.isfile(cache_p): + return False, f"FAIL: missing CMakeCache.txt in {asan_build}" + cache = parse_cmake_cache(cache_p) + home = cache.get("CMAKE_HOME_DIRECTORY", "") + if not home or os.path.realpath(home) != os.path.realpath(repo): + return False, f"FAIL: ASan CMakeCache CMAKE_HOME_DIRECTORY {home!r} does not match repo {repo!r}" + sans = _extract_sanitizers_from_cache(cache) + missing_flags = [s for s in ("address", "undefined") if s not in sans] + if missing_flags: + return False, f"FAIL: {cache_p} missing CXX compile -fsanitize flags for {missing_flags} (found {sorted(sans)})" + for target in SANITIZER_TARGETS: + ok_cf, err_cf = _verify_target_compile_flags(asan_build, target) + if not ok_cf: + return False, err_cf + rc, out = _run(["cmake", "--build", asan_build]) + if rc != 0: + return False, "FAIL: cmake --build failed: " + out.strip()[-200:] + for target in SANITIZER_TARGETS: + bp = os.path.join(asan_build, target) + has_asan, has_ubsan, err = inspect_binary_sanitizers(bp) + if err: + return False, f"FAIL: {target}: {err}" + if not has_asan or not has_ubsan: + return False, (f"FAIL: {target} lacks sanitizer instrumentation calls " + f"(asan_report={has_asan}, ubsan_handle={has_ubsan})") + return True, "ok" + + +def prepare_host_build(host_build: str, repo: str) -> tuple[bool, str]: + """Require this repo's Release cache, then rebuild before ctest records a pass.""" + cache_p = os.path.join(host_build, "CMakeCache.txt") + if not os.path.isfile(cache_p): + return False, f"FAIL: missing CMakeCache.txt in {host_build}" + cache = parse_cmake_cache(cache_p) + home = cache.get("CMAKE_HOME_DIRECTORY", "") + if not home or os.path.realpath(home) != os.path.realpath(repo): + return False, f"FAIL: CMakeCache CMAKE_HOME_DIRECTORY {home!r} does not match repo {repo!r}" + build_type = cache.get("CMAKE_BUILD_TYPE", "") + if build_type != "Release": + return False, f"FAIL: --host-build CMAKE_BUILD_TYPE is {build_type!r}, expected 'Release'" + rc, out = _run(["cmake", "--build", host_build]) + if rc != 0: + return False, "FAIL: cmake --build failed: " + out.strip()[-200:] + return True, "ok" + + +def cmd_host_verify(a): + repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + checks = [] + host_ok, host_msg = prepare_host_build(a.host_build, repo) + if not host_ok: + checks.append({"check": "`--host-build` CMake cache + rebuild before `ctest`", "result": host_msg}) + else: + rc, out = _run(["ctest", "-E", "token_loop_proof_receipt_reconciled"], cwd=a.host_build) + ok, tot = _ctest_summary(out) + checks.append({"check": "`ctest` (host, Release; all tests except this reconciliation test, which checks the " + "file it would be recorded in)", "result": f"{'PASS' if rc == 0 else 'FAIL'}, {ok}/{tot}"}) + if a.asan_build: + san_ok, san_msg = verify_asan_ubsan_build_dir(a.asan_build, a.host_build, repo) + if not san_ok: + checks.append({"check": "ASan + UBSan `ctest -R token_loop` (`halt_on_error=1`)", + "result": san_msg}) + else: + env = dict(os.environ, ASAN_OPTIONS="halt_on_error=1", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + rc, out = _run(["ctest", "-R", "token_loop", "-E", "token_loop_proof_receipt_reconciled"], + cwd=a.asan_build, env=env) + ok, tot = _ctest_summary(out) + checks.append({"check": "ASan + UBSan `ctest -R token_loop` (`halt_on_error=1`)", + "result": f"{'PASS' if rc == 0 else 'FAIL'}, {ok}/{tot}"}) + rc, out = _run(["./scripts/clean-room-audit.sh"], cwd=repo) + m = re.search(r"(\d+) error", out) + checks.append({"check": "`./scripts/clean-room-audit.sh`", + "result": f"{'PASS' if rc == 0 else 'FAIL'}, {m.group(1) if m else '?'} errors"}) + a64_results = verify_arm64_matrix(a.a64_ob, a.a64_noob, a.ndk, repo) + for label, result in a64_results: + checks.append({"check": f"`arm64-v8a` CMake build {label} `libopenbuenos` (NDK `{os.path.basename(a.ndk)}`, " + "`-Wall -Wextra -Werror`)", + "result": result}) + try: + cxx = resolve_ndk_cxx(a.ndk, getattr(a, "ndk_cxx", None)) + except RuntimeError as exc: + checks.append({"check": "NDK clang++ for this host", "result": "FAIL: " + str(exc)}) + cxx = "" + base = [cxx, "--target=aarch64-linux-android35", "-U__ANDROID__", "-std=c++17", "-fsyntax-only", "-Wall", + "-Wextra", "-Werror", "-Wunused-parameter", "-Wunused-variable", "-Wunused-but-set-variable", + "-fno-exceptions", "-fno-rtti", f"-I{repo}/include", f"-I{repo}/tools"] + variants = [("bench", [], "tools/volcanic_tpu_token_loop_bench.cpp"), + ("bench + `FREESCHED_HAVE_LIBOPENBUENOS`", ["-DFREESCHED_HAVE_LIBOPENBUENOS=1", + f"-I{a.ob_include}"], "tools/volcanic_tpu_token_loop_bench.cpp"), + ("unit test", [], "tests/test_token_loop_riif.cpp")] + for label, extra, src in variants: + rc, out = _run([*base, *extra, os.path.join(repo, src)]) + checks.append({"check": f"Non-Android Linux `-fsyntax-only` ({label}; NDK clang, `__ANDROID__` undefined)", + "result": "PASS" if rc == 0 else "FAIL: " + out[:200]}) + path = os.path.join(a.proof_dir, "host-verification.json") + with open(path, "w", encoding="utf-8") as f: + json.dump({"schema": "freesched.proof.host_verification/v1", "checks": checks}, f, indent=2) + f.write("\n") + for c in checks: + print(c["check"], "->", c["result"]) + return 0 if all(c["result"].startswith("PASS") for c in checks) else 1 + + +def main(argv): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sp = ap.add_subparsers(dest="cmd", required=True) + for c in ("write", "check"): + sp.add_parser(c).add_argument("proof_dir") + hv = sp.add_parser("host-verify") + hv.add_argument("proof_dir") + for opt in ("--host-build", "--a64-ob", "--a64-noob", "--ndk", "--ob-include"): + hv.add_argument(opt, required=True) + hv.add_argument("--asan-build") + hv.add_argument("--ndk-cxx", help="clang++ to use instead of the host NDK prebuilt") + a = ap.parse_args(argv[1:]) + if a.cmd == "write": + return cmd_write(a.proof_dir) + if a.cmd == "check": + return cmd_check(a.proof_dir) + return cmd_host_verify(a) + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/shaders/volcanic/dequant_u8_f32.comp b/shaders/volcanic/dequant_u8_f32.comp new file mode 100644 index 0000000..ed6b1ea --- /dev/null +++ b/shaders/volcanic/dequant_u8_f32.comp @@ -0,0 +1,41 @@ +#version 450 +/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ QUANT8_ASYMM -> FP32 bridge shader. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Dequantizes the uint8 EdgeTPU 1x1 CONV_2D output Y[l] (NHWC [1,1,1,N], + * TENSOR_QUANT8_ASYMM) back to the FP32 raw-accumulator layout consumed by the + * residual + RMSNorm shader: + * + * Y[i] = (float(q[i]) - zero_point) * scale + */ +layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; + +layout(std430, set = 0, binding = 0) readonly buffer BufQ { + uint Q[]; +}; +layout(std430, set = 0, binding = 1) writeonly buffer BufOut { + float Y[]; +}; + +layout(push_constant) uniform PushConsts { + uint N; + float scale; + uint zero_point; + uint pad; +} pc; + +void main() { + uint w = gl_GlobalInvocationID.x; + uint base = w * 4u; + if (base >= pc.N) { + return; + } + uint packed = Q[w]; + float zp = float(pc.zero_point); + Y[base] = (float(packed & 0xffu) - zp) * pc.scale; + Y[base + 1u] = (float((packed >> 8u) & 0xffu) - zp) * pc.scale; + Y[base + 2u] = (float((packed >> 16u) & 0xffu) - zp) * pc.scale; + Y[base + 3u] = (float(packed >> 24u) - zp) * pc.scale; +} diff --git a/shaders/volcanic/quant_f32_u8.comp b/shaders/volcanic/quant_f32_u8.comp new file mode 100644 index 0000000..2afebc9 --- /dev/null +++ b/shaders/volcanic/quant_f32_u8.comp @@ -0,0 +1,44 @@ +#version 450 +/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ FP32 -> QUANT8_ASYMM bridge shader. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Quantizes the FP32 attention projection A[l] into the uint8 NNAPI + * TENSOR_QUANT8_ASYMM layout consumed by the EdgeTPU 1x1 CONV_2D stage: + * + * q[i] = clamp(roundEven(A[i] * inv_scale) + zero_point, 0, 255) + * + * Four consecutive bytes are packed little-endian into one uint so the shared + * zero-copy buffer is exactly N bytes of NHWC [1,1,1,N] uint8 data. + */ +layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in; + +layout(std430, set = 0, binding = 0) readonly buffer BufIn { + float A[]; +}; +layout(std430, set = 0, binding = 1) writeonly buffer BufQ { + uint Q[]; +}; + +layout(push_constant) uniform PushConsts { + uint N; + float inv_scale; + uint zero_point; + uint pad; +} pc; + +uint q8(float v) { + float q = roundEven(v * pc.inv_scale) + float(pc.zero_point); + return uint(clamp(q, 0.0, 255.0)); +} + +void main() { + uint w = gl_GlobalInvocationID.x; + uint base = w * 4u; + if (base >= pc.N) { + return; + } + uint packed = q8(A[base]) | (q8(A[base + 1u]) << 8u) | (q8(A[base + 2u]) << 16u) | (q8(A[base + 3u]) << 24u); + Q[w] = packed; +} diff --git a/shaders/volcanic/residual_rmsnorm_f32.comp b/shaders/volcanic/residual_rmsnorm_f32.comp new file mode 100644 index 0000000..88edaa3 --- /dev/null +++ b/shaders/volcanic/residual_rmsnorm_f32.comp @@ -0,0 +1,61 @@ +#version 450 +/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ Residual + RMSNorm Decode Shader. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Consumes raw FP32 EdgeTPU W8A16 FFN output directly from a shared DMA-BUF + * SSBO, applies the per-channel INT8 dequant scale, adds the residual hidden + * state and RMS-normalizes the result in place: + * + * v[i] = Y_tpu[i] * Scale[i] + X[i] + * X[i] = v[i] * inversesqrt(mean(v^2) + eps) * Gamma[i] + * + * One 256-lane workgroup per token; each lane only ever reads and writes the + * indices i == lane (mod 256), so the in-place update is race-free. + */ +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout(std430, set = 0, binding = 0) readonly buffer BufYTpu { + float Y_tpu[]; +}; +layout(std430, set = 0, binding = 1) readonly buffer BufScale { + float Scale[]; +}; +layout(std430, set = 0, binding = 2) buffer BufX { + float X[]; +}; +layout(std430, set = 0, binding = 3) readonly buffer BufGamma { + float Gamma[]; +}; + +layout(push_constant) uniform PushConsts { + uint N; + float eps; +} pc; + +shared float s_partial[256]; + +void main() { + uint tid = gl_LocalInvocationID.x; + float acc = 0.0; + for (uint i = tid; i < pc.N; i += 256u) { + float v = Y_tpu[i] * Scale[i] + X[i]; + acc += v * v; + } + s_partial[tid] = acc; + memoryBarrierShared(); + barrier(); + for (uint s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + s_partial[tid] += s_partial[tid + s]; + } + memoryBarrierShared(); + barrier(); + } + float inv_rms = inversesqrt(s_partial[0] / float(pc.N) + pc.eps); + for (uint i = tid; i < pc.N; i += 256u) { + float v = Y_tpu[i] * Scale[i] + X[i]; + X[i] = v * inv_rms * Gamma[i]; + } +} diff --git a/tests/ctest_run_expect.cmake b/tests/ctest_run_expect.cmake new file mode 100644 index 0000000..c24a43b --- /dev/null +++ b/tests/ctest_run_expect.cmake @@ -0,0 +1,32 @@ +# ctest_run_expect.cmake - run a test command and require BOTH exit code 0 AND a +# stdout match. +# +# PASS_REGULAR_EXPRESSION makes CTest ignore the process exit code, so a regex +# that also matches a nested object (e.g. an arm's "pass":true) can mask a +# failed top-level result. This wrapper keeps the exit-code check. +# +# cmake -DCMD=||... -DEXPECT_REGEX= [-DEMULATOR=||...] +# -P ctest_run_expect.cmake +# +# EMULATOR carries CMAKE_CROSSCOMPILING_EMULATOR ('|'-joined list: command plus +# arguments); when non-empty it is prepended to CMD, exactly as CTest does for +# tests whose command names an executable target. +# +# Copyright 2026 FreeSilicon Contributors +# SPDX-License-Identifier: Apache-2.0 +if(NOT DEFINED CMD) + message(FATAL_ERROR "ctest_run_expect: CMD is required") +endif() +string(REPLACE "|" ";" _cmd "${CMD}") +if(DEFINED EMULATOR AND NOT EMULATOR STREQUAL "") + string(REPLACE "|" ";" _emu "${EMULATOR}") + list(PREPEND _cmd ${_emu}) +endif() +execute_process(COMMAND ${_cmd} RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _err) +message("${_out}") +if(NOT _rc STREQUAL "0") + message(FATAL_ERROR "ctest_run_expect: exit code ${_rc} (expected 0)\n${_err}") +endif() +if(DEFINED EXPECT_REGEX AND NOT _out MATCHES "${EXPECT_REGEX}") + message(FATAL_ERROR "ctest_run_expect: stdout does not match: ${EXPECT_REGEX}") +endif() diff --git a/tests/test_token_loop_riif.cpp b/tests/test_token_loop_riif.cpp new file mode 100644 index 0000000..83100bd --- /dev/null +++ b/tests/test_token_loop_riif.cpp @@ -0,0 +1,1001 @@ +/* + * test_token_loop_riif - Host unit tests for the token-loop benchmark helpers: + * software IIF fence semantics, graceful /dev/iif runtime detection, + * /proc/self/status context-switch parsing, ODPM energy parsing/deltas and + * nearest-rank percentiles / parity, the --require-iif gate, the NNAPI IIF + * bridge gate, non-finite JSON diagnostics, the sync_file handoff status check + * (SYNC_IOC_FILE_INFO.status, incl. a live errored /dev/iif bridge) and the + * NNAPI EdgeTPU x dmabuf_fd fenced-dispatch guard / submission timer (mock), + * strict CLI number parsing, the mock-mode IIF probe skip and IIF fence + * outstanding accounting (failure-recovery drain). + * + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + */ +#include "volcanic_nnapi_edgetpu.h" +#include "volcanic_token_loop_util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +using namespace fs_tokloop; + +static int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +static void test_sw_iif_semantics() { + IifFences f; + int h = -1; + CHECK(f.create(FS_IIF_IP_GPU, 1u, &h) == IIF_ERR_STATE); /* uninitialized backend */ + f.init_sw(); + CHECK(f.kind() == FS_IIF_BACKEND_SW_EMULATED); + CHECK(f.create(FS_IIF_IP_GPU, 0u, &h) == IIF_ERR_ARG); + CHECK(f.create(FS_IIF_IP_GPU, 1u, nullptr) == IIF_ERR_ARG); + + /* Single signaler: wait before signal times out, then succeeds. */ + CHECK(f.create(FS_IIF_IP_GPU, 1u, &h) == IIF_OK && h >= 0); + CHECK(f.wait(h, 0u) == IIF_ERR_TIMEOUT); + CHECK(f.signal(h, 0) == IIF_OK); + CHECK(f.signal(h, 0) == IIF_ERR_STATE); /* over-signal rejected */ + CHECK(f.wait(h, 0u) == IIF_OK); + f.destroy(h); + CHECK(f.wait(h, 0u) == IIF_ERR_ARG); /* destroyed handle */ + CHECK(f.live_count() == 0u); + + /* Multi-signaler fence retires only after every signaler; errors propagate. */ + int m = -1; + CHECK(f.create(FS_IIF_IP_TPU, 3u, &m) == IIF_OK); + CHECK(f.signal(m, 0) == IIF_OK); + CHECK(f.signal(m, -5) == IIF_OK); + CHECK(f.wait(m, 0u) == IIF_ERR_TIMEOUT); + CHECK(f.signal(m, 0) == IIF_OK); + CHECK(f.wait(m, 0u) == IIF_ERR_FENCE); + f.destroy(m); + + /* Handle slots are recycled without leaking. */ + for (int i = 0; i < 1000; ++i) { + int x = -1; + CHECK(f.create(FS_IIF_IP_GPU, 1u, &x) == IIF_OK); + CHECK(f.signal(x, 0) == IIF_OK); + CHECK(f.wait(x, 0u) == IIF_OK); + f.destroy(x); + } + CHECK(f.live_count() == 0u); + CHECK(f.created() == 1002u); + CHECK(f.signaled() == 1004u); +} + +static void test_iif_uapi_constants() { + CHECK(FS_IIF_IP_AP == 3); + CHECK(FS_IIF_CREATE_FENCE == 0xc0086900UL); + CHECK(FS_IIF_FENCE_SUBMIT_SIGNALER == 0x00006981UL); + CHECK(FS_IIF_FENCE_SIGNAL == 0xc0086982UL); + CHECK(FS_IIF_FENCE_BRIDGE_DMA == 0x80046985UL); + CHECK(FS_IIF_FENCE_SIGNALER_DONE == 0x00006986UL); + /* _IOC layout: dir[31:30] size[29:16] type[15:8] nr[7:0]. */ + CHECK(((FS_IIF_CREATE_FENCE >> 8) & 0xFFu) == static_cast('i')); + CHECK(((FS_IIF_CREATE_FENCE >> 16) & 0x3FFFu) == sizeof(fs_iif_create_fence_ioctl)); + CHECK(((FS_IIF_FENCE_SIGNAL >> 16) & 0x3FFFu) == sizeof(fs_iif_fence_signal_ioctl)); + CHECK((FS_IIF_FENCE_SIGNAL & 0xFFu) == 0x82u && (FS_IIF_CREATE_FENCE >> 30) == 3u); + CHECK(((FS_IIF_FENCE_BRIDGE_DMA >> 16) & 0x3FFFu) == 4u && (FS_IIF_FENCE_BRIDGE_DMA >> 30) == 2u); + CHECK(sizeof(fs_iif_create_fence_ioctl) == 8u && offsetof(fs_iif_create_fence_ioctl, total_signalers) == 2u && + offsetof(fs_iif_create_fence_ioctl, fence_fd) == 4u); + CHECK(sizeof(fs_iif_fence_signal_ioctl) == 8u && offsetof(fs_iif_fence_signal_ioctl, remaining_signalers) == 4u); + const IifAbi abi = iif_default_abi(); + CHECK(abi.create_req == FS_IIF_CREATE_FENCE && abi.submit_signaler_req == FS_IIF_FENCE_SUBMIT_SIGNALER && + abi.signal_req == FS_IIF_FENCE_SIGNAL && abi.bridge_dma_req == FS_IIF_FENCE_BRIDGE_DMA && + abi.signaler_done_req == FS_IIF_FENCE_SIGNALER_DONE); +} + +static void test_sw_iif_submit_signaler() { + IifFences f; + f.init_sw(); + int h = -1; + CHECK(f.create(FS_IIF_IP_AP, 2u, &h) == IIF_OK); + CHECK(f.create(0x100u, 1u, &h) == IIF_ERR_ARG); /* signaler_ip is a u8 in the UAPI */ + CHECK(f.submit_signaler(h) == IIF_OK); + CHECK(f.submit_signaler(h) == IIF_OK); + CHECK(f.submit_signaler(h) == IIF_ERR_STATE); /* more submitters than signalers */ + CHECK(f.signal(h, 0) == IIF_OK && f.last_remaining() == 1u); + CHECK(f.signal(h, 0) == IIF_OK && f.last_remaining() == 0u); + CHECK(f.wait(h, 0u) == IIF_OK); + CHECK(f.submitted() == 2u); + f.destroy(h); + CHECK(f.live_count() == 0u); +} + +/* + * The raw IIF fence fd is not a sync_file; GPU queues import the sync_file + * returned by FS_IIF_FENCE_BRIDGE_DMA. Software fences have no fd form. + */ +static void test_iif_sync_file_bridge() { + IifFences none; + int fd = 123; + CHECK(none.bridge_sync_file(0, &fd) == IIF_ERR_STATE && fd == -1); + CHECK(none.bridge_sync_file(0, nullptr) == IIF_ERR_ARG); + IifFences f; + f.init_sw(); + int h = -1; + CHECK(f.create(FS_IIF_IP_AP, 1u, &h) == IIF_OK); + fd = 123; + CHECK(f.bridge_sync_file(h, &fd) == IIF_ERR_STATE && fd == -1); + CHECK(f.signal(h, 0) == IIF_OK); + f.destroy(h); + CHECK(!IifFences::fd_is_sync_file(-1)); +#if defined(__linux__) + int pfd[2] = {-1, -1}; + if (pipe(pfd) == 0) { + CHECK(!IifFences::fd_is_sync_file(pfd[0])); /* SYNC_IOC_FILE_INFO -> ENOTTY on a pipe */ + close(pfd[0]); + close(pfd[1]); + } +#endif +} + +static void test_quant8_helpers() { + const Quant8 q = quant8_from_absmax(127.0, 1.0); + CHECK(std::fabs(q.scale - 1.0f) < 1e-6f && q.zero_point == 128); + CHECK(quant8_quantize(0.0f, 1.0f, 128) == 128u); + CHECK(quant8_quantize(1000.0f, 1.0f, 128) == 255u && quant8_quantize(-1000.0f, 1.0f, 128) == 0u); + CHECK(quant8_quantize(2.5f, 1.0f, 128) == 130u); /* round-half-even like GLSL roundEven */ + CHECK(quant8_dequantize(130u, 0.5f, 128) == 1.0f); + /* 1x1 CONV_2D reference == exact int dot product when scales are 1. */ + const uint32_t d = 8u; + int8_t w[d * d]; + uint8_t in[d], out[d]; + for (uint32_t i = 0u; i < d * d; ++i) w[i] = static_cast(static_cast(i % 7u) - 3); + for (uint32_t k = 0u; k < d; ++k) in[k] = static_cast(128 + static_cast(k) - 4); + Quant8 unit; + unit.scale = 1.0f; + unit.zero_point = 128; + quant8_conv1x1_ref(in, unit, w, d, unit, out); + for (uint32_t n = 0u; n < d; ++n) { + int acc = 0; + for (uint32_t k = 0u; k < d; ++k) acc += w[n * d + k] * (static_cast(k) - 4); + const int ex = std::min(255, std::max(0, acc + 128)); + CHECK(out[n] == static_cast(ex)); + } +} + +static void test_iif_probe_graceful() { + const IifAbi abi = iif_default_abi(); + IifFences keep; + const IifProbe p = iif_probe("/nonexistent-freesched-iif-node", abi, FS_IIF_IP_GPU, &keep); + CHECK(!p.usable); + CHECK(!p.opened); + CHECK(!p.node_present); + CHECK(!p.bridge_ok && !p.bridge_signaled && !p.bridge_dma_ok); + CHECK(p.reason != nullptr); + CHECK(keep.kind() == FS_IIF_BACKEND_NONE); +#if defined(__linux__) + CHECK(p.open_errno == ENOENT); + CHECK(std::strcmp(p.reason, "ENOENT") == 0); + /* A regular file is not an IIF node: create must fail with an ABI-mismatch class errno. */ + std::string tpath = fs_temp_dir() + "/fs_iif_probe_XXXXXX"; + std::vector tbuf(tpath.begin(), tpath.end()); + tbuf.push_back('\0'); + char* tmpl = tbuf.data(); + const int fd = mkstemp(tmpl); + CHECK(fd >= 0); + if (fd >= 0) { + close(fd); + const IifProbe q = iif_probe(tmpl, abi, FS_IIF_IP_GPU, &keep); + CHECK(q.opened); + CHECK(!q.create_ok); + CHECK(!q.usable); + CHECK(!q.bridge_dma_ok); + /* Android SELinux ioctl allowlisting rejects unknown ioctls on tmpfs files with EACCES. */ + CHECK(q.create_errno == ENOTTY || q.create_errno == EINVAL || q.create_errno == EACCES); + CHECK(keep.kind() == FS_IIF_BACKEND_NONE); + unlink(tmpl); + } +#else + CHECK(std::strcmp(p.reason, "unsupported_os") == 0); +#endif +} + +static void test_proc_status_parse() { + const char* text = + "Name:\tbench\n" + "Threads:\t4\n" + "voluntary_ctxt_switches:\t123\n" + "nonvoluntary_ctxt_switches:\t45\n"; + int64_t v = 0, n = 0; + CHECK(parse_proc_status_ctxt(text, &v, &n)); + CHECK(v == 123); + CHECK(n == 45); + CHECK(!parse_proc_status_ctxt("voluntary_ctxt_switches: 1\n", &v, &n)); + CHECK(!parse_proc_status_ctxt(nullptr, &v, &n)); + const CtxSwitchSample s0 = sample_ctx_switches(); + usleep(2000); + const CtxSwitchSample s1 = sample_ctx_switches(); + CHECK(s1.voluntary >= s0.voluntary); + CHECK(s1.ru_voluntary >= s0.ru_voluntary); +#if defined(__linux__) + CHECK(s0.from_proc_status == 1); +#endif + const CtxSwitchSample bad = sample_ctx_switches("/nonexistent/status"); + CHECK(bad.from_proc_status == 0); + CHECK(bad.voluntary == bad.ru_voluntary); +} + +static bool write_text(const std::string& path, const char* text) { + FILE* f = std::fopen(path.c_str(), "w"); + if (!f) return false; + std::fputs(text, f); + std::fclose(f); + return true; +} + +static void test_odpm() { + OdpmReading rails; + const char* t0 = + "t=1000\n" + "CH0(T=1000)[S2S_VDD_G3D], 5000000\n" + "CH1(T=1000)[S6S_VDD_TPU], 2000000\n" + "CH2(T=1000)[VSYS_PWR_DISPLAY], 9000000\n" + "garbage line\n"; + CHECK(parse_odpm_energy_text(t0, "iio:device0", &rails) == 3); + CHECK(rails.has_timestamp && rails.timestamp_ms == 1000u && rails.device == "iio:device0"); + CHECK(rails.rails.size() == 3u && rails.rails[0].name == "S2S_VDD_G3D" && rails.rails[1].energy == 2000000); + CHECK(odpm_classify("S2S_VDD_G3D") == ODPM_CLASS_GPU); + CHECK(odpm_classify("vdd_gpu") == ODPM_CLASS_GPU); + CHECK(odpm_classify("S6S_VDD_TPU") == ODPM_CLASS_TPU); + CHECK(odpm_classify("VSYS_PWR_DISPLAY") == ODPM_CLASS_OTHER); + + std::string dpath = fs_temp_dir() + "/fs_odpm_XXXXXX"; + std::vector dbuf(dpath.begin(), dpath.end()); + dbuf.push_back('\0'); + char* root = mkdtemp(dbuf.data()); + CHECK(root != nullptr); + if (!root) return; + const std::string r(root); + const std::string d0 = r + "/iio:device0"; + const std::string d1 = r + "/iio:device1"; + CHECK(mkdir(d0.c_str(), 0700) == 0); + CHECK(mkdir(d1.c_str(), 0700) == 0); + CHECK(write_text(d0 + "/energy_value", "t=1\nCH0(T=1)[S2S_VDD_G3D], 1000000\nCH1(T=1)[S6S_VDD_TPU], 500000\n")); + CHECK(write_text(d1 + "/energy_value", "t=1\nCH0(T=1)[VSYS_PWR_MODEM], 100\n")); + OdpmSnapshot before, after; + CHECK(odpm_read_all(root, &before) == 3); + CHECK(write_text(d0 + "/energy_value", "t=2\nCH0(T=2)[S2S_VDD_G3D], 3000000\nCH1(T=2)[S6S_VDD_TPU], 1500000\n")); + CHECK(write_text(d1 + "/energy_value", "t=2\nCH0(T=2)[VSYS_PWR_MODEM], 500100\n")); + CHECK(odpm_read_all(root, &after) == 3); + const OdpmDelta dl = odpm_delta(before, after, 1e-6); + CHECK(dl.available); + CHECK(dl.rails == 3 && dl.gpu_rails == 1 && dl.tpu_rails == 1); + CHECK(std::fabs(dl.gpu_j - 2.0) < 1e-9); + CHECK(std::fabs(dl.tpu_j - 1.0) < 1e-9); + CHECK(std::fabs(dl.total_j - 3.5) < 1e-9); + unlink((d0 + "/energy_value").c_str()); + unlink((d1 + "/energy_value").c_str()); + rmdir(d0.c_str()); + rmdir(d1.c_str()); + rmdir(root); + + OdpmSnapshot none; + CHECK(odpm_read_all("/nonexistent-iio-root", &none) == 0); + CHECK(!odpm_delta(none, none, 1e-6).available); + + /* Equal `t=` is a cached ODPM sample: energy is unavailable, not a false 0 J delta. */ + OdpmReading cached_before, cached_after, advanced; + const char* same_t = + "t=50\n" + "CH0(T=50)[S2S_VDD_G3D], 1000000\n" + "CH1(T=50)[S6S_VDD_TPU], 2000000\n"; + const char* next_t = + "t=51\n" + "CH0(T=51)[S2S_VDD_G3D], 3000000\n" + "CH1(T=51)[S6S_VDD_TPU], 4000000\n"; + CHECK(parse_odpm_energy_text(same_t, "iio:device0", &cached_before) == 2); + CHECK(parse_odpm_energy_text(same_t, "iio:device0", &cached_after) == 2); + CHECK(cached_before.timestamp_ms == cached_after.timestamp_ms); + const OdpmDelta stale = odpm_delta(OdpmSnapshot{cached_before}, OdpmSnapshot{cached_after}, 1e-6); + CHECK(stale.available); + CHECK(std::isnan(stale.gpu_j) && std::isnan(stale.tpu_j) && std::isnan(stale.total_j)); + CHECK(json_finite_or_null(stale.gpu_j) == "null"); + CHECK(json_finite_or_null(stale.tpu_j) == "null"); + CHECK(json_finite_or_null(stale.total_j / 64.0) == "null"); + CHECK(parse_odpm_energy_text(next_t, "iio:device0", &advanced) == 2); + CHECK(advanced.timestamp_ms == 51u); + const OdpmDelta fresh = odpm_delta(OdpmSnapshot{cached_before}, OdpmSnapshot{advanced}, 1e-6); + CHECK(fresh.available && !std::isnan(fresh.gpu_j) && !std::isnan(fresh.tpu_j) && !std::isnan(fresh.total_j)); + /* +2e6 uJ and +2e6 uJ at 1 uJ = 1e-6 J -> 2 J and 2 J. */ + CHECK(std::fabs(fresh.gpu_j - 2.0) < 1e-12); + CHECK(std::fabs(fresh.tpu_j - 2.0) < 1e-12); + CHECK(std::fabs(fresh.total_j - 4.0) < 1e-12); + CHECK(json_finite_or_null(fresh.total_j, "%.6f") == "4.000000"); +} + +static void test_stats() { + std::vector v; + for (int i = 1; i <= 100; ++i) v.push_back(static_cast(101 - i)); + CHECK(percentile(v, 50.0) == 50.0); + CHECK(percentile(v, 99.0) == 99.0); + CHECK(percentile(v, 100.0) == 100.0); + CHECK(percentile(std::vector{}, 50.0) == 0.0); + CHECK(percentile(std::vector{7.0}, 99.0) == 7.0); + CHECK(std::fabs(mean(v) - 50.5) < 1e-12); + + const float got[3] = {1.0f, 2.0f, 3.0f}; + const double ref[3] = {1.0, 2.0, 3.0}; + const Parity p = parity_f32_vs_f64(got, ref, 3u); + CHECK(std::fabs(p.cos - 1.0) < 1e-12 && p.max_abs_err == 0.0); + const float neg[3] = {-1.0f, -2.0f, -3.0f}; + CHECK(parity_f32_vs_f64(neg, ref, 3u).cos < -0.99); + const float bad[3] = {1.0f, NAN, 3.0f}; + CHECK(parity_f32_vs_f64(bad, ref, 3u).cos == 0.0); + + XorShift64 a(42u), b(42u); + for (int i = 0; i < 16; ++i) CHECK(a.next() == b.next()); + XorShift64 c(7u); + for (int i = 0; i < 1000; ++i) { + const float s = c.symmetric(); + CHECK(s >= -1.0f && s < 1.0f); + } +} + +/* + * --require-iif must be backed by measured IIF use: a live --iif-sw-fallback + * run (software backend, plain sync-fence NNAPI chain, 0 kernel IIF fences) + * must not satisfy it, nor may a kernel backend whose r_iif arm created none. + */ +static void test_require_iif_gate() { + CHECK(iif_requirement_met(true, true, FS_IIF_BACKEND_KERNEL, 64u)); + CHECK(!iif_requirement_met(true, true, FS_IIF_BACKEND_KERNEL, 0u)); + CHECK(!iif_requirement_met(true, true, FS_IIF_BACKEND_SW_EMULATED, 0u)); + CHECK(!iif_requirement_met(true, true, FS_IIF_BACKEND_SW_EMULATED, 768u)); + CHECK(!iif_requirement_met(true, false, FS_IIF_BACKEND_KERNEL, 0u)); + CHECK(!iif_requirement_met(true, true, FS_IIF_BACKEND_NONE, 0u)); + /* Mock: the software emulator is the IIF under test, but fences must still be used. */ + CHECK(iif_requirement_met(false, true, FS_IIF_BACKEND_SW_EMULATED, 16u)); + CHECK(!iif_requirement_met(false, true, FS_IIF_BACKEND_SW_EMULATED, 0u)); + CHECK(!iif_requirement_met(false, false, FS_IIF_BACKEND_SW_EMULATED, 16u)); + CHECK(!iif_requirement_met(false, true, FS_IIF_BACKEND_NONE, 16u)); +} + +/* + * Raw kernel IIF without a working FS_IIF_FENCE_BRIDGE_DMA (older Google IIF + * drivers): the CPU-proxy r_iif handoffs stay available, the NNAPI Vulkan gate + * is disabled (ungated sync-fence chain, 0 IIF fences), and --require-iif still + * rejects that ungated chain. + */ +static void test_iif_raw_without_bridge() { + CHECK(iif_cpu_proxy_available(FS_IIF_BACKEND_KERNEL)); + CHECK(iif_cpu_proxy_available(FS_IIF_BACKEND_SW_EMULATED)); + CHECK(!iif_cpu_proxy_available(FS_IIF_BACKEND_NONE)); + CHECK(iif_nnapi_gate_enabled(FS_IIF_BACKEND_KERNEL, true)); + CHECK(!iif_nnapi_gate_enabled(FS_IIF_BACKEND_KERNEL, false)); /* raw IIF, no bridge */ + CHECK(!iif_nnapi_gate_enabled(FS_IIF_BACKEND_SW_EMULATED, true)); + CHECK(!iif_nnapi_gate_enabled(FS_IIF_BACKEND_NONE, true)); + /* Ungated NNAPI chain records 0 IIF fences: --require-iif must fail. */ + CHECK(!iif_requirement_met(true, true, FS_IIF_BACKEND_KERNEL, 0u)); + /* CPU-proxy handoffs on raw kernel IIF (no bridge needed) still satisfy it. */ + CHECK(iif_requirement_met(true, true, FS_IIF_BACKEND_KERNEL, 24u)); +#if defined(__linux__) + /* + * Live: when /dev/iif opens (root on Tensor G5/G6), a bridge request the driver + * does not implement must leave the raw round trip usable and bridge_dma_ok false. + */ + const int dfd = open("/dev/iif", O_RDWR | O_CLOEXEC); + if (dfd < 0) { + std::printf("test_iif_raw_without_bridge: /dev/iif not openable (errno %d), live probe skipped\n", errno); + return; + } + close(dfd); + const IifAbi good = iif_default_abi(); + const IifProbe g = iif_probe("/dev/iif", good, FS_IIF_IP_AP, nullptr); + CHECK(g.usable); + CHECK(g.bridge_dma_ok == (g.bridge_ok && g.bridge_signaled)); + IifAbi nobridge = good; + nobridge.bridge_dma_req = 0x8004697fUL; /* _IOR('i', 0x7f, 4): not an IIF request */ + const IifProbe n = iif_probe("/dev/iif", nobridge, FS_IIF_IP_AP, nullptr); + CHECK(n.usable); + CHECK(n.create_ok && n.submit_ok && n.signal_ok && n.wait_ok); + CHECK(!n.bridge_ok && !n.bridge_dma_ok && n.bridge_errno != 0); + CHECK(!iif_nnapi_gate_enabled(FS_IIF_BACKEND_KERNEL, n.bridge_dma_ok)); + std::printf("test_iif_raw_without_bridge: live /dev/iif bridge_dma_ok=%d, without bridge usable=%d errno=%d\n", + g.bridge_dma_ok ? 1 : 0, n.usable ? 1 : 0, n.bridge_errno); +#endif +} + +/* Diagnostics document with every non-finite case the bench can produce. */ +static std::string nonfinite_diag_json() { + const double inf = std::numeric_limits::infinity(); + const double nan = std::numeric_limits::quiet_NaN(); + std::string j = "{\"pass\":false,\"cos\":" + json_finite_or_null(0.0, "%.9f"); + j += ",\"max_abs_err\":" + json_finite_or_null(inf, "%.6g"); + j += ",\"neg_inf\":" + json_finite_or_null(-inf, "%.6g"); + j += ",\"cross_arm_max_abs_diff\":" + json_finite_or_null(nan, "%.6g"); + j += ",\"ms_per_tok_p50\":" + json_finite_or_null(nan, "%.6f"); + j += ",\"j_per_tok_vsys\":" + json_finite_or_null(inf); + j += ",\"tok_per_s\":" + json_finite_or_null(12.5, "%.6f") + "}"; + return j; +} + +static void test_json_finite_or_null() { + CHECK(json_finite_or_null(std::numeric_limits::infinity()) == "null"); + CHECK(json_finite_or_null(-std::numeric_limits::infinity(), "%.6g") == "null"); + CHECK(json_finite_or_null(std::numeric_limits::quiet_NaN(), "%.9f") == "null"); + CHECK(json_finite_or_null(0.5, "%.6f") == "0.500000"); + CHECK(json_finite_or_null(24.0, "%.3f") == "24.000"); + CHECK(json_finite_or_null(1e-7, "%.6g") == "1e-07"); + const std::string j = nonfinite_diag_json(); + for (const char* bad : {":inf", ":-inf", ":nan", ":-nan", ":INF", ":NAN"}) CHECK(j.find(bad) == std::string::npos); + CHECK(j.find("\"max_abs_err\":null") != std::string::npos); + CHECK(j.find("\"cross_arm_max_abs_diff\":null") != std::string::npos); + CHECK(j.find("\"pass\":false") != std::string::npos); +} + +/* Caller-supplied --iif-dev path with a quote, backslashes and control characters. */ +static const std::string kHostileIifDev = std::string("/tmp/iif\"\\test") + "\n\x01\x1f"; + +static std::string hostile_probe_json() { + IifProbe p{}; + p.reason = "say \"hi\"\\"; + return iif_probe_json(kHostileIifDev.c_str(), p, iif_default_abi()); +} + +static void test_json_escape() { + CHECK(json_escape("") == "\"\""); + CHECK(json_escape("/dev/iif") == "\"/dev/iif\""); + CHECK(json_escape(kHostileIifDev) == "\"/tmp/iif\\\"\\\\test\\u000a\\u0001\\u001f\""); + const std::string j = hostile_probe_json(); + CHECK(j.rfind("{\"dev\":\"/tmp/iif\\\"\\\\test\\u000a\\u0001\\u001f\",\"probed\":false,\"node_present\":false,", 0) == 0); + CHECK(j.find("\"reason\":\"say \\\"hi\\\"\\\\\",\"abi\":\"google-iif-uapi\"") != std::string::npos); + CHECK(j.back() == '}'); + for (char ch : j) CHECK(static_cast(ch) >= 0x20u); +} + +/* + * sync_file handoff verdict: a readable kernel sync_file is consumed only when + * SYNC_IOC_FILE_INFO reports status == 1. Errored fences (status < 0, e.g. + * -EIO or -ECANCELED from an errored /dev/iif bridge) and unsignaled ones fail. + * Software-mock stand-ins are poll() readiness only: the ioctl result, including + * Android shell EACCES, is not consulted. + */ +static void test_sync_handoff_verdict() { + CHECK(FS_SYNC_IOC_FILE_INFO == 0xc0383e04UL); + const char* why = nullptr; + CHECK(sync_handoff_verdict(1, POLLIN, 0, 1, SYNC_FD_KERNEL_SYNC_FILE, &why) && std::strcmp(why, "ok") == 0); + CHECK(!sync_handoff_verdict(1, POLLIN, 0, -EIO, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "fence_error_status") == 0); + CHECK(!sync_handoff_verdict(1, POLLIN, 0, -ECANCELED, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "fence_error_status") == 0); + CHECK(!sync_handoff_verdict(1, POLLIN, 0, 0, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "fence_unsignaled_status") == 0); + CHECK(!sync_handoff_verdict(1, POLLIN | POLLERR, 0, 1, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "poll_err_or_nval") == 0); + CHECK(!sync_handoff_verdict(1, POLLNVAL, 0, 1, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(!sync_handoff_verdict(0, 0, 0, 1, SYNC_FD_KERNEL_SYNC_FILE, &why) && std::strcmp(why, "timeout") == 0); + CHECK(!sync_handoff_verdict(-1, 0, 0, 1, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(!sync_handoff_verdict(1, 0, 0, 1, SYNC_FD_KERNEL_SYNC_FILE, &why)); + /* Kernel mode: ENOTTY/EINVAL/EACCES all fail closed. Mock mode ignores them. */ + CHECK(!sync_handoff_verdict(1, POLLIN, ENOTTY, 0, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "not_a_sync_file") == 0); + CHECK(!sync_handoff_verdict(1, POLLIN, EINVAL, 0, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(!sync_handoff_verdict(1, POLLIN, EACCES, 0, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "sync_file_info_failed") == 0); + CHECK(sync_handoff_verdict(1, POLLIN, 0, -EIO, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "ok_mock_poll_only") == 0); + CHECK(sync_handoff_verdict(1, POLLIN, ENOTTY, 0, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(sync_handoff_verdict(1, POLLIN, EINVAL, 0, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(sync_handoff_verdict(1, POLLIN, EACCES, 0, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(sync_handoff_verdict(1, POLLIN, EBADF, 0, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(!sync_handoff_verdict(0, POLLIN, 0, 1, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "timeout") == 0); + CHECK(sync_fd_wait_handoff(-1, 0, SYNC_FD_KERNEL_SYNC_FILE, &why) && std::strcmp(why, "ok_no_fence") == 0); +#if defined(__linux__) + /* + * Readable pipe stand-in: kernel mode still runs SYNC_IOC_FILE_INFO and rejects + * the fd. Mock mode does not issue the ioctl, so Android shell EACCES cannot + * fail the wait. + */ + int pfd[2] = {-1, -1}; + CHECK(pipe(pfd) == 0); + if (pfd[0] >= 0) { + CHECK(!sync_fd_wait_handoff(pfd[0], 0, SYNC_FD_KERNEL_SYNC_FILE, &why) && std::strcmp(why, "timeout") == 0); + const char b = 1; + CHECK(write(pfd[1], &b, 1) == 1); + CHECK(!sync_fd_wait_handoff(pfd[0], 100, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "not_a_sync_file") == 0 || std::strcmp(why, "sync_file_info_failed") == 0); + CHECK(sync_fd_wait_handoff(pfd[0], 100, SYNC_FD_MOCK_NON_SYNC_FILE, &why)); + CHECK(std::strcmp(why, "ok_mock_poll_only") == 0); + std::printf("test_sync_handoff_verdict: mock pipe accepted on poll readiness (no SYNC_IOC_FILE_INFO)\n"); + close(pfd[0]); + close(pfd[1]); + } +#endif +} + +/* + * Live (root on Tensor G5/G6): an IIF fence bridged to a sync_file with + * FS_IIF_FENCE_BRIDGE_DMA and signaled WITH an error becomes readable (POLLIN), + * but SYNC_IOC_FILE_INFO reports status < 0, so the handoff must be rejected. + * A cleanly signaled bridge reports status == 1 and is accepted. + */ +static void test_iif_errored_bridge_rejected() { +#if defined(__linux__) + const int dfd = open("/dev/iif", O_RDWR | O_CLOEXEC); + if (dfd < 0) { + std::printf("test_iif_errored_bridge_rejected: /dev/iif not openable (errno %d), live check skipped\n", errno); + return; + } + IifFences f; + f.init_kernel(dfd, iif_default_abi()); /* f owns dfd */ + for (int round = 0; round < 2; ++round) { + const bool errored = (round == 0); + int h = -1, bfd = -1; + if (f.create(FS_IIF_IP_AP, 1u, &h) != IIF_OK || f.submit_signaler(h) != IIF_OK) { + std::printf("test_iif_errored_bridge_rejected: IIF create/submit failed (errno %d), skipped\n", f.last_errno()); + if (h >= 0) f.destroy(h); + return; + } + if (f.bridge_sync_file(h, &bfd) != IIF_OK) { + std::printf("test_iif_errored_bridge_rejected: no FS_IIF_FENCE_BRIDGE_DMA (errno %d), skipped\n", + f.last_errno()); + (void)f.signal(h, 0); + f.destroy(h); + return; + } + CHECK(IifFences::fd_is_sync_file(bfd)); + const int32_t sig_err = errored ? -EIO : 0; + CHECK(f.signal(h, sig_err) == IIF_OK); + struct pollfd p{}; + p.fd = bfd; + p.events = POLLIN; + const int prc = poll(&p, 1, 1000); + const char* why = nullptr; + int32_t status = 0; + const bool ok = sync_fd_wait_handoff(bfd, 1000, SYNC_FD_KERNEL_SYNC_FILE, &why, &status); + std::printf("test_iif_errored_bridge_rejected: signal(error=%d) -> poll rc=%d revents=0x%x, " + "SYNC_IOC_FILE_INFO.status=%d, handoff %s (%s)\n", + static_cast(sig_err), prc, static_cast(p.revents), static_cast(status), + ok ? "accepted" : "rejected", why ? why : "?"); + if (errored) { + CHECK(prc == 1 && (p.revents & POLLIN) != 0); /* readable despite the error: POLLIN alone is not success */ + CHECK(status < 0); + CHECK(!ok); + CHECK(std::strcmp(why, "fence_error_status") == 0); + } else { + CHECK(status == 1); + CHECK(ok); + } + close(bfd); + (void)f.wait(h, 1000u); + f.destroy(h); + } +#endif +} + +#if !defined(__ANDROID__) +/* ---- NNAPI fenced-start mock (host seam of NnEdgeTpu) ---- */ +static int g_nn_start_calls = 0, g_nn_dep_calls = 0, g_nn_free_calls = 0, g_nn_wait_calls = 0; +static int g_nn_dep_sleep_us = 0; +static int g_nn_out_event_tag = 0, g_nn_dep_event_tag = 0, g_nn_exec_tag = 0; +static int mock_exec_start(void*, const void* const*, uint32_t, uint64_t, void** out_event) { + ++g_nn_start_calls; + *out_event = &g_nn_out_event_tag; + return 0; +} +static int mock_event_from_fd(int, void** ev) { + ++g_nn_dep_calls; + if (g_nn_dep_sleep_us > 0) usleep(static_cast(g_nn_dep_sleep_us)); + *ev = &g_nn_dep_event_tag; + return 0; +} +static int mock_event_get_fd(const void*, int* fd) { + *fd = -1; /* unfenced completion: no fd to leak */ + return 0; +} +static int mock_event_wait(void*) { + ++g_nn_wait_calls; + return 0; +} +static int g_nn_exec_free_calls = 0; +static void mock_event_free(void*) { ++g_nn_free_calls; } +static void mock_exec_free(void*) { ++g_nn_exec_free_calls; } + +static void install_mock(NnEdgeTpu* nn, const char* dev, + int64_t feature_level = kNnapiFeatureLevel4, + int32_t device_type = kNnapiDeviceTypeAccelerator) { + NnEdgeTpu::TestHooks h; + h.exec_start_deps = mock_exec_start; + h.event_from_fd = mock_event_from_fd; + h.event_get_fd = mock_event_get_fd; + h.event_wait = mock_event_wait; + h.event_free = mock_event_free; + h.exec_free = mock_exec_free; + h.exec = &g_nn_exec_tag; + h.feature_level = feature_level; + h.device_type = device_type; + nn->install_test_hooks(dev, h); +} +#endif + +/* + * google-edgetpu x dmabuf_fd x fenced execution is refused before dispatch: + * no dependency event, no ANeuralNetworksExecution_startComputeWithDependencies. + */ +static void test_nnapi_edgetpu_dmabuf_fenced_guard() { + CHECK(nnapi_device_is_edgetpu("google-edgetpu")); + CHECK(nnapi_device_is_edgetpu("Google-EdgeTPU")); + CHECK(!nnapi_device_is_edgetpu("qti-dsp") && !nnapi_device_is_edgetpu(nullptr)); + CHECK(std::strcmp(nnapi_fenced_dmabuf_block_reason("google-edgetpu", true, false), FS_NN_FENCED_DMABUF_BLOCKED) == 0); + CHECK(nnapi_fenced_dmabuf_block_reason("google-edgetpu", false, false) == nullptr); /* AHB */ + CHECK(nnapi_fenced_dmabuf_block_reason("google-edgetpu", true, true) == nullptr); /* debug probe */ + CHECK(nnapi_fenced_dmabuf_block_reason("qti-dsp", true, false) == nullptr); + CHECK(std::strcmp(nnapi_fenced_dmabuf_policy("google-edgetpu", true, false), "blocked_edgetpu_before_dispatch") == 0); + CHECK(std::strcmp(nnapi_fenced_dmabuf_policy("google-edgetpu", true, true), "allowed_edgetpu_debug_probe") == 0); + CHECK(std::strcmp(nnapi_fenced_dmabuf_policy("google-edgetpu", false, false), "not_applicable_ahb") == 0); +#if !defined(__ANDROID__) + { + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu"); + nn.set_fenced_memory(true, false); + g_nn_start_calls = g_nn_dep_calls = 0; + int out_fd = 7; + NnInflight inf; + double bus = -1.0; + bool unf = true; + std::string err; + CHECK(!nn.start(0u, -1, &out_fd, &inf, &bus, &unf, &err)); + CHECK(err.find(FS_NN_FENCED_DMABUF_BLOCKED) != std::string::npos); + CHECK(out_fd == -1 && bus == 0.0 && !unf && inf.out_event == nullptr && inf.dep_event == nullptr); + /* With a dependency fd (r_iif): still refused before ANeuralNetworksEvent_createFromSyncFenceFd. */ + err.clear(); + CHECK(!nn.start(1u, 0, &out_fd, &inf, &bus, &unf, &err)); + CHECK(g_nn_start_calls == 0 && g_nn_dep_calls == 0); + CHECK(nn.exec_start_calls() == 0u && nn.fenced_refusals() == 2u); + CHECK(std::strcmp(nn.fenced_block_reason(), FS_NN_FENCED_DMABUF_BLOCKED) == 0); + } + { + /* Same device with AHB memory, or with the explicit debug probe: dispatched. */ + for (int k = 0; k < 2; ++k) { + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu"); + nn.set_fenced_memory(k == 1, k == 1); + g_nn_start_calls = g_nn_dep_calls = g_nn_free_calls = 0; + int out_fd = -1; + NnInflight inf; + double bus = 0.0; + bool unf = false; + std::string err; + CHECK(nn.start(0u, -1, &out_fd, &inf, &bus, &unf, &err)); + CHECK(g_nn_start_calls == 1 && nn.exec_start_calls() == 1u && nn.fenced_refusals() == 0u); + CHECK(nn.check_done(&inf, &err)); + nn.release(&inf); + CHECK(g_nn_free_calls == 1); + } + } + { + /* + * Timer placement: dependency-event creation (made slow here) is reported in + * dep_event_create_us and excluded from block_us, which brackets only + * startComputeWithDependencies (instant in the mock). + */ + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu"); + nn.set_fenced_memory(false, false); + g_nn_start_calls = g_nn_dep_calls = g_nn_free_calls = 0; + g_nn_dep_sleep_us = 30000; + int out_fd = -1; + NnInflight inf; + double bus = 0.0; + bool unf = false; + std::string err; + CHECK(nn.start(0u, 0, &out_fd, &inf, &bus, &unf, &err)); + g_nn_dep_sleep_us = 0; + CHECK(g_nn_dep_calls == 1 && g_nn_start_calls == 1); + CHECK(inf.dep_event_create_us >= 25000.0); + CHECK(bus < 20000.0 && bus < inf.dep_event_create_us); + std::printf("test_nnapi_edgetpu_dmabuf_fenced_guard: dep_event_create_us=%.1f block_us=%.1f\n", + inf.dep_event_create_us, bus); + nn.release(&inf); + CHECK(g_nn_free_calls == 2); /* out_event + dep_event */ + } + { + /* + * Abandoning in-flight NNAPI work after a fence timeout preserves every + * event/execution/compilation through shutdown() and ~NnEdgeTpu(). + */ + g_nn_start_calls = g_nn_dep_calls = g_nn_free_calls = g_nn_exec_free_calls = 0; + { + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu"); + nn.set_fenced_memory(false, false); + int out_fd = -1; + NnInflight inf; + double bus = 0.0; + bool unf = false; + std::string err; + CHECK(nn.start(0u, 0, &out_fd, &inf, &bus, &unf, &err)); + inf.execution = &g_nn_exec_tag; + nn.abandon_in_flight(); + CHECK(nn.abandoned()); + nn.release(&inf); + CHECK(inf.out_event == nullptr && inf.dep_event == nullptr && inf.execution == nullptr); + CHECK(!nn.start(0u, -1, &out_fd, &inf, &bus, &unf, &err)); + CHECK(err.find("abandoned") != std::string::npos); + nn.shutdown(); + } + CHECK(g_nn_free_calls == 0 && g_nn_exec_free_calls == 0); + } +#endif +} + +/* + * NNAPI feature-level guard: native fenced execution requires an ACCELERATOR + * device at feature level >= 30 (ANEURALNETWORKS_FEATURE_LEVEL_4 / HAL 1.3+). + * Below 30 (or when getFeatureLevel is unavailable / device is CPU), + * fenced_api() is false and start() refuses BEFORE calling into NNAPI so the + * runtime cannot take its unbounded synchronous sync_wait() fallback. + */ +static void test_nnapi_feature_level_fenced_guard() { + CHECK(nnapi_device_supports_native_fenced(kNnapiDeviceTypeAccelerator, 30)); + CHECK(nnapi_device_supports_native_fenced(kNnapiDeviceTypeAccelerator, 31)); + CHECK(nnapi_device_supports_native_fenced(kNnapiDeviceTypeAccelerator, 1000008)); + CHECK(!nnapi_device_supports_native_fenced(kNnapiDeviceTypeAccelerator, 29)); + CHECK(!nnapi_device_supports_native_fenced(kNnapiDeviceTypeAccelerator, 0)); + CHECK(!nnapi_device_supports_native_fenced(kNnapiDeviceTypeAccelerator, -1)); + CHECK(!nnapi_device_supports_native_fenced(kNnapiDeviceTypeCpu, 30)); + CHECK(nnapi_fenced_feature_level_block_reason(kNnapiDeviceTypeAccelerator, 30) == nullptr); + CHECK(std::strcmp(nnapi_fenced_feature_level_block_reason(kNnapiDeviceTypeAccelerator, 29), + FS_NN_FENCED_FEATURE_LEVEL_TOO_LOW) == 0); + CHECK(std::strcmp(nnapi_fenced_feature_level_block_reason(kNnapiDeviceTypeAccelerator, -1), + FS_NN_FENCED_FEATURE_LEVEL_TOO_LOW) == 0); + CHECK(std::strcmp(nnapi_fenced_feature_level_block_reason(kNnapiDeviceTypeCpu, 30), + FS_NN_FENCED_NON_ACCELERATOR) == 0); +#if !defined(__ANDROID__) + /* Feature level 29 (< 30): fenced_api() disabled, start() refused before any NNAPI call. */ + for (int64_t bad_fl : {static_cast(29), static_cast(-1)}) { + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu", bad_fl, kNnapiDeviceTypeAccelerator); + nn.set_fenced_memory(false, false); + CHECK(nn.ready()); + CHECK(nn.device_feature_level() == bad_fl); + CHECK(!nn.fenced_api()); + CHECK(nn.fenced_feature_level_block_reason() != nullptr); + CHECK(std::strcmp(nn.fenced_feature_level_block_reason(), FS_NN_FENCED_FEATURE_LEVEL_TOO_LOW) == 0); + g_nn_start_calls = g_nn_dep_calls = 0; + int out_fd = 9; + NnInflight inf; + double bus = -1.0; + bool unf = true; + std::string err; + CHECK(!nn.start(0u, 0, &out_fd, &inf, &bus, &unf, &err)); + CHECK(err.find(FS_NN_FENCED_FEATURE_LEVEL_TOO_LOW) != std::string::npos); + CHECK(out_fd == -1 && bus == 0.0 && !unf && inf.out_event == nullptr && inf.dep_event == nullptr); + CHECK(g_nn_start_calls == 0 && g_nn_dep_calls == 0 && nn.exec_start_calls() == 0u); + } + /* Non-accelerator (CPU) device even at feature level 30+: refused before dispatch. */ + { + NnEdgeTpu nn; + install_mock(&nn, "nnapi-reference", 31, kNnapiDeviceTypeCpu); + nn.set_fenced_memory(false, false); + CHECK(!nn.fenced_api()); + CHECK(std::strcmp(nn.fenced_feature_level_block_reason(), FS_NN_FENCED_NON_ACCELERATOR) == 0); + g_nn_start_calls = g_nn_dep_calls = 0; + int out_fd = 9; + NnInflight inf; + double bus = -1.0; + bool unf = true; + std::string err; + CHECK(!nn.start(0u, 0, &out_fd, &inf, &bus, &unf, &err)); + CHECK(err.find(FS_NN_FENCED_NON_ACCELERATOR) != std::string::npos); + CHECK(g_nn_start_calls == 0 && g_nn_dep_calls == 0); + } + /* Feature level >= 30 on ACCELERATOR: fenced_api() enabled and dispatches cleanly. */ + { + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu", 1000008, kNnapiDeviceTypeAccelerator); + nn.set_fenced_memory(false, false); + CHECK(nn.fenced_api()); + CHECK(nn.device_feature_level() == 1000008); + CHECK(nn.fenced_feature_level_block_reason() == nullptr); + g_nn_start_calls = g_nn_dep_calls = g_nn_free_calls = 0; + int out_fd = -1; + NnInflight inf; + double bus = 0.0; + bool unf = false; + std::string err; + CHECK(nn.start(0u, 0, &out_fd, &inf, &bus, &unf, &err)); + CHECK(g_nn_start_calls == 1 && g_nn_dep_calls == 1); + nn.release(&inf); + CHECK(g_nn_free_calls == 2); + } +#endif +} + +static void test_strict_cli_parsing() { + double d = -1.0; + CHECK(parse_strict_positive_double("1e-6", &d) && d == 1e-6); + CHECK(parse_strict_positive_double("0.000001", &d) && d == 1e-6); + CHECK(parse_strict_positive_double("2.5", &d) && d == 2.5); + /* "1e\u22126" (U+2212 MINUS SIGN): atof() returned 1, a factor 1e6 energy overstatement. */ + d = -1.0; + CHECK(!parse_strict_positive_double("1e\xe2\x88\x92" "6", &d) && d == -1.0); + CHECK(!parse_strict_positive_double("0", &d)); + CHECK(!parse_strict_positive_double("-0", &d)); + CHECK(!parse_strict_positive_double("-1e-6", &d)); + CHECK(!parse_strict_positive_double("nan", &d)); + CHECK(!parse_strict_positive_double("NaN", &d)); + CHECK(!parse_strict_positive_double("inf", &d)); + CHECK(!parse_strict_positive_double("infinity", &d)); + CHECK(!parse_strict_positive_double("1e999", &d)); /* ERANGE overflow */ + CHECK(!parse_strict_positive_double("1e-400", &d)); /* ERANGE underflow */ + CHECK(!parse_strict_positive_double("", &d)); + CHECK(!parse_strict_positive_double(nullptr, &d)); + CHECK(!parse_strict_positive_double(" 1e-6", &d)); + CHECK(!parse_strict_positive_double("1e-6 ", &d)); + CHECK(!parse_strict_positive_double("1e-6J", &d)); + CHECK(parse_strict_double("0.995", 0.0, 1.0, &d) && d == 0.995); + CHECK(!parse_strict_double("1.5", 0.0, 1.0, &d)); + CHECK(!parse_strict_double("0.99x", 0.0, 1.0, &d)); + uint32_t u = 7u; + CHECK(parse_strict_u32("12", 10, &u) && u == 12u); + CHECK(parse_strict_u32("4294967295", 10, &u) && u == 0xFFFFFFFFu); + u = 7u; + CHECK(!parse_strict_u32("12x", 10, &u) && u == 7u); + CHECK(!parse_strict_u32("-1", 10, &u)); + CHECK(!parse_strict_u32("+1", 10, &u)); + CHECK(!parse_strict_u32(" 12", 10, &u)); + CHECK(!parse_strict_u32("4294967296", 10, &u)); + CHECK(!parse_strict_u32("0x10", 10, &u)); + CHECK(parse_strict_u32("0x10", 0, &u) && u == 16u); + CHECK(!parse_strict_u32("", 10, &u)); + unsigned long long ull = 0u; + CHECK(parse_strict_uint("0x8004697f", 0, 0xFFFFFFFFull, &ull) && ull == 0x8004697full); + CHECK(!parse_strict_uint("0x8004697fz", 0, 0xFFFFFFFFull, &ull)); + CHECK(!parse_strict_uint("99999999999999999999999", 10, ~0ull, &ull)); /* ERANGE */ + long long ll = 0; + CHECK(parse_strict_int("-5", -10, 10, &ll) && ll == -5); + CHECK(!parse_strict_int("-11", -10, 10, &ll)); + CHECK(!parse_strict_int("5.0", -10, 10, &ll)); +} + +/* --mock never probes /dev/iif: the not-run probe touches nothing and says why. */ +static void test_iif_probe_not_run() { + const uint64_t opens0 = iif_dev_open_calls(); + const IifProbe p = iif_probe_not_run("not_probed_mock"); + CHECK(!p.probed && !p.node_present && !p.opened && !p.usable && !p.bridge_dma_ok); + CHECK(p.open_errno == 0 && p.create_errno == 0); + CHECK(std::strcmp(p.reason, "not_probed_mock") == 0); + CHECK(iif_dev_open_calls() == opens0); + const std::string j = iif_probe_json("/dev/iif", p, iif_default_abi()); + CHECK(j.find("\"probed\":false") != std::string::npos); + CHECK(j.find("\"reason\":\"not_probed_mock\"") != std::string::npos); + IifFences keep; + const IifProbe q = iif_probe("/nonexistent-freesched-iif-node", iif_default_abi(), FS_IIF_IP_AP, &keep); + CHECK(q.probed); +#if defined(__linux__) + CHECK(iif_dev_open_calls() == opens0 + 1u); /* a real probe counts its open(2) */ +#endif +} + +/* + * Bounded NNAPI fence timeout recovery: an unsignaled completion fence reports + * why == "timeout" within the poll timeout, and recovery skips unbounded + * wait_done() / release() rather than calling ANeuralNetworksEvent_wait. + */ +static void test_nnapi_timeout_recovery_bounded() { +#if defined(__linux__) + int pfd[2] = {-1, -1}; + CHECK(pipe(pfd) == 0); + if (pfd[0] >= 0) { + const char* why = nullptr; + int32_t status = 0; + const bool ok = sync_fd_wait_handoff(pfd[0], 5, SYNC_FD_KERNEL_SYNC_FILE, &why, &status); + CHECK(!ok); + CHECK(why != nullptr && std::strcmp(why, "timeout") == 0); + close(pfd[0]); + close(pfd[1]); + } +#endif + const char* why = nullptr; + CHECK(!sync_handoff_verdict(0, 0, 0, 0, SYNC_FD_KERNEL_SYNC_FILE, &why)); + CHECK(why != nullptr && std::strcmp(why, "timeout") == 0); +#if !defined(__ANDROID__) + NnEdgeTpu nn; + install_mock(&nn, "google-edgetpu"); + nn.set_fenced_memory(false, false); + g_nn_start_calls = g_nn_dep_calls = g_nn_free_calls = g_nn_wait_calls = 0; + int out_fd = -1; + NnInflight inf; + double bus = 0.0; + bool unf = false; + std::string err; + CHECK(nn.start(0u, -1, &out_fd, &inf, &bus, &unf, &err)); + /* Mock returns unfenced (event_get_fd -> -1) so start() already waited once; simulate a timed-out fenced wait. */ + const int waits_after_start = g_nn_wait_calls; + const bool timed_out = (std::strcmp(why, "timeout") == 0); + if (!timed_out) { + nn.wait_done(&inf); + nn.release(&inf); + } + CHECK(timed_out); + CHECK(g_nn_wait_calls == waits_after_start); + CHECK(g_nn_free_calls == 0); + /* Cleanup mock pointers (no real heap allocations in mock). */ + inf = NnInflight{}; +#endif +} + +/* Failure-recovery drain input: IIF fences created and not destroyed stay outstanding. */ +static void test_iif_outstanding_accounting() { + IifFences f; + f.init_sw(); + CHECK(f.outstanding() == 0u); + int a = -1, b = -1; + CHECK(f.create(FS_IIF_IP_AP, 1u, &a) == IIF_OK); + CHECK(f.create(FS_IIF_IP_AP, 1u, &b) == IIF_OK); + CHECK(f.outstanding() == 2u); + f.destroy(a); + CHECK(f.outstanding() == 1u); + f.destroy(a); /* double destroy of a dead handle is not counted twice */ + CHECK(f.outstanding() == 1u); + f.destroy(b); + CHECK(f.outstanding() == 0u); + CHECK(f.create(FS_IIF_IP_AP, 1u, &a) == IIF_OK); + f.shutdown(); + CHECK(f.outstanding() == 0u); +} + +int main(int argc, char** argv) { + if (argc > 1 && std::strcmp(argv[1], "--emit-hostile-probe-json") == 0) { + std::printf("%s\n", hostile_probe_json().c_str()); /* strict python3 json check in CTest */ + return 0; + } + if (argc > 1 && std::strcmp(argv[1], "--emit-nonfinite-json") == 0) { + std::printf("%s\n", nonfinite_diag_json().c_str()); /* validated by python3 json in CTest */ + return 0; + } + test_sw_iif_semantics(); + test_iif_uapi_constants(); + test_sw_iif_submit_signaler(); + test_iif_sync_file_bridge(); + test_quant8_helpers(); + test_iif_probe_graceful(); + test_proc_status_parse(); + test_odpm(); + test_stats(); + test_require_iif_gate(); + test_iif_raw_without_bridge(); + test_json_finite_or_null(); + test_json_escape(); + test_sync_handoff_verdict(); + test_iif_errored_bridge_rejected(); + test_nnapi_edgetpu_dmabuf_fenced_guard(); + test_nnapi_feature_level_fenced_guard(); + test_nnapi_timeout_recovery_bounded(); + test_strict_cli_parsing(); + test_iif_probe_not_run(); + test_iif_outstanding_accounting(); + if (g_failures != 0) { + std::fprintf(stderr, "test_token_loop_riif: %d failure(s)\n", g_failures); + return 1; + } + std::printf("test_token_loop_riif: all checks passed\n"); + return 0; +} diff --git a/tests/token_loop_json_check.py b/tests/token_loop_json_check.py new file mode 100644 index 0000000..14a33e4 --- /dev/null +++ b/tests/token_loop_json_check.py @@ -0,0 +1,1313 @@ +#!/usr/bin/env python3 +"""Validate token-loop JSON output with a strict JSON parser (CTest helper). + + token_loop_json_check.py nonfinite + The non-finite diagnostics document must parse, report null for + inf/nan fields and keep pass=false. + token_loop_json_check.py escape + The IIF probe JSON for a device path containing a quote, backslashes + and control characters must parse and round-trip the exact path. + token_loop_json_check.py probe + `--iif-probe-only --iif-dev ` must exit 0 and print strict + JSON whose "dev" decodes to exactly that path. + token_loop_json_check.py bench + The bench must exit 0 and print one JSON object whose top-level pass is + true and whose every number is finite. + token_loop_json_check.py recover + Mock fault injection: a GPU fence failure mid-arm (pool slot left + INFLIGHT) is drained and retired so the next arm runs and passes; when the + drain cannot prove the device idle the executor is tainted and every later + arm is skipped (executor_tainted) without running. + token_loop_json_check.py mockiif + --mock never opens the IIF node (dev_open_calls == 0, probe.probed false) + even when --iif-dev names an existing file; --iif-probe-only still does. + token_loop_json_check.py badargs + Malformed numeric options (Unicode minus, 0, nan, trailing garbage, ...) + must exit exactly 2. + token_loop_json_check.py scripts + Unit tests for scripts/token_loop_capture.py and scripts/token_loop_receipt.py. + +Leading --emulator-arg= options (one per CMAKE_CROSSCOMPILING_EMULATOR list +element, command first) are prepended to every launched target executable, as +CTest does for tests that name an executable target. + +Copyright 2026 FreeSilicon Contributors +SPDX-License-Identifier: Apache-2.0 +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import io +import json +import os +import posixpath +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest import mock + + +# A valid path containing a quote and a backslash (never a real IIF node). +HOSTILE_IIF_DEV = '/tmp/iif"\\test' + + +def _reject_constant(name: str) -> None: + raise ValueError(f"non-JSON constant {name}") + + +def _load(text: str): + return json.loads(text, parse_constant=_reject_constant) + + +def _split_emulator(argv: list[str]) -> tuple[list[str], list[str]]: + emu: list[str] = [] + rest = [argv[0]] + i = 1 + while i < len(argv) and argv[i].startswith("--emulator-arg="): + emu.append(argv[i][len("--emulator-arg="):]) + i += 1 + rest.extend(argv[i:]) + return emu, rest + + +def _run_json(emu: list[str], exe: str, args: list[str], want_rc: int): + proc = subprocess.run([*emu, exe, *args], capture_output=True, text=True, check=False) + assert proc.returncode == want_rc, f"exit code {proc.returncode} != {want_rc}\n{proc.stdout}\n{proc.stderr}" + return _load(proc.stdout) + + +def _arm(doc, name): + return next(a for a in doc["arms"] if a["arm"] == name) + + +def _check_recover(emu: list[str], exe: str) -> int: + base = ["--mock", "--layers", "4", "--tokens", "4", "--warmup", "1", "--d", "512", "--json"] + # 1. Drained + retired: the failing arm reports its own error, the next arms run and pass. + for backend, arms, fault in (("auto", "sync_file_poll,r_iif", "sync_file_poll:3:2"), + ("nnapi", "host_staged,sync_file_poll,r_iif", "host_staged:0:0"), + ("auto", "host_staged,r_iif", "host_staged:2:3")): + doc = _run_json(emu, exe, [*base, "--tpu-backend", backend, "--arms", arms, + "--fault-inject-gpu-fence", fault], 1) + failed = _arm(doc, fault.split(":")[0]) + assert failed["ran"] is False and "injected GPU fence failure" in failed["error"], failed + assert failed["recovery"] == "drained_retired", failed + later = [a for a in arms.split(",") if a != failed["arm"]] + for name in later: + a = _arm(doc, name) + assert a["ran"] is True and a["pass"] is True, a + st = doc["executor_state"] + assert st["tainted"] is False and st["failure_recoveries"] == 1, st + assert st["submissions_retired_after_drain"] >= 1, st + assert st["ledger_inflight_at_exit"] == 0 and st["pool_inflight_slots_at_exit"] == 0, st + assert doc["pass"] is False, "a failed arm must fail the run" + # 2. Drain cannot prove idle: tainted, the later arm is skipped before it runs. + doc = _run_json(emu, exe, [*base, "--arms", "sync_file_poll,r_iif", "--fault-inject-gpu-fence", + "sync_file_poll:3:2", "--fault-inject-quiesce-fail"], 1) + assert _arm(doc, "sync_file_poll")["recovery"] == "tainted", doc + r = _arm(doc, "r_iif") + assert r["ran"] is False and r["skip_reason"] == "executor_tainted", r + assert "recovery" not in r, r + st = doc["executor_state"] + assert st["tainted"] is True and st["submissions_retired_after_drain"] == 0, st + assert st["ledger_inflight_at_exit"] == 1 and st["pool_inflight_slots_at_exit"] == 1, st + # 3. Fence wait timeout: bounded recovery returns immediately without calling quiesce(), + # taints the executor, quarantines the in-flight slot, and skips every later arm. + for arms, fault in (("sync_file_poll,r_iif", "sync_file_poll:2:1"), + ("host_staged,sync_file_poll,r_iif", "host_staged:0:0"), + ("r_iif", "r_iif:1:0")): + t0 = time.monotonic() + doc = _run_json(emu, exe, [*base, "--tpu-backend", "nnapi", "--arms", arms, + "--fault-inject-fence-timeout", fault], 1) + elapsed = time.monotonic() - t0 + assert elapsed < 5.0, f"timeout recovery took too long: {elapsed:.2f}s" + failed_name = fault.split(":")[0] + failed = _arm(doc, failed_name) + assert failed["ran"] is False and "timeout" in failed["error"], failed + assert failed["recovery"] == "tainted", failed + later = [a for a in arms.split(",") if a != failed_name] + for name in later: + a = _arm(doc, name) + assert a["ran"] is False and a["skip_reason"] == "executor_tainted", a + st = doc["executor_state"] + assert st["tainted"] is True and "BUG: quiesce()" not in st["taint_reason"], st + assert "timeout" in st["taint_reason"], st + assert st["failure_recoveries"] == 1 and st["submissions_retired_after_drain"] == 0, st + assert st["ledger_inflight_at_exit"] == 1 and st["pool_inflight_slots_at_exit"] == 1, st + # 4. The seams are mock-only. + for live_flag in (["--fault-inject-quiesce-fail"], ["--fault-inject-fence-timeout", "r_iif:0:0"]): + proc = subprocess.run([*emu, exe, "--live", *live_flag, "--json"], capture_output=True, + text=True, check=False) + assert proc.returncode == 2, (live_flag, proc.returncode) + print("failure recovery: drained+retired arms continue; timeout & tainted executor skip later arms without blocking") + return 0 + + +def _check_mock_iif(emu: list[str], exe: str) -> int: + with tempfile.TemporaryDirectory() as td: + node = os.path.join(td, "iif-node") + with open(node, "w", encoding="utf-8") as f: + f.write("not an iif node\n") + doc = _run_json(emu, exe, ["--mock", "--layers", "2", "--tokens", "2", "--d", "512", "--iif-dev", node, + "--require-iif", "--json"], 0) + iif = doc["iif"] + assert iif["dev_open_calls"] == 0, iif + assert iif["backend"] == "sw_emulated" and iif["signal_path"] == "sw_emulated", iif + p = iif["probe"] + assert p["probed"] is False and p["reason"] == "not_probed_mock", p + assert p["node_present"] is False and p["opened"] is False and p["open_errno"] == 0, p + probe = _run_json(emu, exe, ["--iif-probe-only", "--iif-dev", node], 0) + assert probe["probed"] is True, probe + if probe["reason"] != "unsupported_os": # Linux/Android: the explicit probe does open the node + assert probe["node_present"] is True and probe["opened"] is True, probe + print("--mock: 0 IIF node opens (software fences only); --iif-probe-only still probes") + return 0 + + +BAD_ARGS = ( + ["--odpm-unit-j", "1e\u22126"], + ["--odpm-unit-j", "0"], + ["--odpm-unit-j", "nan"], + ["--odpm-unit-j", "inf"], + ["--odpm-unit-j", "-1e-6"], + ["--odpm-unit-j", "1e-400"], + ["--odpm-unit-j", "1e-6J"], + ["--layers", "12x"], + ["--layers", "-1"], + ["--layers", " 12"], + ["--tokens", "4294967296"], + ["--warmup", "2.0"], + ["--min-cos", "0.99x"], + ["--min-cos", "nan"], + ["--min-cos", "0"], + ["--seed", ""], + ["--iif-ioctl-bridge", "0x8004697fz"], + ["--iif-signaler-ip", "256"], + ["--fault-inject-gpu-fence", "r_iif:1"], + ["--fault-inject-fence-timeout", "r_iif:1"], +) + + +def _check_badargs(emu: list[str], exe: str) -> int: + for bad in BAD_ARGS: + proc = subprocess.run([*emu, exe, "--mock", "--layers", "2", "--tokens", "2", *bad, "--json"], + capture_output=True, check=False) + assert proc.returncode == 2, (bad, proc.returncode) + ok = subprocess.run([*emu, exe, "--mock", "--layers", "2", "--tokens", "2", "--odpm-unit-j", "1e-6", "--json"], + capture_output=True, check=False) + assert ok.returncode == 0, ok.returncode + print(f"{len(BAD_ARGS)} malformed numeric options exit 2; a valid --odpm-unit-j still runs") + return 0 + + +def _load_script_module(name: str, rel_path: str): + repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + spec = importlib.util.spec_from_file_location(name, os.path.join(repo, rel_path)) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _check_scripts(proof_dir: str) -> int: + cap = _load_script_module("token_loop_capture", "scripts/token_loop_capture.py") + rec = _load_script_module("token_loop_receipt", "scripts/token_loop_receipt.py") + + class TestTokenLoopScripts(unittest.TestCase): + def _make_fake_build(self, td: str) -> tuple[str, str, str]: + bdir = os.path.join(td, "build") + os.makedirs(bdir, exist_ok=True) + bench_p = os.path.join(bdir, cap.BENCH) + unit_p = os.path.join(bdir, cap.UNIT) + with open(bench_p, "wb") as f: + f.write(b"fake-bench-binary\n") + with open(unit_p, "wb") as f: + f.write(b"fake-unit-binary\n") + return bdir, cap.sha256_file(bench_p), cap.sha256_file(unit_p) + + def _load_valid_run_payloads(self) -> dict[str, bytes]: + payloads: dict[str, bytes] = {} + for fname, _uid, _args, _want, _watch in cap.RUNS: + src = os.path.join(proof_dir, fname) + with open(src, "rb") as f: + raw = f.read() + if fname == "iif-probe-only-hostile-dev.json": + doc = json.loads(raw.decode("utf-8")) + doc["dev"] = cap.HOSTILE_DEV + raw = (json.dumps(doc) + "\n").encode("utf-8") + payloads[fname] = raw + return payloads + + def _run_capture_mocked( + self, + device_dir: str | None = None, + existing_tmp: tuple[str, ...] = ("other_file",), + session_mkdir_rc: int = 0, + push_rc: int = 0, + dmesg_rcs: tuple[int, int] = (0, 0), + crash_rcs: tuple[int, int] = (0, 0), + unit_outcomes: tuple[tuple[int, str], ...] = ( + (0, "test_token_loop_riif: all checks passed\n"), + (0, "test_token_loop_riif: all checks passed\n"), + (0, "test_token_loop_riif: all checks passed\n"), + ), + dmesg_after_extra: bytes = b"", + crash_after_extra: bytes = b"", + crash_before_body: bytes = b"--------- beginning of crash\n", + hal_pids: tuple[str, ...] = (), + hal_rcs: tuple[int, ...] = (), + date_rc: int = 0, + date_out: bytes = b"12-03 18:02:00.123456789\n", + prepopulate_out: dict[str, bytes] | None = None, + run_stdout_overrides: dict[str, bytes] | None = None, + watch_event_overrides: dict[str, bytes] | None = None, + tamper_sha_after_n: int | None = None, + extra_cli: tuple[str, ...] = (), + ) -> tuple[int, str, list[list[str]], dict]: + if device_dir is None: + device_dir = posixpath.join(cap.ROOT_EXEC_PARENT, "fs59test") + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + bdir, bsha, usha = self._make_fake_build(td) + out_dir = os.path.join(td, "out") + if prepopulate_out: + os.makedirs(out_dir, exist_ok=True) + for fn, data in prepopulate_out.items(): + with open(os.path.join(out_dir, fn), "wb") as f: + f.write(data) + lock_p = os.path.join(td, "adb.lock") + payloads = self._load_valid_run_payloads() + if run_stdout_overrides: + payloads.update(run_stdout_overrides) + calls: list[list[str]] = [] + state = {"dmesg": 0, "crash": 0, "unit": 0, "session_dir_exists": False, + "sha_calls": 0, "last_fname": "", "streamed_files": 0} + tmp_root = cap.DEVICE_TMP_ROOT + root_parent = cap.ROOT_EXEC_PARENT + + def fake_run(cmd, input=None, capture_output=True, check=False, **_kw): + calls.append(list(cmd)) + assert cmd[:2] == ["adb", "-s"] + assert cmd[3] == "shell", f"unexpected non-shell adb command (adb push forbidden): {cmd!r}" + sh = cmd[4] + is_root = sh.startswith("su -c ") + inner = sh[len("su -c "):].strip("'") if is_root else sh + if is_root: + assert tmp_root not in inner, f"privileged su command touched shell-writable tmp: {inner!r}" + if inner.startswith("getprop "): + return subprocess.CompletedProcess(cmd, 0, b"val\n", b"") + if inner == f"ls {tmp_root}": + assert not is_root, "ls of device tmp must run unprivileged as shell" + return subprocess.CompletedProcess(cmd, 0, ("\n".join(existing_tmp) + "\n").encode(), b"") + if inner.startswith("pidof " + cap.BENCH): + return subprocess.CompletedProcess(cmd, 1, b"", b"") + if inner.startswith("pidof "): + n = state.get("hal_n", 0) + state["hal_n"] = n + 1 + pid = hal_pids[n] if n < len(hal_pids) else "1234" + hrc = hal_rcs[n] if n < len(hal_rcs) else 0 + return subprocess.CompletedProcess(cmd, hrc, (pid + "\n").encode(), b"") + if inner.startswith("date "): + return subprocess.CompletedProcess(cmd, date_rc, date_out if date_rc == 0 else b"", b"date err") + if inner == "dmesg": + idx = state["dmesg"] + state["dmesg"] += 1 + rc = dmesg_rcs[min(idx, 1)] + body = b"[1.0] boot\n" if rc == 0 else b"" + if idx >= 1 and rc == 0: + body += dmesg_after_extra + return subprocess.CompletedProcess(cmd, rc, body, b"denied") + if inner.startswith("logcat -b crash -T ") and inner.endswith(" -d"): + idx = state["crash"] + state["crash"] += 1 + rc = crash_rcs[min(idx, 1)] + body = b"" if rc != 0 else crash_before_body + if idx >= 1 and rc == 0: + body += crash_after_extra + return subprocess.CompletedProcess(cmd, rc, body, b"err") + if inner.startswith("set -e; test -d /data/local;"): + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if inner.startswith("mkdir -m 0711 -- "): + if session_mkdir_rc == 0: + state["session_dir_exists"] = True + return subprocess.CompletedProcess( + cmd, session_mkdir_rc, b"", b"File exists" if session_mkdir_rc else b"") + if inner.startswith("set -e; umask 077;") and "base64 -d" in inner: + assert input is not None and len(input) > 0, "expected base64 binary payload on stdin" + state["streamed_files"] += 1 + return subprocess.CompletedProcess(cmd, push_rc, b"", b"stream err" if push_rc else b"") + if inner.startswith("set -e; chown 0:0 ") or inner.startswith("set -e; mkdir -m 0755 -- "): + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if inner.startswith("sha256sum "): + state["sha_calls"] += 1 + if tamper_sha_after_n is not None and state["sha_calls"] >= tamper_sha_after_n: + sha = "0" * 64 + else: + sha = usha if cap.UNIT in inner else bsha + return subprocess.CompletedProcess(cmd, 0, f"{sha} bin\n".encode(), b"") + if f"./{cap.BENCH} " in inner: + run_idx = state.get("bench_idx", 0) + state["bench_idx"] = run_idx + 1 + fname, _, _, want, _ = cap.RUNS[run_idx] + state["last_fname"] = fname + return subprocess.CompletedProcess(cmd, want, payloads[fname], b"") + if inner.startswith("cat ") and "iif-watch.status" in inner: + return subprocess.CompletedProcess(cmd, 0, b"watcher_active: true\n", b"") + if inner.startswith("cat ") and "iif-watch.txt" in inner: + last_fn = state.get("last_fname", "") + if watch_event_overrides and last_fn in watch_event_overrides: + ev = watch_event_overrides[last_fn] + else: + ev = b"r /dev/iif\n" if last_fn == "iif-probe-only.json" else b"" + return subprocess.CompletedProcess(cmd, 0, ev, b"") + if inner.startswith("rm -f") and "iif-watch.txt" in inner: + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if f"./{cap.UNIT}" in inner: + uidx = state["unit"] + state["unit"] += 1 + urc, uout = unit_outcomes[uidx] + return subprocess.CompletedProcess(cmd, urc, uout.encode(), b"") + if inner.startswith("rm -rf "): + if root_parent in inner: + state["session_dir_exists"] = False + return subprocess.CompletedProcess(cmd, 0, b"", b"") + if inner.startswith("ls -d "): + if state["session_dir_exists"]: + return subprocess.CompletedProcess(cmd, 0, f"{root_parent}/fs59test\n".encode(), b"") + return subprocess.CompletedProcess(cmd, 1, b"ls: No such file or directory\n", b"") + raise AssertionError(f"unhandled adb shell cmd: {sh!r} (inner={inner!r})") + + buf_out, buf_err = io.StringIO(), io.StringIO() + with mock.patch.object(cap.subprocess, "run", side_effect=fake_run), redirect_stdout(buf_out), redirect_stderr(buf_err): + rc = cap.main(["token_loop_capture.py", "--serial", "FAKE123", "--build", bdir, + "--out", out_dir, "--lock", lock_p, "--device-dir", device_dir, *extra_cli]) + summary: dict = {} + lines = [ln.strip() for ln in buf_out.getvalue().splitlines() if ln.strip()] + if lines and lines[-1].startswith("{"): + summary = json.loads(lines[-1]) + return rc, out_dir, calls, summary + + def test_device_dir_validation_and_exclusive_cleanup(self) -> None: + root = cap.ROOT_EXEC_PARENT + g12 = posixpath.join(root, "fs59g12") + test_dir = posixpath.join(root, "fs59test") + self.assertEqual(cap.validate_device_dir(g12), g12) + self.assertEqual(cap.validate_device_dir(g12 + "/"), g12) + for bad in ( + "", + "fs59g12", + root.lstrip("/") + "/fs59g12", + root, + root + "/", + root + "/.", + root + "/..", + root + "/a/../b", + root + "/../tmp/fs59g12", + root + "/nested/dir", + posixpath.join(cap.DEVICE_TMP_ROOT, "fs59g12"), + "/sdcard/fs59g12", + "/" + root + "/fs59g12", + root + "/bad space", + root + "/bad;rm", + root + "/$var", + root + "/.hidden", + root + "/-rf", + ): + with self.assertRaises(ValueError, msg=bad): + cap.validate_device_dir(bad) + # Invalid --device-dir exits 2 before touching adb. + rc, _, calls, _ = self._run_capture_mocked(device_dir=root + "/") + self.assertEqual(rc, 2) + self.assertEqual(calls, []) + # Exclusive mkdir -m 0711 (no -p) failing on pre-existing dir: aborts before streaming and never runs rm -rf. + rc, out_dir, calls, _ = self._run_capture_mocked(device_dir=test_dir + "/", session_mkdir_rc=1) + self.assertEqual(rc, 1) + self.assertFalse(os.path.exists(os.path.join(out_dir, "session.json"))) + flat = [" ".join(c) for c in calls] + mkdir_cmds = [c for c in flat if f"mkdir -m 0711 -- {test_dir}" in c] + self.assertEqual(len(mkdir_cmds), 1, flat) + self.assertNotIn("-p", mkdir_cmds[0]) + self.assertFalse(any("base64 -d" in c for c in flat), flat) + self.assertFalse(any("rm -rf" in c for c in flat), flat) + # Once exclusive mkdir succeeds, a later streaming failure DOES clean up the newly created session dir. + rc, _, calls, _ = self._run_capture_mocked(device_dir=test_dir + "/", session_mkdir_rc=0, push_rc=1) + self.assertEqual(rc, 1) + flat = [" ".join(c) for c in calls] + self.assertTrue(any(f"rm -rf -- {test_dir}" in c for c in flat), flat) + + def test_privileged_file_ops_stay_outside_shell_writable_dir(self) -> None: + test_dir = posixpath.join(cap.ROOT_EXEC_PARENT, "fs59test") + root_exec = cap.root_exec_dir_for(test_dir) + shell_exec = cap.shell_exec_dir_for(test_dir) + shell_tmp = cap.shell_tmp_dir_for(test_dir) + rc, out_dir, calls, summary = self._run_capture_mocked(device_dir=test_dir) + self.assertEqual(rc, 0, summary) + self.assertTrue(summary["published"]) + flat = [" ".join(c) for c in calls] + # 1. Zero adb push calls and zero su commands referencing /data/local/tmp. + self.assertFalse(any(len(c) > 3 and c[3] == "push" for c in calls), flat) + for c in flat: + if "su -c" in c: + self.assertNotIn(cap.DEVICE_TMP_ROOT, c) + # 2. Exclusive mkdir -m 0711 (no -p) on session dir and 0700 on root-exec. + sess_mkdir_idx = next(i for i, c in enumerate(flat) if f"mkdir -m 0711 -- {test_dir}" in c) + self.assertIn("su -c", flat[sess_mkdir_idx]) + self.assertNotIn("-p", flat[sess_mkdir_idx]) + self.assertTrue(any(f"mkdir -m 0700 -- {root_exec}" in c for c in flat), flat) + # 3. Binaries streamed via base64 -d into root_exec BEFORE first sha256sum and BEFORE execution. + stream_idxs = [i for i, c in enumerate(flat) if "base64 -d" in c] + self.assertEqual(len(stream_idxs), 2, flat) + for si in stream_idxs: + self.assertIn(root_exec, flat[si]) + first_sha_idx = next(i for i, c in enumerate(flat) if "sha256sum" in c) + first_bench_idx = next(i for i, c in enumerate(flat) if f"./{cap.BENCH}" in c) + self.assertLess(max(stream_idxs), first_sha_idx) + self.assertLess(first_sha_idx, first_bench_idx) + # 4. Every privileged su bench/unit/inotifyd command runs ONLY from root_exec, never shell_exec or shell_tmp. + su_execs = [c for c in flat if "su -c" in c and (f"./{cap.BENCH}" in c or f"./{cap.UNIT}" in c or "inotifyd" in c)] + self.assertTrue(len(su_execs) >= 13, su_execs) + for c in su_execs: + self.assertIn(root_exec, c) + self.assertNotIn(shell_exec, c) + self.assertNotIn(shell_tmp, c) + # 4b. Unprivileged shell runs execute from root-owned 0755 shell_exec (with 0700 shell_tmp as TMPDIR). + shell_execs = [c for c in flat if "su -c" not in c and (f"./{cap.BENCH}" in c or f"./{cap.UNIT}" in c)] + self.assertTrue(len(shell_execs) >= 4, shell_execs) + for c in shell_execs: + self.assertIn(shell_exec, c) + self.assertNotIn(root_exec, c) + self.assertTrue(any(f"TMPDIR={shell_tmp} " in c for c in shell_execs), shell_execs) + setup = next(c for c in flat if f"mkdir -m 0755 -- {shell_exec}" in c and "chcon -h" in c) + self.assertNotIn("chcon -R", setup) + tmp_root_own = f"chown 0:0 {shell_tmp}" + tmp_chcon = f"chcon -h u:object_r:shell_data_file:s0 {shell_tmp}" + tmp_chown = f"chown shell:shell {shell_tmp}" + self.assertLess(setup.index(tmp_root_own), setup.index(tmp_chcon)) + self.assertLess(setup.index(tmp_chcon), setup.index(tmp_chown)) + for path in (shell_exec, f"{shell_exec}/{cap.BENCH}", f"{shell_exec}/{cap.UNIT}"): + self.assertIn(f"chcon -h u:object_r:shell_data_file:s0 {path}", setup) + self.assertNotIn(f"chown shell:shell {shell_exec}", setup) + watched = [c for c in flat if "inotifyd" in c and f"./{cap.BENCH}" in c] + self.assertGreaterEqual(len(watched), 4, watched) + for c in watched: + self.assertIn("iif-watch.err", c) + self.assertNotIn("iif-watch.txt 2>/dev/null", c) + self.assertIn("2> ", c.split("inotifyd", 1)[1].split("&", 1)[0]) + bench_at = c.index(f"./{cap.BENCH}") + first_alive = c.index("kill -0") + second_alive = c.index("kill -0", first_alive + 1) + kill_at = c.rindex("kill ") + self.assertLess(first_alive, bench_at) + self.assertLess(bench_at, second_alive) + self.assertLess(second_alive, kill_at) + self.assertIn("watcher_active: false", c) + self.assertIn("sleep 0.1", c) + with open(os.path.join(out_dir, "session.json"), encoding="utf-8") as f: + sess = json.load(f) + for run in sess["runs"]: + if run.get("iif_dev_open_watch_expect") in ("zero", "nonzero"): + self.assertIs(run.get("watcher_active"), True, run["file"]) + # 4c. The root unit-test invocation MUST explicitly set TMPDIR=. + root_unit_execs = [c for c in flat if "su -c" in c and f"./{cap.UNIT}" in c] + self.assertEqual(len(root_unit_execs), 1, root_unit_execs) + self.assertIn(f"TMPDIR={root_exec} ", root_unit_execs[0]) + self.assertIn("unset LD_LIBRARY_PATH", root_unit_execs[0]) + # 5. Session dir cleaned up, and session.json contains zero forbidden device-tmp prefix. + self.assertTrue(any(f"rm -rf -- {test_dir}" in c for c in flat), flat) + with open(os.path.join(out_dir, "session.json"), encoding="utf-8") as f: + sess_text = f.read() + self.assertNotIn(cap.DEVICE_TMP_ROOT + "/", sess_text) + # 6. Tampered binary hash on device aborts BEFORE running the bench. + rc_tamper, out_tamper, calls_tamper, _ = self._run_capture_mocked(tamper_sha_after_n=1) + self.assertEqual(rc_tamper, 1) + self.assertFalse(os.path.exists(os.path.join(out_tamper, "session.json"))) + self.assertFalse(any(f"./{cap.BENCH}" in " ".join(c) for c in calls_tamper)) + + def test_sweep_requires_nnapi_edgetpu_and_kernel_iif(self) -> None: + # Verify capture RUNS explicitly pin --tpu-backend nnapi on smoke and the main L=12 sweep. + by_file = {f: args for f, _u, args, _w, _wa in cap.RUNS} + for fname in ("smoke-L4-T8-d512.json", "bench-L12-T64-d512.json", + "bench-L12-T64-d1024.json", "bench-L12-T64-d2048.json"): + self.assertTrue(rec._has_cli_flag_value(by_file[fname], "--tpu-backend", "nnapi"), fname) + with open(os.path.join(proof_dir, "bench-L12-T64-d512.json"), encoding="utf-8") as f: + orig = json.load(f) + mutations = [ + ("cpu backend", lambda d: d.update({"tpu_backend": "cpu"}), "tpu_backend='nnapi'"), + ("auto requested", lambda d: d.update({"tpu_backend_requested": "auto"}), "tpu_backend_requested='nnapi'"), + ("non-edgetpu device", lambda d: d["nnapi"].update({"device": "nnapi-reference"}), "google-edgetpu"), + ("low feature level", lambda d: d["nnapi"].update({"device_feature_level": 29}), "device_feature_level"), + ("dmabuf shared_mem", lambda d: d["nnapi"].update({"shared_mem": "dmabuf_fd"}), "ahb_blob_gpu_data_buffer"), + ("no bridge_dma", lambda d: d["iif"].update({"bridge_dma_ok": False}), "bridge_dma_ok=true"), + ("zero iif fences", lambda d: next(a for a in d["arms"] if a["arm"] == "r_iif").update({"iif_fences_per_tok": 0.0}), + "iif_fences_per_tok > 0"), + ("unfenced fallback", lambda d: next(a for a in d["arms"] if a["arm"] == "r_iif").update({"nnapi_unfenced_hops_per_tok": 1.0}), + "nnapi_unfenced_hops_per_tok == 0"), + ] + for label, mutate, needle in mutations: + mut = json.loads(json.dumps(orig)) + mut["tpu_backend_requested"] = "nnapi" + mut["nnapi"]["device_feature_level"] = 1000008 + mutate(mut) + rc, _, _, summary = self._run_capture_mocked( + run_stdout_overrides={"bench-L12-T64-d512.json": (json.dumps(mut) + "\n").encode()}, + ) + self.assertEqual(rc, 1, (label, summary)) + self.assertFalse(summary["published"], label) + self.assertTrue(any(needle in e for e in summary.get("validation_errors", [])), + (label, needle, summary.get("validation_errors"))) + + def test_staged_capture_rejects_invalid_proof_outcomes_before_publish(self) -> None: + prev = { + "session.json": b'{"previous": true}\n', + "neg-nobridge-require-iif-L4-T8-d512.json": b'{"old_neg": 1}\n', + "PROOF.md": b"# existing proof\n", + } + # 1. Negative run exits with expected code 1, but reports requirement_met=true -> must NOT publish! + with open(os.path.join(proof_dir, "neg-nobridge-require-iif-L4-T8-d512.json"), encoding="utf-8") as f: + bad_neg = json.load(f) + bad_neg["iif"]["requirement_met"] = True + rc, out_dir, _, summary = self._run_capture_mocked( + prepopulate_out=prev, + run_stdout_overrides={"neg-nobridge-require-iif-L4-T8-d512.json": (json.dumps(bad_neg) + "\n").encode()}, + ) + self.assertEqual(rc, 1) + self.assertFalse(summary["published"]) + self.assertTrue(any("require-iif gate not the failure cause" in e for e in summary.get("validation_errors", [])), summary) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + # 2. IIF watch positive control sees 0 events -> must NOT publish! + rc2, out_dir2, _, summary2 = self._run_capture_mocked( + prepopulate_out=prev, + watch_event_overrides={"iif-probe-only.json": b""}, + ) + self.assertEqual(rc2, 1) + self.assertFalse(summary2["published"]) + self.assertTrue(any("open watch positive control" in e for e in summary2.get("validation_errors", [])), summary2) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir2, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + # 3. Positive run exits 0 but reports pass=false -> must NOT publish! + with open(os.path.join(proof_dir, "smoke-L4-T8-d512.json"), encoding="utf-8") as f: + bad_smoke = json.load(f) + bad_smoke["pass"] = False + rc3, out_dir3, _, summary3 = self._run_capture_mocked( + prepopulate_out=prev, + run_stdout_overrides={"smoke-L4-T8-d512.json": (json.dumps(bad_smoke) + "\n").encode()}, + ) + self.assertEqual(rc3, 1) + self.assertFalse(summary3["published"]) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir3, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + # 4. Sweep passes with iif.requirement_met=true, but host_staged was skipped (isolated staging unavailable) + # -> validate_staged_capture() must reject BEFORE publishing and preserve previous --out! + with open(os.path.join(proof_dir, "bench-L12-T64-d512.json"), encoding="utf-8") as f: + orig_sweep = json.load(f) + skipped_sweep = json.loads(json.dumps(orig_sweep)) + skipped_sweep["arms"][0] = { + "arm": "host_staged", + "ran": False, + "pass": True, + "skip_reason": "isolated_staging_unavailable", + } + rc4, out_dir4, _, summary4 = self._run_capture_mocked( + prepopulate_out=prev, + run_stdout_overrides={"bench-L12-T64-d512.json": (json.dumps(skipped_sweep) + "\n").encode()}, + ) + self.assertEqual(rc4, 1, summary4) + self.assertFalse(summary4["published"]) + self.assertTrue(summary4.get("validation_errors"), summary4) + self.assertTrue(rec.validate_staged_capture(summary4["staging_dir"]), summary4) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir4, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + # 5. Sweep passes with all arms ran, but host_staged VSYS energy is null or 0 (ODPM unavailable) + # -> validate_staged_capture() must reject BEFORE publishing and preserve previous --out! + for bad_vsys in (None, 0.0): + null_vsys_sweep = json.loads(json.dumps(orig_sweep)) + null_vsys_sweep["arms"][0]["j_per_tok_vsys"] = bad_vsys + rc5, out_dir5, _, summary5 = self._run_capture_mocked( + prepopulate_out=prev, + run_stdout_overrides={"bench-L12-T64-d512.json": (json.dumps(null_vsys_sweep) + "\n").encode()}, + ) + self.assertEqual(rc5, 1, (bad_vsys, summary5)) + self.assertFalse(summary5["published"]) + self.assertTrue(any("j_per_tok_vsys" in e or "render failed" in e + for e in summary5.get("validation_errors", [])), summary5) + self.assertTrue(rec.validate_staged_capture(summary5["staging_dir"]), summary5) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir5, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + + def test_device_log_failures_fail_health_capture(self) -> None: + test_dir = posixpath.join(cap.ROOT_EXEC_PARENT, "fs59test") + # Device.text() itself must raise on non-zero exit rather than returning empty text. + dev = cap.Device("FAKE", test_dir) + with mock.patch.object(cap.subprocess, "run", + return_value=subprocess.CompletedProcess(["adb"], 1, b"", b"permission denied")): + with self.assertRaises(RuntimeError): + dev.text("dmesg", "root") + for dmesg_rcs, crash_rcs, date_rc, expect_rm in ( + ((1, 0), (0, 0), 0, False), + ((0, 0), (1, 0), 0, False), + ((0, 0), (0, 0), 1, False), + ((0, 1), (0, 0), 0, True), + ((0, 0), (0, 1), 0, True), + ): + rc, out_dir, calls, _ = self._run_capture_mocked( + dmesg_rcs=dmesg_rcs, crash_rcs=crash_rcs, date_rc=date_rc) + self.assertEqual(rc, 1, (dmesg_rcs, crash_rcs, date_rc)) + self.assertFalse(os.path.exists(os.path.join(out_dir, "session.json"))) + flat = [" ".join(c) for c in calls] + self.assertEqual(any(f"rm -rf -- {test_dir}" in c for c in flat), expect_rm) + + def test_staged_capture_preserves_previous_outputs_until_overall_ok(self) -> None: + prev = { + "session.json": b'{"previous": true}\n', + "smoke-L4-T8-d512.json": b'{"old_smoke": 1}\n', + "unit-test-device.txt": b"old unit transcript\n", + "PROOF.md": b"# existing proof\n", + } + # 1. Failed capture (health gate failure) leaves pre-existing out_dir untouched and retains staging dir. + rc, out_dir, _, summary = self._run_capture_mocked( + dmesg_after_extra=b"[2.0] edgetpu: fault on dma-buf\n", prepopulate_out=prev) + self.assertEqual(rc, 1) + self.assertFalse(summary["published"]) + stage_dir = summary["staging_dir"] + self.assertTrue(stage_dir and os.path.isdir(stage_dir)) + self.assertTrue(os.path.isfile(os.path.join(stage_dir, "session.json"))) + self.assertTrue(os.path.isfile(os.path.join(stage_dir, "smoke-L4-T8-d512.json"))) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + # 2. Mid-session RuntimeError (after runs wrote staged outputs) ALSO leaves out_dir untouched. + rc, out_dir, _, _ = self._run_capture_mocked(dmesg_rcs=(0, 1), prepopulate_out=prev) + self.assertEqual(rc, 1) + for fn, expected_bytes in prev.items(): + with open(os.path.join(out_dir, fn), "rb") as f: + self.assertEqual(f.read(), expected_bytes, fn) + # 3. Successful capture atomically publishes into out_dir, preserves PROOF.md, and cleans staging. + rc, out_dir, _, summary = self._run_capture_mocked(prepopulate_out=prev) + self.assertEqual(rc, 0) + self.assertTrue(summary["published"]) + self.assertIsNone(summary["staging_dir"]) + with open(os.path.join(out_dir, "PROOF.md"), "rb") as f: + self.assertEqual(f.read(), prev["PROOF.md"]) + with open(os.path.join(out_dir, "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertTrue(sess["overall_ok"]) + parent_entries = os.listdir(os.path.dirname(out_dir)) + self.assertFalse(any(".staging-" in n or ".backup-" in n for n in parent_entries), parent_entries) + # 4. --staging-dir inside --out is rejected (exit 2). + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + with self.assertRaises(ValueError): + cap.create_staging_dir(os.path.join(td, "out"), os.path.join(td, "out", "sub")) + + def test_unit_test_exit_codes_checked_in_capture(self) -> None: + # Positive baseline + rc, out_dir, _, summary = self._run_capture_mocked() + self.assertEqual(rc, 0) + self.assertTrue(summary["published"]) + with open(os.path.join(out_dir, "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertTrue(sess["overall_ok"]) + self.assertEqual([u["exit_code"] for u in sess["unit_test_runs"]], [0, 0, 0]) + # Any unit test exiting non-zero must fail capture and record the exit code in retained staging. + rc, out_dir, _, summary = self._run_capture_mocked(unit_outcomes=( + (0, "test_token_loop_riif: all checks passed\n"), + (1, "test_token_loop_riif: 1 failure(s)\n"), + (0, "test_token_loop_riif: all checks passed\n"), + )) + self.assertEqual(rc, 1) + self.assertFalse(os.path.exists(os.path.join(out_dir, "session.json"))) + with open(os.path.join(summary["staging_dir"], "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertFalse(sess["overall_ok"]) + self.assertEqual([u["exit_code"] for u in sess["unit_test_runs"]], [0, 1, 0]) + + def test_health_gate_fails_capture_on_faults_crashes_or_hal_restart(self) -> None: + rc, out_dir, calls, _ = self._run_capture_mocked(hal_pids=("9820 9829",) * 4) + self.assertEqual(rc, 0) + with open(os.path.join(out_dir, "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertEqual(sess["health_gate"], + {"new_kernel_faults": 0, "new_crash_entries": 0, "hal_pids_unchanged": True}) + self.assertEqual(sess["crash_buffer"]["cursor_mode"], "logcat_T") + self.assertEqual(sess["crash_buffer"]["start_timestamp"], "12-03 18:02:00.123") + self.assertEqual(sess["hal_pid_exit_codes"], + {"before": 0, "before_dmabuf_guard": 0, "after_dmabuf_guard": 0, "end": 0}) + flat = [" ".join(c) for c in calls] + self.assertTrue(any("logcat -b crash -T '12-03 18:02:00.123' -d" in c for c in flat), flat) + # Kernel fault fails capture. + rc, _, _, summary = self._run_capture_mocked(dmesg_after_extra=b"[2.0] edgetpu: fault on dma-buf\n") + self.assertEqual(rc, 1) + with open(os.path.join(summary["staging_dir"], "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertGreater(sess["health_gate"]["new_kernel_faults"], 0) + self.assertFalse(sess["overall_ok"]) + # Crash entry detected even when crash buffer rolled over (cursor-based logcat -T, header stripped). + rc, _, _, summary = self._run_capture_mocked( + crash_before_body=b"--------- beginning of crash\n", + crash_after_extra=b"12-03 18:02:05.456 9999 9999 F DEBUG : Fatal signal 11\n") + self.assertEqual(rc, 1) + with open(os.path.join(summary["staging_dir"], "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertEqual(sess["health_gate"]["new_crash_entries"], 1) + self.assertEqual(sess["crash_buffer"]["new_lines"], 1) + self.assertFalse(sess["overall_ok"]) + # HAL restart fails capture. + rc, _, _, summary = self._run_capture_mocked(hal_pids=("111", "111", "111", "222")) + self.assertEqual(rc, 1) + with open(os.path.join(summary["staging_dir"], "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertFalse(sess["health_gate"]["hal_pids_unchanged"]) + self.assertFalse(sess["overall_ok"]) + # Empty HAL PIDs ("" == ""), invalid PIDs ("0", "abc"), or non-zero pidof rc MUST NEVER pass! + for bad_pids, bad_rcs in ( + (("", "", "", ""), (0, 0, 0, 0)), + (("", "", "", ""), (1, 1, 1, 1)), + (("0", "0", "0", "0"), (0, 0, 0, 0)), + (("abc", "abc", "abc", "abc"), (0, 0, 0, 0)), + (("1234", "1234", "1234", "1234"), (0, 0, 1, 0)), + ): + rc, _, _, summary = self._run_capture_mocked(hal_pids=bad_pids, hal_rcs=bad_rcs) + self.assertEqual(rc, 1, (bad_pids, bad_rcs)) + with open(os.path.join(summary["staging_dir"], "session.json"), encoding="utf-8") as f: + sess = json.load(f) + self.assertFalse(sess["health_gate"]["hal_pids_unchanged"], (bad_pids, bad_rcs)) + self.assertFalse(sess["overall_ok"], (bad_pids, bad_rcs)) + + def test_receipt_rejects_invalid_hal_pids_and_non_cursor_crash_buffer(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + pdir = os.path.join(td, "proof") + shutil.copytree(proof_dir, pdir) + sess_p = os.path.join(pdir, "session.json") + with open(sess_p, encoding="utf-8") as f: + orig = json.load(f) + # Ensure empty HAL pids, non-zero HAL exit code, and missing logcat_T cursor are each rejected. + for mutate, needle in ( + (lambda s: s["hal_pids"].update({k: "" for k in rec.HAL_SNAPSHOT_KEYS}), "numeric PID"), + (lambda s: s["hal_pid_exit_codes"].update({"end": 1}), "hal_pid_exit_codes"), + (lambda s: s["crash_buffer"].update({"cursor_mode": "line_count"}), "logcat_T"), + (lambda s: s["crash_buffer"].update({"start_timestamp": "bad-ts"}), "start_timestamp"), + ): + sdoc = json.loads(json.dumps(orig)) + sdoc.setdefault("hal_pid_exit_codes", {k: 0 for k in rec.HAL_SNAPSHOT_KEYS}) + sdoc["crash_buffer"].setdefault("cursor_mode", "logcat_T") + sdoc["crash_buffer"].setdefault("start_timestamp", "12-03 18:02:00.123") + mutate(sdoc) + with open(sess_p, "w", encoding="utf-8") as f: + json.dump(sdoc, f) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_check(pdir), 1, needle) + self.assertIn(needle, err.getvalue()) + + def test_arm64_matrix_verification_checks_cache_distinct_dirs_and_build(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + repo_dir = os.path.join(td, "repo") + ndk_dir = os.path.join(td, "ndk", "27.3.13750724") + os.makedirs(repo_dir) + os.makedirs(ndk_dir) + elf_a64 = b"\x7fELF\x02\x01\x01" + b"\x00" * 11 + (183).to_bytes(2, "little") + + def mk_build(name: str, with_ob: bool, abi: str = "arm64-v8a", bench_tag: bytes = b"A", + elf_hdr: bytes = elf_a64) -> str: + bdir = os.path.join(td, name) + os.makedirs(bdir, exist_ok=True) + lines = [ + f"CMAKE_HOME_DIRECTORY:INTERNAL={repo_dir}", + "CMAKE_SYSTEM_NAME:STRING=Android", + f"ANDROID_ABI:STRING={abi}", + f"ANDROID_NDK:PATH={ndk_dir}", + f"CMAKE_TOOLCHAIN_FILE:FILEPATH={ndk_dir}/build/cmake/android.toolchain.cmake", + ] + if with_ob: + lines.extend([ + f"FREESCHED_OPENBUENOS_DIR:PATH={td}/ob", + f"_FREESCHED_OB_INCLUDE:PATH={td}/ob/include", + f"_FREESCHED_OB_LIB:FILEPATH={td}/ob/libopenbuenos.a", + ]) + with open(os.path.join(bdir, "CMakeCache.txt"), "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + with open(os.path.join(bdir, "volcanic_tpu_token_loop_bench"), "wb") as f: + f.write(elf_hdr + bench_tag) + with open(os.path.join(bdir, "test_token_loop_riif"), "wb") as f: + f.write(elf_hdr + b"unit-" + bench_tag) + return bdir + + ob_dir = mk_build("a64-ob", True, bench_tag=b"with-ob") + noob_dir = mk_build("a64-noob", False, bench_tag=b"without-ob") + with mock.patch.object(rec, "_run", return_value=(0, "ok")): + # 1. Valid distinct dirs with opposite libopenbuenos settings PASS. + rows = rec.verify_arm64_matrix(ob_dir, noob_dir, ndk_dir, repo_dir) + self.assertTrue(all(r.startswith("PASS:") for _, r in rows), rows) + # 2. Passing the same dir for both MUST FAIL. + rows = rec.verify_arm64_matrix(ob_dir, ob_dir, ndk_dir, repo_dir) + self.assertTrue(all(r.startswith("FAIL:") for _, r in rows), rows) + # 3. Swapped dirs (wrong libopenbuenos config in each) MUST FAIL. + rows = rec.verify_arm64_matrix(noob_dir, ob_dir, ndk_dir, repo_dir) + self.assertTrue(all(r.startswith("FAIL:") for _, r in rows), rows) + # 4. Identical bench SHA-256 across with/without MUST FAIL. + same_noob = mk_build("a64-noob-same", False, bench_tag=b"with-ob") + rows = rec.verify_arm64_matrix(ob_dir, same_noob, ndk_dir, repo_dir) + self.assertTrue(all(r.startswith("FAIL:") for _, r in rows), rows) + # 5. Wrong ABI or non-ELF64-AArch64 binary MUST FAIL. + bad_abi = mk_build("a64-x86", False, abi="x86_64", bench_tag=b"x86") + rows = rec.verify_arm64_matrix(ob_dir, bad_abi, ndk_dir, repo_dir) + self.assertTrue(rows[1][1].startswith("FAIL:"), rows) + bad_elf = mk_build("a64-badelf", False, bench_tag=b"notelf", elf_hdr=b"not-an-elf-binary-xx") + rows = rec.verify_arm64_matrix(ob_dir, bad_elf, ndk_dir, repo_dir) + self.assertTrue(rows[1][1].startswith("FAIL:"), rows) + # 6. Failing cmake --build MUST FAIL. + with mock.patch.object(rec, "_run", return_value=(1, "compile error")): + rows = rec.verify_arm64_matrix(ob_dir, noob_dir, ndk_dir, repo_dir) + self.assertTrue(all(r.startswith("FAIL:") for _, r in rows), rows) + + def test_receipt_archived_unexpected_exit_and_manifest_checks(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + pdir = os.path.join(td, "proof") + shutil.copytree(proof_dir, pdir) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_check(pdir), 0, err.getvalue()) + # Locate archived unexpected-exit raw file (successful runs in that session are already manifest-only). + arch_dir = os.path.join(pdir, "observed-failures", "session3-r_iif-d1024") + raw_fail = os.path.join(arch_dir, "bench-L12-T64-d1024.json") + with open(raw_fail, "rb") as f: + orig_bytes = f.read() + # 1. Missing raw file for recorded unexpected exit must fail BOTH write and check. + os.remove(raw_fail) + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(rec.cmd_write(pdir), 1) + self.assertEqual(rec.cmd_check(pdir), 1) + with open(os.path.join(pdir, "receipt.json"), encoding="utf-8") as f: + self.assertTrue(len(json.load(f)["observed_failures"]) >= 1) + # 2. Present raw file with mismatched SHA-256 must fail BOTH write and check. + with open(raw_fail, "wb") as f: + f.write(orig_bytes + b"\n") + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(rec.cmd_write(pdir), 1) + self.assertEqual(rec.cmd_check(pdir), 1) + # Restore valid archived raw file and verify check passes again. + with open(raw_fail, "wb") as f: + f.write(orig_bytes) + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(rec.cmd_check(pdir), 0) + # 3. Receipt check also rejects failed unit_test_runs or failed log snapshot reads in session.json. + sess_p = os.path.join(pdir, "session.json") + with open(sess_p, encoding="utf-8") as f: + orig_sess = f.read() + sdoc = json.loads(orig_sess) + sdoc["unit_test_runs"][0]["exit_code"] = 1 + with open(sess_p, "w", encoding="utf-8") as f: + json.dump(sdoc, f) + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(rec.cmd_check(pdir), 1) + sdoc = json.loads(orig_sess) + sdoc["kernel_log"]["after_exit_code"] = 1 + with open(sess_p, "w", encoding="utf-8") as f: + json.dump(sdoc, f) + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(rec.cmd_check(pdir), 1) + + def test_write_validates_before_replacing_proof_files(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + pdir = os.path.join(td, "proof") + shutil.copytree(proof_dir, pdir) + rp = os.path.join(pdir, "receipt.json") + pp = os.path.join(pdir, "PROOF.md") + with open(rp, "rb") as f: + receipt_before = f.read() + with open(pp, "rb") as f: + proof_before = f.read() + sess_p = os.path.join(pdir, "session.json") + with open(sess_p, encoding="utf-8") as f: + sdoc = json.load(f) + sdoc["kernel_log"]["subsystem_fault_lines"] = ["edgetpu: fault"] + sdoc["overall_ok"] = True + with open(sess_p, "w", encoding="utf-8") as f: + json.dump(sdoc, f) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_write(pdir), 1) + self.assertIn("new_kernel_faults", err.getvalue()) + with open(rp, "rb") as f: + self.assertEqual(f.read(), receipt_before) + with open(pp, "rb") as f: + self.assertEqual(f.read(), proof_before) + self.assertFalse(any(n.startswith(".receipt.json.") or n.startswith(".PROOF.md.") + for n in os.listdir(pdir))) + + def test_negative_runs_must_fail_for_the_structured_reason(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + pdir = os.path.join(td, "proof") + shutil.copytree(proof_dir, pdir) + rp = os.path.join(pdir, "receipt.json") + with open(rp, "rb") as f: + receipt_before = f.read() + raw_name = "neg-nobridge-require-iif-L4-T8-d512.json" + raw_p = os.path.join(pdir, raw_name) + with open(raw_p, encoding="utf-8") as f: + doc = json.load(f) + doc["iif"]["requirement_met"] = True + raw = (json.dumps(doc) + "\n").encode() + with open(raw_p, "wb") as f: + f.write(raw) + with open(os.path.join(pdir, "session.json"), encoding="utf-8") as f: + sdoc = json.load(f) + for run in sdoc["runs"]: + if run["file"] == raw_name: + run["stdout_sha256"] = hashlib.sha256(raw).hexdigest() + with open(os.path.join(pdir, "session.json"), "w", encoding="utf-8") as f: + json.dump(sdoc, f) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_write(pdir), 1) + self.assertEqual(rec.cmd_check(pdir), 1) + self.assertIn("require-iif gate not the failure cause", err.getvalue()) + with open(rp, "rb") as f: + self.assertEqual(f.read(), receipt_before) + + def test_ndk_cxx_follows_the_host(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + ndk = os.path.join(td, "ndk") + for host in ("darwin-x86_64", "darwin-arm64", "linux-x86_64"): + bindir = os.path.join(ndk, "toolchains", "llvm", "prebuilt", host, "bin") + os.makedirs(bindir) + with open(os.path.join(bindir, "clang++"), "w", encoding="utf-8") as f: + f.write("#!/bin/sh\n") + self.assertTrue(rec.resolve_ndk_cxx(ndk, platform_name="darwin", machine="arm64").endswith( + "darwin-arm64/bin/clang++")) + self.assertTrue(rec.resolve_ndk_cxx(ndk, platform_name="darwin", machine="x86_64").endswith( + "darwin-x86_64/bin/clang++")) + self.assertTrue(rec.resolve_ndk_cxx(ndk, platform_name="linux", machine="x86_64").endswith( + "linux-x86_64/bin/clang++")) + only = os.path.join(td, "ndk-x86") + bindir = os.path.join(only, "toolchains", "llvm", "prebuilt", "linux-x86_64", "bin") + os.makedirs(bindir) + with open(os.path.join(bindir, "clang++"), "w", encoding="utf-8") as f: + f.write("#!/bin/sh\n") + self.assertTrue(rec.resolve_ndk_cxx(only, platform_name="darwin", machine="arm64").endswith( + "linux-x86_64/bin/clang++")) + custom = os.path.join(td, "clang++") + with open(custom, "w", encoding="utf-8") as f: + f.write("#!/bin/sh\n") + self.assertEqual(rec.resolve_ndk_cxx(ndk, override=custom, platform_name="linux", machine="x86_64"), + custom) + with self.assertRaises(RuntimeError): + rec.resolve_ndk_cxx(os.path.join(td, "missing-ndk"), platform_name="linux", machine="x86_64") + + def test_archived_failure_without_json_is_preserved(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + pdir = os.path.join(td, "proof") + shutil.copytree(proof_dir, pdir) + arch = os.path.join(pdir, "observed-failures", "session-crash-nojson") + os.makedirs(arch) + empty_bytes = b"" + partial_bytes = b'{"pass":false,"arms":[' + empty_sha = hashlib.sha256(empty_bytes).hexdigest() + partial_sha = hashlib.sha256(partial_bytes).hexdigest() + with open(os.path.join(arch, "bench-L12-T64-d512.json"), "wb") as f: + f.write(empty_bytes) + with open(os.path.join(arch, "bench-L12-T64-d1024.json"), "wb") as f: + f.write(partial_bytes) + bsha = "a" * 64 + sess = { + "started_utc": "2026-12-03T10:00:00Z", + "binary": { + "bench_sha256_host": bsha, + "bench_sha256_device": bsha, + "bench_sha256_device_at_end": bsha, + }, + "runs": [ + { + "file": "bench-L12-T64-d512.json", + "uid": "root", + "args": ["--live", "--d", "512", "--json"], + "exit_code": -11, + "expected_exit_code": 0, + "binary_sha256": bsha, + "stdout_sha256": empty_sha, + }, + { + "file": "bench-L12-T64-d1024.json", + "uid": "root", + "args": ["--live", "--d", "1024", "--json"], + "exit_code": 139, + "expected_exit_code": 0, + "binary_sha256": bsha, + "stdout_sha256": partial_sha, + }, + ], + } + with open(os.path.join(arch, "session.json"), "w", encoding="utf-8") as f: + json.dump(sess, f) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_write(pdir), 0, err.getvalue()) + self.assertEqual(rec.cmd_check(pdir), 0, err.getvalue()) + with open(os.path.join(pdir, "receipt.json"), encoding="utf-8") as f: + receipt = json.load(f) + crashes = [x for x in receipt["observed_failures"] if x["dir"] == "observed-failures/session-crash-nojson"] + self.assertEqual(len(crashes), 2, crashes) + by_file = {x["file"]: x for x in crashes} + self.assertIs(by_file["bench-L12-T64-d512.json"]["json_parsed"], False) + self.assertEqual(by_file["bench-L12-T64-d512.json"]["exit_code"], -11) + self.assertEqual(by_file["bench-L12-T64-d512.json"]["stdout_bytes"], 0) + self.assertTrue(by_file["bench-L12-T64-d512.json"]["json_parse_error"]) + self.assertIs(by_file["bench-L12-T64-d1024.json"]["json_parsed"], False) + self.assertEqual(by_file["bench-L12-T64-d1024.json"]["exit_code"], 139) + self.assertEqual(by_file["bench-L12-T64-d1024.json"]["stdout_bytes"], len(partial_bytes)) + self.assertTrue(by_file["bench-L12-T64-d1024.json"]["json_parse_error"]) + # Tampering with the raw non-JSON crash file must still fail SHA-256 verification. + with open(os.path.join(arch, "bench-L12-T64-d512.json"), "wb") as f: + f.write(b"tampered") + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(rec.cmd_check(pdir), 1) + + def test_asan_ubsan_verification_rejects_uninstrumented_builds(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + repo_dir = os.path.join(td, "repo") + os.makedirs(repo_dir) + + def mk_build(name: str, cxx_flags: str, linker_flags: str = "", create_bins: bool = True, + flags_make_cxx: str | None = None) -> str: + bdir = os.path.join(td, name) + os.makedirs(bdir, exist_ok=True) + lines = [ + f"CMAKE_HOME_DIRECTORY:INTERNAL={repo_dir}", + "CMAKE_BUILD_TYPE:STRING=Debug", + f"CMAKE_CXX_FLAGS:STRING={cxx_flags}", + f"CMAKE_C_FLAGS:STRING={cxx_flags}", + f"CMAKE_EXE_LINKER_FLAGS:STRING={linker_flags}", + ] + with open(os.path.join(bdir, "CMakeCache.txt"), "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + if create_bins: + for tgt in ("volcanic_tpu_token_loop_bench", "test_token_loop_riif"): + with open(os.path.join(bdir, tgt), "wb") as f: + f.write(b"fake-bin") + if flags_make_cxx is not None: + fdir = os.path.join(bdir, "CMakeFiles", "volcanic_tpu_token_loop_bench.dir") + os.makedirs(fdir, exist_ok=True) + with open(os.path.join(fdir, "flags.make"), "w", encoding="utf-8") as f: + f.write(f"CXX_FLAGS = {flags_make_cxx}\n") + return bdir + + host_dir = mk_build("host", "-O3") + uninst_dir = mk_build("uninst", "-O2") + linker_only_dir = mk_build("linker-only", "-O2", linker_flags="-fsanitize=address,undefined") + asan_only_dir = mk_build("asan-only", "-fsanitize=address") + negated_dir = mk_build("negated", "-fsanitize=address,undefined -fno-sanitize=undefined") + bad_fmake_dir = mk_build("bad-fmake", "-fsanitize=address,undefined", flags_make_cxx="-O2 -g") + full_dir = mk_build("asan-ubsan", "-fsanitize=address,undefined", + flags_make_cxx="-g -fsanitize=address,undefined") + + # 1. Passing --asan-build == --host-build must fail. + ok, msg = rec.verify_asan_ubsan_build_dir(host_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("same directory", msg) + # 2. Uninstrumented build dir must fail on CMakeCache.txt. + ok, msg = rec.verify_asan_ubsan_build_dir(uninst_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("missing CXX compile -fsanitize flags", msg) + # 2b. Linker-only sanitizer flags (without compile flags) MUST be rejected! + ok, msg = rec.verify_asan_ubsan_build_dir(linker_only_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("missing CXX compile -fsanitize flags", msg) + # 3. ASan-only or negated compile flags must fail. + ok, msg = rec.verify_asan_ubsan_build_dir(asan_only_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("undefined", msg) + ok, msg = rec.verify_asan_ubsan_build_dir(negated_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("undefined", msg) + # 3b. flags.make without compile sanitizer flags must fail even if CMakeCache has them. + ok, msg = rec.verify_asan_ubsan_build_dir(bad_fmake_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("flags.make", msg) + # 4. Cache claims ASan+UBSan, but binary symbols lack instrumentation -> must fail. + with mock.patch.object(rec.shutil, "which", side_effect=lambda x: "/usr/bin/nm" if x == "nm" else None): + with mock.patch.object(rec, "_run", return_value=(0, "U _malloc\nU _free\n")): + ok, msg = rec.verify_asan_ubsan_build_dir(full_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("lacks sanitizer instrumentation", msg) + # 4b. Linked runtime names / bare __asan_init WITHOUT __asan_report_ + __ubsan_handle_ MUST FAIL! + with mock.patch.object(rec, "_run", + return_value=(0, "U ___asan_init\nlibclang_rt.asan\nlibclang_rt.ubsan\n")): + ok, msg = rec.verify_asan_ubsan_build_dir(full_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("asan_report=False", msg) + # 5. Binary has ASan report only (missing UBSan handler) -> must fail. + with mock.patch.object(rec, "_run", return_value=(0, "U ___asan_report_load4\n")): + ok, msg = rec.verify_asan_ubsan_build_dir(full_dir, host_dir, repo_dir) + self.assertFalse(ok) + self.assertIn("ubsan_handle=False", msg) + # 6. Binary has BOTH __asan_report_ and __ubsan_handle_ call symbols -> must PASS. + with mock.patch.object(rec, "_run", + return_value=(0, "U ___asan_report_load4\nU ___ubsan_handle_add_overflow\n")): + ok, msg = rec.verify_asan_ubsan_build_dir(full_dir, host_dir, repo_dir) + self.assertTrue(ok, msg) + calls: list[list[str]] = [] + + def _record(cmd, cwd=None, env=None): + calls.append(list(cmd)) + if cmd and cmd[0] == "cmake": + return 0, "built" + return 0, "U __asan_report_load4\nU __ubsan_handle_add_overflow\n" + + with mock.patch.object(rec, "_run", side_effect=_record): + ok, msg = rec.verify_asan_ubsan_build_dir(full_dir, host_dir, repo_dir) + self.assertTrue(ok, msg) + build_i = next(i for i, c in enumerate(calls) if c[:2] == ["cmake", "--build"]) + sym_i = next(i for i, c in enumerate(calls) if c and c[0] == "nm") + self.assertLess(build_i, sym_i) + + def test_validate_capture_rejects_mismatched_d_model_and_dead_watcher(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + pdir = os.path.join(td, "proof") + shutil.copytree(proof_dir, pdir) + raw_p = os.path.join(pdir, "bench-L12-T64-d512.json") + with open(raw_p, encoding="utf-8") as f: + doc = json.load(f) + doc["d_model"] = 256 + with open(raw_p, "w", encoding="utf-8") as f: + json.dump(doc, f) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_check(pdir), 1) + self.assertIn("reported d_model=256", err.getvalue()) + + shutil.rmtree(pdir) + shutil.copytree(proof_dir, pdir) + sess_p = os.path.join(pdir, "session.json") + with open(sess_p, encoding="utf-8") as f: + sess = json.load(f) + for run in sess["runs"]: + if run.get("iif_dev_open_watch_expect") in ("zero", "nonzero"): + run["watcher_active"] = run["file"] != "mock-root-L4-T8-d512.json" + with open(sess_p, "w", encoding="utf-8") as f: + json.dump(sess, f) + err = io.StringIO() + with redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(rec.cmd_check(pdir), 1) + self.assertIn("mock-root-L4-T8-d512.json: watcher_active must be true", err.getvalue()) + + def test_host_verify_rebuilds_release_tree_before_ctest(self) -> None: + td = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, td, True) + repo = os.path.dirname(os.path.dirname(os.path.abspath(rec.__file__))) + host = os.path.join(td, "host") + os.makedirs(host) + with open(os.path.join(host, "CMakeCache.txt"), "w", encoding="utf-8") as f: + f.write(f"CMAKE_HOME_DIRECTORY:INTERNAL={repo}\nCMAKE_BUILD_TYPE:STRING=Debug\n") + ok, msg = rec.prepare_host_build(host, repo) + self.assertFalse(ok) + self.assertIn("expected 'Release'", msg) + with open(os.path.join(host, "CMakeCache.txt"), "w", encoding="utf-8") as f: + f.write("CMAKE_HOME_DIRECTORY:INTERNAL=/not/this/repo\nCMAKE_BUILD_TYPE:STRING=Release\n") + ok, msg = rec.prepare_host_build(host, repo) + self.assertFalse(ok) + self.assertIn("CMAKE_HOME_DIRECTORY", msg) + with open(os.path.join(host, "CMakeCache.txt"), "w", encoding="utf-8") as f: + f.write(f"CMAKE_HOME_DIRECTORY:INTERNAL={repo}\nCMAKE_BUILD_TYPE:STRING=Release\n") + calls: list[list[str]] = [] + + def _record(cmd, cwd=None, env=None): + calls.append(list(cmd)) + if cmd and cmd[0] == "ctest": + return 0, "100% tests passed out of 1\n" + return 0, "built" + + proof = os.path.join(td, "proof") + os.makedirs(proof) + ns = rec.argparse.Namespace(host_build=host, asan_build=None, a64_ob=os.path.join(td, "missing-ob"), + a64_noob=os.path.join(td, "missing-noob"), ndk=os.path.join(td, "missing-ndk"), + ob_include=os.path.join(td, "ob"), ndk_cxx=None, proof_dir=proof) + with mock.patch.object(rec, "_run", side_effect=_record): + self.assertEqual(rec.cmd_host_verify(ns), 1) + build_i = next(i for i, c in enumerate(calls) if c[:2] == ["cmake", "--build"] and c[2] == host) + ctest_i = next(i for i, c in enumerate(calls) if c and c[0] == "ctest" and "-E" in c) + self.assertLess(build_i, ctest_i) + + suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestTokenLoopScripts) + res = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) + return 0 if res.wasSuccessful() else 1 + + +def main(argv: list[str]) -> int: + emu, argv = _split_emulator(argv) + if len(argv) >= 3 and argv[1] == "scripts": + return _check_scripts(argv[2]) + if len(argv) < 3 or argv[1] not in ("nonfinite", "escape", "probe", "bench", "recover", "mockiif", "badargs"): + print(__doc__, file=sys.stderr) + return 2 + mode, exe = argv[1], argv[2] + if mode == "nonfinite": + proc = subprocess.run([*emu, exe, "--emit-nonfinite-json"], capture_output=True, text=True, check=False) + if proc.returncode != 0: + print(f"exit code {proc.returncode}", file=sys.stderr) + return 1 + doc = _load(proc.stdout) + assert doc["pass"] is False, doc + for key in ("max_abs_err", "neg_inf", "cross_arm_max_abs_diff", "ms_per_tok_p50", "j_per_tok_vsys"): + assert doc[key] is None, (key, doc[key]) + assert doc["cos"] == 0.0 and doc["tok_per_s"] == 12.5, doc + print("nonfinite diagnostics: valid JSON, inf/nan -> null") + return 0 + if mode == "escape": + proc = subprocess.run([*emu, exe, "--emit-hostile-probe-json"], capture_output=True, text=True, check=False) + if proc.returncode != 0: + print(f"exit code {proc.returncode}", file=sys.stderr) + return 1 + doc = _load(proc.stdout) + assert doc["dev"] == HOSTILE_IIF_DEV + "\n\x01\x1f", doc["dev"] + assert doc["reason"] == 'say "hi"\\', doc["reason"] + print("hostile IIF probe JSON: valid, dev and reason round-trip") + return 0 + if mode == "probe": + proc = subprocess.run([*emu, exe, "--iif-probe-only", "--iif-dev", HOSTILE_IIF_DEV], capture_output=True, + text=True, check=False) + if proc.returncode != 0: + print(f"exit code {proc.returncode}\n{proc.stdout}\n{proc.stderr}", file=sys.stderr) + return 1 + doc = _load(proc.stdout) + assert doc["dev"] == HOSTILE_IIF_DEV, doc["dev"] + assert doc["usable"] is False and doc["abi"] == "google-iif-uapi", doc + print("--iif-probe-only with a hostile --iif-dev: valid JSON, dev round-trips") + return 0 + if mode == "recover": + return _check_recover(emu, exe) + if mode == "mockiif": + return _check_mock_iif(emu, exe) + if mode == "badargs": + return _check_badargs(emu, exe) + proc = subprocess.run([*emu, exe, *argv[3:]], capture_output=True, text=True, check=False) + if proc.returncode != 0: + print(f"exit code {proc.returncode}\n{proc.stdout}\n{proc.stderr}", file=sys.stderr) + return 1 + doc = _load(proc.stdout) + assert doc["pass"] is True, "top-level pass must be true" + print(f"bench JSON valid; top-level pass={doc['pass']}, arms={[a['arm'] for a in doc['arms']]}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tools/volcanic_nnapi_edgetpu.h b/tools/volcanic_nnapi_edgetpu.h new file mode 100644 index 0000000..3c6fa7c --- /dev/null +++ b/tools/volcanic_nnapi_edgetpu.h @@ -0,0 +1,808 @@ +/* + * volcanic_nnapi_edgetpu - Clean-room NNAPI accelerator stage for the + * multi-layer GPU<->EdgeTPU token decode loop (tools/volcanic_tpu_token_loop_bench.cpp). + * + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Runtime dlopen(libneuralnetworks.so / libandroid.so / libnativewindow.so) + * only; nothing vendor-specific is linked or bundled. Per transformer layer it + * compiles one TENSOR_QUANT8_ASYMM NHWC 1x1 CONV_2D (the same lowering as + * src/fs_android_ahb_nnapi.cpp) pinned to a single NNAPI ACCELERATOR device + * (google-edgetpu preferred via fs_ahb_classify_npu_device) and runs it: + * - host-staged : ANeuralNetworksExecution_setInput/setOutput host pointers + * + synchronous ANeuralNetworksExecution_compute; + * - zero-copy : ANeuralNetworksMemory over the shared buffer + * (AHardwareBuffer BLOB GPU_DATA_BUFFER, or the DMA-BUF fd) + * + ANeuralNetworksExecution_startComputeWithDependencies, + * with an optional ANeuralNetworksEvent_createFromSyncFenceFd + * dependency and an output sync fence fd + * (ANeuralNetworksEvent_getSyncFenceFd). + * Off Android every entry point reports unavailable. + */ +#ifndef FREESCHED_VOLCANIC_NNAPI_EDGETPU_H_ +#define FREESCHED_VOLCANIC_NNAPI_EDGETPU_H_ + +#include "fs_android_ahb_nnapi.h" +#include "volcanic_token_loop_util.h" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__ANDROID__) +#include +#include +#include +#endif + +namespace fs_tokloop { + +/* Outstanding NNAPI objects of one hop; released only after completion is observed. */ +struct NnInflight { + void* execution = nullptr; /* owned only when !reusable */ + void* dep_event = nullptr; + void* out_event = nullptr; + double unfenced_wait_us = 0.0; /* ANeuralNetworksEvent_wait inside start() when the driver lacks fenced execution */ + double dep_event_create_us = 0.0; /* ANeuralNetworksEvent_createFromSyncFenceFd, outside the submission timer */ +}; + +/* + * Fenced DMA-BUF policy. On Tensor G6 the shared google-edgetpu NNAPI HAL + * crashed (and was restarted by init) on the FIRST + * ANeuralNetworksExecution_startComputeWithDependencies whose operands were + * ANeuralNetworksMemory_createFromFd(dmabuf_fd) memories. Retiring pool slots + * afterwards cannot undo a crash of a system-wide service, so the combination + * EdgeTPU device x dmabuf_fd memory x fenced execution is refused BEFORE any + * dispatch, unless the operator explicitly opts into the + * --allow-edgetpu-dmabuf-fenced-probe debug probe. + */ +inline bool nnapi_device_is_edgetpu(const char* name) { + if (!name) return false; + std::string low(name); + for (char& ch : low) ch = static_cast(std::tolower(static_cast(ch))); + return low.find("edgetpu") != std::string::npos; +} + +#define FS_NN_FENCED_DMABUF_BLOCKED "nnapi_fenced_dmabuf_unavailable_on_edgetpu" +#define FS_NN_FENCED_FEATURE_LEVEL_TOO_LOW "nnapi_fenced_feature_level_below_30" +#define FS_NN_FENCED_NON_ACCELERATOR "nnapi_fenced_non_accelerator_device" + +/* + * Android NNAPI native fenced execution (IDevice::executeFenced) requires + * ANEURALNETWORKS_FEATURE_LEVEL_4 (30, Android 11 / NNAPI HAL 1.3+) on a + * non-CPU accelerator. On devices below feature level 30, + * ANeuralNetworksExecution_startComputeWithDependencies() falls back to an + * unbounded synchronous sync_wait() on incoming dependency fences, which would + * bypass our bounded r_iif timeout. Refuse fenced dispatch whenever feature + * level is unavailable (< 0) or < 30, or when the device is not an accelerator. + */ +static constexpr int64_t kNnapiFeatureLevel4 = 30; +static constexpr int32_t kNnapiDeviceTypeCpu = 2; +static constexpr int32_t kNnapiDeviceTypeAccelerator = 4; + +inline bool nnapi_device_supports_native_fenced(int32_t device_type, int64_t feature_level) { + return device_type == kNnapiDeviceTypeAccelerator && feature_level >= kNnapiFeatureLevel4; +} + +inline const char* nnapi_fenced_feature_level_block_reason(int32_t device_type, int64_t feature_level) { + if (device_type != kNnapiDeviceTypeAccelerator) return FS_NN_FENCED_NON_ACCELERATOR; + if (feature_level < kNnapiFeatureLevel4) return FS_NN_FENCED_FEATURE_LEVEL_TOO_LOW; + return nullptr; +} + +/* nullptr when fenced execution may be dispatched; otherwise the stable skip/refusal reason. */ +inline const char* nnapi_fenced_dmabuf_block_reason(const char* device, bool dmabuf_mem, bool allow_edgetpu_probe) { + if (!dmabuf_mem || allow_edgetpu_probe || !nnapi_device_is_edgetpu(device)) return nullptr; + return FS_NN_FENCED_DMABUF_BLOCKED; +} + +/* JSON label of the policy for a (device, memory, flag) combination. */ +inline const char* nnapi_fenced_dmabuf_policy(const char* device, bool dmabuf_mem, bool allow_edgetpu_probe) { + if (!dmabuf_mem) return "not_applicable_ahb"; + if (!nnapi_device_is_edgetpu(device)) return "allowed_non_edgetpu"; + return allow_edgetpu_probe ? "allowed_edgetpu_debug_probe" : "blocked_edgetpu_before_dispatch"; +} + +class NnEdgeTpu { + public: + NnEdgeTpu() = default; + ~NnEdgeTpu() { + if (!abandoned_) shutdown(); + } + NnEdgeTpu(const NnEdgeTpu&) = delete; + NnEdgeTpu& operator=(const NnEdgeTpu&) = delete; + + /* + * Marks in-flight NNAPI work as unproven (fence timeout or unreleased queue + * gate). Preserves every execution, compilation, model, memory, and event + * through process exit so freeing a compilation cannot race an in-flight + * reusable execution. + */ + void abandon_in_flight() { abandoned_ = true; } + bool abandoned() const { return abandoned_; } + + bool ready() const { return ready_; } + const char* device_name() const { return dev_name_.c_str(); } + int32_t device_type() const { return dev_type_; } + int64_t device_feature_level() const { return dev_feature_level_; } + bool reusable() const { return reusable_; } + bool fenced_api() const { return fenced_api_; } + const char* fenced_feature_level_block_reason() const { + return nnapi_fenced_feature_level_block_reason(dev_type_, dev_feature_level_); + } + /* + * Records the shared-tensor memory kind before any fenced dispatch. With + * dmabuf_fd memory on an EdgeTPU device, start() refuses every hop before + * calling into NNAPI unless allow_edgetpu_probe is set. + */ + void set_fenced_memory(bool dmabuf_mem, bool allow_edgetpu_probe) { + dmabuf_mem_ = dmabuf_mem; + allow_edgetpu_dmabuf_probe_ = allow_edgetpu_probe; + } + const char* fenced_block_reason() const { + return nnapi_fenced_dmabuf_block_reason(dev_name_.c_str(), dmabuf_mem_, allow_edgetpu_dmabuf_probe_); + } + const char* fenced_policy() const { + return nnapi_fenced_dmabuf_policy(dev_name_.c_str(), dmabuf_mem_, allow_edgetpu_dmabuf_probe_); + } + uint64_t exec_start_calls() const { return exec_start_calls_; } + uint64_t fenced_refusals() const { return fenced_refusals_; } + + /* + * Zero-copy fenced start of layer l. dep_fd (borrowed, may be -1) becomes an + * in-kernel dependency via ANeuralNetworksEvent_createFromSyncFenceFd. + * *out_done_fd receives an owned completion sync fence fd, or -1 when the + * driver completed the execution before returning (unfenced fallback). + * *block_us reports the wall time spent inside the + * ANeuralNetworksExecution_startComputeWithDependencies call only (identical + * interval with or without a dependency); dependency-event creation is + * reported separately in inf->dep_event_create_us. + */ + bool start(uint32_t l, int dep_fd, int* out_done_fd, NnInflight* inf, double* block_us, bool* unfenced, + std::string* err) { + *out_done_fd = -1; + *unfenced = false; + *block_us = 0.0; + *inf = NnInflight{}; + if (abandoned_) { + *err = "NNAPI abandoned after unproven in-flight work"; + return false; + } + /* Refused before ANY NNAPI call (no execution, no event, no dispatch). */ + if (const char* why = fenced_block_reason()) { + ++fenced_refusals_; + *err = std::string(why) + ": fenced execution with dmabuf_fd memory on " + dev_name_ + + " is refused before dispatch (it crashed the shared EdgeTPU HAL); use AHB memory or " + "--allow-edgetpu-dmabuf-fenced-probe"; + return false; + } + if (const char* why = fenced_feature_level_block_reason()) { + *err = std::string(why) + ": NNAPI device " + dev_name_ + " (type=" + std::to_string(dev_type_) + + ", feature_level=" + std::to_string(dev_feature_level_) + + ") lacks native fenced execution (requires ACCELERATOR and feature_level >= 30)"; + return false; + } + if (!fenced_api_) { +#if defined(__ANDROID__) + *err = "NNAPI fenced execution API unavailable"; +#else + *err = "NNAPI requires Android"; +#endif + return false; + } + void* ex = nullptr; + if (!acquire_exec(l, &ex, inf)) { + *err = "ANeuralNetworksExecution(zero-copy) setup failed"; + return false; + } + const void* deps[1] = {nullptr}; + uint32_t nd = 0u; + if (dep_fd >= 0) { + const auto td = std::chrono::steady_clock::now(); + const int erc = event_from_fd_(dep_fd, &inf->dep_event); + const double dep_us = us_between(td, std::chrono::steady_clock::now()); + if (erc != kNoError || !inf->dep_event) { + *err = "ANeuralNetworksEvent_createFromSyncFenceFd failed"; + release(inf); + return false; + } + inf->dep_event_create_us = dep_us; + deps[0] = inf->dep_event; + nd = 1u; + } + /* Timer brackets exactly the submission call, so every arm reports the same interval. */ + ++exec_start_calls_; + const auto t0 = std::chrono::steady_clock::now(); + const int rc = exec_start_deps_(ex, nd ? deps : nullptr, nd, 0u, &inf->out_event); + *block_us = us_between(t0, std::chrono::steady_clock::now()); + if (rc != kNoError || !inf->out_event) { + *err = "ANeuralNetworksExecution_startComputeWithDependencies failed (rc=" + std::to_string(rc) + ")"; + release(inf); + return false; + } + int fd = -1; + if (event_get_fd_(inf->out_event, &fd) == kNoError && fd >= 0) { + *out_done_fd = fd; + } else { + /* Driver without fenced execution: the runtime finished the work synchronously. */ + *unfenced = true; + const auto tw = std::chrono::steady_clock::now(); + const int wrc = event_wait_ ? event_wait_(inf->out_event) : kNoError; + inf->unfenced_wait_us = us_between(tw, std::chrono::steady_clock::now()); + if (wrc != kNoError) { + *err = "ANeuralNetworksEvent_wait reported an execution error"; + release(inf); + return false; + } + } + return true; + } + + /* Frees hop objects; only call once the hop's completion has been observed. */ + void release(NnInflight* inf) { + if (abandoned_) { + *inf = NnInflight{}; + return; + } + if (inf->out_event && event_free_) event_free_(inf->out_event); + if (inf->dep_event && event_free_) event_free_(inf->dep_event); + if (inf->execution && exec_free_) exec_free_(inf->execution); + *inf = NnInflight{}; + } + + /* Blocks until a started hop finished (error-path drain before release()). */ + void wait_done(NnInflight* inf) { + if (inf->out_event && event_wait_) (void)event_wait_(inf->out_event); + } + + /* + * Execution status of a hop whose completion fence was already observed. A + * sync fence can signal while the NNAPI completion callback reports a failed + * execution; ANeuralNetworksEvent_free() would silently drop that status, so + * every fenced hop must pass this check before release(). + */ + bool check_done(NnInflight* inf, std::string* err) { + if (!inf->out_event) return true; + if (!event_wait_) { + *err = "ANeuralNetworksEvent_wait unavailable: cannot verify NNAPI execution status"; + return false; + } + const int rc = event_wait_(inf->out_event); + if (rc != kNoError) { + *err = "ANeuralNetworksEvent_wait reported an execution error (rc=" + std::to_string(rc) + ")"; + return false; + } + return true; + } + + static double us_between(std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) { + return static_cast(std::chrono::duration_cast(b - a).count()) / 1e3; + } + + +#if defined(__ANDROID__) + /* want: "auto" (best ACCELERATOR, google-edgetpu first) or a device-name substring. */ + bool init(const char* want, std::string* err) { + lib_ = dlopen("libneuralnetworks.so", RTLD_NOW | RTLD_LOCAL); + if (!lib_) { + *err = "dlopen(libneuralnetworks.so) failed"; + return false; + } +#define FS_NN_SYM(field, name) field = reinterpret_cast(dlsym(lib_, name)) + FS_NN_SYM(get_device_count_, "ANeuralNetworks_getDeviceCount"); + FS_NN_SYM(get_device_, "ANeuralNetworks_getDevice"); + FS_NN_SYM(device_get_name_, "ANeuralNetworksDevice_getName"); + FS_NN_SYM(device_get_type_, "ANeuralNetworksDevice_getType"); + FS_NN_SYM(device_get_feature_level_, "ANeuralNetworksDevice_getFeatureLevel"); + FS_NN_SYM(mem_from_fd_, "ANeuralNetworksMemory_createFromFd"); + FS_NN_SYM(mem_from_ahb_, "ANeuralNetworksMemory_createFromAHardwareBuffer"); + FS_NN_SYM(mem_free_, "ANeuralNetworksMemory_free"); + FS_NN_SYM(model_create_, "ANeuralNetworksModel_create"); + FS_NN_SYM(model_free_, "ANeuralNetworksModel_free"); + FS_NN_SYM(model_add_operand_, "ANeuralNetworksModel_addOperand"); + FS_NN_SYM(model_set_val_, "ANeuralNetworksModel_setOperandValue"); + FS_NN_SYM(model_add_op_, "ANeuralNetworksModel_addOperation"); + FS_NN_SYM(model_id_io_, "ANeuralNetworksModel_identifyInputsAndOutputs"); + FS_NN_SYM(model_finish_, "ANeuralNetworksModel_finish"); + FS_NN_SYM(comp_create_for_devs_, "ANeuralNetworksCompilation_createForDevices"); + FS_NN_SYM(comp_set_pref_, "ANeuralNetworksCompilation_setPreference"); + FS_NN_SYM(comp_finish_, "ANeuralNetworksCompilation_finish"); + FS_NN_SYM(comp_free_, "ANeuralNetworksCompilation_free"); + FS_NN_SYM(exec_create_, "ANeuralNetworksExecution_create"); + FS_NN_SYM(exec_free_, "ANeuralNetworksExecution_free"); + FS_NN_SYM(exec_set_reusable_, "ANeuralNetworksExecution_setReusable"); + FS_NN_SYM(exec_set_in_, "ANeuralNetworksExecution_setInput"); + FS_NN_SYM(exec_set_out_, "ANeuralNetworksExecution_setOutput"); + FS_NN_SYM(exec_set_in_mem_, "ANeuralNetworksExecution_setInputFromMemory"); + FS_NN_SYM(exec_set_out_mem_, "ANeuralNetworksExecution_setOutputFromMemory"); + FS_NN_SYM(exec_compute_, "ANeuralNetworksExecution_compute"); + FS_NN_SYM(exec_start_deps_, "ANeuralNetworksExecution_startComputeWithDependencies"); + FS_NN_SYM(event_from_fd_, "ANeuralNetworksEvent_createFromSyncFenceFd"); + FS_NN_SYM(event_get_fd_, "ANeuralNetworksEvent_getSyncFenceFd"); + FS_NN_SYM(event_wait_, "ANeuralNetworksEvent_wait"); + FS_NN_SYM(event_free_, "ANeuralNetworksEvent_free"); +#undef FS_NN_SYM + if (!get_device_count_ || !get_device_ || !device_get_name_ || !device_get_type_ || !model_create_ || + !model_add_operand_ || !model_set_val_ || !model_add_op_ || !model_id_io_ || !model_finish_ || + !comp_create_for_devs_ || !comp_finish_ || !exec_create_ || !exec_set_in_ || !exec_set_out_ || + !exec_set_in_mem_ || !exec_set_out_mem_ || !exec_compute_ || !mem_free_) { + *err = "libneuralnetworks.so lacks required API-29 entry points"; + return false; + } + const bool fenced_syms = exec_start_deps_ && event_from_fd_ && event_get_fd_ && event_free_; + uint32_t n = 0u; + if (get_device_count_(&n) != kNoError || n == 0u) { + *err = "NNAPI reports no devices"; + return false; + } + int best_rank = -1; + std::string seen; + for (uint32_t i = 0u; i < n; ++i) { + void* dev = nullptr; + const char* nm = nullptr; + int32_t type = 0; + if (get_device_(i, &dev) != kNoError || !dev) continue; + (void)device_get_name_(dev, &nm); + (void)device_get_type_(dev, &type); + const std::string name = nm ? nm : ""; + seen += (seen.empty() ? "" : ",") + name; + if (type != kDeviceAccelerator) continue; + int rank = 0; + fs_nnapi_op_lowering_t low = FS_NNAPI_LOWERING_CONV1X1; + const fs_ahb_npu_vendor_t v = fs_ahb_classify_npu_device(name.c_str(), &rank, &low); + if (want && std::strcmp(want, "auto") != 0) { + if (name.find(want) == std::string::npos) continue; + rank = 1000; + } else if (v == FS_AHB_NPU_VENDOR_GOOGLE_EDGETPU) { + rank += 1000; + } + if (rank > best_rank) { + best_rank = rank; + dev_ = dev; + dev_name_ = name; + dev_type_ = type; + } + } + if (!dev_) { + *err = "no matching NNAPI ACCELERATOR device (seen: " + seen + ")"; + return false; + } + dev_feature_level_ = -1; + if (device_get_feature_level_) { + int64_t fl = -1; + if (device_get_feature_level_(dev_, &fl) == kNoError) dev_feature_level_ = fl; + } + fenced_api_ = fenced_syms && nnapi_device_supports_native_fenced(dev_type_, dev_feature_level_); + ready_ = true; + return true; + } + + /* + * Per-layer QUANT8_ASYMM 1x1 CONV_2D: in [1,1,1,d] (qa), filter [d,1,1,d] + * uint8 = int8 + 128 (scale 1, zp 128), bias int32 zeros (scale qa.scale), + * out [1,1,1,d] (qy). + */ + bool compile_layer(const int8_t* w, uint32_t d, const Quant8& qa, const Quant8& qy, std::string* err) { + Layer ly; + ly.d = d; + ly.wq.resize(static_cast(d) * d); + for (size_t i = 0u; i < ly.wq.size(); ++i) ly.wq[i] = static_cast(static_cast(w[i]) + 128); + ly.bias.assign(d, 0); + if (model_create_(&ly.model) != kNoError) { + *err = "ANeuralNetworksModel_create failed"; + return false; + } + const uint32_t in_dims[4] = {1u, 1u, 1u, d}; + const uint32_t w_dims[4] = {d, 1u, 1u, d}; + const uint32_t b_dims[1] = {d}; + const OperandType ops[7] = { + {kTensorQuant8Asymm, 4u, in_dims, qa.scale, qa.zero_point}, + {kTensorQuant8Asymm, 4u, w_dims, 1.0f, 128}, + {kTensorInt32, 1u, b_dims, qa.scale * 1.0f, 0}, + {kInt32, 0u, nullptr, 0.0f, 0}, + {kInt32, 0u, nullptr, 0.0f, 0}, + {kInt32, 0u, nullptr, 0.0f, 0}, + {kTensorQuant8Asymm, 4u, in_dims, qy.scale, qy.zero_point}, + }; + bool ok = true; + for (int i = 0; i < 7 && ok; ++i) ok = model_add_operand_(ly.model, &ops[i]) == kNoError; + const int32_t pad = kPaddingValid, stride = 1, act = kFusedNone; + ok = ok && model_set_val_(ly.model, 1, ly.wq.data(), ly.wq.size()) == kNoError && + model_set_val_(ly.model, 2, ly.bias.data(), ly.bias.size() * sizeof(int32_t)) == kNoError && + model_set_val_(ly.model, 3, &pad, sizeof(pad)) == kNoError && + model_set_val_(ly.model, 4, &stride, sizeof(stride)) == kNoError && + model_set_val_(ly.model, 5, &act, sizeof(act)) == kNoError; + const uint32_t conv_in[7] = {0u, 1u, 2u, 3u, 4u, 4u, 5u}; + const uint32_t conv_out[1] = {6u}; + const uint32_t mi[1] = {0u}, mo[1] = {6u}; + ok = ok && model_add_op_(ly.model, kConv2d, 7u, conv_in, 1u, conv_out) == kNoError && + model_id_io_(ly.model, 1u, mi, 1u, mo) == kNoError && model_finish_(ly.model) == kNoError; + if (!ok) { + free_layer(&ly); + *err = "NNAPI QUANT8_ASYMM 1x1 CONV_2D model build failed"; + return false; + } + const void* devs[1] = {dev_}; + if (comp_create_for_devs_(ly.model, devs, 1u, &ly.comp) != kNoError || !ly.comp) { + free_layer(&ly); + *err = "ANeuralNetworksCompilation_createForDevices(" + dev_name_ + ") failed"; + return false; + } + if (comp_set_pref_) (void)comp_set_pref_(ly.comp, kPreferSustainedSpeed); + const int frc = comp_finish_(ly.comp); + if (frc != kNoError) { + free_layer(&ly); + *err = "ANeuralNetworksCompilation_finish on " + dev_name_ + " rejected the QUANT8 1x1 CONV_2D (rc=" + + std::to_string(frc) + ")"; + return false; + } + layers_.push_back(std::move(ly)); + return true; + } + + /* Wraps a BLOB AHardwareBuffer (borrowed) as NNAPI memory. */ + bool import_ahb(const void* ahb, void** out_mem) { + *out_mem = nullptr; + if (!mem_from_ahb_ || !ahb) return false; + return mem_from_ahb_(ahb, out_mem) == kNoError && *out_mem; + } + /* Wraps a DMA-BUF / shareable fd (NNAPI dups it) as NNAPI memory. */ + bool import_fd(int fd, size_t size, void** out_mem) { + *out_mem = nullptr; + if (!mem_from_fd_ || fd < 0) return false; + return mem_from_fd_(size, PROT_READ | PROT_WRITE, fd, 0u, out_mem) == kNoError && *out_mem; + } + void free_mem(void* mem) { + if (abandoned_) return; + if (mem && mem_free_) mem_free_(mem); + } + + /* + * Binds per-layer zero-copy executions (in_mem[l] -> out_mem[l]). Uses + * reusable executions (API 31+) when available; otherwise executions are + * created per hop in start(). + */ + bool bind_zero_copy(const std::vector& in_mem, const std::vector& out_mem, std::string* err) { + zc_in_ = in_mem; + zc_out_ = out_mem; + reusable_ = exec_set_reusable_ != nullptr; + for (size_t l = 0u; l < layers_.size() && reusable_; ++l) { + void* ex = nullptr; + if (!make_exec(l, true, &ex)) { + reusable_ = false; + break; + } + layers_[l].zc_exec = ex; + } + if (!reusable_) { + for (Layer& ly : layers_) { + if (ly.zc_exec) exec_free_(ly.zc_exec); + ly.zc_exec = nullptr; + } + void* probe = nullptr; + if (!layers_.empty() && !make_exec(0u, false, &probe)) { + *err = "ANeuralNetworksExecution_setInput/OutputFromMemory rejected the shared buffer"; + return false; + } + if (probe) exec_free_(probe); + } + return true; + } + + /* Host-staged synchronous execution of layer l (host pointers). */ + bool compute_host(uint32_t l, const uint8_t* in, uint8_t* out, std::string* err) { + Layer& ly = layers_[l]; + void* ex = nullptr; + if (exec_create_(ly.comp, &ex) != kNoError || !ex) { + *err = "ANeuralNetworksExecution_create failed"; + return false; + } + const bool ok = exec_set_in_(ex, 0, nullptr, in, ly.d) == kNoError && + exec_set_out_(ex, 0, nullptr, out, ly.d) == kNoError && exec_compute_(ex) == kNoError; + exec_free_(ex); + if (!ok) *err = "ANeuralNetworksExecution_compute(host-staged) failed"; + return ok; + } + + /* Frees executions/compilations/models (memories must be freed before shutdown()). */ + void free_layers() { + if (abandoned_) return; + for (Layer& ly : layers_) free_layer(&ly); + layers_.clear(); + } + + void shutdown() { + if (abandoned_) { + ready_ = false; + return; + } + free_layers(); + /* + * libneuralnetworks.so is intentionally never dlclose()d: the NNAPI runtime + * keeps detached worker threads (fenced/async execution callbacks) parked in + * pthread_cond_clockwait after every object is freed. Unloading the library + * unmaps their code and they SIGSEGV during process exit (seen live on + * Tensor G6 with google-edgetpu). The handle is simply dropped. + */ + lib_ = nullptr; + ready_ = false; + } + + private: + static constexpr int32_t kInt32 = 1; + static constexpr int32_t kTensorInt32 = 4; + static constexpr int32_t kTensorQuant8Asymm = 5; + static constexpr int32_t kConv2d = 3; + static constexpr int32_t kFusedNone = 0; + static constexpr int32_t kPaddingValid = 2; + static constexpr int32_t kPreferSustainedSpeed = 2; + static constexpr int32_t kDeviceAccelerator = 4; + + struct OperandType { + int32_t type; + uint32_t dimensionCount; + const uint32_t* dimensions; + float scale; + int32_t zeroPoint; + }; + struct Layer { + uint32_t d = 0u; + std::vector wq; + std::vector bias; + void* model = nullptr; + void* comp = nullptr; + void* zc_exec = nullptr; + }; + + /* Zero-copy execution of layer l: the reusable one, or a per-hop execution owned by inf. */ + bool acquire_exec(uint32_t l, void** out, NnInflight* inf) { + *out = nullptr; + if (l >= layers_.size()) return false; + if (layers_[l].zc_exec) { + *out = layers_[l].zc_exec; + return true; + } + if (!make_exec(l, false, out)) return false; + inf->execution = *out; + return true; + } + + bool make_exec(size_t l, bool reusable, void** out) { + *out = nullptr; + Layer& ly = layers_[l]; + if (l >= zc_in_.size() || l >= zc_out_.size()) return false; + void* ex = nullptr; + if (exec_create_(ly.comp, &ex) != kNoError || !ex) return false; + bool ok = true; + if (reusable) ok = exec_set_reusable_(ex, true) == kNoError; + ok = ok && exec_set_in_mem_(ex, 0, nullptr, zc_in_[l], 0u, ly.d) == kNoError && + exec_set_out_mem_(ex, 0, nullptr, zc_out_[l], 0u, ly.d) == kNoError; + if (!ok) { + exec_free_(ex); + return false; + } + *out = ex; + return true; + } + + void free_layer(Layer* ly) { + if (ly->zc_exec && exec_free_) exec_free_(ly->zc_exec); + if (ly->comp && comp_free_) comp_free_(ly->comp); + if (ly->model && model_free_) model_free_(ly->model); + ly->zc_exec = ly->comp = ly->model = nullptr; + } + + void* lib_ = nullptr; + void* dev_ = nullptr; + std::vector layers_; + std::vector zc_in_, zc_out_; + + int (*get_device_count_)(uint32_t*) = nullptr; + int (*get_device_)(uint32_t, void**) = nullptr; + int (*device_get_name_)(const void*, const char**) = nullptr; + int (*device_get_type_)(const void*, int32_t*) = nullptr; + int (*device_get_feature_level_)(const void*, int64_t*) = nullptr; + int (*mem_from_fd_)(size_t, int, int, size_t, void**) = nullptr; + int (*mem_from_ahb_)(const void*, void**) = nullptr; + void (*mem_free_)(void*) = nullptr; + int (*model_create_)(void**) = nullptr; + void (*model_free_)(void*) = nullptr; + int (*model_add_operand_)(void*, const OperandType*) = nullptr; + int (*model_set_val_)(void*, int32_t, const void*, size_t) = nullptr; + int (*model_add_op_)(void*, int32_t, uint32_t, const uint32_t*, uint32_t, const uint32_t*) = nullptr; + int (*model_id_io_)(void*, uint32_t, const uint32_t*, uint32_t, const uint32_t*) = nullptr; + int (*model_finish_)(void*) = nullptr; + int (*comp_create_for_devs_)(void*, const void* const*, uint32_t, void**) = nullptr; + int (*comp_set_pref_)(void*, int32_t) = nullptr; + int (*comp_finish_)(void*) = nullptr; + void (*comp_free_)(void*) = nullptr; + int (*exec_create_)(void*, void**) = nullptr; + int (*exec_set_reusable_)(void*, bool) = nullptr; + int (*exec_set_in_)(void*, int32_t, const OperandType*, const void*, size_t) = nullptr; + int (*exec_set_out_)(void*, int32_t, const OperandType*, void*, size_t) = nullptr; + int (*exec_set_in_mem_)(void*, int32_t, const OperandType*, const void*, size_t, size_t) = nullptr; + int (*exec_set_out_mem_)(void*, int32_t, const OperandType*, const void*, size_t, size_t) = nullptr; + int (*exec_compute_)(void*) = nullptr; +#else /* !__ANDROID__ */ + bool init(const char*, std::string* err) { + *err = "NNAPI requires Android"; + return false; + } + bool compile_layer(const int8_t*, uint32_t, const Quant8&, const Quant8&, std::string* err) { + *err = "NNAPI requires Android"; + return false; + } + bool import_ahb(const void*, void** out_mem) { + *out_mem = nullptr; + return false; + } + bool import_fd(int, size_t, void** out_mem) { + *out_mem = nullptr; + return false; + } + void free_mem(void*) {} + bool bind_zero_copy(const std::vector&, const std::vector&, std::string* err) { + *err = "NNAPI requires Android"; + return false; + } + bool compute_host(uint32_t, const uint8_t*, uint8_t*, std::string* err) { + *err = "NNAPI requires Android"; + return false; + } + void free_layers() {} + void shutdown() { + if (abandoned_) { + ready_ = false; + return; + } + ready_ = false; + } + + /* + * Host-only test seam: drives the shared start()/check_done()/release() path + * with mock NNAPI entry points (tests/test_token_loop_riif.cpp). Never + * compiled into the Android bench. + */ + struct TestHooks { + int (*exec_start_deps)(void*, const void* const*, uint32_t, uint64_t, void**) = nullptr; + int (*event_from_fd)(int, void**) = nullptr; + int (*event_get_fd)(const void*, int*) = nullptr; + int (*event_wait)(void*) = nullptr; + void (*event_free)(void*) = nullptr; + void (*exec_free)(void*) = nullptr; + void* exec = nullptr; /* reusable zero-copy execution handle returned for every layer */ + int32_t device_type = kNnapiDeviceTypeAccelerator; + int64_t feature_level = kNnapiFeatureLevel4; + }; + void install_test_hooks(const char* device_name, const TestHooks& h) { + dev_name_ = device_name ? device_name : ""; + dev_type_ = h.device_type; + dev_feature_level_ = h.feature_level; + exec_start_deps_ = h.exec_start_deps; + event_from_fd_ = h.event_from_fd; + event_get_fd_ = h.event_get_fd; + event_wait_ = h.event_wait; + event_free_ = h.event_free; + exec_free_ = h.exec_free; + test_exec_ = h.exec; + const bool fenced_syms = exec_start_deps_ && event_from_fd_ && event_get_fd_ && event_free_; + fenced_api_ = fenced_syms && nnapi_device_supports_native_fenced(dev_type_, dev_feature_level_); + reusable_ = true; + ready_ = true; + } + + private: + bool acquire_exec(uint32_t, void** out, NnInflight*) { + *out = test_exec_; + return test_exec_ != nullptr; + } + void* test_exec_ = nullptr; +#endif + + private: + static constexpr int32_t kNoError = 0; + int (*exec_start_deps_)(void*, const void* const*, uint32_t, uint64_t, void**) = nullptr; + int (*event_from_fd_)(int, void**) = nullptr; + int (*event_get_fd_)(const void*, int*) = nullptr; + int (*event_wait_)(void*) = nullptr; + void (*event_free_)(void*) = nullptr; + void (*exec_free_)(void*) = nullptr; + bool dmabuf_mem_ = false; + bool allow_edgetpu_dmabuf_probe_ = false; + uint64_t exec_start_calls_ = 0u; + uint64_t fenced_refusals_ = 0u; + int32_t dev_type_ = 0; + int64_t dev_feature_level_ = -1; + bool ready_ = false; + bool reusable_ = false; + bool fenced_api_ = false; + bool abandoned_ = false; + std::string dev_name_; +}; + +/* ========================================================================= + * AHardwareBuffer BLOB helpers (GPU_DATA_BUFFER shared with NNAPI + Vulkan) + * ========================================================================= */ +struct AhbApi { + bool ok = false; + uint64_t allocs = 0u; /* successful AHardwareBuffer_allocate calls */ +#if defined(__ANDROID__) + struct Desc { + uint32_t width, height, layers, format; + uint64_t usage; + uint32_t stride, rfu0; + uint64_t rfu1; + }; + struct NativeHandle { + int version, numFds, numInts; + int data[1]; + }; + int (*allocate)(const Desc*, void**) = nullptr; + void (*release)(void*) = nullptr; + int (*lock)(void*, uint64_t, int32_t, const void*, void**) = nullptr; + int (*unlock)(void*, int32_t*) = nullptr; + const NativeHandle* (*native_handle)(const void*) = nullptr; + void* lib = nullptr; + void* nw = nullptr; + + bool load() { + lib = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL); + nw = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL); + void* srcs[2] = {nw, lib}; + for (void* h : srcs) { + if (!h) continue; + if (!allocate) allocate = reinterpret_cast(dlsym(h, "AHardwareBuffer_allocate")); + if (!release) release = reinterpret_cast(dlsym(h, "AHardwareBuffer_release")); + if (!lock) lock = reinterpret_cast(dlsym(h, "AHardwareBuffer_lock")); + if (!unlock) unlock = reinterpret_cast(dlsym(h, "AHardwareBuffer_unlock")); + if (!native_handle) { + native_handle = reinterpret_cast(dlsym(h, "AHardwareBuffer_getNativeHandle")); + } + } + ok = allocate && release && lock && unlock && native_handle; + return ok; + } + /* BLOB AHB of `bytes`; returns its first native-handle fd (the DMA-BUF) borrowed. */ + bool alloc_blob(size_t bytes, uint64_t usage, void** out_ahb, int* out_fd) { + *out_ahb = nullptr; + *out_fd = -1; + Desc d{}; + d.width = static_cast(bytes); + d.height = 1u; + d.layers = 1u; + d.format = 0x21u; /* AHARDWAREBUFFER_FORMAT_BLOB */ + d.usage = usage; + if (allocate(&d, out_ahb) != 0 || !*out_ahb) return false; + const NativeHandle* nh = native_handle(*out_ahb); + if (!nh || nh->numFds < 1 || nh->data[0] < 0) { + release(*out_ahb); + *out_ahb = nullptr; + return false; + } + *out_fd = nh->data[0]; + ++allocs; + return true; + } + bool read(void* ahb, void* dst, size_t n) { + void* p = nullptr; + if (lock(ahb, FS_AHB_USAGE_CPU_READ_OFTEN, -1, nullptr, &p) != 0 || !p) return false; + std::memcpy(dst, p, n); + return unlock(ahb, nullptr) == 0; + } + bool write(void* ahb, const void* src, size_t n) { + void* p = nullptr; + if (lock(ahb, FS_AHB_USAGE_CPU_WRITE_OFTEN, -1, nullptr, &p) != 0 || !p) return false; + std::memcpy(p, src, n); + return unlock(ahb, nullptr) == 0; + } +#endif +}; + +} // namespace fs_tokloop + +#endif /* FREESCHED_VOLCANIC_NNAPI_EDGETPU_H_ */ diff --git a/tools/volcanic_quant8_spirv.h b/tools/volcanic_quant8_spirv.h new file mode 100644 index 0000000..0344682 --- /dev/null +++ b/tools/volcanic_quant8_spirv.h @@ -0,0 +1,195 @@ +/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ Embedded SPIR-V: FP32 <-> QUANT8_ASYMM bridges. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Generated by scripts/gen_volcanic_quant8_spirv.sh from + * shaders/volcanic/quant_f32_u8.comp and shaders/volcanic/dequant_u8_f32.comp + * via glslangValidator + spirv-val. + */ +#ifndef FREESCHED_VOLCANIC_QUANT8_SPIRV_H_ +#define FREESCHED_VOLCANIC_QUANT8_SPIRV_H_ + +#include + +static const uint32_t g_volcanic_quant_f32_u8_spv[] = { + 0x07230203u, 0x00010300u, 0x0008000bu, 0x0000006fu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x0006000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000002au, 0x00060010u, 0x00000004u, + 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, + 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, 0x0000000bu, 0x66283871u, 0x00003b31u, 0x00030005u, + 0x0000000au, 0x00000076u, 0x00030005u, 0x0000000du, 0x00000071u, 0x00050005u, 0x0000000fu, 0x68737550u, + 0x736e6f43u, 0x00007374u, 0x00040006u, 0x0000000fu, 0x00000000u, 0x0000004eu, 0x00060006u, 0x0000000fu, + 0x00000001u, 0x5f766e69u, 0x6c616373u, 0x00000065u, 0x00060006u, 0x0000000fu, 0x00000002u, 0x6f72657au, + 0x696f705fu, 0x0000746eu, 0x00040006u, 0x0000000fu, 0x00000003u, 0x00646170u, 0x00030005u, 0x00000011u, + 0x00006370u, 0x00030005u, 0x00000027u, 0x00000077u, 0x00080005u, 0x0000002au, 0x475f6c67u, 0x61626f6cu, + 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x0000002fu, 0x65736162u, 0x00000000u, + 0x00040005u, 0x0000003cu, 0x6b636170u, 0x00006465u, 0x00040005u, 0x0000003eu, 0x49667542u, 0x0000006eu, + 0x00040006u, 0x0000003eu, 0x00000000u, 0x00000041u, 0x00030005u, 0x00000040u, 0x00000000u, 0x00040005u, + 0x00000042u, 0x61726170u, 0x0000006du, 0x00040005u, 0x0000004au, 0x61726170u, 0x0000006du, 0x00040005u, + 0x00000054u, 0x61726170u, 0x0000006du, 0x00040005u, 0x0000005eu, 0x61726170u, 0x0000006du, 0x00040005u, + 0x00000066u, 0x51667542u, 0x00000000u, 0x00040006u, 0x00000066u, 0x00000000u, 0x00000051u, 0x00030005u, + 0x00000068u, 0x00000000u, 0x00030047u, 0x0000000fu, 0x00000002u, 0x00050048u, 0x0000000fu, 0x00000000u, + 0x00000023u, 0x00000000u, 0x00050048u, 0x0000000fu, 0x00000001u, 0x00000023u, 0x00000004u, 0x00050048u, + 0x0000000fu, 0x00000002u, 0x00000023u, 0x00000008u, 0x00050048u, 0x0000000fu, 0x00000003u, 0x00000023u, + 0x0000000cu, 0x00040047u, 0x0000002au, 0x0000000bu, 0x0000001cu, 0x00040047u, 0x0000003du, 0x00000006u, + 0x00000004u, 0x00030047u, 0x0000003eu, 0x00000002u, 0x00040048u, 0x0000003eu, 0x00000000u, 0x00000018u, + 0x00050048u, 0x0000003eu, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x00000040u, 0x00000018u, + 0x00040047u, 0x00000040u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000040u, 0x00000022u, 0x00000000u, + 0x00040047u, 0x00000065u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000066u, 0x00000002u, 0x00040048u, + 0x00000066u, 0x00000000u, 0x00000019u, 0x00050048u, 0x00000066u, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00030047u, 0x00000068u, 0x00000019u, 0x00040047u, 0x00000068u, 0x00000021u, 0x00000001u, 0x00040047u, + 0x00000068u, 0x00000022u, 0x00000000u, 0x00040047u, 0x0000006eu, 0x0000000bu, 0x00000019u, 0x00020013u, + 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040020u, + 0x00000007u, 0x00000007u, 0x00000006u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x00040021u, + 0x00000009u, 0x00000008u, 0x00000007u, 0x0006001eu, 0x0000000fu, 0x00000008u, 0x00000006u, 0x00000008u, + 0x00000008u, 0x00040020u, 0x00000010u, 0x00000009u, 0x0000000fu, 0x0004003bu, 0x00000010u, 0x00000011u, + 0x00000009u, 0x00040015u, 0x00000012u, 0x00000020u, 0x00000001u, 0x0004002bu, 0x00000012u, 0x00000013u, + 0x00000001u, 0x00040020u, 0x00000014u, 0x00000009u, 0x00000006u, 0x0004002bu, 0x00000012u, 0x00000019u, + 0x00000002u, 0x00040020u, 0x0000001au, 0x00000009u, 0x00000008u, 0x0004002bu, 0x00000006u, 0x00000020u, + 0x00000000u, 0x0004002bu, 0x00000006u, 0x00000021u, 0x437f0000u, 0x00040020u, 0x00000026u, 0x00000007u, + 0x00000008u, 0x00040017u, 0x00000028u, 0x00000008u, 0x00000003u, 0x00040020u, 0x00000029u, 0x00000001u, + 0x00000028u, 0x0004003bu, 0x00000029u, 0x0000002au, 0x00000001u, 0x0004002bu, 0x00000008u, 0x0000002bu, + 0x00000000u, 0x00040020u, 0x0000002cu, 0x00000001u, 0x00000008u, 0x0004002bu, 0x00000008u, 0x00000031u, + 0x00000004u, 0x0004002bu, 0x00000012u, 0x00000034u, 0x00000000u, 0x00020014u, 0x00000037u, 0x0003001du, + 0x0000003du, 0x00000006u, 0x0003001eu, 0x0000003eu, 0x0000003du, 0x00040020u, 0x0000003fu, 0x0000000cu, + 0x0000003eu, 0x0004003bu, 0x0000003fu, 0x00000040u, 0x0000000cu, 0x00040020u, 0x00000043u, 0x0000000cu, + 0x00000006u, 0x0004002bu, 0x00000008u, 0x00000048u, 0x00000001u, 0x0004002bu, 0x00000008u, 0x0000004eu, + 0x00000008u, 0x0004002bu, 0x00000008u, 0x00000052u, 0x00000002u, 0x0004002bu, 0x00000008u, 0x00000058u, + 0x00000010u, 0x0004002bu, 0x00000008u, 0x0000005cu, 0x00000003u, 0x0004002bu, 0x00000008u, 0x00000062u, + 0x00000018u, 0x0003001du, 0x00000065u, 0x00000008u, 0x0003001eu, 0x00000066u, 0x00000065u, 0x00040020u, + 0x00000067u, 0x0000000cu, 0x00000066u, 0x0004003bu, 0x00000067u, 0x00000068u, 0x0000000cu, 0x00040020u, + 0x0000006bu, 0x0000000cu, 0x00000008u, 0x0004002bu, 0x00000008u, 0x0000006du, 0x00000040u, 0x0006002cu, + 0x00000028u, 0x0000006eu, 0x0000006du, 0x00000048u, 0x00000048u, 0x00050036u, 0x00000002u, 0x00000004u, + 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000026u, 0x00000027u, 0x00000007u, + 0x0004003bu, 0x00000026u, 0x0000002fu, 0x00000007u, 0x0004003bu, 0x00000026u, 0x0000003cu, 0x00000007u, + 0x0004003bu, 0x00000007u, 0x00000042u, 0x00000007u, 0x0004003bu, 0x00000007u, 0x0000004au, 0x00000007u, + 0x0004003bu, 0x00000007u, 0x00000054u, 0x00000007u, 0x0004003bu, 0x00000007u, 0x0000005eu, 0x00000007u, + 0x00050041u, 0x0000002cu, 0x0000002du, 0x0000002au, 0x0000002bu, 0x0004003du, 0x00000008u, 0x0000002eu, + 0x0000002du, 0x0003003eu, 0x00000027u, 0x0000002eu, 0x0004003du, 0x00000008u, 0x00000030u, 0x00000027u, + 0x00050084u, 0x00000008u, 0x00000032u, 0x00000030u, 0x00000031u, 0x0003003eu, 0x0000002fu, 0x00000032u, + 0x0004003du, 0x00000008u, 0x00000033u, 0x0000002fu, 0x00050041u, 0x0000001au, 0x00000035u, 0x00000011u, + 0x00000034u, 0x0004003du, 0x00000008u, 0x00000036u, 0x00000035u, 0x000500aeu, 0x00000037u, 0x00000038u, + 0x00000033u, 0x00000036u, 0x000300f7u, 0x0000003au, 0x00000000u, 0x000400fau, 0x00000038u, 0x00000039u, + 0x0000003au, 0x000200f8u, 0x00000039u, 0x000100fdu, 0x000200f8u, 0x0000003au, 0x0004003du, 0x00000008u, + 0x00000041u, 0x0000002fu, 0x00060041u, 0x00000043u, 0x00000044u, 0x00000040u, 0x00000034u, 0x00000041u, + 0x0004003du, 0x00000006u, 0x00000045u, 0x00000044u, 0x0003003eu, 0x00000042u, 0x00000045u, 0x00050039u, + 0x00000008u, 0x00000046u, 0x0000000bu, 0x00000042u, 0x0004003du, 0x00000008u, 0x00000047u, 0x0000002fu, + 0x00050080u, 0x00000008u, 0x00000049u, 0x00000047u, 0x00000048u, 0x00060041u, 0x00000043u, 0x0000004bu, + 0x00000040u, 0x00000034u, 0x00000049u, 0x0004003du, 0x00000006u, 0x0000004cu, 0x0000004bu, 0x0003003eu, + 0x0000004au, 0x0000004cu, 0x00050039u, 0x00000008u, 0x0000004du, 0x0000000bu, 0x0000004au, 0x000500c4u, + 0x00000008u, 0x0000004fu, 0x0000004du, 0x0000004eu, 0x000500c5u, 0x00000008u, 0x00000050u, 0x00000046u, + 0x0000004fu, 0x0004003du, 0x00000008u, 0x00000051u, 0x0000002fu, 0x00050080u, 0x00000008u, 0x00000053u, + 0x00000051u, 0x00000052u, 0x00060041u, 0x00000043u, 0x00000055u, 0x00000040u, 0x00000034u, 0x00000053u, + 0x0004003du, 0x00000006u, 0x00000056u, 0x00000055u, 0x0003003eu, 0x00000054u, 0x00000056u, 0x00050039u, + 0x00000008u, 0x00000057u, 0x0000000bu, 0x00000054u, 0x000500c4u, 0x00000008u, 0x00000059u, 0x00000057u, + 0x00000058u, 0x000500c5u, 0x00000008u, 0x0000005au, 0x00000050u, 0x00000059u, 0x0004003du, 0x00000008u, + 0x0000005bu, 0x0000002fu, 0x00050080u, 0x00000008u, 0x0000005du, 0x0000005bu, 0x0000005cu, 0x00060041u, + 0x00000043u, 0x0000005fu, 0x00000040u, 0x00000034u, 0x0000005du, 0x0004003du, 0x00000006u, 0x00000060u, + 0x0000005fu, 0x0003003eu, 0x0000005eu, 0x00000060u, 0x00050039u, 0x00000008u, 0x00000061u, 0x0000000bu, + 0x0000005eu, 0x000500c4u, 0x00000008u, 0x00000063u, 0x00000061u, 0x00000062u, 0x000500c5u, 0x00000008u, + 0x00000064u, 0x0000005au, 0x00000063u, 0x0003003eu, 0x0000003cu, 0x00000064u, 0x0004003du, 0x00000008u, + 0x00000069u, 0x00000027u, 0x0004003du, 0x00000008u, 0x0000006au, 0x0000003cu, 0x00060041u, 0x0000006bu, + 0x0000006cu, 0x00000068u, 0x00000034u, 0x00000069u, 0x0003003eu, 0x0000006cu, 0x0000006au, 0x000100fdu, + 0x00010038u, 0x00050036u, 0x00000008u, 0x0000000bu, 0x00000000u, 0x00000009u, 0x00030037u, 0x00000007u, + 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003bu, 0x00000007u, 0x0000000du, 0x00000007u, 0x0004003du, + 0x00000006u, 0x0000000eu, 0x0000000au, 0x00050041u, 0x00000014u, 0x00000015u, 0x00000011u, 0x00000013u, + 0x0004003du, 0x00000006u, 0x00000016u, 0x00000015u, 0x00050085u, 0x00000006u, 0x00000017u, 0x0000000eu, + 0x00000016u, 0x0006000cu, 0x00000006u, 0x00000018u, 0x00000001u, 0x00000002u, 0x00000017u, 0x00050041u, + 0x0000001au, 0x0000001bu, 0x00000011u, 0x00000019u, 0x0004003du, 0x00000008u, 0x0000001cu, 0x0000001bu, + 0x00040070u, 0x00000006u, 0x0000001du, 0x0000001cu, 0x00050081u, 0x00000006u, 0x0000001eu, 0x00000018u, + 0x0000001du, 0x0003003eu, 0x0000000du, 0x0000001eu, 0x0004003du, 0x00000006u, 0x0000001fu, 0x0000000du, + 0x0008000cu, 0x00000006u, 0x00000022u, 0x00000001u, 0x0000002bu, 0x0000001fu, 0x00000020u, 0x00000021u, + 0x0004006du, 0x00000008u, 0x00000023u, 0x00000022u, 0x000200feu, 0x00000023u, 0x00010038u, +}; + +static const uint32_t g_volcanic_dequant_u8_f32_spv[] = { + 0x07230203u, 0x00010300u, 0x0008000bu, 0x0000006fu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x0006000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, 0x00060010u, 0x00000004u, + 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, + 0x00000004u, 0x6e69616du, 0x00000000u, 0x00030005u, 0x00000008u, 0x00000077u, 0x00080005u, 0x0000000bu, + 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x00000010u, + 0x65736162u, 0x00000000u, 0x00050005u, 0x00000016u, 0x68737550u, 0x736e6f43u, 0x00007374u, 0x00040006u, + 0x00000016u, 0x00000000u, 0x0000004eu, 0x00050006u, 0x00000016u, 0x00000001u, 0x6c616373u, 0x00000065u, + 0x00060006u, 0x00000016u, 0x00000002u, 0x6f72657au, 0x696f705fu, 0x0000746eu, 0x00040006u, 0x00000016u, + 0x00000003u, 0x00646170u, 0x00030005u, 0x00000018u, 0x00006370u, 0x00040005u, 0x00000023u, 0x6b636170u, + 0x00006465u, 0x00040005u, 0x00000025u, 0x51667542u, 0x00000000u, 0x00040006u, 0x00000025u, 0x00000000u, + 0x00000051u, 0x00030005u, 0x00000027u, 0x00000000u, 0x00030005u, 0x0000002du, 0x0000707au, 0x00040005u, + 0x00000033u, 0x4f667542u, 0x00007475u, 0x00040006u, 0x00000033u, 0x00000000u, 0x00000059u, 0x00030005u, + 0x00000035u, 0x00000000u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, 0x00030047u, 0x00000016u, + 0x00000002u, 0x00050048u, 0x00000016u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000016u, + 0x00000001u, 0x00000023u, 0x00000004u, 0x00050048u, 0x00000016u, 0x00000002u, 0x00000023u, 0x00000008u, + 0x00050048u, 0x00000016u, 0x00000003u, 0x00000023u, 0x0000000cu, 0x00040047u, 0x00000024u, 0x00000006u, + 0x00000004u, 0x00030047u, 0x00000025u, 0x00000002u, 0x00040048u, 0x00000025u, 0x00000000u, 0x00000018u, + 0x00050048u, 0x00000025u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x00000027u, 0x00000018u, + 0x00040047u, 0x00000027u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000027u, 0x00000022u, 0x00000000u, + 0x00040047u, 0x00000032u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000033u, 0x00000002u, 0x00040048u, + 0x00000033u, 0x00000000u, 0x00000019u, 0x00050048u, 0x00000033u, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00030047u, 0x00000035u, 0x00000019u, 0x00040047u, 0x00000035u, 0x00000021u, 0x00000001u, 0x00040047u, + 0x00000035u, 0x00000022u, 0x00000000u, 0x00040047u, 0x0000006eu, 0x0000000bu, 0x00000019u, 0x00020013u, + 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, + 0x00040020u, 0x00000007u, 0x00000007u, 0x00000006u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, + 0x00040020u, 0x0000000au, 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, + 0x0004002bu, 0x00000006u, 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, + 0x0004002bu, 0x00000006u, 0x00000012u, 0x00000004u, 0x00030016u, 0x00000015u, 0x00000020u, 0x0006001eu, + 0x00000016u, 0x00000006u, 0x00000015u, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000017u, 0x00000009u, + 0x00000016u, 0x0004003bu, 0x00000017u, 0x00000018u, 0x00000009u, 0x00040015u, 0x00000019u, 0x00000020u, + 0x00000001u, 0x0004002bu, 0x00000019u, 0x0000001au, 0x00000000u, 0x00040020u, 0x0000001bu, 0x00000009u, + 0x00000006u, 0x00020014u, 0x0000001eu, 0x0003001du, 0x00000024u, 0x00000006u, 0x0003001eu, 0x00000025u, + 0x00000024u, 0x00040020u, 0x00000026u, 0x0000000cu, 0x00000025u, 0x0004003bu, 0x00000026u, 0x00000027u, + 0x0000000cu, 0x00040020u, 0x00000029u, 0x0000000cu, 0x00000006u, 0x00040020u, 0x0000002cu, 0x00000007u, + 0x00000015u, 0x0004002bu, 0x00000019u, 0x0000002eu, 0x00000002u, 0x0003001du, 0x00000032u, 0x00000015u, + 0x0003001eu, 0x00000033u, 0x00000032u, 0x00040020u, 0x00000034u, 0x0000000cu, 0x00000033u, 0x0004003bu, + 0x00000034u, 0x00000035u, 0x0000000cu, 0x0004002bu, 0x00000006u, 0x00000038u, 0x000000ffu, 0x0004002bu, + 0x00000019u, 0x0000003du, 0x00000001u, 0x00040020u, 0x0000003eu, 0x00000009u, 0x00000015u, 0x00040020u, + 0x00000042u, 0x0000000cu, 0x00000015u, 0x0004002bu, 0x00000006u, 0x00000045u, 0x00000001u, 0x0004002bu, + 0x00000006u, 0x00000048u, 0x00000008u, 0x0004002bu, 0x00000006u, 0x00000053u, 0x00000002u, 0x0004002bu, + 0x00000006u, 0x00000056u, 0x00000010u, 0x0004002bu, 0x00000006u, 0x00000061u, 0x00000003u, 0x0004002bu, + 0x00000006u, 0x00000064u, 0x00000018u, 0x0004002bu, 0x00000006u, 0x0000006du, 0x00000040u, 0x0006002cu, + 0x00000009u, 0x0000006eu, 0x0000006du, 0x00000045u, 0x00000045u, 0x00050036u, 0x00000002u, 0x00000004u, + 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000007u, 0x00000008u, 0x00000007u, + 0x0004003bu, 0x00000007u, 0x00000010u, 0x00000007u, 0x0004003bu, 0x00000007u, 0x00000023u, 0x00000007u, + 0x0004003bu, 0x0000002cu, 0x0000002du, 0x00000007u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, + 0x0000000cu, 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, 0x0003003eu, 0x00000008u, 0x0000000fu, + 0x0004003du, 0x00000006u, 0x00000011u, 0x00000008u, 0x00050084u, 0x00000006u, 0x00000013u, 0x00000011u, + 0x00000012u, 0x0003003eu, 0x00000010u, 0x00000013u, 0x0004003du, 0x00000006u, 0x00000014u, 0x00000010u, + 0x00050041u, 0x0000001bu, 0x0000001cu, 0x00000018u, 0x0000001au, 0x0004003du, 0x00000006u, 0x0000001du, + 0x0000001cu, 0x000500aeu, 0x0000001eu, 0x0000001fu, 0x00000014u, 0x0000001du, 0x000300f7u, 0x00000021u, + 0x00000000u, 0x000400fau, 0x0000001fu, 0x00000020u, 0x00000021u, 0x000200f8u, 0x00000020u, 0x000100fdu, + 0x000200f8u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000028u, 0x00000008u, 0x00060041u, 0x00000029u, + 0x0000002au, 0x00000027u, 0x0000001au, 0x00000028u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au, + 0x0003003eu, 0x00000023u, 0x0000002bu, 0x00050041u, 0x0000001bu, 0x0000002fu, 0x00000018u, 0x0000002eu, + 0x0004003du, 0x00000006u, 0x00000030u, 0x0000002fu, 0x00040070u, 0x00000015u, 0x00000031u, 0x00000030u, + 0x0003003eu, 0x0000002du, 0x00000031u, 0x0004003du, 0x00000006u, 0x00000036u, 0x00000010u, 0x0004003du, + 0x00000006u, 0x00000037u, 0x00000023u, 0x000500c7u, 0x00000006u, 0x00000039u, 0x00000037u, 0x00000038u, + 0x00040070u, 0x00000015u, 0x0000003au, 0x00000039u, 0x0004003du, 0x00000015u, 0x0000003bu, 0x0000002du, + 0x00050083u, 0x00000015u, 0x0000003cu, 0x0000003au, 0x0000003bu, 0x00050041u, 0x0000003eu, 0x0000003fu, + 0x00000018u, 0x0000003du, 0x0004003du, 0x00000015u, 0x00000040u, 0x0000003fu, 0x00050085u, 0x00000015u, + 0x00000041u, 0x0000003cu, 0x00000040u, 0x00060041u, 0x00000042u, 0x00000043u, 0x00000035u, 0x0000001au, + 0x00000036u, 0x0003003eu, 0x00000043u, 0x00000041u, 0x0004003du, 0x00000006u, 0x00000044u, 0x00000010u, + 0x00050080u, 0x00000006u, 0x00000046u, 0x00000044u, 0x00000045u, 0x0004003du, 0x00000006u, 0x00000047u, + 0x00000023u, 0x000500c2u, 0x00000006u, 0x00000049u, 0x00000047u, 0x00000048u, 0x000500c7u, 0x00000006u, + 0x0000004au, 0x00000049u, 0x00000038u, 0x00040070u, 0x00000015u, 0x0000004bu, 0x0000004au, 0x0004003du, + 0x00000015u, 0x0000004cu, 0x0000002du, 0x00050083u, 0x00000015u, 0x0000004du, 0x0000004bu, 0x0000004cu, + 0x00050041u, 0x0000003eu, 0x0000004eu, 0x00000018u, 0x0000003du, 0x0004003du, 0x00000015u, 0x0000004fu, + 0x0000004eu, 0x00050085u, 0x00000015u, 0x00000050u, 0x0000004du, 0x0000004fu, 0x00060041u, 0x00000042u, + 0x00000051u, 0x00000035u, 0x0000001au, 0x00000046u, 0x0003003eu, 0x00000051u, 0x00000050u, 0x0004003du, + 0x00000006u, 0x00000052u, 0x00000010u, 0x00050080u, 0x00000006u, 0x00000054u, 0x00000052u, 0x00000053u, + 0x0004003du, 0x00000006u, 0x00000055u, 0x00000023u, 0x000500c2u, 0x00000006u, 0x00000057u, 0x00000055u, + 0x00000056u, 0x000500c7u, 0x00000006u, 0x00000058u, 0x00000057u, 0x00000038u, 0x00040070u, 0x00000015u, + 0x00000059u, 0x00000058u, 0x0004003du, 0x00000015u, 0x0000005au, 0x0000002du, 0x00050083u, 0x00000015u, + 0x0000005bu, 0x00000059u, 0x0000005au, 0x00050041u, 0x0000003eu, 0x0000005cu, 0x00000018u, 0x0000003du, + 0x0004003du, 0x00000015u, 0x0000005du, 0x0000005cu, 0x00050085u, 0x00000015u, 0x0000005eu, 0x0000005bu, + 0x0000005du, 0x00060041u, 0x00000042u, 0x0000005fu, 0x00000035u, 0x0000001au, 0x00000054u, 0x0003003eu, + 0x0000005fu, 0x0000005eu, 0x0004003du, 0x00000006u, 0x00000060u, 0x00000010u, 0x00050080u, 0x00000006u, + 0x00000062u, 0x00000060u, 0x00000061u, 0x0004003du, 0x00000006u, 0x00000063u, 0x00000023u, 0x000500c2u, + 0x00000006u, 0x00000065u, 0x00000063u, 0x00000064u, 0x00040070u, 0x00000015u, 0x00000066u, 0x00000065u, + 0x0004003du, 0x00000015u, 0x00000067u, 0x0000002du, 0x00050083u, 0x00000015u, 0x00000068u, 0x00000066u, + 0x00000067u, 0x00050041u, 0x0000003eu, 0x00000069u, 0x00000018u, 0x0000003du, 0x0004003du, 0x00000015u, + 0x0000006au, 0x00000069u, 0x00050085u, 0x00000015u, 0x0000006bu, 0x00000068u, 0x0000006au, 0x00060041u, + 0x00000042u, 0x0000006cu, 0x00000035u, 0x0000001au, 0x00000062u, 0x0003003eu, 0x0000006cu, 0x0000006bu, + 0x000100fdu, 0x00010038u, +}; + +#endif /* FREESCHED_VOLCANIC_QUANT8_SPIRV_H_ */ diff --git a/tools/volcanic_token_loop_spirv.h b/tools/volcanic_token_loop_spirv.h new file mode 100644 index 0000000..c2d22c8 --- /dev/null +++ b/tools/volcanic_token_loop_spirv.h @@ -0,0 +1,143 @@ +/* + * Clean-room PowerVR Volcanic Vulkan 1.1+ Embedded SPIR-V: Residual + RMSNorm. + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Generated by scripts/gen_volcanic_token_loop_spirv.sh from + * shaders/volcanic/residual_rmsnorm_f32.comp via glslangValidator + spirv-val. + */ +#ifndef FREESCHED_VOLCANIC_TOKEN_LOOP_SPIRV_H_ +#define FREESCHED_VOLCANIC_TOKEN_LOOP_SPIRV_H_ + +#include + +static const uint32_t g_volcanic_residual_rmsnorm_f32_spv[] = { + 0x07230203u, 0x00010300u, 0x0008000bu, 0x0000009fu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x0006000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, 0x00060010u, 0x00000004u, + 0x00000011u, 0x00000100u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, + 0x00000004u, 0x6e69616du, 0x00000000u, 0x00030005u, 0x00000008u, 0x00646974u, 0x00080005u, 0x0000000bu, + 0x4c5f6c67u, 0x6c61636fu, 0x6f766e49u, 0x69746163u, 0x44496e6fu, 0x00000000u, 0x00030005u, 0x00000012u, + 0x00636361u, 0x00030005u, 0x00000014u, 0x00000069u, 0x00050005u, 0x0000001cu, 0x68737550u, 0x736e6f43u, + 0x00007374u, 0x00040006u, 0x0000001cu, 0x00000000u, 0x0000004eu, 0x00040006u, 0x0000001cu, 0x00000001u, + 0x00737065u, 0x00030005u, 0x0000001eu, 0x00006370u, 0x00030005u, 0x00000026u, 0x00000076u, 0x00040005u, + 0x00000028u, 0x59667542u, 0x00757054u, 0x00050006u, 0x00000028u, 0x00000000u, 0x70745f59u, 0x00000075u, + 0x00030005u, 0x0000002au, 0x00000000u, 0x00050005u, 0x00000030u, 0x53667542u, 0x656c6163u, 0x00000000u, + 0x00050006u, 0x00000030u, 0x00000000u, 0x6c616353u, 0x00000065u, 0x00030005u, 0x00000032u, 0x00000000u, + 0x00040005u, 0x00000038u, 0x58667542u, 0x00000000u, 0x00040006u, 0x00000038u, 0x00000000u, 0x00000058u, + 0x00030005u, 0x0000003au, 0x00000000u, 0x00050005u, 0x00000049u, 0x61705f73u, 0x61697472u, 0x0000006cu, + 0x00030005u, 0x00000051u, 0x00000073u, 0x00040005u, 0x0000006bu, 0x5f766e69u, 0x00736d72u, 0x00030005u, + 0x00000078u, 0x00000069u, 0x00030005u, 0x00000083u, 0x00000076u, 0x00050005u, 0x00000094u, 0x47667542u, + 0x616d6d61u, 0x00000000u, 0x00050006u, 0x00000094u, 0x00000000u, 0x6d6d6147u, 0x00000061u, 0x00030005u, + 0x00000096u, 0x00000000u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001bu, 0x00030047u, 0x0000001cu, + 0x00000002u, 0x00050048u, 0x0000001cu, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x0000001cu, + 0x00000001u, 0x00000023u, 0x00000004u, 0x00040047u, 0x00000027u, 0x00000006u, 0x00000004u, 0x00030047u, + 0x00000028u, 0x00000002u, 0x00040048u, 0x00000028u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000028u, + 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x0000002au, 0x00000018u, 0x00040047u, 0x0000002au, + 0x00000021u, 0x00000000u, 0x00040047u, 0x0000002au, 0x00000022u, 0x00000000u, 0x00040047u, 0x0000002fu, + 0x00000006u, 0x00000004u, 0x00030047u, 0x00000030u, 0x00000002u, 0x00040048u, 0x00000030u, 0x00000000u, + 0x00000018u, 0x00050048u, 0x00000030u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x00000032u, + 0x00000018u, 0x00040047u, 0x00000032u, 0x00000021u, 0x00000001u, 0x00040047u, 0x00000032u, 0x00000022u, + 0x00000000u, 0x00040047u, 0x00000037u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000038u, 0x00000002u, + 0x00050048u, 0x00000038u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x0000003au, 0x00000021u, + 0x00000002u, 0x00040047u, 0x0000003au, 0x00000022u, 0x00000000u, 0x00040047u, 0x00000093u, 0x00000006u, + 0x00000004u, 0x00030047u, 0x00000094u, 0x00000002u, 0x00040048u, 0x00000094u, 0x00000000u, 0x00000018u, + 0x00050048u, 0x00000094u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x00000096u, 0x00000018u, + 0x00040047u, 0x00000096u, 0x00000021u, 0x00000003u, 0x00040047u, 0x00000096u, 0x00000022u, 0x00000000u, + 0x00040047u, 0x0000009eu, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, + 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x00040020u, 0x00000007u, 0x00000007u, + 0x00000006u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, 0x00000001u, + 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, 0x0000000cu, + 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x00030016u, 0x00000010u, 0x00000020u, + 0x00040020u, 0x00000011u, 0x00000007u, 0x00000010u, 0x0004002bu, 0x00000010u, 0x00000013u, 0x00000000u, + 0x0004001eu, 0x0000001cu, 0x00000006u, 0x00000010u, 0x00040020u, 0x0000001du, 0x00000009u, 0x0000001cu, + 0x0004003bu, 0x0000001du, 0x0000001eu, 0x00000009u, 0x00040015u, 0x0000001fu, 0x00000020u, 0x00000001u, + 0x0004002bu, 0x0000001fu, 0x00000020u, 0x00000000u, 0x00040020u, 0x00000021u, 0x00000009u, 0x00000006u, + 0x00020014u, 0x00000024u, 0x0003001du, 0x00000027u, 0x00000010u, 0x0003001eu, 0x00000028u, 0x00000027u, + 0x00040020u, 0x00000029u, 0x0000000cu, 0x00000028u, 0x0004003bu, 0x00000029u, 0x0000002au, 0x0000000cu, + 0x00040020u, 0x0000002cu, 0x0000000cu, 0x00000010u, 0x0003001du, 0x0000002fu, 0x00000010u, 0x0003001eu, + 0x00000030u, 0x0000002fu, 0x00040020u, 0x00000031u, 0x0000000cu, 0x00000030u, 0x0004003bu, 0x00000031u, + 0x00000032u, 0x0000000cu, 0x0003001du, 0x00000037u, 0x00000010u, 0x0003001eu, 0x00000038u, 0x00000037u, + 0x00040020u, 0x00000039u, 0x0000000cu, 0x00000038u, 0x0004003bu, 0x00000039u, 0x0000003au, 0x0000000cu, + 0x0004002bu, 0x00000006u, 0x00000044u, 0x00000100u, 0x0004001cu, 0x00000047u, 0x00000010u, 0x00000044u, + 0x00040020u, 0x00000048u, 0x00000004u, 0x00000047u, 0x0004003bu, 0x00000048u, 0x00000049u, 0x00000004u, + 0x00040020u, 0x0000004cu, 0x00000004u, 0x00000010u, 0x0004002bu, 0x00000006u, 0x0000004eu, 0x00000001u, + 0x0004002bu, 0x00000006u, 0x0000004fu, 0x00000108u, 0x0004002bu, 0x00000006u, 0x00000050u, 0x00000002u, + 0x0004002bu, 0x00000006u, 0x00000052u, 0x00000080u, 0x0004002bu, 0x0000001fu, 0x00000072u, 0x00000001u, + 0x00040020u, 0x00000073u, 0x00000009u, 0x00000010u, 0x0003001du, 0x00000093u, 0x00000010u, 0x0003001eu, + 0x00000094u, 0x00000093u, 0x00040020u, 0x00000095u, 0x0000000cu, 0x00000094u, 0x0004003bu, 0x00000095u, + 0x00000096u, 0x0000000cu, 0x0006002cu, 0x00000009u, 0x0000009eu, 0x00000044u, 0x0000004eu, 0x0000004eu, + 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, + 0x00000007u, 0x00000008u, 0x00000007u, 0x0004003bu, 0x00000011u, 0x00000012u, 0x00000007u, 0x0004003bu, + 0x00000007u, 0x00000014u, 0x00000007u, 0x0004003bu, 0x00000011u, 0x00000026u, 0x00000007u, 0x0004003bu, + 0x00000007u, 0x00000051u, 0x00000007u, 0x0004003bu, 0x00000011u, 0x0000006bu, 0x00000007u, 0x0004003bu, + 0x00000007u, 0x00000078u, 0x00000007u, 0x0004003bu, 0x00000011u, 0x00000083u, 0x00000007u, 0x00050041u, + 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, + 0x0003003eu, 0x00000008u, 0x0000000fu, 0x0003003eu, 0x00000012u, 0x00000013u, 0x0004003du, 0x00000006u, + 0x00000015u, 0x00000008u, 0x0003003eu, 0x00000014u, 0x00000015u, 0x000200f9u, 0x00000016u, 0x000200f8u, + 0x00000016u, 0x000400f6u, 0x00000018u, 0x00000019u, 0x00000000u, 0x000200f9u, 0x0000001au, 0x000200f8u, + 0x0000001au, 0x0004003du, 0x00000006u, 0x0000001bu, 0x00000014u, 0x00050041u, 0x00000021u, 0x00000022u, + 0x0000001eu, 0x00000020u, 0x0004003du, 0x00000006u, 0x00000023u, 0x00000022u, 0x000500b0u, 0x00000024u, + 0x00000025u, 0x0000001bu, 0x00000023u, 0x000400fau, 0x00000025u, 0x00000017u, 0x00000018u, 0x000200f8u, + 0x00000017u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x00000014u, 0x00060041u, 0x0000002cu, 0x0000002du, + 0x0000002au, 0x00000020u, 0x0000002bu, 0x0004003du, 0x00000010u, 0x0000002eu, 0x0000002du, 0x0004003du, + 0x00000006u, 0x00000033u, 0x00000014u, 0x00060041u, 0x0000002cu, 0x00000034u, 0x00000032u, 0x00000020u, + 0x00000033u, 0x0004003du, 0x00000010u, 0x00000035u, 0x00000034u, 0x00050085u, 0x00000010u, 0x00000036u, + 0x0000002eu, 0x00000035u, 0x0004003du, 0x00000006u, 0x0000003bu, 0x00000014u, 0x00060041u, 0x0000002cu, + 0x0000003cu, 0x0000003au, 0x00000020u, 0x0000003bu, 0x0004003du, 0x00000010u, 0x0000003du, 0x0000003cu, + 0x00050081u, 0x00000010u, 0x0000003eu, 0x00000036u, 0x0000003du, 0x0003003eu, 0x00000026u, 0x0000003eu, + 0x0004003du, 0x00000010u, 0x0000003fu, 0x00000026u, 0x0004003du, 0x00000010u, 0x00000040u, 0x00000026u, + 0x00050085u, 0x00000010u, 0x00000041u, 0x0000003fu, 0x00000040u, 0x0004003du, 0x00000010u, 0x00000042u, + 0x00000012u, 0x00050081u, 0x00000010u, 0x00000043u, 0x00000042u, 0x00000041u, 0x0003003eu, 0x00000012u, + 0x00000043u, 0x000200f9u, 0x00000019u, 0x000200f8u, 0x00000019u, 0x0004003du, 0x00000006u, 0x00000045u, + 0x00000014u, 0x00050080u, 0x00000006u, 0x00000046u, 0x00000045u, 0x00000044u, 0x0003003eu, 0x00000014u, + 0x00000046u, 0x000200f9u, 0x00000016u, 0x000200f8u, 0x00000018u, 0x0004003du, 0x00000006u, 0x0000004au, + 0x00000008u, 0x0004003du, 0x00000010u, 0x0000004bu, 0x00000012u, 0x00050041u, 0x0000004cu, 0x0000004du, + 0x00000049u, 0x0000004au, 0x0003003eu, 0x0000004du, 0x0000004bu, 0x000300e1u, 0x0000004eu, 0x0000004fu, + 0x000400e0u, 0x00000050u, 0x00000050u, 0x0000004fu, 0x0003003eu, 0x00000051u, 0x00000052u, 0x000200f9u, + 0x00000053u, 0x000200f8u, 0x00000053u, 0x000400f6u, 0x00000055u, 0x00000056u, 0x00000000u, 0x000200f9u, + 0x00000057u, 0x000200f8u, 0x00000057u, 0x0004003du, 0x00000006u, 0x00000058u, 0x00000051u, 0x000500acu, + 0x00000024u, 0x00000059u, 0x00000058u, 0x0000000cu, 0x000400fau, 0x00000059u, 0x00000054u, 0x00000055u, + 0x000200f8u, 0x00000054u, 0x0004003du, 0x00000006u, 0x0000005au, 0x00000008u, 0x0004003du, 0x00000006u, + 0x0000005bu, 0x00000051u, 0x000500b0u, 0x00000024u, 0x0000005cu, 0x0000005au, 0x0000005bu, 0x000300f7u, + 0x0000005eu, 0x00000000u, 0x000400fau, 0x0000005cu, 0x0000005du, 0x0000005eu, 0x000200f8u, 0x0000005du, + 0x0004003du, 0x00000006u, 0x0000005fu, 0x00000008u, 0x0004003du, 0x00000006u, 0x00000060u, 0x00000008u, + 0x0004003du, 0x00000006u, 0x00000061u, 0x00000051u, 0x00050080u, 0x00000006u, 0x00000062u, 0x00000060u, + 0x00000061u, 0x00050041u, 0x0000004cu, 0x00000063u, 0x00000049u, 0x00000062u, 0x0004003du, 0x00000010u, + 0x00000064u, 0x00000063u, 0x00050041u, 0x0000004cu, 0x00000065u, 0x00000049u, 0x0000005fu, 0x0004003du, + 0x00000010u, 0x00000066u, 0x00000065u, 0x00050081u, 0x00000010u, 0x00000067u, 0x00000066u, 0x00000064u, + 0x00050041u, 0x0000004cu, 0x00000068u, 0x00000049u, 0x0000005fu, 0x0003003eu, 0x00000068u, 0x00000067u, + 0x000200f9u, 0x0000005eu, 0x000200f8u, 0x0000005eu, 0x000300e1u, 0x0000004eu, 0x0000004fu, 0x000400e0u, + 0x00000050u, 0x00000050u, 0x0000004fu, 0x000200f9u, 0x00000056u, 0x000200f8u, 0x00000056u, 0x0004003du, + 0x00000006u, 0x00000069u, 0x00000051u, 0x000500c2u, 0x00000006u, 0x0000006au, 0x00000069u, 0x0000004eu, + 0x0003003eu, 0x00000051u, 0x0000006au, 0x000200f9u, 0x00000053u, 0x000200f8u, 0x00000055u, 0x00050041u, + 0x0000004cu, 0x0000006cu, 0x00000049u, 0x00000020u, 0x0004003du, 0x00000010u, 0x0000006du, 0x0000006cu, + 0x00050041u, 0x00000021u, 0x0000006eu, 0x0000001eu, 0x00000020u, 0x0004003du, 0x00000006u, 0x0000006fu, + 0x0000006eu, 0x00040070u, 0x00000010u, 0x00000070u, 0x0000006fu, 0x00050088u, 0x00000010u, 0x00000071u, + 0x0000006du, 0x00000070u, 0x00050041u, 0x00000073u, 0x00000074u, 0x0000001eu, 0x00000072u, 0x0004003du, + 0x00000010u, 0x00000075u, 0x00000074u, 0x00050081u, 0x00000010u, 0x00000076u, 0x00000071u, 0x00000075u, + 0x0006000cu, 0x00000010u, 0x00000077u, 0x00000001u, 0x00000020u, 0x00000076u, 0x0003003eu, 0x0000006bu, + 0x00000077u, 0x0004003du, 0x00000006u, 0x00000079u, 0x00000008u, 0x0003003eu, 0x00000078u, 0x00000079u, + 0x000200f9u, 0x0000007au, 0x000200f8u, 0x0000007au, 0x000400f6u, 0x0000007cu, 0x0000007du, 0x00000000u, + 0x000200f9u, 0x0000007eu, 0x000200f8u, 0x0000007eu, 0x0004003du, 0x00000006u, 0x0000007fu, 0x00000078u, + 0x00050041u, 0x00000021u, 0x00000080u, 0x0000001eu, 0x00000020u, 0x0004003du, 0x00000006u, 0x00000081u, + 0x00000080u, 0x000500b0u, 0x00000024u, 0x00000082u, 0x0000007fu, 0x00000081u, 0x000400fau, 0x00000082u, + 0x0000007bu, 0x0000007cu, 0x000200f8u, 0x0000007bu, 0x0004003du, 0x00000006u, 0x00000084u, 0x00000078u, + 0x00060041u, 0x0000002cu, 0x00000085u, 0x0000002au, 0x00000020u, 0x00000084u, 0x0004003du, 0x00000010u, + 0x00000086u, 0x00000085u, 0x0004003du, 0x00000006u, 0x00000087u, 0x00000078u, 0x00060041u, 0x0000002cu, + 0x00000088u, 0x00000032u, 0x00000020u, 0x00000087u, 0x0004003du, 0x00000010u, 0x00000089u, 0x00000088u, + 0x00050085u, 0x00000010u, 0x0000008au, 0x00000086u, 0x00000089u, 0x0004003du, 0x00000006u, 0x0000008bu, + 0x00000078u, 0x00060041u, 0x0000002cu, 0x0000008cu, 0x0000003au, 0x00000020u, 0x0000008bu, 0x0004003du, + 0x00000010u, 0x0000008du, 0x0000008cu, 0x00050081u, 0x00000010u, 0x0000008eu, 0x0000008au, 0x0000008du, + 0x0003003eu, 0x00000083u, 0x0000008eu, 0x0004003du, 0x00000006u, 0x0000008fu, 0x00000078u, 0x0004003du, + 0x00000010u, 0x00000090u, 0x00000083u, 0x0004003du, 0x00000010u, 0x00000091u, 0x0000006bu, 0x00050085u, + 0x00000010u, 0x00000092u, 0x00000090u, 0x00000091u, 0x0004003du, 0x00000006u, 0x00000097u, 0x00000078u, + 0x00060041u, 0x0000002cu, 0x00000098u, 0x00000096u, 0x00000020u, 0x00000097u, 0x0004003du, 0x00000010u, + 0x00000099u, 0x00000098u, 0x00050085u, 0x00000010u, 0x0000009au, 0x00000092u, 0x00000099u, 0x00060041u, + 0x0000002cu, 0x0000009bu, 0x0000003au, 0x00000020u, 0x0000008fu, 0x0003003eu, 0x0000009bu, 0x0000009au, + 0x000200f9u, 0x0000007du, 0x000200f8u, 0x0000007du, 0x0004003du, 0x00000006u, 0x0000009cu, 0x00000078u, + 0x00050080u, 0x00000006u, 0x0000009du, 0x0000009cu, 0x00000044u, 0x0003003eu, 0x00000078u, 0x0000009du, + 0x000200f9u, 0x0000007au, 0x000200f8u, 0x0000007cu, 0x000100fdu, 0x00010038u, +}; + +#endif /* FREESCHED_VOLCANIC_TOKEN_LOOP_SPIRV_H_ */ diff --git a/tools/volcanic_token_loop_util.h b/tools/volcanic_token_loop_util.h new file mode 100644 index 0000000..ee7e5cf --- /dev/null +++ b/tools/volcanic_token_loop_util.h @@ -0,0 +1,1322 @@ +/* + * volcanic_token_loop_util - Clean-room helpers for the multi-layer GPU<->EdgeTPU + * token decode loop benchmark (tools/volcanic_tpu_token_loop_bench.cpp). + * + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Header-only so host unit tests can exercise every helper deterministically: + * - Deterministic xorshift64 PRNG + nearest-rank percentiles + parity. + * - /proc/self/status voluntary/nonvoluntary context-switch sampling with a + * getrusage(RUSAGE_SELF) all-threads companion (and fallback off Linux). + * - On-device power monitor (ODPM) IIO energy_value parsing, rail + * classification (GPU / TPU / all-rails VSYS proxy) and before/after deltas. + * - Inter-IP fence (IIF) abstraction over the google,iif /dev/iif UAPI with + * three runtime backends: + * * FS_IIF_BACKEND_SW_EMULATED: deterministic in-process fence table + * (multi-signaler counting, error propagation, never blocks). + * * FS_IIF_BACKEND_KERNEL: /dev/iif character device driven through + * FS_IIF_CREATE_FENCE (on the node) and FS_IIF_FENCE_SUBMIT_SIGNALER / + * FS_IIF_FENCE_SIGNAL (on the returned IIF fence fd), with per-request + * runtime overrides. The IIF fence fd (anon_inode:iif_file) is + * pollable but is NOT a sync_file: SYNC_IOC_FILE_INFO fails with + * ENOTTY and Vulkan SYNC_FD import rejects it. FS_IIF_FENCE_BRIDGE_DMA + * returns a new, owned sync_file fd whose dma_fence tracks the IIF + * fence; that bridged fd is what GPU queues import. + * * FS_IIF_BACKEND_NONE: graceful runtime detection failure + * (missing node, EACCES, ENOTTY/EINVAL ABI mismatch) -> arm degrades. + * - sync_file handoff verification. Real kernel sync_file fds always run + * SYNC_IOC_FILE_INFO and require status == 1, so an errored producer fence + * (POLLIN with status < 0) is never consumed. Software-mock stand-in fds + * (pipe/eventfd) are a separate mode: poll() readiness only, and the ioctl + * is not issued (Android shell SELinux returns EACCES for it on a pipe). + * - NNAPI TENSOR_QUANT8_ASYMM calibration / quantize / 1x1 CONV_2D reference + * helpers shared by the EdgeTPU NNAPI stage, the GPU bridge shaders and + * the host mock. + * + * IIF UAPI note: request numbers and argument layouts follow the google,iif + * kernel UAPI (ioctl type 'i'); their _IO/_IOR/_IOWR encodings are checked + * with static_asserts on Linux. iif_probe() reports the errno of every step so + * on-device runs confirm the live kernel accepts them before r_iif chains a + * dma_iif_fence into the GPU queue. + */ +#ifndef FREESCHED_VOLCANIC_TOKEN_LOOP_UTIL_H_ +#define FREESCHED_VOLCANIC_TOKEN_LOOP_UTIL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#endif + +namespace fs_tokloop { + +/* ========================================================================= + * Deterministic PRNG & statistics + * ========================================================================= */ + +struct XorShift64 { + uint64_t s; + explicit XorShift64(uint64_t seed) : s(seed ? seed : 0x9E3779B97F4A7C15ull) {} + uint64_t next() { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + return s; + } + /* Uniform in [0, 1) with 53-bit resolution. */ + double uniform() { return static_cast(next() >> 11) * (1.0 / 9007199254740992.0); } + /* Uniform in [-1, 1). */ + float symmetric() { return static_cast(uniform() * 2.0 - 1.0); } +}; + +/* Nearest-rank percentile (p in [0, 100]); returns 0 for empty input. */ +inline double percentile(std::vector v, double p) { + if (v.empty()) return 0.0; + std::sort(v.begin(), v.end()); + if (p <= 0.0) return v.front(); + if (p >= 100.0) return v.back(); + size_t rank = static_cast(std::ceil((p / 100.0) * static_cast(v.size()))); + if (rank == 0u) rank = 1u; + if (rank > v.size()) rank = v.size(); + return v[rank - 1u]; +} + +inline double mean(const std::vector& v) { + if (v.empty()) return 0.0; + double s = 0.0; + for (double x : v) s += x; + return s / static_cast(v.size()); +} + +struct Parity { + double cos; + double max_abs_err; + double rmse; +}; + +/* + * JSON has no inf/nan literals. Parity failures deliberately produce non-finite + * diagnostics (max_abs_err = inf on NaN), so every floating JSON field goes + * through this: finite values use `fmt`, anything else becomes null. + */ +inline std::string json_finite_or_null(double v, const char* fmt = "%.9g") { + if (!std::isfinite(v)) return "null"; + char buf[64]; + const int n = std::snprintf(buf, sizeof(buf), fmt, v); + if (n <= 0 || static_cast(n) >= sizeof(buf)) return "null"; + return std::string(buf); +} + +/* + * Temporary directory usable on host Linux/macOS and on a stock Android shell + * (no /tmp there): $TMPDIR, then /data/local/tmp when writable, then /tmp. + */ +inline std::string fs_temp_dir() { + const char* t = std::getenv("TMPDIR"); + if (t != nullptr && *t != '\0' && access(t, W_OK | X_OK) == 0) return std::string(t); + if (access("/data/local/tmp", W_OK | X_OK) == 0) return "/data/local/tmp"; + return "/tmp"; +} + +inline Parity parity_f32_vs_f64(const float* got, const double* ref, size_t n) { + Parity p{1.0, 0.0, 0.0}; + double dot = 0.0, gg = 0.0, rr = 0.0, se = 0.0, mx = 0.0; + bool nan_seen = false; + for (size_t i = 0u; i < n; ++i) { + const double g = static_cast(got[i]); + const double r = ref[i]; + const double e = std::fabs(g - r); + if (std::isnan(e)) nan_seen = true; + if (e > mx) mx = e; + se += e * e; + dot += g * r; + gg += g * g; + rr += r * r; + } + const double denom = std::sqrt(gg * rr); + p.cos = (denom > 1e-300) ? dot / denom : ((gg == 0.0 && rr == 0.0) ? 1.0 : 0.0); + if (nan_seen || std::isnan(p.cos)) { + p.cos = 0.0; + mx = INFINITY; + } + p.max_abs_err = mx; + p.rmse = (n > 0u) ? std::sqrt(se / static_cast(n)) : 0.0; + return p; +} + +/* ========================================================================= + * CPU context-switch sampling + * ========================================================================= */ + +struct CtxSwitchSample { + int64_t voluntary; /* /proc/self/status voluntary_ctxt_switches (or rusage fallback) */ + int64_t nonvoluntary; /* /proc/self/status nonvoluntary_ctxt_switches (or rusage fallback) */ + int64_t ru_voluntary; /* getrusage(RUSAGE_SELF).ru_nvcsw (all threads) */ + int64_t ru_nonvoluntary; /* getrusage(RUSAGE_SELF).ru_nivcsw (all threads) */ + int from_proc_status; /* 1 if voluntary/nonvoluntary came from /proc/self/status */ +}; + +/* Parses the two ctxt-switch counters out of /proc//status text. */ +inline bool parse_proc_status_ctxt(const char* text, int64_t* out_vol, int64_t* out_nonvol) { + if (!text || !out_vol || !out_nonvol) return false; + static const char kVol[] = "voluntary_ctxt_switches:"; + static const char kNon[] = "nonvoluntary_ctxt_switches:"; + bool have_vol = false, have_non = false; + const char* line = text; + while (*line != '\0') { + if (std::strncmp(line, kVol, sizeof(kVol) - 1u) == 0) { + *out_vol = static_cast(std::strtoll(line + sizeof(kVol) - 1u, nullptr, 10)); + have_vol = true; + } else if (std::strncmp(line, kNon, sizeof(kNon) - 1u) == 0) { + *out_nonvol = static_cast(std::strtoll(line + sizeof(kNon) - 1u, nullptr, 10)); + have_non = true; + } + const char* nl = std::strchr(line, '\n'); + if (!nl) break; + line = nl + 1; + } + return have_vol && have_non; +} + +inline bool read_small_file(const char* path, std::string* out, size_t cap = 65536u) { + out->clear(); + FILE* f = std::fopen(path, "r"); + if (!f) return false; + char buf[4096]; + size_t n = 0u; + while ((n = std::fread(buf, 1u, sizeof(buf), f)) > 0u) { + out->append(buf, n); + if (out->size() >= cap) break; + } + std::fclose(f); + return true; +} + +inline CtxSwitchSample sample_ctx_switches(const char* proc_status_path = "/proc/self/status") { + CtxSwitchSample s{}; + struct rusage ru; + std::memset(&ru, 0, sizeof(ru)); + if (getrusage(RUSAGE_SELF, &ru) == 0) { + s.ru_voluntary = static_cast(ru.ru_nvcsw); + s.ru_nonvoluntary = static_cast(ru.ru_nivcsw); + } + std::string text; + int64_t vol = 0, nonvol = 0; + if (proc_status_path && read_small_file(proc_status_path, &text) && + parse_proc_status_ctxt(text.c_str(), &vol, &nonvol)) { + s.voluntary = vol; + s.nonvoluntary = nonvol; + s.from_proc_status = 1; + } else { + s.voluntary = s.ru_voluntary; + s.nonvoluntary = s.ru_nonvoluntary; + s.from_proc_status = 0; + } + return s; +} + +/* ========================================================================= + * ODPM (IIO on-device power monitor) energy sampling + * ========================================================================= */ + +struct OdpmRail { + std::string name; /* rail name between [] */ + int64_t energy = 0; /* raw accumulated energy counter (default unit: microjoules) */ +}; + +/* One IIO device's energy_value sample. timestamp_ms is the leading `t=` line. */ +struct OdpmReading { + std::string device; /* e.g. "iio:device0" */ + uint64_t timestamp_ms = 0; + bool has_timestamp = false; + std::vector rails; +}; + +using OdpmSnapshot = std::vector; + +enum OdpmClass { ODPM_CLASS_OTHER = 0, ODPM_CLASS_GPU = 1, ODPM_CLASS_TPU = 2 }; + +inline OdpmClass odpm_classify(const std::string& rail_name) { + std::string up(rail_name); + for (char& c : up) c = static_cast(std::toupper(static_cast(c))); + if (up.find("G3D") != std::string::npos || up.find("GPU") != std::string::npos) return ODPM_CLASS_GPU; + if (up.find("TPU") != std::string::npos) return ODPM_CLASS_TPU; + return ODPM_CLASS_OTHER; +} + +/* First line of energy_value: `t=` device snapshot time in milliseconds. */ +inline bool parse_odpm_snapshot_timestamp(const std::string& line, uint64_t* ts) { + if (!ts || line.size() < 3u || line[0] != 't' || line[1] != '=') return false; + const char* num = line.c_str() + 2; + char* endp = nullptr; + errno = 0; + const unsigned long long v = std::strtoull(num, &endp, 10); + if (endp == num || *endp != '\0' || errno == ERANGE) return false; + *ts = static_cast(v); + return true; +} + +/* + * Parses energy_value text into one device reading. + * The first line may be `t=` and is retained as OdpmReading::timestamp_ms. + * Accepted channel line shape: + * CH(T=)[], + */ +inline int parse_odpm_energy_text(const char* text, const char* device, OdpmReading* out) { + if (!text || !out) return 0; + out->device = device ? device : ""; + out->timestamp_ms = 0; + out->has_timestamp = false; + out->rails.clear(); + int added = 0; + bool first = true; + const char* line = text; + while (*line != '\0') { + const char* nl = std::strchr(line, '\n'); + const size_t len = nl ? static_cast(nl - line) : std::strlen(line); + std::string l(line, len); + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (first) { + first = false; + uint64_t ts = 0; + if (parse_odpm_snapshot_timestamp(l, &ts)) { + out->timestamp_ms = ts; + out->has_timestamp = true; + } + } + if (l.size() > 2u && l[0] == 'C' && l[1] == 'H') { + const size_t lb = l.find('['); + const size_t rb = (lb == std::string::npos) ? std::string::npos : l.find(']', lb + 1u); + if (lb != std::string::npos && rb != std::string::npos) { + const size_t comma = l.find(',', rb); + if (comma != std::string::npos) { + char* endp = nullptr; + const char* num = l.c_str() + comma + 1u; + const long long v = std::strtoll(num, &endp, 10); + if (endp != num) { + OdpmRail r; + r.name = l.substr(lb + 1u, rb - lb - 1u); + r.energy = static_cast(v); + out->rails.push_back(r); + ++added; + } + } + } + } + if (!nl) break; + line = nl + 1; + } + return added; +} + +/* Reads /iio:device/energy_value for every IIO device. */ +inline int odpm_read_all(const char* iio_root, OdpmSnapshot* out) { + out->clear(); + if (!iio_root) return 0; + DIR* d = opendir(iio_root); + if (!d) return 0; + std::vector devs; + while (struct dirent* e = readdir(d)) { + if (std::strncmp(e->d_name, "iio:device", 10) == 0) devs.emplace_back(e->d_name); + } + closedir(d); + std::sort(devs.begin(), devs.end()); + int total = 0; + std::string text; + for (const std::string& dev : devs) { + const std::string p = std::string(iio_root) + "/" + dev + "/energy_value"; + OdpmReading reading; + if (read_small_file(p.c_str(), &text)) { + total += parse_odpm_energy_text(text.c_str(), dev.c_str(), &reading); + out->push_back(reading); + } + } + return total; +} + +struct OdpmDelta { + bool available; + int rails; + double gpu_j; + double tpu_j; + double total_j; /* sum over every measured rail (VSYS-side proxy) */ + int gpu_rails; + int tpu_rails; +}; + +inline OdpmDelta odpm_delta(const OdpmSnapshot& before, const OdpmSnapshot& after, double unit_to_joule) { + OdpmDelta dl{}; + bool any_stale = false, gpu_stale = false, tpu_stale = false; + for (const OdpmReading& a : after) { + const OdpmReading* bdev = nullptr; + for (const OdpmReading& b : before) { + if (a.device == b.device) { + bdev = &b; + break; + } + } + if (!bdev) continue; + /* A repeated or missing `t=` means the driver handed back a cached sample. */ + const bool stale = !a.has_timestamp || !bdev->has_timestamp || a.timestamp_ms <= bdev->timestamp_ms; + for (const OdpmRail& ar : a.rails) { + const OdpmRail* br = nullptr; + for (const OdpmRail& b : bdev->rails) { + if (ar.name == b.name) { + br = &b; + break; + } + } + if (!br) continue; + dl.rails += 1; + const OdpmClass cls = odpm_classify(ar.name); + if (stale) { + any_stale = true; + if (cls == ODPM_CLASS_GPU) { + gpu_stale = true; + dl.gpu_rails += 1; + } else if (cls == ODPM_CLASS_TPU) { + tpu_stale = true; + dl.tpu_rails += 1; + } + continue; + } + const double j = static_cast(ar.energy - br->energy) * unit_to_joule; + dl.total_j += j; + switch (cls) { + case ODPM_CLASS_GPU: + dl.gpu_j += j; + dl.gpu_rails += 1; + break; + case ODPM_CLASS_TPU: + dl.tpu_j += j; + dl.tpu_rails += 1; + break; + default: + break; + } + } + } + if (gpu_stale) dl.gpu_j = std::numeric_limits::quiet_NaN(); + if (tpu_stale) dl.tpu_j = std::numeric_limits::quiet_NaN(); + if (any_stale) dl.total_j = std::numeric_limits::quiet_NaN(); + dl.available = dl.rails > 0; + return dl; +} + +/* ========================================================================= + * sync_file handoff verification (poll readiness + SYNC_IOC_FILE_INFO.status) + * ========================================================================= */ + +/* + * Linux reports POLLIN on a sync_file once its fence signals, including when + * the fence signaled WITH an error (dma_fence_set_error before signaling). A + * readable sync_file is therefore not a successful handoff by itself: the + * consumer must also read SYNC_IOC_FILE_INFO and require status == 1 + * (signaled without error). status == 0 means still active, status < 0 is the + * propagated fence error (-EIO, -ECANCELED, ...). + * + * struct sync_file_info (include/uapi/linux/sync_file.h) is 56 bytes on every + * ABI, so SYNC_IOC_FILE_INFO = _IOWR('>', 4, struct sync_file_info) = 0xc0383e04. + */ +struct fs_sync_file_info { + char name[32]; + int32_t status; + uint32_t flags; + uint32_t num_fences; + uint32_t pad; + uint64_t sync_fence_info; +}; +static_assert(sizeof(struct fs_sync_file_info) == 56u, "sync_file_info layout"); +#define FS_SYNC_IOC_FILE_INFO \ + ((3UL << 30) | (static_cast(sizeof(struct fs_sync_file_info)) << 16) | \ + (static_cast('>') << 8) | 4UL) +#if defined(__linux__) +static_assert(FS_SYNC_IOC_FILE_INFO == static_cast(_IOWR('>', 4, struct fs_sync_file_info)), + "SYNC_IOC_FILE_INFO encoding"); +#endif +static_assert(FS_SYNC_IOC_FILE_INFO == 0xc0383e04UL, "SYNC_IOC_FILE_INFO == 0xc0383e04"); + +/* + * What kind of fd a handoff waits on. The mode is explicit: never infer a + * stand-in from errno (SYNC_IOC_FILE_INFO on a pipe is ENOTTY/EINVAL on desktop + * Linux and EACCES under Android shell SELinux). + * - SYNC_FD_KERNEL_SYNC_FILE: Vulkan SYNC_FD exports, DMA_BUF_IOCTL_EXPORT_SYNC_FILE, + * NNAPI completion fences, FS_IIF_FENCE_BRIDGE_DMA bridges. The wait ALWAYS + * runs SYNC_IOC_FILE_INFO and requires status == 1. + * - SYNC_FD_MOCK_NON_SYNC_FILE: stand-in fds the software mock created (pipe or + * eventfd). poll() readiness only; SYNC_IOC_FILE_INFO is not issued. + */ +enum SyncFdMode { SYNC_FD_KERNEL_SYNC_FILE = 0, SYNC_FD_MOCK_NON_SYNC_FILE = 1 }; + +/* SYNC_IOC_FILE_INFO on fd: returns 0 and *status, or the errno (ENOTTY/EINVAL for a non-sync_file). */ +inline int sync_file_query_status(int fd, int32_t* status) { + *status = 0; +#if defined(__linux__) + if (fd < 0) return EBADF; + struct fs_sync_file_info info; + std::memset(&info, 0, sizeof(info)); /* num_fences = 0: count only; flags/pad must be 0 */ + int rc = 0; + do { + errno = 0; + rc = ioctl(fd, FS_SYNC_IOC_FILE_INFO, &info); + } while (rc != 0 && errno == EINTR); + if (rc != 0) return errno ? errno : EIO; + *status = info.status; + return 0; +#else + (void)fd; + return ENOTTY; +#endif +} + +/* + * Pure verdict of one handoff wait (unit-testable): poll() result + revents, + * then (kernel sync_files only) the SYNC_IOC_FILE_INFO result and status. + * Mock stand-ins ignore info_err/status: the caller did not issue the ioctl. + * Returns true only for a cleanly signaled producer fence; *why names the reason. + */ +inline bool sync_handoff_verdict(int poll_rc, int revents, int info_err, int32_t status, SyncFdMode mode, + const char** why) { + const char* w = "ok"; + bool ok = false; + const int bad = POLLERR | POLLNVAL; + const int in = POLLIN; + if (poll_rc == 0) { + w = "timeout"; + } else if (poll_rc < 0) { + w = "poll_failed"; + } else if ((revents & bad) != 0) { + w = "poll_err_or_nval"; + } else if ((revents & in) == 0) { + w = "not_readable"; + } else if (mode == SYNC_FD_MOCK_NON_SYNC_FILE) { + (void)info_err; + (void)status; + ok = true; + w = "ok_mock_poll_only"; + } else if (info_err == 0) { + if (status == 1) { + ok = true; + } else if (status < 0) { + w = "fence_error_status"; + } else { + w = "fence_unsignaled_status"; + } + } else if (info_err == ENOTTY || info_err == EINVAL) { + w = "not_a_sync_file"; + } else { + w = "sync_file_info_failed"; + } + if (why) *why = w; + return ok; +} + +/* + * Waits for a producer fence fd and verifies it before the consumer touches the + * buffer. Kernel sync_files: poll(POLLIN) without POLLERR/POLLNVAL, then + * SYNC_IOC_FILE_INFO.status == 1 (the ioctl always runs once poll returns). + * Mock stand-ins: poll() readiness only; SYNC_IOC_FILE_INFO is not called. + * fd < 0 means "already signaled" (Vulkan SYNC_FD export of a completed payload). + * *out_status (optional) receives the sync_file status, or 0 if not queried. + */ +inline bool sync_fd_wait_handoff(int fd, int timeout_ms, SyncFdMode mode, const char** why = nullptr, + int32_t* out_status = nullptr) { + if (out_status) *out_status = 0; + if (fd < 0) { + if (why) *why = "ok_no_fence"; + return true; + } +#if defined(__linux__) + struct pollfd pfd; + std::memset(&pfd, 0, sizeof(pfd)); + pfd.fd = fd; + pfd.events = POLLIN; + int rc = 0; + do { + rc = poll(&pfd, 1, timeout_ms); + } while (rc < 0 && errno == EINTR); + if (mode == SYNC_FD_MOCK_NON_SYNC_FILE) { + return sync_handoff_verdict(rc, pfd.revents, 0, 0, mode, why); + } + int32_t status = 0; + const int info_err = (rc > 0) ? sync_file_query_status(fd, &status) : 0; + if (out_status) *out_status = status; + return sync_handoff_verdict(rc, pfd.revents, info_err, status, mode, why); +#else + (void)timeout_ms; + (void)mode; + if (why) *why = "unsupported_os"; + return false; +#endif +} + +/* ========================================================================= + * Inter-IP fence (IIF): google,iif /dev/iif UAPI + runtime backends + * ========================================================================= */ + +/* + * Signaler IP identifiers (iif_ip_type order: DSP, TPU, GPU, AP). The AP (CPU) + * id is the one this userspace benchmark signals from; the others label the + * producing IP in the software emulator and remain runtime-overridable. + */ +#define FS_IIF_IP_DSP 0 +#define FS_IIF_IP_TPU 1 +#define FS_IIF_IP_GPU 2 +#define FS_IIF_IP_AP 3 + +/* FS_IIF_CREATE_FENCE argument (issued on the /dev/iif node). */ +struct fs_iif_create_fence_ioctl { + uint8_t signaler_ip; /* in: FS_IIF_IP_* of the signaling IP */ + uint8_t pad; /* in: must be 0 */ + uint16_t total_signalers; /* in: number of signals required to retire */ + int32_t fence_fd; /* out: IIF fence fd (pollable, not a sync_file) */ +}; + +/* FS_IIF_FENCE_SIGNAL argument (issued on the returned fence fd). */ +struct fs_iif_fence_signal_ioctl { + int32_t error; /* in: 0 = success, negative errno propagates to waiters */ + uint16_t remaining_signalers; /* out: signals still outstanding after this one */ + uint16_t pad; +}; + +static_assert(sizeof(struct fs_iif_create_fence_ioctl) == 8u, "IIF create ioctl arg must be 8 bytes"); +static_assert(sizeof(struct fs_iif_fence_signal_ioctl) == 8u, "IIF signal ioctl arg must be 8 bytes"); + +/* google,iif UAPI request numbers (ioctl type 'i'). */ +#define FS_IIF_CREATE_FENCE 0xc0086900UL /* _IOWR('i', 0x00, 8) on /dev/iif */ +#define FS_IIF_FENCE_SUBMIT_SIGNALER 0x00006981UL /* _IO('i', 0x81) on fence_fd */ +#define FS_IIF_FENCE_SIGNAL 0xc0086982UL /* _IOWR('i', 0x82, 8) on fence_fd */ +#define FS_IIF_FENCE_BRIDGE_DMA 0x80046985UL /* _IOR('i', 0x85, 4) on fence_fd / bridge fd */ +#define FS_IIF_FENCE_SIGNALER_DONE 0x00006986UL /* _IO('i', 0x86) on fence_fd */ + +#if defined(__linux__) +static_assert(FS_IIF_CREATE_FENCE == static_cast(_IOWR('i', 0x00, struct fs_iif_create_fence_ioctl)), + "FS_IIF_CREATE_FENCE encoding"); +static_assert(FS_IIF_FENCE_SUBMIT_SIGNALER == static_cast(_IO('i', 0x81)), + "FS_IIF_FENCE_SUBMIT_SIGNALER encoding"); +static_assert(FS_IIF_FENCE_SIGNAL == static_cast(_IOWR('i', 0x82, struct fs_iif_fence_signal_ioctl)), + "FS_IIF_FENCE_SIGNAL encoding"); +static_assert(FS_IIF_FENCE_BRIDGE_DMA == static_cast(_IOR('i', 0x85, uint32_t)), + "FS_IIF_FENCE_BRIDGE_DMA encoding"); +static_assert(FS_IIF_FENCE_SIGNALER_DONE == static_cast(_IO('i', 0x86)), + "FS_IIF_FENCE_SIGNALER_DONE encoding"); +#endif + +struct IifAbi { + unsigned long create_req; + unsigned long submit_signaler_req; + unsigned long signal_req; + unsigned long bridge_dma_req; + unsigned long signaler_done_req; +}; + +inline IifAbi iif_default_abi() { + IifAbi a{}; + a.create_req = FS_IIF_CREATE_FENCE; + a.submit_signaler_req = FS_IIF_FENCE_SUBMIT_SIGNALER; + a.signal_req = FS_IIF_FENCE_SIGNAL; + a.bridge_dma_req = FS_IIF_FENCE_BRIDGE_DMA; + a.signaler_done_req = FS_IIF_FENCE_SIGNALER_DONE; + return a; +} + +enum IifBackendKind { + FS_IIF_BACKEND_NONE = 0, + FS_IIF_BACKEND_SW_EMULATED = 1, + FS_IIF_BACKEND_KERNEL = 2 +}; + +inline const char* iif_backend_name(IifBackendKind k) { + switch (k) { + case FS_IIF_BACKEND_SW_EMULATED: return "sw_emulated"; + case FS_IIF_BACKEND_KERNEL: return "kernel"; + default: return "none"; + } +} + +/* + * --require-iif gate. Met only when the r_iif arm ran AND actually created IIF + * fences (r_iif_fences = the arm's measured TokenCounters::iif_fences). On live + * silicon those fences must come from the kernel /dev/iif backend: a live + * --iif-sw-fallback run whose zero-copy chain used plain sync fences (0 kernel + * IIF fences) must not pass. Mock runs exercise the software emulator by design. + */ +inline bool iif_requirement_met(bool live, bool r_iif_ran, IifBackendKind backend, uint64_t r_iif_fences) { + if (!r_iif_ran || r_iif_fences == 0u) return false; + return live ? backend == FS_IIF_BACKEND_KERNEL : backend != FS_IIF_BACKEND_NONE; +} + +/* + * Raw IIF fences (create -> submit -> signal -> poll) are enough for the CPU-proxy + * r_iif handoffs, so any initialized backend keeps that arm available. + */ +inline bool iif_cpu_proxy_available(IifBackendKind backend) { return backend != FS_IIF_BACKEND_NONE; } + +/* + * The NNAPI r_iif chain imports its AP-signaled IIF gate into a Vulkan queue. + * The raw IIF fd is not a sync_file, so the gate needs FS_IIF_FENCE_BRIDGE_DMA + * to return a sync_file that signals with the IIF fence (IifProbe::bridge_dma_ok). + * Older Google IIF drivers expose create/submit/signal/poll without the bridge: + * there the NNAPI arm runs the ungated sync-fence chain, records 0 IIF fences + * and therefore still fails --require-iif. + */ +inline bool iif_nnapi_gate_enabled(IifBackendKind backend, bool bridge_dma_ok) { + return backend == FS_IIF_BACKEND_KERNEL && bridge_dma_ok; +} + +/* Return codes of IifFences operations (0 == OK). */ +enum IifRc { + IIF_OK = 0, + IIF_ERR_ARG = -1, + IIF_ERR_STATE = -2, /* over-signal, or backend not initialized */ + IIF_ERR_TIMEOUT = -3, /* waited on an unsignaled fence */ + IIF_ERR_FENCE = -4, /* fence retired with a propagated error */ + IIF_ERR_SYS = -5 /* kernel call failed (see last_errno) */ +}; + +/* + * Fence lifetime rule (kernel backend): an IIF fence fd that was imported into + * a GPU queue (e.g. as a Vulkan SYNC_FD wait semaphore, which the PowerVR + * kernel driver resolves to a firmware IIF handle) must be signaled and the + * GPU queue drained before destroy() closes it. Callers own that ordering; + * destroy() never signals implicitly. + */ +class IifFences { + public: + IifFences() = default; + ~IifFences() { shutdown(); } + IifFences(const IifFences&) = delete; + IifFences& operator=(const IifFences&) = delete; + + void init_sw() { + shutdown(); + kind_ = FS_IIF_BACKEND_SW_EMULATED; + } + +#if defined(__linux__) + /* Takes ownership of an already-opened /dev/iif fd. */ + void init_kernel(int dev_fd, const IifAbi& abi) { + shutdown(); + kind_ = FS_IIF_BACKEND_KERNEL; + dev_fd_ = dev_fd; + abi_ = abi; + } +#endif + + IifBackendKind kind() const { return kind_; } + const IifAbi& abi() const { return abi_; } + int last_errno() const { return last_errno_; } + uint64_t created() const { return created_; } + uint64_t submitted() const { return submitted_; } + uint64_t signaled() const { return signaled_; } + uint64_t waited() const { return waited_; } + uint32_t last_remaining() const { return last_remaining_; } + /* Fences created and not yet destroy()ed (kernel fds still open / live sw entries). */ + uint64_t outstanding() const { return created_ - destroyed_; } + size_t live_count() const { + size_t n = 0u; + for (const SwFence& f : sw_) n += f.live ? 1u : 0u; + return n; + } + + /* FS_IIF_CREATE_FENCE: returns a pollable IIF fence fd (kernel) or table index (sw). */ + int create(uint32_t signaler_ip, uint32_t total_signalers, int* out_handle) { + if (!out_handle || total_signalers == 0u || total_signalers > 0xFFFFu || signaler_ip > 0xFFu) { + return IIF_ERR_ARG; + } + *out_handle = -1; + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) { + size_t idx = sw_.size(); + for (size_t i = 0u; i < sw_.size(); ++i) { + if (!sw_[i].live) { + idx = i; + break; + } + } + if (idx == sw_.size()) sw_.push_back(SwFence{}); + SwFence& f = sw_[idx]; + f.live = true; + f.signaler_ip = signaler_ip; + f.total = total_signalers; + f.submitted = 0u; + f.done = 0u; + f.error = 0; + *out_handle = static_cast(idx); + ++created_; + return IIF_OK; + } +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + fs_iif_create_fence_ioctl req; + std::memset(&req, 0, sizeof(req)); + req.signaler_ip = static_cast(signaler_ip); + req.total_signalers = static_cast(total_signalers); + req.fence_fd = -1; + errno = 0; + if (ioctl(dev_fd_, abi_.create_req, &req) != 0 || req.fence_fd < 0) { + last_errno_ = errno ? errno : EBADF; + return IIF_ERR_SYS; + } + *out_handle = req.fence_fd; + ++created_; + return IIF_OK; + } +#endif + return IIF_ERR_STATE; + } + + /* FS_IIF_FENCE_SUBMIT_SIGNALER: the signaler commits to signaling this fence. */ + int submit_signaler(int handle) { + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) { + SwFence* f = sw_get(handle); + if (!f) return IIF_ERR_ARG; + if (f->submitted >= f->total) return IIF_ERR_STATE; + f->submitted += 1u; + ++submitted_; + return IIF_OK; + } +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + if (handle < 0) return IIF_ERR_ARG; + errno = 0; + if (ioctl(handle, abi_.submit_signaler_req) != 0) { + last_errno_ = errno ? errno : EIO; + return IIF_ERR_SYS; + } + ++submitted_; + return IIF_OK; + } +#endif + return IIF_ERR_STATE; + } + + /* FS_IIF_FENCE_SIGNAL: one signaler completes (error != 0 propagates to waiters). */ + int signal(int handle, int32_t error = 0) { + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) { + SwFence* f = sw_get(handle); + if (!f) return IIF_ERR_ARG; + if (f->done >= f->total) return IIF_ERR_STATE; + f->done += 1u; + if (error != 0 && f->error == 0) f->error = error; + last_remaining_ = f->total - f->done; + ++signaled_; + return IIF_OK; + } +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + if (handle < 0) return IIF_ERR_ARG; + fs_iif_fence_signal_ioctl req; + std::memset(&req, 0, sizeof(req)); + req.error = error; + errno = 0; + if (ioctl(handle, abi_.signal_req, &req) != 0) { + last_errno_ = errno ? errno : EIO; + return IIF_ERR_SYS; + } + last_remaining_ = req.remaining_signalers; + ++signaled_; + return IIF_OK; + } +#endif + return IIF_ERR_STATE; + } + + /* + * Waits for all signalers. Kernel IIF fence fds are pollable, so this is + * a plain poll(POLLIN) (used by the probe and CPU-proxy arms only; the r_iif + * GPU<->TPU chain never calls it). The software backend never blocks. + */ + int wait(int handle, uint32_t timeout_ms) { + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) { + (void)timeout_ms; + SwFence* f = sw_get(handle); + if (!f) return IIF_ERR_ARG; + if (f->done < f->total) return IIF_ERR_TIMEOUT; + ++waited_; + return (f->error != 0) ? IIF_ERR_FENCE : IIF_OK; + } +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + if (handle < 0) return IIF_ERR_ARG; + struct pollfd pfd; + std::memset(&pfd, 0, sizeof(pfd)); + pfd.fd = handle; + pfd.events = POLLIN; + int prc = 0; + do { + prc = poll(&pfd, 1, static_cast(timeout_ms)); + } while (prc < 0 && errno == EINTR); + if (prc == 0) return IIF_ERR_TIMEOUT; + if (prc < 0 || (pfd.revents & POLLNVAL) != 0) { + last_errno_ = (prc < 0 && errno) ? errno : EBADF; + return IIF_ERR_SYS; + } + ++waited_; + return ((pfd.revents & POLLERR) != 0) ? IIF_ERR_FENCE : IIF_OK; + } +#endif + return IIF_ERR_STATE; + } + + /* + * FS_IIF_FENCE_BRIDGE_DMA (_IOR 4 bytes) on a fence fd. On the kernel backend + * the returned value is a new, caller-owned sync_file fd bridging the IIF + * fence to a dma_fence (see bridge_sync_file()). + */ + int bridge_dma(int handle, uint32_t* out_val) { + if (!out_val) return IIF_ERR_ARG; + *out_val = 0u; + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) return sw_get(handle) ? IIF_OK : IIF_ERR_ARG; +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + if (handle < 0) return IIF_ERR_ARG; + uint32_t v = 0u; + errno = 0; + if (ioctl(handle, abi_.bridge_dma_req, &v) != 0) { + last_errno_ = errno ? errno : EIO; + return IIF_ERR_SYS; + } + *out_val = v; + return IIF_OK; + } +#endif + return IIF_ERR_STATE; + } + + /* + * Bridges a kernel IIF fence to an owned sync_file fd (Vulkan SYNC_FD / + * NNAPI importable). The result is validated with SYNC_IOC_FILE_INFO; a + * non-sync_file result is closed and reported as ENOTTY. Software fences + * have no fd representation (IIF_ERR_STATE). + */ + int bridge_sync_file(int handle, int* out_fd) { + if (!out_fd) return IIF_ERR_ARG; + *out_fd = -1; +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + uint32_t v = 0u; + const int rc = bridge_dma(handle, &v); + if (rc != IIF_OK) return rc; + const int fd = static_cast(v); + if (fd < 0 || !fd_is_sync_file(fd)) { + if (fd >= 0) close(fd); + last_errno_ = ENOTTY; + return IIF_ERR_SYS; + } + *out_fd = fd; + return IIF_OK; + } +#endif + (void)handle; + return IIF_ERR_STATE; + } + + /* True if fd answers SYNC_IOC_FILE_INFO (i.e. it is a sync_file). */ + static bool fd_is_sync_file(int fd) { + int32_t status = 0; + return fd >= 0 && sync_file_query_status(fd, &status) == 0; + } + + /* FS_IIF_FENCE_SIGNALER_DONE (_IO) on a fence fd. */ + int signaler_done(int handle) { + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) return sw_get(handle) ? IIF_OK : IIF_ERR_ARG; +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL) { + if (handle < 0) return IIF_ERR_ARG; + errno = 0; + if (ioctl(handle, abi_.signaler_done_req) != 0) { + last_errno_ = errno ? errno : EIO; + return IIF_ERR_SYS; + } + return IIF_OK; + } +#endif + return IIF_ERR_STATE; + } + + /* Closes the fence handle. See the fence lifetime rule above. */ + void destroy(int handle) { + if (kind_ == FS_IIF_BACKEND_SW_EMULATED) { + SwFence* f = sw_get(handle); + if (f) { + f->live = false; + ++destroyed_; + } + return; + } +#if defined(__linux__) + if (kind_ == FS_IIF_BACKEND_KERNEL && handle >= 0) { + close(handle); + ++destroyed_; + } +#endif + } + + void shutdown() { +#if defined(__linux__) + if (dev_fd_ >= 0) close(dev_fd_); +#endif + dev_fd_ = -1; + sw_.clear(); + kind_ = FS_IIF_BACKEND_NONE; + destroyed_ = created_; /* backend torn down: nothing of it is outstanding */ + } + + private: + struct SwFence { + bool live = false; + uint32_t signaler_ip = 0u; + uint32_t total = 0u; + uint32_t submitted = 0u; + uint32_t done = 0u; + int32_t error = 0; + }; + SwFence* sw_get(int handle) { + if (handle < 0 || static_cast(handle) >= sw_.size() || + !sw_[static_cast(handle)].live) { + return nullptr; + } + return &sw_[static_cast(handle)]; + } + + IifBackendKind kind_ = FS_IIF_BACKEND_NONE; + int dev_fd_ = -1; + IifAbi abi_ = iif_default_abi(); + std::vector sw_; + int last_errno_ = 0; + uint32_t last_remaining_ = 0u; + uint64_t created_ = 0u; + uint64_t destroyed_ = 0u; + uint64_t submitted_ = 0u; + uint64_t signaled_ = 0u; + uint64_t waited_ = 0u; +}; + +struct IifProbe { + bool probed; /* false: the node was never opened (e.g. --mock uses the software backend) */ + bool node_present; /* open reached the node (any errno other than ENOENT/ENOTDIR) */ + bool opened; /* open(O_RDWR) succeeded */ + bool create_ok; + bool submit_ok; + bool signal_ok; + bool wait_ok; + bool usable; /* full create -> submit -> signal -> poll round trip succeeded */ + int open_errno; + int create_errno; + int submit_errno; + int signal_errno; + int wait_errno; + uint32_t remaining_after_signal; + bool fence_is_sync_file; /* the raw IIF fence fd answers SYNC_IOC_FILE_INFO */ + bool bridge_ok; /* FS_IIF_FENCE_BRIDGE_DMA returned a sync_file fd */ + bool bridge_signaled; /* bridged sync_file became readable after the IIF signal */ + bool bridge_dma_ok; /* bridge_ok && bridge_signaled: a GPU queue can wait on the IIF fence */ + int bridge_errno; + const char* reason; /* short machine-readable reason */ +}; + +inline const char* iif_errno_reason(int e) { + switch (e) { + case 0: return "ok"; + case ENOENT: return "ENOENT"; + case ENOTDIR: return "ENOTDIR"; + case EACCES: return "EACCES"; + case EPERM: return "EPERM"; + case ENOTTY: return "ENOTTY_abi_mismatch"; + case EINVAL: return "EINVAL_abi_mismatch"; + case EFAULT: return "EFAULT_abi_mismatch"; + case ENODEV: return "ENODEV"; + case EBUSY: return "EBUSY"; + case ETIMEDOUT: return "ETIMEDOUT"; + default: return "errno"; + } +} + +/* + * Probes the IIF node with a full FS_IIF_CREATE_FENCE(signaler_ip, 1) -> + * FS_IIF_FENCE_SUBMIT_SIGNALER -> FS_IIF_FENCE_SIGNAL -> poll(POLLIN) -> close + * round trip. The probe fence is never imported anywhere, so closing it after + * the signal is always safe. If `keep` is non-null and the probe succeeds, a + * fresh device fd is handed to `keep` (kernel backend). + */ +/* open(2) calls this process made on an IIF device node (iif_probe() is the only opener). */ +inline uint64_t& iif_dev_open_calls() { + static uint64_t n = 0u; + return n; +} + +/* A probe that never touched the node: `reason` says why (e.g. "not_probed_mock"). */ +inline IifProbe iif_probe_not_run(const char* reason) { + IifProbe p{}; + p.probed = false; + p.reason = reason; + return p; +} + +inline IifProbe iif_probe(const char* dev_path, const IifAbi& abi, uint32_t signaler_ip, IifFences* keep) { + IifProbe p{}; + p.probed = true; + p.reason = "unsupported_os"; +#if defined(__linux__) + if (dev_path != nullptr) ++iif_dev_open_calls(); + const int fd = (dev_path != nullptr) ? open(dev_path, O_RDWR | O_CLOEXEC) : -1; + if (fd < 0) { + p.open_errno = (dev_path != nullptr) ? errno : ENOENT; + p.node_present = (p.open_errno != ENOENT && p.open_errno != ENOTDIR); + p.reason = iif_errno_reason(p.open_errno); + return p; + } + p.node_present = true; + p.opened = true; + IifFences f; + f.init_kernel(fd, abi); + int h = -1; + if (f.create(signaler_ip, 1u, &h) != IIF_OK) { + p.create_errno = f.last_errno(); + p.reason = iif_errno_reason(p.create_errno); + return p; /* f closes fd */ + } + p.create_ok = true; + if (f.submit_signaler(h) != IIF_OK) { + p.submit_errno = f.last_errno(); + p.reason = iif_errno_reason(p.submit_errno); + f.destroy(h); /* never imported: safe to close unsignaled */ + return p; + } + p.submit_ok = true; + p.fence_is_sync_file = IifFences::fd_is_sync_file(h); + int bfd = -1; + if (f.bridge_sync_file(h, &bfd) == IIF_OK) { + p.bridge_ok = true; + } else { + p.bridge_errno = f.last_errno(); + } + if (f.signal(h, 0) != IIF_OK) { + p.signal_errno = f.last_errno(); + p.reason = iif_errno_reason(p.signal_errno); + if (bfd >= 0) close(bfd); + f.destroy(h); + return p; + } + if (bfd >= 0) { + struct pollfd bp{}; + bp.fd = bfd; + bp.events = POLLIN; + p.bridge_signaled = poll(&bp, 1, 1000) == 1 && (bp.revents & POLLIN) != 0; + close(bfd); + } + /* + * Recorded separately from `usable`: raw IIF (create/submit/signal/poll) is + * enough for CPU-proxy handoffs; only the Vulkan-imported gate needs the bridge. + */ + p.bridge_dma_ok = p.bridge_ok && p.bridge_signaled; + p.signal_ok = true; + p.remaining_after_signal = f.last_remaining(); + const int wrc = f.wait(h, 1000u); + f.destroy(h); + if (wrc != IIF_OK) { + p.wait_errno = (wrc == IIF_ERR_TIMEOUT) ? ETIMEDOUT : (wrc == IIF_ERR_FENCE ? EIO : f.last_errno()); + p.reason = iif_errno_reason(p.wait_errno); + return p; + } + p.wait_ok = true; + p.usable = true; + p.reason = "ok"; + if (keep) { + ++iif_dev_open_calls(); + const int fd2 = open(dev_path, O_RDWR | O_CLOEXEC); + if (fd2 >= 0) { + keep->init_kernel(fd2, abi); + } else { + p.usable = false; + p.reason = iif_errno_reason(errno); + } + } +#else + (void)dev_path; + (void)abi; + (void)signaler_ip; + (void)keep; +#endif + return p; +} + +/* ========================================================================= + * NNAPI TENSOR_QUANT8_ASYMM helpers (EdgeTPU 1x1 CONV_2D FFN stage) + * ========================================================================= */ + +/* Asymmetric uint8 quantization parameters (real = (q - zero_point) * scale). */ +struct Quant8 { + float scale = 1.0f; + int32_t zero_point = 128; +}; + +/* Symmetric-range calibration: |x| <= absmax maps onto [1, 255] around zp 128. */ +inline Quant8 quant8_from_absmax(double absmax, double margin = 1.05) { + Quant8 q; + const double a = (absmax > 1e-12 ? absmax : 1e-12) * margin; + q.scale = static_cast(a / 127.0); + q.zero_point = 128; + return q; +} + +/* Matches the GPU bridge shader: clamp(roundEven(v * inv_scale) + zp, 0, 255). */ +inline uint8_t quant8_quantize(float v, float inv_scale, int32_t zp) { + const float q = std::nearbyint(v * inv_scale) + static_cast(zp); + const float c = q < 0.0f ? 0.0f : (q > 255.0f ? 255.0f : q); + return static_cast(c); +} + +inline float quant8_dequantize(uint8_t q, float scale, int32_t zp) { + return (static_cast(q) - static_cast(zp)) * scale; +} + +/* + * Reference for the NNAPI QUANT8_ASYMM 1x1 CONV_2D used on the EdgeTPU: + * input [1,1,1,d] (in), filter [d,1,1,d] = int8 weight + 128 with scale 1 and + * zero point 128 (so the real filter value is exactly the int8 weight), zero + * int32 bias, output [1,1,1,d] (out). Accumulates in int32 like the hardware. + */ +inline void quant8_conv1x1_ref(const uint8_t* qin, const Quant8& in, const int8_t* w, uint32_t d, + const Quant8& out, uint8_t* qout) { + const double mult = static_cast(in.scale) / static_cast(out.scale); + for (uint32_t n = 0u; n < d; ++n) { + int64_t acc = 0; + const int8_t* row = w + static_cast(n) * d; + for (uint32_t k = 0u; k < d; ++k) { + acc += static_cast(row[k]) * (static_cast(qin[k]) - in.zero_point); + } + const double r = std::nearbyint(static_cast(acc) * mult) + static_cast(out.zero_point); + qout[n] = static_cast(r < 0.0 ? 0.0 : (r > 255.0 ? 255.0 : r)); + } +} + +/* + * JSON string value: quoted, with '"' and '\\' backslash-escaped and every + * control character (< 0x20) emitted as \u00XX. Every string the token-loop + * bench prints into JSON (including caller-supplied paths) goes through this. + */ +inline std::string json_escape(const std::string& s) { + std::string o; + o.reserve(s.size() + 2u); + o.push_back('"'); + for (char ch : s) { + const unsigned char u = static_cast(ch); + if (ch == '"' || ch == '\\') { + o.push_back('\\'); + o.push_back(ch); + } else if (u < 0x20u) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(u)); + o += buf; + } else { + o.push_back(ch); + } + } + o.push_back('"'); + return o; +} + +/* The --iif-probe-only / "iif.probe" JSON object; dev and reason are escaped. */ +inline std::string iif_probe_json(const char* dev, const IifProbe& p, const IifAbi& abi) { + auto tf = [](bool v) { return v ? "true" : "false"; }; + char mid[1024]; + std::snprintf(mid, sizeof(mid), + ",\"probed\":%s,\"node_present\":%s,\"opened\":%s,\"create_ok\":%s,\"submit_ok\":%s,\"signal_ok\":%s," + "\"wait_ok\":%s,\"usable\":%s,\"open_errno\":%d,\"create_errno\":%d,\"submit_errno\":%d," + "\"signal_errno\":%d,\"wait_errno\":%d,\"remaining_after_signal\":%u,\"fence_is_sync_file\":%s," + "\"bridge_sync_file_ok\":%s,\"bridge_signaled\":%s,\"bridge_dma_ok\":%s,\"bridge_errno\":%d," + "\"reason\":", + tf(p.probed), tf(p.node_present), tf(p.opened), tf(p.create_ok), tf(p.submit_ok), tf(p.signal_ok), tf(p.wait_ok), + tf(p.usable), p.open_errno, p.create_errno, p.submit_errno, p.signal_errno, p.wait_errno, + static_cast(p.remaining_after_signal), tf(p.fence_is_sync_file), tf(p.bridge_ok), + tf(p.bridge_signaled), tf(p.bridge_dma_ok), p.bridge_errno); + char tail[512]; + std::snprintf(tail, sizeof(tail), + ",\"abi\":\"google-iif-uapi\",\"ioctl_create\":\"0x%lx\",\"ioctl_submit_signaler\":\"0x%lx\"," + "\"ioctl_signal\":\"0x%lx\",\"ioctl_bridge_dma\":\"0x%lx\",\"ioctl_signaler_done\":\"0x%lx\"}", + abi.create_req, abi.submit_signaler_req, abi.signal_req, abi.bridge_dma_req, abi.signaler_done_req); + return "{\"dev\":" + json_escape(dev ? dev : "") + mid + json_escape(p.reason ? p.reason : "") + tail; +} + +/* ========================================================================= + * Strict CLI number parsing (the bench never uses atoi/atof/atol) + * + * The whole argument must parse: no leading whitespace, no trailing bytes + * (so a Unicode minus in "1e\xe2\x88\x926" is rejected instead of + * truncating to 1), no ERANGE, finite values only and an inclusive range. + * Unsigned values also reject a sign (strtoull silently negates "-1"). + * ========================================================================= */ + +inline bool strict_number_start_ok(const char* s) { + return s != nullptr && *s != '\0' && !std::isspace(static_cast(*s)); +} + +/* base 10 for counts, 0 (decimal / 0x hex / 0 octal) for ioctl numbers and IP ids. */ +inline bool parse_strict_uint(const char* s, int base, unsigned long long max, unsigned long long* out) { + if (!strict_number_start_ok(s) || *s == '-' || *s == '+') return false; + char* end = nullptr; + errno = 0; + const unsigned long long v = std::strtoull(s, &end, base); + if (errno != 0 || end == s || *end != '\0' || v > max) return false; + *out = v; + return true; +} + +inline bool parse_strict_int(const char* s, long long min, long long max, long long* out) { + if (!strict_number_start_ok(s)) return false; + char* end = nullptr; + errno = 0; + const long long v = std::strtoll(s, &end, 10); + if (errno != 0 || end == s || *end != '\0' || v < min || v > max) return false; + *out = v; + return true; +} + +inline bool parse_strict_u32(const char* s, int base, uint32_t* out) { + unsigned long long v = 0u; + if (!parse_strict_uint(s, base, 0xFFFFFFFFull, &v)) return false; + *out = static_cast(v); + return true; +} + +/* Finite double within [min, max]; NaN, +/-Inf, ERANGE and partial parses are rejected. */ +inline bool parse_strict_double(const char* s, double min, double max, double* out) { + if (!strict_number_start_ok(s)) return false; + char* end = nullptr; + errno = 0; + const double v = std::strtod(s, &end); + if (errno != 0 || end == s || *end != '\0' || !std::isfinite(v) || !(v >= min && v <= max)) return false; + *out = v; + return true; +} + +/* Finite and strictly positive (e.g. the --odpm-unit-j energy conversion factor). */ +inline bool parse_strict_positive_double(const char* s, double* out) { + double v = 0.0; + if (!parse_strict_double(s, 0.0, std::numeric_limits::max(), &v) || !(v > 0.0)) return false; + *out = v; + return true; +} + +} // namespace fs_tokloop + +#endif /* FREESCHED_VOLCANIC_TOKEN_LOOP_UTIL_H_ */ diff --git a/tools/volcanic_tpu_token_loop_bench.cpp b/tools/volcanic_tpu_token_loop_bench.cpp new file mode 100644 index 0000000..422ef46 --- /dev/null +++ b/tools/volcanic_tpu_token_loop_bench.cpp @@ -0,0 +1,3704 @@ +/* + * volcanic_tpu_token_loop_bench - Multi-Layer Pipelined Transformer Token Decode + * Loop over Zero-Copy shared buffers: PowerVR Volcanic GPU <-> EdgeTPU with a + * 3-arm inter-IP synchronization comparison (host_staged vs sync_file_poll vs r_iif). + * + * Copyright 2026 FreeSilicon Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Per decode token, L transformer blocks are chained: + * + * Volcanic GPU : A[l] = W_attn[l] @ x (attention output projection GEMV) + * -- fence (GPU -> TPU) -- + * EdgeTPU : Y[l] = W_ffn_int8[l] @ A[l] (INT8 FFN projection, raw accum) + * -- fence (TPU -> GPU) -- + * Volcanic GPU : x = RMSNorm(Y[l] * Scale[l] + x) * Gamma[l] (dequant + residual + norm) + * + * EdgeTPU stage backends (--tpu-backend, default auto): + * openbuenos : libopenbuenos W8A16 over pinned DMA-BUF IOVAs (Tensor G5 node). + * nnapi : selected automatically when no Tensor G5 node opens (e.g. Tensor + * G6): one NNAPI TENSOR_QUANT8_ASYMM NHWC 1x1 CONV_2D per layer + * compiled for the google-edgetpu ACCELERATOR (same lowering as + * src/fs_android_ahb_nnapi.cpp). The GPU writes A[l] as uint8 and + * reads Y[l] as uint8 through FP32<->QUANT8 bridge shaders, so the + * GPU and the EdgeTPU share the exact same zero-copy tensors + * (AHardwareBuffer BLOB GPU_DATA_BUFFER, or the pinned DMA-BUF). + * cpu : CPU emulation of the TPU stage (FP32 W8A16). + * + * All fs_iova_pool activations, weights and norm parameters are allocated, + * uploaded and pinned BEFORE the hot loop; the hot loop runs with fs_context + * hot-loop mode active so any dynamic pool map/unmap fails closed + * (hot_loop_map_count == 0 && hot_loop_unmap_count == 0 is asserted for the + * pool slots). External backend resources (NNAPI AHardwareBuffers, or + * libopenbuenos packed weight caches) are prepared/pre-warmed across all L + * layers before hot-loop entry, and iova_observation_scope reports what the + * pool counters observe. + * + * Synchronization arms for each of the 2*L inter-IP handoffs per token: + * host_staged : CPU blocks on the producer (vkWaitForFences / synchronous + * NNAPI or libopenbuenos compute) and bounces every tensor + * through host memory (2L host copies per token). + * sync_file_poll : zero-copy. Each asynchronous hop exports a sync_file + * (Vulkan SYNC_FD semaphore / NNAPI output sync fence) that + * a waiter thread poll()s before waking the submitting + * thread. NNAPI: 2L polls + wakeups per token. + * --tpu-backend openbuenos (ob_gemm_matmul_f32_w8a16_dmabuf + * waits synchronously before returning) and --tpu-backend + * cpu: L wakeups (only the GPU -> TPU/CPU Vulkan SYNC_FD; + * the synchronous output hop is counted in + * synchronous_tpu_hops_per_tok / synchronous_cpu_hops_per_tok + * rather than as a fenced handoff). + * r_iif : zero-copy. NNAPI backend: the whole token is one kernel fence + * chain (vkGetSemaphoreFdKHR -> ANeuralNetworksEvent_createFromSyncFenceFd + * -> startComputeWithDependencies -> ANeuralNetworksEvent_getSyncFenceFd + * -> vkImportSemaphoreFdKHR), gated by an AP-signaled /dev/iif fence + * (bridged to a sync_file) imported into the GPU queue, with zero userspace + * poll() between layers. Other backends: CPU-proxied IIF handoffs. + * + * --mock runs every stage on the CPU over the same pinned pool slots (and a + * software IIF emulator) so host CI verifies the full control/data path, + * numerics (cos vs an FP64 reference) and the JSON schema; --mock + * --tpu-backend nnapi emulates the QUANT8 bridge + 1x1 CONV_2D bit-for-bit. + * --mock never opens or ioctls the IIF node; only --live and --iif-probe-only do. + * + * Arms share one executor and its buffers. Every fs_iova_pool submission is + * recorded in a ledger until its fence retires. When an arm fails, the + * executor first releases any imported IIF gate, then proves every engine idle + * (vkDeviceWaitIdle, no live NNAPI hop or IIF fence) and only then retires the + * leftover submissions. If the gate cannot be signaled, it does not call + * vkQueueWaitIdle/vkDeviceWaitIdle (bounded vkWaitForFences only), taints the + * executor, and leaves in-flight slots unretired. A tainted executor skips + * every later arm before it touches SLOT_X (executor_state in the JSON). + * + * Attention scores/softmax over a KV cache are intentionally NOT modelled; each + * token is teacher-forced from a deterministic embedding table so arms are + * numerically comparable token-by-token. + */ +#include "freesched.h" +#include "fs_iova_pool.h" +#include "volcanic_token_loop_util.h" +#include "volcanic_nnapi_edgetpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#endif + +#if defined(__linux__) && __has_include() +#define VK_NO_PROTOTYPES 1 +#include +#define FS_TL_HAVE_VULKAN 1 +#include "volcanic_tpu_spirv.h" +#include "volcanic_token_loop_spirv.h" +#include "volcanic_quant8_spirv.h" +#else +#define FS_TL_HAVE_VULKAN 0 +#endif + +#ifdef FREESCHED_HAVE_LIBOPENBUENOS +#include "openbuenos.h" +#endif + +namespace { + +using namespace fs_tokloop; + +enum Arm { ARM_HOST_STAGED = 0, ARM_SYNC_FILE = 1, ARM_R_IIF = 2, ARM_COUNT = 3 }; +const char* const kArmNames[ARM_COUNT] = {"host_staged", "sync_file_poll", "r_iif"}; + +uint64_t now_ns() { + const auto t = std::chrono::steady_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(t).count()); +} + +/* ========================================================================= + * Deterministic synthetic transformer model + FP64 reference + * ========================================================================= */ + +struct Model { + uint32_t d = 0u; + uint32_t layers = 0u; + uint32_t vocab = 0u; + float eps = 1e-5f; + std::vector w_attn; /* [L][d(out)][d(in)] */ + std::vector w_ffn; /* [L][d(out)][d(in)] */ + std::vector scale; /* [L][d] */ + std::vector gamma; /* [L][d] */ + std::vector embed; /* [vocab][d] */ +}; + +void build_model(Model* m, uint32_t d, uint32_t layers, uint64_t seed) { + m->d = d; + m->layers = layers; + m->vocab = 97u; + XorShift64 rng(seed); + const size_t dd = static_cast(d) * d; + m->w_attn.resize(dd * layers); + m->w_ffn.resize(dd * layers); + m->scale.resize(static_cast(d) * layers); + m->gamma.resize(static_cast(d) * layers); + m->embed.resize(static_cast(m->vocab) * d); + const float attn_amp = std::sqrt(3.0f / static_cast(d)); + for (float& w : m->w_attn) w = rng.symmetric() * attn_amp; + for (int8_t& w : m->w_ffn) w = static_cast(static_cast(rng.next() % 63u) - 31); + /* |W_ffn| ~ U[-31, 31] (std ~= 18.2): dequant scale keeps Y*Scale ~ O(1). */ + const float base_scale = 1.0f / (18.2f * std::sqrt(static_cast(d))); + for (float& s : m->scale) s = base_scale * (0.9f + 0.2f * static_cast(rng.uniform())); + for (float& g : m->gamma) g = 0.9f + 0.2f * static_cast(rng.uniform()); + for (float& e : m->embed) e = rng.symmetric(); +} + +uint32_t token_id(uint32_t t, uint32_t vocab) { return (t * 7919u + 13u) % vocab; } + +/* FP64 reference; optionally accumulates per-layer max|A[l]| / max|Y[l]| (QUANT8 calibration). */ +void reference_token(const Model& m, uint32_t tok, double* out, double* amax_a = nullptr, + double* amax_y = nullptr) { + const uint32_t d = m.d; + std::vector x(d), a(d), y(d); + const float* e = m.embed.data() + static_cast(tok) * d; + for (uint32_t i = 0u; i < d; ++i) x[i] = e[i]; + for (uint32_t l = 0u; l < m.layers; ++l) { + const float* wa = m.w_attn.data() + static_cast(l) * d * d; + const int8_t* wf = m.w_ffn.data() + static_cast(l) * d * d; + for (uint32_t n = 0u; n < d; ++n) { + double acc = 0.0; + const float* row = wa + static_cast(n) * d; + for (uint32_t k = 0u; k < d; ++k) acc += static_cast(row[k]) * x[k]; + a[n] = acc; + if (amax_a && std::fabs(acc) > amax_a[l]) amax_a[l] = std::fabs(acc); + } + for (uint32_t n = 0u; n < d; ++n) { + double acc = 0.0; + const int8_t* row = wf + static_cast(n) * d; + for (uint32_t k = 0u; k < d; ++k) acc += static_cast(row[k]) * a[k]; + y[n] = acc; + if (amax_y && std::fabs(acc) > amax_y[l]) amax_y[l] = std::fabs(acc); + } + double ss = 0.0; + const float* sc = m.scale.data() + static_cast(l) * d; + const float* ga = m.gamma.data() + static_cast(l) * d; + for (uint32_t n = 0u; n < d; ++n) { + const double v = y[n] * static_cast(sc[n]) + x[n]; + y[n] = v; + ss += v * v; + } + const double inv = 1.0 / std::sqrt(ss / static_cast(d) + static_cast(m.eps)); + for (uint32_t n = 0u; n < d; ++n) x[n] = y[n] * inv * static_cast(ga[n]); + } + for (uint32_t i = 0u; i < d; ++i) out[i] = x[i]; +} + +/* CPU stage kernels (mock executor + live --tpu-backend cpu). */ +void cpu_gemv_f32(const float* w, const float* x, float* y, uint32_t d) { + for (uint32_t n = 0u; n < d; ++n) { + const float* row = w + static_cast(n) * d; + float acc = 0.0f; + for (uint32_t k = 0u; k < d; ++k) acc += row[k] * x[k]; + y[n] = acc; + } +} + +void cpu_tpu_w8a16(const int8_t* w, const float* a, float* y, uint32_t d, std::vector* scratch) { + scratch->resize(d); + float* ah = scratch->data(); + for (uint32_t k = 0u; k < d; ++k) ah[k] = fs_f16_to_f32(fs_f32_to_f16(a[k])); + for (uint32_t n = 0u; n < d; ++n) { + const int8_t* row = w + static_cast(n) * d; + float acc = 0.0f; + for (uint32_t k = 0u; k < d; ++k) acc += static_cast(row[k]) * ah[k]; + y[n] = acc; + } +} + +void cpu_residual_rmsnorm(const float* y, const float* scale, float* x, const float* gamma, + uint32_t d, float eps) { + float ss = 0.0f; + for (uint32_t i = 0u; i < d; ++i) { + const float v = y[i] * scale[i] + x[i]; + ss += v * v; + } + const float inv = 1.0f / std::sqrt(ss / static_cast(d) + eps); + for (uint32_t i = 0u; i < d; ++i) { + const float v = y[i] * scale[i] + x[i]; + x[i] = v * inv * gamma[i]; + } +} + +/* ========================================================================= + * Upfront pinned fs_iova_pool layout + * ========================================================================= */ + +enum SmallSlot : uint32_t { + SLOT_X = 0u, + SLOT_MID0 = 1u, + SLOT_MID1 = 2u, + SLOT_OUT0 = 3u, + SLOT_OUT1 = 4u, + SLOT_H = 5u, + SLOT_QMID0 = 6u, /* uint8 QUANT8 A[l] (NNAPI EdgeTPU input, dmabuf_fd mode) */ + SLOT_QMID1 = 7u, + SLOT_QOUT0 = 8u, /* uint8 QUANT8 Y[l] (NNAPI EdgeTPU output, dmabuf_fd mode) */ + SLOT_QOUT1 = 9u, + SLOT_PARAM_BASE = 10u /* scale[l] = BASE + l, gamma[l] = BASE + L + l */ +}; + +struct Pools { + fs_context_t* ctx = nullptr; + fs_iova_pool_t* small = nullptr; /* activations + per-layer scale/gamma */ + fs_iova_pool_t* weights = nullptr; /* per-layer W_attn */ + uint32_t d = 0u; + uint32_t layers = 0u; + bool hot = false; + + uint32_t mid_slot(uint32_t p) const { return SLOT_MID0 + (p & 1u); } + uint32_t out_slot(uint32_t p) const { return SLOT_OUT0 + (p & 1u); } + uint32_t qmid_slot(uint32_t p) const { return SLOT_QMID0 + (p & 1u); } + uint32_t qout_slot(uint32_t p) const { return SLOT_QOUT0 + (p & 1u); } + uint32_t scale_slot(uint32_t l) const { return SLOT_PARAM_BASE + l; } + uint32_t gamma_slot(uint32_t l) const { return SLOT_PARAM_BASE + layers + l; } + fs_dmabuf_t* sbuf(uint32_t slot) const { return fs_iova_pool_slot_buffer(small, slot); } + fs_dmabuf_t* wbuf(uint32_t l) const { return fs_iova_pool_slot_buffer(weights, l); } + float* host(fs_dmabuf_t* b) const { return static_cast(b->host_ptr); } + uint8_t* host_u8(fs_dmabuf_t* b) const { return static_cast(b->host_ptr); } +}; + +size_t round_up(size_t v, size_t a) { return (v + a - 1u) / a * a; } + +bool cpu_write(fs_context_t* ctx, fs_dmabuf_t* b, const void* src, size_t bytes, uint64_t* syncs) { + if (!b->host_ptr) return false; + if (fs_buffer_cpu_sync_begin(ctx, b, FS_DMA_SYNC_WRITE) != FS_OK) return false; + std::memcpy(b->host_ptr, src, bytes); + if (fs_buffer_cpu_sync_end(ctx, b, FS_DMA_SYNC_WRITE) != FS_OK) return false; + if (syncs) *syncs += 2u; + return true; +} + +bool cpu_read(fs_context_t* ctx, fs_dmabuf_t* b, void* dst, size_t bytes, uint64_t* syncs) { + if (!b->host_ptr) return false; + if (fs_buffer_cpu_sync_begin(ctx, b, FS_DMA_SYNC_READ) != FS_OK) return false; + std::memcpy(dst, b->host_ptr, bytes); + if (fs_buffer_cpu_sync_end(ctx, b, FS_DMA_SYNC_READ) != FS_OK) return false; + if (syncs) *syncs += 2u; + return true; +} + +bool setup_pools(fs_context_t* ctx, const Model& m, bool live, Pools* p, std::string* err) { + p->ctx = ctx; + p->d = m.d; + p->layers = m.layers; + const size_t act_bytes = round_up(static_cast(m.d) * sizeof(float), 4096u); + const size_t w_bytes = round_up(static_cast(m.d) * m.d * sizeof(float), 4096u); + + fs_iova_pool_config_t cfg = fs_iova_pool_config_default(); + cfg.slot_count = SLOT_PARAM_BASE + 2u * m.layers; + cfg.slot_bytes = act_bytes; + cfg.initial_owner = FS_DEV_GPU_VK; + cfg.pin_dev_mask = (1u << FS_DEV_GPU_VK) | (1u << FS_DEV_TPU); + cfg.buf_flags = FS_BUF_ZERO_INIT; + cfg.cacheability = FS_CACHE_CACHED; + cfg.coherency_policy = FS_COHERENCY_POLICY_CACHED_SYNC; + if (fs_iova_pool_create(ctx, &cfg, &p->small) != FS_OK || !p->small) { + *err = std::string("fs_iova_pool_create(activations) failed: ") + fs_context_last_error(ctx); + return false; + } + fs_iova_pool_config_t wcfg = cfg; + wcfg.slot_count = m.layers; + wcfg.slot_bytes = w_bytes; + wcfg.pin_dev_mask = (1u << FS_DEV_GPU_VK); + if (fs_iova_pool_create(ctx, &wcfg, &p->weights) != FS_OK || !p->weights) { + *err = std::string("fs_iova_pool_create(weights) failed: ") + fs_context_last_error(ctx); + return false; + } + auto check_buf = [&](fs_dmabuf_t* b) -> bool { + if (!b || !b->host_ptr) return false; + if (live && (b->backing != FS_BACKING_DMA_HEAP || b->dmabuf_fd < 0)) return false; + return true; + }; + for (uint32_t s = 0u; s < cfg.slot_count; ++s) { + if (!check_buf(p->sbuf(s))) { + *err = "activation pool slot lacks host mapping or real DMA-heap backing"; + return false; + } + } + for (uint32_t l = 0u; l < m.layers; ++l) { + if (!check_buf(p->wbuf(l))) { + *err = "weight pool slot lacks host mapping or real DMA-heap backing"; + return false; + } + } + /* Upload weights + norm params once (outside the hot loop). */ + const size_t dd = static_cast(m.d) * m.d; + for (uint32_t l = 0u; l < m.layers; ++l) { + if (!cpu_write(ctx, p->wbuf(l), m.w_attn.data() + dd * l, dd * sizeof(float), nullptr) || + !cpu_write(ctx, p->sbuf(p->scale_slot(l)), m.scale.data() + static_cast(m.d) * l, + m.d * sizeof(float), nullptr) || + !cpu_write(ctx, p->sbuf(p->gamma_slot(l)), m.gamma.data() + static_cast(m.d) * l, + m.d * sizeof(float), nullptr)) { + *err = std::string("weight upload (DMA_BUF_IOCTL_SYNC bracket) failed: ") + fs_context_last_error(ctx); + return false; + } + } + return true; +} + +bool pools_enter_hot(Pools* p) { + if (fs_iova_pool_enter_hot_loop(p->small) != FS_OK) return false; + if (fs_iova_pool_enter_hot_loop(p->weights) != FS_OK) { + (void)fs_iova_pool_exit_hot_loop(p->small); + return false; + } + p->hot = true; + return true; +} + +void pools_exit_hot(Pools* p) { + if (!p->hot) return; + (void)fs_iova_pool_exit_hot_loop(p->weights); + (void)fs_iova_pool_exit_hot_loop(p->small); + p->hot = false; +} + +void pools_destroy(Pools* p) { + pools_exit_hot(p); + if (p->weights) (void)fs_iova_pool_destroy(p->weights); + if (p->small) (void)fs_iova_pool_destroy(p->small); + p->weights = nullptr; + p->small = nullptr; +} + +struct HotStats { + uint64_t maps = 0u, unmaps = 0u, map_rejects = 0u, unmap_rejects = 0u; +}; + +HotStats context_hot_stats(fs_context_t* ctx) { + HotStats s{}; + uint64_t up = 0u, un = 0u; + (void)fs_context_get_iova_stats(ctx, &up, &un, &s.maps, &s.unmaps, &s.map_rejects, &s.unmap_rejects); + return s; +} + + +/* ========================================================================= + * Per-token counters + executor interface + * ========================================================================= */ + +struct TokenCounters { + uint64_t inter_ip_host_copies = 0u; + uint64_t fence_handoffs = 0u; + uint64_t cpu_dma_syncs = 0u; + uint64_t sync_files_exported = 0u; + uint64_t sync_files_imported = 0u; + uint64_t iif_fences = 0u; + /* + * tpu_hw_us is hardware EdgeTPU execution time only (libopenbuenos + * hw_execution_us). NNAPI, including synchronous ANeuralNetworksExecution_compute, + * does not measure it: the JSON emits null unless tpu_hw_measured is set. + * nnapi_sync_call_us is the host-side compute() duration and is null on fenced arms. + */ + double tpu_hw_us = 0.0; + bool tpu_hw_measured = false; + double nnapi_sync_call_us = 0.0; + bool nnapi_sync_call_measured = false; + /* + * Timing fields use the same interval definitions in every arm and executor: + * - host_wait_us: wall time the decode thread is blocked in host-side waits + * only: sync_file poll() (inline, or handed to the waiter thread), + * vkWaitForFences, vkQueueWaitIdle (IIF gate drain), ANeuralNetworksEvent_wait + * and the /dev/iif wait ioctl. Submission calls are excluded. + * - dispatch_submit_us: wall time inside vkQueueSubmit and + * ANeuralNetworksExecution_startComputeWithDependencies only (the NNAPI + * dependency event is created before that timer starts). + * - pipelined_chain_us: r_iif NNAPI chain only: first chain vkQueueSubmit + * through the token-boundary VkFence (it spans both fields above); + * pipelined_chains counts the chains. + */ + double host_wait_us = 0.0; + double dispatch_submit_us = 0.0; + double pipelined_chain_us = 0.0; + uint64_t pipelined_chains = 0u; + /* + * Hops whose producer finished synchronously on the decode thread before the + * handoff: --tpu-backend cpu W8A16 output writes (synchronous_cpu_hops) and + * --tpu-backend openbuenos ob_gemm_matmul_f32_w8a16_dmabuf completions + * (synchronous_tpu_hops). No asynchronous producer fence exists, so neither + * is exported/polled or counted in fence_handoffs. + */ + uint64_t synchronous_cpu_hops = 0u; + uint64_t synchronous_tpu_hops = 0u; + uint64_t userspace_fence_polls = 0u; /* poll()/CPU waits on an inter-IP fence (any thread) */ + /* + * Cross-thread wakeups only: a separate waiter thread observed the fence and + * woke the decode thread. Inline poll()/waits on the submitting thread count + * in userspace_fence_polls but never here. + */ + uint64_t userspace_wakeups = 0u; + uint64_t nnapi_unfenced_hops = 0u; /* NNAPI ran synchronously (driver lacks fenced exec) */ + double nnapi_start_block_us = 0.0; /* wall time inside startComputeWithDependencies only */ + /* + * ANeuralNetworksEvent_createFromSyncFenceFd (r_iif dependency events), kept + * out of nnapi_start_block_us and dispatch_submit_us so both fenced arms time + * the identical submission call. + */ + double nnapi_dep_event_create_us = 0.0; + uint64_t nnapi_event_checks = 0u; /* ANeuralNetworksEvent_wait status checks of fenced hops */ +}; + +double us_since(uint64_t t0_ns) { return static_cast(now_ns() - t0_ns) / 1e3; } + +struct IifConfig { + uint32_t gpu_ip = FS_IIF_IP_GPU; + uint32_t tpu_ip = FS_IIF_IP_TPU; + uint32_t ap_ip = FS_IIF_IP_AP; /* signaler id used for fences the CPU signals */ + uint32_t timeout_ms = 5000u; +}; + +/* Per-layer QUANT8_ASYMM parameters of the EdgeTPU NNAPI stage (A[l] in, Y[l] out). */ +struct QuantCal { + std::vector a, y; +}; + +void quantize_buf(const float* src, uint8_t* dst, const Quant8& q, uint32_t d) { + const float inv = 1.0f / q.scale; + for (uint32_t i = 0u; i < d; ++i) dst[i] = quant8_quantize(src[i], inv, q.zero_point); +} + +void dequantize_buf(const uint8_t* src, float* dst, const Quant8& q, uint32_t d) { + for (uint32_t i = 0u; i < d; ++i) dst[i] = quant8_dequantize(src[i], q.scale, q.zero_point); +} + +class Executor { + public: + explicit Executor(Pools* pools) : pools_(pools) {} + virtual ~Executor() = default; + virtual const char* name() const = 0; + /* Returns nullptr if the arm can run, else a short skip reason. */ + virtual const char* arm_unavailable(Arm arm) const = 0; + virtual bool run_token(Arm arm, uint32_t tok, float* out_hidden, TokenCounters* c, std::string* err) = 0; + + /* + * Failure recovery between arms. A failed or timed-out hop can return with + * device work still queued and with fs_iova_pool submissions INFLIGHT (e.g. + * a rejected GPU fence short-circuits the slot retire). Reusing the executor + * is safe only once every engine is proven idle, so: + * 1. quiesce(): vkDeviceWaitIdle (live), ob_graph_wait_all (libopenbuenos), + * and no NNAPI execution/event or IIF fence may still be outstanding; + * 2. only if (1) holds, retire every submission still in the ledger + * (its device work is proven finished) and require every pool slot to + * be IDLE again (no INFLIGHT / CANCELED_DRAINING slot). + * Any failure taints the executor: buffer reuse cannot be proven safe, and + * run_arm() skips every later arm before it writes SLOT_X or any buffer. + */ + bool last_failure_timed_out() const { return last_failure_timed_out_; } + + bool recover_after_failure(bool timed_out = false) { + ++recoveries_; + if (timed_out || last_failure_timed_out_) { + /* + * Bounded timeout recovery: an unsignaled fence means hardware completion + * is unproven, so an unbounded drain (vkQueueWaitIdle / vkDeviceWaitIdle / + * ANeuralNetworksEvent_wait) could hang indefinitely. Taint immediately + * and leave every in-flight pool slot and NNAPI object quarantined. + */ + if (!tainted_) { + taint("fence wait timed out; skipped unbounded device drain (in-flight slots quarantined)"); + } + return false; + } + std::string why; + if (!quiesce(&why)) { + taint("engines not proven idle: " + why); + return false; + } + while (!ledger_.empty()) { + LedgerEntry e = ledger_.back(); + ledger_.pop_back(); + if (fs_iova_pool_signal_fence(e.pool, &e.sub, -1, FS_OK) != FS_OK) { + taint("retiring drained slot " + std::to_string(e.sub.slot_index) + " failed"); + return false; + } + ++retired_after_drain_; + } + if (!pools_idle(&why)) { + taint(why); + return false; + } + return true; + } + /* A successful arm must leave nothing in flight. */ + bool clean_after_success(std::string* why) const { + if (!ledger_.empty()) { + *why = std::to_string(ledger_.size()) + " pool submission(s) left INFLIGHT"; + return false; + } + return pools_idle(why); + } + bool tainted() const { return tainted_; } + const std::string& taint_reason() const { return taint_reason_; } + uint64_t recoveries() const { return recoveries_; } + uint64_t retired_after_drain() const { return retired_after_drain_; } + size_t ledger_size() const { return ledger_.size(); } + + protected: + /* Proves every engine idle (no queued device work, no live NNAPI/IIF object). */ + virtual bool quiesce(std::string* why) = 0; + virtual void on_taint() {} + void taint(const std::string& why) { + tainted_ = true; + taint_reason_ = why; + on_taint(); + } + void mark_fence_timeout(const std::string& why) { + last_failure_timed_out_ = true; + taint(why); + } + + /* Pool submission bookkeeping: a slot is INFLIGHT on `dev` (and in the ledger) until its fence retires. */ + bool slot_begin(fs_iova_pool_t* pool, uint32_t slot, fs_dev_t dev, fs_iova_submission_t* sub) { + if (fs_iova_pool_submit(pool, slot, dev, sub) != FS_OK) return false; + ledger_.push_back(LedgerEntry{pool, *sub}); + return true; + } + bool slot_end(fs_iova_pool_t* pool, fs_iova_submission_t* sub, int sync_fd) { + const fs_iova_submission_t key = *sub; + if (fs_iova_pool_signal_fence(pool, sub, sync_fd, FS_OK) != FS_OK) return false; + for (size_t i = 0u; i < ledger_.size(); ++i) { + const LedgerEntry& e = ledger_[i]; + if (e.pool == pool && e.sub.slot_index == key.slot_index && e.sub.generation == key.generation && + e.sub.fence_seq == key.fence_seq) { + ledger_.erase(ledger_.begin() + static_cast(i)); + break; + } + } + return true; + } + + private: + struct LedgerEntry { + fs_iova_pool_t* pool; + fs_iova_submission_t sub; + }; + bool pools_idle(std::string* why) const { + fs_iova_pool_t* const ps[2] = {pools_->small, pools_->weights}; + for (fs_iova_pool_t* pool : ps) { + fs_iova_pool_stats_t st{}; + if (!pool || fs_iova_pool_get_stats(pool, &st) != FS_OK) { + *why = "fs_iova_pool_get_stats failed"; + return false; + } + if (st.inflight_slots != 0u || st.canceled_draining_slots != 0u) { + *why = "pool not idle after drain: " + std::to_string(st.inflight_slots) + " INFLIGHT, " + + std::to_string(st.canceled_draining_slots) + " CANCELED_DRAINING slot(s)"; + return false; + } + } + return true; + } + + Pools* pools_; + std::vector ledger_; + bool tainted_ = false; + bool last_failure_timed_out_ = false; + std::string taint_reason_; + uint64_t recoveries_ = 0u; + uint64_t retired_after_drain_ = 0u; +}; + +/* + * Mock-only test seam (--fault-inject-gpu-fence ARM:CALL:LAYER): run_token call + * CALL (0-based, warmup included) of ARM fails at LAYER as if the GPU fence of + * the stage were rejected, with that stage's pool slot left INFLIGHT. + * --fault-inject-quiesce-fail makes the drain unable to prove the device idle. + */ +struct FaultInject { + int arm = -1; + uint32_t call = 0u; + uint32_t layer = 0u; + int timeout_arm = -1; + uint32_t timeout_call = 0u; + uint32_t timeout_layer = 0u; + bool quiesce_fail = false; +}; + +/* + * IIF CPU-proxy handoff: producer completion already observed -> create -> + * submit_signaler -> signal -> wait -> destroy. Kernel fences are created with + * the AP signaler id because the CPU is the IP that signals them. + */ +bool iif_handoff(IifFences* iif, uint32_t signaler_ip, uint32_t timeout_ms, TokenCounters* c, + std::string* err) { + int h = -1; + int rc = iif->create(signaler_ip, 1u, &h); + if (rc != IIF_OK) { + *err = "IIF create failed (" + std::string(iif_errno_reason(iif->last_errno())) + ")"; + return false; + } + rc = iif->submit_signaler(h); + if (rc == IIF_OK) rc = iif->signal(h, 0); + if (rc == IIF_OK) { + const uint64_t tw = now_ns(); + rc = iif->wait(h, timeout_ms); + c->host_wait_us += us_since(tw); + } + iif->destroy(h); /* never imported into another queue */ + if (rc != IIF_OK) { + *err = "IIF submit/signal/wait failed rc=" + std::to_string(rc) + " (" + + std::string(iif_errno_reason(iif->last_errno())) + ")"; + return false; + } + if (iif->kind() == FS_IIF_BACKEND_KERNEL) { + c->userspace_fence_polls += 1u; /* inline poll() on the submitting thread: no cross-thread wakeup */ + } + c->iif_fences += 1u; + c->fence_handoffs += 1u; + return true; +} + +/* ------------------------------------------------------------------------- + * Mock executor: CPU "devices" over the same pinned pool slots + * ------------------------------------------------------------------------- */ + +class MockExecutor : public Executor { + public: + MockExecutor(const Model& m, Pools* p, IifFences* iif, const IifConfig& ic, const QuantCal* qc, + const FaultInject& fault) + : Executor(p), m_(m), p_(p), iif_(iif), ic_(ic), qc_(qc), fault_(fault), stage_in_(m.d), stage_out_(m.d), + stage_in_u8_(m.d), stage_out_u8_(m.d) {} + const char* name() const override { return qc_ ? "mock_cpu_nnapi_quant8" : "mock_cpu"; } + const char* arm_unavailable(Arm arm) const override { + if (arm == ARM_R_IIF && iif_->kind() == FS_IIF_BACKEND_NONE) return "iif_unavailable"; + return nullptr; + } + + bool run_token(Arm arm, uint32_t tok, float* out_hidden, TokenCounters* c, std::string* err) override { + const uint32_t d = m_.d; + const uint32_t call = calls_[arm]++; + fs_context_t* ctx = p_->ctx; + fs_dmabuf_t* xb = p_->sbuf(SLOT_X); + if (!cpu_write(ctx, xb, m_.embed.data() + static_cast(tok) * d, d * sizeof(float), + &c->cpu_dma_syncs)) { + *err = "embedding upload failed"; + return false; + } + float* x = p_->host(xb); + for (uint32_t l = 0u; l < m_.layers; ++l) { + fs_dmabuf_t* mid = p_->sbuf(p_->mid_slot(l)); + fs_dmabuf_t* out = p_->sbuf(p_->out_slot(l)); + fs_dmabuf_t* qmid = p_->sbuf(p_->qmid_slot(l)); + fs_dmabuf_t* qout = p_->sbuf(p_->qout_slot(l)); + const int8_t* wf = m_.w_ffn.data() + static_cast(l) * d * d; + const bool staged = (arm == ARM_HOST_STAGED); + fs_iova_submission_t sm{}, so{}; + /* GPU stage A (emulated) writes straight into the pinned mid slot. */ + if (!slot_begin(p_->small, p_->mid_slot(l), FS_DEV_GPU_VK, &sm)) { + *err = "pool submit(mid, GPU) rejected"; + return false; + } + cpu_gemv_f32(p_->host(p_->wbuf(l)), x, p_->host(mid), d); + if (qc_) quantize_buf(p_->host(mid), p_->host_u8(qmid), qc_->a[l], d); /* GPU FP32->QUANT8 bridge */ + if (fault_.timeout_arm == static_cast(arm) && fault_.timeout_call == call && fault_.timeout_layer == l) { + /* Same shape as a live unsignaled fence timeout: quarantine slot, taint immediately, skip quiesce(). */ + const std::string msg = "injected fence wait timeout at layer " + std::to_string(l) + + " (skipped unbounded drain; in-flight slot quarantined)"; + mark_fence_timeout(msg); + *err = msg; + return false; + } + if (fault_.arm == static_cast(arm) && fault_.call == call && fault_.layer == l) { + /* Same shape as a live rejected GPU fence: return before the mid slot retires. */ + *err = "injected GPU fence failure at layer " + std::to_string(l) + " (mid slot left INFLIGHT)"; + return false; + } + bool ok = true; + if (staged) { + ok = slot_end(p_->small, &sm, -1) && + (qc_ ? cpu_read(ctx, qmid, stage_in_u8_.data(), d, &c->cpu_dma_syncs) + : cpu_read(ctx, mid, stage_in_.data(), d * sizeof(float), &c->cpu_dma_syncs)); + c->inter_ip_host_copies += 1u; + } else if (arm == ARM_SYNC_FILE) { + ok = fence_roundtrip(FS_DEV_GPU_VK, &sm, c); + } else { + ok = iif_handoff(iif_, ic_.gpu_ip, ic_.timeout_ms, c, err) && slot_end(p_->small, &sm, -1); + } + if (!ok) { + if (err->empty()) *err = "GPU->TPU handoff failed"; + return false; + } + /* + * EdgeTPU stage (emulated W8A16, or the NNAPI QUANT8_ASYMM 1x1 CONV_2D + * reference). Its submission is recorded on the slot it actually writes: + * FP32 out(l) for W8A16, the QUANT8 qout(l) pool slot for the NNAPI path. + */ + if (!slot_begin(p_->small, qc_ ? p_->qout_slot(l) : p_->out_slot(l), FS_DEV_TPU, &so)) { + *err = "pool submit(out, TPU) rejected"; + return false; + } + if (qc_) { + quant8_conv1x1_ref(staged ? stage_in_u8_.data() : p_->host_u8(qmid), qc_->a[l], wf, d, qc_->y[l], + staged ? stage_out_u8_.data() : p_->host_u8(qout)); + } else if (staged) { + cpu_tpu_w8a16(wf, stage_in_.data(), stage_out_.data(), d, &scratch_); + } else { + cpu_tpu_w8a16(wf, p_->host(mid), p_->host(out), d, &scratch_); + } + if (staged) { + ok = (qc_ ? cpu_write(ctx, qout, stage_out_u8_.data(), d, &c->cpu_dma_syncs) + : cpu_write(ctx, out, stage_out_.data(), d * sizeof(float), &c->cpu_dma_syncs)) && + slot_end(p_->small, &so, -1); + c->inter_ip_host_copies += 1u; + } else if (arm == ARM_SYNC_FILE) { + ok = fence_roundtrip(FS_DEV_TPU, &so, c); + } else { + ok = iif_handoff(iif_, ic_.tpu_ip, ic_.timeout_ms, c, err) && slot_end(p_->small, &so, -1); + } + if (!ok) { + if (err->empty()) *err = "TPU->GPU handoff failed"; + return false; + } + /* GPU stage C (emulated): [QUANT8->FP32 bridge] + dequant + residual + RMSNorm in place. */ + if (qc_) dequantize_buf(p_->host_u8(qout), p_->host(out), qc_->y[l], d); + cpu_residual_rmsnorm(p_->host(out), p_->host(p_->sbuf(p_->scale_slot(l))), x, + p_->host(p_->sbuf(p_->gamma_slot(l))), d, m_.eps); + } + if (!cpu_read(ctx, xb, out_hidden, d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "hidden-state readback failed"; + return false; + } + return true; + } + + private: + bool fence_roundtrip(fs_dev_t producer, fs_iova_submission_t* sub, TokenCounters* c) { + fs_fence_t f = fs_fence_init(producer); + bool ok = fs_fence_signal(&f, -1) == FS_OK; + if (ok) { + const uint64_t tw = now_ns(); + ok = fs_fence_wait(&f, 5000u) == FS_OK; + c->host_wait_us += us_since(tw); + } + ok = ok && slot_end(p_->small, sub, -1); + fs_fence_close(&f); + c->fence_handoffs += 1u; + c->userspace_fence_polls += 1u; /* inline wait on the submitting thread: no cross-thread wakeup */ + return ok; + } + + /* CPU "devices" finish synchronously: idle unless the test seam says otherwise or an IIF fence leaked. */ + bool quiesce(std::string* why) override { + if (last_failure_timed_out()) { + *why = "BUG: quiesce() called after fence timeout"; + return false; + } + if (fault_.quiesce_fail) { + *why = "injected quiesce failure (device idle cannot be proven)"; + return false; + } + if (iif_->outstanding() != 0u) { + *why = std::to_string(iif_->outstanding()) + " IIF fence(s) still open"; + return false; + } + return true; + } + + const Model& m_; + Pools* p_; + IifFences* iif_; + IifConfig ic_; + const QuantCal* qc_; + FaultInject fault_; + uint32_t calls_[ARM_COUNT] = {0u, 0u, 0u}; + std::vector stage_in_, stage_out_, scratch_; + std::vector stage_in_u8_, stage_out_u8_; +}; + +/* ------------------------------------------------------------------------- + * Live executor: Volcanic Vulkan + EdgeTPU (libopenbuenos | NNAPI accelerator | CPU) + * ------------------------------------------------------------------------- */ +#if FS_TL_HAVE_VULKAN + +int dup_cloexec(int fd) { + if (fd < 0) return -1; + return fcntl(fd, F_DUPFD_CLOEXEC, 0); +} + +/* + * Every producer fence the live executor polls is a kernel sync_file (Vulkan + * SYNC_FD export, DMA_BUF_IOCTL_EXPORT_SYNC_FILE, NNAPI completion fence). + * POLLIN alone is not success: a fence that signaled with an error is readable + * too, so sync_fd_wait_handoff() also requires SYNC_IOC_FILE_INFO.status == 1 + * before the consumer may touch the buffer. + */ +bool poll_sync_fd(int fd, int timeout_ms, bool* timed_out = nullptr) { + if (timed_out) *timed_out = false; + const char* why = nullptr; + int32_t status = 0; + const bool ok = sync_fd_wait_handoff(fd, timeout_ms, SYNC_FD_KERNEL_SYNC_FILE, &why, &status); + if (!ok) { + if (timed_out && why && std::strcmp(why, "timeout") == 0) *timed_out = true; + std::fprintf(stderr, "sync_file handoff rejected: %s (status=%d)\n", why ? why : "?", static_cast(status)); + } + return ok; +} + +/* poll_sync_fd() on the decode thread, accounted as host_wait_us. */ +bool poll_sync_fd_timed(int fd, int timeout_ms, TokenCounters* c, bool* timed_out = nullptr) { + const uint64_t tw = now_ns(); + const bool ok = poll_sync_fd(fd, timeout_ms, timed_out); + c->host_wait_us += us_since(tw); + return ok; +} + +/* + * sync_file_poll arm helper: a dedicated waiter thread poll()s each fence fd + * and wakes the submitting thread through a condition variable, modelling the + * classic userspace runtime handoff (one poll + one cross-thread wakeup/hop). + */ +class FdWaiter { + public: + ~FdWaiter() { stop(); } + void start() { + if (started_) return; + quit_ = false; + worker_ = std::thread([this]() { loop(); }); + started_ = true; + } + void stop() { + if (!started_) return; + { + std::lock_guard lk(mu_); + quit_ = true; + } + cv_.notify_all(); + worker_.join(); + started_ = false; + } + bool started() const { return started_; } + /* Borrowed fd; returns once the waiter thread observed it signaled (or timed out). */ + bool wait(int fd, int timeout_ms, bool* timed_out = nullptr) { + if (timed_out) *timed_out = false; + std::unique_lock lk(mu_); + fd_ = fd; + timeout_ms_ = timeout_ms; + done_ = false; + timed_out_ = false; + has_job_ = true; + cv_.notify_all(); + cv_.wait(lk, [this]() { return done_; }); + if (timed_out) *timed_out = timed_out_; + return ok_; + } + + private: + void loop() { + std::unique_lock lk(mu_); + for (;;) { + cv_.wait(lk, [this]() { return quit_ || has_job_; }); + if (quit_) return; + const int fd = fd_; + const int to = timeout_ms_; + has_job_ = false; + lk.unlock(); + /* Same verdict as poll_sync_fd(): POLLIN plus SYNC_IOC_FILE_INFO.status == 1. */ + const char* why = nullptr; + int32_t status = 0; + const bool ok = sync_fd_wait_handoff(fd, to, SYNC_FD_KERNEL_SYNC_FILE, &why, &status); + const bool to_hit = !ok && why && std::strcmp(why, "timeout") == 0; + if (!ok) { + std::fprintf(stderr, "sync_file handoff rejected (waiter): %s (status=%d)\n", why ? why : "?", + static_cast(status)); + } + lk.lock(); + ok_ = ok; + timed_out_ = to_hit; + done_ = true; + cv_.notify_all(); + } + } + + std::thread worker_; + std::mutex mu_; + std::condition_variable cv_; + bool started_ = false; + bool quit_ = false; + bool has_job_ = false; + bool done_ = false; + bool ok_ = false; + bool timed_out_ = false; + int fd_ = -1; + int timeout_ms_ = 0; +}; + +struct VkDmaBuffer { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + VkDeviceSize size = 0u; +}; + +#define FS_TL_VK_INSTANCE_FNS(X) \ + X(vkDestroyInstance) \ + X(vkEnumeratePhysicalDevices) \ + X(vkGetPhysicalDeviceProperties) \ + X(vkGetPhysicalDeviceMemoryProperties) \ + X(vkGetPhysicalDeviceQueueFamilyProperties) \ + X(vkEnumerateDeviceExtensionProperties) \ + X(vkCreateDevice) \ + X(vkGetDeviceProcAddr) + +#define FS_TL_VK_DEVICE_FNS(X) \ + X(vkDestroyDevice) \ + X(vkGetDeviceQueue) \ + X(vkQueueSubmit) \ + X(vkQueueWaitIdle) \ + X(vkDeviceWaitIdle) \ + X(vkCreateBuffer) \ + X(vkDestroyBuffer) \ + X(vkGetBufferMemoryRequirements) \ + X(vkAllocateMemory) \ + X(vkFreeMemory) \ + X(vkBindBufferMemory) \ + X(vkGetMemoryFdPropertiesKHR) \ + X(vkCreateShaderModule) \ + X(vkDestroyShaderModule) \ + X(vkCreateDescriptorSetLayout) \ + X(vkDestroyDescriptorSetLayout) \ + X(vkCreatePipelineLayout) \ + X(vkDestroyPipelineLayout) \ + X(vkCreateComputePipelines) \ + X(vkDestroyPipeline) \ + X(vkCreateDescriptorPool) \ + X(vkDestroyDescriptorPool) \ + X(vkAllocateDescriptorSets) \ + X(vkUpdateDescriptorSets) \ + X(vkCreateCommandPool) \ + X(vkDestroyCommandPool) \ + X(vkAllocateCommandBuffers) \ + X(vkBeginCommandBuffer) \ + X(vkEndCommandBuffer) \ + X(vkCmdBindPipeline) \ + X(vkCmdBindDescriptorSets) \ + X(vkCmdPushConstants) \ + X(vkCmdDispatch) \ + X(vkCmdPipelineBarrier) \ + X(vkCreateFence) \ + X(vkDestroyFence) \ + X(vkResetFences) \ + X(vkWaitForFences) \ + X(vkCreateSemaphore) \ + X(vkDestroySemaphore) \ + X(vkGetSemaphoreFdKHR) \ + X(vkImportSemaphoreFdKHR) + +struct VkRunner { + void* dl = nullptr; + VkInstance instance = VK_NULL_HANDLE; + VkPhysicalDevice phys = VK_NULL_HANDLE; + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + uint32_t qf = UINT32_MAX; + VkPhysicalDeviceMemoryProperties mem_props{}; + char device_name[256]{}; + uint32_t vendor_id = 0u; + bool has_sem_fd = false; + bool has_qf_foreign = false; /* VK_EXT_queue_family_foreign enabled */ + uint32_t ext_qf = VK_QUEUE_FAMILY_IGNORED; /* owner of tensors shared with the TPU (see init) */ + uint64_t ownership_barriers = 0u; /* recorded release + acquire buffer barriers */ + + VkCommandPool cmd_pool = VK_NULL_HANDLE; + VkDescriptorSetLayout dsl = VK_NULL_HANDLE; + VkDescriptorPool dpool = VK_NULL_HANDLE; + VkPipelineLayout gemv_layout = VK_NULL_HANDLE, norm_layout = VK_NULL_HANDLE; + VkPipeline gemv_pipe = VK_NULL_HANDLE, norm_pipe = VK_NULL_HANDLE; + VkPipelineLayout quant_layout = VK_NULL_HANDLE, dequant_layout = VK_NULL_HANDLE; + VkPipeline quant_pipe = VK_NULL_HANDLE, dequant_pipe = VK_NULL_HANDLE; + VkFence fence = VK_NULL_HANDLE; + VkSemaphore sem_export = VK_NULL_HANDLE; + VkSemaphore sem_import = VK_NULL_HANDLE; + /* Set when vkQueueSubmit signaled an export semaphore but SYNC_FD export failed. */ + VkSemaphore* pending_signaled_export_ = nullptr; + bool export_semaphore_recovery_failed = false; + + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr; + PFN_vkCreateInstance vkCreateInstance = nullptr; +#define FS_TL_DECL(fn) PFN_##fn fn = nullptr; + FS_TL_VK_INSTANCE_FNS(FS_TL_DECL) + FS_TL_VK_DEVICE_FNS(FS_TL_DECL) +#undef FS_TL_DECL + + bool init(const char* preferred, uint32_t max_sets, std::string* err) { + dl = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); + if (!dl) dl = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL); + if (!dl) { + *err = "dlopen(libvulkan.so) failed"; + return false; + } + vkGetInstanceProcAddr = reinterpret_cast(dlsym(dl, "vkGetInstanceProcAddr")); + if (!vkGetInstanceProcAddr) { + *err = "dlsym(vkGetInstanceProcAddr) failed"; + return false; + } + vkCreateInstance = reinterpret_cast(vkGetInstanceProcAddr(nullptr, "vkCreateInstance")); + VkApplicationInfo app{}; + app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + app.pApplicationName = "volcanic_tpu_token_loop_bench"; + app.pEngineName = "freesched"; + app.apiVersion = VK_API_VERSION_1_1; + VkInstanceCreateInfo ici{}; + ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + ici.pApplicationInfo = &app; + if (!vkCreateInstance || vkCreateInstance(&ici, nullptr, &instance) != VK_SUCCESS) { + *err = "vkCreateInstance failed"; + return false; + } +#define FS_TL_LOAD_I(fn) fn = reinterpret_cast(vkGetInstanceProcAddr(instance, #fn)); + FS_TL_VK_INSTANCE_FNS(FS_TL_LOAD_I) +#undef FS_TL_LOAD_I + uint32_t n = 0u; + if (!vkEnumeratePhysicalDevices || vkEnumeratePhysicalDevices(instance, &n, nullptr) != VK_SUCCESS || n == 0u) { + *err = "no Vulkan physical devices"; + return false; + } + std::vector devs(n); + vkEnumeratePhysicalDevices(instance, &n, devs.data()); + int best = -1; + for (VkPhysicalDevice pd : devs) { + VkPhysicalDeviceProperties props{}; + vkGetPhysicalDeviceProperties(pd, &props); + if (preferred && preferred[0] != '\0' && std::strstr(props.deviceName, preferred) == nullptr) continue; + uint32_t ne = 0u; + vkEnumerateDeviceExtensionProperties(pd, nullptr, &ne, nullptr); + std::vector exts(ne); + if (ne) vkEnumerateDeviceExtensionProperties(pd, nullptr, &ne, exts.data()); + bool em = false, emfd = false, dmabuf = false, semfd = false, es = false, qff = false; + for (const auto& e : exts) { + if (!std::strcmp(e.extensionName, "VK_KHR_external_memory")) em = true; + else if (!std::strcmp(e.extensionName, "VK_KHR_external_memory_fd")) emfd = true; + else if (!std::strcmp(e.extensionName, "VK_EXT_external_memory_dma_buf")) dmabuf = true; + else if (!std::strcmp(e.extensionName, "VK_KHR_external_semaphore_fd")) semfd = true; + else if (!std::strcmp(e.extensionName, "VK_KHR_external_semaphore")) es = true; + else if (!std::strcmp(e.extensionName, "VK_EXT_queue_family_foreign")) qff = true; + } + if (!(em && emfd && dmabuf)) continue; + int score = 10 + ((props.vendorID == 0x1010u || std::strstr(props.deviceName, "PowerVR")) ? 100 : 0) + + ((semfd && es) ? 10 : 0); + if (score > best) { + best = score; + phys = pd; + vendor_id = props.vendorID; + has_sem_fd = semfd && es; + has_qf_foreign = qff; + std::snprintf(device_name, sizeof(device_name), "%.255s", props.deviceName); + } + } + if (!phys) { + *err = "no Vulkan device with VK_EXT_external_memory_dma_buf matched"; + return false; + } + vkGetPhysicalDeviceMemoryProperties(phys, &mem_props); + uint32_t nq = 0u; + vkGetPhysicalDeviceQueueFamilyProperties(phys, &nq, nullptr); + std::vector qfs(nq); + vkGetPhysicalDeviceQueueFamilyProperties(phys, &nq, qfs.data()); + for (uint32_t q = 0u; q < nq; ++q) { + if (qfs[q].queueCount && (qfs[q].queueFlags & VK_QUEUE_COMPUTE_BIT)) { + qf = q; + break; + } + } + if (qf == UINT32_MAX) { + *err = "no compute queue"; + return false; + } + std::vector dev_exts = {"VK_KHR_external_memory", "VK_KHR_external_memory_fd", + "VK_EXT_external_memory_dma_buf"}; + if (has_sem_fd) { + dev_exts.push_back("VK_KHR_external_semaphore"); + dev_exts.push_back("VK_KHR_external_semaphore_fd"); + } + /* + * DMA-BUFs shared with the EdgeTPU are owned by a non-Vulkan device, which only + * VK_QUEUE_FAMILY_FOREIGN_EXT (VK_EXT_queue_family_foreign) can represent. + * VK_QUEUE_FAMILY_EXTERNAL is limited to the same physical device and driver, + * so it is NOT a valid fallback: without the extension the accelerator + * backends (openbuenos, nnapi) report themselves unavailable in select_tpu(). + */ + if (has_qf_foreign) dev_exts.push_back("VK_EXT_queue_family_foreign"); + const float prio = 1.0f; + VkDeviceQueueCreateInfo qci{}; + qci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + qci.queueFamilyIndex = qf; + qci.queueCount = 1u; + qci.pQueuePriorities = &prio; + VkDeviceCreateInfo dci{}; + dci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + dci.queueCreateInfoCount = 1u; + dci.pQueueCreateInfos = &qci; + dci.enabledExtensionCount = static_cast(dev_exts.size()); + dci.ppEnabledExtensionNames = dev_exts.data(); + if (vkCreateDevice(phys, &dci, nullptr, &device) != VK_SUCCESS) { + *err = "vkCreateDevice failed"; + return false; + } + /* + * Without foreign ownership the only remaining consumer is the CPU-emulated + * TPU (--tpu-backend cpu), which touches the DMA-BUFs from the host only + * (DMA_BUF_IOCTL_SYNC + HOST-stage barriers). The tensors then stay owned by + * the compute queue family and no queue-family transfer is recorded. + */ + ext_qf = has_qf_foreign ? VK_QUEUE_FAMILY_FOREIGN_EXT : qf; +#define FS_TL_LOAD_D(fn) fn = reinterpret_cast(vkGetDeviceProcAddr(device, #fn)); + FS_TL_VK_DEVICE_FNS(FS_TL_LOAD_D) +#undef FS_TL_LOAD_D + if (!vkQueueSubmit || !vkCreateBuffer || !vkGetMemoryFdPropertiesKHR || !vkCreateComputePipelines) { + *err = "required Vulkan device entry points missing"; + return false; + } + if (!vkGetSemaphoreFdKHR || !vkImportSemaphoreFdKHR) has_sem_fd = false; + vkGetDeviceQueue(device, qf, 0u, &queue); + + VkCommandPoolCreateInfo cpci{}; + cpci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + cpci.queueFamilyIndex = qf; + if (vkCreateCommandPool(device, &cpci, nullptr, &cmd_pool) != VK_SUCCESS) { + *err = "vkCreateCommandPool failed"; + return false; + } + VkFenceCreateInfo fci{}; + fci.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + if (vkCreateFence(device, &fci, nullptr, &fence) != VK_SUCCESS) { + *err = "vkCreateFence failed"; + return false; + } + if (has_sem_fd) { + VkExportSemaphoreCreateInfo esci{}; + esci.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO; + esci.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT; + VkSemaphoreCreateInfo sci{}; + sci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + sci.pNext = &esci; + VkSemaphoreCreateInfo plain{}; + plain.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + if (vkCreateSemaphore(device, &sci, nullptr, &sem_export) != VK_SUCCESS || + vkCreateSemaphore(device, &plain, nullptr, &sem_import) != VK_SUCCESS) { + has_sem_fd = false; + } + } + VkDescriptorSetLayoutBinding b[4]{}; + for (uint32_t i = 0u; i < 4u; ++i) { + b[i].binding = i; + b[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + b[i].descriptorCount = 1u; + b[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + } + VkDescriptorSetLayoutCreateInfo dslci{}; + dslci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + dslci.bindingCount = 4u; + dslci.pBindings = b; + if (vkCreateDescriptorSetLayout(device, &dslci, nullptr, &dsl) != VK_SUCCESS) { + *err = "vkCreateDescriptorSetLayout failed"; + return false; + } + /* Every set uses the 4-binding storage-buffer layout above. */ + VkDescriptorPoolSize ps{}; + ps.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + ps.descriptorCount = 4u * max_sets; + VkDescriptorPoolCreateInfo dpci{}; + dpci.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + dpci.maxSets = max_sets; + dpci.poolSizeCount = 1u; + dpci.pPoolSizes = &ps; + if (vkCreateDescriptorPool(device, &dpci, nullptr, &dpool) != VK_SUCCESS) { + *err = "vkCreateDescriptorPool failed"; + return false; + } + return create_pipeline(g_volcanic_prefill_gemm_f32_spv, sizeof(g_volcanic_prefill_gemm_f32_spv), 16u, + &gemv_layout, &gemv_pipe, err) && + create_pipeline(g_volcanic_residual_rmsnorm_f32_spv, sizeof(g_volcanic_residual_rmsnorm_f32_spv), + 8u, &norm_layout, &norm_pipe, err); + } + + bool create_pipeline(const uint32_t* spv, size_t bytes, uint32_t push_bytes, VkPipelineLayout* out_layout, + VkPipeline* out_pipe, std::string* err) { + VkShaderModuleCreateInfo smci{}; + smci.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + smci.codeSize = bytes; + smci.pCode = spv; + VkShaderModule sm = VK_NULL_HANDLE; + if (vkCreateShaderModule(device, &smci, nullptr, &sm) != VK_SUCCESS) { + *err = "vkCreateShaderModule failed"; + return false; + } + VkPushConstantRange pcr{}; + pcr.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + pcr.size = push_bytes; + VkPipelineLayoutCreateInfo plci{}; + plci.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + plci.setLayoutCount = 1u; + plci.pSetLayouts = &dsl; + plci.pushConstantRangeCount = 1u; + plci.pPushConstantRanges = &pcr; + if (vkCreatePipelineLayout(device, &plci, nullptr, out_layout) != VK_SUCCESS) { + vkDestroyShaderModule(device, sm, nullptr); + *err = "vkCreatePipelineLayout failed"; + return false; + } + VkComputePipelineCreateInfo cpci{}; + cpci.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; + cpci.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + cpci.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + cpci.stage.module = sm; + cpci.stage.pName = "main"; + cpci.layout = *out_layout; + const VkResult rc = vkCreateComputePipelines(device, VK_NULL_HANDLE, 1u, &cpci, nullptr, out_pipe); + vkDestroyShaderModule(device, sm, nullptr); + if (rc != VK_SUCCESS) { + *err = "vkCreateComputePipelines failed"; + return false; + } + return true; + } + + bool import_dmabuf(const fs_dmabuf_t* b, VkDmaBuffer* out, std::string* err) { + return import_fd(b->dmabuf_fd, b->size, out, err); + } + + /* Imports any DMA-BUF fd (borrowed; dup()ed for Vulkan) as a storage buffer. */ + bool import_fd(int src_fd, size_t size, VkDmaBuffer* out, std::string* err) { + *out = VkDmaBuffer{}; + VkExternalMemoryBufferCreateInfo embci{}; + embci.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO; + embci.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT; + VkBufferCreateInfo bci{}; + bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bci.pNext = &embci; + bci.size = static_cast(size); + bci.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + if (vkCreateBuffer(device, &bci, nullptr, &out->buffer) != VK_SUCCESS) { + *err = "vkCreateBuffer(DMA_BUF) failed"; + return false; + } + VkMemoryRequirements reqs{}; + vkGetBufferMemoryRequirements(device, out->buffer, &reqs); + VkMemoryFdPropertiesKHR fdp{}; + fdp.sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR; + if (vkGetMemoryFdPropertiesKHR(device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, src_fd, &fdp) != + VK_SUCCESS) { + *err = "vkGetMemoryFdPropertiesKHR(DMA_BUF) failed"; + return false; + } + const uint32_t bits = reqs.memoryTypeBits & fdp.memoryTypeBits; + uint32_t idx = UINT32_MAX; + for (uint32_t pass = 0u; pass < 2u && idx == UINT32_MAX; ++pass) { + for (uint32_t i = 0u; i < mem_props.memoryTypeCount; ++i) { + const bool dev_local = (mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0u; + if ((bits & (1u << i)) && (pass == 1u || dev_local)) { + idx = i; + break; + } + } + } + if (idx == UINT32_MAX) { + *err = "no Vulkan memory type compatible with DMA-BUF"; + return false; + } + const int fd = dup_cloexec(src_fd); + if (fd < 0) { + *err = "dup(dmabuf_fd) failed"; + return false; + } + VkImportMemoryFdInfoKHR imp{}; + imp.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR; + imp.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT; + imp.fd = fd; + VkMemoryAllocateInfo mai{}; + mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + mai.pNext = &imp; + mai.allocationSize = std::max(reqs.size, static_cast(size)); + mai.memoryTypeIndex = idx; + if (vkAllocateMemory(device, &mai, nullptr, &out->memory) != VK_SUCCESS) { + close(fd); + *err = "vkAllocateMemory(DMA_BUF import) failed"; + return false; + } + if (vkBindBufferMemory(device, out->buffer, out->memory, 0u) != VK_SUCCESS) { + *err = "vkBindBufferMemory failed"; + return false; + } + out->size = static_cast(size); + return true; + } + + void destroy_buffer(VkDmaBuffer* b) { + if (!device) return; + if (b->buffer) vkDestroyBuffer(device, b->buffer, nullptr); + if (b->memory) vkFreeMemory(device, b->memory, nullptr); + *b = VkDmaBuffer{}; + } + + bool alloc_set(const VkDmaBuffer* const bufs[4], VkDescriptorSet* out) { + VkDescriptorSetAllocateInfo ai{}; + ai.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + ai.descriptorPool = dpool; + ai.descriptorSetCount = 1u; + ai.pSetLayouts = &dsl; + if (vkAllocateDescriptorSets(device, &ai, out) != VK_SUCCESS) return false; + VkDescriptorBufferInfo infos[4]{}; + VkWriteDescriptorSet w[4]{}; + for (uint32_t i = 0u; i < 4u; ++i) { + infos[i].buffer = bufs[i]->buffer; + infos[i].range = bufs[i]->size; + w[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + w[i].dstSet = *out; + w[i].dstBinding = i; + w[i].descriptorCount = 1u; + w[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + w[i].pBufferInfo = &infos[i]; + } + vkUpdateDescriptorSets(device, 4u, w, 0u, nullptr); + return true; + } + + void barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, VkAccessFlags src, + VkPipelineStageFlags dst_stage, VkAccessFlags dst) { + VkMemoryBarrier mb{}; + mb.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; + mb.srcAccessMask = src; + mb.dstAccessMask = dst; + vkCmdPipelineBarrier(cb, src_stage, dst_stage, 0u, 1u, &mb, 0u, nullptr, 0u, nullptr); + } + + /* + * Queue-family ownership transfer of the DMA-BUF tensors shared with the + * EdgeTPU. Between GPU submissions every shared tensor is owned by ext_qf + * (the TPU side): a GPU stage acquires it (ext_qf -> qf) before its first + * access and releases it (qf -> ext_qf) after its last one, so GPU writes + * are made available to the external device and TPU writes become visible + * to the GPU. Buffers are VK_SHARING_MODE_EXCLUSIVE; contents are preserved. + */ + void transfer_ownership(VkCommandBuffer cb, const VkBuffer* bufs, uint32_t n, bool acquire) { + VkBufferMemoryBarrier bmb[2]{}; + uint32_t m = 0u; + for (uint32_t i = 0u; i < n && m < 2u; ++i) { + if (bufs[i] == VK_NULL_HANDLE) continue; + VkBufferMemoryBarrier& b = bmb[m++]; + b.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + b.srcAccessMask = acquire ? 0u : static_cast(VK_ACCESS_SHADER_WRITE_BIT); + b.dstAccessMask = + acquire ? static_cast(VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT) : 0u; + b.srcQueueFamilyIndex = acquire ? ext_qf : qf; + b.dstQueueFamilyIndex = acquire ? qf : ext_qf; + b.buffer = bufs[i]; + b.offset = 0u; + b.size = VK_WHOLE_SIZE; + } + if (m == 0u || ext_qf == qf) return; /* host-only CPU backend: no ownership transfer */ + vkCmdPipelineBarrier(cb, acquire ? VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + acquire ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0u, + 0u, nullptr, m, bmb, 0u, nullptr); + ownership_barriers += m; + } + + /* + * [optional residual+RMSNorm of layer l-1] -> [optional GEMV of layer l], recorded once. + * ext_in: TPU-produced tensor read by the norm (Y[l-1]); ext_out: GPU-produced tensor + * the TPU reads next (A[l]). Either may be VK_NULL_HANDLE. + */ + bool record(VkCommandBuffer cb, VkDescriptorSet norm_set, VkDescriptorSet gemv_set, uint32_t d, float eps, + VkBuffer ext_in, VkBuffer ext_out) { + VkCommandBufferBeginInfo bi{}; + bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + if (vkBeginCommandBuffer(cb, &bi) != VK_SUCCESS) return false; + const VkBuffer shared[2] = {ext_in, ext_out}; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + transfer_ownership(cb, shared, 2u, true); + if (norm_set != VK_NULL_HANDLE) { + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, norm_pipe); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, norm_layout, 0u, 1u, &norm_set, 0u, nullptr); + uint32_t pc[2] = {d, 0u}; + std::memcpy(&pc[1], &eps, sizeof(float)); + vkCmdPushConstants(cb, norm_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(pc), pc); + vkCmdDispatch(cb, 1u, 1u, 1u); + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + } + if (gemv_set != VK_NULL_HANDLE) { + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, gemv_pipe); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, gemv_layout, 0u, 1u, &gemv_set, 0u, nullptr); + const uint32_t pc[4] = {1u, d, d, 0u}; /* M=1 decode row, K=d, N=d, decode_row=0 */ + vkCmdPushConstants(cb, gemv_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(pc), pc); + vkCmdDispatch(cb, (d + 15u) / 16u, 1u, 1u); + } + transfer_ownership(cb, shared, 2u, false); + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_HOST_READ_BIT); + return vkEndCommandBuffer(cb) == VK_SUCCESS; + } + + /* FP32 <-> QUANT8_ASYMM bridge pipelines (EdgeTPU NNAPI stage). */ + bool init_quant(std::string* err) { + if (quant_pipe != VK_NULL_HANDLE) return true; + return create_pipeline(g_volcanic_quant_f32_u8_spv, sizeof(g_volcanic_quant_f32_u8_spv), 16u, &quant_layout, + &quant_pipe, err) && + create_pipeline(g_volcanic_dequant_u8_f32_spv, sizeof(g_volcanic_dequant_u8_f32_spv), 16u, + &dequant_layout, &dequant_pipe, err); + } + + bool make_semaphore(bool exportable, VkSemaphore* out) { + *out = VK_NULL_HANDLE; + VkExportSemaphoreCreateInfo esci{}; + esci.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO; + esci.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT; + VkSemaphoreCreateInfo sci{}; + sci.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + sci.pNext = exportable ? &esci : nullptr; + return vkCreateSemaphore(device, &sci, nullptr, out) == VK_SUCCESS; + } + void destroy_semaphore(VkSemaphore* s) { + if (device && *s) vkDestroySemaphore(device, *s, nullptr); + *s = VK_NULL_HANDLE; + } + + void wait_idle() { + if (device && queue) vkQueueWaitIdle(queue); + } + /* Whole-device drain for failure recovery: VK_SUCCESS proves no queued GPU work remains. */ + VkResult device_wait_idle() { + if (!device || !vkDeviceWaitIdle) return VK_ERROR_INITIALIZATION_FAILED; + return vkDeviceWaitIdle(device); + } + /* Bounded completion check. Never a substitute for an idle proof when the queue is blocked. */ + VkResult wait_fence_bounded(uint64_t timeout_ns) { + if (!device || !fence || !vkWaitForFences) return VK_ERROR_INITIALIZATION_FAILED; + return vkWaitForFences(device, 1u, &fence, VK_TRUE, timeout_ns); + } + bool export_replace_pending() const { return pending_signaled_export_ != nullptr; } + /* + * vkQueueSubmit succeeded and vkGetSemaphoreFdKHR failed, so `slot` is a + * signaled binary semaphore. Drain, then replace it. Callers must already + * have released any imported IIF gate; this uses vkDeviceWaitIdle. + * A failed drain or recreate sets export_semaphore_recovery_failed and leaves + * the semaphore unreplaced. + */ + bool replace_pending_signaled_export() { + if (!pending_signaled_export_) return true; + VkSemaphore* slot = pending_signaled_export_; + const VkResult vr = device_wait_idle(); + if (vr != VK_SUCCESS) { + export_semaphore_recovery_failed = true; + return false; + } + destroy_semaphore(slot); + pending_signaled_export_ = nullptr; + if (!make_semaphore(true, slot)) { + export_semaphore_recovery_failed = true; + return false; + } + return true; + } + + void dispatch_bridge(VkCommandBuffer cb, bool quantize, VkDescriptorSet set, uint32_t d, const Quant8& q) { + const VkPipeline pipe = quantize ? quant_pipe : dequant_pipe; + const VkPipelineLayout lay = quantize ? quant_layout : dequant_layout; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, lay, 0u, 1u, &set, 0u, nullptr); + const float s = quantize ? 1.0f / q.scale : q.scale; + uint32_t pc[4] = {d, 0u, static_cast(q.zero_point), 0u}; + std::memcpy(&pc[1], &s, sizeof(float)); + vkCmdPushConstants(cb, lay, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(pc), pc); + vkCmdDispatch(cb, (d / 4u + 63u) / 64u, 1u, 1u); + } + + /* + * EdgeTPU NNAPI flavour of record(): [dequant Y[l-1] (u8) -> FP32] -> + * [residual + RMSNorm of l-1] -> [GEMV of l] -> [quant A[l] FP32 -> u8]. + * ext_in: uint8 Y[l-1] the EdgeTPU wrote; ext_out: uint8 A[l] the EdgeTPU reads next. + */ + bool record_q(VkCommandBuffer cb, VkDescriptorSet deq_set, VkDescriptorSet norm_set, VkDescriptorSet gemv_set, + VkDescriptorSet q_set, uint32_t d, float eps, const Quant8* yq, const Quant8* aq, VkBuffer ext_in, + VkBuffer ext_out) { + VkCommandBufferBeginInfo bi{}; + bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + if (vkBeginCommandBuffer(cb, &bi) != VK_SUCCESS) return false; + const VkPipelineStageFlags cs = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; + const VkAccessFlags rw = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + const VkBuffer shared[2] = {ext_in, ext_out}; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, cs, rw); + transfer_ownership(cb, shared, 2u, true); + if (deq_set != VK_NULL_HANDLE && yq) { + dispatch_bridge(cb, false, deq_set, d, *yq); + barrier(cb, cs, VK_ACCESS_SHADER_WRITE_BIT, cs, rw); + } + if (norm_set != VK_NULL_HANDLE) { + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, norm_pipe); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, norm_layout, 0u, 1u, &norm_set, 0u, nullptr); + uint32_t pc[2] = {d, 0u}; + std::memcpy(&pc[1], &eps, sizeof(float)); + vkCmdPushConstants(cb, norm_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(pc), pc); + vkCmdDispatch(cb, 1u, 1u, 1u); + barrier(cb, cs, VK_ACCESS_SHADER_WRITE_BIT, cs, rw); + } + if (gemv_set != VK_NULL_HANDLE) { + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, gemv_pipe); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, gemv_layout, 0u, 1u, &gemv_set, 0u, nullptr); + const uint32_t pc[4] = {1u, d, d, 0u}; + vkCmdPushConstants(cb, gemv_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(pc), pc); + vkCmdDispatch(cb, (d + 15u) / 16u, 1u, 1u); + if (q_set != VK_NULL_HANDLE && aq) { + barrier(cb, cs, VK_ACCESS_SHADER_WRITE_BIT, cs, rw); + dispatch_bridge(cb, true, q_set, d, *aq); + } + } + transfer_ownership(cb, shared, 2u, false); + barrier(cb, cs, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_HOST_READ_BIT); + return vkEndCommandBuffer(cb) == VK_SUCCESS; + } + + /* + * Submits `cb`. wait_fd (owned, may be -1) is imported as a temporary SYNC_FD + * payload of `imp` (or, if allow_poll, CPU-polled when import is unavailable; + * otherwise closed and the submit fails). If export_fd != nullptr the + * completion is signaled on `exp` and exported as a SYNC_FD. + */ + bool submit_ex(VkCommandBuffer cb, int wait_fd, VkSemaphore imp, VkSemaphore* exp, int* export_fd, bool use_fence, + bool allow_poll, TokenCounters* c) { + if (export_fd) *export_fd = -1; + VkSemaphore exp_sem = (exp && *exp != VK_NULL_HANDLE) ? *exp : VK_NULL_HANDLE; + VkSemaphore wait_sem = VK_NULL_HANDLE; + /* + * Every recorded command buffer starts with a foreign -> compute queue-family + * ownership acquire of the TPU-written tensors. Legacy (non-sync2) acquires run + * outside the defined pipeline stages, so a COMPUTE_SHADER wait would let the + * acquire execute before the EdgeTPU signal. Block all commands instead. + */ + const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + if (wait_fd >= 0) { + bool imported = false; + if (has_sem_fd && imp != VK_NULL_HANDLE) { + VkImportSemaphoreFdInfoKHR ii{}; + ii.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR; + ii.semaphore = imp; + ii.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT; + ii.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT; + ii.fd = wait_fd; + imported = vkImportSemaphoreFdKHR(device, &ii) == VK_SUCCESS; /* fd owned by driver on success */ + } + if (imported) { + wait_sem = imp; + c->sync_files_imported += 1u; + } else if (allow_poll) { + const bool ok = poll_sync_fd_timed(wait_fd, 5000, c); + close(wait_fd); + c->userspace_fence_polls += 1u; + if (!ok) return false; + } else { + close(wait_fd); + return false; + } + } + VkSubmitInfo si{}; + si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + si.commandBufferCount = 1u; + si.pCommandBuffers = &cb; + if (wait_sem != VK_NULL_HANDLE) { + si.waitSemaphoreCount = 1u; + si.pWaitSemaphores = &wait_sem; + si.pWaitDstStageMask = &wait_stage; + } + const bool do_export = export_fd && has_sem_fd && exp_sem != VK_NULL_HANDLE; + if (do_export) { + si.signalSemaphoreCount = 1u; + si.pSignalSemaphores = &exp_sem; + } + if (use_fence) vkResetFences(device, 1u, &fence); + const uint64_t ts = now_ns(); + const VkResult sr = vkQueueSubmit(queue, 1u, &si, use_fence ? fence : VK_NULL_HANDLE); + c->dispatch_submit_us += us_since(ts); + if (sr != VK_SUCCESS) return false; + if (do_export) { + VkSemaphoreGetFdInfoKHR gi{}; + gi.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR; + gi.semaphore = exp_sem; + gi.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT; + int fd = -1; + if (vkGetSemaphoreFdKHR(device, &gi, &fd) != VK_SUCCESS) { + /* + * The submit already signaled this binary semaphore. Remember the slot + * so the caller can replace it after any imported IIF gate is released. + * Do not vkDeviceWaitIdle here: the queue may still be blocked on that gate. + */ + pending_signaled_export_ = exp; + return false; + } + *export_fd = fd; /* -1 is legal: payload already signaled */ + c->sync_files_exported += 1u; + } + return true; + } + + bool submit(VkCommandBuffer cb, int wait_fd, int* export_fd, bool use_fence, TokenCounters* c) { + return submit_ex(cb, wait_fd, sem_import, &sem_export, export_fd, use_fence, true, c); + } + + bool wait_fence(TokenCounters* c, bool* timed_out = nullptr) { + if (timed_out) *timed_out = false; + const uint64_t tw = now_ns(); + const VkResult vr = vkWaitForFences(device, 1u, &fence, VK_TRUE, 5000000000ull); + c->host_wait_us += us_since(tw); + if (vr == VK_TIMEOUT && timed_out) *timed_out = true; + return vr == VK_SUCCESS; + } + + void shutdown() { + if (device) { + if (queue) vkQueueWaitIdle(queue); + if (sem_export) vkDestroySemaphore(device, sem_export, nullptr); + if (sem_import) vkDestroySemaphore(device, sem_import, nullptr); + if (fence) vkDestroyFence(device, fence, nullptr); + if (gemv_pipe) vkDestroyPipeline(device, gemv_pipe, nullptr); + if (norm_pipe) vkDestroyPipeline(device, norm_pipe, nullptr); + if (quant_pipe) vkDestroyPipeline(device, quant_pipe, nullptr); + if (dequant_pipe) vkDestroyPipeline(device, dequant_pipe, nullptr); + if (quant_layout) vkDestroyPipelineLayout(device, quant_layout, nullptr); + if (dequant_layout) vkDestroyPipelineLayout(device, dequant_layout, nullptr); + if (gemv_layout) vkDestroyPipelineLayout(device, gemv_layout, nullptr); + if (norm_layout) vkDestroyPipelineLayout(device, norm_layout, nullptr); + if (dpool) vkDestroyDescriptorPool(device, dpool, nullptr); + if (dsl) vkDestroyDescriptorSetLayout(device, dsl, nullptr); + if (cmd_pool) vkDestroyCommandPool(device, cmd_pool, nullptr); + vkDestroyDevice(device, nullptr); + device = VK_NULL_HANDLE; + } + if (instance && vkDestroyInstance) vkDestroyInstance(instance, nullptr); + instance = VK_NULL_HANDLE; + if (dl) dlclose(dl); + dl = nullptr; + } +}; + +enum TpuKind { TPU_CPU = 0, TPU_OB = 1, TPU_NNAPI = 2 }; + +/* One GPU<->TPU shared QUANT8 tensor: AHB BLOB (preferred) or a pinned pool DMA-BUF. */ +struct QBuf { + void* ahb = nullptr; /* owned AHardwareBuffer (ahb mode) */ + fs_dmabuf_t* pool = nullptr; /* borrowed pool slot (dmabuf_fd mode) */ + int fd = -1; /* borrowed DMA-BUF fd backing the tensor */ + size_t bytes = 0u; + VkDmaBuffer vk; + void* nn_mem = nullptr; +}; + +class LiveExecutor : public Executor { + public: + LiveExecutor(const Model& m, Pools* p, IifFences* iif, const IifConfig& ic, const QuantCal& qc, + const char* req_backend, const char* nn_device, const char* nn_mem) + : Executor(p), m_(m), p_(p), iif_(iif), ic_(ic), qc_(qc), req_(req_backend), nn_device_(nn_device), + nn_mem_req_(nn_mem), + stage_in_(m.d), stage_out_(m.d), ones_(m.d, 1.0f), stage_in_u8_(m.d), stage_out_u8_(m.d) {} + ~LiveExecutor() override { shutdown(); } + + const char* name() const override { + return tpu_ == TPU_NNAPI ? "live_vulkan_nnapi" : (tpu_ == TPU_OB ? "live_vulkan_openbuenos" : "live_vulkan_cpu_tpu"); + } + const char* tpu_name() const { return tpu_ == TPU_NNAPI ? "nnapi" : (tpu_ == TPU_OB ? "openbuenos" : "cpu"); } + bool quant() const { return tpu_ == TPU_NNAPI; } + const std::string& fallback_reason() const { return fallback_reason_; } + const char* nn_device() const { return nn_.device_name(); } + int64_t nn_feature_level() const { return nn_.device_feature_level(); } + const std::string& nn_mem_mode() const { return nn_mem_mode_; } + const std::string& nn_mem_fallback() const { return mem_fallback_reason_; } + const std::string& staged_mem_mode() const { return staged_mem_mode_; } + const std::string& staged_mem_fallback() const { return staged_fallback_reason_; } + const char* vk_ext_qf_name() const { return vk_.has_qf_foreign ? "foreign_ext" : "none_host_only"; } + uint64_t vk_ownership_barriers() const { return vk_.ownership_barriers; } + bool nn_reusable() const { return nn_.reusable(); } + bool nn_fenced() const { return nn_.fenced_api(); } + const char* nn_fenced_dmabuf_policy() const { return nn_.fenced_policy(); } + uint64_t nn_fenced_refusals() const { return nn_.fenced_refusals(); } + uint64_t nn_exec_start_calls() const { return nn_.exec_start_calls(); } + /* Debug-only opt-in to fenced DMA-BUF execution on an EdgeTPU (see nnapi_fenced_dmabuf_block_reason()). */ + void set_allow_edgetpu_dmabuf_fenced_probe(bool on) { allow_edgetpu_dmabuf_probe_ = on; } + /* + * The NNAPI chain imports the IIF gate into the GPU queue, which needs a working + * FS_IIF_FENCE_BRIDGE_DMA sync_file (IifProbe::bridge_dma_ok). Raw kernel IIF + * without the bridge stays available for the CPU-proxy handoffs only. + */ + bool iif_gate() const { return tpu_ == TPU_NNAPI && iif_nnapi_gate_enabled(iif_->kind(), iif_bridge_dma_ok_); } + void set_iif_bridge_dma_ok(bool ok) { iif_bridge_dma_ok_ = ok; } + + const char* arm_unavailable(Arm arm) const override { + if (tpu_ == TPU_NNAPI) { + /* Never alias the zero-copy tensors from the CPU: no isolated staging -> no host_staged arm. */ + if (arm == ARM_HOST_STAGED) return staged_isolated() ? nullptr : "host_staged_isolated_staging_unavailable"; + /* EdgeTPU x dmabuf_fd x fenced execution: skipped before any dispatch (shared HAL crash). */ + if (const char* why = nn_.fenced_block_reason()) return why; + if (!vk_.has_sem_fd) return "vk_external_semaphore_sync_fd_unavailable"; + if (const char* why = nn_.fenced_feature_level_block_reason()) return why; + if (!nn_.fenced_api()) return "nnapi_fenced_execution_unavailable"; + if (arm == ARM_R_IIF && sem_in_.size() != m_.layers + 1u) return "vk_chain_semaphores_unavailable"; + return nullptr; + } + if (arm == ARM_SYNC_FILE && !vk_.has_sem_fd) return "vk_external_semaphore_sync_fd_unavailable"; + if (arm == ARM_R_IIF && !iif_cpu_proxy_available(iif_->kind())) return "iif_unavailable"; + return nullptr; + } + const VkRunner& vk() const { return vk_; } + + bool init(const char* preferred, const char* heap, const char* dive, std::string* err) { + const uint32_t L = m_.layers; + /* + * Descriptor sets per layer: GEMV + RMSNorm, the QUANT8 quant + dequant + * bridge, and the isolated host_staged quant + dequant bridge = 6 sets + * (24 storage-buffer descriptors). The TPU backend is chosen after Vulkan + * init, so the pool always budgets the maximum. + */ + if (!vk_.init(preferred, 6u * L, err)) return false; + const uint32_t n_small = SLOT_PARAM_BASE + 2u * L; + vsmall_.resize(n_small); + vw_.resize(L); + for (uint32_t s = 0u; s < n_small; ++s) { + if (!vk_.import_dmabuf(p_->sbuf(s), &vsmall_[s], err)) return false; + } + for (uint32_t l = 0u; l < L; ++l) { + if (!vk_.import_dmabuf(p_->wbuf(l), &vw_[l], err)) return false; + } + if (!select_tpu(heap, dive, err)) return false; + gemv_sets_.resize(L); + norm_sets_.resize(L); + for (uint32_t l = 0u; l < L; ++l) { + const VkDmaBuffer* g[4] = {&vsmall_[SLOT_X], &vw_[l], &vsmall_[SLOT_H], &vsmall_[p_->mid_slot(l)]}; + const VkDmaBuffer* n[4] = {&vsmall_[p_->out_slot(l)], &vsmall_[p_->scale_slot(l)], &vsmall_[SLOT_X], + &vsmall_[p_->gamma_slot(l)]}; + if (!vk_.alloc_set(g, &gemv_sets_[l]) || !vk_.alloc_set(n, &norm_sets_[l])) { + *err = "vkAllocateDescriptorSets failed"; + return false; + } + } + if (quant()) { + q_sets_.resize(L); + deq_sets_.resize(L); + for (uint32_t l = 0u; l < L; ++l) { + const uint32_t pp = l & 1u; + const VkDmaBuffer* q[4] = {&vsmall_[p_->mid_slot(l)], &qmid_[pp].vk, &vsmall_[SLOT_H], &vsmall_[SLOT_H]}; + const VkDmaBuffer* dq[4] = {&qout_[pp].vk, &vsmall_[p_->out_slot(l)], &vsmall_[SLOT_H], &vsmall_[SLOT_H]}; + if (!vk_.alloc_set(q, &q_sets_[l]) || !vk_.alloc_set(dq, &deq_sets_[l])) { + *err = "vkAllocateDescriptorSets(quant8 bridge) failed"; + return false; + } + } + if (staged_isolated()) { + hq_sets_.resize(L); + hdeq_sets_.resize(L); + for (uint32_t l = 0u; l < L; ++l) { + const uint32_t pp = l & 1u; + const VkDmaBuffer* q[4] = {&vsmall_[p_->mid_slot(l)], &hmid_[pp].vk, &vsmall_[SLOT_H], &vsmall_[SLOT_H]}; + const VkDmaBuffer* dq[4] = {&hout_[pp].vk, &vsmall_[p_->out_slot(l)], &vsmall_[SLOT_H], &vsmall_[SLOT_H]}; + if (!vk_.alloc_set(q, &hq_sets_[l]) || !vk_.alloc_set(dq, &hdeq_sets_[l])) { + *err = "vkAllocateDescriptorSets(host-staged quant8 bridge) failed"; + return false; + } + } + } + } + cmds_.resize(L + 1u); + VkCommandBufferAllocateInfo cai{}; + cai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + cai.commandPool = vk_.cmd_pool; + cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cai.commandBufferCount = L + 1u; + if (vk_.vkAllocateCommandBuffers(vk_.device, &cai, cmds_.data()) != VK_SUCCESS) { + *err = "vkAllocateCommandBuffers failed"; + return false; + } + if (quant() && staged_isolated()) { + hcmds_.resize(L + 1u); + if (vk_.vkAllocateCommandBuffers(vk_.device, &cai, hcmds_.data()) != VK_SUCCESS) { + *err = "vkAllocateCommandBuffers(host-staged) failed"; + return false; + } + for (uint32_t l = 0u; l <= L; ++l) { + const VkDescriptorSet ns = (l > 0u) ? norm_sets_[l - 1u] : VK_NULL_HANDLE; + const VkDescriptorSet gs = (l < L) ? gemv_sets_[l] : VK_NULL_HANDLE; + if (!vk_.record_q(hcmds_[l], (l > 0u) ? hdeq_sets_[l - 1u] : VK_NULL_HANDLE, ns, gs, + (l < L) ? hq_sets_[l] : VK_NULL_HANDLE, m_.d, m_.eps, (l > 0u) ? &qc_.y[l - 1u] : nullptr, + (l < L) ? &qc_.a[l] : nullptr, (l > 0u) ? hout_[(l - 1u) & 1u].vk.buffer : VK_NULL_HANDLE, + (l < L) ? hmid_[l & 1u].vk.buffer : VK_NULL_HANDLE)) { + *err = "Vulkan command buffer recording (host-staged) failed"; + return false; + } + } + } + for (uint32_t l = 0u; l <= L; ++l) { + const VkDescriptorSet ns = (l > 0u) ? norm_sets_[l - 1u] : VK_NULL_HANDLE; + const VkDescriptorSet gs = (l < L) ? gemv_sets_[l] : VK_NULL_HANDLE; + bool rok; + if (quant()) { + rok = vk_.record_q(cmds_[l], (l > 0u) ? deq_sets_[l - 1u] : VK_NULL_HANDLE, ns, gs, + (l < L) ? q_sets_[l] : VK_NULL_HANDLE, m_.d, m_.eps, (l > 0u) ? &qc_.y[l - 1u] : nullptr, + (l < L) ? &qc_.a[l] : nullptr, (l > 0u) ? qout_[(l - 1u) & 1u].vk.buffer : VK_NULL_HANDLE, + (l < L) ? qmid_[l & 1u].vk.buffer : VK_NULL_HANDLE); + } else { + /* W8A16: Y[l-1] (out slot) is TPU-written, A[l] (mid slot) is TPU-read. */ + rok = vk_.record(cmds_[l], ns, gs, m_.d, m_.eps, + (l > 0u) ? vsmall_[p_->out_slot(l - 1u)].buffer : VK_NULL_HANDLE, + (l < L) ? vsmall_[p_->mid_slot(l)].buffer : VK_NULL_HANDLE); + } + if (!rok) { + *err = "Vulkan command buffer recording failed"; + return false; + } + } + return true; + } + + void mark_live_fence_timeout(const std::string& why) { + gpu_queue_blocked_ = true; + mark_fence_timeout(why); + } + + /* Cross-thread poll() of one real sync_file fd (same accounting as the NNAPI sync_file_poll arm). */ + bool wait_on_waiter(int fd, int timeout_ms, TokenCounters* c, bool* timed_out = nullptr) { + const uint64_t tw = now_ns(); + const bool ok = waiter_.wait(fd, timeout_ms, timed_out); + c->host_wait_us += us_since(tw); + c->userspace_fence_polls += 1u; + c->userspace_wakeups += 1u; + return ok; + } + + bool run_token(Arm arm, uint32_t tok, float* out_hidden, TokenCounters* c, std::string* err) override { + if (tpu_ == TPU_NNAPI) return run_token_nnapi(arm, tok, out_hidden, c, err); + /* W8A16 sync_file_poll waits on FdWaiter; setup_nnapi() is the only other starter. */ + if (arm == ARM_SYNC_FILE) waiter_.start(); + const uint32_t d = m_.d; + fs_context_t* ctx = p_->ctx; + fs_dmabuf_t* xb = p_->sbuf(SLOT_X); + if (!cpu_write(ctx, xb, m_.embed.data() + static_cast(tok) * d, d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "embedding upload failed"; + return false; + } + const uint32_t proxy_ip_gpu = (iif_->kind() == FS_IIF_BACKEND_KERNEL) ? ic_.ap_ip : ic_.gpu_ip; + for (uint32_t l = 0u; l < m_.layers; ++l) { + const uint32_t pp = l & 1u; + fs_dmabuf_t* mid = p_->sbuf(p_->mid_slot(l)); + fs_dmabuf_t* out = p_->sbuf(p_->out_slot(l)); + fs_iova_submission_t sm{}, so{}; + if (!slot_begin(p_->small, p_->mid_slot(l), FS_DEV_GPU_VK, &sm)) { + *err = "pool submit(mid, GPU) rejected"; + return false; + } + /* ---- GPU stage (norm of l-1 + GEMV of l) and GPU -> TPU handoff ---- */ + bool ok = true; + bool wait_to = false; + if (arm == ARM_HOST_STAGED) { + ok = vk_.submit(cmds_[l], -1, nullptr, true, c); + ok = ok && vk_.wait_fence(c, &wait_to); + if (wait_to) { + const std::string msg = "GPU VkFence timed out at layer " + std::to_string(l); + mark_live_fence_timeout(msg); + *err = msg; + return false; + } + ok = ok && slot_end(p_->small, &sm, -1) && + cpu_read(ctx, mid, stage_in_.data(), d * sizeof(float), &c->cpu_dma_syncs); + c->inter_ip_host_copies += 1u; + } else if (arm == ARM_SYNC_FILE) { + /* GPU -> TPU: waiter-thread poll() of a real exported Vulkan SYNC_FD. */ + int g2t = -1; + ok = vk_.submit(cmds_[l], -1, &g2t, false, c); /* fails if the SYNC_FD export fails */ + if (ok && g2t >= 0) ok = wait_on_waiter(g2t, 5000, c, &wait_to); + if (g2t >= 0) close(g2t); + if (wait_to) { + const std::string msg = "GPU -> TPU sync_file poll timed out at layer " + std::to_string(l); + mark_live_fence_timeout(msg); + *err = msg; + return false; + } + ok = ok && slot_end(p_->small, &sm, -1); + c->fence_handoffs += 1u; + } else { + int g2t = -1; + ok = vk_.submit(cmds_[l], -1, &g2t, !vk_.has_sem_fd, c); + /* + * CPU proxy: observe GPU completion, then signal the IIF the TPU side waits on. + * g2t == -1 is an already-signaled Vulkan SYNC_FD payload: do not poll it. + */ + if (ok && vk_.has_sem_fd) { + if (g2t >= 0) { + ok = poll_sync_fd_timed(g2t, 5000, c, &wait_to); + c->userspace_fence_polls += 1u; + } + } else if (ok) { + ok = vk_.wait_fence(c, &wait_to); + } + if (g2t >= 0) close(g2t); + if (wait_to) { + const std::string msg = "GPU -> TPU fence wait timed out at layer " + std::to_string(l); + mark_live_fence_timeout(msg); + *err = msg; + return false; + } + ok = ok && iif_handoff(iif_, proxy_ip_gpu, ic_.timeout_ms, c, err) && slot_end(p_->small, &sm, -1); + } + if (!ok) { + if (err->empty()) *err = "GPU stage / GPU->TPU handoff failed at layer " + std::to_string(l); + return false; + } + /* ---- EdgeTPU W8A16 FFN stage ---- */ + if (!slot_begin(p_->small, p_->out_slot(l), FS_DEV_TPU, &so)) { + *err = "pool submit(out, TPU) rejected"; + return false; + } + const int8_t* wf = m_.w_ffn.data() + static_cast(l) * d * d; + if (!run_tpu(arm == ARM_HOST_STAGED, wf, pp, mid, out, c, err)) return false; + if (arm == ARM_HOST_STAGED) { + ok = cpu_write(ctx, out, stage_out_.data(), d * sizeof(float), &c->cpu_dma_syncs) && + slot_end(p_->small, &so, -1); + c->inter_ip_host_copies += 1u; + } else if (tpu_ == TPU_CPU) { + /* + * --tpu-backend cpu: run_tpu() already wrote Y[l] synchronously on this + * thread inside its DMA_BUF_IOCTL_SYNC bracket. No producer fence exists, + * so exporting the DMA-BUF reservation fence could only return an + * already-signaled stub, and a CPU-proxy IIF would gate nothing. Both + * fenced arms report the hop as synchronous instead of as a fenced handoff. + */ + ok = slot_end(p_->small, &so, -1); + c->synchronous_cpu_hops += 1u; + } else { + /* + * --tpu-backend openbuenos: ob_gemm_matmul_f32_w8a16_dmabuf() waits + * synchronously for EdgeTPU completion before returning. Do not export or + * poll a DMA-BUF fence or create a no-op CPU-proxy IIF after synchronous + * completion; count the TPU -> GPU hop as synchronous (L per token) and + * count only the GPU -> TPU Vulkan fence in fence_handoffs (L per token). + */ + ok = slot_end(p_->small, &so, -1); + c->synchronous_tpu_hops += 1u; + } + if (!ok) { + if (err->empty()) *err = "TPU->GPU handoff failed at layer " + std::to_string(l); + return false; + } + } + /* Final residual + RMSNorm of layer L-1, then CPU readback at the token boundary. */ + bool fin_to = false; + if (!vk_.submit(cmds_[m_.layers], -1, nullptr, true, c) || !vk_.wait_fence(c, &fin_to)) { + if (fin_to) { + const std::string msg = "final GPU norm VkFence timed out"; + mark_live_fence_timeout(msg); + *err = msg; + } else { + *err = "final GPU norm submit failed"; + } + return false; + } + if (!cpu_read(ctx, xb, out_hidden, d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "hidden-state readback failed"; + return false; + } + return true; + } + + void on_taint() override { nn_.abandon_in_flight(); } + + void shutdown() { + waiter_.stop(); + if (tainted() || gpu_queue_blocked_ || iif_gate_blocks_queue_ || last_failure_timed_out()) { + /* + * Do not vkQueueWaitIdle/vkDeviceWaitIdle or destroy Vulkan/NNAPI/DMA-BUF + * objects while completion is unproven; preserve the NNAPI object graph + * through process exit. + */ + nn_.abandon_in_flight(); + return; + } + vk_.wait_idle(); +#ifdef FREESCHED_HAVE_LIBOPENBUENOS + shutdown_ob(); +#endif + (void)ones_.size(); /* host-staged EdgeTPU tile scale vector (libopenbuenos builds) */ + nn_.free_layers(); + release_qbufs(); + nn_.shutdown(); + for (VkSemaphore& s : sem_in_) vk_.destroy_semaphore(&s); + for (VkSemaphore& s : sem_out_) vk_.destroy_semaphore(&s); + sem_in_.clear(); + sem_out_.clear(); + for (VkDmaBuffer& b : vsmall_) vk_.destroy_buffer(&b); + for (VkDmaBuffer& b : vw_) vk_.destroy_buffer(&b); + vsmall_.clear(); + vw_.clear(); + vk_.shutdown(); + } + + uint64_t ob_upfront_maps() const { return ob_upfront_maps_; } + uint32_t ob_prewarmed_layers() const { return ob_prewarmed_layers_; } + uint64_t ahb_allocs() const { return ahb_.allocs; } + uint32_t nn_ahb_registrations() const { return nn_ahb_registrations_; } + + private: + /* ---- TPU backend auto-selection: openbuenos (Tensor G5 node) -> NNAPI accelerator -> error ---- */ + bool select_tpu(const char* heap, const char* dive, std::string* err) { + if (req_ == "cpu") { + tpu_ = TPU_CPU; + return true; + } + /* + * Zero-copy GPU<->EdgeTPU sharing needs VK_QUEUE_FAMILY_FOREIGN_EXT ownership + * transfers; VK_QUEUE_FAMILY_EXTERNAL cannot name the EdgeTPU, so the shared + * tensor contents would be undefined. Refuse the accelerator path cleanly. + */ + if (!vk_.has_qf_foreign) { + (void)heap; + (void)dive; + *err = std::string("VK_EXT_queue_family_foreign unsupported by '") + vk_.device_name + + "': GPU<->EdgeTPU zero-copy accelerator path unavailable (try --tpu-backend cpu)"; + return false; + } + if (req_ == "openbuenos" || req_ == "auto") { + std::string ob_err; +#ifdef FREESCHED_HAVE_LIBOPENBUENOS + if (init_ob(heap, dive, &ob_err)) { + tpu_ = TPU_OB; + return true; + } + shutdown_ob(); +#else + (void)heap; + (void)dive; + ob_err = "built without FREESCHED_HAVE_LIBOPENBUENOS"; +#endif + if (req_ == "openbuenos") { + *err = ob_err + " (try --tpu-backend nnapi or cpu)"; + return false; + } + fallback_reason_ = "openbuenos: " + ob_err; + } else { + (void)heap; + (void)dive; + } + std::string nn_err; + if (setup_nnapi(&nn_err)) { + tpu_ = TPU_NNAPI; + return true; + } + *err = (fallback_reason_.empty() ? std::string() : fallback_reason_ + "; ") + "nnapi: " + nn_err + + " (try --tpu-backend cpu)"; + return false; + } + +#ifdef FREESCHED_HAVE_LIBOPENBUENOS + static std::string sanitize_ob_error(std::string s) { + const std::string needle = std::string("/data") + "/local" + "/tmp/"; + size_t pos = 0u; + while ((pos = s.find(needle, pos)) != std::string::npos) { + s.replace(pos, needle.size(), "/"); + pos += 13u; + } + return s; + } + + bool init_ob(const char* heap, const char* dive, std::string* err) { + ob_config_t cfg = ob_config_default(); + cfg.mock_mode = 0; + cfg.dma_heap_path = heap; + cfg.perf_mode = 5u; + if (ob_context_create(&cfg, &ob_) != OB_OK || !ob_) { + *err = "ob_context_create failed (no Tensor G5 EdgeTPU node)"; + ob_ = nullptr; + return false; + } + if (ob_gemm_register_builtin_emitter(ob_, dive) != OB_OK) { + *err = sanitize_ob_error(std::string("ob_gemm_register_builtin_emitter failed: ") + ob_context_last_error(ob_)); + return false; + } + for (uint32_t pp = 0u; pp < 2u; ++pp) { + if (!ob_map(p_->sbuf(p_->mid_slot(pp)), &mid_iova_[pp]) || !ob_map(p_->sbuf(p_->out_slot(pp)), &out_iova_[pp])) { + *err = sanitize_ob_error(std::string("ob_dmabuf_map failed: ") + ob_context_last_error(ob_)); + return false; + } + } + /* + * Pre-warm every layer's libopenbuenos packed weight cache strictly BEFORE + * fs_iova_pool_enter_hot_loop() (even when --warmup 0): ob_gemm_matmul_f32_w8a16_dmabuf + * lazily packs and IOVA-maps per-layer weight buffers inside ob_context_t on + * first use, so one full pass across all L layers keeps those allocations and + * mappings out of the hot loop. + */ + const uint32_t d = m_.d; + std::vector zeros(d, 0.0f); + uint64_t dummy_sync = 0u; + if (!cpu_write(p_->ctx, p_->sbuf(p_->mid_slot(0u)), zeros.data(), d * sizeof(float), &dummy_sync)) { + *err = "libopenbuenos weight pre-warm zero-fill failed"; + return false; + } + ob_prewarmed_layers_ = 0u; + for (uint32_t l = 0u; l < m_.layers; ++l) { + const int8_t* wf = m_.w_ffn.data() + static_cast(l) * d * d; + ob_invoke_stats_t st{}; + const ob_status_t rc = ob_gemm_matmul_f32_w8a16_dmabuf(ob_, mid_iova_[0u], d * sizeof(float), wf, d, d, + out_iova_[0u], d * sizeof(float), &st); + if (rc != OB_OK) { + *err = sanitize_ob_error(std::string("libopenbuenos weight pre-warm failed at layer ") + std::to_string(l) + + ": " + ob_status_string(rc) + " (" + ob_context_last_error(ob_) + ")"); + return false; + } + ob_prewarmed_layers_ += 1u; + } + return true; + } + + void shutdown_ob() { + if (ob_) { + for (uint32_t pp = 0u; pp < 2u; ++pp) { + if (mid_iova_[pp]) (void)ob_dmabuf_unmap(ob_, mid_iova_[pp]); + if (out_iova_[pp]) (void)ob_dmabuf_unmap(ob_, out_iova_[pp]); + mid_iova_[pp] = out_iova_[pp] = 0u; + } + ob_context_destroy(ob_); + ob_ = nullptr; + } + ob_upfront_maps_ = 0u; + ob_prewarmed_layers_ = 0u; + } + + bool ob_map(fs_dmabuf_t* b, uint64_t* out_iova) { + const off_t len = lseek(b->dmabuf_fd, 0, SEEK_END); + const uint64_t sz = (len > 0 && static_cast(len) >= b->size) ? static_cast(len) + : static_cast(b->size); + if (ob_dmabuf_map(ob_, b->dmabuf_fd, 0u, sz, OB_BUF_BIDIRECTIONAL, out_iova) != OB_OK) return false; + ob_upfront_maps_ += 1u; + return true; + } +#endif + + /* ---- NNAPI accelerator stage (Tensor G6 google-edgetpu and other NNAPI NPUs) ---- */ + bool setup_nnapi(std::string* err) { + const uint32_t L = m_.layers, d = m_.d; + if (!nn_.init(nn_device_.c_str(), err)) return false; + for (uint32_t l = 0u; l < L; ++l) { + if (!nn_.compile_layer(m_.w_ffn.data() + static_cast(l) * d * d, d, qc_.a[l], qc_.y[l], err)) { + return false; + } + } + const size_t qbytes = round_up(static_cast(d), 4096u); + bool ahb_ok = false; + if (nn_mem_req_ != "dmabuf") { + std::string ahb_err; +#if defined(__ANDROID__) + if (!ahb_.load()) { + ahb_err = "AHardwareBuffer entry points unavailable"; + } else { + ahb_ok = true; + for (uint32_t i = 0u; i < 4u && ahb_ok; ++i) { + QBuf& q = (i < 2u) ? qmid_[i] : qout_[i - 2u]; + q.bytes = qbytes; + if (!ahb_.alloc_blob(qbytes, FS_AHB_USAGE_GPU_DATA_BUFFER | FS_AHB_USAGE_CPU_READ_OFTEN | + FS_AHB_USAGE_CPU_WRITE_OFTEN, + &q.ahb, &q.fd)) { + ahb_err = "AHardwareBuffer_allocate(BLOB, GPU_DATA_BUFFER) failed"; + ahb_ok = false; + } else if (!vk_.import_fd(q.fd, qbytes, &q.vk, &ahb_err)) { + ahb_err = "Vulkan import of AHB DMA-BUF: " + ahb_err; + ahb_ok = false; + } else if (!nn_.import_ahb(q.ahb, &q.nn_mem)) { + ahb_err = "ANeuralNetworksMemory_createFromAHardwareBuffer failed"; + ahb_ok = false; + } + } + } +#else + ahb_err = "AHardwareBuffer requires Android"; +#endif + if (!ahb_ok) { + release_qbufs(); + if (nn_mem_req_ == "ahb") { + *err = ahb_err; + return false; + } + mem_fallback_reason_ = ahb_err; + } + } + if (ahb_ok) { + nn_.set_fenced_memory(false, allow_edgetpu_dmabuf_probe_); + nn_mem_mode_ = "ahb_blob_gpu_data_buffer"; + nn_ahb_registrations_ = 4u; /* ANeuralNetworksMemory_createFromAHardwareBuffer, once, before the hot loop */ + } else { + /* + * dmabuf_fd shared tensors (explicit --nnapi-mem dmabuf, or the automatic + * fallback after an AHB failure). On an EdgeTPU the first fenced execution + * over these memories crashed the shared HAL, so unless the debug probe is + * explicitly allowed the tensors are imported for the GPU only: NNAPI never + * sees them, no fenced execution is created, and both fenced arms are + * reported unavailable before dispatch. + */ + nn_.set_fenced_memory(true, allow_edgetpu_dmabuf_probe_); + const bool nn_blocked = nn_.fenced_block_reason() != nullptr; + if (nn_blocked) { + const std::string why = std::string(FS_NN_FENCED_DMABUF_BLOCKED) + " (" + nn_.device_name() + + "): fenced dmabuf_fd execution is disabled before dispatch; pass " + "--allow-edgetpu-dmabuf-fenced-probe to probe it"; + mem_fallback_reason_ = mem_fallback_reason_.empty() ? why : mem_fallback_reason_ + "; " + why; + } + for (uint32_t i = 0u; i < 4u; ++i) { + QBuf& q = (i < 2u) ? qmid_[i] : qout_[i - 2u]; + q.pool = p_->sbuf((i < 2u) ? p_->qmid_slot(i) : p_->qout_slot(i - 2u)); + q.fd = q.pool->dmabuf_fd; + q.bytes = q.pool->size; + if (!vk_.import_dmabuf(q.pool, &q.vk, err)) return false; + if (!nn_blocked && !nn_.import_fd(q.fd, q.bytes, &q.nn_mem)) { + *err = "ANeuralNetworksMemory_createFromFd(DMA-BUF) failed"; + return false; + } + } + nn_mem_mode_ = "dmabuf_fd"; + nn_zero_copy_bound_ = !nn_blocked; + } + /* + * Live-silicon rule (Tensor G6): the zero-copy GPU<->EdgeTPU tensors must + * never be CPU-accessed. A CPU lock+read/write of a shared tensor (even + * correctly bracketed by AHardwareBuffer_lock/unlock) leaves cache state + * that a later device-only GPU->EdgeTPU->GPU handoff observes as stale data + * (cos 0.16..0.88 instead of 0.9998). The host_staged arm therefore copies + * through its own CPU-visible bridge tensors. + */ + if (!setup_staged_qbufs(qbytes, &staged_fallback_reason_)) { + /* Fail closed: host_staged is reported unavailable instead of CPU-touching the zero-copy tensors. */ + staged_mem_mode_ = "unavailable"; + } + std::vector in(L), out(L); + for (uint32_t l = 0u; l < L; ++l) { + in[l] = qmid_[l & 1u].nn_mem; + out[l] = qout_[l & 1u].nn_mem; + } + if (nn_zero_copy_bound_ && !nn_.bind_zero_copy(in, out, err)) return false; + if (!vk_.init_quant(err)) return false; + if (vk_.has_sem_fd) { + sem_in_.assign(L + 1u, VK_NULL_HANDLE); + sem_out_.assign(L, VK_NULL_HANDLE); + bool sok = true; + for (VkSemaphore& s : sem_in_) sok = sok && vk_.make_semaphore(false, &s); + for (VkSemaphore& s : sem_out_) sok = sok && vk_.make_semaphore(true, &s); + if (!sok) { + for (VkSemaphore& s : sem_in_) vk_.destroy_semaphore(&s); + for (VkSemaphore& s : sem_out_) vk_.destroy_semaphore(&s); + sem_in_.clear(); + sem_out_.clear(); + } + } + waiter_.start(); + return true; + } + + /* Allocates the host_staged-only QUANT8 bridge tensors (CPU-visible AHB BLOBs). */ + bool setup_staged_qbufs(size_t qbytes, std::string* why) { +#if defined(__ANDROID__) + if (!ahb_.ok && !ahb_.load()) { + *why = "AHardwareBuffer entry points unavailable"; + return false; + } + for (uint32_t i = 0u; i < 4u; ++i) { + QBuf& q = (i < 2u) ? hmid_[i] : hout_[i - 2u]; + q.bytes = qbytes; + std::string e; + if (!ahb_.alloc_blob(qbytes, FS_AHB_USAGE_GPU_DATA_BUFFER | FS_AHB_USAGE_CPU_READ_OFTEN | + FS_AHB_USAGE_CPU_WRITE_OFTEN, + &q.ahb, &q.fd)) { + *why = "AHardwareBuffer_allocate(host_staged bridge) failed"; + release_staged_qbufs(); + return false; + } + if (!vk_.import_fd(q.fd, qbytes, &q.vk, &e)) { + *why = "Vulkan import of host_staged bridge: " + e; + release_staged_qbufs(); + return false; + } + } + staged_mem_mode_ = "isolated_ahb_blob"; + return true; +#else + (void)qbytes; + *why = "isolated host_staged bridge requires Android AHardwareBuffer"; + return false; +#endif + } + + void release_one(QBuf* q) { + if (q->nn_mem) nn_.free_mem(q->nn_mem); + vk_.destroy_buffer(&q->vk); +#if defined(__ANDROID__) + if (q->ahb && ahb_.release) ahb_.release(q->ahb); +#endif + *q = QBuf{}; + } + + void release_staged_qbufs() { + for (uint32_t i = 0u; i < 2u; ++i) { + release_one(&hmid_[i]); + release_one(&hout_[i]); + } + } + + void release_qbufs() { + for (uint32_t i = 0u; i < 4u; ++i) release_one((i < 2u) ? &qmid_[i] : &qout_[i - 2u]); + release_staged_qbufs(); + } + + bool staged_isolated() const { + for (uint32_t i = 0u; i < 2u; ++i) { + if (hmid_[i].vk.buffer == VK_NULL_HANDLE || hout_[i].vk.buffer == VK_NULL_HANDLE) return false; + } + return true; + } + + bool q_read(QBuf& q, void* dst, size_t n, TokenCounters* c) { +#if defined(__ANDROID__) + if (q.ahb) { + c->cpu_dma_syncs += 2u; + return ahb_.read(q.ahb, dst, n); + } +#endif + return cpu_read(p_->ctx, q.pool, dst, n, &c->cpu_dma_syncs); + } + + bool q_write(QBuf& q, const void* src, size_t n, TokenCounters* c) { +#if defined(__ANDROID__) + if (q.ahb) { + c->cpu_dma_syncs += 2u; + return ahb_.write(q.ahb, src, n); + } +#endif + return cpu_write(p_->ctx, q.pool, src, n, &c->cpu_dma_syncs); + } + + /* fs_iova_pool submissions of one stage, released together once its fence is observed. */ + struct SlotSubs { + fs_iova_submission_t s[2]{}; + uint32_t n = 0u; + }; + bool subs_begin(uint32_t slot, fs_dev_t dev, SlotSubs* ss) { + if (ss->n >= 2u || !slot_begin(p_->small, slot, dev, &ss->s[ss->n])) return false; + ++ss->n; + return true; + } + bool subs_end(SlotSubs* ss) { + bool ok = true; + for (uint32_t i = 0u; i < ss->n; ++i) ok = slot_end(p_->small, &ss->s[i], -1) && ok; + ss->n = 0u; + return ok; + } + /* True when the QUANT8 GPU<->EdgeTPU tensors are fs_iova_pool slots (dmabuf_fd), false for external AHBs. */ + bool nn_pool_tensors() const { return nn_mem_mode_ == "dmabuf_fd"; } + /* GPU command buffer l (0..L) writes FP32 mid(l) (GEMV, l < L) and FP32 out(l-1) (dequant of Y[l-1], l > 0). */ + bool gpu_quant_slots_begin(uint32_t l, SlotSubs* ss) { + bool ok = (l >= m_.layers) || subs_begin(p_->mid_slot(l), FS_DEV_GPU_VK, ss); + ok = ok && (l == 0u || subs_begin(p_->out_slot(l - 1u), FS_DEV_GPU_VK, ss)); + if (!ok) (void)subs_end(ss); + return ok; + } + /* EdgeTPU hop l reads QUANT8 A[l] (qmid) and writes QUANT8 Y[l] (qout): tracked when they are pool slots. */ + bool tpu_quant_slots_begin(uint32_t l, SlotSubs* ss) { + if (!nn_pool_tensors()) return true; + const bool ok = subs_begin(p_->qmid_slot(l), FS_DEV_TPU, ss) && subs_begin(p_->qout_slot(l), FS_DEV_TPU, ss); + if (!ok) (void)subs_end(ss); + return ok; + } + + bool run_token_nnapi(Arm arm, uint32_t tok, float* out_hidden, TokenCounters* c, std::string* err) { + const uint32_t d = m_.d; + fs_context_t* ctx = p_->ctx; + fs_dmabuf_t* xb = p_->sbuf(SLOT_X); + if (!cpu_write(ctx, xb, m_.embed.data() + static_cast(tok) * d, d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "embedding upload failed"; + return false; + } + if (arm == ARM_HOST_STAGED && (!staged_isolated() || hcmds_.size() != m_.layers + 1u)) { + *err = "host_staged isolated staging unavailable (zero-copy tensors are never CPU-accessed)"; + return false; + } + if (arm == ARM_R_IIF) { + if (!run_chain_riif(c, err)) return false; + } else { + for (uint32_t l = 0u; l < m_.layers; ++l) { + const uint32_t pp = l & 1u; + /* ---- GPU: [dequant+norm of l-1] + GEMV of l + quant A[l] -> GPU -> TPU handoff ---- */ + SlotSubs gsub, tsub; + if (!gpu_quant_slots_begin(l, &gsub)) { + *err = "pool submit(mid/out, GPU) rejected"; + return false; + } + bool ok = true; + bool gpu_wait_to = false; + if (arm == ARM_HOST_STAGED) { + ok = vk_.submit(hcmds_[l], -1, nullptr, true, c); + ok = ok && vk_.wait_fence(c, &gpu_wait_to); + if (gpu_wait_to) { + const std::string msg = "GPU VkFence timed out at layer " + std::to_string(l); + mark_live_fence_timeout(msg); + *err = msg; + return false; + } + ok = ok && subs_end(&gsub) && q_read(hmid_[pp], stage_in_u8_.data(), d, c); + c->inter_ip_host_copies += 1u; + } else { + int g2t = -1; + ok = vk_.submit_ex(cmds_[l], -1, VK_NULL_HANDLE, &vk_.sem_export, &g2t, false, false, c); + if (ok && g2t >= 0) ok = wait_on_waiter(g2t, 5000, c, &gpu_wait_to); /* userspace poll + cross-thread wakeup */ + if (g2t >= 0) close(g2t); + if (gpu_wait_to) { + const std::string msg = "GPU -> EdgeTPU sync_file poll timed out at layer " + std::to_string(l); + mark_live_fence_timeout(msg); + *err = msg; + c->fence_handoffs += 1u; + return false; + } + ok = ok && subs_end(&gsub); + c->fence_handoffs += 1u; + } + if (!ok) { + if (err->empty()) *err = "GPU stage / GPU->TPU handoff failed at layer " + std::to_string(l); + return false; + } + /* ---- EdgeTPU QUANT8_ASYMM 1x1 CONV_2D (NNAPI) ---- */ + if (arm == ARM_HOST_STAGED) { + /* + * Synchronous NNAPI compute on host copies (counted in tpu_hw_us); the + * isolated AHB bridge tensors it writes are outside fs_iova_pool. + */ + const uint64_t tt = now_ns(); + ok = nn_.compute_host(l, stage_in_u8_.data(), stage_out_u8_.data(), err); + c->nnapi_sync_call_us += us_since(tt); + c->nnapi_sync_call_measured = true; + ok = ok && q_write(hout_[pp], stage_out_u8_.data(), d, c); + c->inter_ip_host_copies += 1u; + } else { + if (!tpu_quant_slots_begin(l, &tsub)) { + *err = "pool submit(qmid/qout, TPU) rejected"; + return false; + } + int n2g = -1; + NnInflight inf; + double bus = 0.0; + bool unf = false; + ok = nn_start(l, -1, &n2g, &inf, &bus, &unf, err); + c->nnapi_start_block_us += bus; + c->dispatch_submit_us += bus; + c->nnapi_dep_event_create_us += inf.dep_event_create_us; + c->host_wait_us += inf.unfenced_wait_us; + if (unf) c->nnapi_unfenced_hops += 1u; + bool wait_timed_out = false; + if (ok && n2g >= 0) { + c->sync_files_exported += 1u; + ok = wait_on_waiter(n2g, 5000, c, &wait_timed_out); + } + if (n2g >= 0) close(n2g); + if (wait_timed_out) { + /* + * Bounded timeout recovery: do not call unbounded nn_.wait_done(), + * do not release live NNAPI objects, and do not retire tsub slots. + */ + const std::string msg = "NNAPI completion fence timed out at layer " + std::to_string(l) + + " (skipped unbounded ANeuralNetworksEvent_wait and device drain)"; + mark_live_fence_timeout(msg); + if (err->empty()) *err = msg; + c->fence_handoffs += 1u; + return false; + } + /* + * wait_on_waiter() already counted the TPU completion poll in host_wait_us. + * Start tw here so host_wait_us counts the poll once and check_done()/wait_done() once. + */ + const uint64_t tw = now_ns(); + if (ok) { + /* The fence signaled: confirm the NNAPI execution itself succeeded before consuming Y[l]. */ + std::string e; + c->nnapi_event_checks += 1u; + ok = nn_.check_done(&inf, &e); + if (!ok) *err = "EdgeTPU layer " + std::to_string(l) + ": " + e; + } else { + nn_.wait_done(&inf); + } + c->host_wait_us += us_since(tw); + nn_release(&inf); + /* + * The hop is drained here (never started, check_done() returned, or + * wait_done() blocked until it finished), so its QUANT8 slots retire even + * on failure: a failed arm must not leave them INFLIGHT for the next arm. + */ + ok = subs_end(&tsub) && ok; + c->fence_handoffs += 1u; + } + if (!ok) { + if (err->empty()) *err = "TPU stage / TPU->GPU handoff failed at layer " + std::to_string(l); + return false; + } + } + /* Final dequant (writes FP32 out(L-1)) + residual + RMSNorm of layer L-1. */ + const VkCommandBuffer fin = (arm == ARM_HOST_STAGED) ? hcmds_[m_.layers] : cmds_[m_.layers]; + SlotSubs fsub; + if (!gpu_quant_slots_begin(m_.layers, &fsub)) { + *err = "pool submit(out, GPU) rejected"; + return false; + } + bool fin_to = false; + if (!vk_.submit(fin, -1, nullptr, true, c) || !vk_.wait_fence(c, &fin_to)) { + if (fin_to) { + const std::string msg = "final GPU norm VkFence timed out"; + mark_live_fence_timeout(msg); + *err = msg; + } else { + *err = "final GPU norm submit failed"; + } + return false; + } + if (!subs_end(&fsub)) { + *err = "final GPU norm slot retire failed"; + return false; + } + } + if (!cpu_read(ctx, xb, out_hidden, d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "hidden-state readback failed"; + return false; + } + return true; + } + + /* + * r_iif: the whole token is enqueued as one kernel-resolved fence chain with + * zero userspace poll() between layers: + * [AP-signaled dma_iif_fence gate] -> GPU(l) --SYNC_FD--> NNAPI(l) + * --sync fence fd--> GPU(l+1) ... -> GPU(final norm) -> one VkFence at the + * token boundary. + * GPU -> TPU: vkGetSemaphoreFdKHR(SYNC_FD) -> ANeuralNetworksEvent_createFromSyncFenceFd + * dependency of ANeuralNetworksExecution_startComputeWithDependencies. + * TPU -> GPU: ANeuralNetworksEvent_getSyncFenceFd -> vkImportSemaphoreFdKHR. + * When /dev/iif is usable AND its FS_IIF_FENCE_BRIDGE_DMA bridge works + * (probe bridge_dma_ok), layer 0's GPU submission additionally waits on an + * FS_IIF_CREATE_FENCE(AP, 1) fence, bridged to a sync_file with + * FS_IIF_FENCE_BRIDGE_DMA and imported as a SYNC_FD semaphore; the AP + * signals it right after the submit, and the fence fd is closed only after + * the queue drained (vkQueueWaitIdle). + */ + bool run_chain_riif(TokenCounters* c, std::string* err) { + const uint32_t L = m_.layers; + /* + * Pool slots the chain uses, INFLIGHT until the token-boundary drain: the GPU + * writes FP32 mid(pp) (GEMV) and FP32 out(pp) (dequant of Y); the EdgeTPU + * reads QUANT8 A (qmid) and writes QUANT8 Y (qout). The QUANT8 tensors are + * tracked only in dmabuf_fd mode, where they are fs_iova_pool slots. In AHB + * mode they are external AHardwareBuffers registered with NNAPI once before + * the hot loop and are not attributed to any pool slot. + */ + fs_iova_submission_t subs[8]{}; + uint32_t nsubs = 0u; + const uint32_t used_pp = (L > 1u) ? 2u : 1u; + bool ok = true; + for (uint32_t pp = 0u; pp < used_pp && ok; ++pp) { + const uint32_t slots[4] = {p_->mid_slot(pp), p_->out_slot(pp), p_->qmid_slot(pp), p_->qout_slot(pp)}; + const fs_dev_t devs[4] = {FS_DEV_GPU_VK, FS_DEV_GPU_VK, FS_DEV_TPU, FS_DEV_TPU}; + const uint32_t n = nn_pool_tensors() ? 4u : 2u; + for (uint32_t i = 0u; i < n && ok; ++i) { + ok = slot_begin(p_->small, slots[i], devs[i], &subs[nsubs]); + if (ok) ++nsubs; + } + } + if (!ok) { + for (uint32_t i = 0u; i < nsubs; ++i) (void)slot_end(p_->small, &subs[i], -1); + *err = "pool submit(chain) rejected"; + return false; + } + /* Ungated sync-fence chain (0 IIF fences) when the bridge is unavailable. */ + const bool use_gate = iif_gate(); + int gate_fd = -1; + bool gate_signaled = false; + int wait_fd = -1; + if (use_gate) { + if (iif_->create(ic_.ap_ip, 1u, &gate_fd) != IIF_OK) { + *err = "IIF gate create failed (" + std::string(iif_errno_reason(iif_->last_errno())) + ")"; + ok = false; + } else if (iif_->submit_signaler(gate_fd) != IIF_OK) { + *err = "IIF gate submit_signaler failed (" + std::string(iif_errno_reason(iif_->last_errno())) + ")"; + ok = false; + } else if (iif_->bridge_sync_file(gate_fd, &wait_fd) != IIF_OK) { + /* + * The raw IIF fd is anon_inode:iif_file, not a sync_file, so Vulkan + * SYNC_FD import rejects it; the GPU waits on the bridged sync_file. + */ + *err = "IIF gate FS_IIF_FENCE_BRIDGE_DMA sync_file bridge failed (" + + std::string(iif_errno_reason(iif_->last_errno())) + ")"; + ok = false; + } + if (!ok) { + /* The gate was never imported into the GPU queue: signal (best effort) and close. */ + if (gate_fd >= 0) { + (void)iif_->signal(gate_fd, -ECANCELED); + iif_->destroy(gate_fd); + } + for (uint32_t i = 0u; i < nsubs; ++i) (void)slot_end(p_->small, &subs[i], -1); + return false; + } + } + std::vector infl(L); + const uint64_t chain_t0 = now_ns(); + for (uint32_t l = 0u; l < L && ok; ++l) { + int g2t = -1; + ok = vk_.submit_ex(cmds_[l], wait_fd, sem_in_[l], &sem_out_[l], &g2t, false, false, c); + wait_fd = -1; /* imported (driver-owned) or closed by submit_ex */ + if (l == 0u && use_gate && (ok || vk_.export_replace_pending())) { + /* The queue submit landed with the bridged dma_iif_fence imported. */ + iif_imported_gate_fd_ = gate_fd; + iif_gate_blocks_queue_ = true; + } + if (l == 0u && use_gate) { + /* GPU layer 0 now waits on the dma_iif_fence; the AP releases it. */ + if (iif_->signal(gate_fd, ok ? 0 : -ECANCELED) == IIF_OK) { + gate_signaled = true; + iif_gate_blocks_queue_ = false; + if (ok) c->iif_fences += 1u; + } else if (ok || vk_.export_replace_pending()) { + *err = "IIF gate signal failed (" + std::string(iif_errno_reason(iif_->last_errno())) + ")"; + ok = false; + } + } + if (!ok) { + if (g2t >= 0) close(g2t); + if (err->empty()) *err = "GPU submit (chain) failed at layer " + std::to_string(l); + break; + } + int n2g = -1; + double bus = 0.0; + bool unf = false; + ok = nn_start(l, g2t, &n2g, &infl[l], &bus, &unf, err); + if (g2t >= 0) close(g2t); /* NNAPI dup'd the dependency fd */ + c->nnapi_start_block_us += bus; + c->dispatch_submit_us += bus; + c->nnapi_dep_event_create_us += infl[l].dep_event_create_us; + c->host_wait_us += infl[l].unfenced_wait_us; + if (unf) c->nnapi_unfenced_hops += 1u; + if (n2g >= 0) c->sync_files_exported += 1u; + c->fence_handoffs += 2u; + wait_fd = n2g; + } + bool fence_timed_out = false; + if (ok) { + ok = vk_.submit_ex(cmds_[L], wait_fd, sem_in_[L], nullptr, nullptr, true, false, c); + wait_fd = -1; + if (ok) ok = vk_.wait_fence(c, &fence_timed_out); /* the single CPU wait of the token */ + if (!ok && err->empty()) { + *err = fence_timed_out ? "final GPU norm (chain) VkFence timed out" : "final GPU norm (chain) failed"; + } + } else if (wait_fd >= 0) { + close(wait_fd); /* an NNAPI completion fence, never imported */ + wait_fd = -1; + } + c->pipelined_chain_us += us_since(chain_t0); + c->pipelined_chains += 1u; + if (use_gate && !gate_signaled && gate_fd >= 0 && iif_gate_blocks_queue_) { + /* Fail-safe: release a GPU wait on the imported dma_iif_fence BEFORE any idle wait. */ + if (iif_->signal(gate_fd, -ECANCELED) == IIF_OK) { + gate_signaled = true; + iif_gate_blocks_queue_ = false; + } + } + if (fence_timed_out) { + /* + * Bounded timeout recovery: VkFence timed out (e.g., an unsignaled TPU + * completion fence stalled the chain). Skip unbounded vkQueueWaitIdle / + * vkDeviceWaitIdle / ANeuralNetworksEvent_wait, keep unproven slots and + * NNAPI events quarantined, and taint immediately. + */ + const std::string msg = + "r_iif chain VkFence timed out; skipped unbounded vkQueueWaitIdle/vkDeviceWaitIdle and " + "ANeuralNetworksEvent_wait (in-flight slots and NNAPI events quarantined)"; + mark_live_fence_timeout(msg); + if (err->empty()) *err = msg; + return false; + } + if (!release_blocking_iif_gate(c, err)) return false; + if (!vk_.replace_pending_signaled_export()) { + const std::string msg = "SYNC_FD export left a signaled binary semaphore and replacing it failed"; + taint(msg); + if (err->empty()) *err = msg; + return false; + } + /* pvrsrvkm retires imported IIF fences asynchronously: drain before closing the gate fd. */ + if (use_gate || !ok) { + const uint64_t tw = now_ns(); + vk_.wait_idle(); + c->host_wait_us += us_since(tw); + } + /* + * Token boundary: the single VkFence wait above implies every NNAPI + * completion fence signaled; confirm each layer's execution status before + * freeing its event (a fence can signal for a failed execution). + */ + const bool chain_ok = ok; + for (uint32_t l = 0u; l < L; ++l) { + NnInflight& inf = infl[l]; + const uint64_t tw = now_ns(); + if (chain_ok) { + std::string e; + c->nnapi_event_checks += 1u; + const bool done_ok = nn_.check_done(&inf, &e); + c->host_wait_us += us_since(tw); + if (!done_ok) { + if (ok) *err = "EdgeTPU layer " + std::to_string(l) + ": " + e; + ok = false; + } + } else { + nn_.wait_done(&inf); + c->host_wait_us += us_since(tw); + } + nn_release(&inf); + } + if (use_gate && gate_fd >= 0) { + if (gate_signaled) { + iif_->destroy(gate_fd); + } else { + /* Never close an unsignaled imported dma_iif_fence: leak the fd and fail. */ + if (err->empty()) *err = "IIF gate could not be signaled; fence fd intentionally leaked"; + ok = false; + } + } + for (uint32_t i = 0u; i < nsubs; ++i) ok = slot_end(p_->small, &subs[i], -1) && ok; + if (!ok && err->empty()) *err = "r_iif chain failed"; + return ok; + } + + /* NNAPI hop accounting: every started hop is released (after its wait) before run_token returns. */ + static bool nn_holds(const NnInflight& inf) { return inf.execution || inf.dep_event || inf.out_event; } + bool nn_start(uint32_t l, int dep_fd, int* out_fd, NnInflight* inf, double* bus, bool* unf, std::string* err) { + const bool ok = nn_.start(l, dep_fd, out_fd, inf, bus, unf, err); + if (nn_holds(*inf)) ++nn_outstanding_; + return ok; + } + void nn_release(NnInflight* inf) { + if (nn_holds(*inf) && nn_outstanding_ > 0u) --nn_outstanding_; + nn_.release(inf); + } + + /* + * Signal/cancel an imported IIF gate before any unbounded queue wait. If the + * signal fails, the queue may still be blocked on it: bounded vkWaitForFences + * only, taint, and do not retire in-flight slots. + */ + bool release_blocking_iif_gate(TokenCounters* c, std::string* why) { + if (!iif_gate_blocks_queue_) return true; + if (iif_imported_gate_fd_ >= 0 && iif_->signal(iif_imported_gate_fd_, -ECANCELED) == IIF_OK) { + iif_gate_blocks_queue_ = false; + return true; + } + const uint64_t tw = now_ns(); + const VkResult vr = vk_.wait_fence_bounded(5000000000ull); + if (c) c->host_wait_us += us_since(tw); + gpu_queue_blocked_ = true; + const std::string msg = + "imported IIF gate could not be released; skipped vkQueueWaitIdle/vkDeviceWaitIdle after bounded " + "vkWaitForFences (VkResult " + + std::to_string(static_cast(vr)) + ")"; + taint(msg); + if (why) { + if (!why->empty()) *why += "; "; + *why += msg; + } + return false; + } + + /* + * Failure-recovery drain. Release any imported IIF gate first. vkDeviceWaitIdle + * must return VK_SUCCESS (a lost or hung device cannot prove buffer reuse safe), + * any active libopenbuenos context must drain all in-flight jobs + * (ob_graph_wait_all == OB_OK), every NNAPI hop must have been waited and + * released, and no IIF fence may still be open (an unsignaled gate is + * intentionally leaked rather than closed, which also fails here). When the + * gate cannot be released, this returns without vkDeviceWaitIdle. + */ + bool quiesce(std::string* why) override { + if (last_failure_timed_out() || gpu_queue_blocked_) { + const std::string msg = + "fence wait timed out or GPU queue blocked; skipped unbounded vkQueueWaitIdle/vkDeviceWaitIdle"; + taint(msg); + if (why) { + if (!why->empty()) *why += "; "; + *why += msg; + } + return false; + } + if (!release_blocking_iif_gate(nullptr, why)) return false; + if (!vk_.replace_pending_signaled_export()) { + const std::string msg = "SYNC_FD export left a signaled binary semaphore and replacing it failed"; + taint(msg); + if (why->empty()) *why = msg; + else *why += "; " + msg; + return false; + } + bool ok = true; + const VkResult vr = vk_.device_wait_idle(); + if (vr != VK_SUCCESS) { + *why = "vkDeviceWaitIdle returned " + std::to_string(static_cast(vr)); + ok = false; + } +#ifdef FREESCHED_HAVE_LIBOPENBUENOS + if (ob_ != nullptr) { + const ob_status_t orc = ob_graph_wait_all(ob_, 0u); + if (orc != OB_OK) { + const char* st = ob_status_string(orc); + const char* last = ob_context_last_error(ob_); + *why += std::string(why->empty() ? "" : "; ") + "ob_graph_wait_all returned " + (st ? st : "error") + + (last && last[0] ? std::string(" (") + last + ")" : std::string()); + ok = false; + } + } +#endif + if (nn_outstanding_ != 0u) { + *why += std::string(why->empty() ? "" : "; ") + std::to_string(nn_outstanding_) + + " NNAPI hop(s) never waited/released"; + ok = false; + } + if (iif_->outstanding() != 0u) { + *why += std::string(why->empty() ? "" : "; ") + std::to_string(iif_->outstanding()) + " IIF fence(s) still open"; + ok = false; + } + return ok; + } + + bool run_tpu(bool staged, const int8_t* wf, uint32_t pp, fs_dmabuf_t* mid, fs_dmabuf_t* out, TokenCounters* c, + std::string* err) { + const uint32_t d = m_.d; +#ifdef FREESCHED_HAVE_LIBOPENBUENOS + if (tpu_ == TPU_OB) { + ob_invoke_stats_t st{}; + ob_status_t rc; + if (staged) { + rc = ob_gemm_matmul_f32_w8a16_tile(ob_, stage_in_.data(), wf, ones_.data(), d, d, stage_out_.data(), &st); + } else { + rc = ob_gemm_matmul_f32_w8a16_dmabuf(ob_, mid_iova_[pp], d * sizeof(float), wf, d, d, out_iova_[pp], + d * sizeof(float), &st); + } + if (rc != OB_OK) { + *err = sanitize_ob_error(std::string("EdgeTPU W8A16 failed: ") + ob_status_string(rc) + " (" + + ob_context_last_error(ob_) + ")"); + return false; + } + c->tpu_hw_us += static_cast(st.hw_execution_us); + c->tpu_hw_measured = true; + return true; + } +#endif + (void)pp; + (void)c; /* only the libopenbuenos path and the fenced CPU path below use the counters */ + if (staged) { + /* host_staged: the caller already counted the stage_in_ / stage_out_ copies. */ + cpu_tpu_w8a16(wf, stage_in_.data(), stage_out_.data(), d, &scratch_); + return true; + } + /* + * CPU-emulated TPU on the fenced arms: the shared DMA-BUF is copied into + * stage_in_ and the result copied back from stage_out_ (with CPU cache + * maintenance), i.e. the same two host copies per layer as host_staged. + */ + if (!cpu_read(p_->ctx, mid, stage_in_.data(), d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "cpu-tpu mid read failed"; + return false; + } + c->inter_ip_host_copies += 1u; + cpu_tpu_w8a16(wf, stage_in_.data(), stage_out_.data(), d, &scratch_); + if (!cpu_write(p_->ctx, out, stage_out_.data(), d * sizeof(float), &c->cpu_dma_syncs)) { + *err = "cpu-tpu out write failed"; + return false; + } + c->inter_ip_host_copies += 1u; + return true; + } + + const Model& m_; + Pools* p_; + IifFences* iif_; + bool iif_bridge_dma_ok_ = false; + IifConfig ic_; + const QuantCal& qc_; + std::string req_, nn_device_, nn_mem_req_; + TpuKind tpu_ = TPU_CPU; + std::string fallback_reason_, nn_mem_mode_ = "none", mem_fallback_reason_; + VkRunner vk_; + std::vector vsmall_, vw_; + std::vector gemv_sets_, norm_sets_, q_sets_, deq_sets_, hq_sets_, hdeq_sets_; + std::vector cmds_, hcmds_; /* hcmds_: host_staged arm (QUANT8 path) */ + std::vector sem_in_, sem_out_; + std::vector stage_in_, stage_out_, ones_, scratch_; + std::vector stage_in_u8_, stage_out_u8_; + NnEdgeTpu nn_; + AhbApi ahb_; + QBuf qmid_[2], qout_[2]; + QBuf hmid_[2], hout_[2]; /* host_staged-only bridge tensors */ + std::string staged_mem_mode_ = "none", staged_fallback_reason_; + FdWaiter waiter_; + int iif_imported_gate_fd_ = -1; + bool iif_gate_blocks_queue_ = false; + bool gpu_queue_blocked_ = false; + uint64_t ob_upfront_maps_ = 0u; + uint32_t ob_prewarmed_layers_ = 0u; + uint32_t nn_ahb_registrations_ = 0u; + bool allow_edgetpu_dmabuf_probe_ = false; + bool nn_zero_copy_bound_ = true; /* false: dmabuf_fd blocked from NNAPI (EdgeTPU) */ + uint64_t nn_outstanding_ = 0u; /* started NNAPI hops not yet released */ +#ifdef FREESCHED_HAVE_LIBOPENBUENOS + ob_context_t* ob_ = nullptr; + uint64_t mid_iova_[2] = {0u, 0u}; + uint64_t out_iova_[2] = {0u, 0u}; +#endif +}; +#endif /* FS_TL_HAVE_VULKAN */ + +/* ========================================================================= + * Arm driver: warmup, timing, ctx switches, ODPM energy, parity + * ========================================================================= */ + +struct ArmResult { + bool ran = false; + bool pass = false; + std::string skip_reason; + std::string error; + std::string recovery; /* after an error: "drained_retired" or "tainted" */ + std::vector ms_per_tok; + double tok_per_s = 0.0; + double cos = 0.0, cos_min_tok = 0.0, max_abs_err = 0.0; + double ctx_vol_per_tok = 0.0, ctx_nonvol_per_tok = 0.0, ctx_all_threads_per_tok = 0.0; + int ctx_from_proc = 0; + OdpmDelta energy{}; + HotStats hot{}; + TokenCounters totals{}; + std::vector outputs; +}; + +struct RunConfig { + uint32_t tokens = 64u; + uint32_t warmup = 2u; + double min_cos = 0.9999; + const char* odpm_root = "/sys/bus/iio/devices"; + double odpm_unit_j = 1e-6; +}; + +/* An arm failed: drain + retire (or taint) before any later arm may reuse the executor. */ +void fail_arm(Executor* ex, ArmResult* r, const std::string& error) { + r->error = error; + r->recovery = ex->recover_after_failure(ex->last_failure_timed_out()) ? "drained_retired" : "tainted"; + if (ex->tainted()) r->error += " [executor tainted: " + ex->taint_reason() + "]"; +} + +void run_arm(Executor* ex, Arm arm, const Model& m, const RunConfig& rc, const std::vector& ref, + Pools* pools, ArmResult* r) { + /* Checked before arm_unavailable() and before any run_token(): SLOT_X is never written. */ + if (ex->tainted()) { + r->skip_reason = "executor_tainted"; + r->error = "skipped: executor tainted by an earlier arm (" + ex->taint_reason() + ")"; + return; + } + const char* why = ex->arm_unavailable(arm); + if (why) { + r->skip_reason = why; + return; + } + const uint32_t d = m.d; + std::vector tmp(d); + std::string err; + for (uint32_t w = 0u; w < rc.warmup; ++w) { + TokenCounters junk{}; + if (!ex->run_token(arm, token_id(w, m.vocab), tmp.data(), &junk, &err)) { + fail_arm(ex, r, "warmup: " + err); + return; + } + } + r->outputs.assign(static_cast(rc.tokens) * d, 0.0f); + const HotStats hot0 = context_hot_stats(pools->ctx); + OdpmSnapshot e0, e1; + odpm_read_all(rc.odpm_root, &e0); + double vol = 0.0, nonvol = 0.0, allthr = 0.0; + int from_proc = 1; + const uint64_t loop0 = now_ns(); + for (uint32_t t = 0u; t < rc.tokens; ++t) { + const CtxSwitchSample c0 = sample_ctx_switches(); + const uint64_t t0 = now_ns(); + if (!ex->run_token(arm, token_id(t, m.vocab), r->outputs.data() + static_cast(t) * d, &r->totals, + &err)) { + fail_arm(ex, r, "token " + std::to_string(t) + ": " + err); + return; + } + const uint64_t t1 = now_ns(); + const CtxSwitchSample c1 = sample_ctx_switches(); + r->ms_per_tok.push_back(static_cast(t1 - t0) / 1e6); + vol += static_cast(c1.voluntary - c0.voluntary); + nonvol += static_cast(c1.nonvoluntary - c0.nonvoluntary); + allthr += static_cast((c1.ru_voluntary - c0.ru_voluntary) + (c1.ru_nonvoluntary - c0.ru_nonvoluntary)); + from_proc &= c1.from_proc_status; + } + const uint64_t loop1 = now_ns(); + if (!ex->clean_after_success(&err)) { + fail_arm(ex, r, "arm finished with work in flight: " + err); + return; + } + odpm_read_all(rc.odpm_root, &e1); + r->energy = odpm_delta(e0, e1, rc.odpm_unit_j); + const HotStats hot1 = context_hot_stats(pools->ctx); + r->hot.maps = hot1.maps - hot0.maps; + r->hot.unmaps = hot1.unmaps - hot0.unmaps; + r->hot.map_rejects = hot1.map_rejects - hot0.map_rejects; + r->hot.unmap_rejects = hot1.unmap_rejects - hot0.unmap_rejects; + const double T = static_cast(rc.tokens); + r->ran = true; + r->tok_per_s = T / (static_cast(loop1 - loop0) / 1e9); + r->ctx_vol_per_tok = vol / T; + r->ctx_nonvol_per_tok = nonvol / T; + r->ctx_all_threads_per_tok = allthr / T; + r->ctx_from_proc = from_proc; + const Parity all = parity_f32_vs_f64(r->outputs.data(), ref.data(), r->outputs.size()); + r->cos = all.cos; + r->max_abs_err = all.max_abs_err; + r->cos_min_tok = 1.0; + for (uint32_t t = 0u; t < rc.tokens; ++t) { + const Parity pt = parity_f32_vs_f64(r->outputs.data() + static_cast(t) * d, + ref.data() + static_cast(t) * d, d); + r->cos_min_tok = std::min(r->cos_min_tok, pt.cos); + } + r->pass = r->cos >= rc.min_cos && r->cos_min_tok >= rc.min_cos && r->hot.maps == 0u && r->hot.unmaps == 0u; +} + +/* printf("%s") argument for a JSON number: finite -> fmt, inf/nan -> null. */ +#define JNUM(v, fmt) json_finite_or_null(static_cast(v), fmt).c_str() + +void print_num_or_null(bool avail, double v) { + if (!avail) { + std::fputs("null", stdout); + return; + } + const std::string encoded = json_finite_or_null(v); + std::fputs(encoded.c_str(), stdout); +} + +void json_escape_print(const std::string& s) { std::fputs(json_escape(s).c_str(), stdout); } + +/* printf("%s") argument for a JSON string value: escaped and quoted (fs_tokloop::json_escape). */ +#define JSTR(s) json_escape(s).c_str() + +void print_iif_probe_json(const char* dev, const IifProbe& p, const IifAbi& abi) { + std::fputs(iif_probe_json(dev, p, abi).c_str(), stdout); +} + +void print_usage(const char* argv0) { + std::fprintf(stderr, + "Usage: %s [--mock|--live] [options]\n" + " --layers Transformer blocks per token (1..64, default 12)\n" + " --tokens Measured decode tokens (1..4096, default 64)\n" + " --d Hidden size in {512,1024,1536,2048} (default 512)\n" + " --warmup Warmup tokens per arm (default 2)\n" + " --arms Comma list of host_staged,sync_file_poll,r_iif (default all;\n" + " 'sync_file' is accepted as an alias of sync_file_poll)\n" + " --min-cos Parity gate vs FP64 reference (default 0.9999; 0.995 for\n" + " the QUANT8_ASYMM NNAPI stage)\n" + " --seed Model PRNG seed (default 20261202)\n" + " --iif-dev IIF device node (default /dev/iif)\n" + " --iif-signaler-ip Signaler IP of CPU-signaled IIF fences (default 3 = AP)\n" + " --iif-gpu-ip / --iif-tpu-ip Software-emulator producer ids (default 2 / 1)\n" + " --iif-ioctl-create|--iif-ioctl-submit|--iif-ioctl-signal|--iif-ioctl-bridge \n" + " UAPI request overrides (a bogus bridge request emulates an IIF\n" + " driver without FS_IIF_FENCE_BRIDGE_DMA)\n" + " --iif-sw-fallback Live: run CPU-proxy r_iif on the software IIF emulator\n" + " --require-iif Fail unless r_iif ran and created IIF fences (live: kernel\n" + " /dev/iif fences; --iif-sw-fallback does not satisfy it)\n" + " --iif-probe-only Probe the IIF node, print JSON and exit (only this and --live\n" + " open the IIF node; --mock uses the software fence backend)\n" + " --odpm-root IIO root (default /sys/bus/iio/devices)\n" + " --odpm-unit-j Joules per energy_value unit (finite, > 0; default 1e-6)\n" + " --heap DMA-BUF heap (default /dev/dma_heap/system)\n" + " --dive Optional RV64 DIVE interpreter for libopenbuenos\n" + " --preferred-driver Vulkan device name filter (default PowerVR)\n" + " --tpu-backend EdgeTPU stage backend (default auto:\n" + " libopenbuenos if a Tensor G5 node opens, else the NNAPI\n" + " accelerator; mock: nnapi selects the QUANT8 emulation)\n" + " --nnapi-device NNAPI accelerator name substring (default auto, google-edgetpu first)\n" + " --nnapi-mem Shared QUANT8 tensor memory (default auto: AHB BLOB\n" + " GPU_DATA_BUFFER, falling back to the pinned DMA-BUF fd).\n" + " On an EdgeTPU, dmabuf_fd memory is never used for fenced\n" + " execution: the fenced arms are skipped before dispatch\n" + " --allow-edgetpu-dmabuf-fenced-probe DEBUG ONLY: dispatch fenced EdgeTPU executions over\n" + " dmabuf_fd memory (crashed the shared Tensor G6 EdgeTPU HAL)\n" + " --json Emit JSON\n" + " --fault-inject-gpu-fence :: MOCK TEST SEAM: fail that run_token call\n" + " (0-based, warmup included) at with its GPU slot INFLIGHT\n" + " --fault-inject-fence-timeout :: MOCK TEST SEAM: simulate an unsignaled\n" + " fence wait timeout at (bounded recovery, taints immediately)\n" + " --fault-inject-quiesce-fail MOCK TEST SEAM: the failure drain cannot prove the device idle\n" + "Numbers are parsed strictly (whole argument, finite, in range); invalid values exit 2.\n", + argv0); +} + +/* Decimal counts (--layers 12x, " 12", "-1", "012" style surprises are rejected or decimal). */ +bool parse_count(const char* s, uint32_t* out) { return parse_strict_u32(s, 10, out); } + +/* IP ids and ioctl request numbers accept 0x hex. */ +bool parse_id(const char* s, uint32_t* out) { return parse_strict_u32(s, 0, out); } + +bool parse_ioctl_req(const char* s, unsigned long* out) { + unsigned long long v = 0u; + if (!parse_strict_uint(s, 0, std::numeric_limits::max(), &v)) return false; + *out = static_cast(v); + return true; +} + +/* --fault-inject-gpu-fence / --fault-inject-fence-timeout ARM:CALL:LAYER (mock test seam). */ +bool parse_fault_target(const char* s, int* out_arm, uint32_t* out_call, uint32_t* out_layer) { + const std::string v(s ? s : ""); + const size_t a = v.find(':'); + const size_t b = (a == std::string::npos) ? std::string::npos : v.find(':', a + 1u); + if (b == std::string::npos) return false; + const std::string arm = v.substr(0u, a), call = v.substr(a + 1u, b - a - 1u), layer = v.substr(b + 1u); + *out_arm = -1; + for (int k = 0; k < ARM_COUNT; ++k) { + if (arm == kArmNames[k]) *out_arm = k; + } + return *out_arm >= 0 && parse_count(call.c_str(), out_call) && parse_count(layer.c_str(), out_layer); +} + +} // namespace + +int main(int argc, char** argv) { + bool live = false; + bool json = false; + bool probe_only = false; + bool require_iif = false; + bool iif_sw_fallback = false; + bool min_cos_set = false; + bool allow_edgetpu_dmabuf_probe = false; + uint32_t layers = 12u, d = 512u; + uint32_t seed = 20261202u; + bool arm_on[ARM_COUNT] = {true, true, true}; + const char* iif_dev = "/dev/iif"; + const char* heap = "/dev/dma_heap/system"; + const char* dive = nullptr; + const char* preferred = "PowerVR"; + const char* tpu_backend = "auto"; + const char* nn_device = "auto"; + const char* nn_mem = "auto"; + RunConfig rc; + IifConfig ic; + IifAbi abi = iif_default_abi(); + FaultInject fault; + bool fault_set = false; + + for (int i = 1; i < argc; ++i) { + const char* a = argv[i]; + const char* v = (i + 1 < argc) ? argv[i + 1] : nullptr; + bool ok = true; + if (!std::strcmp(a, "--mock")) { + live = false; + } else if (!std::strcmp(a, "--live")) { + live = true; + } else if (!std::strcmp(a, "--json")) { + json = true; + } else if (!std::strcmp(a, "--iif-probe-only")) { + probe_only = true; + } else if (!std::strcmp(a, "--require-iif")) { + require_iif = true; + } else if (!std::strcmp(a, "--iif-sw-fallback")) { + iif_sw_fallback = true; + } else if (!std::strcmp(a, "--allow-edgetpu-dmabuf-fenced-probe")) { + allow_edgetpu_dmabuf_probe = true; + } else if (!std::strcmp(a, "--fault-inject-quiesce-fail")) { + fault.quiesce_fail = true; + fault_set = true; + } else if (!std::strcmp(a, "--help") || !std::strcmp(a, "-h")) { + print_usage(argv[0]); + return 0; + } else if (v == nullptr) { + ok = false; + } else { + ++i; + if (!std::strcmp(a, "--layers")) ok = parse_count(v, &layers); + else if (!std::strcmp(a, "--tokens")) ok = parse_count(v, &rc.tokens); + else if (!std::strcmp(a, "--d")) ok = parse_count(v, &d); + else if (!std::strcmp(a, "--warmup")) ok = parse_count(v, &rc.warmup); + else if (!std::strcmp(a, "--seed")) ok = parse_count(v, &seed); + else if (!std::strcmp(a, "--min-cos")) { + /* (0, 1]: finite, fully parsed; 0 is rejected by the config check below. */ + ok = parse_strict_double(v, 0.0, 1.0, &rc.min_cos) && rc.min_cos > 0.0; + min_cos_set = true; + } + else if (!std::strcmp(a, "--iif-dev")) iif_dev = v; + else if (!std::strcmp(a, "--iif-signaler-ip")) ok = parse_id(v, &ic.ap_ip) && ic.ap_ip <= 0xFFu; + else if (!std::strcmp(a, "--iif-gpu-ip")) ok = parse_id(v, &ic.gpu_ip); + else if (!std::strcmp(a, "--iif-tpu-ip")) ok = parse_id(v, &ic.tpu_ip); + else if (!std::strcmp(a, "--iif-ioctl-create")) ok = parse_ioctl_req(v, &abi.create_req); + else if (!std::strcmp(a, "--iif-ioctl-submit")) ok = parse_ioctl_req(v, &abi.submit_signaler_req); + else if (!std::strcmp(a, "--iif-ioctl-signal")) ok = parse_ioctl_req(v, &abi.signal_req); + else if (!std::strcmp(a, "--iif-ioctl-bridge")) ok = parse_ioctl_req(v, &abi.bridge_dma_req); + else if (!std::strcmp(a, "--odpm-root")) rc.odpm_root = v; + /* J per ODPM count: a partial parse (e.g. a Unicode minus) would silently scale every energy figure. */ + else if (!std::strcmp(a, "--odpm-unit-j")) ok = parse_strict_positive_double(v, &rc.odpm_unit_j); + else if (!std::strcmp(a, "--fault-inject-gpu-fence")) { + ok = parse_fault_target(v, &fault.arm, &fault.call, &fault.layer); + fault_set = true; + } else if (!std::strcmp(a, "--fault-inject-fence-timeout")) { + ok = parse_fault_target(v, &fault.timeout_arm, &fault.timeout_call, &fault.timeout_layer); + fault_set = true; + } + else if (!std::strcmp(a, "--heap")) heap = v; + else if (!std::strcmp(a, "--dive")) dive = v; + else if (!std::strcmp(a, "--preferred-driver")) preferred = v; + else if (!std::strcmp(a, "--tpu-backend")) tpu_backend = v; + else if (!std::strcmp(a, "--nnapi-device")) nn_device = v; + else if (!std::strcmp(a, "--nnapi-mem")) nn_mem = v; + else if (!std::strcmp(a, "--arms")) { + for (bool& on : arm_on) on = false; + std::string list(v); + size_t pos = 0u; + while (ok && pos <= list.size()) { + const size_t comma = list.find(',', pos); + const std::string tok = list.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos); + bool matched = false; + for (int k = 0; k < ARM_COUNT; ++k) { + if (tok == kArmNames[k] || (k == ARM_SYNC_FILE && tok == "sync_file")) { + arm_on[k] = true; + matched = true; + } + } + ok = matched; + if (comma == std::string::npos) break; + pos = comma + 1u; + } + } else { + ok = false; + } + } + if (!ok) { + std::fprintf(stderr, "Invalid or unknown option: %s\n", a); + print_usage(argv[0]); + return 2; + } + } + + if (fault_set && live) { + std::fprintf(stderr, "Invalid option: --fault-inject-* is a --mock test seam\n"); + return 2; + } + + if (probe_only) { + const IifProbe p = iif_probe(iif_dev, abi, ic.ap_ip, nullptr); + print_iif_probe_json(iif_dev, p, abi); + std::printf("\n"); + return 0; + } + + const bool d_ok = (d == 512u || d == 1024u || d == 1536u || d == 2048u); + const std::string req(tpu_backend); + const bool backend_ok = (req == "auto" || req == "openbuenos" || req == "nnapi" || req == "cpu"); + const std::string mem_req(nn_mem); + const bool mem_ok = (mem_req == "auto" || mem_req == "ahb" || mem_req == "dmabuf"); + if (!d_ok || layers == 0u || layers > 64u || rc.tokens == 0u || rc.tokens > 4096u || rc.warmup > 64u || + !(rc.min_cos > 0.0 && rc.min_cos <= 1.0) || !backend_ok || !mem_ok) { + std::fprintf(stderr, + "Invalid config: d=%u (EdgeTPU W8A16 needs 512/1024/1536/2048) layers=%u (1..64) " + "tokens=%u (1..4096) warmup=%u (<=64) min_cos=%g tpu_backend=%s nnapi_mem=%s\n", + d, layers, rc.tokens, rc.warmup, rc.min_cos, tpu_backend, nn_mem); + return 2; + } + + Model model; + build_model(&model, d, layers, seed); + + /* FP64 reference for every measured token + per-layer QUANT8 calibration ranges. */ + std::vector ref(static_cast(rc.tokens) * d); + std::vector amax_a(layers, 0.0), amax_y(layers, 0.0); + for (uint32_t t = 0u; t < rc.tokens; ++t) { + reference_token(model, token_id(t, model.vocab), ref.data() + static_cast(t) * d, amax_a.data(), + amax_y.data()); + } + QuantCal qcal; + for (uint32_t l = 0u; l < layers; ++l) { + qcal.a.push_back(quant8_from_absmax(amax_a[l])); + qcal.y.push_back(quant8_from_absmax(amax_y[l])); + } + const bool mock_quant = !live && req == "nnapi"; + + /* + * IIF runtime detection (probe fences are AP-signaled). Only --live (and + * --iif-probe-only above) touch the kernel driver: --mock never opens or + * ioctls the IIF node, even as root on a Tensor device. + */ + IifFences iif; + const IifProbe probe = live ? iif_probe(iif_dev, abi, ic.ap_ip, &iif) : iif_probe_not_run("not_probed_mock"); + const char* iif_signal_path = "none"; + if (!live) { + iif.init_sw(); + iif_signal_path = "sw_emulated"; + } else if (iif.kind() == FS_IIF_BACKEND_KERNEL) { + iif_signal_path = "cpu_proxy"; + } else if (iif_sw_fallback) { + iif.init_sw(); + iif_signal_path = "sw_emulated"; + } + + fs_config_t fcfg = fs_config_default(); + fcfg.mock_mode = live ? 0 : 1; + fcfg.profile = FS_PROFILE_PIXEL10_LAGUNA; + fcfg.dma_heap_path = heap; + fs_context_t* fctx = nullptr; + if (fs_context_create(&fcfg, &fctx) != FS_OK || !fctx) { + std::fprintf(stderr, "fs_context_create failed\n"); + return 1; + } + + Pools pools; + std::string err; + if (!setup_pools(fctx, model, live, &pools, &err)) { + std::fprintf(stderr, "ERROR: %s\n", err.c_str()); + pools_destroy(&pools); + fs_context_destroy(fctx); + return 1; + } + + Executor* ex = nullptr; + MockExecutor* mock_ex = nullptr; + const char* gpu_name = "cpu_emulated"; + uint64_t ob_upfront_maps = 0u; + uint32_t ob_prewarmed_layers = 0u; + std::string tpu_selected = mock_quant ? "nnapi_quant8_emulated" : "cpu_emulated"; + std::string tpu_fallback, nn_dev_name, nn_mem_mode = "none", nn_mem_fallback, staged_mem_mode = "none"; + std::string staged_mem_fallback, vk_qf_transfer = "none"; + uint64_t vk_ownership_barriers = 0u; + bool quant = mock_quant, nn_reusable = false, nn_fenced = false, iif_gate = false; + int64_t nn_dev_feature_level = -1; + const char* nn_fenced_policy = "not_applicable"; +#if FS_TL_HAVE_VULKAN + LiveExecutor* live_ex = nullptr; +#endif + if (!live) { + mock_ex = new MockExecutor(model, &pools, &iif, ic, mock_quant ? &qcal : nullptr, fault); + ex = mock_ex; + } else { +#if FS_TL_HAVE_VULKAN + live_ex = new LiveExecutor(model, &pools, &iif, ic, qcal, tpu_backend, nn_device, nn_mem); + live_ex->set_allow_edgetpu_dmabuf_fenced_probe(allow_edgetpu_dmabuf_probe); + live_ex->set_iif_bridge_dma_ok(probe.bridge_dma_ok); + if (!live_ex->init(preferred, heap, dive, &err)) { + std::fprintf(stderr, "ERROR: live init failed: %s\n", err.c_str()); + delete live_ex; + pools_destroy(&pools); + fs_context_destroy(fctx); + return 1; + } + gpu_name = live_ex->vk().device_name; + ob_upfront_maps = live_ex->ob_upfront_maps(); + ob_prewarmed_layers = live_ex->ob_prewarmed_layers(); + tpu_selected = live_ex->tpu_name(); + tpu_fallback = live_ex->fallback_reason(); + vk_qf_transfer = live_ex->vk_ext_qf_name(); + vk_ownership_barriers = live_ex->vk_ownership_barriers(); + quant = live_ex->quant(); + if (quant) { + nn_dev_name = live_ex->nn_device(); + nn_dev_feature_level = live_ex->nn_feature_level(); + nn_mem_mode = live_ex->nn_mem_mode(); + staged_mem_mode = live_ex->staged_mem_mode(); + staged_mem_fallback = live_ex->staged_mem_fallback(); + nn_mem_fallback = live_ex->nn_mem_fallback(); + nn_reusable = live_ex->nn_reusable(); + nn_fenced = live_ex->nn_fenced(); + nn_fenced_policy = live_ex->nn_fenced_dmabuf_policy(); + iif_gate = live_ex->iif_gate(); + if (iif_gate) { + iif_signal_path = "ap_signaled_gate_imported_into_gpu_queue"; + } else if (iif.kind() == FS_IIF_BACKEND_KERNEL) { + iif_signal_path = "ungated_nnapi_sync_fence_chain_bridge_unavailable"; + } + } + ex = live_ex; +#else + (void)preferred; + (void)dive; + (void)nn_device; + std::fprintf(stderr, "ERROR: --live requires Linux/Android Vulkan headers\n"); + pools_destroy(&pools); + fs_context_destroy(fctx); + return 1; +#endif + } + /* 8-bit A[l]/Y[l] activations compound over L layers (cos ~0.9987 at d=2048, L=24). */ + if (quant && !min_cos_set) rc.min_cos = 0.995; + + /* Everything is allocated, uploaded, imported and IOVA-mapped: enter the hot loop. */ + if (!pools_enter_hot(&pools)) { + std::fprintf(stderr, "ERROR: fs_iova_pool_enter_hot_loop failed\n"); + delete ex; + pools_destroy(&pools); + fs_context_destroy(fctx); + return 1; + } + +#if FS_TL_HAVE_VULKAN + const uint64_t ahb_allocs0 = live_ex ? live_ex->ahb_allocs() : 0u; +#endif + ArmResult results[ARM_COUNT]; + for (int k = 0; k < ARM_COUNT; ++k) { + if (!arm_on[k]) { + results[k].skip_reason = "not_selected"; + continue; + } + run_arm(ex, static_cast(k), model, rc, ref, &pools, &results[k]); + } + + /* + * IOVA observation scope. The pool counters cover every fs_iova_pool slot. + * - In NNAPI AHB mode the QUANT8 GPU<->EdgeTPU tensors are external + * AHardwareBuffers (registered once with ANeuralNetworksMemory_createFromAHardwareBuffer + * before the hot loop); their driver-internal gralloc/NNAPI mappings are not + * observable from userspace, so hot_loop_map_count == 0 covers only the pool + * (Vulkan-imported) buffers. ahb_hot_loop_allocs counts AHardwareBuffer_allocate + * calls made by this process while the arms ran. + * - In libopenbuenos mode every layer's packed weight cache is pre-warmed via + * ob_gemm_matmul_f32_w8a16_dmabuf before fs_iova_pool_enter_hot_loop() + * (ob_prewarmed_layers == L), but libopenbuenos manages those internal weight + * buffers outside fs_iova_pool so pool counters cannot directly observe them + * (vulkan_pool_only_openbuenos_weights_external). + */ + uint64_t ahb_hot_allocs = 0u; + uint32_t nn_ahb_regs = 0u; + uint64_t nn_refusals = 0u, nn_exec_starts = 0u; /* fenced EdgeTPU dmabuf refusals / startComputeWithDependencies calls */ +#if FS_TL_HAVE_VULKAN + if (live_ex) { + ahb_hot_allocs = live_ex->ahb_allocs() - ahb_allocs0; + nn_ahb_regs = live_ex->nn_ahb_registrations(); + nn_refusals = live_ex->nn_fenced_refusals(); + nn_exec_starts = live_ex->nn_exec_start_calls(); + } +#endif + const char* iova_scope = !live ? "full_pool_mock" + : (tpu_selected == "openbuenos") ? "vulkan_pool_only_openbuenos_weights_external" + : (quant && nn_mem_mode != "dmabuf_fd") ? "vulkan_pool_only_nnapi_ahb_external" + : "full_pool_dmabuf"; + fs_iova_pool_stats_t ps_small{}, ps_w{}; + (void)fs_iova_pool_get_stats(pools.small, &ps_small); + (void)fs_iova_pool_get_stats(pools.weights, &ps_w); + pools_exit_hot(&pools); + + /* Cross-arm agreement (bit-exact expected in mock; reported in live). */ + double arms_max_abs_diff = 0.0; + int first = -1; + for (int k = 0; k < ARM_COUNT; ++k) { + if (!results[k].ran) continue; + if (first < 0) { + first = k; + continue; + } + for (size_t i = 0u; i < results[k].outputs.size(); ++i) { + const double diff = std::fabs(static_cast(results[k].outputs[i]) - + static_cast(results[first].outputs[i])); + if (!(diff <= arms_max_abs_diff)) arms_max_abs_diff = diff; + } + } + + bool any_ran = false, all_pass = true; + for (int k = 0; k < ARM_COUNT; ++k) { + if (!arm_on[k]) continue; + if (results[k].ran) { + any_ran = true; + all_pass = all_pass && results[k].pass; + } else if (!results[k].error.empty()) { + all_pass = false; /* an arm that could run but failed is a hard failure */ + } + } + const uint64_t hot_maps = ps_small.hot_loop_map_count + ps_w.hot_loop_map_count; + const uint64_t hot_unmaps = ps_small.hot_loop_unmap_count + ps_w.hot_loop_unmap_count; + bool pass = any_ran && all_pass && hot_maps == 0u && hot_unmaps == 0u; + if (!live) pass = pass && arms_max_abs_diff == 0.0; + /* --require-iif: r_iif must have measurably used IIF fences (kernel /dev/iif fences when live). */ + const bool iif_met = + iif_requirement_met(live, results[ARM_R_IIF].ran, iif.kind(), results[ARM_R_IIF].totals.iif_fences); + if (require_iif && !iif_met) pass = false; + + const double L2 = 2.0 * static_cast(layers); + if (json) { + std::printf("{\"pass\":%s,\"mode\":%s,\"executor\":%s,\"gpu\":%s", pass ? "true" : "false", + JSTR(live ? "live" : "mock"), JSTR(ex->name()), JSTR(gpu_name)); + std::printf(",\"vk_shared_tensor_ownership\":{\"queue_family\":%s," + "\"release_acquire_barriers_recorded\":%llu}", + JSTR(vk_qf_transfer), static_cast(vk_ownership_barriers)); + std::printf(",\"tpu_backend\":%s,\"tpu_backend_requested\":%s,\"tpu_numerics\":%s,\"tpu_backend_fallback\":%s", + JSTR(tpu_selected), JSTR(tpu_backend), JSTR(quant ? "quant8_asymm_conv1x1" : "w8a16_f32"), + JSTR(tpu_fallback)); + const std::string nn_fl_json = (nn_dev_feature_level >= 0) ? std::to_string(nn_dev_feature_level) : "null"; + std::printf(",\"nnapi\":{\"device\":%s,\"device_feature_level\":%s,\"shared_mem\":%s,\"shared_mem_fallback\":%s,\"host_staged_mem\":%s," + "\"host_staged_mem_fallback\":%s,\"reusable_executions\":%s,\"fenced_api\":%s," + "\"fenced_dmabuf_policy\":%s,\"allow_edgetpu_dmabuf_fenced_probe\":%s," + "\"fenced_dmabuf_refusals\":%llu,\"exec_start_calls\":%llu},", + JSTR(nn_dev_name), nn_fl_json.c_str(), JSTR(nn_mem_mode), JSTR(nn_mem_fallback), JSTR(staged_mem_mode), + JSTR(staged_mem_fallback), nn_reusable ? "true" : "false", nn_fenced ? "true" : "false", + JSTR(nn_fenced_policy), allow_edgetpu_dmabuf_probe ? "true" : "false", + static_cast(nn_refusals), static_cast(nn_exec_starts)); + std::printf("\"sync_fd_handoff_check\":%s,", JSTR("poll_pollin_no_err_nval_and_sync_ioc_file_info_status_eq_1")); + std::printf("\"layers\":%u,\"tokens\":%u,\"warmup\":%u,\"d_model\":%u," + "\"min_cos\":%s,\"handoffs_per_tok\":%u,", + layers, rc.tokens, rc.warmup, d, json_finite_or_null(rc.min_cos, "%.6f").c_str(), 2u * layers); + std::printf("\"iova_pool\":{\"slots\":%u,\"weight_slots\":%u,\"cacheability\":%s,\"coherency\":%s," + "\"upfront_pin_count\":%llu,\"hot_loop_map_count\":%llu,\"hot_loop_unmap_count\":%llu," + "\"total_submissions\":%llu,\"completed_drains\":%llu,\"ob_upfront_iova_maps\":%llu," + "\"ob_prewarmed_layers\":%u,\"iova_observation_scope\":%s,\"ahb_hot_loop_allocs\":%llu," + "\"nnapi_ahb_memories_registered_before_hot_loop\":%u},", + ps_small.slot_count, ps_w.slot_count, JSTR(fs_cacheability_name(FS_CACHE_CACHED)), + JSTR(fs_coherency_policy_name(FS_COHERENCY_POLICY_CACHED_SYNC)), + static_cast(ps_small.upfront_pin_count + ps_w.upfront_pin_count), + static_cast(hot_maps), static_cast(hot_unmaps), + static_cast(ps_small.total_submissions + ps_w.total_submissions), + static_cast(ps_small.completed_drains + ps_w.completed_drains), + static_cast(ob_upfront_maps), ob_prewarmed_layers, JSTR(iova_scope), + static_cast(ahb_hot_allocs), nn_ahb_regs); + std::printf("\"executor_state\":{\"tainted\":%s,\"taint_reason\":%s,\"failure_recoveries\":%llu," + "\"submissions_retired_after_drain\":%llu,\"ledger_inflight_at_exit\":%llu," + "\"pool_inflight_slots_at_exit\":%u},", + ex->tainted() ? "true" : "false", JSTR(ex->taint_reason()), + static_cast(ex->recoveries()), + static_cast(ex->retired_after_drain()), + static_cast(ex->ledger_size()), + ps_small.inflight_slots + ps_small.canceled_draining_slots + ps_w.inflight_slots + + ps_w.canceled_draining_slots); + std::printf("\"iif\":{\"backend\":%s,\"signal_path\":%s,\"gpu_gate\":%s,\"bridge_dma_ok\":%s," + "\"signaler_ip\":%u,\"require_iif\":%s,\"requirement_met\":%s,\"dev_open_calls\":%llu,\"probe\":", + JSTR(iif_backend_name(iif.kind())), JSTR(iif_signal_path), iif_gate ? "true" : "false", + probe.bridge_dma_ok ? "true" : "false", ic.ap_ip, require_iif ? "true" : "false", + iif_met ? "true" : "false", static_cast(iif_dev_open_calls())); + print_iif_probe_json(iif_dev, probe, abi); + std::printf("},\"arms\":["); + bool first_out = true; + for (int k = 0; k < ARM_COUNT; ++k) { + const ArmResult& r = results[k]; + if (!first_out) std::printf(","); + first_out = false; + std::printf("{\"arm\":%s,\"ran\":%s", JSTR(kArmNames[k]), r.ran ? "true" : "false"); + if (!r.ran) { + std::printf(",\"pass\":false,\"skip_reason\":"); + json_escape_print(r.skip_reason.empty() ? std::string("error") : r.skip_reason); + if (!r.error.empty()) { + std::printf(",\"error\":"); + json_escape_print(r.error); + } + if (!r.recovery.empty()) { + std::printf(",\"recovery\":"); + json_escape_print(r.recovery); + } + std::printf("}"); + continue; + } + const double T = static_cast(rc.tokens); + const bool e = r.energy.available; + std::printf(",\"pass\":%s,\"tok_per_s\":%s,\"ms_per_tok_p50\":%s,\"ms_per_tok_p99\":%s," + "\"ms_per_tok_mean\":%s,", + r.pass ? "true" : "false", JNUM(r.tok_per_s, "%.6f"), JNUM(percentile(r.ms_per_tok, 50.0), "%.6f"), + JNUM(percentile(r.ms_per_tok, 99.0), "%.6f"), JNUM(mean(r.ms_per_tok), "%.6f")); + std::printf("\"j_per_tok_gpu\":"); + print_num_or_null(e && r.energy.gpu_rails > 0, r.energy.gpu_j / T); + std::printf(",\"j_per_tok_tpu\":"); + print_num_or_null(e && r.energy.tpu_rails > 0, r.energy.tpu_j / T); + std::printf(",\"j_per_tok_vsys\":"); + print_num_or_null(e, r.energy.total_j / T); + std::printf(",\"odpm_rails\":%d,", r.energy.rails); + std::printf("\"cpu_ctx_switches_per_tok\":%s,\"voluntary_ctxt_switches_per_tok\":%s," + "\"nonvoluntary_ctxt_switches_per_tok\":%s,\"ctx_switches_all_threads_per_tok\":%s," + "\"ctx_source\":%s,", + JNUM(r.ctx_vol_per_tok + r.ctx_nonvol_per_tok, "%.4f"), JNUM(r.ctx_vol_per_tok, "%.4f"), + JNUM(r.ctx_nonvol_per_tok, "%.4f"), JNUM(r.ctx_all_threads_per_tok, "%.4f"), + JSTR(r.ctx_from_proc ? "proc_self_status" : "getrusage")); + std::printf("\"hot_loop_map_count\":%llu,\"hot_loop_unmap_count\":%llu,", + static_cast(r.hot.maps), static_cast(r.hot.unmaps)); + /* Failed parity keeps pass=false; non-finite diagnostics (max_abs_err = inf on NaN) become null. */ + std::printf("\"cos\":%s,\"cos_min_tok\":%s,\"max_abs_err\":%s,", JNUM(r.cos, "%.9f"), + JNUM(r.cos_min_tok, "%.9f"), JNUM(r.max_abs_err, "%.6g")); + std::printf("\"inter_ip_host_copies_per_tok\":%s,\"fence_handoffs_per_tok\":%s,\"synchronous_cpu_hops_per_tok\":%s," + "\"synchronous_tpu_hops_per_tok\":%s,\"iif_fences_per_tok\":%s,\"sync_files_exported_per_tok\":%s," + "\"sync_files_imported_per_tok\":%s,\"userspace_fence_polls_per_tok\":%s," + "\"userspace_wakeups_per_tok\":%s,\"cpu_dma_syncs_per_tok\":%s," + "\"nnapi_start_block_us_per_tok\":%s,\"nnapi_dep_event_create_us_per_tok\":%s," + "\"nnapi_unfenced_hops_per_tok\":%s," + "\"nnapi_event_checks_per_tok\":%s," + "\"host_wait_us_per_tok\":%s,\"dispatch_submit_us_per_tok\":%s,\"pipelined_chain_us_per_tok\":%s," + "\"tpu_hw_us_per_tok\":%s,\"nnapi_sync_call_us_per_tok\":%s,\"expected_handoffs_per_tok\":%s}", + JNUM(static_cast(r.totals.inter_ip_host_copies) / T, "%.3f"), + JNUM(static_cast(r.totals.fence_handoffs) / T, "%.3f"), + JNUM(static_cast(r.totals.synchronous_cpu_hops) / T, "%.3f"), + JNUM(static_cast(r.totals.synchronous_tpu_hops) / T, "%.3f"), + JNUM(static_cast(r.totals.iif_fences) / T, "%.3f"), + JNUM(static_cast(r.totals.sync_files_exported) / T, "%.3f"), + JNUM(static_cast(r.totals.sync_files_imported) / T, "%.3f"), + JNUM(static_cast(r.totals.userspace_fence_polls) / T, "%.3f"), + JNUM(static_cast(r.totals.userspace_wakeups) / T, "%.3f"), + JNUM(static_cast(r.totals.cpu_dma_syncs) / T, "%.3f"), + JNUM(r.totals.nnapi_start_block_us / T, "%.3f"), + JNUM(r.totals.nnapi_dep_event_create_us / T, "%.3f"), + JNUM(static_cast(r.totals.nnapi_unfenced_hops) / T, "%.3f"), + JNUM(static_cast(r.totals.nnapi_event_checks) / T, "%.3f"), + JNUM(r.totals.host_wait_us / T, "%.3f"), + JNUM(r.totals.dispatch_submit_us / T, "%.3f"), + JNUM(r.totals.pipelined_chains ? r.totals.pipelined_chain_us / T : NAN, "%.3f"), + (r.totals.tpu_hw_measured ? JNUM(r.totals.tpu_hw_us / T, "%.3f") : "null"), + (r.totals.nnapi_sync_call_measured ? JNUM(r.totals.nnapi_sync_call_us / T, "%.3f") : "null"), + JNUM(L2, "%.0f")); + } + std::printf("],\"arms_max_abs_diff\":%s}\n", JNUM(arms_max_abs_diff, "%.6g")); + } else { + std::printf("[%s] volcanic_tpu_token_loop_bench (%s) L=%u T=%u d=%u gpu=%s tpu=%s%s%s iif=%s(%s)\n", + pass ? "PASS" : "FAIL", live ? "live" : "mock", layers, rc.tokens, d, gpu_name, tpu_selected.c_str(), + nn_dev_name.empty() ? "" : ":", nn_dev_name.c_str(), iif_backend_name(iif.kind()), + probe.reason ? probe.reason : ""); + for (int k = 0; k < ARM_COUNT; ++k) { + const ArmResult& r = results[k]; + if (!r.ran) { + std::printf(" %-14s skipped: %s %s%s%s\n", kArmNames[k], r.skip_reason.c_str(), r.error.c_str(), + r.recovery.empty() ? "" : " recovery=", r.recovery.c_str()); + continue; + } + const double T = static_cast(rc.tokens); + std::printf(" %-14s %s tok/s=%.2f p50=%.3fms p99=%.3fms ctxsw/tok=%.2f polls/tok=%.1f copies/tok=%.1f " + "cos=%.8f maps=%llu\n", + kArmNames[k], r.pass ? "ok " : "BAD", r.tok_per_s, percentile(r.ms_per_tok, 50.0), + percentile(r.ms_per_tok, 99.0), r.ctx_vol_per_tok + r.ctx_nonvol_per_tok, + static_cast(r.totals.userspace_fence_polls) / T, + static_cast(r.totals.inter_ip_host_copies) / T, r.cos, + static_cast(r.hot.maps)); + } + } + + if (live && ex->tainted()) { + /* + * Intentionally preserve the tainted live executor (and its in-flight + * Vulkan/NNAPI/libopenbuenos/DMA-BUF objects) through process exit so no + * member destructor tears down live hardware resources whose completion + * could not be proved. + */ + } else { + delete ex; + pools_destroy(&pools); + fs_context_destroy(fctx); + } + return pass ? 0 : 1; +}