From dace3e42a8d4313a4f235845377f2145313f0824 Mon Sep 17 00:00:00 2001 From: Ryan S <159389674+saariuslystoned@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:28:49 -0500 Subject: [PATCH 1/3] feat(freetile): add multi-gen Cloud TPU serving planner, SparseCore ragged gathers, and 4-bit codebook parity (#44) --- README.md | 1 + docs/cloud-tpu/multigen-serving-sparsecore.md | 101 ++ freetile/CMakeLists.txt | 8 + freetile/Makefile | 16 +- freetile/README.md | 1 + freetile/include/freetile/serving_planner.hpp | 410 ++++++ freetile/src/serving_planner.cpp | 1225 +++++++++++++++++ freetile/tests/test_serving_planner.cpp | 696 ++++++++++ 8 files changed, 2454 insertions(+), 4 deletions(-) create mode 100644 docs/cloud-tpu/multigen-serving-sparsecore.md create mode 100644 freetile/include/freetile/serving_planner.hpp create mode 100644 freetile/src/serving_planner.cpp create mode 100644 freetile/tests/test_serving_planner.cpp diff --git a/README.md b/README.md index 4fa9255b..d4f36449 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ export OPENBUENOS_DIVE_INTERP_PATH=/data/local/tmp/tpu_open_stack/dive_interp_rv - [`libopenbuenos` Guide](docs/libopenbuenos/README.md) & [`ggml-edgetpu` Guide](docs/llama-cpp-edgetpu/README.md) - [Headless Colab TPU Tooling](docs/cloud-tpu/colab-headless-tooling.md) — Track B `v6e-1`/`v5e-1` headless harness (`tools/colab_tpu_bench.py`), Colab MCP/`v1beta` contract & Track C boundaries - [Cloud TPU Ops: Container CDI & Prometheus Telemetry](docs/cloud-tpu/ops-container-telemetry.md) — Zero-dep `tpu-exporter` (`:9400/metrics`) & `freetpu-cdi` CNCF CDI `v0.6.0` (`freetpu.dev/tpu=all`) Docker/K8s manifests +- [Multi-Generation Serving & SparseCore Planning](docs/cloud-tpu/multigen-serving-sparsecore.md) — Host-side `v5e` / `v5p` / `v6e` / `tpu7x` capability profiles, roofline offload, paged-KV and MoE reference, codebook dequant, and prefix-aware request routing - [FreeTPU Router v0 Guide](docs/router/README.md) — OpenAI-compatible router across Pixel Tensor G5 clusters, local hosts, and Cloud TPU slices --- diff --git a/docs/cloud-tpu/multigen-serving-sparsecore.md b/docs/cloud-tpu/multigen-serving-sparsecore.md new file mode 100644 index 00000000..3a80a661 --- /dev/null +++ b/docs/cloud-tpu/multigen-serving-sparsecore.md @@ -0,0 +1,101 @@ +# Multi-Generation Cloud TPU Serving & SparseCore Planning + +Host-only planner in [`freetile/include/freetile/serving_planner.hpp`](../../freetile/include/freetile/serving_planner.hpp). It describes `v5e`, `v5p`, `v6e` (Trillium), and `tpu7x` (Ironwood) chips, estimates MXU / VPU / HBM roofline knees, plans SparseCore ragged paged-KV gather and MoE scatter/gather with a CPU reference, dequantizes four 4-bit codebooks, and routes prefix-aware prefill and decode across multi-chip slices. The reference runs on the host. It does not open a device, a USB port, or a cloud API. + +```bash +make -C freetile test +cmake -S freetile -B freetile/build -DCMAKE_BUILD_TYPE=Release +cmake --build freetile/build +ctest --test-dir freetile/build --output-on-failure -R freetile_serving_planner_tests +``` + +`ChipTarget` in `tile_ir.hpp` stays `V5E`, `V6E`, `TPU7X`, and `BUENOS_A0`. `v5p` is a serving-planner generation, not a new tile-IR chip target. + +## Capability profiles + +Peaks below are chip peaks. HBM bandwidth is decimal GBps (`bytes/s = gbps * 1e9`). VMEM is the FreeTile planning budget and matches `target_profile` for `V5E` (16 MiB), `V6E` (32 MiB), and `TPU7X` (64 MiB per chiplet). It is not the libopentpu HAL VMEM field. `smem_bytes` is a 1 MiB planner constant on every generation. + +| | `v5e` | `v5p` | `v6e` Trillium | `tpu7x` Ironwood | +| --- | ---: | ---: | ---: | ---: | +| TensorCores / chip | 1 | 2 | 1 | 2 | +| MXU shape | 128x128 | 128x128 | 256x256 | 256x256 | +| MXUs / TensorCore | 4 | 4 | 2 | 2 | +| MXUs / chip | 4 | 8 | 2 | 4 | +| SparseCores / chip | 0 | 4 | 2 | 4 | +| Chiplets / chip | 1 | 1 | 1 | 2 | +| BF16 TFLOP/s | 197 | 459 | 918 | 2307 | +| INT8 TOPS | 393 published | 918 modeled (`2 * BF16`) | 1836 published | 4614 modeled (equal to FP8) | +| FP8 TFLOP/s | none | 459 (equal to BF16) | 918 (equal to BF16) | 4614 (2x BF16) | +| HBM / chip | 16 GiB | 95 GiB | 32 GiB | 192 GiB | +| HBM bandwidth | 819 GBps | 2765 GBps | 1638 GBps | 7380 GBps | +| VMEM / chip | 16 MiB | 32 MiB | 32 MiB | 128 MiB | +| ICI | 2D torus, 400 GBps, 4 ports | 3D torus, 1200 GBps, port count unpublished | 2D torus, 800 GBps, 4 ports | 3D torus, 1200 GBps, port count unpublished | +| `has_sparsecore` | false | true | true | true | +| Native INT8 / BF16 | yes / yes | yes / yes | yes / yes | yes / yes | +| `supports_fp8` | false | true | true | true | +| `supports_native_fp8` | false | false | false | true | +| `supports_native_s4` | true | true | true | false | + +`supports_native_fp8` is true only when the published FP8 peak is strictly greater than BF16 (`tpu7x`). `v5p` and `v6e` list an FP8 rate equal to BF16, so the format is recognized and the 2x-FP8 MXU path is not. Stock profiles set `supports_fp4`, `supports_mxfp4`, and `supports_native_fp4` to false: FP4 is not a published MXU peak format. `tpu7x` die-to-die bandwidth is `d2d_link_multiplier = 6` times one 1D ICI link. Each `tpu7x` chiplet is one TensorCore, two SparseCores, 96 GiB HBM, and 64 MiB VMEM. + +`parse_generation` accepts case-insensitive names such as `ct5lp-hightpu-1t`, `ct5p-hightpu-4t`, `TPU v6e Trillium`, and `Ironwood tpu7x-4t`. A bare `v5` is rejected. `tpu7x` / `ironwood` win over a substring that also contains `v6` or `v5`. + +## Roofline and offload + +One MXU cycle is `2 * mxu_m * mxu_n` BF16 FLOPs, so + +```text +clock_hz = bf16_flops / (mxus_per_chip * 2 * mxu_m * mxu_n) +``` + +The planner models one VPU per TensorCore, 128 lanes by 8 sublanes, and one BF16 FMA (2 FLOPs) per lane-sublane per cycle. Knees are peak flops divided by HBM bytes/s. On `v6e` the MXU/HBM knee is `918e12 / 1638e9`, about 560.44 FLOPs/byte. A square BF16 matmul has arithmetic intensity `n / 3`. `n = 1024` is HBM-bound on `v6e` and compute-bound on `v5e`. `n = 4096` is compute-bound on `v6e`. + +Dispatch: + +- Dense matmul stays on the MXU. `FORCE_VPU` does not move it. `FORCE_SPARSECORE` returns `dense matmul cannot be forced onto SparseCore`. +- Gather and scatter in `AUTO`: a chip with no SparseCore uses the VPU. A working set that fits in chip VMEM stays on the VPU and is marked resident. A larger working set whose intensity is below the VPU/HBM knee goes to SparseCore. Otherwise it stays on the VPU and is compute-bound. +- `FORCE_SPARSECORE` selects SparseCore on `v5p`, `v6e`, and `tpu7x` even when the set fits in VMEM. On `v5e` it fails with `v5e has no SparseCore; refusing forced SparseCore dispatch`. `AUTO` on `v5e` is a successful VPU plan with the same numeric reference. + +## Paged KV and MoE + +`plan_paged_kv` packs variable-length sequences into fixed pages. Each sequence starts a fresh page. Unused block-table slots are `0xffffffff`. `paged_kv_pack`, `paged_kv_gather`, and `paged_kv_scatter` are inverses of a concatenated sequence-major float store. Partial-page tails are zero. The same plan runs on every generation; only the offload unit changes. Forced SparseCore dispatch on `v5e` is rejected before any page is written. + +`plan_moe_route` reads row-major finite scores `[token][expert]`. Top-k is unique, and ties keep the lower expert id. Capacity is `ceil(capacity_factor * tokens * top_k / experts)`. Tokens are assigned in token order, then rank order; overflow drops the later pair. A repeated `(token, expert)` shares one compact slot and does not consume a second capacity entry. `moe_apply_reference` accumulates `activation * (expert_id + 1)` in rank order so a direct loop can check bit-exact parity. `v5e` `AUTO` uses the VPU path and the same compact layout. Forced SparseCore routing on `v5e` fails with the same SparseCore error. + +## Codebook dequant + +`codebook_descriptor` is one 16-entry f32 table plus a group size. Dequant is one multiply, `out[i] = center[nibble] * scale`, so the LUT, the select tree, and the E2M1 decoder match at 0.0 ULP, including a negative zero times `1.0`. Even indexes occupy the low nibble. + +| Format | Group | Centers | +| --- | ---: | --- | +| `IQ4_XS` | 32 | int8 lattice `-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113` stored as exact f32. One scale per group. | +| `NF4` | 64 | exact f32 bits `bf800000 bf3239b1 bf066b30 beca32a0 be91a24d be3d353f bdba7871 00000000 3da2faff 3e24cae3 3e7c04dd 3ead033a 3ee1a4b8 3f1007ab 3f3913b3 3f800000` | +| `BOF4` | 32 | block-offset 4-bit lattice defined here: center = nibble - 8, so offsets `-8 .. 7`. This name is the planner's offset-8 codebook, not a separately published wire format. | +| `FP4` / `MXFP4` | 32 | OCP E2M1. Nibbles `0 .. 7` are `0, 0.5, 1, 1.5, 2, 3, 4, 6` and `8 .. 15` are the signed values, including `-0`. | + +`mxfp4_e8m0_scale` is `2^(exponent - 127)`. Exponent `255` is NaN and fails. The select tree is a complete 4-bit trie: 31 nodes, depth-first preorder, MSB (bit 3) first, left child when the bit is clear. `codebook_select_tree_index` returns the nibble. + +Lowering is a report, not a different numeric result: + +- `FP4` / `MXFP4` with `supports_native_fp4` set on the profile reports `native_fp4`. +- Otherwise `mxu_m >= 256` (`v6e`, `tpu7x`) reports `vperm`. +- Otherwise (`v5e`, `v5p`) reports `vreg_select_tree`. + +Stock profiles never report native FP4. Setting `supports_native_fp4` on a copied `tpu7x` profile reports `native_fp4` for `FP4` / `MXFP4` only. `supports_native_s4` does not change codebook lowering. + +## Prefix-aware request router + +Slice presets are geometry, not a locked chip generation: + +| Preset | Devices | Layout | +| --- | ---: | --- | +| `1x1` | 1 | one package | +| `2x2` | 4 | `dim_x = 2`, `dim_y = 2` | +| `2x4` | 8 | `dim_x = 2`, `dim_y = 4` | +| `tpu7x-dual-chiplet` | 2 | one package, two chiplets | + +`device = fnv1a64(prefix) % num_devices`. An empty prefix hashes the little-endian request id. `package = device / chiplets`, `chiplet = device % chiplets`, `x = package % dim_x`, `y = package / dim_x`. `d2d_buddy` exists only when `chiplets == 2`: the other chiplet on the same package. + +Length buckets are `<=128`, `<=512`, `<=2048`, `<=8192`, then the rest. Decode is `generated_tokens > 0`. Prefill is `generated_tokens == 0` with `prompt_tokens > 0`. Both zero is invalid. Decode length is the saturating sum of prompt and generated tokens. The scheduler orders decode before prefill, then bucket, length, request id, and original index. A request that does not fit the remaining budget is skipped. + +Speculative draft/target verification uses `gamma` and the step budget. A decode request charges `1 + verified` tokens, where `verified = min(draft_tokens, gamma, remaining step budget)`. Accepted drafts are `min(draft_accepted, verified)`. The rest of the verified drafts are rejected, and `draft_tokens - verified` stay pending. Prefill charges `prompt_tokens` and verifies nothing. `draft_accepted > draft_tokens` is invalid. diff --git a/freetile/CMakeLists.txt b/freetile/CMakeLists.txt index 4179fda2..88c88424 100644 --- a/freetile/CMakeLists.txt +++ b/freetile/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(freetile STATIC src/buenos_splines.cpp src/flash_attn_planner.cpp src/malibu_profile.cpp + src/serving_planner.cpp ) target_include_directories(freetile PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") target_compile_options(freetile PRIVATE -Wall -Wextra -Wpedantic -Werror) @@ -32,6 +33,13 @@ target_compile_options(test_splines_and_flash_attn PRIVATE -Wall -Wextra -Wpedantic -Werror -fno-exceptions -fno-rtti) add_test(NAME freetile_splines_flash_attn_tests COMMAND test_splines_and_flash_attn) +add_executable(test_serving_planner + tests/test_serving_planner.cpp +) +target_link_libraries(test_serving_planner PRIVATE freetile) +target_compile_options(test_serving_planner PRIVATE -Wall -Wextra -Wpedantic -Werror) +add_test(NAME freetile_serving_planner_tests COMMAND test_serving_planner) + option(FREETILE_BUILD_BUENOS_PARITY_TEST "Build bit-exact parity test against sibling libopenbuenos" ON) option(FREETILE_BUILD_DIGITAL_TWIN "Build freetile-twin digital twin library, CLI, and tests" ON) diff --git a/freetile/Makefile b/freetile/Makefile index 4f1507ce..a66b7f69 100644 --- a/freetile/Makefile +++ b/freetile/Makefile @@ -27,7 +27,8 @@ CORE_SRCS := \ $(THIS_DIR)/src/buenos_emitter.cpp \ $(THIS_DIR)/src/buenos_splines.cpp \ $(THIS_DIR)/src/flash_attn_planner.cpp \ - $(THIS_DIR)/src/malibu_profile.cpp + $(THIS_DIR)/src/malibu_profile.cpp \ + $(THIS_DIR)/src/serving_planner.cpp CORE_HDRS := \ $(THIS_DIR)/include/freetile/tile_ir.hpp \ @@ -35,7 +36,8 @@ CORE_HDRS := \ $(THIS_DIR)/include/freetile/buenos_emitter.hpp \ $(THIS_DIR)/include/freetile/buenos_splines.hpp \ $(THIS_DIR)/include/freetile/flash_attn_planner.hpp \ - $(THIS_DIR)/include/freetile/malibu_profile.hpp + $(THIS_DIR)/include/freetile/malibu_profile.hpp \ + $(THIS_DIR)/include/freetile/serving_planner.hpp TWIN_HDR := $(THIS_DIR)/include/freetile/twin.h TWIN_SRC := $(THIS_DIR)/src/twin.cpp @@ -53,13 +55,14 @@ TEST_FREETILE := $(BUILD_DIR)/test_freetile TEST_SPLINES := $(BUILD_DIR)/test_splines_and_flash_attn TEST_PARITY := $(BUILD_DIR)/test_buenos_parity TEST_TWIN := $(BUILD_DIR)/test_freetile_twin +TEST_SERVING := $(BUILD_DIR)/test_serving_planner .PHONY: all host twin test verify-header clean openbuenos-host all: host host: $(FREETILE_LIB) $(FREETILE_TWIN_LIB) $(TWIN_CLI) $(ROOT_TWIN_CLI) \ - $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) + $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) twin: $(TWIN_CLI) $(ROOT_TWIN_CLI) @@ -97,6 +100,10 @@ $(TEST_FREETILE): $(THIS_DIR)/tests/test_freetile.cpp $(FREETILE_LIB) $(CORE_HDR @mkdir -p $(dir $@) $(HOST_CXX) $(CXXFLAGS_BASE) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) +$(TEST_SERVING): $(THIS_DIR)/tests/test_serving_planner.cpp $(FREETILE_LIB) $(CORE_HDRS) + @mkdir -p $(dir $@) + $(HOST_CXX) $(CXXFLAGS_BASE) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) + $(TEST_SPLINES): $(THIS_DIR)/tests/test_splines_and_flash_attn.cpp $(FREETILE_LIB) $(CORE_HDRS) @mkdir -p $(dir $@) $(HOST_CXX) $(CXXFLAGS_NOEXC) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) @@ -113,11 +120,12 @@ verify-header: $(TWIN_HDR) $(HOST_CC) -x c -std=c11 -fsyntax-only -Wall -Wextra -Wpedantic -Werror $< $(HOST_CXX) -x c++ -std=c++17 -fsyntax-only -Wall -Wextra -Wpedantic -Werror $< -test: verify-header $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(ROOT_TWIN_CLI) +test: verify-header $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) $(ROOT_TWIN_CLI) $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) + $(TEST_SERVING) clean: rm -rf $(THIS_DIR)/build $(ROOT_TWIN_CLI) diff --git a/freetile/README.md b/freetile/README.md index afbde891..e04cbcdd 100644 --- a/freetile/README.md +++ b/freetile/README.md @@ -17,6 +17,7 @@ - Emits **11-chunk zero-DRAM in-SRAM chained SwiGLU** (`try_emit_buenos_swiglu` / `emit_buenos_swiglu`: `gate -> 0x640 SiLU * up [0x100 MUL] -> down`) with 100% bit-exact parity against `libopenbuenos` across all 6 silicon-proven shapes (`M=1`: `(576,512,576)`, `(576,1536,576)`, `(1536,512,1536)`, `(1536,1024,1536)`; `M=64`: `(576,512,576)`, `(1536,512,1536)`), plus an exact IEEE-754 RNE Horner simulator (`buenos_simulate_swiglu_exact`). - Extends 7-chunk per-tensor `W8A16(FP16)` (`[N/32, K/2, 32, 2]` `w^0x80` layout, `FP32` accumulator, zero intermediate `FP16` overflow hazard) to `K=576`/`N=576` (`SmolLM2-135M`, `M=1`) and batched `M=64` prefill (`W8A16_PT_64X`, `K,N in {512,576,1024,1536}` within the `768 KiB` Core-0 narrow SRAM ceiling), tagged `silicon_verified = false` until live `rango` verification; includes `buenos_should_prefer_w8a16(...)` encoding the selective mixed-precision policy (`lm_head`, `down_proj`, Layer 0–1, `Q6_K`, outlier crest guard, `>32768` FP16 prescale advisory). - Pure C++17 standard library only (zero dependency on `libopenbuenos`, LLVM, MLIR, or Python; `-fno-exceptions -fno-rtti` safe). Optional `test_buenos_parity` verifies bit-exact byte-for-byte parity against `libopenbuenos` when the sibling directory is present. +- **Multi-generation serving planner (`include/freetile/serving_planner.hpp`):** host-only `v5e` / `v5p` / `v6e` / `tpu7x` capability profiles, MXU/VPU/HBM roofline offload, SparseCore-gated paged-KV and MoE reference, 4-bit codebook dequant, and prefix-aware request routing. No device, USB, or cloud access. Covered by `make -C freetile test` and `ctest` name `freetile_serving_planner_tests`. See [multi-generation serving](../docs/cloud-tpu/multigen-serving-sparsecore.md). ## Build & Test diff --git a/freetile/include/freetile/serving_planner.hpp b/freetile/include/freetile/serving_planner.hpp new file mode 100644 index 00000000..a008d5b9 --- /dev/null +++ b/freetile/include/freetile/serving_planner.hpp @@ -0,0 +1,410 @@ +// SPDX-License-Identifier: Apache-2.0 +// Clean-room host planner for multi-generation Cloud TPU serving. +// Profiles, roofline offload, paged-KV gather, MoE routing, 4-bit codebook +// dequant, and prefix-aware request scheduling. No device, cloud, or USB access. +// +// ChipTarget in tile_ir.hpp is unchanged: v5p lives only in this planner so the +// existing V5E / V6E / TPU7X / BUENOS_A0 lowering enum stays stable. +// +// Builds under -std=c++17 -Wall -Wextra -Wpedantic -Werror. + +#pragma once + +#include +#include +#include + +namespace freetile { + +enum class TpuGeneration : uint8_t { + V5E = 0, + V5P = 1, + V6E = 2, + TPU7X = 3, +}; + +enum class IciTopology : uint8_t { + TORUS_2D = 0, + TORUS_3D = 1, +}; + +// Published per-chip peaks are integer TFLOPs / TOPS / GBps from the Cloud TPU +// architecture tables. VMEM figures are FreeTile planning budgets: 16 MiB per +// 128-wide TensorCore (v5e and each v5p TensorCore), 32 MiB for v6e, and +// 64 MiB per tpu7x chiplet (the same budgets as target_profile()). +struct GenerationProfile { + TpuGeneration generation = TpuGeneration::V5E; + const char* name = "invalid"; + const char* architecture = "invalid"; + int32_t mxu_m = 0; + int32_t mxu_n = 0; + int32_t mxus_per_tensorcore = 0; + int32_t tensorcores_per_chip = 0; + int32_t sparsecores_per_chip = 0; + int32_t chiplets_per_chip = 0; + int32_t vpu_lanes = 0; + int32_t vpu_sublanes = 0; + int32_t bf16_tflops = 0; + int32_t int8_tops = 0; + int32_t fp8_tflops = 0; + int32_t hbm_bw_gbps = 0; + int32_t ici_bw_gbps = 0; + int32_t ici_ports = 0; + int32_t d2d_link_multiplier = 0; + IciTopology ici_topology = IciTopology::TORUS_2D; + uint64_t hbm_bytes_per_chip = 0; + uint64_t hbm_bytes_per_chiplet = 0; + uint64_t vmem_bytes_per_tensorcore = 0; + uint64_t vmem_bytes_per_chip = 0; + uint64_t vmem_bytes_per_chiplet = 0; + uint64_t smem_bytes = 0; + bool has_sparsecore = false; + bool supports_int8 = false; + bool supports_bf16 = false; + bool supports_fp8 = false; + bool supports_native_fp8 = false; + bool supports_fp4 = false; + bool supports_mxfp4 = false; + bool supports_native_fp4 = false; + bool supports_native_s4 = false; + bool int8_peak_published = false; + bool fp8_peak_published = false; + bool valid = false; +}; + +inline int32_t mxus_per_chip(const GenerationProfile& profile) { + return profile.mxus_per_tensorcore * profile.tensorcores_per_chip; +} + +GenerationProfile generation_profile(TpuGeneration generation); +bool parse_generation(const char* text, TpuGeneration* out); +const char* ici_topology_name(IciTopology topology); + +enum class NativeQuant : uint8_t { + INT8 = 0, + BF16 = 1, + FP8 = 2, + FP4 = 3, + MXFP4 = 4, +}; + +bool generation_supports_quant(const GenerationProfile& profile, NativeQuant quant); + +enum class ServingOpKind : uint8_t { + DENSE_MATMUL = 0, + PAGED_KV_GATHER = 1, + MOE_SCATTER_GATHER = 2, +}; + +enum class OffloadUnit : uint8_t { + MXU = 0, + VPU = 1, + SPARSECORE = 2, +}; + +enum class DispatchMode : uint8_t { + AUTO = 0, + FORCE_SPARSECORE = 1, + FORCE_VPU = 2, +}; + +struct IntensitySample { + double flops = 0.0; + double hbm_bytes = 0.0; + double working_set_bytes = 0.0; +}; + +struct RooflineKnees { + double clock_hz = 0.0; + double mxu_bf16_flops_per_s = 0.0; + double mxu_int8_ops_per_s = 0.0; + double vpu_bf16_flops_per_s = 0.0; + double hbm_bytes_per_s = 0.0; + double mxu_hbm_knee_flops_per_byte = 0.0; + double vpu_hbm_knee_flops_per_byte = 0.0; + double int8_hbm_knee_ops_per_byte = 0.0; +}; + +struct OffloadDecision { + bool ok = false; + OffloadUnit unit = OffloadUnit::VPU; + bool compute_bound = false; + bool hbm_bound = false; + bool vmem_resident = false; + double arithmetic_intensity = 0.0; + double mxu_hbm_knee = 0.0; + double vpu_hbm_knee = 0.0; + const char* error = ""; +}; + +// Clock is derived from the published BF16 peak and the MXU lattice: +// clock = bf16_flops / (mxus_per_chip * 2 * mxu_m * mxu_n) +// because one MXU cycle contributes 2*m*n BF16 FLOPs. The VPU model is one +// BF16 FMA per lane-sublane per cycle, with one VPU per TensorCore. +RooflineKnees roofline_knees(const GenerationProfile& profile); + +// Dense matmul stays on the MXU. Gather / scatter uses SparseCore only when +// the chip has one, the caller did not force the VPU, and the working set +// does not fit in on-chip VMEM while its arithmetic intensity is below the +// VPU/HBM knee. Forced SparseCore dispatch on a chip without SparseCore +// (v5e) fails with a stable error string. +OffloadDecision decide_offload(const GenerationProfile& profile, + ServingOpKind kind, + const IntensitySample& sample, + DispatchMode mode); + +IntensitySample matmul_intensity(int64_t m, int64_t k, int64_t n, uint32_t elem_bytes); + +const char* offload_unit_name(OffloadUnit unit); +const char* forced_sparsecore_error(TpuGeneration generation); + +// ----------------------------------------------------------------------------- +// 4-bit codebook dequant +// ----------------------------------------------------------------------------- + +constexpr uint32_t kCodebookEntries = 16u; + +enum class CodebookFormat : uint8_t { + IQ4_XS = 0, + NF4 = 1, + BOF4 = 2, + FP4_MXFP4 = 3, +}; + +enum class CodebookPath : uint8_t { + LUT = 0, + SELECT_TREE = 1, + NATIVE_FP4 = 2, +}; + +enum class CodebookLowering : uint8_t { + VREG_SELECT_TREE = 0, + VPERM = 1, + NATIVE_FP4 = 2, +}; + +struct CodebookDescriptor { + CodebookFormat format = CodebookFormat::IQ4_XS; + const char* name = ""; + uint32_t group_size = 0; + float centers[kCodebookEntries] = {}; +}; + +// IQ4_XS uses the 16-entry IQ4 non-linear integer lattice. +// NF4 uses the 16-entry normal-float codebook. +// BOF4 is the block-offset lattice center = nibble - 8 (the Q4_0 offsets). +// FP4/MXFP4 uses the 16 OCP E2M1 finite values, including signed zero. +// group_size is the scale-group length: 32, 64, 32, and 32 respectively. +CodebookDescriptor codebook_descriptor(CodebookFormat format); + +// 256-wide MXU generations (v6e, tpu7x) report VPERM. 128-wide generations +// (v5e, v5p) report a VREG select tree. NATIVE_FP4 is reported only when the +// profile sets supports_native_fp4 and the format is FP4/MXFP4. Published +// profiles leave that flag clear. +CodebookLowering codebook_lowering(const GenerationProfile& profile, CodebookFormat format); +const char* codebook_lowering_name(CodebookLowering lowering); +const char* codebook_format_name(CodebookFormat format); + +// Depth-first 4-bit trie. Returns the nibble itself when the tree is well formed. +uint8_t codebook_select_tree_index(uint8_t nibble); + +// packed holds (n_values + 1) / 2 bytes. Even elements use the low nibble. +// NATIVE_FP4 is rejected unless format is FP4_MXFP4. +// out[i] = center * scale, one multiply, so LUT / select-tree / E2M1 agree in bits. +bool dequant_codebook(CodebookFormat format, + CodebookPath path, + const uint8_t* packed, + uint32_t n_values, + float scale, + float* out, + const char** err); + +// OCP E8M0 power-of-two scale, 2^(exponent - 127). 0xFF is NaN and fails. +bool mxfp4_e8m0_scale(uint8_t exponent, float* out_scale, const char** err); + +// ----------------------------------------------------------------------------- +// Paged KV gather +// ----------------------------------------------------------------------------- + +struct PagedKvRequest { + TpuGeneration generation = TpuGeneration::V5E; + DispatchMode dispatch = DispatchMode::AUTO; + uint32_t page_size = 0; + uint32_t kv_dim = 0; + uint32_t num_sequences = 0; + const uint32_t* seq_lens = nullptr; +}; + +struct PagedKvPlan { + bool ok = false; + OffloadUnit unit = OffloadUnit::VPU; + bool vmem_resident = false; + uint32_t page_size = 0; + uint32_t kv_dim = 0; + uint32_t num_sequences = 0; + uint32_t num_pages = 0; + uint32_t block_stride = 0; + uint32_t total_tokens = 0; + std::vector seq_len; + std::vector seq_offset; + std::vector block_table; + const char* error = ""; +}; + +// Sequential bump allocator: each sequence starts on a fresh page. Sequences +// do not share a page. block_table[seq * block_stride + page] is the page id, +// or 0xffffffff when that slot is unused. +bool plan_paged_kv(const PagedKvRequest& request, PagedKvPlan* out); + +// tokens is the concatenated sequence-major KV store, total_tokens * kv_dim. +// pages is num_pages * page_size * kv_dim, with unused tail slots left at 0. +bool paged_kv_pack(const PagedKvPlan& plan, const float* tokens, float* pages, const char** err); +bool paged_kv_gather(const PagedKvPlan& plan, const float* pages, float* tokens, const char** err); +bool paged_kv_scatter(const PagedKvPlan& plan, const float* tokens, float* pages, const char** err); + +// ----------------------------------------------------------------------------- +// MoE token routing +// ----------------------------------------------------------------------------- + +struct MoeRouteRequest { + TpuGeneration generation = TpuGeneration::V5E; + DispatchMode dispatch = DispatchMode::AUTO; + uint32_t num_tokens = 0; + uint32_t num_experts = 0; + uint32_t top_k = 0; + double capacity_factor = 1.0; + uint32_t hidden_dim = 0; + const float* scores = nullptr; +}; + +struct MoeRoutePlan { + bool ok = false; + OffloadUnit unit = OffloadUnit::VPU; + bool vmem_resident = false; + uint32_t num_tokens = 0; + uint32_t num_experts = 0; + uint32_t top_k = 0; + uint32_t capacity = 0; + uint32_t hidden_dim = 0; + uint32_t dropped = 0; + std::vector assignment; + std::vector scatter_index; + std::vector compact_tokens; + std::vector expert_counts; + const char* error = ""; +}; + +// capacity = ceil(capacity_factor * num_tokens * top_k / num_experts). +// Ties break toward the lower expert id. Overflow drops later tokens. +// Duplicate (token, expert) pairs share one compact slot. +// AUTO on v5e selects the VPU. FORCE_SPARSECORE on v5e fails. +bool plan_moe_route(const MoeRouteRequest& request, MoeRoutePlan* out); + +// Reference expert: y = x * float(expert_id + 1), accumulated in top-k order. +// Bit-exact against a direct per-token loop that uses the same assignment. +bool moe_apply_reference(const MoeRoutePlan& plan, + const float* token_hidden, + float* token_out, + const char** err); + +// ----------------------------------------------------------------------------- +// Prefix-aware bucketed router +// ----------------------------------------------------------------------------- + +enum class SliceShape : uint8_t { + SLICE_1X1 = 0, + SLICE_2X2 = 1, + SLICE_2X4 = 2, + TPU7X_DUAL_CHIPLET = 3, +}; + +enum class RequestPhase : uint8_t { + PREFILL = 0, + DECODE = 1, +}; + +struct SliceTopology { + SliceShape shape = SliceShape::SLICE_1X1; + uint32_t dim_x = 1; + uint32_t dim_y = 1; + uint32_t chiplets_per_chip = 1; + const char* name = "1x1"; +}; + +struct ChipPlacement { + uint32_t device = 0; + uint32_t package = 0; + uint32_t chip_x = 0; + uint32_t chip_y = 0; + uint32_t chiplet = 0; +}; + +struct ServingRequest { + uint64_t request_id = 0; + const char* prefix = nullptr; + size_t prefix_len = 0; + uint32_t prompt_tokens = 0; + uint32_t generated_tokens = 0; + uint32_t draft_tokens = 0; + uint32_t draft_accepted = 0; +}; + +struct ScheduleLimits { + uint32_t max_decode_tokens = 0; + uint32_t max_prefill_tokens = 0; + uint32_t verify_gamma = 0; + uint32_t verify_step_budget = 0; +}; + +struct DraftVerifyBudget { + uint32_t verified = 0; + uint32_t accepted = 0; + uint32_t rejected = 0; + uint32_t pending = 0; +}; + +struct ScheduledItem { + uint64_t request_id = 0; + RequestPhase phase = RequestPhase::PREFILL; + uint32_t length_bucket = 0; + uint32_t scheduled_tokens = 0; + ChipPlacement place; + DraftVerifyBudget verify; +}; + +struct ScheduleStep { + bool ok = false; + std::vector items; + uint32_t decode_tokens = 0; + uint32_t prefill_tokens = 0; + uint32_t verify_tokens = 0; + const char* error = ""; +}; + +inline uint32_t slice_device_count(const SliceTopology& topology) { + return topology.dim_x * topology.dim_y * topology.chiplets_per_chip; +} + +SliceTopology slice_topology(SliceShape shape); +uint64_t fnv1a64(const void* data, size_t size); +uint64_t request_prefix_hash(const ServingRequest& request); +uint32_t length_bucket(uint32_t tokens); + +// device = prefix_hash % device_count. A non-empty prefix sticks to one device. +// A null or empty prefix falls back to the little-endian request id. +bool place_prefix(const SliceTopology& topology, uint64_t prefix_hash, ChipPlacement* out); +bool d2d_buddy(const SliceTopology& topology, const ChipPlacement& place, ChipPlacement* buddy); + +// Decode is scheduled before prefill. Inside a phase, shorter length buckets +// go first, then shorter sequences, then smaller request ids. A request that +// does not fit is skipped so a later smaller request can still fill the step. +// Speculative draft tokens consume verify_gamma per request and +// verify_step_budget across the step. accepted + rejected = verified, and +// pending = draft_tokens - verified. +bool schedule_serving_step(const SliceTopology& topology, + const ServingRequest* requests, + size_t request_count, + const ScheduleLimits& limits, + ScheduleStep* out); + +} // namespace freetile diff --git a/freetile/src/serving_planner.cpp b/freetile/src/serving_planner.cpp new file mode 100644 index 00000000..0efe1d58 --- /dev/null +++ b/freetile/src/serving_planner.cpp @@ -0,0 +1,1225 @@ +// SPDX-License-Identifier: Apache-2.0 +// Host reference for the multi-generation Cloud TPU serving planner. + +#include "freetile/serving_planner.hpp" + +#include +#include +#include + +namespace freetile { +namespace { + +constexpr uint32_t kInvalidPage = 0xffffffffu; +constexpr uint64_t kMaxWorkingSetBytes = 1ull << 40; +constexpr uint32_t kMaxSequences = 1u << 20; +constexpr uint32_t kMaxPageSize = 1u << 16; +constexpr uint32_t kMaxKvDim = 1u << 16; +constexpr uint32_t kMaxTotalTokens = 1u << 24; +constexpr uint32_t kMaxMoeTokens = 1u << 20; +constexpr uint32_t kMaxExperts = 4096u; +constexpr uint32_t kMaxTopK = 64u; +constexpr size_t kMaxScheduleRequests = 100000u; + +constexpr uint64_t kMib = 1024ull * 1024ull; +constexpr uint64_t kGib = 1024ull * 1024ull * 1024ull; + +bool fail(const char** err, const char* message) { + if (err != nullptr) { + *err = message; + } + return false; +} + +bool is_finite(double value) { + return value == value && value < 1.0e300 && value > -1.0e300; +} + +float bits_to_f32(uint32_t bits) { + float out = 0.0f; + std::memcpy(&out, &bits, sizeof(out)); + return out; +} + +float apply_sign(float magnitude, bool negative) { + uint32_t bits = 0u; + std::memcpy(&bits, &magnitude, sizeof(bits)); + if (negative) { + bits |= 0x80000000u; + } else { + bits &= 0x7fffffffu; + } + return bits_to_f32(bits); +} + +float decode_e2m1(uint8_t nibble) { + const bool negative = (nibble & 0x8u) != 0u; + const uint32_t exp = (static_cast(nibble) >> 1) & 0x3u; + const uint32_t man = static_cast(nibble) & 0x1u; + float magnitude = 0.0f; + if (exp == 0u) { + magnitude = (man == 0u) ? 0.0f : 0.5f; + } else { + const float base = (man == 0u) ? 1.0f : 1.5f; + magnitude = base * static_cast(1u << (exp - 1u)); + } + return apply_sign(magnitude, negative); +} + +char ascii_lower(char ch) { + if (ch >= 'A' && ch <= 'Z') { + return static_cast(ch - 'A' + 'a'); + } + return ch; +} + +bool contains_text(const std::string& haystack, const char* needle) { + return haystack.find(needle) != std::string::npos; +} + +uint32_t positive_ceil_u32(double raw, bool* overflow) { + if (!is_finite(raw) || raw < 0.0 || raw >= 4294967296.0) { + *overflow = true; + return 0u; + } + const uint32_t truncated = static_cast(raw); + if (raw > static_cast(truncated)) { + if (truncated == 0xffffffffu) { + *overflow = true; + return 0u; + } + return truncated + 1u; + } + return truncated; +} + +struct SelectNode { + uint8_t bit = 0; + uint8_t leaf = 0; + uint16_t left = 0; + uint16_t right = 0; +}; + +constexpr uint16_t kSelectNodeCount = 31u; + +struct SelectTree { + SelectNode nodes[kSelectNodeCount]; + uint16_t count = 0; +}; + +uint16_t build_select_node(SelectTree* tree, int bit, uint8_t prefix) { + const uint16_t idx = tree->count++; + if (bit < 0) { + tree->nodes[idx].bit = 0xffu; + tree->nodes[idx].leaf = prefix; + tree->nodes[idx].left = 0u; + tree->nodes[idx].right = 0u; + return idx; + } + tree->nodes[idx].bit = static_cast(bit); + tree->nodes[idx].leaf = 0u; + const uint16_t left = build_select_node(tree, bit - 1, prefix); + const uint8_t right_prefix = static_cast(prefix | static_cast(1u << bit)); + const uint16_t right = build_select_node(tree, bit - 1, right_prefix); + tree->nodes[idx].left = left; + tree->nodes[idx].right = right; + return idx; +} + +const SelectTree& select_tree() { + static const SelectTree tree = []() { + SelectTree built; + build_select_node(&built, 3, 0u); + return built; + }(); + return tree; +} + +uint8_t walk_select_tree(uint8_t nibble) { + const SelectTree& tree = select_tree(); + uint16_t idx = 0u; + for (int guard = 0; guard < 8; ++guard) { + const SelectNode& node = tree.nodes[idx]; + if (node.bit == 0xffu) { + return node.leaf; + } + const bool set = ((static_cast(nibble) >> node.bit) & 0x1u) != 0u; + idx = set ? node.right : node.left; + } + return 0u; +} + +void fill_iq4_xs(float* centers) { + static const int8_t kValues[kCodebookEntries] = { + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 + }; + for (uint32_t i = 0u; i < kCodebookEntries; ++i) { + centers[i] = static_cast(kValues[i]); + } +} + +void fill_nf4(float* centers) { + // Exact f32 bits of the public 16-entry normal-float codebook. + static const uint32_t kBits[kCodebookEntries] = { + 0xbf800000u, 0xbf3239b1u, 0xbf066b30u, 0xbeca32a0u, + 0xbe91a24du, 0xbe3d353fu, 0xbdba7871u, 0x00000000u, + 0x3da2faffu, 0x3e24cae3u, 0x3e7c04ddu, 0x3ead033au, + 0x3ee1a4b8u, 0x3f1007abu, 0x3f3913b3u, 0x3f800000u + }; + for (uint32_t i = 0u; i < kCodebookEntries; ++i) { + centers[i] = bits_to_f32(kBits[i]); + } +} + +void fill_bof4(float* centers) { + for (uint32_t i = 0u; i < kCodebookEntries; ++i) { + centers[i] = static_cast(static_cast(i) - 8); + } +} + +void fill_fp4(float* centers) { + for (uint32_t i = 0u; i < kCodebookEntries; ++i) { + centers[i] = decode_e2m1(static_cast(i)); + } +} + +GenerationProfile make_v5e() { + GenerationProfile p; + p.generation = TpuGeneration::V5E; + p.name = "v5e"; + p.architecture = "v5e"; + p.mxu_m = 128; + p.mxu_n = 128; + p.mxus_per_tensorcore = 4; + p.tensorcores_per_chip = 1; + p.sparsecores_per_chip = 0; + p.chiplets_per_chip = 1; + p.vpu_lanes = 128; + p.vpu_sublanes = 8; + p.bf16_tflops = 197; + p.int8_tops = 393; + p.fp8_tflops = 0; + p.hbm_bw_gbps = 819; + p.ici_bw_gbps = 400; + p.ici_ports = 4; + p.d2d_link_multiplier = 0; + p.ici_topology = IciTopology::TORUS_2D; + p.hbm_bytes_per_chip = 16ull * kGib; + p.hbm_bytes_per_chiplet = p.hbm_bytes_per_chip; + p.vmem_bytes_per_tensorcore = 16ull * kMib; + p.vmem_bytes_per_chip = 16ull * kMib; + p.vmem_bytes_per_chiplet = 16ull * kMib; + p.smem_bytes = 1ull * kMib; + p.has_sparsecore = false; + p.supports_int8 = true; + p.supports_bf16 = true; + p.supports_fp8 = false; + p.supports_native_fp8 = false; + p.supports_fp4 = false; + p.supports_mxfp4 = false; + p.supports_native_fp4 = false; + p.supports_native_s4 = true; + p.int8_peak_published = true; + p.fp8_peak_published = false; + p.valid = true; + return p; +} + +GenerationProfile make_v5p() { + GenerationProfile p; + p.generation = TpuGeneration::V5P; + p.name = "v5p"; + p.architecture = "v5p"; + p.mxu_m = 128; + p.mxu_n = 128; + p.mxus_per_tensorcore = 4; + p.tensorcores_per_chip = 2; + p.sparsecores_per_chip = 4; + p.chiplets_per_chip = 1; + p.vpu_lanes = 128; + p.vpu_sublanes = 8; + p.bf16_tflops = 459; + p.int8_tops = 918; + p.fp8_tflops = 459; + p.hbm_bw_gbps = 2765; + p.ici_bw_gbps = 1200; + p.ici_ports = 0; + p.d2d_link_multiplier = 0; + p.ici_topology = IciTopology::TORUS_3D; + p.hbm_bytes_per_chip = 95ull * kGib; + p.hbm_bytes_per_chiplet = p.hbm_bytes_per_chip; + p.vmem_bytes_per_tensorcore = 16ull * kMib; + p.vmem_bytes_per_chip = 32ull * kMib; + p.vmem_bytes_per_chiplet = 32ull * kMib; + p.smem_bytes = 1ull * kMib; + p.has_sparsecore = true; + p.supports_int8 = true; + p.supports_bf16 = true; + p.supports_fp8 = true; + p.supports_native_fp8 = false; + p.supports_fp4 = false; + p.supports_mxfp4 = false; + p.supports_native_fp4 = false; + p.supports_native_s4 = true; + p.int8_peak_published = false; + p.fp8_peak_published = true; + p.valid = true; + return p; +} + +GenerationProfile make_v6e() { + GenerationProfile p; + p.generation = TpuGeneration::V6E; + p.name = "v6e"; + p.architecture = "Trillium"; + p.mxu_m = 256; + p.mxu_n = 256; + p.mxus_per_tensorcore = 2; + p.tensorcores_per_chip = 1; + p.sparsecores_per_chip = 2; + p.chiplets_per_chip = 1; + p.vpu_lanes = 128; + p.vpu_sublanes = 8; + p.bf16_tflops = 918; + p.int8_tops = 1836; + p.fp8_tflops = 918; + p.hbm_bw_gbps = 1638; + p.ici_bw_gbps = 800; + p.ici_ports = 4; + p.d2d_link_multiplier = 0; + p.ici_topology = IciTopology::TORUS_2D; + p.hbm_bytes_per_chip = 32ull * kGib; + p.hbm_bytes_per_chiplet = p.hbm_bytes_per_chip; + p.vmem_bytes_per_tensorcore = 32ull * kMib; + p.vmem_bytes_per_chip = 32ull * kMib; + p.vmem_bytes_per_chiplet = 32ull * kMib; + p.smem_bytes = 1ull * kMib; + p.has_sparsecore = true; + p.supports_int8 = true; + p.supports_bf16 = true; + p.supports_fp8 = true; + p.supports_native_fp8 = false; + p.supports_fp4 = false; + p.supports_mxfp4 = false; + p.supports_native_fp4 = false; + p.supports_native_s4 = true; + p.int8_peak_published = true; + p.fp8_peak_published = true; + p.valid = true; + return p; +} + +GenerationProfile make_tpu7x() { + GenerationProfile p; + p.generation = TpuGeneration::TPU7X; + p.name = "tpu7x"; + p.architecture = "Ironwood"; + p.mxu_m = 256; + p.mxu_n = 256; + p.mxus_per_tensorcore = 2; + p.tensorcores_per_chip = 2; + p.sparsecores_per_chip = 4; + p.chiplets_per_chip = 2; + p.vpu_lanes = 128; + p.vpu_sublanes = 8; + p.bf16_tflops = 2307; + p.int8_tops = 4614; + p.fp8_tflops = 4614; + p.hbm_bw_gbps = 7380; + p.ici_bw_gbps = 1200; + p.ici_ports = 0; + p.d2d_link_multiplier = 6; + p.ici_topology = IciTopology::TORUS_3D; + p.hbm_bytes_per_chiplet = 96ull * kGib; + p.hbm_bytes_per_chip = 192ull * kGib; + p.vmem_bytes_per_tensorcore = 64ull * kMib; + p.vmem_bytes_per_chiplet = 64ull * kMib; + p.vmem_bytes_per_chip = 128ull * kMib; + p.smem_bytes = 1ull * kMib; + p.has_sparsecore = true; + p.supports_int8 = true; + p.supports_bf16 = true; + p.supports_fp8 = true; + p.supports_native_fp8 = true; + p.supports_fp4 = false; + p.supports_mxfp4 = false; + p.supports_native_fp4 = false; + p.supports_native_s4 = false; + p.int8_peak_published = false; + p.fp8_peak_published = true; + p.valid = true; + return p; +} + +bool profile_ready(const GenerationProfile& profile) { + return profile.valid && profile.mxu_m > 0 && profile.mxu_n > 0 && + profile.tensorcores_per_chip > 0 && profile.chiplets_per_chip > 0 && + profile.hbm_bw_gbps > 0 && profile.bf16_tflops > 0 && + profile.vmem_bytes_per_chip > 0; +} + +uint32_t context_length(const ServingRequest& request, RequestPhase phase) { + if (phase == RequestPhase::PREFILL) { + return request.prompt_tokens; + } + const uint32_t prompt = request.prompt_tokens; + const uint32_t generated = request.generated_tokens; + if (prompt > 0xffffffffu - generated) { + return 0xffffffffu; + } + return prompt + generated; +} + +bool resolve_phase(const ServingRequest& request, RequestPhase* phase, const char** err) { + if (request.prefix_len > 0u && request.prefix == nullptr) { + return fail(err, "prefix length set without prefix bytes"); + } + if (request.draft_accepted > request.draft_tokens) { + return fail(err, "draft_accepted exceeds draft_tokens"); + } + if (request.generated_tokens == 0u) { + if (request.prompt_tokens == 0u) { + return fail(err, "request needs prompt tokens or generated tokens"); + } + *phase = RequestPhase::PREFILL; + return true; + } + *phase = RequestPhase::DECODE; + return true; +} + +} // namespace + +GenerationProfile generation_profile(TpuGeneration generation) { + switch (generation) { + case TpuGeneration::V5E: return make_v5e(); + case TpuGeneration::V5P: return make_v5p(); + case TpuGeneration::V6E: return make_v6e(); + case TpuGeneration::TPU7X: return make_tpu7x(); + } + GenerationProfile invalid; + return invalid; +} + +bool parse_generation(const char* text, TpuGeneration* out) { + if (text == nullptr || out == nullptr || text[0] == '\0') { + return false; + } + std::string lower; + lower.reserve(64u); + for (const char* cursor = text; *cursor != '\0' && lower.size() < 128u; ++cursor) { + lower.push_back(ascii_lower(*cursor)); + } + if (contains_text(lower, "tpu7x") || contains_text(lower, "ironwood")) { + *out = TpuGeneration::TPU7X; + return true; + } + if (contains_text(lower, "ct6e") || contains_text(lower, "v6e") || + contains_text(lower, "trillium") || contains_text(lower, "v6")) { + *out = TpuGeneration::V6E; + return true; + } + if (contains_text(lower, "ct5p") || contains_text(lower, "v5p")) { + *out = TpuGeneration::V5P; + return true; + } + if (contains_text(lower, "ct5lp") || contains_text(lower, "v5e") || + contains_text(lower, "v5-lite") || contains_text(lower, "v5lite")) { + *out = TpuGeneration::V5E; + return true; + } + return false; +} + +const char* ici_topology_name(IciTopology topology) { + switch (topology) { + case IciTopology::TORUS_2D: return "torus_2d"; + case IciTopology::TORUS_3D: return "torus_3d"; + } + return "invalid"; +} + +bool generation_supports_quant(const GenerationProfile& profile, NativeQuant quant) { + switch (quant) { + case NativeQuant::INT8: return profile.supports_int8; + case NativeQuant::BF16: return profile.supports_bf16; + case NativeQuant::FP8: return profile.supports_fp8; + case NativeQuant::FP4: return profile.supports_fp4; + case NativeQuant::MXFP4: return profile.supports_mxfp4; + } + return false; +} + +RooflineKnees roofline_knees(const GenerationProfile& profile) { + RooflineKnees knees; + if (!profile_ready(profile)) { + return knees; + } + const double bf16_flops = static_cast(profile.bf16_tflops) * 1.0e12; + const double mxus = static_cast(mxus_per_chip(profile)); + const double lattice = mxus * 2.0 * static_cast(profile.mxu_m) * + static_cast(profile.mxu_n); + knees.mxu_bf16_flops_per_s = bf16_flops; + knees.clock_hz = bf16_flops / lattice; + knees.vpu_bf16_flops_per_s = + static_cast(profile.tensorcores_per_chip) * + static_cast(profile.vpu_lanes) * + static_cast(profile.vpu_sublanes) * 2.0 * knees.clock_hz; + knees.hbm_bytes_per_s = static_cast(profile.hbm_bw_gbps) * 1.0e9; + knees.mxu_hbm_knee_flops_per_byte = bf16_flops / knees.hbm_bytes_per_s; + knees.vpu_hbm_knee_flops_per_byte = knees.vpu_bf16_flops_per_s / knees.hbm_bytes_per_s; + if (profile.int8_tops > 0) { + knees.mxu_int8_ops_per_s = static_cast(profile.int8_tops) * 1.0e12; + knees.int8_hbm_knee_ops_per_byte = knees.mxu_int8_ops_per_s / knees.hbm_bytes_per_s; + } + return knees; +} + +const char* offload_unit_name(OffloadUnit unit) { + switch (unit) { + case OffloadUnit::MXU: return "mxu"; + case OffloadUnit::VPU: return "vpu"; + case OffloadUnit::SPARSECORE: return "sparsecore"; + } + return "invalid"; +} + +const char* forced_sparsecore_error(TpuGeneration generation) { + if (generation == TpuGeneration::V5E) { + return "v5e has no SparseCore; refusing forced SparseCore dispatch"; + } + return "generation has no SparseCore; refusing forced SparseCore dispatch"; +} + +OffloadDecision decide_offload(const GenerationProfile& profile, + ServingOpKind kind, + const IntensitySample& sample, + DispatchMode mode) { + OffloadDecision decision; + if (!profile_ready(profile)) { + decision.error = "generation profile is incomplete"; + return decision; + } + if (!is_finite(sample.flops) || !is_finite(sample.hbm_bytes) || + !is_finite(sample.working_set_bytes) || sample.flops < 0.0 || + sample.hbm_bytes < 0.0 || sample.working_set_bytes < 0.0) { + decision.error = "intensity sample must be finite and non-negative"; + return decision; + } + const RooflineKnees knees = roofline_knees(profile); + if (sample.hbm_bytes > 0.0) { + decision.arithmetic_intensity = sample.flops / sample.hbm_bytes; + } else if (sample.flops > 0.0) { + decision.arithmetic_intensity = 1.0e300; + } + decision.mxu_hbm_knee = knees.mxu_hbm_knee_flops_per_byte; + decision.vpu_hbm_knee = knees.vpu_hbm_knee_flops_per_byte; + + if (kind == ServingOpKind::DENSE_MATMUL) { + if (mode == DispatchMode::FORCE_SPARSECORE) { + decision.error = "dense matmul cannot be forced onto SparseCore"; + return decision; + } + decision.unit = OffloadUnit::MXU; + decision.compute_bound = decision.arithmetic_intensity >= decision.mxu_hbm_knee; + decision.hbm_bound = !decision.compute_bound; + decision.ok = true; + return decision; + } + + if (mode == DispatchMode::FORCE_SPARSECORE && !profile.has_sparsecore) { + decision.error = forced_sparsecore_error(profile.generation); + return decision; + } + + const bool fits_vmem = sample.working_set_bytes <= static_cast(profile.vmem_bytes_per_chip); + const bool below_vpu_knee = decision.arithmetic_intensity < decision.vpu_hbm_knee; + if (mode == DispatchMode::FORCE_VPU || !profile.has_sparsecore) { + decision.unit = OffloadUnit::VPU; + } else if (mode == DispatchMode::FORCE_SPARSECORE) { + decision.unit = OffloadUnit::SPARSECORE; + } else if (fits_vmem || !below_vpu_knee) { + decision.unit = OffloadUnit::VPU; + } else { + decision.unit = OffloadUnit::SPARSECORE; + } + decision.vmem_resident = decision.unit == OffloadUnit::VPU && fits_vmem; + decision.compute_bound = decision.unit == OffloadUnit::VPU && !below_vpu_knee; + decision.hbm_bound = !decision.compute_bound && !decision.vmem_resident; + decision.ok = true; + return decision; +} + +IntensitySample matmul_intensity(int64_t m, int64_t k, int64_t n, uint32_t elem_bytes) { + IntensitySample sample; + if (m <= 0 || k <= 0 || n <= 0 || elem_bytes == 0u) { + sample.flops = -1.0; + return sample; + } + const double md = static_cast(m); + const double kd = static_cast(k); + const double nd = static_cast(n); + sample.flops = 2.0 * md * kd * nd; + const double elements = md * kd + kd * nd + md * nd; + sample.hbm_bytes = elements * static_cast(elem_bytes); + sample.working_set_bytes = sample.hbm_bytes; + return sample; +} + +CodebookDescriptor codebook_descriptor(CodebookFormat format) { + CodebookDescriptor descriptor; + descriptor.format = format; + switch (format) { + case CodebookFormat::IQ4_XS: + descriptor.name = "iq4_xs"; + descriptor.group_size = 32u; + fill_iq4_xs(descriptor.centers); + break; + case CodebookFormat::NF4: + descriptor.name = "nf4"; + descriptor.group_size = 64u; + fill_nf4(descriptor.centers); + break; + case CodebookFormat::BOF4: + descriptor.name = "bof4"; + descriptor.group_size = 32u; + fill_bof4(descriptor.centers); + break; + case CodebookFormat::FP4_MXFP4: + descriptor.name = "fp4_mxfp4"; + descriptor.group_size = 32u; + fill_fp4(descriptor.centers); + break; + } + return descriptor; +} + +CodebookLowering codebook_lowering(const GenerationProfile& profile, CodebookFormat format) { + if (format == CodebookFormat::FP4_MXFP4 && profile.supports_native_fp4) { + return CodebookLowering::NATIVE_FP4; + } + if (profile.mxu_m >= 256 && profile.mxu_n >= 256) { + return CodebookLowering::VPERM; + } + return CodebookLowering::VREG_SELECT_TREE; +} + +const char* codebook_lowering_name(CodebookLowering lowering) { + switch (lowering) { + case CodebookLowering::VREG_SELECT_TREE: return "vreg_select_tree"; + case CodebookLowering::VPERM: return "vperm"; + case CodebookLowering::NATIVE_FP4: return "native_fp4"; + } + return "invalid"; +} + +const char* codebook_format_name(CodebookFormat format) { + return codebook_descriptor(format).name; +} + +uint8_t codebook_select_tree_index(uint8_t nibble) { + return walk_select_tree(static_cast(nibble & 0x0fu)); +} + +bool dequant_codebook(CodebookFormat format, + CodebookPath path, + const uint8_t* packed, + uint32_t n_values, + float scale, + float* out, + const char** err) { + if (n_values > 0u && (packed == nullptr || out == nullptr)) { + return fail(err, "dequant buffers are required"); + } + if (out == nullptr && n_values == 0u) { + return true; + } + if (!is_finite(static_cast(scale))) { + return fail(err, "codebook scale must be finite"); + } + if (path == CodebookPath::NATIVE_FP4 && format != CodebookFormat::FP4_MXFP4) { + return fail(err, "native FP4 dequant applies only to FP4/MXFP4"); + } + const CodebookDescriptor descriptor = codebook_descriptor(format); + for (uint32_t i = 0u; i < n_values; ++i) { + const uint8_t byte = packed[i >> 1]; + const uint8_t nibble = (i & 1u) != 0u ? static_cast(byte >> 4) + : static_cast(byte & 0x0fu); + float center = 0.0f; + if (path == CodebookPath::NATIVE_FP4) { + center = decode_e2m1(nibble); + } else if (path == CodebookPath::SELECT_TREE) { + center = descriptor.centers[walk_select_tree(nibble)]; + } else { + center = descriptor.centers[nibble]; + } + out[i] = center * scale; + } + return true; +} + +bool mxfp4_e8m0_scale(uint8_t exponent, float* out_scale, const char** err) { + if (out_scale == nullptr) { + return fail(err, "scale output is required"); + } + if (exponent == 0xffu) { + return fail(err, "E8M0 exponent 0xFF is NaN"); + } + if (exponent == 0u) { + *out_scale = bits_to_f32(0x00400000u); + return true; + } + *out_scale = bits_to_f32(static_cast(exponent) << 23); + return true; +} + +bool plan_paged_kv(const PagedKvRequest& request, PagedKvPlan* out) { + if (out == nullptr) { + return false; + } + *out = PagedKvPlan{}; + const GenerationProfile profile = generation_profile(request.generation); + if (!profile.valid) { + out->error = "unknown generation"; + return false; + } + if (request.page_size == 0u || request.page_size > kMaxPageSize || + request.kv_dim == 0u || request.kv_dim > kMaxKvDim || + request.num_sequences == 0u || request.num_sequences > kMaxSequences || + request.seq_lens == nullptr) { + out->error = "paged KV request is out of range"; + return false; + } + + uint32_t stride = 0u; + uint64_t total_tokens = 0u; + uint64_t total_pages = 0u; + for (uint32_t seq = 0u; seq < request.num_sequences; ++seq) { + const uint32_t len = request.seq_lens[seq]; + if (len == 0u) { + out->error = "sequence length must be positive"; + return false; + } + const uint64_t pages = + (static_cast(len) + request.page_size - 1u) / request.page_size; + if (pages > 0xffffffffu) { + out->error = "sequence page count overflows"; + return false; + } + if (static_cast(pages) > stride) { + stride = static_cast(pages); + } + total_pages += pages; + total_tokens += len; + } + if (total_tokens > kMaxTotalTokens || total_pages > kMaxTotalTokens || total_pages == 0u) { + out->error = "paged KV working set is out of range"; + return false; + } + const uint64_t page_bytes = static_cast(request.page_size) * + static_cast(request.kv_dim) * sizeof(float); + if (page_bytes == 0u || total_pages > kMaxWorkingSetBytes / page_bytes) { + out->error = "paged KV byte count overflows"; + return false; + } + const uint64_t working = total_pages * page_bytes; + IntensitySample sample; + sample.flops = 0.0; + sample.hbm_bytes = static_cast(working); + sample.working_set_bytes = sample.hbm_bytes; + const OffloadDecision decision = + decide_offload(profile, ServingOpKind::PAGED_KV_GATHER, sample, request.dispatch); + if (!decision.ok) { + out->error = decision.error; + return false; + } + + out->page_size = request.page_size; + out->kv_dim = request.kv_dim; + out->num_sequences = request.num_sequences; + out->num_pages = static_cast(total_pages); + out->block_stride = stride; + out->total_tokens = static_cast(total_tokens); + out->unit = decision.unit; + out->vmem_resident = decision.vmem_resident; + out->seq_len.assign(request.seq_lens, request.seq_lens + request.num_sequences); + out->seq_offset.assign(static_cast(request.num_sequences) + 1u, 0u); + out->block_table.assign(static_cast(request.num_sequences) * stride, kInvalidPage); + + uint32_t next_page = 0u; + uint32_t cursor = 0u; + for (uint32_t seq = 0u; seq < request.num_sequences; ++seq) { + out->seq_offset[seq] = cursor; + const uint32_t len = out->seq_len[seq]; + const uint32_t pages = (len + request.page_size - 1u) / request.page_size; + for (uint32_t page = 0u; page < pages; ++page) { + out->block_table[static_cast(seq) * stride + page] = next_page++; + } + cursor += len; + } + out->seq_offset[request.num_sequences] = cursor; + out->ok = true; + return true; +} + +bool paged_plan_ready(const PagedKvPlan& plan, const char** err) { + if (!plan.ok || plan.page_size == 0u || plan.kv_dim == 0u || plan.num_pages == 0u) { + return fail(err, "paged KV plan is not ready"); + } + return true; +} + +bool paged_kv_pack(const PagedKvPlan& plan, const float* tokens, float* pages, const char** err) { + if (!paged_plan_ready(plan, err)) { + return false; + } + if (tokens == nullptr || pages == nullptr) { + return fail(err, "paged KV buffers are required"); + } + const uint64_t page_floats = static_cast(plan.num_pages) * plan.page_size * plan.kv_dim; + std::memset(pages, 0, static_cast(page_floats) * sizeof(float)); + for (uint32_t seq = 0u; seq < plan.num_sequences; ++seq) { + const uint32_t len = plan.seq_len[seq]; + for (uint32_t token = 0u; token < len; ++token) { + const uint32_t page_slot = token / plan.page_size; + const uint32_t page = plan.block_table[static_cast(seq) * plan.block_stride + page_slot]; + const uint32_t offset = token % plan.page_size; + const float* src = tokens + (static_cast(plan.seq_offset[seq] + token) * plan.kv_dim); + float* dst = pages + (static_cast(page * plan.page_size + offset) * plan.kv_dim); + std::memcpy(dst, src, static_cast(plan.kv_dim) * sizeof(float)); + } + } + return true; +} + +bool paged_kv_gather(const PagedKvPlan& plan, const float* pages, float* tokens, const char** err) { + if (!paged_plan_ready(plan, err)) { + return false; + } + if (pages == nullptr || tokens == nullptr) { + return fail(err, "paged KV buffers are required"); + } + for (uint32_t seq = 0u; seq < plan.num_sequences; ++seq) { + const uint32_t len = plan.seq_len[seq]; + for (uint32_t token = 0u; token < len; ++token) { + const uint32_t page_slot = token / plan.page_size; + const uint32_t page = plan.block_table[static_cast(seq) * plan.block_stride + page_slot]; + const uint32_t offset = token % plan.page_size; + const float* src = pages + (static_cast(page * plan.page_size + offset) * plan.kv_dim); + float* dst = tokens + (static_cast(plan.seq_offset[seq] + token) * plan.kv_dim); + std::memcpy(dst, src, static_cast(plan.kv_dim) * sizeof(float)); + } + } + return true; +} + +bool paged_kv_scatter(const PagedKvPlan& plan, const float* tokens, float* pages, const char** err) { + return paged_kv_pack(plan, tokens, pages, err); +} + +bool plan_moe_route(const MoeRouteRequest& request, MoeRoutePlan* out) { + if (out == nullptr) { + return false; + } + *out = MoeRoutePlan{}; + const GenerationProfile profile = generation_profile(request.generation); + if (!profile.valid) { + out->error = "unknown generation"; + return false; + } + if (request.num_tokens == 0u || request.num_tokens > kMaxMoeTokens || + request.num_experts == 0u || request.num_experts > kMaxExperts || + request.top_k == 0u || request.top_k > kMaxTopK || + request.top_k > request.num_experts || request.hidden_dim == 0u || + request.scores == nullptr) { + out->error = "MoE route request is out of range"; + return false; + } + if (!is_finite(request.capacity_factor) || request.capacity_factor < 0.0) { + out->error = "capacity factor must be finite and non-negative"; + return false; + } + const size_t score_count = static_cast(request.num_tokens) * request.num_experts; + for (size_t i = 0u; i < score_count; ++i) { + if (!is_finite(static_cast(request.scores[i]))) { + out->error = "MoE scores must be finite"; + return false; + } + } + bool overflow = false; + const double raw = request.capacity_factor * static_cast(request.num_tokens) * + static_cast(request.top_k) / + static_cast(request.num_experts); + const uint32_t capacity = positive_ceil_u32(raw, &overflow); + if (overflow) { + out->error = "expert capacity overflows"; + return false; + } + const uint64_t hidden_bytes = static_cast(request.num_tokens) * + static_cast(request.hidden_dim) * sizeof(float); + if (hidden_bytes == 0u || hidden_bytes > kMaxWorkingSetBytes) { + out->error = "MoE hidden working set is out of range"; + return false; + } + IntensitySample sample; + sample.flops = 0.0; + sample.hbm_bytes = static_cast(hidden_bytes) * 2.0; + sample.working_set_bytes = static_cast(hidden_bytes); + const OffloadDecision decision = + decide_offload(profile, ServingOpKind::MOE_SCATTER_GATHER, sample, request.dispatch); + if (!decision.ok) { + out->error = decision.error; + return false; + } + + const size_t assign_count = static_cast(request.num_tokens) * request.top_k; + const size_t compact_count = static_cast(request.num_experts) * capacity; + out->num_tokens = request.num_tokens; + out->num_experts = request.num_experts; + out->top_k = request.top_k; + out->capacity = capacity; + out->hidden_dim = request.hidden_dim; + out->unit = decision.unit; + out->vmem_resident = decision.vmem_resident; + out->assignment.assign(assign_count, -1); + out->scatter_index.assign(assign_count, -1); + out->compact_tokens.assign(compact_count, -1); + out->expert_counts.assign(request.num_experts, 0u); + + std::vector chosen(request.num_experts, 0u); + for (uint32_t token = 0u; token < request.num_tokens; ++token) { + std::fill(chosen.begin(), chosen.end(), 0u); + const float* row = request.scores + static_cast(token) * request.num_experts; + for (uint32_t rank = 0u; rank < request.top_k; ++rank) { + int32_t best = -1; + float best_score = 0.0f; + for (uint32_t expert = 0u; expert < request.num_experts; ++expert) { + if (chosen[expert] != 0u) { + continue; + } + const float score = row[expert]; + if (best < 0 || score > best_score || (score == best_score && static_cast(expert) < best)) { + best = static_cast(expert); + best_score = score; + } + } + if (best < 0) { + out->error = "failed to select an expert"; + *out = MoeRoutePlan{}; + out->error = "failed to select an expert"; + return false; + } + chosen[static_cast(best)] = 1u; + const size_t slot = static_cast(token) * request.top_k + rank; + const uint32_t expert = static_cast(best); + int32_t existing = -1; + const uint32_t count = out->expert_counts[expert]; + const size_t base = static_cast(expert) * capacity; + for (uint32_t local = 0u; local < count; ++local) { + if (out->compact_tokens[base + local] == static_cast(token)) { + existing = static_cast(base + local); + break; + } + } + if (existing >= 0) { + out->assignment[slot] = best; + out->scatter_index[slot] = existing; + continue; + } + if (count >= capacity) { + out->dropped += 1u; + continue; + } + out->compact_tokens[base + count] = static_cast(token); + out->expert_counts[expert] = count + 1u; + out->assignment[slot] = best; + out->scatter_index[slot] = static_cast(base + count); + } + } + out->ok = true; + return true; +} + +bool moe_apply_reference(const MoeRoutePlan& plan, + const float* token_hidden, + float* token_out, + const char** err) { + if (!plan.ok || plan.hidden_dim == 0u) { + return fail(err, "MoE plan is not ready"); + } + if (token_hidden == nullptr || token_out == nullptr) { + return fail(err, "MoE hidden buffers are required"); + } + const uint32_t hidden = plan.hidden_dim; + const size_t compact_count = plan.compact_tokens.size(); + std::vector workspace(compact_count * hidden, 0.0f); + for (uint32_t expert = 0u; expert < plan.num_experts; ++expert) { + const float weight = static_cast(expert + 1u); + const size_t base = static_cast(expert) * plan.capacity; + for (uint32_t local = 0u; local < plan.expert_counts[expert]; ++local) { + const int32_t token = plan.compact_tokens[base + local]; + if (token < 0) { + return fail(err, "compact expert slot is empty"); + } + const float* src = token_hidden + static_cast(token) * hidden; + float* dst = workspace.data() + (base + local) * hidden; + for (uint32_t lane = 0u; lane < hidden; ++lane) { + dst[lane] = src[lane] * weight; + } + } + } + const size_t token_floats = static_cast(plan.num_tokens) * hidden; + std::fill(token_out, token_out + token_floats, 0.0f); + for (uint32_t token = 0u; token < plan.num_tokens; ++token) { + float* dst = token_out + static_cast(token) * hidden; + for (uint32_t rank = 0u; rank < plan.top_k; ++rank) { + const int32_t index = plan.scatter_index[static_cast(token) * plan.top_k + rank]; + if (index < 0) { + continue; + } + const float* src = workspace.data() + static_cast(index) * hidden; + for (uint32_t lane = 0u; lane < hidden; ++lane) { + dst[lane] += src[lane]; + } + } + } + return true; +} + +SliceTopology slice_topology(SliceShape shape) { + SliceTopology topology; + switch (shape) { + case SliceShape::SLICE_1X1: + topology.shape = shape; + topology.dim_x = 1u; + topology.dim_y = 1u; + topology.chiplets_per_chip = 1u; + topology.name = "1x1"; + return topology; + case SliceShape::SLICE_2X2: + topology.shape = shape; + topology.dim_x = 2u; + topology.dim_y = 2u; + topology.chiplets_per_chip = 1u; + topology.name = "2x2"; + return topology; + case SliceShape::SLICE_2X4: + topology.shape = shape; + topology.dim_x = 2u; + topology.dim_y = 4u; + topology.chiplets_per_chip = 1u; + topology.name = "2x4"; + return topology; + case SliceShape::TPU7X_DUAL_CHIPLET: + topology.shape = shape; + topology.dim_x = 1u; + topology.dim_y = 1u; + topology.chiplets_per_chip = 2u; + topology.name = "tpu7x-dual-chiplet"; + return topology; + } + return topology; +} + +uint64_t fnv1a64(const void* data, size_t size) { + uint64_t hash = 14695981039346656037ull; + const auto* bytes = static_cast(data); + for (size_t i = 0u; i < size; ++i) { + hash ^= bytes[i]; + hash *= 1099511628211ull; + } + return hash; +} + +uint64_t request_prefix_hash(const ServingRequest& request) { + if (request.prefix != nullptr && request.prefix_len > 0u) { + return fnv1a64(request.prefix, request.prefix_len); + } + uint8_t bytes[8]; + uint64_t id = request.request_id; + for (int lane = 0; lane < 8; ++lane) { + bytes[lane] = static_cast(id & 0xffu); + id >>= 8; + } + return fnv1a64(bytes, 8u); +} + +uint32_t length_bucket(uint32_t tokens) { + static const uint32_t kBounds[] = {128u, 512u, 2048u, 8192u}; + for (uint32_t bucket = 0u; bucket < 4u; ++bucket) { + if (tokens <= kBounds[bucket]) { + return bucket; + } + } + return 4u; +} + +bool place_prefix(const SliceTopology& topology, uint64_t prefix_hash, ChipPlacement* out) { + if (out == nullptr) { + return false; + } + const uint32_t devices = slice_device_count(topology); + if (devices == 0u || topology.dim_x == 0u || topology.chiplets_per_chip == 0u) { + return false; + } + const uint32_t device = static_cast(prefix_hash % devices); + const uint32_t package = device / topology.chiplets_per_chip; + out->device = device; + out->package = package; + out->chiplet = device % topology.chiplets_per_chip; + out->chip_x = package % topology.dim_x; + out->chip_y = package / topology.dim_x; + return true; +} + +bool d2d_buddy(const SliceTopology& topology, const ChipPlacement& place, ChipPlacement* buddy) { + if (buddy == nullptr || topology.chiplets_per_chip != 2u) { + return false; + } + const uint32_t devices = slice_device_count(topology); + if (place.device >= devices || place.chiplet > 1u) { + return false; + } + *buddy = place; + buddy->chiplet = place.chiplet ^ 1u; + buddy->device = place.package * topology.chiplets_per_chip + buddy->chiplet; + return true; +} + +bool schedule_serving_step(const SliceTopology& topology, + const ServingRequest* requests, + size_t request_count, + const ScheduleLimits& limits, + ScheduleStep* out) { + if (out == nullptr) { + return false; + } + *out = ScheduleStep{}; + if (slice_device_count(topology) == 0u) { + out->error = "slice topology has no devices"; + return false; + } + if (request_count > kMaxScheduleRequests) { + out->error = "too many requests in one step"; + return false; + } + if (request_count > 0u && requests == nullptr) { + out->error = "request list is required"; + return false; + } + + struct Order { + int phase_rank = 0; + uint32_t bucket = 0; + uint32_t length = 0; + uint64_t request_id = 0; + size_t index = 0; + RequestPhase phase = RequestPhase::PREFILL; + }; + std::vector order; + order.reserve(request_count); + for (size_t index = 0u; index < request_count; ++index) { + RequestPhase phase = RequestPhase::PREFILL; + if (!resolve_phase(requests[index], &phase, &out->error)) { + *out = ScheduleStep{}; + resolve_phase(requests[index], &phase, &out->error); + return false; + } + Order item; + item.phase = phase; + item.phase_rank = (phase == RequestPhase::DECODE) ? 0 : 1; + item.length = context_length(requests[index], phase); + item.bucket = length_bucket(item.length); + item.request_id = requests[index].request_id; + item.index = index; + order.push_back(item); + } + std::sort(order.begin(), order.end(), [](const Order& lhs, const Order& rhs) { + if (lhs.phase_rank != rhs.phase_rank) { + return lhs.phase_rank < rhs.phase_rank; + } + if (lhs.bucket != rhs.bucket) { + return lhs.bucket < rhs.bucket; + } + if (lhs.length != rhs.length) { + return lhs.length < rhs.length; + } + if (lhs.request_id != rhs.request_id) { + return lhs.request_id < rhs.request_id; + } + return lhs.index < rhs.index; + }); + + uint64_t decode_left = limits.max_decode_tokens; + uint64_t prefill_left = limits.max_prefill_tokens; + uint64_t verify_left = limits.verify_step_budget; + uint64_t decode_tokens = 0u; + uint64_t prefill_tokens = 0u; + uint64_t verify_tokens = 0u; + out->items.reserve(request_count); + for (const Order& item : order) { + const ServingRequest& request = requests[item.index]; + ChipPlacement place; + if (!place_prefix(topology, request_prefix_hash(request), &place)) { + out->error = "failed to place request"; + out->items.clear(); + return false; + } + ScheduledItem scheduled; + scheduled.request_id = request.request_id; + scheduled.phase = item.phase; + scheduled.length_bucket = item.bucket; + scheduled.place = place; + if (item.phase == RequestPhase::DECODE) { + const uint64_t wanted = request.draft_tokens; + const uint64_t gamma = limits.verify_gamma; + uint64_t verified = wanted; + if (verified > gamma) { + verified = gamma; + } + if (verified > verify_left) { + verified = verify_left; + } + const uint64_t charge = 1ull + verified; + if (charge > decode_left) { + continue; + } + const uint32_t verified_u32 = static_cast(verified); + uint32_t accepted = request.draft_accepted; + if (accepted > verified_u32) { + accepted = verified_u32; + } + scheduled.verify.verified = verified_u32; + scheduled.verify.accepted = accepted; + scheduled.verify.rejected = verified_u32 - accepted; + scheduled.verify.pending = request.draft_tokens - verified_u32; + scheduled.scheduled_tokens = static_cast(charge); + decode_left -= charge; + verify_left -= verified; + decode_tokens += charge; + verify_tokens += verified; + } else { + const uint64_t charge = request.prompt_tokens; + if (charge > prefill_left) { + continue; + } + scheduled.scheduled_tokens = request.prompt_tokens; + prefill_left -= charge; + prefill_tokens += charge; + } + out->items.push_back(scheduled); + } + if (decode_tokens > 0xffffffffu || prefill_tokens > 0xffffffffu || verify_tokens > 0xffffffffu) { + out->error = "scheduled token count overflows"; + out->items.clear(); + return false; + } + out->decode_tokens = static_cast(decode_tokens); + out->prefill_tokens = static_cast(prefill_tokens); + out->verify_tokens = static_cast(verify_tokens); + out->ok = true; + out->error = ""; + return true; +} + +} // namespace freetile diff --git a/freetile/tests/test_serving_planner.cpp b/freetile/tests/test_serving_planner.cpp new file mode 100644 index 00000000..b66d2e22 --- /dev/null +++ b/freetile/tests/test_serving_planner.cpp @@ -0,0 +1,696 @@ +#include "freetile/serving_planner.hpp" +#include "freetile/tile_ir.hpp" + +#include +#include +#include +#include + +#define CHECK_TRUE(cond, msg) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL [%s:%d]: %s\n", __FILE__, __LINE__, (msg)); \ + return 1; \ + } \ + } while (0) + +namespace { + +uint32_t fbits(float value) { + uint32_t bits = 0u; + std::memcpy(&bits, &value, sizeof(bits)); + return bits; +} + +float ffrom(uint32_t bits) { + float value = 0.0f; + std::memcpy(&value, &bits, sizeof(value)); + return value; +} + +bool close_rel(double got, double expect) { + const double diff = got - expect; + const double denom = expect < 0.0 ? -expect : expect; + const double limit = denom * 1.0e-12; + return diff <= limit && diff >= -limit; +} + +uint32_t page_index(const freetile::PagedKvPlan& plan, uint32_t seq, uint32_t token) { + const uint32_t slot = token / plan.page_size; + const uint32_t page = plan.block_table[static_cast(seq) * plan.block_stride + slot]; + const uint32_t offset = token % plan.page_size; + return (page * plan.page_size + offset) * plan.kv_dim; +} + +void naive_moe(const freetile::MoeRoutePlan& plan, const std::vector& in, std::vector* out) { + const uint32_t hidden = plan.hidden_dim; + out->assign(static_cast(plan.num_tokens) * hidden, 0.0f); + for (uint32_t token = 0u; token < plan.num_tokens; ++token) { + for (uint32_t rank = 0u; rank < plan.top_k; ++rank) { + const int32_t expert = plan.assignment[static_cast(token) * plan.top_k + rank]; + if (expert < 0) { + continue; + } + const float weight = static_cast(expert + 1); + for (uint32_t lane = 0u; lane < hidden; ++lane) { + (*out)[static_cast(token) * hidden + lane] += + in[static_cast(token) * hidden + lane] * weight; + } + } + } +} + +freetile::ServingRequest req(uint64_t id, + const char* prefix, + uint32_t prompt, + uint32_t generated, + uint32_t drafts, + uint32_t accepted) { + freetile::ServingRequest request; + request.request_id = id; + request.prefix = prefix; + request.prefix_len = prefix == nullptr ? 0u : std::strlen(prefix); + request.prompt_tokens = prompt; + request.generated_tokens = generated; + request.draft_tokens = drafts; + request.draft_accepted = accepted; + return request; +} + +} // namespace + +int main() { + using freetile::ChipTarget; + using freetile::CodebookFormat; + using freetile::CodebookLowering; + using freetile::CodebookPath; + using freetile::DispatchMode; + using freetile::OffloadUnit; + using freetile::ServingOpKind; + using freetile::TpuGeneration; + + const freetile::GenerationProfile v5e = freetile::generation_profile(TpuGeneration::V5E); + const freetile::GenerationProfile v5p = freetile::generation_profile(TpuGeneration::V5P); + const freetile::GenerationProfile v6e = freetile::generation_profile(TpuGeneration::V6E); + const freetile::GenerationProfile t7x = freetile::generation_profile(TpuGeneration::TPU7X); + const freetile::GenerationProfile gens[] = {v5e, v5p, v6e, t7x}; + + // Published peaks, SparseCore gating, and FreeTile VMEM budgets. + { + CHECK_TRUE(v5e.valid && std::strcmp(v5e.name, "v5e") == 0, "v5e name"); + CHECK_TRUE(!v5e.has_sparsecore && v5e.sparsecores_per_chip == 0, "v5e has no SparseCore"); + CHECK_TRUE(v5e.mxu_m == 128 && v5e.mxu_n == 128 && freetile::mxus_per_chip(v5e) == 4, "v5e MXU"); + CHECK_TRUE(v5e.tensorcores_per_chip == 1 && v5e.bf16_tflops == 197 && v5e.int8_tops == 393, "v5e peaks"); + CHECK_TRUE(v5e.int8_peak_published && !v5e.supports_fp8 && v5e.fp8_tflops == 0, "v5e quant"); + CHECK_TRUE(v5e.hbm_bytes_per_chip == (16ull << 30) && v5e.hbm_bw_gbps == 819, "v5e HBM"); + CHECK_TRUE(v5e.ici_bw_gbps == 400 && v5e.ici_ports == 4, "v5e ICI"); + CHECK_TRUE(v5e.ici_topology == freetile::IciTopology::TORUS_2D, "v5e torus"); + CHECK_TRUE(v5e.vmem_bytes_per_chip == freetile::target_profile(ChipTarget::V5E).vmem_bytes, "v5e VMEM"); + CHECK_TRUE(v5e.supports_native_s4 == freetile::target_profile(ChipTarget::V5E).supports_s4_native, "v5e s4"); + CHECK_TRUE(!v5e.supports_fp4 && !v5e.supports_mxfp4 && !v5e.supports_native_fp4, "v5e no fp4"); + + CHECK_TRUE(v5p.has_sparsecore && v5p.sparsecores_per_chip == 4 && v5p.tensorcores_per_chip == 2, "v5p cores"); + CHECK_TRUE(v5p.mxu_m == 128 && freetile::mxus_per_chip(v5p) == 8 && v5p.bf16_tflops == 459, "v5p MXU"); + CHECK_TRUE(v5p.fp8_tflops == 459 && v5p.supports_fp8 && !v5p.supports_native_fp8, "v5p fp8 equals bf16"); + CHECK_TRUE(v5p.hbm_bytes_per_chip == (95ull << 30) && v5p.hbm_bw_gbps == 2765, "v5p HBM"); + CHECK_TRUE(v5p.ici_bw_gbps == 1200 && v5p.ici_topology == freetile::IciTopology::TORUS_3D, "v5p ICI"); + CHECK_TRUE(!v5p.int8_peak_published && v5p.int8_tops == 2 * v5p.bf16_tflops, "v5p modeled int8"); + CHECK_TRUE(v5p.vmem_bytes_per_tensorcore == (16ull << 20) && v5p.vmem_bytes_per_chip == (32ull << 20), "v5p VMEM"); + + CHECK_TRUE(std::strcmp(v6e.architecture, "Trillium") == 0, "v6e architecture"); + CHECK_TRUE(v6e.has_sparsecore && v6e.sparsecores_per_chip == 2, "v6e SparseCore"); + CHECK_TRUE(v6e.mxu_m == 256 && v6e.mxu_n == 256 && freetile::mxus_per_chip(v6e) == 2, "v6e MXU"); + CHECK_TRUE(v6e.bf16_tflops == 918 && v6e.int8_tops == 1836 && v6e.int8_peak_published, "v6e peaks"); + CHECK_TRUE(v6e.fp8_tflops == 918 && v6e.supports_fp8 && !v6e.supports_native_fp8, "v6e fp8"); + CHECK_TRUE(v6e.hbm_bytes_per_chip == (32ull << 30) && v6e.hbm_bw_gbps == 1638, "v6e HBM"); + CHECK_TRUE(v6e.ici_bw_gbps == 800 && v6e.ici_ports == 4, "v6e ICI"); + CHECK_TRUE(v6e.vmem_bytes_per_chip == freetile::target_profile(ChipTarget::V6E).vmem_bytes, "v6e VMEM"); + CHECK_TRUE(v6e.bf16_tflops * 8 == 7344, "v6e-8 aggregate BF16"); + + CHECK_TRUE(std::strcmp(t7x.architecture, "Ironwood") == 0 && t7x.chiplets_per_chip == 2, "tpu7x chiplet"); + CHECK_TRUE(t7x.has_sparsecore && t7x.sparsecores_per_chip == 4 && t7x.tensorcores_per_chip == 2, "tpu7x cores"); + CHECK_TRUE(t7x.mxu_m == 256 && freetile::mxus_per_chip(t7x) == 4, "tpu7x MXU"); + CHECK_TRUE(t7x.bf16_tflops == 2307 && t7x.fp8_tflops == 4614 && t7x.supports_native_fp8, "tpu7x fp8"); + CHECK_TRUE(t7x.hbm_bytes_per_chiplet == (96ull << 30) && t7x.hbm_bytes_per_chip == (192ull << 30), "tpu7x HBM"); + CHECK_TRUE(t7x.hbm_bw_gbps == 7380 && t7x.ici_bw_gbps == 1200 && t7x.d2d_link_multiplier == 6, "tpu7x links"); + CHECK_TRUE(t7x.vmem_bytes_per_chiplet == freetile::target_profile(ChipTarget::TPU7X).vmem_bytes, "tpu7x VMEM"); + CHECK_TRUE(t7x.vmem_bytes_per_chip == 2u * t7x.vmem_bytes_per_chiplet, "tpu7x chip VMEM"); + CHECK_TRUE(!t7x.supports_native_s4 && !t7x.supports_fp4 && !t7x.supports_mxfp4, "tpu7x no native fp4"); + CHECK_TRUE(!t7x.int8_peak_published && t7x.int8_tops == t7x.fp8_tflops, "tpu7x modeled int8"); + + for (const freetile::GenerationProfile& profile : gens) { + CHECK_TRUE(profile.supports_bf16 && profile.supports_int8, "every generation has int8 and bf16"); + CHECK_TRUE(profile.hbm_bytes_per_chip == profile.hbm_bytes_per_chiplet * static_cast(profile.chiplets_per_chip), + "HBM chiplet rollup"); + CHECK_TRUE(profile.has_sparsecore == (profile.sparsecores_per_chip > 0), "SparseCore flag"); + CHECK_TRUE(profile.supports_fp8 == (profile.fp8_tflops > 0), "fp8 flag"); + CHECK_TRUE(profile.supports_native_fp8 == (profile.fp8_tflops > profile.bf16_tflops), "native fp8 flag"); + const freetile::RooflineKnees knees = freetile::roofline_knees(profile); + const double bf16 = static_cast(profile.bf16_tflops) * 1.0e12; + const double hbm = static_cast(profile.hbm_bw_gbps) * 1.0e9; + const double lattice = static_cast(freetile::mxus_per_chip(profile)) * 2.0 * + static_cast(profile.mxu_m) * static_cast(profile.mxu_n); + CHECK_TRUE(close_rel(knees.mxu_hbm_knee_flops_per_byte, bf16 / hbm), "MXU knee"); + CHECK_TRUE(close_rel(knees.clock_hz, bf16 / lattice), "derived clock"); + CHECK_TRUE(knees.vpu_hbm_knee_flops_per_byte < knees.mxu_hbm_knee_flops_per_byte, "VPU knee below MXU"); + } + const freetile::RooflineKnees v6e_knees = freetile::roofline_knees(v6e); + CHECK_TRUE(v6e_knees.mxu_hbm_knee_flops_per_byte > 560.0 && + v6e_knees.mxu_hbm_knee_flops_per_byte < 561.0, + "v6e BF16 ridge near 560 FLOPs/byte"); + + TpuGeneration parsed = TpuGeneration::V5E; + CHECK_TRUE(freetile::parse_generation("TPU v6e Trillium", &parsed) && parsed == TpuGeneration::V6E, "parse v6e"); + CHECK_TRUE(freetile::parse_generation("Ironwood tpu7x-4t", &parsed) && parsed == TpuGeneration::TPU7X, "parse tpu7x"); + CHECK_TRUE(freetile::parse_generation("ct5p-hightpu-4t", &parsed) && parsed == TpuGeneration::V5P, "parse v5p"); + CHECK_TRUE(freetile::parse_generation("ct5lp-hightpu-1t", &parsed) && parsed == TpuGeneration::V5E, "parse v5e"); + CHECK_TRUE(!freetile::parse_generation("v5", &parsed), "bare v5 is ambiguous"); + CHECK_TRUE(!freetile::generation_supports_quant(v5e, freetile::NativeQuant::FP8), "v5e fp8 unsupported"); + CHECK_TRUE(freetile::generation_supports_quant(t7x, freetile::NativeQuant::FP8), "tpu7x fp8 supported"); + CHECK_TRUE(!freetile::generation_supports_quant(t7x, freetile::NativeQuant::MXFP4), "mxfp4 unsupported"); + } + + // Roofline knees decide MXU vs VPU vs SparseCore. + { + const freetile::IntensitySample wide = freetile::matmul_intensity(4096, 4096, 4096, 2u); + const freetile::IntensitySample narrow = freetile::matmul_intensity(1024, 1024, 1024, 2u); + const freetile::OffloadDecision wide_v6 = + freetile::decide_offload(v6e, ServingOpKind::DENSE_MATMUL, wide, DispatchMode::AUTO); + const freetile::OffloadDecision narrow_v6 = + freetile::decide_offload(v6e, ServingOpKind::DENSE_MATMUL, narrow, DispatchMode::AUTO); + const freetile::OffloadDecision narrow_v5 = + freetile::decide_offload(v5e, ServingOpKind::DENSE_MATMUL, narrow, DispatchMode::AUTO); + CHECK_TRUE(wide_v6.ok && wide_v6.unit == OffloadUnit::MXU && wide_v6.compute_bound, "wide matmul is MXU compute-bound"); + CHECK_TRUE(narrow_v6.ok && narrow_v6.unit == OffloadUnit::MXU && narrow_v6.hbm_bound && !narrow_v6.compute_bound, + "1024 matmul is HBM-bound on v6e"); + CHECK_TRUE(narrow_v5.ok && narrow_v5.unit == OffloadUnit::MXU && narrow_v5.compute_bound, + "1024 matmul is compute-bound on v5e"); + const freetile::OffloadDecision forced_matmul = + freetile::decide_offload(v6e, ServingOpKind::DENSE_MATMUL, wide, DispatchMode::FORCE_SPARSECORE); + CHECK_TRUE(!forced_matmul.ok, "dense matmul rejects forced SparseCore"); + + for (const freetile::GenerationProfile& profile : gens) { + freetile::IntensitySample resident; + resident.flops = 0.0; + resident.hbm_bytes = static_cast(profile.vmem_bytes_per_chip); + resident.working_set_bytes = resident.hbm_bytes; + const freetile::OffloadDecision fit = freetile::decide_offload( + profile, ServingOpKind::PAGED_KV_GATHER, resident, DispatchMode::AUTO); + CHECK_TRUE(fit.ok && fit.unit == OffloadUnit::VPU && fit.vmem_resident, "VMEM-resident gather stays on the VPU"); + + freetile::IntensitySample spilled = resident; + spilled.working_set_bytes += 1.0; + spilled.hbm_bytes += 1.0; + const freetile::OffloadDecision spill = freetile::decide_offload( + profile, ServingOpKind::PAGED_KV_GATHER, spilled, DispatchMode::AUTO); + if (profile.has_sparsecore) { + CHECK_TRUE(spill.ok && spill.unit == OffloadUnit::SPARSECORE && spill.hbm_bound, "large gather uses SparseCore"); + } else { + CHECK_TRUE(spill.ok && spill.unit == OffloadUnit::VPU && !spill.vmem_resident && spill.hbm_bound, + "v5e large gather falls back to the VPU"); + } + const freetile::OffloadDecision forced = freetile::decide_offload( + profile, ServingOpKind::MOE_SCATTER_GATHER, spilled, DispatchMode::FORCE_SPARSECORE); + if (profile.has_sparsecore) { + CHECK_TRUE(forced.ok && forced.unit == OffloadUnit::SPARSECORE, "forced SparseCore on a capable chip"); + } else { + CHECK_TRUE(!forced.ok, "forced SparseCore fails closed"); + CHECK_TRUE(std::strcmp(forced.error, "v5e has no SparseCore; refusing forced SparseCore dispatch") == 0, + "v5e forced SparseCore error"); + } + } + + const freetile::RooflineKnees knees = freetile::roofline_knees(v6e); + freetile::IntensitySample heavy; + heavy.working_set_bytes = static_cast(v6e.vmem_bytes_per_chip) * 2.0; + heavy.hbm_bytes = heavy.working_set_bytes; + heavy.flops = heavy.hbm_bytes * (knees.vpu_hbm_knee_flops_per_byte * 2.0); + const freetile::OffloadDecision compute_gather = + freetile::decide_offload(v6e, ServingOpKind::PAGED_KV_GATHER, heavy, DispatchMode::AUTO); + CHECK_TRUE(compute_gather.ok && compute_gather.unit == OffloadUnit::VPU && compute_gather.compute_bound, + "gather above the VPU knee stays on the VPU"); + + freetile::IntensitySample bad; + bad.flops = -1.0; + CHECK_TRUE(!freetile::decide_offload(v6e, ServingOpKind::DENSE_MATMUL, bad, DispatchMode::AUTO).ok, + "negative intensity is rejected"); + } + + // Ragged paged-KV gather matches the dense token stream on every generation. + { + const uint32_t page_size = 4u; + const uint32_t kv_dim = 2u; + const uint32_t lens[] = {3u, 5u, 1u}; + std::vector source; + for (uint32_t seq = 0u; seq < 3u; ++seq) { + for (uint32_t token = 0u; token < lens[seq]; ++token) { + source.push_back(static_cast((seq + 1u) * 1000u + token * 10u)); + source.push_back(static_cast((seq + 1u) * 1000u + token * 10u + 1u)); + } + } + CHECK_TRUE(source.size() == 18u, "3+5+1 tokens, two lanes"); + + for (const freetile::GenerationProfile& profile : gens) { + freetile::PagedKvRequest request; + request.generation = profile.generation; + request.dispatch = DispatchMode::AUTO; + request.page_size = page_size; + request.kv_dim = kv_dim; + request.num_sequences = 3u; + request.seq_lens = lens; + freetile::PagedKvPlan plan; + CHECK_TRUE(freetile::plan_paged_kv(request, &plan), "paged plan"); + CHECK_TRUE(plan.ok && plan.num_pages == 4u && plan.block_stride == 2u && plan.total_tokens == 9u, "page geometry"); + CHECK_TRUE(plan.block_table[0] == 0u && plan.block_table[1] == 0xffffffffu, "seq0 pages"); + CHECK_TRUE(plan.block_table[2] == 1u && plan.block_table[3] == 2u, "seq1 pages"); + CHECK_TRUE(plan.block_table[4] == 3u && plan.block_table[5] == 0xffffffffu, "seq2 pages"); + CHECK_TRUE(plan.unit == OffloadUnit::VPU && plan.vmem_resident, "tiny cache stays in VMEM"); + + std::vector pages(static_cast(plan.num_pages) * page_size * kv_dim, 7.0f); + const char* err = ""; + CHECK_TRUE(freetile::paged_kv_pack(plan, source.data(), pages.data(), &err), "pack"); + CHECK_TRUE(pages[page_index(plan, 0u, 0u)] == source[0] && pages[page_index(plan, 1u, 0u)] == source[6], + "pack places seq0 and seq1 on distinct pages"); + CHECK_TRUE(pages[(0u * page_size + 3u) * kv_dim] == 0.0f && pages[(0u * page_size + 3u) * kv_dim + 1u] == 0.0f, + "partial page tail is zero"); + std::vector gathered(source.size(), 0.0f); + CHECK_TRUE(freetile::paged_kv_gather(plan, pages.data(), gathered.data(), &err), "gather"); + CHECK_TRUE(std::memcmp(gathered.data(), source.data(), source.size() * sizeof(float)) == 0, "ragged gather parity"); + + gathered[0] = 42.0f; + gathered[1] = -3.0f; + CHECK_TRUE(freetile::paged_kv_scatter(plan, gathered.data(), pages.data(), &err), "scatter"); + CHECK_TRUE(pages[page_index(plan, 0u, 0u)] == 42.0f && pages[page_index(plan, 0u, 0u) + 1u] == -3.0f, + "scatter writes the dense update"); + std::vector roundtrip(source.size(), 0.0f); + CHECK_TRUE(freetile::paged_kv_gather(plan, pages.data(), roundtrip.data(), &err), "gather after scatter"); + CHECK_TRUE(std::memcmp(roundtrip.data(), gathered.data(), gathered.size() * sizeof(float)) == 0, + "scatter/gather round trip"); + } + + const uint32_t one_len[] = {65552u}; + freetile::PagedKvRequest large; + large.generation = TpuGeneration::V6E; + large.page_size = 16u; + large.kv_dim = 128u; + large.num_sequences = 1u; + large.seq_lens = one_len; + large.dispatch = DispatchMode::AUTO; + freetile::PagedKvPlan large_plan; + CHECK_TRUE(freetile::plan_paged_kv(large, &large_plan), "large v6e plan"); + CHECK_TRUE(large_plan.unit == OffloadUnit::SPARSECORE && large_plan.num_pages == 4097u, "large v6e gather uses SparseCore"); + large.generation = TpuGeneration::V5E; + CHECK_TRUE(freetile::plan_paged_kv(large, &large_plan) && large_plan.unit == OffloadUnit::VPU, + "large v5e gather stays on the VPU"); + large.dispatch = DispatchMode::FORCE_SPARSECORE; + CHECK_TRUE(!freetile::plan_paged_kv(large, &large_plan), "v5e paged plan rejects forced SparseCore"); + CHECK_TRUE(std::strcmp(large_plan.error, "v5e has no SparseCore; refusing forced SparseCore dispatch") == 0, + "paged v5e error text"); + + freetile::PagedKvRequest forced; + forced.generation = TpuGeneration::TPU7X; + forced.dispatch = DispatchMode::FORCE_SPARSECORE; + forced.page_size = page_size; + forced.kv_dim = kv_dim; + forced.num_sequences = 3u; + forced.seq_lens = lens; + freetile::PagedKvPlan forced_plan; + CHECK_TRUE(freetile::plan_paged_kv(forced, &forced_plan) && forced_plan.unit == OffloadUnit::SPARSECORE, + "tpu7x can force SparseCore"); + std::vector pages(static_cast(forced_plan.num_pages) * page_size * kv_dim, 0.0f); + std::vector gathered(source.size(), 0.0f); + const char* err = ""; + CHECK_TRUE(freetile::paged_kv_pack(forced_plan, source.data(), pages.data(), &err), "forced pack"); + CHECK_TRUE(freetile::paged_kv_gather(forced_plan, pages.data(), gathered.data(), &err), "forced gather"); + CHECK_TRUE(std::memcmp(gathered.data(), source.data(), source.size() * sizeof(float)) == 0, + "forced SparseCore gather stays bit-exact"); + } + + // MoE scatter/gather parity, capacity drops, and the v5e fallback. + { + const uint32_t tokens = 4u; + const uint32_t experts = 4u; + const uint32_t top_k = 2u; + const float scores[] = { + 0.9f, 0.8f, 0.1f, 0.0f, + 0.7f, 0.6f, 0.2f, 0.1f, + 0.1f, 0.0f, 0.9f, 0.8f, + 0.2f, 0.1f, 0.7f, 0.6f, + }; + freetile::MoeRouteRequest request; + request.generation = TpuGeneration::V5P; + request.num_tokens = tokens; + request.num_experts = experts; + request.top_k = top_k; + request.capacity_factor = 1.0; + request.hidden_dim = 2u; + request.scores = scores; + freetile::MoeRoutePlan plan; + CHECK_TRUE(freetile::plan_moe_route(request, &plan), "moe plan"); + CHECK_TRUE(plan.capacity == 2u && plan.dropped == 0u, "capacity 2 accepts every assignment"); + const int32_t expect_assign[] = {0, 1, 0, 1, 2, 3, 2, 3}; + CHECK_TRUE(plan.assignment.size() == 8u, "assignment width"); + for (size_t i = 0u; i < 8u; ++i) { + CHECK_TRUE(plan.assignment[i] == expect_assign[i], "full-capacity assignment"); + } + CHECK_TRUE(plan.expert_counts[0] == 2u && plan.expert_counts[1] == 2u, "deduped expert counts"); + + request.capacity_factor = 0.5; + CHECK_TRUE(freetile::plan_moe_route(request, &plan), "tight moe plan"); + CHECK_TRUE(plan.capacity == 1u && plan.dropped == 4u, "half capacity drops four assignments"); + CHECK_TRUE(plan.assignment[0] == 0 && plan.assignment[1] == 1, "token 0 kept"); + CHECK_TRUE(plan.assignment[2] == -1 && plan.assignment[3] == -1, "token 1 dropped"); + CHECK_TRUE(plan.assignment[4] == 2 && plan.assignment[5] == 3, "token 2 kept"); + CHECK_TRUE(plan.assignment[6] == -1 && plan.assignment[7] == -1, "token 3 dropped"); + + std::vector hidden = {0.1f, 0.25f, 0.5f, -0.5f, 1.0f, 2.0f, 3.0f, -4.0f}; + std::vector got; + std::vector naive; + const char* err = ""; + for (TpuGeneration generation : {TpuGeneration::V5E, TpuGeneration::V5P, TpuGeneration::V6E, TpuGeneration::TPU7X}) { + request.generation = generation; + request.capacity_factor = 0.5; + request.dispatch = DispatchMode::AUTO; + request.hidden_dim = 2u; + CHECK_TRUE(freetile::plan_moe_route(request, &plan), "auto moe"); + if (generation == TpuGeneration::V5E) { + CHECK_TRUE(plan.unit == OffloadUnit::VPU, "v5e MoE falls back to the VPU"); + } else { + CHECK_TRUE(plan.unit == OffloadUnit::VPU && plan.vmem_resident, "tiny MoE batch stays in VMEM"); + } + got.assign(hidden.size(), 0.0f); + CHECK_TRUE(freetile::moe_apply_reference(plan, hidden.data(), got.data(), &err), "moe apply"); + naive_moe(plan, hidden, &naive); + CHECK_TRUE(std::memcmp(got.data(), naive.data(), got.size() * sizeof(float)) == 0, "moe scatter/gather parity"); + if (generation != TpuGeneration::V5E) { + request.dispatch = DispatchMode::FORCE_SPARSECORE; + CHECK_TRUE(freetile::plan_moe_route(request, &plan) && plan.unit == OffloadUnit::SPARSECORE, "forced moe"); + CHECK_TRUE(freetile::moe_apply_reference(plan, hidden.data(), got.data(), &err), "forced apply"); + naive_moe(plan, hidden, &naive); + CHECK_TRUE(std::memcmp(got.data(), naive.data(), got.size() * sizeof(float)) == 0, "forced moe parity"); + } + } + request.generation = TpuGeneration::V5E; + request.dispatch = DispatchMode::FORCE_SPARSECORE; + CHECK_TRUE(!freetile::plan_moe_route(request, &plan), "v5e moe rejects forced SparseCore"); + CHECK_TRUE(std::strstr(plan.error, "v5e") != nullptr && std::strstr(plan.error, "SparseCore") != nullptr, + "v5e moe error names the chip and SparseCore"); + + const float ties[] = {1.0f, 1.0f, 0.0f, 0.0f}; + request.dispatch = DispatchMode::AUTO; + request.num_tokens = 1u; + request.top_k = 1u; + request.capacity_factor = 1.0; + request.scores = ties; + request.hidden_dim = 2u; + CHECK_TRUE(freetile::plan_moe_route(request, &plan) && plan.assignment[0] == 0, "tie breaks to the lower expert"); + request.top_k = 2u; + CHECK_TRUE(freetile::plan_moe_route(request, &plan) && plan.assignment[0] == 0 && plan.assignment[1] == 1, + "second tie takes the next expert"); + + request.num_tokens = tokens; + request.top_k = top_k; + request.scores = scores; + request.capacity_factor = 0.0; + CHECK_TRUE(freetile::plan_moe_route(request, &plan) && plan.capacity == 0u && plan.dropped == tokens * top_k, + "zero capacity drops every assignment"); + got.assign(hidden.size(), 1.0f); + CHECK_TRUE(freetile::moe_apply_reference(plan, hidden.data(), got.data(), &err), "zero-capacity apply"); + for (float value : got) { + CHECK_TRUE(value == 0.0f, "dropped tokens contribute nothing"); + } + + const float nan_scores[] = {ffrom(0x7fc00000u), 0.0f, 0.0f, 0.0f}; + request.num_tokens = 1u; + request.top_k = 1u; + request.capacity_factor = 1.0; + request.scores = nan_scores; + CHECK_TRUE(!freetile::plan_moe_route(request, &plan), "non-finite scores fail"); + + std::vector wide_scores(64u * 2u, 0.0f); + for (uint32_t token = 0u; token < 64u; ++token) { + wide_scores[token * 2u + (token & 1u)] = 1.0f; + } + request.generation = TpuGeneration::V6E; + request.num_tokens = 64u; + request.num_experts = 2u; + request.top_k = 1u; + request.capacity_factor = 1.0; + request.hidden_dim = 131073u; + request.scores = wide_scores.data(); + request.dispatch = DispatchMode::AUTO; + CHECK_TRUE(freetile::plan_moe_route(request, &plan) && plan.unit == OffloadUnit::SPARSECORE, + "large v6e MoE routing uses SparseCore"); + request.generation = TpuGeneration::V5E; + CHECK_TRUE(freetile::plan_moe_route(request, &plan) && plan.unit == OffloadUnit::VPU, + "large v5e MoE routing stays on the VPU"); + request.dispatch = DispatchMode::FORCE_SPARSECORE; + CHECK_TRUE(!freetile::plan_moe_route(request, &plan), "large v5e MoE still refuses SparseCore"); + } + + // Codebook dequant is 0 ULP across LUT, select-tree, and native FP4. + { + const int8_t iq4[] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; + const uint32_t nf4_bits[] = { + 0xbf800000u, 0xbf3239b1u, 0xbf066b30u, 0xbeca32a0u, + 0xbe91a24du, 0xbe3d353fu, 0xbdba7871u, 0x00000000u, + 0x3da2faffu, 0x3e24cae3u, 0x3e7c04ddu, 0x3ead033au, + 0x3ee1a4b8u, 0x3f1007abu, 0x3f3913b3u, 0x3f800000u + }; + const float fp4_mag[] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + const freetile::CodebookDescriptor iq = freetile::codebook_descriptor(CodebookFormat::IQ4_XS); + const freetile::CodebookDescriptor nf = freetile::codebook_descriptor(CodebookFormat::NF4); + const freetile::CodebookDescriptor bof = freetile::codebook_descriptor(CodebookFormat::BOF4); + const freetile::CodebookDescriptor fp4 = freetile::codebook_descriptor(CodebookFormat::FP4_MXFP4); + CHECK_TRUE(iq.group_size == 32u && nf.group_size == 64u && bof.group_size == 32u && fp4.group_size == 32u, + "codebook group sizes"); + for (uint32_t i = 0u; i < 16u; ++i) { + CHECK_TRUE(iq.centers[i] == static_cast(iq4[i]), "iq4_xs center"); + CHECK_TRUE(fbits(nf.centers[i]) == nf4_bits[i], "nf4 center bits"); + CHECK_TRUE(bof.centers[i] == static_cast(static_cast(i) - 8), "bof4 center"); + const uint32_t expect = fbits(fp4_mag[i & 7u]) | ((i & 8u) != 0u ? 0x80000000u : 0u); + CHECK_TRUE(fbits(fp4.centers[i]) == expect, "fp4 e2m1 center"); + CHECK_TRUE(freetile::codebook_select_tree_index(static_cast(i)) == i, "select tree index"); + } + CHECK_TRUE(fbits(fp4.centers[8]) == 0x80000000u, "fp4 keeps signed zero"); + + const CodebookFormat formats[] = { + CodebookFormat::IQ4_XS, CodebookFormat::NF4, CodebookFormat::BOF4, CodebookFormat::FP4_MXFP4 + }; + float e8 = 0.0f; + const char* err = ""; + CHECK_TRUE(freetile::mxfp4_e8m0_scale(127u, &e8, &err) && fbits(e8) == 0x3f800000u, "e8m0 bias 127"); + CHECK_TRUE(freetile::mxfp4_e8m0_scale(129u, &e8, &err) && e8 == 4.0f, "e8m0 2^2"); + CHECK_TRUE(freetile::mxfp4_e8m0_scale(0u, &e8, &err) && fbits(e8) == 0x00400000u, "e8m0 2^-127"); + CHECK_TRUE(!freetile::mxfp4_e8m0_scale(255u, &e8, &err), "e8m0 0xFF is NaN"); + + const float scales[] = {1.0f, -1.0f, 0.5f, 2.0f, e8}; + for (CodebookFormat format : formats) { + const freetile::CodebookDescriptor descriptor = freetile::codebook_descriptor(format); + std::vector packed((descriptor.group_size + 1u) / 2u, 0u); + for (uint32_t i = 0u; i < descriptor.group_size; ++i) { + const uint8_t nibble = static_cast(i & 15u); + if ((i & 1u) == 0u) { + packed[i >> 1] = nibble; + } else { + packed[i >> 1] = static_cast(packed[i >> 1] | static_cast(nibble << 4)); + } + } + for (float scale : scales) { + std::vector lut(descriptor.group_size, 0.0f); + std::vector tree(descriptor.group_size, 0.0f); + CHECK_TRUE(freetile::dequant_codebook(format, CodebookPath::LUT, packed.data(), descriptor.group_size, + scale, lut.data(), &err), + "lut dequant"); + CHECK_TRUE(freetile::dequant_codebook(format, CodebookPath::SELECT_TREE, packed.data(), + descriptor.group_size, scale, tree.data(), &err), + "select-tree dequant"); + CHECK_TRUE(std::memcmp(lut.data(), tree.data(), lut.size() * sizeof(float)) == 0, "0 ULP lut vs select tree"); + if (format == CodebookFormat::FP4_MXFP4) { + std::vector native(descriptor.group_size, 0.0f); + CHECK_TRUE(freetile::dequant_codebook(format, CodebookPath::NATIVE_FP4, packed.data(), + descriptor.group_size, scale, native.data(), &err), + "native fp4 dequant"); + CHECK_TRUE(std::memcmp(lut.data(), native.data(), lut.size() * sizeof(float)) == 0, + "0 ULP lut vs native fp4"); + } else { + CHECK_TRUE(!freetile::dequant_codebook(format, CodebookPath::NATIVE_FP4, packed.data(), + descriptor.group_size, scale, lut.data(), &err), + "native fp4 rejects integer codebooks"); + } + } + for (const freetile::GenerationProfile& profile : gens) { + const CodebookLowering lowering = freetile::codebook_lowering(profile, format); + if (profile.mxu_m >= 256) { + CHECK_TRUE(lowering == CodebookLowering::VPERM, "256-wide MXU uses VPERM"); + CHECK_TRUE(std::strcmp(freetile::codebook_lowering_name(lowering), "vperm") == 0, "vperm name"); + } else { + CHECK_TRUE(lowering == CodebookLowering::VREG_SELECT_TREE, "128-wide MXU uses a VREG select tree"); + } + } + } + freetile::GenerationProfile native_fp4 = t7x; + native_fp4.supports_native_fp4 = true; + native_fp4.supports_mxfp4 = true; + CHECK_TRUE(freetile::codebook_lowering(native_fp4, CodebookFormat::FP4_MXFP4) == CodebookLowering::NATIVE_FP4, + "native fp4 lowering when the profile allows it"); + CHECK_TRUE(freetile::codebook_lowering(native_fp4, CodebookFormat::IQ4_XS) == CodebookLowering::VPERM, + "integer codebooks stay on VPERM"); + CHECK_TRUE(freetile::codebook_lowering(v5e, CodebookFormat::NF4) == CodebookLowering::VREG_SELECT_TREE, + "v5e NF4 select tree"); + CHECK_TRUE(std::strcmp(freetile::codebook_lowering_name(CodebookLowering::VREG_SELECT_TREE), "vreg_select_tree") == 0, + "select tree name"); + CHECK_TRUE(std::strcmp(freetile::codebook_lowering_name(CodebookLowering::NATIVE_FP4), "native_fp4") == 0, + "native fp4 name"); + + const uint8_t mixed = 0xa5u; + float one = 0.0f; + CHECK_TRUE(freetile::dequant_codebook(CodebookFormat::BOF4, CodebookPath::LUT, &mixed, 1u, 1.0f, &one, &err), + "single nibble"); + CHECK_TRUE(one == static_cast(5 - 8), "low nibble is consumed first"); + } + + // Prefix affinity, length buckets, and speculative draft/target budgets. + { + CHECK_TRUE(freetile::fnv1a64("", 0u) == 0xcbf29ce484222325ull, "fnv empty"); + CHECK_TRUE(freetile::fnv1a64("a", 1u) == 0xaf63dc4c8601ec8cull, "fnv a"); + CHECK_TRUE(freetile::fnv1a64("hello", 5u) == 0xa430d84680aabd0bull, "fnv hello"); + CHECK_TRUE(freetile::length_bucket(128u) == 0u && freetile::length_bucket(129u) == 1u, "bucket edge 128"); + CHECK_TRUE(freetile::length_bucket(512u) == 1u && freetile::length_bucket(513u) == 2u, "bucket edge 512"); + CHECK_TRUE(freetile::length_bucket(8192u) == 3u && freetile::length_bucket(8193u) == 4u, "bucket edge 8192"); + + const freetile::SliceTopology one = freetile::slice_topology(freetile::SliceShape::SLICE_1X1); + const freetile::SliceTopology grid = freetile::slice_topology(freetile::SliceShape::SLICE_2X2); + const freetile::SliceTopology host = freetile::slice_topology(freetile::SliceShape::SLICE_2X4); + const freetile::SliceTopology dual = freetile::slice_topology(freetile::SliceShape::TPU7X_DUAL_CHIPLET); + CHECK_TRUE(freetile::slice_device_count(one) == 1u && std::strcmp(one.name, "1x1") == 0, "1x1"); + CHECK_TRUE(freetile::slice_device_count(grid) == 4u && grid.dim_x == 2u && grid.dim_y == 2u, "2x2"); + CHECK_TRUE(freetile::slice_device_count(host) == 8u && host.dim_x == 2u && host.dim_y == 4u, "2x4"); + CHECK_TRUE(freetile::slice_device_count(dual) == 2u && dual.chiplets_per_chip == 2u, "dual chiplet"); + + freetile::ChipPlacement place; + for (uint32_t device = 0u; device < 4u; ++device) { + CHECK_TRUE(freetile::place_prefix(grid, device, &place) && place.device == device, "2x2 distinct devices"); + CHECK_TRUE(place.chip_x == device % 2u && place.chip_y == device / 2u && place.chiplet == 0u, "2x2 coordinates"); + } + CHECK_TRUE(freetile::place_prefix(grid, 4u, &place) && place.device == 0u, "prefix hash wraps the slice"); + CHECK_TRUE(freetile::place_prefix(one, 99u, &place) && place.device == 0u, "1x1 has one device"); + CHECK_TRUE(freetile::place_prefix(host, 7u, &place) && place.device == 7u && place.chip_x == 1u && place.chip_y == 3u, + "2x4 corner"); + + freetile::ChipPlacement buddy; + CHECK_TRUE(freetile::place_prefix(dual, 0u, &place) && place.chiplet == 0u, "chiplet 0"); + CHECK_TRUE(freetile::d2d_buddy(dual, place, &buddy) && buddy.chiplet == 1u && buddy.package == place.package && + buddy.device == 1u, + "d2d buddy"); + freetile::ChipPlacement other; + CHECK_TRUE(freetile::place_prefix(dual, 1u, &other) && other.device == buddy.device, "hash 1 is the buddy device"); + CHECK_TRUE(!freetile::d2d_buddy(grid, place, &buddy), "single-chiplet slices have no d2d buddy"); + + const freetile::ServingRequest sticky_a = req(1u, "shared-prefix", 32u, 1u, 0u, 0u); + const freetile::ServingRequest sticky_b = req(99u, "shared-prefix", 32u, 1u, 0u, 0u); + CHECK_TRUE(freetile::request_prefix_hash(sticky_a) == freetile::request_prefix_hash(sticky_b), "prefix hash sticks"); + freetile::ChipPlacement sticky_place_a; + freetile::ChipPlacement sticky_place_b; + CHECK_TRUE(freetile::place_prefix(host, freetile::request_prefix_hash(sticky_a), &sticky_place_a), "place a"); + CHECK_TRUE(freetile::place_prefix(host, freetile::request_prefix_hash(sticky_b), &sticky_place_b), "place b"); + CHECK_TRUE(sticky_place_a.device == sticky_place_b.device, "same prefix lands on one chip"); + const freetile::ServingRequest bare_a = req(1u, nullptr, 32u, 1u, 0u, 0u); + const freetile::ServingRequest bare_b = req(2u, nullptr, 32u, 1u, 0u, 0u); + CHECK_TRUE(freetile::request_prefix_hash(bare_a) != freetile::request_prefix_hash(bare_b), + "missing prefix falls back to the request id"); + + freetile::ScheduleLimits limits; + limits.max_decode_tokens = 10u; + limits.max_prefill_tokens = 200u; + limits.verify_gamma = 4u; + limits.verify_step_budget = 16u; + const freetile::ServingRequest mixed[] = { + req(1u, "prefill", 100u, 0u, 0u, 0u), + req(5u, "decode", 10u, 1u, 0u, 0u), + }; + freetile::ScheduleStep step; + CHECK_TRUE(freetile::schedule_serving_step(host, mixed, 2u, limits, &step), "mixed schedule"); + CHECK_TRUE(step.items.size() == 2u && step.items[0].request_id == 5u && step.items[0].phase == freetile::RequestPhase::DECODE, + "decode is scheduled first"); + CHECK_TRUE(step.items[1].request_id == 1u && step.items[1].phase == freetile::RequestPhase::PREFILL, "prefill follows"); + freetile::ChipPlacement expected; + CHECK_TRUE(freetile::place_prefix(host, freetile::request_prefix_hash(mixed[1]), &expected) && + step.items[0].place.device == expected.device && + step.items[0].place.chip_x == expected.chip_x && + step.items[0].place.device < freetile::slice_device_count(host), + "decode placement follows the prefix hash"); + CHECK_TRUE(freetile::place_prefix(host, freetile::request_prefix_hash(mixed[0]), &expected) && + step.items[1].place.device == expected.device && + step.items[1].place.chip_y == expected.chip_y, + "prefill placement follows the prefix hash"); + + const freetile::ServingRequest bucketed[] = { + req(1u, "long", 128u, 1u, 0u, 0u), + req(9u, "short", 127u, 1u, 0u, 0u), + }; + CHECK_TRUE(freetile::schedule_serving_step(grid, bucketed, 2u, limits, &step), "bucket schedule"); + CHECK_TRUE(step.items.size() == 2u && step.items[0].request_id == 9u && step.items[0].length_bucket == 0u, + "shorter decode bucket runs first"); + CHECK_TRUE(step.items[1].request_id == 1u && step.items[1].length_bucket == 1u, "129-token context is bucket 1"); + + limits.max_decode_tokens = 4u; + freetile::ServingRequest many[10]; + for (uint32_t i = 0u; i < 10u; ++i) { + many[i] = req(i + 1u, "decode-bucket", 16u, 1u, 0u, 0u); + } + CHECK_TRUE(freetile::schedule_serving_step(one, many, 10u, limits, &step), "budget schedule"); + CHECK_TRUE(step.items.size() == 4u && step.decode_tokens == 4u, "decode budget admits four target tokens"); + for (uint32_t i = 0u; i < 4u; ++i) { + CHECK_TRUE(step.items[i].request_id == i + 1u, "lowest request ids fill the budget"); + CHECK_TRUE(step.items[i].place.device == 0u, "shared prefix stays on the only chip"); + } + + limits.max_decode_tokens = 3u; + limits.verify_gamma = 4u; + limits.verify_step_budget = 100u; + const freetile::ServingRequest skip_wide[] = { + req(1u, "wide", 16u, 1u, 10u, 3u), + req(2u, "cheap", 16u, 1u, 0u, 0u), + }; + CHECK_TRUE(freetile::schedule_serving_step(grid, skip_wide, 2u, limits, &step), "skip wide"); + CHECK_TRUE(step.items.size() == 1u && step.items[0].request_id == 2u, "a too-wide draft request is skipped"); + + limits.max_decode_tokens = 20u; + limits.verify_step_budget = 5u; + const freetile::ServingRequest drafts[] = { + req(1u, "draft-a", 16u, 1u, 10u, 3u), + req(2u, "draft-b", 16u, 1u, 4u, 4u), + }; + CHECK_TRUE(freetile::schedule_serving_step(dual, drafts, 2u, limits, &step), "speculative schedule"); + CHECK_TRUE(step.items.size() == 2u && step.verify_tokens == 5u && step.decode_tokens == 7u, "verify budget is 5"); + CHECK_TRUE(step.items[0].verify.verified == 4u && step.items[0].verify.accepted == 3u && + step.items[0].verify.rejected == 1u && step.items[0].verify.pending == 6u, + "first request verifies four drafts"); + CHECK_TRUE(step.items[1].verify.verified == 1u && step.items[1].verify.accepted == 1u && + step.items[1].verify.rejected == 0u && step.items[1].verify.pending == 3u, + "second request gets the remaining verify token"); + CHECK_TRUE(step.items[0].verify.accepted + step.items[0].verify.rejected == step.items[0].verify.verified, + "accepted plus rejected equals verified"); + + limits.max_decode_tokens = 0u; + limits.max_prefill_tokens = 500u; + limits.verify_step_budget = 0u; + const freetile::ServingRequest prefills[] = { + req(3u, "p100", 100u, 0u, 0u, 0u), + req(2u, "p200", 200u, 0u, 0u, 0u), + req(1u, "p3000", 3000u, 0u, 0u, 0u), + }; + CHECK_TRUE(freetile::schedule_serving_step(host, prefills, 3u, limits, &step), "prefill schedule"); + CHECK_TRUE(step.items.size() == 2u && step.prefill_tokens == 300u, "prefill budget skips the 3000-token prompt"); + CHECK_TRUE(step.items[0].request_id == 3u && step.items[1].request_id == 2u, "shorter prefills run first"); + + const freetile::ServingRequest empty_req = req(1u, "x", 0u, 0u, 0u, 0u); + CHECK_TRUE(!freetile::schedule_serving_step(one, &empty_req, 1u, limits, &step), "empty request fails"); + CHECK_TRUE(freetile::schedule_serving_step(one, nullptr, 0u, limits, &step) && step.ok && step.items.empty(), + "empty step is a successful no-op"); + } + + std::printf("freetile serving planner tests passed\n"); + return 0; +} From 2a775bb59c516b7b8fbea302ac07f4543949dd0b Mon Sep 17 00:00:00 2001 From: Ryan S <159389674+saariuslystoned@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:45:28 -0500 Subject: [PATCH 2/3] harden(freetile): fail-closed serving planner bounds, ASan/UBSan clean, fuzz stress - saturate mxus_per_chip product, overflow-safe slice_device_count - paged KV pack/gather: 64-bit offsets, full plan-consistency validation - MoE: route-table and workspace size caps, plan validation - reject invalid codebook format/path enums, validate d2d buddy packages - fix shift >=64 UB in build_op640 (freetile + libopenbuenos) - add deterministic fuzz/property stress test wiring into make/ctest --- freetile/CMakeLists.txt | 7 + freetile/Makefile | 10 +- freetile/include/freetile/serving_planner.hpp | 21 +- freetile/src/buenos_emitter.cpp | 2 +- freetile/src/serving_planner.cpp | 206 ++++++++- freetile/tests/test_serving_planner_fuzz.cpp | 422 ++++++++++++++++++ libopenbuenos/src/ob_gemm_emitter.cpp | 2 +- 7 files changed, 647 insertions(+), 23 deletions(-) create mode 100644 freetile/tests/test_serving_planner_fuzz.cpp diff --git a/freetile/CMakeLists.txt b/freetile/CMakeLists.txt index 88c88424..8792dfd5 100644 --- a/freetile/CMakeLists.txt +++ b/freetile/CMakeLists.txt @@ -40,6 +40,13 @@ target_link_libraries(test_serving_planner PRIVATE freetile) target_compile_options(test_serving_planner PRIVATE -Wall -Wextra -Wpedantic -Werror) add_test(NAME freetile_serving_planner_tests COMMAND test_serving_planner) +add_executable(test_serving_planner_fuzz + tests/test_serving_planner_fuzz.cpp +) +target_link_libraries(test_serving_planner_fuzz PRIVATE freetile) +target_compile_options(test_serving_planner_fuzz PRIVATE -Wall -Wextra -Wpedantic -Werror) +add_test(NAME freetile_serving_planner_fuzz COMMAND test_serving_planner_fuzz) + option(FREETILE_BUILD_BUENOS_PARITY_TEST "Build bit-exact parity test against sibling libopenbuenos" ON) option(FREETILE_BUILD_DIGITAL_TWIN "Build freetile-twin digital twin library, CLI, and tests" ON) diff --git a/freetile/Makefile b/freetile/Makefile index a66b7f69..9524ac82 100644 --- a/freetile/Makefile +++ b/freetile/Makefile @@ -56,13 +56,14 @@ TEST_SPLINES := $(BUILD_DIR)/test_splines_and_flash_attn TEST_PARITY := $(BUILD_DIR)/test_buenos_parity TEST_TWIN := $(BUILD_DIR)/test_freetile_twin TEST_SERVING := $(BUILD_DIR)/test_serving_planner +TEST_FUZZ := $(BUILD_DIR)/test_serving_planner_fuzz .PHONY: all host twin test verify-header clean openbuenos-host all: host host: $(FREETILE_LIB) $(FREETILE_TWIN_LIB) $(TWIN_CLI) $(ROOT_TWIN_CLI) \ - $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) + $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) $(TEST_FUZZ) twin: $(TWIN_CLI) $(ROOT_TWIN_CLI) @@ -104,6 +105,10 @@ $(TEST_SERVING): $(THIS_DIR)/tests/test_serving_planner.cpp $(FREETILE_LIB) $(CO @mkdir -p $(dir $@) $(HOST_CXX) $(CXXFLAGS_BASE) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) +$(TEST_FUZZ): $(THIS_DIR)/tests/test_serving_planner_fuzz.cpp $(FREETILE_LIB) $(CORE_HDRS) + @mkdir -p $(dir $@) + $(HOST_CXX) $(CXXFLAGS_BASE) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) + $(TEST_SPLINES): $(THIS_DIR)/tests/test_splines_and_flash_attn.cpp $(FREETILE_LIB) $(CORE_HDRS) @mkdir -p $(dir $@) $(HOST_CXX) $(CXXFLAGS_NOEXC) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) @@ -120,12 +125,13 @@ verify-header: $(TWIN_HDR) $(HOST_CC) -x c -std=c11 -fsyntax-only -Wall -Wextra -Wpedantic -Werror $< $(HOST_CXX) -x c++ -std=c++17 -fsyntax-only -Wall -Wextra -Wpedantic -Werror $< -test: verify-header $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) $(ROOT_TWIN_CLI) +test: verify-header $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) $(TEST_FUZZ) $(ROOT_TWIN_CLI) $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SERVING) + $(TEST_FUZZ) clean: rm -rf $(THIS_DIR)/build $(ROOT_TWIN_CLI) diff --git a/freetile/include/freetile/serving_planner.hpp b/freetile/include/freetile/serving_planner.hpp index a008d5b9..530251dc 100644 --- a/freetile/include/freetile/serving_planner.hpp +++ b/freetile/include/freetile/serving_planner.hpp @@ -73,7 +73,15 @@ struct GenerationProfile { }; inline int32_t mxus_per_chip(const GenerationProfile& profile) { - return profile.mxus_per_tensorcore * profile.tensorcores_per_chip; + const int64_t product = static_cast(profile.mxus_per_tensorcore) * + static_cast(profile.tensorcores_per_chip); + if (product > static_cast(0x7fffffff)) { + return 0x7fffffff; + } + if (product < static_cast(-0x7fffffff - 1)) { + return static_cast(-0x7fffffff - 1); + } + return static_cast(product); } GenerationProfile generation_profile(TpuGeneration generation); @@ -382,7 +390,16 @@ struct ScheduleStep { }; inline uint32_t slice_device_count(const SliceTopology& topology) { - return topology.dim_x * topology.dim_y * topology.chiplets_per_chip; + if (topology.dim_x == 0u || topology.dim_y == 0u || topology.chiplets_per_chip == 0u) { + return 0u; + } + const uint64_t total = static_cast(topology.dim_x) * + static_cast(topology.dim_y) * + static_cast(topology.chiplets_per_chip); + if (total > 0xffffffffull) { + return 0u; + } + return static_cast(total); } SliceTopology slice_topology(SliceShape shape); diff --git a/freetile/src/buenos_emitter.cpp b/freetile/src/buenos_emitter.cpp index 70dfa3f5..09478f2a 100644 --- a/freetile/src/buenos_emitter.cpp +++ b/freetile/src/buenos_emitter.cpp @@ -675,7 +675,7 @@ Pkt build_op640(uint32_t d, float scale, int32_t zp) { Pkt fl(std::begin(kBaseOp640), std::end(kBaseOp640)); const uint32_t n_c32 = (d + 31u) / 32u; if (n_c32 > 1u) { - const uint64_t mask = (1ULL << n_c32) - 1ULL; + const uint64_t mask = (n_c32 >= 64u) ? ~0ULL : ((1ULL << n_c32) - 1ULL); fl[0].lo = (fl[0].lo & 0xFFFFFFFFFFFF0FFFULL) | (mask << 12); fl[0].hi = 0x0000043000000000ULL; } diff --git a/freetile/src/serving_planner.cpp b/freetile/src/serving_planner.cpp index 0efe1d58..29b95fba 100644 --- a/freetile/src/serving_planner.cpp +++ b/freetile/src/serving_planner.cpp @@ -23,6 +23,10 @@ constexpr size_t kMaxScheduleRequests = 100000u; constexpr uint64_t kMib = 1024ull * 1024ull; constexpr uint64_t kGib = 1024ull * 1024ull * 1024ull; +constexpr size_t kMaxBlockTableEntries = 1u << 26; +constexpr size_t kMaxMoeAssignmentEntries = 1u << 26; +constexpr size_t kMaxMoeCompactEntries = 1u << 26; +constexpr uint64_t kMaxMoeWorkspaceFloats = 1ull << 28; bool fail(const char** err, const char* message) { if (err != nullptr) { @@ -353,9 +357,127 @@ GenerationProfile make_tpu7x() { bool profile_ready(const GenerationProfile& profile) { return profile.valid && profile.mxu_m > 0 && profile.mxu_n > 0 && - profile.tensorcores_per_chip > 0 && profile.chiplets_per_chip > 0 && - profile.hbm_bw_gbps > 0 && profile.bf16_tflops > 0 && - profile.vmem_bytes_per_chip > 0; + profile.mxus_per_tensorcore > 0 && profile.tensorcores_per_chip > 0 && + profile.chiplets_per_chip > 0 && profile.vpu_lanes > 0 && + profile.vpu_sublanes > 0 && profile.hbm_bw_gbps > 0 && + profile.bf16_tflops > 0 && profile.vmem_bytes_per_chip > 0; +} + +bool valid_codebook_format(CodebookFormat format) { + switch (format) { + case CodebookFormat::IQ4_XS: + case CodebookFormat::NF4: + case CodebookFormat::BOF4: + case CodebookFormat::FP4_MXFP4: + return true; + } + return false; +} + +bool valid_codebook_path(CodebookPath path) { + switch (path) { + case CodebookPath::LUT: + case CodebookPath::SELECT_TREE: + case CodebookPath::NATIVE_FP4: + return true; + } + return false; +} + +bool paged_plan_consistent(const PagedKvPlan& plan) { + if (!plan.ok || plan.page_size == 0u || plan.kv_dim == 0u || plan.num_pages == 0u || + plan.num_sequences == 0u || plan.block_stride == 0u) { + return false; + } + if (plan.seq_len.size() != static_cast(plan.num_sequences)) { + return false; + } + if (plan.seq_offset.size() != static_cast(plan.num_sequences) + 1u) { + return false; + } + const uint64_t expected_entries = + static_cast(plan.num_sequences) * plan.block_stride; + if (expected_entries > 0xffffffffull || + plan.block_table.size() != static_cast(expected_entries)) { + return false; + } + if (expected_entries > kMaxBlockTableEntries) { + return false; + } + uint64_t cursor = 0u; + for (uint32_t seq = 0u; seq < plan.num_sequences; ++seq) { + if (plan.seq_offset[seq] != static_cast(cursor)) { + return false; + } + const uint32_t len = plan.seq_len[seq]; + if (len == 0u) { + return false; + } + const uint64_t pages = + (static_cast(len) + plan.page_size - 1u) / plan.page_size; + if (pages > plan.block_stride) { + return false; + } + for (uint64_t page = 0u; page < pages; ++page) { + const uint32_t id = + plan.block_table[static_cast(seq) * plan.block_stride + page]; + if (id >= plan.num_pages) { + return false; + } + } + cursor += len; + if (cursor > 0xffffffffull) { + return false; + } + } + if (plan.seq_offset[plan.num_sequences] != static_cast(cursor)) { + return false; + } + if (plan.total_tokens != static_cast(cursor)) { + return false; + } + return true; +} + +bool moe_plan_consistent(const MoeRoutePlan& plan) { + if (!plan.ok || plan.num_tokens == 0u || plan.num_experts == 0u || plan.top_k == 0u || + plan.hidden_dim == 0u) { + return false; + } + const uint64_t assign = static_cast(plan.num_tokens) * plan.top_k; + if (assign > kMaxMoeAssignmentEntries || + plan.assignment.size() != static_cast(assign) || + plan.scatter_index.size() != static_cast(assign)) { + return false; + } + const uint64_t compact = static_cast(plan.num_experts) * plan.capacity; + if (compact > kMaxMoeCompactEntries || + plan.compact_tokens.size() != static_cast(compact)) { + return false; + } + if (plan.expert_counts.size() != static_cast(plan.num_experts)) { + return false; + } + for (uint32_t expert = 0u; expert < plan.num_experts; ++expert) { + if (plan.expert_counts[expert] > plan.capacity) { + return false; + } + } + for (size_t i = 0u; i < compact; ++i) { + const int32_t token = plan.compact_tokens[i]; + if (token < -1 || token >= static_cast(plan.num_tokens)) { + return false; + } + } + for (size_t i = 0u; i < assign; ++i) { + const int32_t index = plan.scatter_index[i]; + if (index < -1 || static_cast(static_cast(index)) >= compact) { + if (index != -1) { + return false; + } + } + } + return true; } uint32_t context_length(const ServingRequest& request, RequestPhase phase) { @@ -456,7 +578,8 @@ RooflineKnees roofline_knees(const GenerationProfile& profile) { return knees; } const double bf16_flops = static_cast(profile.bf16_tflops) * 1.0e12; - const double mxus = static_cast(mxus_per_chip(profile)); + const double mxus = static_cast(profile.mxus_per_tensorcore) * + static_cast(profile.tensorcores_per_chip); const double lattice = mxus * 2.0 * static_cast(profile.mxu_m) * static_cast(profile.mxu_n); knees.mxu_bf16_flops_per_s = bf16_flops; @@ -634,6 +757,9 @@ bool dequant_codebook(CodebookFormat format, if (out == nullptr && n_values == 0u) { return true; } + if (!valid_codebook_format(format) || !valid_codebook_path(path)) { + return fail(err, "unknown codebook format or path"); + } if (!is_finite(static_cast(scale))) { return fail(err, "codebook scale must be finite"); } @@ -716,6 +842,12 @@ bool plan_paged_kv(const PagedKvRequest& request, PagedKvPlan* out) { out->error = "paged KV working set is out of range"; return false; } + const uint64_t block_entries = + static_cast(request.num_sequences) * stride; + if (block_entries > kMaxBlockTableEntries) { + out->error = "paged KV block table is out of range"; + return false; + } const uint64_t page_bytes = static_cast(request.page_size) * static_cast(request.kv_dim) * sizeof(float); if (page_bytes == 0u || total_pages > kMaxWorkingSetBytes / page_bytes) { @@ -751,7 +883,8 @@ bool plan_paged_kv(const PagedKvRequest& request, PagedKvPlan* out) { for (uint32_t seq = 0u; seq < request.num_sequences; ++seq) { out->seq_offset[seq] = cursor; const uint32_t len = out->seq_len[seq]; - const uint32_t pages = (len + request.page_size - 1u) / request.page_size; + const uint32_t pages = static_cast( + (static_cast(len) + request.page_size - 1u) / request.page_size); for (uint32_t page = 0u; page < pages; ++page) { out->block_table[static_cast(seq) * stride + page] = next_page++; } @@ -763,7 +896,7 @@ bool plan_paged_kv(const PagedKvRequest& request, PagedKvPlan* out) { } bool paged_plan_ready(const PagedKvPlan& plan, const char** err) { - if (!plan.ok || plan.page_size == 0u || plan.kv_dim == 0u || plan.num_pages == 0u) { + if (!paged_plan_consistent(plan)) { return fail(err, "paged KV plan is not ready"); } return true; @@ -776,7 +909,9 @@ bool paged_kv_pack(const PagedKvPlan& plan, const float* tokens, float* pages, c if (tokens == nullptr || pages == nullptr) { return fail(err, "paged KV buffers are required"); } - const uint64_t page_floats = static_cast(plan.num_pages) * plan.page_size * plan.kv_dim; + const uint64_t page_floats = static_cast(plan.num_pages) * + static_cast(plan.page_size) * + static_cast(plan.kv_dim); std::memset(pages, 0, static_cast(page_floats) * sizeof(float)); for (uint32_t seq = 0u; seq < plan.num_sequences; ++seq) { const uint32_t len = plan.seq_len[seq]; @@ -784,8 +919,14 @@ bool paged_kv_pack(const PagedKvPlan& plan, const float* tokens, float* pages, c const uint32_t page_slot = token / plan.page_size; const uint32_t page = plan.block_table[static_cast(seq) * plan.block_stride + page_slot]; const uint32_t offset = token % plan.page_size; - const float* src = tokens + (static_cast(plan.seq_offset[seq] + token) * plan.kv_dim); - float* dst = pages + (static_cast(page * plan.page_size + offset) * plan.kv_dim); + const size_t src_index = + (static_cast(plan.seq_offset[seq]) + token) * + static_cast(plan.kv_dim); + const size_t dst_index = + (static_cast(page) * static_cast(plan.page_size) + offset) * + static_cast(plan.kv_dim); + const float* src = tokens + src_index; + float* dst = pages + dst_index; std::memcpy(dst, src, static_cast(plan.kv_dim) * sizeof(float)); } } @@ -805,8 +946,14 @@ bool paged_kv_gather(const PagedKvPlan& plan, const float* pages, float* tokens, const uint32_t page_slot = token / plan.page_size; const uint32_t page = plan.block_table[static_cast(seq) * plan.block_stride + page_slot]; const uint32_t offset = token % plan.page_size; - const float* src = pages + (static_cast(page * plan.page_size + offset) * plan.kv_dim); - float* dst = tokens + (static_cast(plan.seq_offset[seq] + token) * plan.kv_dim); + const size_t src_index = + (static_cast(page) * static_cast(plan.page_size) + offset) * + static_cast(plan.kv_dim); + const size_t dst_index = + (static_cast(plan.seq_offset[seq]) + token) * + static_cast(plan.kv_dim); + const float* src = pages + src_index; + float* dst = tokens + dst_index; std::memcpy(dst, src, static_cast(plan.kv_dim) * sizeof(float)); } } @@ -872,8 +1019,17 @@ bool plan_moe_route(const MoeRouteRequest& request, MoeRoutePlan* out) { return false; } - const size_t assign_count = static_cast(request.num_tokens) * request.top_k; - const size_t compact_count = static_cast(request.num_experts) * capacity; + const uint64_t assign_count_u64 = + static_cast(request.num_tokens) * request.top_k; + const uint64_t compact_count_u64 = + static_cast(request.num_experts) * capacity; + if (assign_count_u64 > kMaxMoeAssignmentEntries || + compact_count_u64 > kMaxMoeCompactEntries) { + out->error = "MoE route tables are out of range"; + return false; + } + const size_t assign_count = static_cast(assign_count_u64); + const size_t compact_count = static_cast(compact_count_u64); out->num_tokens = request.num_tokens; out->num_experts = request.num_experts; out->top_k = request.top_k; @@ -944,7 +1100,7 @@ bool moe_apply_reference(const MoeRoutePlan& plan, const float* token_hidden, float* token_out, const char** err) { - if (!plan.ok || plan.hidden_dim == 0u) { + if (!moe_plan_consistent(plan)) { return fail(err, "MoE plan is not ready"); } if (token_hidden == nullptr || token_out == nullptr) { @@ -952,13 +1108,18 @@ bool moe_apply_reference(const MoeRoutePlan& plan, } const uint32_t hidden = plan.hidden_dim; const size_t compact_count = plan.compact_tokens.size(); - std::vector workspace(compact_count * hidden, 0.0f); + const uint64_t workspace_floats = + static_cast(compact_count) * static_cast(hidden); + if (workspace_floats > kMaxMoeWorkspaceFloats) { + return fail(err, "MoE workspace is out of range"); + } + std::vector workspace(static_cast(workspace_floats), 0.0f); for (uint32_t expert = 0u; expert < plan.num_experts; ++expert) { const float weight = static_cast(expert + 1u); const size_t base = static_cast(expert) * plan.capacity; for (uint32_t local = 0u; local < plan.expert_counts[expert]; ++local) { const int32_t token = plan.compact_tokens[base + local]; - if (token < 0) { + if (token < 0 || static_cast(token) >= plan.num_tokens) { return fail(err, "compact expert slot is empty"); } const float* src = token_hidden + static_cast(token) * hidden; @@ -1023,6 +1184,9 @@ SliceTopology slice_topology(SliceShape shape) { uint64_t fnv1a64(const void* data, size_t size) { uint64_t hash = 14695981039346656037ull; + if (data == nullptr) { + return hash; + } const auto* bytes = static_cast(data); for (size_t i = 0u; i < size; ++i) { hash ^= bytes[i]; @@ -1077,7 +1241,15 @@ bool d2d_buddy(const SliceTopology& topology, const ChipPlacement& place, ChipPl return false; } const uint32_t devices = slice_device_count(topology); - if (place.device >= devices || place.chiplet > 1u) { + if (devices == 0u || place.device >= devices || place.chiplet > 1u) { + return false; + } + const uint64_t packages = + static_cast(topology.dim_x) * static_cast(topology.dim_y); + if (static_cast(place.package) >= packages) { + return false; + } + if (place.chip_x >= topology.dim_x || place.chip_y >= topology.dim_y) { return false; } *buddy = place; diff --git a/freetile/tests/test_serving_planner_fuzz.cpp b/freetile/tests/test_serving_planner_fuzz.cpp new file mode 100644 index 00000000..e72c0962 --- /dev/null +++ b/freetile/tests/test_serving_planner_fuzz.cpp @@ -0,0 +1,422 @@ +// SPDX-License-Identifier: Apache-2.0 +// Adversarial fuzz / property stress for the serving planner. +// Deterministic PRNG; every malformed shape must fail closed without +// OOB, overflow, or UB (meaningful under ASan + UBSan). + +#include "freetile/serving_planner.hpp" + +#include +#include +#include +#include +#include + +namespace { + +uint64_t splitmix64(uint64_t& state) { + uint64_t z = (state += 0x9e3779b97f4a7c15ull); + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebull; + return z ^ (z >> 31); +} + +uint32_t pick_u32(uint64_t& rng, uint32_t lo, uint32_t hi) { + if (hi <= lo) return lo; + return lo + static_cast(splitmix64(rng) % (hi - lo)); +} + +float pick_scale(uint64_t& rng) { + switch (splitmix64(rng) % 10u) { + case 0: return 0.0f; + case 1: return 1.0f; + case 2: return -2.0f; + case 3: return 1e30f; + case 4: return 1e-30f; + case 5: return 3.4028235e38f; + case 6: return static_cast(splitmix64(rng) % 1000) * 0.001f; + case 7: return std::numeric_limits::max(); + case 8: return std::numeric_limits::infinity(); + default: return std::numeric_limits::quiet_NaN(); + } +} + +float pick_score(uint64_t& rng) { + switch (splitmix64(rng) % 12u) { + case 0: return 0.0f; + case 1: return 1.0f; + case 2: return -1.0f; + case 3: return 1e9f; + case 4: return -1e9f; + case 5: return std::numeric_limits::infinity(); + case 6: return -std::numeric_limits::infinity(); + case 7: return std::numeric_limits::quiet_NaN(); + case 8: return 1.0f; + case 9: return 1.0f; + case 10: return 0.5f; + default: return static_cast(splitmix64(rng) % 200) * 0.01f - 1.0f; + } +} + +double pick_capacity(uint64_t& rng) { + switch (splitmix64(rng) % 10u) { + case 0: return 0.0; + case 1: return 1.0; + case 2: return 0.5; + case 3: return 1e12; + case 4: return 1e300; + case 5: return -1.0; + case 6: return std::numeric_limits::quiet_NaN(); + case 7: return std::numeric_limits::infinity(); + case 8: return 262144.0; + default: return 2.25; + } +} + +int g_fail = 0; +void check(bool ok, const char* msg) { + if (!ok) { + std::fprintf(stderr, "FUZZ FAIL: %s\n", msg); + ++g_fail; + } +} + +} // namespace + +int main() { + using namespace freetile; + uint64_t rng = 0x12345678deadbeefull; + + // 1) Offload / roofline: 3000 random + hostile samples. + { + const TpuGeneration gens[] = {TpuGeneration::V5E, TpuGeneration::V5P, + TpuGeneration::V6E, TpuGeneration::TPU7X}; + for (int i = 0; i < 2500; ++i) { + const auto profile = generation_profile(gens[i % 4]); + IntensitySample s; + s.flops = pick_score(rng) * 1e6f; + s.hbm_bytes = pick_score(rng) * 1e6f + 1e9; + if (i % 7 == 0) s.flops = -s.flops; + if (i % 11 == 0) s.hbm_bytes = std::nan(""); + if (i % 13 == 0) s.working_set_bytes = 1e300; + const auto d = decide_offload(profile, ServingOpKind::PAGED_KV_GATHER, s, + DispatchMode::AUTO); + if (s.flops < 0.0 || s.hbm_bytes < 0.0 || s.hbm_bytes != s.hbm_bytes) { + check(!d.ok, "negative/NaN intensity must fail closed"); + } + (void)roofline_knees(profile); + (void)matmul_intensity((int64_t)pick_u32(rng, 0, 9000) - 100, + (int64_t)pick_u32(rng, 0, 9000) - 100, + (int64_t)pick_u32(rng, 0, 9000) - 100, + pick_u32(rng, 0, 8)); + } + // Invalid enum values must not crash. + const auto bad_gen = generation_profile(static_cast(99u)); + check(!bad_gen.valid, "invalid generation must be invalid"); + GenerationProfile bad_profile; + bad_profile.valid = true; + bad_profile.mxus_per_tensorcore = 2000000000; + bad_profile.tensorcores_per_chip = 2000000000; + bad_profile.mxu_m = 128; + bad_profile.mxu_n = 128; + bad_profile.chiplets_per_chip = 1; + bad_profile.vpu_lanes = 1; + bad_profile.vpu_sublanes = 1; + bad_profile.hbm_bw_gbps = 1; + bad_profile.bf16_tflops = 1; + bad_profile.vmem_bytes_per_chip = 1; + bad_profile.generation = TpuGeneration::V5E; + const auto knees = roofline_knees(bad_profile); + check(knees.clock_hz == knees.clock_hz, "huge profile clock is finite or inf, no UB"); + check((int64_t)mxus_per_chip(bad_profile) <= 0x7fffffffLL, "mxu product saturates"); + } + + // 2) Paged KV: valid parity + hostile shapes + forged plans. + { + for (int i = 0; i < 1200; ++i) { + PagedKvRequest r; + r.generation = TpuGeneration::V6E; + r.dispatch = DispatchMode::AUTO; + const uint32_t psel = pick_u32(rng, 0, 9); + r.page_size = psel == 0 ? 1u : (psel == 1 ? 65536u : pick_u32(rng, 1, 128)); + const uint32_t dsel = pick_u32(rng, 0, 9); + r.kv_dim = dsel == 0 ? 1u : (dsel == 1 ? 65536u : pick_u32(rng, 1, 64)); + const uint32_t nsel = pick_u32(rng, 0, 9); + r.num_sequences = nsel == 0 ? 1u : (nsel == 1 ? 1000000u : pick_u32(rng, 1, 32)); + if (i % 17 == 0) r.num_sequences = 0u; + if (i % 19 == 0) r.page_size = 0u; + if (i % 23 == 0) r.seq_lens = nullptr; + std::vector lens; + if (r.seq_lens != nullptr && r.num_sequences <= 64u) { + lens.assign(r.num_sequences, 0u); + for (uint32_t s = 0u; s < r.num_sequences; ++s) { + const uint32_t lsel = pick_u32(rng, 0, 9); + lens[s] = lsel == 0 ? 1u : (lsel == 1 ? 0u : pick_u32(rng, 1, 40)); + } + r.seq_lens = lens.data(); + } else if (r.num_sequences > 64u && i % 5 == 0) { + r.num_sequences = 4u; + lens.assign(4, 3u); + r.seq_lens = lens.data(); + } + PagedKvPlan plan; + const bool ok = plan_paged_kv(r, &plan); + check(ok == plan.ok, "paged plan ok flag agrees"); + if (ok) { + const size_t total = static_cast(plan.total_tokens) * plan.kv_dim; + check(total <= (1u << 27), "fuzz total bounded"); + if (total <= (1u << 24)) { + std::vector tokens(total); + for (size_t t = 0; t < total; ++t) tokens[t] = (float)t * 0.25f; + const size_t cap = + static_cast(plan.num_pages) * plan.page_size * plan.kv_dim; + std::vector pages(cap, 9.0f); + const char* err = ""; + check(paged_kv_pack(plan, tokens.data(), pages.data(), &err), "fuzz pack"); + std::vector back(total, -1.0f); + check(paged_kv_gather(plan, pages.data(), back.data(), &err), "fuzz gather"); + check(std::memcmp(tokens.data(), back.data(), total * sizeof(float)) == 0, + "fuzz paged parity"); + } + // Forged plan must fail closed, never OOB. Buffers are + // sized for the unmutated plan so pack/gather arguments + // satisfy their size contract even when validation fails. + if (total <= (1u << 24) && + static_cast(plan.num_pages) * plan.page_size * plan.kv_dim <= + (1u << 26)) { + const size_t cap = + static_cast(plan.num_pages) * plan.page_size * plan.kv_dim; + PagedKvPlan forged = plan; + const uint32_t mut = pick_u32(rng, 0, 6); + if (mut == 0 && !forged.seq_offset.empty()) forged.seq_offset[0] = 0xfffffffeu; + if (mut == 1 && !forged.block_table.empty()) forged.block_table[0] = 0xfffffffeu; + if (mut == 2 && !forged.seq_len.empty()) forged.seq_len[0] = 0u; + if (mut == 3) forged.block_stride = 1u; + if (mut == 4) forged.num_pages = 1u; + if (mut == 5 && !forged.seq_offset.empty()) forged.seq_offset.pop_back(); + if (mut == 6 && !plan.block_table.empty()) forged.block_table.pop_back(); + std::vector dummy(cap, 1.0f); + std::vector dense(total, 1.0f); + const char* ferr = ""; + (void)paged_kv_pack(forged, dense.data(), dummy.data(), &ferr); + (void)paged_kv_gather(forged, dummy.data(), dense.data(), &ferr); + } + } + } + } + + // 3) MoE: hostile scores/capacity + forged plans + parity. + { + for (int i = 0; i < 1200; ++i) { + MoeRouteRequest r; + r.generation = TpuGeneration::V5P; + r.num_tokens = pick_u32(rng, 1, 12); + r.num_experts = pick_u32(rng, 1, 8); + r.top_k = pick_u32(rng, 0, 9); + if (r.top_k == 0u) r.top_k = 1u; + if (r.top_k > r.num_experts) r.top_k = r.num_experts; + r.hidden_dim = pick_u32(rng, 1, 8); + if (i % 29 == 0) r.num_tokens = 0u; + if (i % 31 == 0) r.top_k = 100u; + if (i % 37 == 0) r.hidden_dim = 0u; + r.capacity_factor = pick_capacity(rng); + std::vector scores(static_cast(r.num_tokens) * r.num_experts); + for (size_t s = 0; s < scores.size(); ++s) scores[s] = pick_score(rng); + r.scores = scores.data(); + if (i % 41 == 0) r.scores = nullptr; + if (i % 43 == 0) r.generation = static_cast(77u); + MoeRoutePlan plan; + const bool ok = plan_moe_route(r, &plan); + check(ok == plan.ok, "moe plan ok flag agrees"); + if (ok) { + const size_t total = static_cast(plan.num_tokens) * plan.hidden_dim; + std::vector hidden(total); + for (size_t t = 0; t < total; ++t) hidden[t] = (float)(t % 5) * 0.5f - 1.0f; + std::vector got(total, 3.0f); + std::vector naive(total, 0.0f); + const char* err = ""; + check(moe_apply_reference(plan, hidden.data(), got.data(), &err), "fuzz moe apply"); + for (uint32_t token = 0; token < plan.num_tokens; ++token) { + for (uint32_t rank = 0; rank < plan.top_k; ++rank) { + const int32_t e = + plan.assignment[static_cast(token) * plan.top_k + rank]; + if (e < 0) continue; + const float w = static_cast(e + 1); + for (uint32_t lane = 0; lane < plan.hidden_dim; ++lane) { + naive[static_cast(token) * plan.hidden_dim + lane] += + hidden[static_cast(token) * plan.hidden_dim + lane] * w; + } + } + } + check(std::memcmp(got.data(), naive.data(), total * sizeof(float)) == 0, + "fuzz moe parity"); + MoeRoutePlan forged = plan; + const uint32_t mut = pick_u32(rng, 0, 5); + if (mut == 0 && !forged.expert_counts.empty()) forged.expert_counts[0] = 999999u; + if (mut == 1 && !forged.scatter_index.empty()) forged.scatter_index[0] = 999999; + if (mut == 2 && !forged.compact_tokens.empty()) forged.compact_tokens[0] = 999999; + if (mut == 3) forged.capacity = 0u; + if (mut == 4 && !forged.assignment.empty()) forged.assignment.pop_back(); + if (mut == 5 && !forged.expert_counts.empty()) forged.expert_counts.pop_back(); + (void)moe_apply_reference(forged, hidden.data(), got.data(), &err); + } else { + check(!plan.ok, "moe failure has ok=false"); + } + } + // Extreme capacity blowup must fail closed, not OOM. + { + std::vector scores(64u * 1u, 1.0f); + MoeRouteRequest r; + r.generation = TpuGeneration::V6E; + r.num_tokens = 64u; + r.num_experts = 1u; + r.top_k = 1u; + r.capacity_factor = 2000000.0; + r.hidden_dim = 2u; + r.scores = scores.data(); + MoeRoutePlan plan; + check(!plan_moe_route(r, &plan), "capacity blowup fails closed"); + } + } + + // 4) Codebook: 0-ULP parity, odd lengths, hostile scales, invalid enums. + { + const CodebookFormat fmts[] = {CodebookFormat::IQ4_XS, CodebookFormat::NF4, + CodebookFormat::BOF4, CodebookFormat::FP4_MXFP4}; + for (int i = 0; i < 1500; ++i) { + const CodebookFormat fmt = fmts[i % 4]; + const auto desc = codebook_descriptor(fmt); + const uint32_t n = (i % 5 == 0) ? pick_u32(rng, 0, 130) : desc.group_size; + std::vector packed((n + 1u) / 2u, 0u); + for (uint32_t v = 0; v < n; ++v) { + const uint8_t nib = static_cast(pick_u32(rng, 0, 16)); + if ((v & 1u) == 0) packed[v >> 1] = nib; + else packed[v >> 1] = static_cast(packed[v >> 1] | (nib << 4)); + } + const float scale = pick_scale(rng); + std::vector a(n, -7.0f), b(n, -7.0f); + const char* err = ""; + const bool ok = dequant_codebook(fmt, CodebookPath::LUT, n ? packed.data() : nullptr, + n, scale, n ? a.data() : nullptr, &err); + check(ok == std::isfinite(scale), "dequant ok iff finite scale"); + if (ok && n > 0) { + check(dequant_codebook(fmt, CodebookPath::SELECT_TREE, + packed.data(), n, scale, b.data(), &err), + "tree dequant"); + check(std::memcmp(a.data(), b.data(), n * sizeof(float)) == 0, "0-ULP lut vs tree"); + for (uint32_t v = 0; v < 16u; ++v) { + check(codebook_select_tree_index(static_cast(v)) == v, "tree identity"); + } + } + float e8 = 0.0f; + const uint8_t exp = static_cast(pick_u32(rng, 0, 256)); + const bool e8_ok = mxfp4_e8m0_scale(exp, &e8, &err); + check(e8_ok == (exp != 255u), "e8m0 rejects only 0xFF"); + if (e8_ok) { + check(std::isfinite(e8), "e8m0 scale finite"); + } + } + { + const uint8_t bad = 0xa5u; + float out = 0.0f; + check(!dequant_codebook(static_cast(99u), CodebookPath::LUT, + &bad, 1u, 1.0f, &out, nullptr), + "invalid format fails closed"); + check(!dequant_codebook(CodebookFormat::NF4, + static_cast(99u), &bad, 1u, 1.0f, &out, nullptr), + "invalid path fails closed"); + check(!dequant_codebook(CodebookFormat::NF4, CodebookPath::NATIVE_FP4, + &bad, 1u, 1.0f, &out, nullptr), + "native rejects integer codebook"); + } + } + + // 5) Scheduling / placement / parsing: hostile topologies and requests. + { + const SliceShape shapes[] = {SliceShape::SLICE_1X1, SliceShape::SLICE_2X2, + SliceShape::SLICE_2X4, SliceShape::TPU7X_DUAL_CHIPLET}; + for (int i = 0; i < 1200; ++i) { + const auto topo = slice_topology(shapes[i % 4]); + ChipPlacement place; + check(place_prefix(topo, pick_u32(rng, 0, 1000000), &place), "placement ok"); + check(place.device < slice_device_count(topo), "device in range"); + ChipPlacement buddy; + const bool has_buddy = d2d_buddy(topo, place, &buddy); + check(has_buddy == (topo.chiplets_per_chip == 2u), "buddy iff dual chiplet"); + // Forged overflow topology must fail closed. + SliceTopology evil{}; + evil.dim_x = 0xffffffffu; + evil.dim_y = 0xffffffffu; + evil.chiplets_per_chip = 0xffffffffu; + check(slice_device_count(evil) == 0u, "overflow topology has no devices"); + check(!place_prefix(evil, 0ull, &place), "overflow placement fails closed"); + // Forged placement must fail closed for buddy. + ChipPlacement forged = place; + forged.package = 0xffffffffu; + (void)d2d_buddy(topo, forged, &buddy); + // Hashers must not crash on null/hostile input. + (void)fnv1a64(nullptr, 0u); + (void)fnv1a64(nullptr, 8u); + ServingRequest sreq{}; + sreq.request_id = pick_u32(rng, 0, 1000000); + sreq.prompt_tokens = pick_u32(rng, 0, 100000); + sreq.generated_tokens = pick_u32(rng, 0, 3); + sreq.draft_tokens = pick_u32(rng, 0, 20); + sreq.draft_accepted = pick_u32(rng, 0, 20); + if (i % 13 == 0) sreq.draft_accepted = sreq.draft_tokens + 5u; + if (i % 17 == 0) { sreq.prompt_tokens = 0u; sreq.generated_tokens = 0u; } + const char* pfx = (i % 3 == 0) ? "fuzz-prefix" : nullptr; + sreq.prefix = pfx; + sreq.prefix_len = pfx ? 11u : 0u; + if (i % 19 == 0) { sreq.prefix = nullptr; sreq.prefix_len = 8u; } + ScheduleLimits lim{}; + lim.max_decode_tokens = pick_u32(rng, 0, 64); + lim.max_prefill_tokens = pick_u32(rng, 0, 5000); + lim.verify_gamma = pick_u32(rng, 0, 8); + lim.verify_step_budget = pick_u32(rng, 0, 40); + ScheduleStep step; + const bool ok = schedule_serving_step(topo, &sreq, 1u, lim, &step); + if (ok) { + uint32_t accepted_plus = 0u, rejected_plus = 0u; + for (const auto& item : step.items) { + check(item.place.device < slice_device_count(topo), "scheduled device in range"); + accepted_plus += item.verify.accepted; + rejected_plus += item.verify.rejected; + check(item.verify.accepted + item.verify.rejected == item.verify.verified, + "budget identity"); + check(item.verify.verified <= item.verify.pending + item.verify.verified, + "pending identity"); + } + (void)accepted_plus; + (void)rejected_plus; + } + TpuGeneration parsed = TpuGeneration::V5E; + const char* names[] = {"v5e", "v6e", "tpu7x", "ironwood", "ct5p", "ct5lp", "v5", "", "TPU v6e"}; + (void)parse_generation(names[i % 9], &parsed); + (void)parse_generation(nullptr, &parsed); + } + // Extreme ragged shapes: single huge row, many empty-adjacent rows. + { + const uint32_t lens[] = {1u, 1u, 1u, 1u}; + PagedKvRequest r{}; + r.generation = TpuGeneration::TPU7X; + r.page_size = 65536u; + r.kv_dim = 1u; + r.num_sequences = 4u; + r.seq_lens = lens; + PagedKvPlan plan; + check(plan_paged_kv(r, &plan), "max page size plan"); + std::vector tokens(4, 1.0f); + std::vector pages(static_cast(plan.num_pages) * 65536u, 0.0f); + std::vector back(4, 0.0f); + const char* err = ""; + check(paged_kv_pack(plan, tokens.data(), pages.data(), &err), "max page pack"); + check(paged_kv_gather(plan, pages.data(), back.data(), &err), "max page gather"); + check(std::memcmp(tokens.data(), back.data(), 4u * sizeof(float)) == 0, "max page parity"); + } + } + + if (g_fail == 0) { + std::printf("serving planner fuzz passed\n"); + } + return g_fail == 0 ? 0 : 1; +} diff --git a/libopenbuenos/src/ob_gemm_emitter.cpp b/libopenbuenos/src/ob_gemm_emitter.cpp index bebe1539..3789d3d1 100644 --- a/libopenbuenos/src/ob_gemm_emitter.cpp +++ b/libopenbuenos/src/ob_gemm_emitter.cpp @@ -739,7 +739,7 @@ Pkt build_op640(uint32_t d, float scale, int32_t zp) { Pkt fl(std::begin(kBaseOp640), std::end(kBaseOp640)); uint32_t n_c32 = (d + 31u) / 32u; if (n_c32 > 1u) { - uint64_t mask = (1ULL << n_c32) - 1ULL; + uint64_t mask = (n_c32 >= 64u) ? ~0ULL : ((1ULL << n_c32) - 1ULL); fl[0].lo = (fl[0].lo & 0xFFFFFFFFFFFF0FFFULL) | (mask << 12); fl[0].hi = 0x0000043000000000ULL; } From 97711c2883e6e0ea6fbd8f286400be2a734ff776 Mon Sep 17 00:00:00 2001 From: Ryan S <159389674+saariuslystoned@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:54:48 -0500 Subject: [PATCH 3/3] fix(test): avoid GCC -Werror=type-limits in serving planner fuzz --- freetile/tests/test_serving_planner_fuzz.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/freetile/tests/test_serving_planner_fuzz.cpp b/freetile/tests/test_serving_planner_fuzz.cpp index e72c0962..5604e855 100644 --- a/freetile/tests/test_serving_planner_fuzz.cpp +++ b/freetile/tests/test_serving_planner_fuzz.cpp @@ -127,7 +127,7 @@ int main() { bad_profile.generation = TpuGeneration::V5E; const auto knees = roofline_knees(bad_profile); check(knees.clock_hz == knees.clock_hz, "huge profile clock is finite or inf, no UB"); - check((int64_t)mxus_per_chip(bad_profile) <= 0x7fffffffLL, "mxu product saturates"); + check(mxus_per_chip(bad_profile) >= 0 && mxus_per_chip(bad_profile) == INT32_MAX, "mxu product saturates"); } // 2) Paged KV: valid parity + hostile shapes + forged plans.