diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16dfc77a..70917b30 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,12 @@ jobs: CLOUDTPU_MOCK=1 "$LLAMA_BUILD/bin/test-backend-ops" test -b CLOUDTPU -o ADD CLOUDTPU_MOCK=1 "$LLAMA_BUILD/bin/test-backend-ops" test -b CLOUDTPU -o RMS_NORM CLOUDTPU_MOCK=1 "$LLAMA_BUILD/bin/test-backend-ops" test -b CLOUDTPU -o SCALE + for bad_spmd in 1x 9 17; do + if CLOUDTPU_MOCK=1 CLOUDTPU_MOCK_PROFILE=tpu7x-4t CLOUDTPU_MOCK_DEVICES=8 CLOUDTPU_SPMD_CHIPS="$bad_spmd" "$LLAMA_BUILD/bin/test-backend-ops" test -b CLOUDTPU -o ADD; then + echo "ERROR: test-backend-ops unexpectedly accepted CLOUDTPU_SPMD_CHIPS=$bad_spmd" >&2 + exit 1 + fi + done - name: Build & test libopenbuenos (Make) run: | @@ -109,6 +115,8 @@ jobs: python3 ops/tpu-cdi/freetpu_cdi.py --help >/dev/null python3 ops/tpu-exporter/test_tpu_exporter.py -v python3 ops/tpu-cdi/test_freetpu_cdi.py -v + for s in tools/ironwood-day1/*.sh; do bash -n "$s"; done + python3 tools/ironwood-day1/test_ironwood_day1.py -v - name: Run FreeTPU Router self-tests run: | diff --git a/docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md b/docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md index c0945d73..c5623031 100644 --- a/docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md +++ b/docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md @@ -5,7 +5,8 @@ **Offline Host Mock profiles (local dev/testing only, not live GCP VM shapes):** - `tpu7x-1t` (`CLOUDTPU_MOCK_PROFILE=tpu7x-1t`, `OPENTPU_MOCK_TOPOLOGY=tpu7x-1t`): `2`-chiplet single-package mock (`192 GiB`, D2D pair `(0, 1)`) -- `tpu7x-4t` (`CLOUDTPU_MOCK_PROFILE=tpu7x-4t`, `OPENTPU_MOCK_TOPOLOGY=tpu7x-4t`): `8`-chiplet quad-package mock (`768 GiB`) +- `tpu7x-4t` / `tpu7x-4t-single` (`OPENTPU_MOCK_TOPOLOGY=tpu7x-4t` / `tpu7x-4t-single`): `8`-chiplet quad-package mock (`4` PCI functions × `2` chiplets = `8` logical devices, `768 GiB`) +- `tpu7x-4t-2fn` (`OPENTPU_MOCK_TOPOLOGY=tpu7x-4t-2fn`): `8`-chiplet `2`-function-per-package quad-package mock (`8` PCI functions × `1` chiplet = `8` logical devices, `768 GiB`) **Goal:** Zero wasted DWS Calendar Mode clock minutes during the 24-hour evaluation window by running four reproducible, non-destructive/benchmark scripts under [`tools/ironwood-day1/`](../../tools/ironwood-day1/) (`00` -> `01` -> `02` -> `03`). @@ -46,12 +47,12 @@ On VMs without JAX installed (or running Python 3.10 where `pip install libtpu` ``` Record from `runs/ironwood-day1/00_pci_vfio_survey.txt`: -- PCI Vendor/Device ID (`0x1ae0:0x0076` guest VFIO ID / `0x0075` or observed Silicon DID) and physical PCI function count (`4` on `tpu7x-standard-4t`). +- PCI Vendor/Device ID (provisional `0x1ae0:0x0075` / `0x0076` candidates pending live Day-1 `lspci -nn` capture), verified physical package count (`4` on `tpu7x-standard-4t`), and PCI function count (`4` in `1-fn` dual-chiplet mode or `8` across `4` physical packages in `2-fn` mode). - `BAR0`, `BAR2`, `BAR4` window sizes and PCIe **Resizable BAR** (`0x0015`) capability fields (`current size:` and `supported:` lines). - `MSI-X` vector count, `/dev/iommu` (`iommufd`) availability, and `/dev/vfio/*` group viability. - Confirm physical-to-logical mapping in PJRT (native C++ `GetPjrtApi` probe with automatic `jax.local_devices(backend="tpu")` fallback preserving any native failure reason in the log): - `tpu7x-standard-4t` -> `8` logical `PJRT_Device*` in serpentine 2×2 Hamiltonian package walk with consecutive D2D pairs `(0,1), (2,3), (4,5), (6,7)` (each package pair sharing `coords` with `core_on_chip = 0, 1`). - - Confirm `STATUS: PJRT_TOPOLOGY_CAPTURED` (the script flags `WARN: TOPOLOGY_COUNT_MISMATCH` / `STATUS: PJRT_TOPOLOGY_MISMATCH` whenever live counts disagree with the expected `4` packages / `8` logical devices). + - Confirm `STATUS: PJRT_TOPOLOGY_CAPTURED` (the script compares verified physical packages `pci_tpu_packages` and live PJRT devices against `4` packages / `8` logical devices, reporting `pci_tpu_functions` separately so both `4`-function `1-fn` and `8`-function `2-fn` layouts validate cleanly). --- @@ -102,7 +103,7 @@ What this captures: Wait for: - `ot_chip_geometry_for_device_id()` & Resizable BAR clamp verification passing (`ALL_HOST_TESTS_PASSED`). -- Live `/dev/vfio/*` probe confirming **`MAPS_LIBTPU=0` and `MAPS_LIBPYTHON=0`** (`CLEANROOM_MAPS_STATUS=PASS`) and either `LIVE_VFIO_PROBE_STATUS=PASS` on validated `0x0063` or explicit pre-reset refusal (`Refusing to reset/program unsupported VFIO PCI device` -> `LIVE_VFIO_PROBE_STATUS=EXPECTED_UNVALIDATED_DEVICE_REFUSAL`) on unvalidated PCI DIDs until `0x0076` / `0x0075` (or observed DID) doorbell registers are documented cleanly. +- Live `/dev/vfio/*` probe confirming **`MAPS_LIBTPU=0` and `MAPS_LIBPYTHON=0`** (`CLEANROOM_MAPS_STATUS=PASS`) and either `LIVE_VFIO_PROBE_STATUS=PASS` on validated `0x0063` or explicit pre-open/pre-reset refusal (`Unsupported TPU PCI device` or `Refusing to reset/program unsupported VFIO PCI device` -> `LIVE_VFIO_PROBE_STATUS=EXPECTED_UNVALIDATED_DEVICE_REFUSAL`) on unvalidated PCI DIDs until `0x0076` / `0x0075` (or observed DID) doorbell registers are documented cleanly. --- diff --git a/docs/cloud-tpu/ops-container-telemetry.md b/docs/cloud-tpu/ops-container-telemetry.md index c9f92d58..e555996a 100644 --- a/docs/cloud-tpu/ops-container-telemetry.md +++ b/docs/cloud-tpu/ops-container-telemetry.md @@ -1,6 +1,6 @@ # Cloud TPU Ops Plumbing: Container CDI & Prometheus Telemetry -FreeTPU Pillar 6 brings GPU-grade operational ergonomics (`dcgm-exporter` + `nvidia-container-toolkit` + Kubernetes device plumbing) to VFIO-backed Google Cloud TPU VMs (`v5e`, `v5p`, `v6e` Trillium) using zero-dependency Python tooling over standard Linux sysfs (`vendor=0x1ae0`) and VFIO (`/dev/vfio/*`). +FreeTPU Pillar 6 brings GPU-grade operational ergonomics (`dcgm-exporter` + `nvidia-container-toolkit` + Kubernetes device plumbing) to VFIO-backed Google Cloud TPU VMs (`v5e`, `v5p`, `v6e` Trillium, and provisional `tpu7x` Ironwood `0x0075`/`0x0076` candidates) using zero-dependency Python tooling over standard Linux sysfs (`vendor=0x1ae0`) and VFIO (`/dev/vfio/*`). --- @@ -12,9 +12,9 @@ FreeTPU Pillar 6 brings GPU-grade operational ergonomics (`dcgm-exporter` + `nvi | `nvidia-ctk cdi generate` | `freetpu-cdi generate` (CNCF CDI `v0.6.0` default, `--cdi-version 1.1.0` opt-in) | [`ops/tpu-cdi/freetpu_cdi.py`](../../ops/tpu-cdi/freetpu_cdi.py) | | `k8s-device-plugin` / GPU Operator | K8s DaemonSet + DRA / CDI Pod Manifests | [`ops/tpu-cdi/manifests/`](../../ops/tpu-cdi/manifests/k8s-tpu-cdi-daemonset.yaml) | -VFIO-backed Cloud TPU VMs (`v5e`, `v5p`, `v6e` Trillium) expose each TPU chip as a PCI function (`vendor=0x1ae0`) bound to the standard Linux `vfio-pci` kernel driver, with per-IOMMU-group character nodes at `/dev/vfio/` and the shared VFIO container at `/dev/vfio/vfio`. +VFIO-backed Cloud TPU VMs (`v5e`, `v5p`, `v6e` Trillium, and provisional `tpu7x` Ironwood `0x0075`/`0x0076`) expose each TPU chip (or chiplet pair in 2-fn layouts) as PCI function(s) (`vendor=0x1ae0`) bound to the standard Linux `vfio-pci` kernel driver, with per-IOMMU-group character nodes at `/dev/vfio/` and the shared VFIO container at `/dev/vfio/vfio`. -> **Cloud TPU v2 / v3 / v4 (`/dev/accel*`) Scope Note:** Google Cloud TPU `v2`, `v3`, and `v4` hosts use Google's `/dev/accel*` character device interface rather than `vfio-pci` + `/dev/vfio/*`. `tpu-exporter` still recognizes `v2/v3` and `v4` PCI IDs for `freetpu_tpu_info` inventory discovery, but `freetpu-cdi` passthrough, VFIO readiness (`freetpu_tpu_health_status`), and `/dev/vfio/*` PID tracking are scoped strictly to VFIO-backed hosts (`v5e`, `v5p`, `v6e` Trillium). +> **Cloud TPU v2 / v3 / v4 (`/dev/accel*`) Scope Note:** Google Cloud TPU `v2`, `v3`, and `v4` hosts use Google's `/dev/accel*` character device interface rather than `vfio-pci` + `/dev/vfio/*`. `tpu-exporter` still recognizes `v2/v3` and `v4` PCI IDs for `freetpu_tpu_info` inventory discovery, but `freetpu-cdi` passthrough, VFIO readiness (`freetpu_tpu_health_status`), and `/dev/vfio/*` PID tracking are scoped strictly to VFIO-backed hosts (`v5e`, `v5p`, `v6e` Trillium, and provisional `tpu7x` Ironwood `0x0075`/`0x0076` pending live Day-1 confirmation). ### Supported Google TPU PCI Device IDs (`vendor=0x1ae0`) @@ -27,8 +27,8 @@ VFIO-backed Cloud TPU VMs (`v5e`, `v5p`, `v6e` Trillium) expose each TPU chip as | `0x0063` | `v5e` | TPU v5e | 16 GiB | `vfio-pci` (`/dev/vfio/*`, full exporter + CDI) | | `0x006e` | `v6e-pf` | TPU v6e (PF) | 32 GiB | `vfio-pci` (`/dev/vfio/*`, sysfs/VFIO inventory + CDI; upstream `tpu-info` CLI discovery omits `0x006e`, while `tpu_exporter.py` maps `0x006e` to `TpuChip.V6E` and queries a reachable `libtpu` endpoint via direct gRPC or `tpu_info.metrics` fallback) | | `0x006f` | `v6e` | TPU v6e (Trillium) | 32 GiB | `vfio-pci` (`/dev/vfio/*`, full exporter + CDI) | -| `0x0075` | `tpu7x` | TPU tpu7x (Ironwood, pending live hardware confirmation `#21`) | 192 GiB | `vfio-pci` (`/dev/vfio/*` or `iommufd`, pending live HW confirmation) | -| `0x0076` | `tpu7x` | TPU tpu7x (Ironwood) | 192 GiB | `vfio-pci` (`/dev/vfio/*` or `iommufd`, matches upstream `tpu-info` Ironwood ID) | +| `0x0075` | `tpu7x` | TPU tpu7x (Ironwood, pending live hardware confirmation `#21`) | 192 GiB | `vfio-pci` (`/dev/vfio/*` or `iommufd`, provisional candidate pending live Day-1 `lspci -nn`) | +| `0x0076` | `tpu7x` | TPU tpu7x (Ironwood, pending live hardware confirmation `#21`) | 192 GiB | `vfio-pci` (`/dev/vfio/*` or `iommufd`, provisional upstream `tpu-info` Ironwood ID pending live Day-1 `lspci -nn`) | > **TPU v6e PF (`0x006e`) note:** Upstream `tpu-info` CLI discovery recognizes the v6e virtual function (`0x006f`) and omits the physical function (`0x006e`), exiting before querying `libtpu` if only `0x006e` is present. On PF-only `0x006e` hosts, `tpu_exporter.py` maps `0x006e` directly to `TpuChip.V6E` and falls back to the Python `tpu_info.metrics` gRPC client against `--runtime-metrics-addr` (default `127.0.0.1:8431`) when the `tpu-info` Python package is installed, so live HBM and duty-cycle telemetry works on PF-only hosts without reconfiguring PCI devices (while PCI/VFIO inventory, readiness, active PIDs, and `freetpu-cdi` work without `tpu-info`). diff --git a/libopentpu/README.md b/libopentpu/README.md index 439edc3b..6b1e6df8 100644 --- a/libopentpu/README.md +++ b/libopentpu/README.md @@ -22,4 +22,4 @@ Outputs in `libopentpu/build/host/`: - **M3 (Self-Contained Bare-Metal `128x128` BF16 MXU Matmul over `/dev/vfio/0`)**: Complete clean-room 120-bundle (`7,680 B`) direct-in-IMEM resident boot/poller + 58-bundle `512`-bit VLIW MXU matmul loop (`ot::emit_v5e_resident_matmul_imem()` in `src/ot_vliw.h`), direct Host -> IMEM DMA (`op=0x04`), core start (`op=0x03 d[8]=0x121`), slot-0 `OtV5eLaunchDesc` doorbell (`0x3fff00000`), and transparent `{1,0:T(2,128)(2,1)}` HBM layout handling in `ot_device.cpp` + `ot_pjrt.cpp`. See [imem_boot_stub_spec.md](../docs/cloud-tpu-vfio/imem_boot_stub_spec.md). - **M4 (`GetPjrtApi()` `0.116`)**: Verified via `dlopen("./build/host/libopentpu.so")` -> `GetPjrtApi()` over live `/dev/vfio/0` (`platform=tpu`, `devices=1`, `PJRT_Client_BufferFromHostBuffer` -> `PJRT_Client_Compile` -> `PJRT_LoadedExecutable_Execute` -> `PJRT_Buffer_ToHostBuffer`, `MAPS_LIBTPU=0`, `MAPS_LIBPYTHON=0`). Because `libopentpu` is intentionally zero-dependency (no LLVM/MLIR/StableHLO runtime linked), `PJRT_Client_Compile` lowers single-op **textual** StableHLO `bf16` `dot_general` (`format="mlir"`) for both live VFIO (`128x128x128`) and mock clients, and returns `PJRT_Error_Code_UNIMPLEMENTED` for binary MLIR bytecode (`ML\xefR`) pending a zero-dependency bytecode decoder. - **M5 (`FreeTile`-Aligned Multi-Tile BF16 & Bare-Metal `Q8_0`/`Q4_0` Quantized GEMM)**: Added C11/C++17 `FreeTile` Backend B descriptor and VMEM double-buffer planner (`include/opentpu_freetile.hpp`, `ot_matmul_bf16_ex`, `ot_matmul_quant`), bare-metal IMEM multi-tile `BF16` GEMM with ping-pong DMA + FP32 accumulation (`128x512x512`, `256x512x256`, `128x4096x4096`), and bare-metal VPU/MXU `Q8_0`/`Q4_0` + per-channel `INT8`/`INT4` dequant+matmul (`0` mismatches vs FP32 reference on live `v5e-1`, `MAPS_LIBTPU=0`, `MAPS_LIBPYTHON=0`). Run `./build/host/opentpu_matmul_proof --mock --multitile --quant` offline or omit `--mock` on live `/dev/vfio/0`. See [freetile_multitile_quant_spec.md](../docs/cloud-tpu-vfio/freetile_multitile_quant_spec.md). -- **Multi-Gen HAL & Ironwood (`tpu7x`) Prep**: `ot_chip_geometry_for_device_id()` / `ot_device_get_geometry()` parameterize MXU tiles (`128x128` for `0x0063` v5e, `2x 256x256` for `0x006e`/`0x006f` v6e, and `0x0076`/`0x0075` Ironwood `tpu7x` with `(4,1)` FP8 inner tile, `64 MiB` VMEM/chiplet, and dual-chiplet `96 GiB/chiplet`), `clamp_bar_mmap_len()` / `parse_pcie_rebar_cap()` guard 64-bit Resizable BAR mappings, and `GetPjrtApi()` enumerates dual-chiplet `coords` + `core_on_chip` attributes (`OPENTPU_MOCK_TOPOLOGY=tpu7x-1t` / `tpu7x-4t`). See [`docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md`](../docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md). +- **Multi-Gen HAL & Ironwood (`tpu7x`) Prep**: `ot_chip_geometry_for_device_id()` / `ot_device_get_geometry()` parameterize MXU tiles (`128x128` for `0x0063` v5e, `2x 256x256` for `0x006e`/`0x006f` v6e, and provisional `0x0075`/`0x0076` Ironwood `tpu7x` candidates pending live Day-1 `lspci -nn`, with `(4,1)` FP8 inner tile, `64 MiB` VMEM/chiplet, and dual-chiplet `96 GiB/chiplet`), `clamp_bar_mmap_len()` / `parse_pcie_rebar_cap()` guard 64-bit Resizable BAR mappings, and `GetPjrtApi()` enumerates dual-chiplet `coords` + `core_on_chip` attributes (`OPENTPU_MOCK_TOPOLOGY=tpu7x-1t` / `tpu7x-4t`). See [`docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md`](../docs/cloud-tpu/ironwood-tpu7x-day1-runbook.md). diff --git a/libopentpu/include/opentpu.h b/libopentpu/include/opentpu.h index ec673f93..1f424f08 100644 --- a/libopentpu/include/opentpu.h +++ b/libopentpu/include/opentpu.h @@ -41,7 +41,7 @@ typedef enum ot_chip_gen { OT_CHIP_UNKNOWN = 0, OT_CHIP_V5E = 1, /* PCI 0x1ae0:0x0063 (128x128 MXU, 1 chiplet/package) */ OT_CHIP_V6E = 2, /* PCI 0x1ae0:0x006f (256x256 MXU, 1 chiplet/package) */ - OT_CHIP_TPU7X = 3 /* PCI 0x1ae0:0x0076 / 0x0075 Ironwood (256x256 MXU, dual-chiplet D2D, 64 MiB VMEM/chiplet) */ + OT_CHIP_TPU7X = 3 /* Provisional 0x1ae0:0x0075 / 0x0076 Ironwood candidates pending Day-1 lspci -nn (256x256 MXU, dual-chiplet D2D, 64 MiB VMEM/chiplet) */ } ot_chip_gen_t; typedef struct ot_device_geometry { diff --git a/libopentpu/src/ot_device.cpp b/libopentpu/src/ot_device.cpp index 96efd670..53c556a2 100644 --- a/libopentpu/src/ot_device.cpp +++ b/libopentpu/src/ot_device.cpp @@ -500,6 +500,27 @@ ot_status_t ot_context_create(const ot_config_t* config, ot_context_t** out_ctx) delete ctx; return OT_ERR_DEVICE; } + // Anchor cfg.bdf to context-owned info.bdf so callers passing temporary/stack BDF buffers + // (e.g. multi-device PJRT mock enumeration) never leave ctx->cfg.bdf dangling. + ctx->cfg.bdf = (ctx->info.bdf[0] != '\0') ? ctx->info.bdf : nullptr; + + if (ctx->info.chip_gen == OT_CHIP_TPU7X) { + const size_t bdf_len = std::strlen(ctx->info.bdf); + const bool non_zero_fn = bdf_len >= 2 && + ctx->info.bdf[bdf_len - 2] == '.' && + ctx->info.bdf[bdf_len - 1] != '0'; + if (ctx->info.device_id == 0x0076u || non_zero_fn) { + ctx->logical_chiplets_per_pci_func_override = 1u; + } else if (cfg.mock_mode) { + ot::MockProfileSpec mock_spec = {}; + std::string mock_err; + if (ot::resolve_mock_profile(&mock_spec, &mock_err) && mock_spec.is_tpu7x_two_fn) { + ctx->logical_chiplets_per_pci_func_override = 1u; + } + } else if (ot::probe_linux_tpu7x_two_fn_layout()) { + ctx->logical_chiplets_per_pci_func_override = 1u; + } + } if (!cfg.mock_mode) { ctx->info.is_prebooted = 0u; @@ -572,6 +593,10 @@ ot_status_t ot_chip_geometry_for_device_id(uint16_t pci_device_id, ot_device_geo ot_status_t ot_device_get_geometry(const ot_context_t* ctx, ot_device_geometry_t* out_geom) { if (!ctx || !out_geom) return OT_ERR_INVALID_ARG; if (ot::chip_geometry_for_device_id(ctx->info.device_id, out_geom)) { + if (ctx->info.chip_gen == OT_CHIP_TPU7X && + ctx->logical_chiplets_per_pci_func_override > 0) { + out_geom->logical_chiplets_per_pci_func = ctx->logical_chiplets_per_pci_func_override; + } return OT_OK; } std::memset(out_geom, 0, sizeof(*out_geom)); @@ -581,7 +606,10 @@ ot_status_t ot_device_get_geometry(const ot_context_t* ctx, ot_device_geometry_t out_geom->vmem_bytes_per_logical_chiplet = ctx->info.vmem_bytes; out_geom->smem_bytes_per_logical_chiplet = ctx->info.smem_bytes; out_geom->num_mxus_per_logical_chiplet = ctx->info.num_mxus; - out_geom->logical_chiplets_per_pci_func = (ctx->info.chip_gen == OT_CHIP_TPU7X) ? 2u : 1u; + out_geom->logical_chiplets_per_pci_func = + ctx->logical_chiplets_per_pci_func_override > 0 + ? ctx->logical_chiplets_per_pci_func_override + : ((ctx->info.chip_gen == OT_CHIP_TPU7X) ? 2u : 1u); return OT_OK; } @@ -698,14 +726,14 @@ bool chip_geometry_for_device_id(uint16_t device_id, ot_device_geometry_t* out) out->vmem_bytes_per_logical_chiplet = 128ULL << 20; out->smem_bytes_per_logical_chiplet = 1ULL << 20; return true; - case 0x0075u: // Ironwood tpu7x (dual-chiplet, 256x256 MXU + (4,1) FP8 inner tile, 96 GiB HBM, 64 MiB VMEM/chiplet) - case 0x0076u: // Documented Cloud TPU v7x (Ironwood) guest VM VFIO PCI Device ID + case 0x0075u: // Provisional Ironwood tpu7x ID pending Day-1 lspci (1-fn dual-chiplet default: 2 chiplets/fn, 96 GiB/chiplet, 64 MiB VMEM/chiplet) + case 0x0076u: // Provisional Ironwood tpu7x ID pending Day-1 lspci (2-fn candidate: 1 chiplet/fn, 96 GiB/chiplet) out->chip_gen = OT_CHIP_TPU7X; out->mxu_rows = 256u; out->mxu_cols = 256u; out->fp8_inner_rows = 4u; out->fp8_inner_cols = 1u; - out->logical_chiplets_per_pci_func = 2u; + out->logical_chiplets_per_pci_func = (device_id == 0x0076u) ? 1u : 2u; out->num_mxus_per_logical_chiplet = 2u; out->supports_native_fp8 = 1u; out->hbm_bytes_per_logical_chiplet = 96ULL << 30; diff --git a/libopentpu/src/ot_internal.h b/libopentpu/src/ot_internal.h index 432a4344..79c1d570 100644 --- a/libopentpu/src/ot_internal.h +++ b/libopentpu/src/ot_internal.h @@ -41,6 +41,28 @@ struct RebarCapabilityInfo { // Parse a 0x1234 hex sysfs attribute safely (no exceptions). bool parse_hex_u64(const std::string& text, uint64_t* out); +// Parse an unsigned 16-bit non-zero PCI device ID (no sign/overflow/trailing junk). +bool parse_mock_device_id(const char* raw, uint16_t* out); + +struct MockProfileSpec { + uint16_t device_id = 0x0063u; + ot_chip_gen_t chip_gen = OT_CHIP_V5E; + size_t pci_funcs = 1; + size_t chiplets_per_func = 1; + bool is_tpu7x_two_fn = false; + bool has_named_topo = false; + bool single_fn_only = false; +}; + +// Shared validation/resolution of OPENTPU_MOCK_TOPOLOGY / _DEVICE_ID / _CHIP +// used identically by both HAL ot_context_create() and PJRT_Client_Create(). +bool resolve_mock_profile(MockProfileSpec* out, std::string* err); + +// Inspect PCI sysfs directory for 2-fn Ironwood evidence (0x0076, non-.0 functions, +// >4 TPU7x functions, multifunction slot siblings, or same-domain shared chip_id). +bool probe_tpu7x_two_fn_layout_from_sysfs(const char* sysfs_pci_root); +bool probe_linux_tpu7x_two_fn_layout(); + // HAL geometry lookup across Google Cloud TPU generations (0x0063 v5e, 0x006e/0x006f v6e, // 0x0075/0x0076 Ironwood tpu7x dual-chiplet). Returns false on unknown device_id. bool chip_geometry_for_device_id(uint16_t device_id, ot_device_geometry_t* out); @@ -56,6 +78,12 @@ bool parse_pcie_rebar_cap(const uint8_t* cfg_bytes, size_t cfg_len, RebarCapabil // Enumerate all visible 0x1ae0 Google Cloud TPU PCI functions on Linux sysfs (sorted by BDF). bool enumerate_linux_tpus(std::vector* out, std::string* err); +// Inspect a PCI sysfs directory for a supported vfio-pci Google Cloud TPU (0x1ae0:0x0063, +// class=0xff0000), failing closed with an explicit pre-open refusal if preferred_bdf selects +// an unvalidated 0x1ae0 vfio-pci accelerator device or class. +bool discover_vfio_tpu_in_sysfs(const char* sysfs_pci_root, const char* preferred_bdf, + PciDiscoveryEntry* out, std::string* err); + // Simple monotonic IOVA bump/free-list allocator over valid IOMMU ranges. struct IovaBlock { uint64_t iova = 0; @@ -238,6 +266,7 @@ struct ot_context { std::mutex mu; ot_config_t cfg{}; ot_device_info_t info{}; + uint32_t logical_chiplets_per_pci_func_override = 0; ot::VfioTransport transport{}; ot::Bar4Descriptor bar4_desc{}; std::vector live_buffers; diff --git a/libopentpu/src/ot_pjrt.cpp b/libopentpu/src/ot_pjrt.cpp index 2ab4d25d..80ba3144 100644 --- a/libopentpu/src/ot_pjrt.cpp +++ b/libopentpu/src/ot_pjrt.cpp @@ -1105,6 +1105,14 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { if (opt.value_size == 0 || !opt.int64_array_value) { return make_err(PJRT_Error_Code_INVALID_ARGUMENT, "visible_devices must be non-empty"); } + if (opt.value_size > 64u) { + return make_err(PJRT_Error_Code_INVALID_ARGUMENT, + "visible_devices exceeds maximum device count"); + } + if (has_visible_devs) { + return make_err(PJRT_Error_Code_INVALID_ARGUMENT, + "duplicate visible_devices or allowed_devices option"); + } has_visible_devs = true; visible_devs.assign(opt.int64_array_value, opt.int64_array_value + opt.value_size); } @@ -1117,10 +1125,9 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { // Validate visible_devices before opening any live VFIO context (which may issue VFIO_DEVICE_RESET). // In live mode OpenTPU exposes only single device 0; reject negative, duplicate, or non-zero IDs early. if (has_visible_devs) { - std::vector seen; - seen.reserve(visible_devs.size()); + bool seen[64] = {}; for (int64_t vid : visible_devs) { - if (vid < 0) { + if (vid < 0 || vid >= 64) { return make_err(PJRT_Error_Code_INVALID_ARGUMENT, "visible_devices index out of range"); } @@ -1128,11 +1135,11 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { return make_err(PJRT_Error_Code_INVALID_ARGUMENT, "visible_devices index out of range for live single-device OpenTPU"); } - if (std::find(seen.begin(), seen.end(), vid) != seen.end()) { + if (seen[static_cast(vid)]) { return make_err(PJRT_Error_Code_INVALID_ARGUMENT, "duplicate device index in visible_devices"); } - seen.push_back(vid); + seen[static_cast(vid)] = true; } } @@ -1143,116 +1150,34 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { size_t chiplets_per_func = 1; if (cfg.mock_mode) { - auto parse_mock_chip_env = [](const char* s) -> ot_chip_gen_t { - if (!s || !s[0]) return OT_CHIP_UNKNOWN; - if (std::strcmp(s, "tpu7x") == 0 || std::strcmp(s, "ironwood") == 0 || - std::strcmp(s, "v7x") == 0) { - return OT_CHIP_TPU7X; - } - if (std::strcmp(s, "v6e") == 0 || std::strcmp(s, "trillium") == 0) { - return OT_CHIP_V6E; - } - if (std::strcmp(s, "v5e") == 0 || std::strcmp(s, "v5lite") == 0) { - return OT_CHIP_V5E; - } - return OT_CHIP_UNKNOWN; - }; - - bool has_named_topo = false; - ot_chip_gen_t topo_gen = OT_CHIP_UNKNOWN; - uint16_t topo_did = 0x0063u; - if (const char* topo_env = std::getenv("OPENTPU_MOCK_TOPOLOGY")) { - if (std::strcmp(topo_env, "tpu7x-1t") == 0 || std::strcmp(topo_env, "tpu7x_1t") == 0) { - has_named_topo = true; - topo_gen = OT_CHIP_TPU7X; - topo_did = 0x0075u; - pci_funcs = 1; - chiplets_per_func = 2; - } else if (std::strcmp(topo_env, "tpu7x-4t") == 0 || std::strcmp(topo_env, "tpu7x_4t") == 0) { - has_named_topo = true; - topo_gen = OT_CHIP_TPU7X; - topo_did = 0x0075u; - pci_funcs = 4; - chiplets_per_func = 2; - } else if (std::strcmp(topo_env, "v6e-8") == 0 || std::strcmp(topo_env, "v6e_8") == 0) { - has_named_topo = true; - topo_gen = OT_CHIP_V6E; - topo_did = 0x006fu; - pci_funcs = 8; - chiplets_per_func = 1; - } else if (std::strcmp(topo_env, "v5e-1") == 0 || std::strcmp(topo_env, "v5e_1") == 0) { - has_named_topo = true; - topo_gen = OT_CHIP_V5E; - topo_did = 0x0063u; - pci_funcs = 1; - chiplets_per_func = 1; - } - } - - bool has_did_env = false; - bool did_parsed_ok = false; - uint16_t env_did = 0; - ot_chip_gen_t did_gen = OT_CHIP_UNKNOWN; - if (const char* did_env = std::getenv("OPENTPU_MOCK_DEVICE_ID")) { - if (did_env[0] != '\0') { - has_did_env = true; - uint64_t parsed = 0; - if (ot::parse_hex_u64(did_env, &parsed) && parsed <= 0xffffULL) { - did_parsed_ok = true; - env_did = static_cast(parsed); - ot_device_geometry_t did_geom = {}; - (void)ot::chip_geometry_for_device_id(env_did, &did_geom); - did_gen = static_cast(did_geom.chip_gen); - } - } - } - - bool has_chip_env = false; - ot_chip_gen_t chip_gen = OT_CHIP_UNKNOWN; - if (const char* chip_env = std::getenv("OPENTPU_MOCK_CHIP")) { - if (chip_env[0] != '\0') { - has_chip_env = true; - chip_gen = parse_mock_chip_env(chip_env); - } - } - - if (has_named_topo && has_did_env && did_gen != topo_gen) { - return make_err(PJRT_Error_Code_INVALID_ARGUMENT, - "OPENTPU_MOCK_TOPOLOGY conflicts with OPENTPU_MOCK_DEVICE_ID chip generation"); - } - if (has_named_topo && has_chip_env && chip_gen != topo_gen) { - return make_err(PJRT_Error_Code_INVALID_ARGUMENT, - "OPENTPU_MOCK_TOPOLOGY conflicts with OPENTPU_MOCK_CHIP chip generation"); - } - if (has_did_env && has_chip_env && - (did_gen == OT_CHIP_UNKNOWN || chip_gen == OT_CHIP_UNKNOWN || did_gen != chip_gen)) { - return make_err(PJRT_Error_Code_INVALID_ARGUMENT, - "OPENTPU_MOCK_DEVICE_ID conflicts with OPENTPU_MOCK_CHIP chip generation"); - } - - uint16_t mock_did = 0x0063u; - if (has_did_env && did_parsed_ok) { - mock_did = env_did; - } else if (has_named_topo) { - mock_did = topo_did; - } else if (has_chip_env) { - if (chip_gen == OT_CHIP_TPU7X) mock_did = 0x0075u; - else if (chip_gen == OT_CHIP_V6E) mock_did = 0x006fu; - else mock_did = 0x0063u; - } - - ot_device_geometry_t mock_geom = {}; - (void)ot::chip_geometry_for_device_id(mock_did, &mock_geom); - if (mock_geom.chip_gen == OT_CHIP_TPU7X) kind_str = "TPU v7x"; - else if (mock_geom.chip_gen == OT_CHIP_V6E) kind_str = "TPU v6 lite"; + ot::MockProfileSpec mock_spec = {}; + std::string mock_err; + if (!ot::resolve_mock_profile(&mock_spec, &mock_err)) { + return make_err(PJRT_Error_Code_INVALID_ARGUMENT, mock_err); + } + if (mock_spec.single_fn_only && cfg.bdf && cfg.bdf[0]) { + const size_t bdf_len = std::strlen(cfg.bdf); + if (bdf_len >= 2 && cfg.bdf[bdf_len - 2] == '.' && cfg.bdf[bdf_len - 1] != '0') { + return make_err( + PJRT_Error_Code_INVALID_ARGUMENT, + "OPENTPU_MOCK_TOPOLOGY=tpu7x-4t-single conflicts with non-zero PCI function BDF"); + } + } + pci_funcs = mock_spec.pci_funcs; + chiplets_per_func = mock_spec.chiplets_per_func; + if (mock_spec.chip_gen == OT_CHIP_TPU7X) kind_str = "TPU v7x"; + else if (mock_spec.chip_gen == OT_CHIP_V6E) kind_str = "TPU v6 lite"; else kind_str = "TPU v5 lite"; - if (!has_named_topo) { - chiplets_per_func = - mock_geom.logical_chiplets_per_pci_func > 0 ? mock_geom.logical_chiplets_per_pci_func : 1u; - } } + if (pci_funcs == 0 || chiplets_per_func == 0 || pci_funcs > 64u || + chiplets_per_func > 64u) { + return make_err(PJRT_Error_Code_INTERNAL, "invalid topology dimensions"); + } const size_t total_logical = pci_funcs * chiplets_per_func; + if (total_logical > 64u) { + return make_err(PJRT_Error_Code_INTERNAL, "mock topology logical device count out of range"); + } std::vector selected_ids; if (has_visible_devs) { selected_ids.reserve(visible_devs.size()); @@ -1276,8 +1201,30 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { } } + const bool is_tpu7x_two_fn = + (kind_str == "TPU v7x" && chiplets_per_func == 1 && (pci_funcs == 2 || pci_funcs == 8)); + const size_t chiplets_per_pkg = + (is_tpu7x_two_fn || chiplets_per_func > 1) ? 2u : 1u; + const size_t package_count = total_logical / chiplets_per_pkg; + + auto assign_mock_fn_bdf = [&](size_t pkg_idx, size_t fn_idx, char* buf, size_t buf_sz) { + const unsigned bus = static_cast(pkg_idx / 28u); + const unsigned dev_slot = static_cast(4u + (pkg_idx % 28u)); + std::snprintf(buf, buf_sz, "0000:%02x:%02x.%u", bus, dev_slot, static_cast(fn_idx)); + }; + + ot_config_t first_cfg = cfg; + char first_bdf_buf[32] = {}; + if (cfg.mock_mode && (!cfg.bdf || !cfg.bdf[0]) && pci_funcs > 1 && !selected_ids.empty()) { + const size_t first_lid = static_cast(selected_ids[0]); + const size_t first_pkg = first_lid / chiplets_per_pkg; + const size_t first_fn = is_tpu7x_two_fn ? (first_lid % chiplets_per_pkg) : 0u; + assign_mock_fn_bdf(first_pkg, first_fn, first_bdf_buf, sizeof(first_bdf_buf)); + first_cfg.bdf = first_bdf_buf; + } + ot_context_t* first_ctx = nullptr; - ot_status_t st = ot_context_create(&cfg, &first_ctx); + ot_status_t st = ot_context_create(&first_cfg, &first_ctx); if (st != OT_OK) { const char* detail = ot_context_last_error(nullptr); std::string msg = std::string("ot_context_create failed: ") + ot_status_string(st); @@ -1313,7 +1260,7 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { // Serpentine 2x2 package walk when 4 physical packages are present (e.g. tpu7x-4t) // so intra-package D2D chiplets remain consecutive pairs (0,1), (2,3), (4,5), (6,7). - const int64_t grid_x = (pci_funcs == 4) ? 2 : static_cast(pci_funcs); + const int64_t grid_x = (package_count == 4) ? 2 : static_cast(package_count); c->devices.reserve(selected_ids.size()); c->dev_ptrs.reserve(selected_ids.size()); c->mem_ptrs.reserve(selected_ids.size()); @@ -1321,11 +1268,11 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { for (size_t idx = 0; idx < selected_ids.size(); ++idx) { const int logical_id = selected_ids[idx]; - const size_t pkg = static_cast(logical_id) / chiplets_per_func; - const size_t core = static_cast(logical_id) % chiplets_per_func; + const size_t pkg = static_cast(logical_id) / chiplets_per_pkg; + const size_t core = static_cast(logical_id) % chiplets_per_pkg; const int64_t y = static_cast(pkg) / grid_x; int64_t x = static_cast(pkg) % grid_x; - if (pci_funcs == 4 && (y & 1) != 0) { + if (package_count == 4 && (y & 1) != 0) { x = grid_x - 1 - x; } @@ -1335,7 +1282,14 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { first_ctx = nullptr; } else { // Each addressable mock device owns an isolated ot_context_t & HBM arena. - ot_status_t dst = ot_context_create(&cfg, &dev_ctx); + ot_config_t dev_cfg = cfg; + char pkg_bdf_buf[32] = {}; + if (cfg.mock_mode && (!cfg.bdf || !cfg.bdf[0]) && pci_funcs > 1) { + const size_t fn_idx = is_tpu7x_two_fn ? core : 0u; + assign_mock_fn_bdf(pkg, fn_idx, pkg_bdf_buf, sizeof(pkg_bdf_buf)); + dev_cfg.bdf = pkg_bdf_buf; + } + ot_status_t dst = ot_context_create(&dev_cfg, &dev_ctx); if (dst != OT_OK) { delete c; return make_err(PJRT_Error_Code_INTERNAL, @@ -1352,7 +1306,7 @@ PJRT_Error* ot_pjrt_client_create(PJRT_Client_Create_Args* args) { dev->desc.debug_str = "OpenTPU:" + std::to_string(logical_id); dev->desc.coords = {x, y, 0}; dev->desc.core_on_chip = - (chiplets_per_func > 1) ? static_cast(core) : -1; + (chiplets_per_pkg > 1) ? static_cast(core) : -1; dev->desc.finalize_attrs(); dev->mem.base.vtable = &kMemoryVtable; dev->mem.id = logical_id; diff --git a/libopentpu/src/ot_vfio.cpp b/libopentpu/src/ot_vfio.cpp index 07f8b555..f535442d 100644 --- a/libopentpu/src/ot_vfio.cpp +++ b/libopentpu/src/ot_vfio.cpp @@ -3,19 +3,20 @@ #include "ot_vliw.h" #include +#include #include #include #include #include #include #include +#include +#include #include #include #include #ifdef __linux__ -#include -#include #include #include #endif @@ -24,14 +25,202 @@ namespace ot { bool parse_hex_u64(const std::string& text, uint64_t* out) { if (!out || text.empty()) return false; + const char* p = text.c_str(); + while (*p != '\0' && std::isspace(static_cast(*p))) ++p; + if (*p == '\0' || *p == '-' || *p == '+') return false; char* end = nullptr; errno = 0; - unsigned long long v = std::strtoull(text.c_str(), &end, 0); - if (errno != 0 || end == text.c_str()) return false; + unsigned long long v = std::strtoull(p, &end, 0); + if (errno != 0 || end == p) return false; + while (*end != '\0' && std::isspace(static_cast(*end))) ++end; + if (*end != '\0') return false; *out = static_cast(v); return true; } +bool parse_mock_device_id(const char* raw, uint16_t* out) { + if (!raw || !out || raw[0] == '\0') return false; + uint64_t parsed = 0; + if (!parse_hex_u64(raw, &parsed) || parsed == 0 || parsed > 0xffffULL) return false; + *out = static_cast(parsed); + return true; +} + +bool resolve_mock_profile(MockProfileSpec* out, std::string* err) { + if (!out) return false; + *out = MockProfileSpec{}; + auto parse_mock_chip_env = [](const char* s) -> ot_chip_gen_t { + if (!s || !s[0]) return OT_CHIP_UNKNOWN; + if (std::strcmp(s, "tpu7x") == 0 || std::strcmp(s, "ironwood") == 0 || + std::strcmp(s, "v7x") == 0) { + return OT_CHIP_TPU7X; + } + if (std::strcmp(s, "v6e") == 0 || std::strcmp(s, "trillium") == 0) { + return OT_CHIP_V6E; + } + if (std::strcmp(s, "v5e") == 0 || std::strcmp(s, "v5lite") == 0) { + return OT_CHIP_V5E; + } + return OT_CHIP_UNKNOWN; + }; + + bool has_topo_env = false; + bool has_named_topo = false; + bool single_fn_only = false; + bool two_fn_topo = false; + bool is_tpu7x_4t_family = false; + bool is_tpu7x_1t = false; + ot_chip_gen_t topo_gen = OT_CHIP_UNKNOWN; + uint16_t topo_did = 0x0063u; + size_t pci_funcs = 1; + size_t chiplets_per_func = 1; + + if (const char* topo_env = std::getenv("OPENTPU_MOCK_TOPOLOGY")) { + if (topo_env[0] != '\0') { + has_topo_env = true; + if (std::strcmp(topo_env, "tpu7x-1t") == 0 || std::strcmp(topo_env, "tpu7x_1t") == 0) { + has_named_topo = true; + is_tpu7x_1t = true; + topo_gen = OT_CHIP_TPU7X; + topo_did = 0x0075u; + pci_funcs = 1; + chiplets_per_func = 2; + } else if (std::strcmp(topo_env, "tpu7x-4t-2fn") == 0 || + std::strcmp(topo_env, "tpu7x_4t_2fn") == 0) { + has_named_topo = true; + two_fn_topo = true; + is_tpu7x_4t_family = true; + topo_gen = OT_CHIP_TPU7X; + topo_did = 0x0076u; + pci_funcs = 8; + chiplets_per_func = 1; + } else if (std::strcmp(topo_env, "tpu7x-4t") == 0 || std::strcmp(topo_env, "tpu7x_4t") == 0 || + std::strcmp(topo_env, "tpu7x-4t-single") == 0 || + std::strcmp(topo_env, "tpu7x_4t_single") == 0) { + has_named_topo = true; + is_tpu7x_4t_family = true; + single_fn_only = (std::strcmp(topo_env, "tpu7x-4t-single") == 0 || + std::strcmp(topo_env, "tpu7x_4t_single") == 0); + topo_gen = OT_CHIP_TPU7X; + topo_did = 0x0075u; + pci_funcs = 4; + chiplets_per_func = 2; + } else if (std::strcmp(topo_env, "v6e-8") == 0 || std::strcmp(topo_env, "v6e_8") == 0) { + has_named_topo = true; + topo_gen = OT_CHIP_V6E; + topo_did = 0x006fu; + pci_funcs = 8; + chiplets_per_func = 1; + } else if (std::strcmp(topo_env, "v5e-1") == 0 || std::strcmp(topo_env, "v5e_1") == 0) { + has_named_topo = true; + topo_gen = OT_CHIP_V5E; + topo_did = 0x0063u; + pci_funcs = 1; + chiplets_per_func = 1; + } + } + } + + bool has_did_env = false; + bool did_parsed_ok = false; + bool did_supported = false; + uint16_t env_did = 0; + ot_chip_gen_t did_gen = OT_CHIP_UNKNOWN; + if (const char* did_env = std::getenv("OPENTPU_MOCK_DEVICE_ID")) { + if (did_env[0] != '\0') { + has_did_env = true; + if (parse_mock_device_id(did_env, &env_did)) { + did_parsed_ok = true; + ot_device_geometry_t did_geom = {}; + if (chip_geometry_for_device_id(env_did, &did_geom) && + did_geom.chip_gen != OT_CHIP_UNKNOWN) { + did_supported = true; + did_gen = static_cast(did_geom.chip_gen); + } + } + } + } + + bool has_chip_env = false; + ot_chip_gen_t chip_gen = OT_CHIP_UNKNOWN; + if (const char* chip_env = std::getenv("OPENTPU_MOCK_CHIP")) { + if (chip_env[0] != '\0') { + has_chip_env = true; + chip_gen = parse_mock_chip_env(chip_env); + } + } + + if (has_topo_env && !has_named_topo) { + if (err) *err = "unrecognized OPENTPU_MOCK_TOPOLOGY value"; + return false; + } + if (has_chip_env && chip_gen == OT_CHIP_UNKNOWN) { + if (err) *err = "unrecognized OPENTPU_MOCK_CHIP value"; + return false; + } + if (has_did_env && !did_parsed_ok) { + if (err) *err = "invalid OPENTPU_MOCK_DEVICE_ID value"; + return false; + } + if (has_did_env && !did_supported) { + if (err) *err = "unsupported OPENTPU_MOCK_DEVICE_ID value"; + return false; + } + if (has_named_topo && has_did_env && did_gen != topo_gen) { + if (err) *err = "OPENTPU_MOCK_TOPOLOGY conflicts with OPENTPU_MOCK_DEVICE_ID chip generation"; + return false; + } + if (has_named_topo && has_chip_env && chip_gen != topo_gen) { + if (err) *err = "OPENTPU_MOCK_TOPOLOGY conflicts with OPENTPU_MOCK_CHIP chip generation"; + return false; + } + if (has_did_env && has_chip_env && + (did_gen == OT_CHIP_UNKNOWN || chip_gen == OT_CHIP_UNKNOWN || did_gen != chip_gen)) { + if (err) *err = "OPENTPU_MOCK_DEVICE_ID conflicts with OPENTPU_MOCK_CHIP chip generation"; + return false; + } + if (single_fn_only && has_did_env && env_did == 0x0076u) { + if (err) *err = "OPENTPU_MOCK_TOPOLOGY=tpu7x-4t-single conflicts with 2-fn device ID 0x0076"; + return false; + } + + uint16_t mock_did = 0x0063u; + if (has_did_env && did_parsed_ok) { + mock_did = env_did; + } else if (has_named_topo) { + mock_did = topo_did; + } else if (has_chip_env) { + if (chip_gen == OT_CHIP_TPU7X) mock_did = 0x0075u; + else if (chip_gen == OT_CHIP_V6E) mock_did = 0x006fu; + else mock_did = 0x0063u; + } + + ot_device_geometry_t mock_geom = {}; + (void)chip_geometry_for_device_id(mock_did, &mock_geom); + if (mock_did == 0x0076u) { + two_fn_topo = true; + if (is_tpu7x_4t_family) { + pci_funcs = 8; + chiplets_per_func = 1; + } else if (is_tpu7x_1t || !has_named_topo) { + pci_funcs = 2; + chiplets_per_func = 1; + } + } else if (!has_named_topo) { + chiplets_per_func = + mock_geom.logical_chiplets_per_pci_func > 0 ? mock_geom.logical_chiplets_per_pci_func : 1u; + } + + out->device_id = mock_did; + out->chip_gen = static_cast(mock_geom.chip_gen); + out->pci_funcs = pci_funcs; + out->chiplets_per_func = chiplets_per_func; + out->is_tpu7x_two_fn = two_fn_topo; + out->has_named_topo = has_named_topo; + out->single_fn_only = single_fn_only; + return true; +} + size_t clamp_bar_mmap_len(uint64_t bar_size, size_t max_len) { if (bar_size == 0 || max_len == 0) return 0; const uint64_t cap = static_cast(max_len); @@ -407,12 +596,49 @@ bool VfioTransport::register_fork_cleanup(std::string* err) { return true; } +static std::string sysfs_read_line(const std::string& path) { + int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) return ""; + char buf[256]; + ssize_t n = ::read(fd, buf, sizeof(buf)); + ::close(fd); + if (n <= 0 || static_cast(n) >= sizeof(buf)) return ""; + if (std::memchr(buf, '\0', static_cast(n)) != nullptr) return ""; + buf[n] = '\0'; + std::string s(buf); + while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) { + s.pop_back(); + } + return s; +} + +static std::string sysfs_read_link_base(const std::string& path) { + char buf[512]; + ssize_t n = ::readlink(path.c_str(), buf, sizeof(buf) - 1); + if (n <= 0) return ""; + buf[n] = '\0'; + std::string s(buf); + auto pos = s.rfind('/'); + return (pos == std::string::npos) ? s : s.substr(pos + 1); +} + +static bool is_supported_vfio_device_id(uint16_t device_id) { + // Only TPU v5e (0x1ae0:0x0063) has a validated VFIO ring/DMA transport. + // Documented TPU v6e (0x1ae0:0x006f) is rejected until its transport is validated. + return device_id == 0x0063u; +} + +static bool is_tpu_accelerator_pci_class(uint64_t cls) { + const uint64_t base_cls = (cls >> 16) & 0xffULL; + return base_cls == 0xffULL || base_cls == 0x12ULL || base_cls == 0x0bULL || base_cls == 0x08ULL; +} + #ifdef __linux__ static inline void dma_wmb() { #if defined(__aarch64__) asm volatile("dsb oshst" ::: "memory"); #elif defined(__arm__) - asm volatile("dsb ost" ::: "memory"); + asm volatile("dsb oshst" ::: "memory"); #elif defined(__x86_64__) || defined(__i386__) asm volatile("sfence" ::: "memory"); #else @@ -432,37 +658,6 @@ static inline void dma_rmb() { #endif } -static bool is_supported_vfio_device_id(uint16_t device_id) { - // Only TPU v5e (0x1ae0:0x0063) has a validated VFIO ring/DMA transport. - // Documented TPU v6e (0x1ae0:0x006f) is rejected until its transport is validated. - return device_id == 0x0063u; -} - -static std::string sysfs_read_line(const std::string& path) { - int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); - if (fd < 0) return ""; - char buf[256]; - ssize_t n = ::read(fd, buf, sizeof(buf) - 1); - ::close(fd); - if (n <= 0) return ""; - buf[n] = '\0'; - std::string s(buf); - while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) { - s.pop_back(); - } - return s; -} - -static std::string sysfs_read_link_base(const std::string& path) { - char buf[512]; - ssize_t n = ::readlink(path.c_str(), buf, sizeof(buf) - 1); - if (n <= 0) return ""; - buf[n] = '\0'; - std::string s(buf); - auto pos = s.rfind('/'); - return (pos == std::string::npos) ? s : s.substr(pos + 1); -} - static void read_sysfs_pci_bars(const std::string& res_path, uint64_t* bar0, uint64_t* bar2, @@ -538,12 +733,26 @@ bool enumerate_linux_tpus(std::vector* out, std::string* err) } static bool discover_linux_tpu(const char* preferred_bdf, PciDiscoveryEntry* out, std::string* err) { - DIR* dir = ::opendir("/sys/bus/pci/devices"); + return discover_vfio_tpu_in_sysfs("/sys/bus/pci/devices", preferred_bdf, out, err); +} +#else +bool enumerate_linux_tpus(std::vector* out, std::string* err) { + if (out) out->clear(); + if (err) *err = "Linux sysfs enumeration unavailable on this host"; + return false; +} +#endif + +bool discover_vfio_tpu_in_sysfs(const char* sysfs_pci_root, const char* preferred_bdf, + PciDiscoveryEntry* out, std::string* err) { + if (!out || !sysfs_pci_root || sysfs_pci_root[0] == '\0') return false; + DIR* dir = ::opendir(sysfs_pci_root); if (!dir) { - if (err) *err = "Failed to open /sys/bus/pci/devices"; + if (err) *err = std::string("Failed to open ") + sysfs_pci_root + ": " + std::strerror(errno); return false; } + const std::string root_str(sysfs_pci_root); bool found = false; struct dirent* ent = nullptr; while ((ent = ::readdir(dir)) != nullptr) { @@ -552,7 +761,7 @@ static bool discover_linux_tpu(const char* preferred_bdf, PciDiscoveryEntry* out if (preferred_bdf && preferred_bdf[0] != '\0' && bdf != preferred_bdf) { continue; } - std::string base = "/sys/bus/pci/devices/" + bdf; + std::string base = root_str + "/" + bdf; uint64_t vid = 0, did = 0, cls = 0; parse_hex_u64(sysfs_read_line(base + "/vendor"), &vid); parse_hex_u64(sysfs_read_line(base + "/device"), &did); @@ -560,18 +769,21 @@ static bool discover_linux_tpu(const char* preferred_bdf, PciDiscoveryEntry* out std::string drv = sysfs_read_link_base(base + "/driver"); std::string grp_str = sysfs_read_link_base(base + "/iommu_group"); - if (drv == "vfio-pci" && vid == 0x1ae0ULL && cls == 0xff0000ULL && !grp_str.empty()) { + if (drv == "vfio-pci" && vid == 0x1ae0ULL && is_tpu_accelerator_pci_class(cls) && + !grp_str.empty()) { char* end = nullptr; errno = 0; unsigned long grp_val = std::strtoul(grp_str.c_str(), &end, 10); if (errno != 0 || end == grp_str.c_str() || *end != '\0') continue; - if (!is_supported_vfio_device_id(static_cast(did))) { + if (!is_supported_vfio_device_id(static_cast(did)) || cls != 0xff0000ULL) { if (preferred_bdf && preferred_bdf[0] != '\0') { if (err) { - char msg[160]; - std::snprintf(msg, sizeof(msg), - "Unsupported TPU PCI device %s (0x%04x:0x%04x); only validated v5e (0x1ae0:0x0063) is supported", - bdf.c_str(), static_cast(vid), static_cast(did)); + char msg[192]; + std::snprintf( + msg, sizeof(msg), + "Unsupported TPU PCI device %s (0x%04x:0x%04x class=0x%06x); only validated v5e (0x1ae0:0x0063 class=0xff0000) is supported", + bdf.c_str(), static_cast(vid), + static_cast(did), static_cast(cls)); *err = msg; } ::closedir(dir); @@ -596,12 +808,123 @@ static bool discover_linux_tpu(const char* preferred_bdf, PciDiscoveryEntry* out } return found; } -#else -bool enumerate_linux_tpus(std::vector* out, std::string* err) { - if (out) out->clear(); - if (err) *err = "Linux sysfs enumeration unavailable on this host"; + +static bool parse_sysfs_chip_id_u16(const std::string& raw, int64_t* out) { + if (!out || raw.empty()) return false; + auto is_trim = [](unsigned char ch) -> bool { + return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; + }; + size_t pos = 0; + const size_t n = raw.size(); + while (pos < n && is_trim(static_cast(raw[pos]))) ++pos; + const size_t dstart = pos; + unsigned long long cid_val = 0; + while (pos < n && raw[pos] >= '0' && raw[pos] <= '9') { + cid_val = cid_val * 10ULL + static_cast(raw[pos] - '0'); + if (cid_val > 65535ULL) return false; + ++pos; + } + const size_t digits = pos - dstart; + if (digits == 0 || digits > 5) return false; + while (pos < n && is_trim(static_cast(raw[pos]))) ++pos; + if (pos != n) return false; + *out = static_cast(cid_val); + return true; +} + +bool probe_tpu7x_two_fn_layout_from_sysfs(const char* sysfs_pci_root) { + if (!sysfs_pci_root || sysfs_pci_root[0] == '\0') return false; + DIR* dir = ::opendir(sysfs_pci_root); + if (!dir) return false; + struct Entry { + std::string bdf; + std::string slot; + std::string dom_key; + int64_t chip_id = -1; + }; + std::vector entries; + struct dirent* ent = nullptr; + while ((ent = ::readdir(dir)) != nullptr) { + if (ent->d_name[0] == '.') continue; + const std::string bdf(ent->d_name); + const std::string base = std::string(sysfs_pci_root) + "/" + bdf; + uint64_t vid = 0; + uint64_t did = 0; + if (!parse_hex_u64(sysfs_read_line(base + "/vendor"), &vid) || vid != 0x1ae0ULL) continue; + if (!parse_hex_u64(sysfs_read_line(base + "/device"), &did)) continue; + if (did != 0x0075ULL && did != 0x0076ULL) continue; + if (did == 0x0076ULL || + (bdf.size() >= 2 && bdf[bdf.size() - 2] == '.' && bdf.back() != '0')) { + ::closedir(dir); + return true; + } + Entry e; + e.bdf = bdf; + const size_t dot = bdf.rfind('.'); + e.slot = (dot != std::string::npos) ? bdf.substr(0, dot) : bdf; + + // Resolve PCIe root complex from canonical sysfs path (/sys/devices/pciXXXX:XX/...). + std::string root; + char resolved_buf[4096] = {}; + if (::realpath(base.c_str(), resolved_buf)) { + std::string rp(resolved_buf); + size_t pos = 0; + while (pos < rp.size()) { + size_t next = rp.find('/', pos); + std::string comp = (next == std::string::npos) ? rp.substr(pos) : rp.substr(pos, next - pos); + if (comp.size() == 10 && comp.compare(0, 3, "pci") == 0 && comp[7] == ':') { + root = comp.substr(3); + break; + } + if (next == std::string::npos) break; + pos = next + 1; + } + } + if (root.empty()) { + const size_t c1 = bdf.find(':'); + const size_t c2 = (c1 != std::string::npos) ? bdf.find(':', c1 + 1) : std::string::npos; + root = (c2 != std::string::npos) ? bdf.substr(0, c2) : bdf; + } + + std::string numa_str = sysfs_read_line(base + "/numa_node"); + std::string numa_key = "pcie"; + if (!numa_str.empty()) { + char* nend = nullptr; + errno = 0; + long nval = std::strtol(numa_str.c_str(), &nend, 10); + if (errno == 0 && nend != numa_str.c_str() && *nend == '\0' && nval >= 0 && nval <= 65535L) { + numa_key = "numa:" + std::to_string(nval); + } + } + e.dom_key = numa_key + "|" + root; + + int64_t cid_val = -1; + if (parse_sysfs_chip_id_u16(sysfs_read_line(base + "/chip_id"), &cid_val)) { + e.chip_id = cid_val; + } + entries.push_back(std::move(e)); + } + ::closedir(dir); + + if (entries.size() > 4u) return true; + for (size_t i = 0; i < entries.size(); ++i) { + for (size_t j = i + 1; j < entries.size(); ++j) { + if (entries[i].slot == entries[j].slot) return true; + if (entries[i].chip_id >= 0 && entries[i].chip_id == entries[j].chip_id && + entries[i].dom_key == entries[j].dom_key) { + return true; + } + } + } return false; } + +#ifdef __linux__ +bool probe_linux_tpu7x_two_fn_layout() { + return probe_tpu7x_two_fn_layout_from_sysfs("/sys/bus/pci/devices"); +} +#else +bool probe_linux_tpu7x_two_fn_layout() { return false; } #endif bool VfioTransport::is_owner_process() const { @@ -617,37 +940,21 @@ bool VfioTransport::open_device(const ot_config_t& cfg, ot_device_info_t* info, if (cfg.mock_mode) { is_mock = true; - uint16_t mock_did = 0x0063u; - const char* did_env = std::getenv("OPENTPU_MOCK_DEVICE_ID"); - if (did_env && did_env[0] != '\0') { - uint64_t parsed = 0; - if (parse_hex_u64(did_env, &parsed) && parsed <= 0xffffULL) { - mock_did = static_cast(parsed); - } - } else if (const char* topo_env = std::getenv("OPENTPU_MOCK_TOPOLOGY")) { - if (std::strcmp(topo_env, "tpu7x-1t") == 0 || std::strcmp(topo_env, "tpu7x_1t") == 0 || - std::strcmp(topo_env, "tpu7x-4t") == 0 || std::strcmp(topo_env, "tpu7x_4t") == 0) { - mock_did = 0x0075u; - } else if (std::strcmp(topo_env, "v6e-8") == 0 || std::strcmp(topo_env, "v6e_8") == 0) { - mock_did = 0x006fu; - } else if (std::strcmp(topo_env, "v5e-1") == 0 || std::strcmp(topo_env, "v5e_1") == 0) { - mock_did = 0x0063u; - } else if (const char* chip_env = std::getenv("OPENTPU_MOCK_CHIP")) { - if (std::strcmp(chip_env, "tpu7x") == 0 || std::strcmp(chip_env, "ironwood") == 0 || - std::strcmp(chip_env, "v7x") == 0) { - mock_did = 0x0075u; - } else if (std::strcmp(chip_env, "v6e") == 0 || std::strcmp(chip_env, "trillium") == 0) { - mock_did = 0x006fu; - } - } - } else if (const char* chip_env = std::getenv("OPENTPU_MOCK_CHIP")) { - if (std::strcmp(chip_env, "tpu7x") == 0 || std::strcmp(chip_env, "ironwood") == 0 || - std::strcmp(chip_env, "v7x") == 0) { - mock_did = 0x0075u; - } else if (std::strcmp(chip_env, "v6e") == 0 || std::strcmp(chip_env, "trillium") == 0) { - mock_did = 0x006fu; + MockProfileSpec mock_spec = {}; + if (!resolve_mock_profile(&mock_spec, err)) { + return false; + } + const char* req_bdf = (cfg.bdf && cfg.bdf[0]) ? cfg.bdf : "0000:00:05.0"; + const size_t req_len = std::strlen(req_bdf); + const bool req_non_zero_fn = + req_len >= 2 && req_bdf[req_len - 2] == '.' && req_bdf[req_len - 1] != '0'; + if (mock_spec.single_fn_only && req_non_zero_fn) { + if (err) { + *err = "OPENTPU_MOCK_TOPOLOGY=tpu7x-4t-single conflicts with non-zero PCI function BDF"; } + return false; } + uint16_t mock_did = mock_spec.device_id; ot_device_geometry_t geom = {}; (void)chip_geometry_for_device_id(mock_did, &geom); diff --git a/libopentpu/tests/opentpu_host_test.cpp b/libopentpu/tests/opentpu_host_test.cpp index b7b47616..4c7cc225 100644 --- a/libopentpu/tests/opentpu_host_test.cpp +++ b/libopentpu/tests/opentpu_host_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -2378,7 +2379,7 @@ static void test_multigen_hal_geometry_and_rebar() { OT_CHECK(g7.mxu_rows == 256u && g7.mxu_cols == 256u); OT_CHECK(g7.fp8_inner_rows == 4u && g7.fp8_inner_cols == 1u); OT_CHECK(g7.supports_native_fp8 == 1u); - OT_CHECK(g7.logical_chiplets_per_pci_func == 2u); + OT_CHECK(g7.logical_chiplets_per_pci_func == (did7 == 0x0076u ? 1u : 2u)); OT_CHECK(g7.num_mxus_per_logical_chiplet == 2u); OT_CHECK(g7.hbm_bytes_per_logical_chiplet == (96ULL << 30)); OT_CHECK(g7.vmem_bytes_per_logical_chiplet == (64ULL << 20)); @@ -2425,7 +2426,7 @@ static void test_multigen_hal_geometry_and_rebar() { ot_context_destroy(ctx); unsetenv("OPENTPU_MOCK_CHIP"); - // Guest VM VFIO Ironwood PCI Device ID (0x0076) via OPENTPU_MOCK_DEVICE_ID. + // Provisional 0x0076 Ironwood PCI Device ID candidate via OPENTPU_MOCK_DEVICE_ID (pending Day-1 lspci). setenv("OPENTPU_MOCK_DEVICE_ID", "0x0076", 1); ctx = nullptr; OT_CHECK(ot_context_create(&cfg, &ctx) == OT_OK && ctx != nullptr); @@ -2524,6 +2525,267 @@ static void test_pjrt_dual_chiplet_tpu7x_enumeration() { printf("[PASS] test_pjrt_dual_chiplet_tpu7x_enumeration\n"); } +static void test_pjrt_single_chiplet_tpu7x_enumeration() { + const PJRT_Api* api = GetPjrtApi(); + OT_CHECK(api != nullptr); + + // tpu7x-4t-single must align with HAL geometry (2 chiplets per PCI function) + // and map 8 logical devices onto 4 serpentine 2x2 packages preserving D2D + // pairs (0,1), (2,3), (4,5), (6,7) with valid core_on_chip (0/1). + const int64_t expected_coords[8][3] = { + {0, 0, 0}, {0, 0, 0}, {1, 0, 0}, {1, 0, 0}, + {1, 1, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 0}, + }; + + const char* expected_bdfs[8] = { + "0000:00:04.0", "0000:00:04.0", "0000:00:05.0", "0000:00:05.0", + "0000:00:06.0", "0000:00:06.0", "0000:00:07.0", "0000:00:07.0", + }; + + for (const char* topo_name : {"tpu7x-4t-single", "tpu7x_4t_single"}) { + unsetenv("OPENTPU_MOCK_DEVICE_ID"); + // Unset OPENTPU_MOCK_CHIP so VfioTransport must resolve tpu7x-4t-single directly. + unsetenv("OPENTPU_MOCK_CHIP"); + setenv("OPENTPU_MOCK", "1", 1); + setenv("OPENTPU_MOCK_TOPOLOGY", topo_name, 1); + + PJRT_Client_Create_Args c_args = {}; + c_args.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + OT_CHECK(api->PJRT_Client_Create(&c_args) == nullptr && c_args.client != nullptr); + + PJRT_Client_AddressableDevices_Args d_args = {}; + d_args.struct_size = PJRT_Client_AddressableDevices_Args_STRUCT_SIZE; + d_args.client = c_args.client; + OT_CHECK(api->PJRT_Client_AddressableDevices(&d_args) == nullptr); + OT_CHECK(d_args.num_addressable_devices == 8u); + + ot_device_geometry_t g7 = {}; + OT_CHECK(ot_chip_geometry_for_device_id(0x0075u, &g7) == OT_OK); + OT_CHECK(g7.chip_gen == OT_CHIP_TPU7X); + OT_CHECK(g7.logical_chiplets_per_pci_func == 2u); + OT_CHECK(g7.mxu_rows == 256u && g7.mxu_cols == 256u); + OT_CHECK(g7.fp8_inner_rows == 4u && g7.fp8_inner_cols == 1u); + OT_CHECK(g7.supports_native_fp8 == 1u); + OT_CHECK(g7.hbm_bytes_per_logical_chiplet == (96ULL << 30)); + + for (size_t i = 0; i < 8u; ++i) { + const ot_context_t* dev_ctx = ot::pjrt_device_context_raw(d_args.addressable_devices[i]); + OT_CHECK(dev_ctx != nullptr); + ot_device_info_t dinfo = {}; + ot_device_geometry_t dgeom = {}; + OT_CHECK(ot_device_get_info(dev_ctx, &dinfo) == OT_OK); + OT_CHECK(ot_device_get_geometry(dev_ctx, &dgeom) == OT_OK); + OT_CHECK(dinfo.chip_gen == OT_CHIP_TPU7X); + OT_CHECK(dinfo.device_id == 0x0075u); + OT_CHECK(std::strcmp(dinfo.bdf, expected_bdfs[i]) == 0); + OT_CHECK(dgeom.logical_chiplets_per_pci_func == 2u); + OT_CHECK(dgeom.hbm_bytes_per_logical_chiplet == (96ULL << 30)); + + PJRT_Device_GetDescription_Args gd = {}; + gd.struct_size = PJRT_Device_GetDescription_Args_STRUCT_SIZE; + gd.device = d_args.addressable_devices[i]; + OT_CHECK(api->PJRT_Device_GetDescription(&gd) == nullptr); + + PJRT_DeviceDescription_Id_Args id_args = {}; + id_args.struct_size = PJRT_DeviceDescription_Id_Args_STRUCT_SIZE; + id_args.device_description = gd.device_description; + OT_CHECK(api->PJRT_DeviceDescription_Id(&id_args) == nullptr); + OT_CHECK(id_args.id == static_cast(i)); + + PJRT_DeviceDescription_Kind_Args k_args = {}; + k_args.struct_size = PJRT_DeviceDescription_Kind_Args_STRUCT_SIZE; + k_args.device_description = gd.device_description; + OT_CHECK(api->PJRT_DeviceDescription_Kind(&k_args) == nullptr); + OT_CHECK(std::string(k_args.device_kind, k_args.device_kind_size) == "TPU v7x"); + + PJRT_DeviceDescription_Attributes_Args attr_args = {}; + attr_args.struct_size = PJRT_DeviceDescription_Attributes_Args_STRUCT_SIZE; + attr_args.device_description = gd.device_description; + OT_CHECK(api->PJRT_DeviceDescription_Attributes(&attr_args) == nullptr); + OT_CHECK(attr_args.num_attributes == 2u); + bool saw_coords = false, saw_core = false; + for (size_t ai = 0; ai < attr_args.num_attributes; ++ai) { + const PJRT_NamedValue& a = attr_args.attributes[ai]; + std::string aname(a.name, a.name_size); + if (aname == "coords") { + OT_CHECK(a.type == PJRT_NamedValue_kInt64List && a.value_size == 3u); + OT_CHECK(a.int64_array_value[0] == expected_coords[i][0] && + a.int64_array_value[1] == expected_coords[i][1] && + a.int64_array_value[2] == expected_coords[i][2]); + saw_coords = true; + } else if (aname == "core_on_chip") { + OT_CHECK(a.type == PJRT_NamedValue_kInt64 && + a.int64_value == static_cast(i % 2)); + saw_core = true; + } + } + OT_CHECK(saw_coords && saw_core); + } + + std::vector def_assign(8u, -1); + PJRT_Client_DefaultDeviceAssignment_Args da_args = {}; + da_args.struct_size = PJRT_Client_DefaultDeviceAssignment_Args_STRUCT_SIZE; + da_args.client = c_args.client; + da_args.num_replicas = 8; + da_args.num_partitions = 1; + da_args.default_assignment = def_assign.data(); + da_args.default_assignment_size = def_assign.size(); + OT_CHECK(api->PJRT_Client_DefaultDeviceAssignment(&da_args) == nullptr); + for (size_t i = 0; i < 8u; ++i) { + OT_CHECK(def_assign[i] == static_cast(i)); + } + + PJRT_Client_Destroy_Args cd_args = {}; + cd_args.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE; + cd_args.client = c_args.client; + OT_CHECK(api->PJRT_Client_Destroy(&cd_args) == nullptr); + } + + // Reject malformed, whitespace-prefixed signed, or out-of-range OPENTPU_MOCK_DEVICE_ID + // consistently across both direct HAL ot_context_create() and PJRT_Client_Create(). + for (const char* bad_did : {"0x0075junk", "\n-18446744073709551499", "0x10075"}) { + unsetenv("OPENTPU_MOCK_TOPOLOGY"); + unsetenv("OPENTPU_MOCK_CHIP"); + setenv("OPENTPU_MOCK", "1", 1); + setenv("OPENTPU_MOCK_DEVICE_ID", bad_did, 1); + ot_config_t bad_hal_cfg = ot_config_default(); + bad_hal_cfg.mock_mode = 1; + ot_context_t* bad_hal_ctx = nullptr; + OT_CHECK(ot_context_create(&bad_hal_cfg, &bad_hal_ctx) != OT_OK && bad_hal_ctx == nullptr); + PJRT_Client_Create_Args bad_c = {}; + bad_c.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + PJRT_Error* bad_err = api->PJRT_Client_Create(&bad_c); + OT_CHECK(bad_err != nullptr); + PJRT_Error_GetCode_Args bad_gc = {}; + bad_gc.struct_size = PJRT_Error_GetCode_Args_STRUCT_SIZE; + bad_gc.error = bad_err; + OT_CHECK(api->PJRT_Error_GetCode(&bad_gc) == nullptr); + OT_CHECK(bad_gc.code == PJRT_Error_Code_INVALID_ARGUMENT); + destroy_pjrt_error(api, bad_err); + } + + // Reject tpu7x-4t-single + 0x0076 (2-fn device ID) on both HAL and PJRT, while + // tpu7x-4t-2fn (and tpu7x-4t + 0x0076) exposes 8 function BDFs (1 chiplet/fn, 768 GiB). + { + unsetenv("OPENTPU_MOCK_CHIP"); + setenv("OPENTPU_MOCK", "1", 1); + setenv("OPENTPU_MOCK_TOPOLOGY", "tpu7x-4t-single", 1); + setenv("OPENTPU_MOCK_DEVICE_ID", "0x0076", 1); + ot_config_t single_cfg = ot_config_default(); + single_cfg.mock_mode = 1; + ot_context_t* single_ctx = nullptr; + OT_CHECK(ot_context_create(&single_cfg, &single_ctx) != OT_OK && single_ctx == nullptr); + PJRT_Client_Create_Args s_c = {}; + s_c.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + PJRT_Error* s_err = api->PJRT_Client_Create(&s_c); + OT_CHECK(s_err != nullptr); + PJRT_Error_GetCode_Args s_gc = {}; + s_gc.struct_size = PJRT_Error_GetCode_Args_STRUCT_SIZE; + s_gc.error = s_err; + OT_CHECK(api->PJRT_Error_GetCode(&s_gc) == nullptr); + OT_CHECK(s_gc.code == PJRT_Error_Code_INVALID_ARGUMENT); + destroy_pjrt_error(api, s_err); + + unsetenv("OPENTPU_MOCK_DEVICE_ID"); + setenv("OPENTPU_MOCK_TOPOLOGY", "tpu7x-4t-2fn", 1); + PJRT_Client_Create_Args f2_c = {}; + f2_c.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + OT_CHECK(api->PJRT_Client_Create(&f2_c) == nullptr && f2_c.client != nullptr); + PJRT_Client_AddressableDevices_Args f2_ad = {}; + f2_ad.struct_size = PJRT_Client_AddressableDevices_Args_STRUCT_SIZE; + f2_ad.client = f2_c.client; + OT_CHECK(api->PJRT_Client_AddressableDevices(&f2_ad) == nullptr); + OT_CHECK(f2_ad.num_addressable_devices == 8u); + const char* two_fn_bdfs[8] = { + "0000:00:04.0", "0000:00:04.1", "0000:00:05.0", "0000:00:05.1", + "0000:00:06.0", "0000:00:06.1", "0000:00:07.0", "0000:00:07.1", + }; + uint64_t total_two_fn_hbm = 0; + for (size_t i = 0; i < 8u; ++i) { + const ot_context_t* dctx = ot::pjrt_device_context_raw(f2_ad.addressable_devices[i]); + ot_device_info_t dinfo = {}; + ot_device_geometry_t dgeom = {}; + OT_CHECK(ot_device_get_info(dctx, &dinfo) == OT_OK); + OT_CHECK(ot_device_get_geometry(dctx, &dgeom) == OT_OK); + OT_CHECK(std::strcmp(dinfo.bdf, two_fn_bdfs[i]) == 0); + OT_CHECK(dinfo.device_id == 0x0076u); + OT_CHECK(dgeom.logical_chiplets_per_pci_func == 1u); + total_two_fn_hbm += static_cast(dgeom.logical_chiplets_per_pci_func) * + dgeom.hbm_bytes_per_logical_chiplet; + } + OT_CHECK(total_two_fn_hbm == (768ULL << 30)); + PJRT_Client_Destroy_Args f2_cd = {}; + f2_cd.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE; + f2_cd.client = f2_c.client; + OT_CHECK(api->PJRT_Client_Destroy(&f2_cd) == nullptr); + + // Reject tpu7x-4t-2fn + 0x0063 consistently in BOTH HAL and PJRT. + setenv("OPENTPU_MOCK_DEVICE_ID", "0x0063", 1); + ot_context_t* bad_m_ctx = nullptr; + OT_CHECK(ot_context_create(&single_cfg, &bad_m_ctx) != OT_OK && bad_m_ctx == nullptr); + PJRT_Client_Create_Args bad_m_c = {}; + bad_m_c.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + PJRT_Error* bad_m_err = api->PJRT_Client_Create(&bad_m_c); + OT_CHECK(bad_m_err != nullptr); + destroy_pjrt_error(api, bad_m_err); + + // Unnamed OPENTPU_MOCK_DEVICE_ID=0x0076 resolves to 2-fn (1 chiplet/fn, + // distinct .0/.1 PCI function BDFs on 1 package in PJRT, and 1u on HAL). + unsetenv("OPENTPU_MOCK_TOPOLOGY"); + setenv("OPENTPU_MOCK_DEVICE_ID", "0x0076", 1); + ot_context_t* u76_ctx = nullptr; + OT_CHECK(ot_context_create(&single_cfg, &u76_ctx) == OT_OK && u76_ctx != nullptr); + ot_device_geometry_t u76_geom = {}; + OT_CHECK(ot_device_get_geometry(u76_ctx, &u76_geom) == OT_OK); + OT_CHECK(u76_geom.logical_chiplets_per_pci_func == 1u); + ot_context_destroy(u76_ctx); + + PJRT_Client_Create_Args u76_c = {}; + u76_c.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + OT_CHECK(api->PJRT_Client_Create(&u76_c) == nullptr && u76_c.client != nullptr); + PJRT_Client_AddressableDevices_Args u76_ad = {}; + u76_ad.struct_size = PJRT_Client_AddressableDevices_Args_STRUCT_SIZE; + u76_ad.client = u76_c.client; + OT_CHECK(api->PJRT_Client_AddressableDevices(&u76_ad) == nullptr); + OT_CHECK(u76_ad.num_addressable_devices == 2u); + ot_device_info_t u0_info = {}; + ot_device_info_t u1_info = {}; + ot_device_geometry_t u0_geom = {}; + OT_CHECK(ot_device_get_info(ot::pjrt_device_context_raw(u76_ad.addressable_devices[0]), &u0_info) == OT_OK); + OT_CHECK(ot_device_get_info(ot::pjrt_device_context_raw(u76_ad.addressable_devices[1]), &u1_info) == OT_OK); + OT_CHECK(ot_device_get_geometry(ot::pjrt_device_context_raw(u76_ad.addressable_devices[0]), &u0_geom) == OT_OK); + OT_CHECK(std::strcmp(u0_info.bdf, "0000:00:04.0") == 0); + OT_CHECK(std::strcmp(u1_info.bdf, "0000:00:04.1") == 0); + OT_CHECK(u0_geom.logical_chiplets_per_pci_func == 1u); + PJRT_Client_Destroy_Args u76_cd = {}; + u76_cd.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE; + u76_cd.client = u76_c.client; + OT_CHECK(api->PJRT_Client_Destroy(&u76_cd) == nullptr); + + // Explicit OPENTPU_MOCK_TOPOLOGY=tpu7x-4t-single rejects a non-zero PCI + // function BDF (.1) in both direct HAL and PJRT instead of silently + // overriding the single-fn profile. + unsetenv("OPENTPU_MOCK_DEVICE_ID"); + setenv("OPENTPU_MOCK_TOPOLOGY", "tpu7x-4t-single", 1); + ot_config_t dot1_cfg = single_cfg; + dot1_cfg.bdf = "0000:00:04.1"; + ot_context_t* dot1_ctx = nullptr; + OT_CHECK(ot_context_create(&dot1_cfg, &dot1_ctx) != OT_OK && dot1_ctx == nullptr); + dot1_cfg.bdf = "0000:00:04.0"; + OT_CHECK(ot_context_create(&dot1_cfg, &dot1_ctx) == OT_OK && dot1_ctx != nullptr); + ot_device_geometry_t dot0_geom = {}; + OT_CHECK(ot_device_get_geometry(dot1_ctx, &dot0_geom) == OT_OK); + OT_CHECK(dot0_geom.logical_chiplets_per_pci_func == 2u); + ot_context_destroy(dot1_ctx); + } + + unsetenv("OPENTPU_MOCK_DEVICE_ID"); + unsetenv("OPENTPU_MOCK_TOPOLOGY"); + unsetenv("OPENTPU_MOCK_CHIP"); + unsetenv("OPENTPU_MOCK"); + printf("[PASS] test_pjrt_single_chiplet_tpu7x_enumeration\n"); +} + static void test_pjrt_multidevice_isolation_and_topology() { const PJRT_Api* api = GetPjrtApi(); OT_CHECK(api != nullptr); @@ -3216,7 +3478,7 @@ static void test_pjrt_multidevice_isolation_and_topology() { } // 8. Conflicting mock topology + device ID / chip selectors must fail with INVALID_ARGUMENT, - // while matching guest Ironwood VFIO ID (0x0076) + tpu7x-4t succeeds consistently. + // while matching provisional 0x0076 2-fn Ironwood candidate + tpu7x-4t succeeds consistently. { setenv("OPENTPU_MOCK", "1", 1); unsetenv("OPENTPU_MOCK_CHIP"); @@ -3252,12 +3514,182 @@ static void test_pjrt_multidevice_isolation_and_topology() { ot_device_info_t dinfo = {}; OT_CHECK(ot_device_get_info(ot::pjrt_device_context_raw(ad.addressable_devices[0]), &dinfo) == OT_OK); OT_CHECK(dinfo.chip_gen == OT_CHIP_TPU7X && dinfo.device_id == 0x0076u); + const ot_context_t* dev1_ctx = ot::pjrt_device_context_raw(ad.addressable_devices[1]); + OT_CHECK(dev1_ctx != nullptr && dev1_ctx->cfg.bdf == dev1_ctx->info.bdf && + std::strcmp(dev1_ctx->cfg.bdf, "0000:00:04.1") == 0); PJRT_Client_Destroy_Args cd = {}; cd.struct_size = PJRT_Client_Destroy_Args_STRUCT_SIZE; cd.client = cc_ok.client; OT_CHECK(api->PJRT_Client_Destroy(&cd) == nullptr); unsetenv("OPENTPU_MOCK_DEVICE_ID"); + + // Unrecognized OPENTPU_MOCK_TOPOLOGY / OPENTPU_MOCK_CHIP must fail closed (never silently fall back to v5e). + unsetenv("OPENTPU_MOCK_CHIP"); + unsetenv("OPENTPU_MOCK_DEVICE_ID"); + setenv("OPENTPU_MOCK_TOPOLOGY", "tpu7x-4t-2f", 1); + ot_context_t* typo_ctx = nullptr; + ot_config_t typo_cfg = ot_config_default(); + typo_cfg.mock_mode = 1; + OT_CHECK(ot_context_create(&typo_cfg, &typo_ctx) == OT_ERR_DEVICE && typo_ctx == nullptr); + OT_CHECK(ot_context_last_error(nullptr) != nullptr && + std::strstr(ot_context_last_error(nullptr), "unrecognized OPENTPU_MOCK_TOPOLOGY") != nullptr); + PJRT_Client_Create_Args cc_typo_topo = {}; + cc_typo_topo.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + PJRT_Error* err_typo_topo = api->PJRT_Client_Create(&cc_typo_topo); + OT_CHECK(err_typo_topo != nullptr && get_err_code(err_typo_topo) == PJRT_Error_Code_INVALID_ARGUMENT); + OT_CHECK(cc_typo_topo.client == nullptr); + destroy_pjrt_error(api, err_typo_topo); + + unsetenv("OPENTPU_MOCK_TOPOLOGY"); + setenv("OPENTPU_MOCK_CHIP", "tpu7xx", 1); + OT_CHECK(ot_context_create(&typo_cfg, &typo_ctx) == OT_ERR_DEVICE && typo_ctx == nullptr); + OT_CHECK(ot_context_last_error(nullptr) != nullptr && + std::strstr(ot_context_last_error(nullptr), "unrecognized OPENTPU_MOCK_CHIP") != nullptr); + PJRT_Client_Create_Args cc_typo_chip = {}; + cc_typo_chip.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + PJRT_Error* err_typo_chip = api->PJRT_Client_Create(&cc_typo_chip); + OT_CHECK(err_typo_chip != nullptr && get_err_code(err_typo_chip) == PJRT_Error_Code_INVALID_ARGUMENT); + OT_CHECK(cc_typo_chip.client == nullptr); + destroy_pjrt_error(api, err_typo_chip); + unsetenv("OPENTPU_MOCK_CHIP"); + + // R13-17: Unsupported numeric OPENTPU_MOCK_DEVICE_ID must fail closed. + setenv("OPENTPU_MOCK_DEVICE_ID", "0x0077", 1); + OT_CHECK(ot_context_create(&typo_cfg, &typo_ctx) == OT_ERR_DEVICE && typo_ctx == nullptr); + PJRT_Client_Create_Args cc_bad_did2 = {}; + cc_bad_did2.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + PJRT_Error* err_bad_did2 = api->PJRT_Client_Create(&cc_bad_did2); + OT_CHECK(err_bad_did2 != nullptr && get_err_code(err_bad_did2) == PJRT_Error_Code_INVALID_ARGUMENT); + OT_CHECK(cc_bad_did2.client == nullptr); + destroy_pjrt_error(api, err_bad_did2); + unsetenv("OPENTPU_MOCK_DEVICE_ID"); + + // R13-18: Conflicting duplicate visible_devices / allowed_devices options must fail closed. + int64_t vis_neg = -1; + int64_t vis_ok = 0; + PJRT_NamedValue vis_pair[2] = {}; + vis_pair[0].struct_size = PJRT_NamedValue_STRUCT_SIZE; + vis_pair[0].name = "visible_devices"; + vis_pair[0].name_size = std::strlen(vis_pair[0].name); + vis_pair[0].type = PJRT_NamedValue_kInt64List; + vis_pair[0].int64_array_value = &vis_neg; + vis_pair[0].value_size = 1; + vis_pair[1].struct_size = PJRT_NamedValue_STRUCT_SIZE; + vis_pair[1].name = "allowed_devices"; + vis_pair[1].name_size = std::strlen(vis_pair[1].name); + vis_pair[1].type = PJRT_NamedValue_kInt64List; + vis_pair[1].int64_array_value = &vis_ok; + vis_pair[1].value_size = 1; + PJRT_Client_Create_Args cc_dup_vis = {}; + cc_dup_vis.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + cc_dup_vis.create_options = vis_pair; + cc_dup_vis.num_options = 2; + PJRT_Error* err_dup_vis = api->PJRT_Client_Create(&cc_dup_vis); + OT_CHECK(err_dup_vis != nullptr && get_err_code(err_dup_vis) == PJRT_Error_Code_INVALID_ARGUMENT); + OT_CHECK(cc_dup_vis.client == nullptr); + destroy_pjrt_error(api, err_dup_vis); + + // Reject oversized visible_devices list (> 64) before copying or quadratic dedupe. + std::vector oversized_vis(65, 0); + for (size_t i = 0; i < oversized_vis.size(); ++i) oversized_vis[i] = static_cast(i); + PJRT_NamedValue vis_opt = {}; + vis_opt.struct_size = PJRT_NamedValue_STRUCT_SIZE; + vis_opt.name = "visible_devices"; + vis_opt.name_size = std::strlen(vis_opt.name); + vis_opt.type = PJRT_NamedValue_kInt64List; + vis_opt.int64_array_value = oversized_vis.data(); + vis_opt.value_size = oversized_vis.size(); + PJRT_Client_Create_Args cc_big = {}; + cc_big.struct_size = PJRT_Client_Create_Args_STRUCT_SIZE; + cc_big.create_options = &vis_opt; + cc_big.num_options = 1; + PJRT_Error* err_big = api->PJRT_Client_Create(&cc_big); + OT_CHECK(err_big != nullptr); + OT_CHECK(cc_big.client == nullptr); + destroy_pjrt_error(api, err_big); + + // Sysfs layout probe enforces shared [0, 65535] runtime chip_id contract. + char sysfs_tmpl[] = "/tmp/ot_probe_sysfs_XXXXXX"; + char* sysfs_dir = ::mkdtemp(sysfs_tmpl); + OT_CHECK(sysfs_dir != nullptr); + auto write_bytes = [](const std::string& p, const char* content, size_t n) { + int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + OT_CHECK(fd >= 0); + OT_CHECK(::write(fd, content, n) == static_cast(n)); + ::close(fd); + }; + auto write_text = [&](const std::string& p, const char* content) { + write_bytes(p, content, std::strlen(content)); + }; + const std::string d0 = std::string(sysfs_dir) + "/0000:00:04.0"; + const std::string d1 = std::string(sysfs_dir) + "/0000:00:05.0"; + OT_CHECK(::mkdir(d0.c_str(), 0700) == 0); + OT_CHECK(::mkdir(d1.c_str(), 0700) == 0); + for (const auto& d : {d0, d1}) { + write_text(d + "/vendor", "0x1ae0\n"); + write_text(d + "/device", "0x0075\n"); + write_text(d + "/numa_node", "0\n"); + write_text(d + "/chip_id", "65536\n"); + } + OT_CHECK(!ot::probe_tpu7x_two_fn_layout_from_sysfs(sysfs_dir)); + std::string padded_over = std::string(255, '0') + "65536\n"; + write_text(d0 + "/chip_id", padded_over.c_str()); + write_text(d1 + "/chip_id", padded_over.c_str()); + OT_CHECK(!ot::probe_tpu7x_two_fn_layout_from_sysfs(sysfs_dir)); + write_text(d0 + "/chip_id", "000001\n"); + write_text(d1 + "/chip_id", "000001\n"); + OT_CHECK(!ot::probe_tpu7x_two_fn_layout_from_sysfs(sysfs_dir)); + write_text(d0 + "/chip_id", "\x0b" "1\x0c"); + write_text(d1 + "/chip_id", "\x0b" "1\x0c"); + OT_CHECK(!ot::probe_tpu7x_two_fn_layout_from_sysfs(sysfs_dir)); + const char nul_attr[] = {'1', '\0', 'j', 'u', 'n', 'k', '\n'}; + write_bytes(d0 + "/chip_id", nul_attr, sizeof(nul_attr)); + write_bytes(d1 + "/chip_id", nul_attr, sizeof(nul_attr)); + OT_CHECK(!ot::probe_tpu7x_two_fn_layout_from_sysfs(sysfs_dir)); + write_text(d0 + "/chip_id", "65535\n"); + write_text(d1 + "/chip_id", "65535\n"); + OT_CHECK(ot::probe_tpu7x_two_fn_layout_from_sysfs(sysfs_dir)); + + // R15-9: VFIO discovery refuses unvalidated 0x0075/0x0076 (0xff0000 or 0x120000) with explicit diagnostic. + const std::string fake_drv_root = std::string(sysfs_dir) + "/_drv"; + const std::string fake_vfio_drv = fake_drv_root + "/vfio-pci"; + const std::string fake_grp_root = std::string(sysfs_dir) + "/_grp"; + const std::string fake_grp0 = fake_grp_root + "/0"; + const std::string fake_grp1 = fake_grp_root + "/1"; + OT_CHECK(::mkdir(fake_drv_root.c_str(), 0700) == 0); + OT_CHECK(::mkdir(fake_vfio_drv.c_str(), 0700) == 0); + OT_CHECK(::mkdir(fake_grp_root.c_str(), 0700) == 0); + OT_CHECK(::mkdir(fake_grp0.c_str(), 0700) == 0); + OT_CHECK(::mkdir(fake_grp1.c_str(), 0700) == 0); + write_text(d0 + "/class", "0xff0000\n"); + write_text(d1 + "/device", "0x0076\n"); + write_text(d1 + "/class", "0x120000\n"); + OT_CHECK(::symlink(fake_vfio_drv.c_str(), (d0 + "/driver").c_str()) == 0); + OT_CHECK(::symlink(fake_grp0.c_str(), (d0 + "/iommu_group").c_str()) == 0); + OT_CHECK(::symlink(fake_vfio_drv.c_str(), (d1 + "/driver").c_str()) == 0); + OT_CHECK(::symlink(fake_grp1.c_str(), (d1 + "/iommu_group").c_str()) == 0); + ot::PciDiscoveryEntry disc_entry; + std::string disc_err; + OT_CHECK(!ot::discover_vfio_tpu_in_sysfs(sysfs_dir, "0000:00:04.0", &disc_entry, &disc_err)); + OT_CHECK(disc_err.find("Unsupported TPU PCI device 0000:00:04.0") != std::string::npos); + disc_err.clear(); + OT_CHECK(!ot::discover_vfio_tpu_in_sysfs(sysfs_dir, "0000:00:05.0", &disc_entry, &disc_err)); + OT_CHECK(disc_err.find("Unsupported TPU PCI device 0000:00:05.0") != std::string::npos); + OT_CHECK(disc_err.find("only validated v5e") != std::string::npos); + + for (const auto& d : {d0, d1}) { + for (const char* f : {"vendor", "device", "class", "numa_node", "chip_id", "driver", "iommu_group"}) { + ::unlink((d + "/" + f).c_str()); + } + ::rmdir(d.c_str()); + } + ::rmdir(fake_vfio_drv.c_str()); + ::rmdir(fake_drv_root.c_str()); + ::rmdir(fake_grp0.c_str()); + ::rmdir(fake_grp1.c_str()); + ::rmdir(fake_grp_root.c_str()); + ::rmdir(sysfs_dir); } unsetenv("OPENTPU_MOCK_TOPOLOGY"); @@ -3282,6 +3714,7 @@ int main() { test_mock_multitile_and_quant_matmul(); test_multigen_hal_geometry_and_rebar(); test_pjrt_dual_chiplet_tpu7x_enumeration(); + test_pjrt_single_chiplet_tpu7x_enumeration(); test_pjrt_multidevice_isolation_and_topology(); printf("ALL_HOST_TESTS_PASSED\n"); return 0; diff --git a/llama-cpp-cloudtpu/ggml-cloudtpu.cpp b/llama-cpp-cloudtpu/ggml-cloudtpu.cpp index a7e986dd..d439ec96 100644 --- a/llama-cpp-cloudtpu/ggml-cloudtpu.cpp +++ b/llama-cpp-cloudtpu/ggml-cloudtpu.cpp @@ -40,7 +40,7 @@ struct cloudtpu_env_config { int mock_devices = 1; cloudtpu::MockTopologyProfile mock_profile = cloudtpu::MockTopologyProfile::AUTO; bool mock_scramble_device_order = false; - int spmd_chips = 1; // 1 = default per-chip devices, 0 = opt-in auto (all rt.device_count()), >1 = explicit SPMD chip count + std::string spmd_chips_raw; // empty = default per-chip (1), "auto" = all, or positive int int spmd_min_rows = 256; // Minimum weight rows/cols to shard across SPMD chips int max_fuse_ops = 4096; // Max ops per fused StableHLO subgraph int verbose = 0; @@ -87,15 +87,8 @@ static cloudtpu_env_config load_env_config() { if (const char* v = std::getenv("CLOUDTPU_MOCK_SCRAMBLE_ORDER")) { cfg.mock_scramble_device_order = (std::atoi(v) != 0); } - if (const char* v = std::getenv("CLOUDTPU_SPMD_CHIPS")) { - if (std::strcmp(v, "auto") == 0 || std::strcmp(v, "AUTO") == 0) { - cfg.spmd_chips = 0; - } else { - const int parsed = std::atoi(v); - if (parsed >= 1) { - cfg.spmd_chips = parsed; - } - } + if (const char* v = std::getenv("CLOUDTPU_SPMD_CHIPS"); v && *v != '\0') { + cfg.spmd_chips_raw = v; } if (const char* v = std::getenv("CLOUDTPU_SPMD_MIN_ROWS")) { const int parsed = std::atoi(v); @@ -210,26 +203,9 @@ static cloudtpu_env_config load_env_config() { } static int resolve_spmd_chips(const cloudtpu_env_config& env, const cloudtpu::PjrtRuntime& rt) { - const int avail = rt.device_count(); - if (avail <= 0) { - throw std::runtime_error("no PJRT devices available"); - } - if (env.spmd_chips <= 0) { - // Explicit CLOUDTPU_SPMD_CHIPS=auto uses all available chips (up to 16). - return std::min(avail, 16); - } - if (env.spmd_chips > 16) { - throw std::runtime_error( - "CLOUDTPU_SPMD_CHIPS=" + std::to_string(env.spmd_chips) + - " exceeds supported SPMD maximum (16); available PJRT devices=" + - std::to_string(avail)); - } - if (env.spmd_chips > avail) { - throw std::runtime_error( - "CLOUDTPU_SPMD_CHIPS=" + std::to_string(env.spmd_chips) + - " exceeds available PJRT devices (" + std::to_string(avail) + ")"); - } - return env.spmd_chips; + return cloudtpu::resolve_spmd_chips_spec( + env.spmd_chips_raw.empty() ? nullptr : env.spmd_chips_raw.c_str(), + rt.device_count()); } struct cloudtpu_hot_env_cache { @@ -5858,7 +5834,6 @@ ggml_backend_t ggml_backend_cloudtpu_init_device(int device_index) { ctx->device_index = dc->device_index; ctx->spmd_chips = spmd; ctx->env = env; - ctx->env.spmd_chips = spmd; if (env.verbose > 0) { const auto& info = rt.device_info(dc->device_index); diff --git a/llama-cpp-cloudtpu/pjrt_runtime.cpp b/llama-cpp-cloudtpu/pjrt_runtime.cpp index fa43abef..9a2497be 100644 --- a/llama-cpp-cloudtpu/pjrt_runtime.cpp +++ b/llama-cpp-cloudtpu/pjrt_runtime.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -716,6 +717,46 @@ MockTopologyProfile parse_mock_topology_profile(const char* val) { return MockTopologyProfile::AUTO; } +int resolve_spmd_chips_spec(const char* raw_env, int available_devices) { + if (available_devices <= 0) { + throw std::runtime_error("no PJRT devices available"); + } + if (raw_env == nullptr || *raw_env == '\0') { + return 1; + } + int requested = 0; + if (std::strcmp(raw_env, "auto") == 0 || std::strcmp(raw_env, "AUTO") == 0) { + return std::min(available_devices, 16); + } + if (raw_env[0] < '0' || raw_env[0] > '9') { + throw std::runtime_error( + std::string("Invalid CLOUDTPU_SPMD_CHIPS=") + raw_env + + " (expected 'auto' or positive integer >= 1)"); + } + errno = 0; + char* end = nullptr; + const long parsed = std::strtol(raw_env, &end, 10); + if (errno != 0 || end == raw_env || *end != '\0' || parsed < 1 || + parsed > std::numeric_limits::max()) { + throw std::runtime_error( + std::string("Invalid CLOUDTPU_SPMD_CHIPS=") + raw_env + + " (expected 'auto' or positive integer >= 1)"); + } + requested = static_cast(parsed); + if (requested > 16) { + throw std::runtime_error( + "CLOUDTPU_SPMD_CHIPS=" + std::to_string(requested) + + " exceeds supported SPMD maximum (16); available PJRT devices=" + + std::to_string(available_devices)); + } + if (requested > available_devices) { + throw std::runtime_error( + "CLOUDTPU_SPMD_CHIPS=" + std::to_string(requested) + + " exceeds available PJRT devices (" + std::to_string(available_devices) + ")"); + } + return requested; +} + bool is_tpu7x_device_kind(const std::string& kind) { std::string lower; lower.reserve(kind.size()); diff --git a/llama-cpp-cloudtpu/pjrt_runtime.hpp b/llama-cpp-cloudtpu/pjrt_runtime.hpp index 7467cf84..a3948245 100644 --- a/llama-cpp-cloudtpu/pjrt_runtime.hpp +++ b/llama-cpp-cloudtpu/pjrt_runtime.hpp @@ -153,6 +153,10 @@ enum class MockTopologyProfile { MockTopologyProfile parse_mock_topology_profile(const char* val); +// Validates CLOUDTPU_SPMD_CHIPS ("auto", "AUTO", or strict unsigned integer >= 1) +// against backend maximum (16) and available PJRT devices. +int resolve_spmd_chips_spec(const char* raw_env, int available_devices); + struct PjrtDeviceInfo { int index = 0; int id = 0; diff --git a/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp b/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp index df9ae978..b5766295 100644 --- a/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp +++ b/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp @@ -6134,6 +6134,35 @@ void test_ggml_cgraph_odd_s4_shard_n() { #endif } +void test_ggml_cloudtpu_rejects_invalid_spmd_env(const char* argv0) { +#if !defined(_WIN32) && defined(CLOUDTPU_HAS_GGML) + std::fflush(stdout); + std::fflush(stderr); + for (const char* bad_val : {"1x", "9", "17"}) { + const pid_t pid = fork(); + CHECK_TRUE(pid >= 0, "fork for fresh-process invalid CLOUDTPU_SPMD_CHIPS rejection test"); + if (pid == 0) { + setenv("CLOUDTPU_MOCK", "1", 1); + setenv("CLOUDTPU_MOCK_PROFILE", "tpu7x-4t", 1); + setenv("CLOUDTPU_MOCK_DEVICES", "8", 1); + setenv("CLOUDTPU_SPMD_CHIPS", bad_val, 1); + if (argv0 && argv0[0] != '\0') { + const char* args[] = {argv0, "--check-invalid-spmd-init", nullptr}; + execvp(argv0, const_cast(args)); + } + ggml_backend_t be = ggml_backend_cloudtpu_init(); + _exit(be == nullptr ? 0 : 1); + } + int status = 0; + CHECK_TRUE(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0, + "fresh-process CLOUDTPU_SPMD_CHIPS invalid width must fail closed"); + } + std::printf(" [PASS] ggml-cloudtpu fresh-process init rejects invalid CLOUDTPU_SPMD_CHIPS ('1x', '9', '17')\n"); +#else + (void)argv0; +#endif +} + void test_ggml_cgraph_reshaped_host_cpy_and_q4_bitcast_view() { #if !defined(_WIN32) // 1) Bucketed CPY into a reshaped host view [1,1,5,32] over host root [1,5,4,8] @@ -7461,9 +7490,39 @@ void test_freetile_mosaic_lowering(cloudtpu::PjrtRuntime& rt) { std::printf(" [PASS] FreeTile Mosaic lowering (Q4_K_I4 S4/U4/F32-scales, Q4_0_I4 U4, Q6_K_SPLIT, fallback & dialect guard)\n"); } + +void test_resolve_spmd_chips_spec_standalone() { + auto expect_throw = [](const char* raw, int avail, const char* msg) { + bool threw = false; + try { + (void)cloudtpu::resolve_spmd_chips_spec(raw, avail); + } catch (const std::runtime_error&) { + threw = true; + } + CHECK_TRUE(threw, msg); + }; + CHECK_TRUE(cloudtpu::resolve_spmd_chips_spec(nullptr, 8) == 1, "unset CLOUDTPU_SPMD_CHIPS defaults to 1"); + CHECK_TRUE(cloudtpu::resolve_spmd_chips_spec("", 8) == 1, "empty CLOUDTPU_SPMD_CHIPS defaults to 1"); + CHECK_TRUE(cloudtpu::resolve_spmd_chips_spec("auto", 8) == 8, "auto uses all 8 available devices"); + CHECK_TRUE(cloudtpu::resolve_spmd_chips_spec("AUTO", 8) == 8, "AUTO uses all 8 available devices"); + CHECK_TRUE(cloudtpu::resolve_spmd_chips_spec("4", 8) == 4, "valid explicit SPMD width 4 accepted"); + expect_throw("1x", 8, "malformed '1x' rejected instead of atoi()==1"); + expect_throw("0", 8, "width 0 rejected"); + expect_throw("-1", 8, "negative width rejected"); + expect_throw(" 2", 8, "leading whitespace rejected"); + expect_throw("9", 8, "width 9 > avail=8 rejected"); + expect_throw("17", 16, "width 17 > max 16 rejected"); + std::printf(" [PASS] cloudtpu::resolve_spmd_chips_spec (standalone + strict width checks)\n"); +} } // namespace int main(int argc, char** argv) { +#ifdef CLOUDTPU_HAS_GGML + if (argc == 2 && std::strcmp(argv[1], "--check-invalid-spmd-init") == 0) { + ggml_backend_t be = ggml_backend_cloudtpu_init(); + return (be == nullptr) ? 0 : 1; + } +#endif bool fp8_parity_only = false; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--fp8-parity-only") == 0) { @@ -7555,12 +7614,14 @@ int main(int argc, char** argv) { test_one_graph_spmd_kv_donation(4); test_continuous_batching_padded_buckets(); test_freetile_mosaic_lowering(rt); + test_resolve_spmd_chips_spec_standalone(); #ifdef CLOUDTPU_HAS_GGML test_ggml_cgraph_odd_s4_shard_n(); test_ggml_cgraph_reshaped_host_cpy_and_q4_bitcast_view(); test_ggml_cgraph_one_graph_decode(); test_ggml_cgraph_continuous_batching_buckets(); test_ggml_cgraph_freetile_mosaic_fallback(); + test_ggml_cloudtpu_rejects_invalid_spmd_env(argv[0]); #endif const size_t py_maps = cloudtpu::count_libpython_mappings(); diff --git a/ops/tpu-cdi/README.md b/ops/tpu-cdi/README.md index 64a86efa..5f7e0dbe 100644 --- a/ops/tpu-cdi/README.md +++ b/ops/tpu-cdi/README.md @@ -89,7 +89,7 @@ docker run --rm \ python3 -c "import os; print(os.listdir('/dev/vfio'))" ``` -Note on IOMMU groups & stable selectors: single-function selectors use stable PCI BDF names (`freetpu.dev/tpu=pci-`) so a disappearing chip retires its selector instead of reassigning it to a different chip (annotated as `freetpu.dev/allocation-unit=single-chip` for 1-function-per-chip generations such as `v5e`/`v5p`/`v6e`, or `single-chiplet` for multi-function generations such as `tpu7x` Ironwood so individual chiplets are never counted as full physical chips). If multiple TPU chips share one `/dev/vfio/` node, `freetpu-cdi` exposes that group strictly as a single allocation unit (`freetpu.dev/tpu=group-pci-_`) plus `freetpu.dev/tpu=all`. If any TPU's IOMMU group also contains a non-TPU PCI device, `freetpu-cdi` fails closed rather than publishing any selector (including `all`) that would expose that non-TPU device. Live VFIO char `major:minor` numbers are tracked in `freetpu.dev/vfio-devnums` annotations (while omitted from `deviceNodes`) so `sync` detects unexpected drift and rewrites `/var/run/cdi/freetpu.json` to drop CDI v0.8.0's cached device numbers; before any planned VFIO/PCI unbind or rebind, always stop affected consumers, stop/pause `sync`, delete `/var/run/cdi/freetpu.json` and confirm runtime selector withdrawal, perform the rebind, and then regenerate or resume `sync`. +Note on IOMMU groups & stable selectors: single-function selectors use stable PCI BDF names (`freetpu.dev/tpu=pci-`) so a disappearing chip retires its selector instead of reassigning it to a different chip (annotated as `freetpu.dev/allocation-unit=single-chip` for 1-function-per-chip generations such as `v5e`/`v5p`/`v6e` and 1-function dual-chiplet `tpu7x` Ironwood, or `single-chiplet` when a 2-function-per-package layout is active—such as 2-fn `tpu7x` Ironwood—so individual half-package chiplets are never counted as full physical chips). If multiple TPU chips share one `/dev/vfio/` node, `freetpu-cdi` exposes that group strictly as a single allocation unit (`freetpu.dev/tpu=group-pci-_`) plus `freetpu.dev/tpu=all`. If any TPU's IOMMU group also contains a non-TPU PCI device, `freetpu-cdi` fails closed rather than publishing any selector (including `all`) that would expose that non-TPU device. Live VFIO char `major:minor` numbers are tracked in `freetpu.dev/vfio-devnums` annotations (while omitted from `deviceNodes`) so `sync` detects unexpected drift and rewrites `/var/run/cdi/freetpu.json` to drop CDI v0.8.0's cached device numbers; before any planned VFIO/PCI unbind or rebind, always stop affected consumers, stop/pause `sync`, delete `/var/run/cdi/freetpu.json` and confirm runtime selector withdrawal, perform the rebind, and then regenerate or resume `sync`. ## Kubernetes Manifests diff --git a/ops/tpu-cdi/freetpu_cdi.py b/ops/tpu-cdi/freetpu_cdi.py index bce6d7f5..1fb89a54 100755 --- a/ops/tpu-cdi/freetpu_cdi.py +++ b/ops/tpu-cdi/freetpu_cdi.py @@ -49,7 +49,7 @@ import sys import tempfile import time -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple # Default to CDI v0.6.0 — the minimum spec version needed for all generated # fields (annotations, deviceNodes.hostPath, env) and compatible with supported @@ -77,7 +77,7 @@ "0x006e": ("v6e-pf", "TPU v6e (PF)"), "0x006f": ("v6e", "TPU v6e (Trillium)"), "0x0075": ("tpu7x", "TPU tpu7x (Ironwood, pending live hardware confirmation #21)"), - "0x0076": ("tpu7x", "TPU tpu7x (Ironwood)"), + "0x0076": ("tpu7x", "TPU tpu7x (Ironwood, pending live hardware confirmation #21)"), } # CNCF CDI parser grammar (ValidateVendorName / ValidateClassName): @@ -107,13 +107,51 @@ {"closID", "l3CacheSchema", "memBwSchema", "schemata", "enableMonitoring"} ) _ALLOWED_NET_DEVICE_KEYS = frozenset({"hostInterfaceName", "name"}) -# PCI functions (chiplets/cores) exposed per physical TPU chip. -# Ironwood (`tpu7x`: 0x0075/0x0076) and legacy v2/v3 (`0x0027`) expose 2 PCI -# functions per physical chip; single-function generations default to 1. +# Default PCI functions exposed per physical TPU chip when no per-host +# `0x0075` 1-fn-per-package vs 2-fn-per-package inventory distinction applies. +# Ironwood (`tpu7x`) supports both 2-fn (`0x0076` or paired `0x0075`) and +# 1-fn (`4 x 1-fn` dual-chiplet `0x0075`) layouts via `_resolve_pci_functions_per_chip`. _PCI_FUNCTIONS_PER_PHYSICAL_CHIP: Dict[str, int] = { "v2-v3": 2, "tpu7x": 2, } + +# Dual-chiplet topology metadata per generation (Issue #21, Ironwood Day-1): +# `chiplets_per_pkg` = logical TensorCore chiplets per physical package (2 on +# tpu7x Ironwood, 1 otherwise); `hbm_gib_per_logical_device` = HBM3e GiB per +# logical device (96 GiB on tpu7x: 192 GiB/package / 2 chiplets). +# `0x1ae0:0x0075` is provisional pending Day-1 `lspci -nn` capture. +TPU_CHIPLETS_PER_PKG: Dict[str, int] = { + "tpu7x": 2, +} +TPU_HBM_GIB_PER_LOGICAL_DEVICE: Dict[str, int] = { + "tpu7x": 96, + "v5e": 16, + "v6e": 32, + "v6e-pf": 32, + "v5p": 95, + "v4": 32, + "v4lite": 8, +} + + +def tpu_topology_metadata(generation: object) -> Dict[str, Optional[int]]: + """Return `{'chiplets_per_pkg': int, 'hbm_gib_per_logical_device': int|None}`.""" + # Fail-closed: any non-str or unhashable generation defaults to 1/None. + if not isinstance(generation, str): + return {"chiplets_per_pkg": 1, "hbm_gib_per_logical_device": None} + gen = generation + try: + chiplets = TPU_CHIPLETS_PER_PKG.get(gen, 1) + hbm = TPU_HBM_GIB_PER_LOGICAL_DEVICE.get(gen) + except TypeError: + return {"chiplets_per_pkg": 1, "hbm_gib_per_logical_device": None} + return { + "chiplets_per_pkg": chiplets, + "hbm_gib_per_logical_device": hbm, + } + + _SYSFS_PCI_ROOT_RE = re.compile(r"^pci([0-9a-fA-F]{4,}:[0-9a-fA-F]{2})\Z") _ALLOWED_HOOK_NAMES = frozenset( { @@ -433,16 +471,33 @@ def _parse_numa_node(pci_entry: Path) -> Optional[int]: return val if val >= 0 else None +def _parse_bounded_ascii_uint(raw_val: Any) -> Optional[int]: + """Parse an ASCII non-negative decimal ordinal in `[0, 65535]` without raising.""" + if ( + not isinstance(raw_val, str) + or not raw_val + or len(raw_val) > 5 + or not raw_val.isascii() + or not raw_val.isdigit() + ): + return None + val = int(raw_val, 10) + return val if 0 <= val <= 65535 else None + + def _parse_runtime_chip_id(pci_entry: Path) -> Optional[int]: - """Read optional sysfs `chip_id` integer when exported by the kernel driver.""" - raw = _read_text(pci_entry / "chip_id") - if raw is None: + """Read optional sysfs `chip_id` integer in `[0, 65535]` when exported by the kernel driver.""" + try: + raw = (pci_entry / "chip_id").read_bytes() + except OSError: + return None + if b"\x00" in raw: return None try: - val = int(raw, 10) - except ValueError: + text = raw.decode("ascii") + except UnicodeDecodeError: return None - return val if val >= 0 else None + return _parse_bounded_ascii_uint(text.strip(" \t\r\n")) _PCI_BDF_CANON_RE = re.compile(r"^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$") @@ -493,13 +548,20 @@ def _load_chip_id_map(raw: Optional[str]) -> Optional[Dict[str, int]]: seen_norm[norm_cmp] = k if isinstance(v, bool): raise ValueError(f"Invalid --chip-id-map value for {k!r}: boolean is not a chip ID") - if isinstance(v, str) and v.strip().isdigit(): - iv = int(v.strip(), 10) - elif isinstance(v, int) and v >= 0: + if isinstance(v, str): + parsed_iv = _parse_bounded_ascii_uint(v.strip()) + if parsed_iv is None: + raise ValueError( + f"Invalid --chip-id-map value {v!r} for {k!r}: " + "expected ASCII integer in [0, 65535]" + ) + iv = parsed_iv + elif isinstance(v, int) and 0 <= v <= 65535: iv = v else: raise ValueError( - f"Invalid --chip-id-map value {v!r} for {k!r}: must be a non-negative integer" + f"Invalid --chip-id-map value {v!r} for {k!r}: " + "must be an integer in [0, 65535]" ) result[norm_cmp] = iv return result @@ -1109,58 +1171,408 @@ def _format_vfio_devnums(entries: Sequence[Tuple[str, Optional[str]]]) -> Option return ",".join(f"{cp}={dn}" for cp, dn in pairs) +def _resolve_tpu7x_pci_functions_per_chip( + chips: Sequence[DiscoveredChip], + *, + chip_id_map: Optional[Dict[str, int]] = None, + host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, + observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + observed_bdf_generations: Optional[Dict[str, str]] = None, + spec_generations: Optional[Sequence[str]] = None, + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, + observed_tpu7x_two_fn: bool = False, +) -> int: + """Return expected PCI functions per physical package for Ironwood (`tpu7x`). + + Returns `2` for 2-function-per-package layouts (provisional `0x0076` + 2-fn candidate pending Day-1 `lspci -nn` capture, non-`.0` PCI functions, + >4 `tpu7x` PCI functions, multifunction slot siblings, same-domain shared + sibling `chip_id`/`--chip-id-map` pairs, or same-boot persisted 2-fn + history) and `1` for pure provisional `0x0075` 1-function dual-chiplet + hosts (`4 x 1-fn`). + """ + inv = host_pci_inventory if host_pci_inventory is not None else chips + tpu7x_inv = [c for c in inv if c.generation == "tpu7x"] + if not tpu7x_inv: + return _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get("tpu7x", 2) + if (observed_tpu7x_two_fn or getattr(observed_domain_bdfs, "tpu7x_two_fn", False)) and ( + spec_generations is None or "tpu7x" in spec_generations + ): + return 2 + if any(c.device_id == "0x0076" for c in tpu7x_inv): + return 2 + if any(not c.pci_bdf.endswith(".0") for c in tpu7x_inv): + return 2 + if len(tpu7x_inv) > 4: + return 2 + + slot_counts: Dict[str, int] = {} + sysfs_rid_counts: Dict[Tuple[Tuple[str, Optional[int], str], int], int] = {} + map_rid_counts: Dict[Tuple[Tuple[str, Optional[int], str], int], int] = {} + inv_by_bdf = {c.pci_bdf: c for c in tpu7x_inv} + non_tpu7x_bdfs: set[str] = {c.pci_bdf for c in inv if c.generation != "tpu7x"} + if observed_bdf_generations: + non_tpu7x_bdfs.update( + bdf for bdf, gen in observed_bdf_generations.items() if gen and gen != "tpu7x" + ) + tpu7x_domains = {_topology_domain_key(c) for c in tpu7x_inv} + tpu7x_roots = {c.pcie_root or _pcie_root_complex(c.pci_bdf) for c in tpu7x_inv} + live_slot_doms: Dict[str, set[Tuple[str, Optional[int], str]]] = {} + live_bus_roots: Dict[Tuple[str, int], set[str]] = {} + live_bus_doms: Dict[Tuple[str, int], set[Tuple[str, Optional[int], str]]] = {} + live_root_doms: Dict[str, set[Tuple[str, Optional[int], str]]] = {} + for c in tpu7x_inv: + base_slot = c.pci_bdf.rsplit(".", 1)[0] + slot_counts[base_slot] = slot_counts.get(base_slot, 0) + 1 + dkey = _topology_domain_key(c) + c_root = dkey[2] + live_slot_doms.setdefault(base_slot, set()).add(dkey) + live_root_doms.setdefault(c_root, set()).add(dkey) + parsed_cb = _parse_pci_domain_bus(c.pci_bdf) + if parsed_cb is not None: + live_bus_roots.setdefault(parsed_cb, set()).add(c_root) + live_bus_doms.setdefault(parsed_cb, set()).add(dkey) + if c.runtime_chip_id is not None: + rid = int(c.runtime_chip_id) + sysfs_rid_counts[(dkey, rid)] = sysfs_rid_counts.get((dkey, rid), 0) + 1 + if chip_id_map and c.pci_bdf in chip_id_map: + mid = int(chip_id_map[c.pci_bdf]) + map_rid_counts[(dkey, mid)] = map_rid_counts.get((dkey, mid), 0) + 1 + + if ( + any(cnt >= 2 for cnt in slot_counts.values()) + or any(cnt >= 2 for cnt in sysfs_rid_counts.values()) + or any(cnt >= 2 for cnt in map_rid_counts.values()) + ): + return 2 + + if chip_id_map: + tpu7x_map_bdfs = {b for b in chip_id_map if b not in non_tpu7x_bdfs} + obs_bdf_domains: Dict[str, set[Tuple[str, Optional[int], str]]] = {} + if observed_domain_bdfs: + for d_k, b_s in observed_domain_bdfs.items(): + for b_item in b_s: + obs_bdf_domains.setdefault(b_item, set()).add(d_k) + + def _place_absent_map_bdf( + bdf: str, + ) -> Optional[Tuple[Tuple[str, Optional[int], str], ...]]: + slot = bdf.rsplit(".", 1)[0] + if slot in live_slot_doms: + return tuple(sorted(live_slot_doms[slot])) + doms = obs_bdf_domains.get(bdf, set()) + matched_obs_doms = doms & tpu7x_domains + if matched_obs_doms: + return tuple(sorted(matched_obs_doms)) + obs_matching_roots = sorted({d[2] for d in doms if d[2] in tpu7x_roots}) + if len(obs_matching_roots) == 1: + placed_root: Optional[str] = obs_matching_roots[0] + else: + parsed_cb = _parse_pci_domain_bus(bdf) + placed_root = None + b_bridge_roots = ( + bridge_bus_to_roots.get(parsed_cb, set()) + if bridge_bus_to_roots and parsed_cb is not None + else set() + ) + if b_bridge_roots: + if len(b_bridge_roots) == 1: + cand = next(iter(b_bridge_roots)) + if cand in tpu7x_roots: + placed_root = cand + else: + if ( + parsed_cb is not None + and len(live_bus_roots.get(parsed_cb, set())) == 1 + ): + cand = next(iter(live_bus_roots[parsed_cb])) + if cand in tpu7x_roots: + placed_root = cand + elif not bdf.endswith(".0"): + cand = _pcie_root_complex(bdf) + if cand in tpu7x_roots: + placed_root = cand + if placed_root is None: + return None + if ( + parsed_cb is not None + and len(live_bus_doms.get(parsed_cb, set())) == 1 + ): + return (next(iter(live_bus_doms[parsed_cb])),) + if len(live_root_doms.get(placed_root, set())) == 1: + return (next(iter(live_root_doms[placed_root])),) + return (("pcie", None, placed_root),) + + placed_absent: Dict[str, Tuple[Tuple[str, Optional[int], str], ...]] = {} + relevant_map_bdfs: set[str] = set() + for b in tpu7x_map_bdfs: + if b in inv_by_bdf: + relevant_map_bdfs.add(b) + continue + doms = _place_absent_map_bdf(b) + if doms: + placed_absent[b] = doms + relevant_map_bdfs.add(b) + map_and_inv_bdfs = {c.pci_bdf for c in tpu7x_inv} | relevant_map_bdfs + if len(map_and_inv_bdfs) > 4 or any(not b.endswith(".0") for b in map_and_inv_bdfs): + return 2 + map_slots: Dict[str, int] = {} + dom_mid_counts: Dict[Tuple[Tuple[str, Optional[int], str], int], int] = {} + for bdf in map_and_inv_bdfs: + slot = bdf.rsplit(".", 1)[0] + map_slots[slot] = map_slots.get(slot, 0) + 1 + if bdf in chip_id_map and bdf not in non_tpu7x_bdfs: + mid = int(chip_id_map[bdf]) + chip_obj = inv_by_bdf.get(bdf) + if chip_obj is not None: + dkey = _topology_domain_key(chip_obj) + dom_mid_counts[(dkey, mid)] = dom_mid_counts.get((dkey, mid), 0) + 1 + else: + for dkey in placed_absent.get(bdf, ()): + dom_mid_counts[(dkey, mid)] = dom_mid_counts.get((dkey, mid), 0) + 1 + if any(cnt >= 2 for cnt in map_slots.values()) or any( + cnt >= 2 for cnt in dom_mid_counts.values() + ): + return 2 + + if observed_domain_bdfs and (spec_generations is None or "tpu7x" in spec_generations): + all_bdfs = {c.pci_bdf for c in tpu7x_inv} + live_tpu7x_slots = {c.pci_bdf.rsplit(".", 1)[0] for c in tpu7x_inv} + live_gens_set = {c.generation for c in inv} + spec_gens_all = {g for g in (spec_generations or []) if g} + pure_tpu7x_host = live_gens_set == {"tpu7x"} and ( + not spec_gens_all or spec_gens_all == {"tpu7x"} + ) + for obs_dkey, obs_bdfs in observed_domain_bdfs.items(): + # Scope unannotated historical BDFs to domains/roots belonging to + # live tpu7x chips (plus unplaced legacy entries) and ignore known + # or potentially non-tpu7x endpoints from mixed-generation specs so + # departed v5e/v6e devices never taint tpu7x. + if ( + obs_dkey != _UNPLACED_OBSERVED_DOMAIN_KEY + and obs_dkey not in tpu7x_domains + and obs_dkey[2] not in tpu7x_roots + ): + continue + for b in obs_bdfs: + if b in non_tpu7x_bdfs: + continue + obs_b_gen = observed_bdf_generations.get(b) if observed_bdf_generations else None + if ( + obs_b_gen == "tpu7x" + or b in inv_by_bdf + or b.rsplit(".", 1)[0] in live_tpu7x_slots + or pure_tpu7x_host + ): + all_bdfs.add(b) + if len(all_bdfs) > 4 or any(not b.endswith(".0") for b in all_bdfs): + return 2 + obs_slots: Dict[str, int] = {} + for bdf in all_bdfs: + slot = bdf.rsplit(".", 1)[0] + obs_slots[slot] = obs_slots.get(slot, 0) + 1 + if any(cnt >= 2 for cnt in obs_slots.values()): + return 2 + + return 1 + + +def _resolve_pci_functions_per_chip( + chips: Sequence[DiscoveredChip], + *, + chip_id_map: Optional[Dict[str, int]] = None, + host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, + observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + observed_bdf_generations: Optional[Dict[str, str]] = None, + spec_generations: Optional[Sequence[str]] = None, + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, + observed_tpu7x_two_fn: bool = False, +) -> Dict[str, int]: + """Return expected PCI functions per physical package keyed by `pci_bdf`.""" + tpu7x_per_chip = _resolve_tpu7x_pci_functions_per_chip( + chips, + chip_id_map=chip_id_map, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=observed_domain_bdfs, + observed_bdf_generations=observed_bdf_generations, + spec_generations=spec_generations, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + inv = host_pci_inventory if host_pci_inventory is not None else chips + out: Dict[str, int] = {} + for c in list(inv) + list(chips): + if c.generation == "tpu7x": + out[c.pci_bdf] = tpu7x_per_chip + else: + out[c.pci_bdf] = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + return out + + +class _PhysicalChipMap(Dict[str, int]): + """Dictionary mapping `pci_bdf -> physical_chip_ordinal` carrying resolved expected function counts.""" + + def __init__( + self, + *args: Any, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, + bdf_to_generation: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + self.expected_fns_by_bdf: Dict[str, int] = dict(expected_fns_by_bdf or {}) + self.bdf_to_generation: Dict[str, str] = dict(bdf_to_generation or {}) + + def _map_physical_chip_indices( chips: Sequence[DiscoveredChip], *, chip_id_map: Optional[Dict[str, int]] = None, + host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, + observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, + observed_tpu7x_two_fn: bool = False, ) -> Dict[str, int]: """Map each discovered PCI BDF to its physical TPU chip ordinal (`0..N-1`). - Generations with 1 PCI function per physical chip (`v5e`, `v5p`, `v6e`, etc.) - map 1:1. Dual-function/chiplet generations (`tpu7x` Ironwood `0x0075`/`0x0076` - and legacy `v2-v3`) pair two PCI functions into one physical chip ONLY when an - explicit verified sibling relationship exists: + Generations with 1 PCI function per physical chip (`v5e`, `v5p`, `v6e`, and + `4 x 1-fn` dual-chiplet `0x0075` Ironwood) map 1:1. Dual-function generations + (`0x0076` / paired `0x0075` Ironwood and legacy `v2-v3`) pair two PCI + functions into one physical chip ONLY when an explicit verified sibling + relationship exists: - multifunction siblings sharing the exact same PCI slot `DDDD:BB:DD` (`slot_count == per_chip`), OR - multiple functions explicitly mapped to the SAME physical chip ID from sysfs `chip_id` or `--chip-id-map` within the same topology domain - (`rid_count == per_chip`). + (`rid_count == per_chip` across the full host PCI inventory). Distinct unique IDs are NEVER paired by integer division (since one surviving function per chip across 4 chips can expose unique physical IDs `0,1,2,3`), and unmatched functions are left as incomplete singletons so degraded chips cannot form bogus multi-chip slices. """ - bdf_to_phys: Dict[str, int] = {} + inv = host_pci_inventory if host_pci_inventory is not None else chips + per_chip_by_bdf = ( + expected_fns_by_bdf + if expected_fns_by_bdf is not None + else _resolve_pci_functions_per_chip( + chips, + chip_id_map=chip_id_map, + host_pci_inventory=inv, + observed_domain_bdfs=observed_domain_bdfs, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + ) + bdf_gens = {c.pci_bdf: c.generation for c in list(inv) + list(chips)} + bdf_to_phys = _PhysicalChipMap( + expected_fns_by_bdf=per_chip_by_bdf, + bdf_to_generation=bdf_gens, + ) slot_counts: Dict[Tuple[str, str], int] = {} for c in chips: base_slot = c.pci_bdf.rsplit(".", 1)[0] key = (c.generation, base_slot) slot_counts[key] = slot_counts.get(key, 0) + 1 + inv_slot_counts: Dict[Tuple[str, str], int] = {} + for c in inv: + base_slot = c.pci_bdf.rsplit(".", 1)[0] + key = (c.generation, base_slot) + inv_slot_counts[key] = inv_slot_counts.get(key, 0) + 1 + # Identify functions explicitly sharing the SAME physical chip ID within one - # topology domain (never pairing distinct unique IDs via integer division). - # Pass 1: preserve verified PCI-slot and shared sysfs `chip_id` pairs first - # so passing a logical per-function `--chip-id-map` (e.g. `0..7` on Ironwood - # where siblings share physical sysfs `chip_id` `0..3`) never masks the - # sysfs sibling relationship. - # Pass 2: for any remaining unresolved dual-function chiplets (including - # separate-slot chiplets whose sysfs `chip_id` is absent OR distinct per - # function), allow explicit `--chip-id-map` shared physical IDs to establish - # sibling pairs within the same topology domain. - shared_sysfs_counts: Dict[Tuple[str, int], int] = {} - shared_sysfs_domains: Dict[Tuple[str, int], set[Tuple[str, Optional[int], str]]] = {} - for c in chips: - per_chip = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + # topology domain across the full host PCI inventory (never pairing when an + # ID claim collides across sysfs chip_id and explicit --chip-id-map, has + # >per_chip claimants, or has any non-.0 claimant in that domain). + full_slot_rids: Dict[Tuple[str, Tuple[str, Optional[int], str], str], List[int]] = {} + for c in inv: + per_chip = per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + if per_chip <= 1: + continue + dom = _topology_domain_key(c) + base_slot = c.pci_bdf.rsplit(".", 1)[0] + if inv_slot_counts.get((c.generation, base_slot), 0) >= per_chip and c.runtime_chip_id is not None: + full_slot_rids.setdefault((c.generation, dom, base_slot), []).append(int(c.runtime_chip_id)) + + all_sysfs_total: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + all_map_total: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + shared_sysfs_total: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + shared_sysfs_dot0: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + sysfs_rkey_per_chip: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + for c in inv: + per_chip = per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) if per_chip <= 1: continue + dom = _topology_domain_key(c) base_slot = c.pci_bdf.rsplit(".", 1)[0] - if slot_counts.get((c.generation, base_slot), 0) == per_chip: + slot_len = inv_slot_counts.get((c.generation, base_slot), 0) + if c.runtime_chip_id is not None: + sys_claim_id = int(c.runtime_chip_id) + if slot_len >= per_chip: + srids = full_slot_rids.get((c.generation, dom, base_slot), []) + if len(srids) == slot_len and len(set(srids)) == slot_len and len({r // per_chip for r in srids}) == 1: + # Distinct consecutive logical chiplet IDs on a full slot (e.g. 0,1 on 04.0/04.1) + # belong to physical package (r // per_chip), not separate package r. + sys_claim_id = srids[0] // per_chip + rkey = (c.generation, dom, sys_claim_id) + all_sysfs_total[rkey] = all_sysfs_total.get(rkey, 0) + 1 + if chip_id_map and c.pci_bdf in chip_id_map: + mkey = (c.generation, dom, int(chip_id_map[c.pci_bdf])) + all_map_total[mkey] = all_map_total.get(mkey, 0) + 1 + if slot_len >= per_chip: + continue + if c.runtime_chip_id is not None: + rkey = (c.generation, dom, int(c.runtime_chip_id)) + shared_sysfs_total[rkey] = shared_sysfs_total.get(rkey, 0) + 1 + if c.pci_bdf.endswith(".0"): + shared_sysfs_dot0[rkey] = shared_sysfs_dot0.get(rkey, 0) + 1 + sysfs_rkey_per_chip[rkey] = per_chip + + map_external_total: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + unmapped_sysfs_total: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + for c in inv: + per_chip = per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + if per_chip <= 1: continue + dom = _topology_domain_key(c) + base_slot = c.pci_bdf.rsplit(".", 1)[0] + full_slot = inv_slot_counts.get((c.generation, base_slot), 0) >= per_chip + has_sysfs_pair = ( + not full_slot + and c.pci_bdf.endswith(".0") + and c.runtime_chip_id is not None + and shared_sysfs_total.get((c.generation, dom, int(c.runtime_chip_id)), 0) == per_chip + and all_sysfs_total.get((c.generation, dom, int(c.runtime_chip_id)), 0) == per_chip + and shared_sysfs_dot0.get((c.generation, dom, int(c.runtime_chip_id)), 0) == per_chip + ) + if chip_id_map and c.pci_bdf in chip_id_map: + mid = int(chip_id_map[c.pci_bdf]) + mkey = (c.generation, dom, mid) + differs = (c.runtime_chip_id is None) or (int(c.runtime_chip_id) != mid) or full_slot + already_phys_paired = full_slot or has_sysfs_pair + if differs and (not already_phys_paired or all_map_total.get(mkey, 0) >= 2): + map_external_total[mkey] = map_external_total.get(mkey, 0) + 1 if c.runtime_chip_id is not None: - rkey = (c.generation, int(c.runtime_chip_id)) - shared_sysfs_counts[rkey] = shared_sysfs_counts.get(rkey, 0) + 1 - shared_sysfs_domains.setdefault(rkey, set()).add(_topology_domain_key(c)) + rkey = (c.generation, dom, int(c.runtime_chip_id)) + if full_slot or not (chip_id_map and c.pci_bdf in chip_id_map): + unmapped_sysfs_total[rkey] = unmapped_sysfs_total.get(rkey, 0) + 1 + + valid_sysfs_rkeys = { + rkey + for rkey, cnt in shared_sysfs_total.items() + if cnt == sysfs_rkey_per_chip[rkey] + and all_sysfs_total.get(rkey, 0) == sysfs_rkey_per_chip[rkey] + and map_external_total.get(rkey, 0) == 0 + and shared_sysfs_dot0.get(rkey, 0) == sysfs_rkey_per_chip[rkey] + } slot_to_phys: Dict[Tuple[str, str], int] = {} shared_rid_to_phys: Dict[Tuple[str, str, Tuple[str, Optional[int], str], int], int] = {} @@ -1168,7 +1580,9 @@ def _map_physical_chip_indices( unresolved_multi: List[DiscoveredChip] = [] for c in chips: - per_chip = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + per_chip = per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) if per_chip <= 1: bdf_to_phys[c.pci_bdf] = next_phys next_phys += 1 @@ -1176,20 +1590,22 @@ def _map_physical_chip_indices( base_slot = c.pci_bdf.rsplit(".", 1)[0] slot_key = (c.generation, base_slot) - if slot_counts.get(slot_key, 0) == per_chip: + if slot_counts.get(slot_key, 0) == per_chip and inv_slot_counts.get(slot_key, 0) == per_chip: if slot_key not in slot_to_phys: slot_to_phys[slot_key] = next_phys next_phys += 1 bdf_to_phys[c.pci_bdf] = slot_to_phys[slot_key] continue - if c.runtime_chip_id is not None: - rkey = (c.generation, int(c.runtime_chip_id)) - if ( - shared_sysfs_counts.get(rkey, 0) == per_chip - and len(shared_sysfs_domains.get(rkey, set())) == 1 - ): - vkey = ("sysfs", c.generation, _topology_domain_key(c), int(c.runtime_chip_id)) + if ( + c.pci_bdf.endswith(".0") + and c.runtime_chip_id is not None + and inv_slot_counts.get(slot_key, 0) < per_chip + ): + dom = _topology_domain_key(c) + rkey = (c.generation, dom, int(c.runtime_chip_id)) + if rkey in valid_sysfs_rkeys: + vkey = ("sysfs", c.generation, dom, int(c.runtime_chip_id)) if vkey not in shared_rid_to_phys: shared_rid_to_phys[vkey] = next_phys next_phys += 1 @@ -1199,24 +1615,64 @@ def _map_physical_chip_indices( unresolved_multi.append(c) if unresolved_multi: - shared_map_counts: Dict[Tuple[str, int], int] = {} - shared_map_domains: Dict[Tuple[str, int], set[Tuple[str, Optional[int], str]]] = {} + shared_map_total: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + shared_map_dot0: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} + map_mkey_per_chip: Dict[Tuple[str, Tuple[str, Optional[int], str], int], int] = {} if chip_id_map: - for c in unresolved_multi: + unresolved_inv = [ + c + for c in inv + if per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + > 1 + and inv_slot_counts.get( + (c.generation, c.pci_bdf.rsplit(".", 1)[0]), 0 + ) + < per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + and not ( + c.runtime_chip_id is not None + and (c.generation, _topology_domain_key(c), int(c.runtime_chip_id)) + in valid_sysfs_rkeys + ) + ] + for c in unresolved_inv: if c.pci_bdf in chip_id_map: - mkey = (c.generation, int(chip_id_map[c.pci_bdf])) - shared_map_counts[mkey] = shared_map_counts.get(mkey, 0) + 1 - shared_map_domains.setdefault(mkey, set()).add(_topology_domain_key(c)) + per_chip = per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + mkey = (c.generation, _topology_domain_key(c), int(chip_id_map[c.pci_bdf])) + shared_map_total[mkey] = shared_map_total.get(mkey, 0) + 1 + if c.pci_bdf.endswith(".0"): + shared_map_dot0[mkey] = shared_map_dot0.get(mkey, 0) + 1 + map_mkey_per_chip[mkey] = per_chip + + valid_map_mkeys = { + mkey + for mkey, cnt in shared_map_total.items() + if cnt == map_mkey_per_chip[mkey] + and all_map_total.get(mkey, 0) == map_mkey_per_chip[mkey] + and unmapped_sysfs_total.get(mkey, 0) == 0 + and shared_map_dot0.get(mkey, 0) == map_mkey_per_chip[mkey] + } for c in unresolved_multi: - per_chip = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) - if chip_id_map and c.pci_bdf in chip_id_map: - mkey = (c.generation, int(chip_id_map[c.pci_bdf])) - if ( - shared_map_counts.get(mkey, 0) == per_chip - and len(shared_map_domains.get(mkey, set())) == 1 - ): - vkey = ("map", c.generation, _topology_domain_key(c), int(chip_id_map[c.pci_bdf])) + per_chip = per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + slot_key = (c.generation, c.pci_bdf.rsplit(".", 1)[0]) + if ( + c.pci_bdf.endswith(".0") + and chip_id_map + and c.pci_bdf in chip_id_map + and inv_slot_counts.get(slot_key, 0) < per_chip + ): + dom = _topology_domain_key(c) + mkey = (c.generation, dom, int(chip_id_map[c.pci_bdf])) + if mkey in valid_map_mkeys: + vkey = ("map", c.generation, dom, int(chip_id_map[c.pci_bdf])) if vkey not in shared_rid_to_phys: shared_rid_to_phys[vkey] = next_phys next_phys += 1 @@ -1287,10 +1743,40 @@ def _is_supported_single_host_chip_count( return physical_chip_count in allowed +def _is_supported_all_domain_counts( + n_chips: int, + domain_phys_counts: List[int], + generations: Sequence[str], +) -> bool: + """Return True iff sorted per-domain complete chip counts satisfy single-host rules.""" + if not _is_supported_single_host_chip_count(n_chips, generations): + return False + norm_gens = {"v6e" if g == "v6e-pf" else g for g in generations if g} + if len(norm_gens) != 1: + return False + gen = next(iter(norm_gens)) + counts = sorted(c for c in domain_phys_counts if c > 0) + if sum(counts) != n_chips: + return False + if n_chips == 1: + return counts == [1] + if n_chips == 2: + return counts == [2] + if n_chips == 4: + if gen in ("tpu7x", "v5p"): + return counts in ([4], [2, 2]) + return counts == [4] + if n_chips == 8: + return counts in ([8], [4, 4]) + return False + + def _is_supported_all_topology( chips: Sequence[DiscoveredChip], bdf_to_phys: Dict[str, int], generations: Sequence[str], + *, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, ) -> bool: """Return True iff the live `all` chip set forms a verified single-host topology. @@ -1300,7 +1786,9 @@ def _is_supported_all_topology( its two NUMA roots, where a supported v6e-4 2x2 slice must sit within one NUMA/PCIe root domain). """ - if not chips or not _has_complete_chip_functions(chips, bdf_to_phys): + if not chips or not _has_complete_chip_functions( + chips, bdf_to_phys, expected_fns_by_bdf=expected_fns_by_bdf + ): return False n_chips = len(_distinct_physical_indices(chips, bdf_to_phys)) if not _is_supported_single_host_chip_count(n_chips, generations): @@ -1313,43 +1801,74 @@ def _is_supported_all_topology( len(_distinct_physical_indices(d_chips, bdf_to_phys)) for d_chips in domains.values() ) - - norm_gens = {"v6e" if g == "v6e-pf" else g for g in generations if g} - gen = next(iter(norm_gens)) - - if n_chips == 1: - return domain_phys_counts == [1] - if n_chips == 2: - return domain_phys_counts == [2] - if n_chips == 4: - if gen in ("tpu7x", "v5p"): - return domain_phys_counts in ([4], [2, 2]) - return domain_phys_counts == [4] - if n_chips == 8: - return domain_phys_counts in ([8], [4, 4]) - return False + return _is_supported_all_domain_counts(n_chips, domain_phys_counts, generations) def _count_complete_chips( subset: Sequence[DiscoveredChip], bdf_to_phys: Dict[str, int], + *, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, + chip_id_map: Optional[Dict[str, int]] = None, + host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, + observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, ) -> Tuple[int, int]: """Return `(complete_chip_count, incomplete_pci_function_count)` for `subset`. Only physical chips exposing their full expected PCI function set (e.g. - both chiplets on `tpu7x` Ironwood or legacy `v2-v3`) are counted in + 2 functions on 2-fn `tpu7x` / legacy `v2-v3`, or 1 function on 1-fn + dual-chiplet `0x0075` `tpu7x` and single-fn generations) are counted in `complete_chip_count`. Unpaired/orphaned functions are excluded from chip capacity and tallied in `incomplete_pci_function_count`. """ - counts_by_phys: Dict[int, Tuple[int, str]] = {} + if expected_fns_by_bdf is not None: + per_chip_by_bdf = expected_fns_by_bdf + elif isinstance(bdf_to_phys, _PhysicalChipMap) and bdf_to_phys.expected_fns_by_bdf: + per_chip_by_bdf = bdf_to_phys.expected_fns_by_bdf + else: + per_chip_by_bdf = _resolve_pci_functions_per_chip( + subset, + chip_id_map=chip_id_map, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=observed_domain_bdfs, + ) + groups_by_phys: Dict[int, List[DiscoveredChip]] = {} for c in subset: phys = bdf_to_phys[c.pci_bdf] - cnt, gen = counts_by_phys.get(phys, (0, c.generation)) - counts_by_phys[phys] = (cnt + 1, gen) + groups_by_phys.setdefault(phys, []).append(c) + + phys_total_members: Dict[int, int] = {} + for phys in bdf_to_phys.values(): + phys_total_members[phys] = phys_total_members.get(phys, 0) + 1 + + tpu7x_paired_in_map = False + if expected_fns_by_bdf is None: + if isinstance(bdf_to_phys, _PhysicalChipMap) and bdf_to_phys.bdf_to_generation: + tpu7x_paired_in_map = any( + bdf_to_phys.bdf_to_generation.get(b) == "tpu7x" + and phys_total_members.get(p, 0) >= 2 + for b, p in bdf_to_phys.items() + ) + elif host_pci_inventory is not None: + tpu7x_paired_in_map = any( + c.generation == "tpu7x" + and phys_total_members.get(bdf_to_phys.get(c.pci_bdf, -1), 0) >= 2 + for c in host_pci_inventory + ) + complete_chips = 0 incomplete_fns = 0 - for cnt, gen in counts_by_phys.values(): - expected = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(gen, 1) + for phys, grp in groups_by_phys.items(): + cnt = len(grp) + rep = grp[0] + expected = max( + per_chip_by_bdf.get( + rep.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(rep.generation, 1) + ), + phys_total_members.get(phys, cnt), + ) + if tpu7x_paired_in_map and rep.generation == "tpu7x": + expected = max(expected, 2) if cnt == expected: complete_chips += 1 else: @@ -1360,11 +1879,23 @@ def _count_complete_chips( def _has_complete_chip_functions( subset: Sequence[DiscoveredChip], bdf_to_phys: Dict[str, int], + *, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, + chip_id_map: Optional[Dict[str, int]] = None, + host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, + observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, ) -> bool: """Return True when every physical chip in `subset` exposes its full expected PCI function set.""" if not subset: return False - complete_chips, incomplete_fns = _count_complete_chips(subset, bdf_to_phys) + complete_chips, incomplete_fns = _count_complete_chips( + subset, + bdf_to_phys, + expected_fns_by_bdf=expected_fns_by_bdf, + chip_id_map=chip_id_map, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=observed_domain_bdfs, + ) return complete_chips > 0 and incomplete_fns == 0 @@ -1375,6 +1906,8 @@ def _resolve_verified_visibility_ordinals( *, chip_id_map: Optional[Dict[str, int]] = None, host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, + observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, ) -> Optional[Tuple[List[int], List[int]]]: """Return `(visible_chip_ordinals, visible_device_ordinals)` ONLY when verified. @@ -1390,22 +1923,103 @@ def _resolve_verified_visibility_ordinals( `TPU_VISIBLE_CHIPS` and `TPU_VISIBLE_DEVICES` and preserves workload-provided visibility settings. """ - if not subset or not _has_complete_chip_functions(subset, bdf_to_phys): + inventory_chips: Sequence[DiscoveredChip] = ( + host_pci_inventory if host_pci_inventory is not None else all_chips + ) + per_chip_by_bdf = ( + expected_fns_by_bdf + if expected_fns_by_bdf is not None + else _resolve_pci_functions_per_chip( + all_chips, + chip_id_map=chip_id_map, + host_pci_inventory=inventory_chips, + observed_domain_bdfs=observed_domain_bdfs, + ) + ) + if not subset or not _has_complete_chip_functions( + subset, + bdf_to_phys, + expected_fns_by_bdf=per_chip_by_bdf, + ): return None + def _bounded_vis( + chips_vis: List[int], devs_vis: List[int] + ) -> Optional[Tuple[List[int], List[int]]]: + if any(v < 0 or v > 65535 for v in chips_vis) or any( + v < 0 or v > 65535 for v in devs_vis + ): + return None + return chips_vis, devs_vis + def _raw_id(chip: DiscoveredChip) -> Optional[int]: if chip_id_map and chip.pci_bdf in chip_id_map: return chip_id_map[chip.pci_bdf] return chip.runtime_chip_id - inventory_chips: Sequence[DiscoveredChip] = ( - host_pci_inventory if host_pci_inventory is not None else all_chips + inv_bdf_to_phys_full = ( + _map_physical_chip_indices( + inventory_chips, + chip_id_map=chip_id_map, + host_pci_inventory=inventory_chips, + expected_fns_by_bdf=per_chip_by_bdf, + ) + if host_pci_inventory is not None or len(inventory_chips) != len(bdf_to_phys) + else bdf_to_phys ) + inv_phys_chips: Dict[int, List[DiscoveredChip]] = {} + for c in inventory_chips: + inv_phys_chips.setdefault(inv_bdf_to_phys_full[c.pci_bdf], []).append(c) + + logical_id_claimants: Dict[int, set[int]] = {} + for phys_idx, p_chips in inv_phys_chips.items(): + p_rep = p_chips[0] + p_per = per_chip_by_bdf.get( + p_rep.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(p_rep.generation, 1) + ) + p_chiplets = TPU_CHIPLETS_PER_PKG.get(p_rep.generation, 1) + p_rids = [_raw_id(pc) for pc in p_chips] + if p_per == 1: + for pr in p_rids: + if pr is not None: + for off in range(p_chiplets): + logical_id_claimants.setdefault(int(pr) * p_chiplets + off, set()).add( + phys_idx + ) + else: + non_none = [int(pr) for pr in p_rids if pr is not None] + if not non_none: + continue + if len(p_chips) == p_per and len(non_none) == p_per and len(set(non_none)) == 1: + only_p = non_none[0] + for off in range(p_per): + logical_id_claimants.setdefault(only_p * p_per + off, set()).add(phys_idx) + elif len(p_chips) == p_per and len(non_none) == p_per and len(set(non_none)) == len(non_none): + for lid in non_none: + logical_id_claimants.setdefault(lid, set()).add(phys_idx) + else: + for pr in non_none: + base_pair = (pr // p_per) * p_per + for off in range(p_per): + logical_id_claimants.setdefault(base_pair + off, set()).add(phys_idx) + logical_id_claimants.setdefault(pr * p_per + off, set()).add(phys_idx) + + tainted_phys = { + p + for owners in logical_id_claimants.values() + if len(owners) > 1 + for p in owners + } + if any(inv_bdf_to_phys_full[c.pci_bdf] in tainted_phys for c in subset): + return None subset_raw: List[Optional[int]] = [_raw_id(c) for c in subset] if all(rid is not None for rid in subset_raw): per_chip_set = { - _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) for c in subset + per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + for c in subset } if len(per_chip_set) == 1: per_chip = next(iter(per_chip_set)) @@ -1419,7 +2033,19 @@ def _raw_id(chip: DiscoveredChip) -> Optional[int]: # Every claimed runtime ID across the full host PCI inventory must be unique. if len(set(all_raw_by_bdf.values())) == len(all_raw_by_bdf): ords = sorted(int(rid) for rid in subset_raw if rid is not None) - return ords, list(ords) + chiplets_set = { + TPU_CHIPLETS_PER_PKG.get(c.generation, 1) for c in subset + } + if len(chiplets_set) == 1: + chiplets = next(iter(chiplets_set)) + if chiplets > 1: + logical = [ + p * chiplets + off + for p in ords + for off in range(chiplets) + ] + return _bounded_vis(ords, logical) + return _bounded_vis(ords, list(ords)) return None # Dual-function/chiplet generations (e.g. Ironwood per_chip=2): @@ -1428,20 +2054,33 @@ def _raw_id(chip: DiscoveredChip) -> Optional[int]: if len(set(sub_ids)) == len(sub_ids) and len(set(all_raw_by_bdf.values())) == len( all_raw_by_bdf ): + inv_bdf_to_phys_a = inv_bdf_to_phys_full + phys_to_logical_ids: Dict[int, List[int]] = {} + for c, rid in zip(subset, sub_ids): + phys_to_logical_ids.setdefault(inv_bdf_to_phys_a[c.pci_bdf], []).append(rid) phys_set = sorted({oid // per_chip for oid in sub_ids}) expected_logical = [ p * per_chip + off for p in phys_set for off in range(per_chip) ] - if sorted(sub_ids) == expected_logical: - return phys_set, expected_logical + pair_consistent = ( + len(phys_to_logical_ids) == len(phys_set) + and all( + len(grp_ids) == per_chip + and len({oid // per_chip for oid in grp_ids}) == 1 + and sorted(grp_ids) + == [ + (grp_ids[0] // per_chip) * per_chip + off + for off in range(per_chip) + ] + for grp_ids in phys_to_logical_ids.values() + ) + ) + if pair_consistent and sorted(sub_ids) == expected_logical: + return _bounded_vis(phys_set, expected_logical) return None # Case B: physical chip ID shared by both PCI functions of each chip. - inv_bdf_to_phys = ( - _map_physical_chip_indices(inventory_chips, chip_id_map=chip_id_map) - if host_pci_inventory is not None - else bdf_to_phys - ) + inv_bdf_to_phys = inv_bdf_to_phys_full phys_to_rids: Dict[int, set[int]] = {} for c in inventory_chips: rid = all_raw_by_bdf.get(c.pci_bdf) @@ -1459,7 +2098,7 @@ def _raw_id(chip: DiscoveredChip) -> Optional[int]: logical = [ p * per_chip + off for p in sub_phys for off in range(per_chip) ] - return sub_phys, logical + return _bounded_vis(sub_phys, logical) return None return None @@ -1491,16 +2130,19 @@ def _logical_device_indices( Ironwood, `v2-v3`), physical chip `c` exposes logical devices `2*c` and `2*c + 1` (e.g. physical chips `2,3` -> logical devices `4,5,6,7`). """ - per_chip_set = { - _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) for c in subset + chiplets_set = { + TPU_CHIPLETS_PER_PKG.get( + c.generation, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) + for c in subset } - if len(per_chip_set) == 1: - per_chip = next(iter(per_chip_set)) - if per_chip > 1: + if len(chiplets_set) == 1: + chiplets = next(iter(chiplets_set)) + if chiplets > 1: return [ - phys_idx * per_chip + offset + phys_idx * chiplets + offset for phys_idx in physical_chip_indices - for offset in range(per_chip) + for offset in range(chiplets) ] return [c.index for c in subset] @@ -1625,6 +2267,7 @@ def _compute_topology_slices( host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, + expected_fns_by_bdf: Optional[Dict[str, int]] = None, ) -> List[_TopologySlice]: """Compute valid single-domain NUMA / PCIe sub-host slices and their canonical aliases. @@ -1642,6 +2285,16 @@ def _compute_topology_slices( return [] full_inventory = host_pci_inventory if host_pci_inventory is not None else chips + per_chip_by_bdf = ( + expected_fns_by_bdf + if expected_fns_by_bdf is not None + else _resolve_pci_functions_per_chip( + chips, + chip_id_map=chip_id_map, + host_pci_inventory=full_inventory, + observed_domain_bdfs=observed_domain_bdfs, + ) + ) inventory_all_bdfs = {inv_chip.pci_bdf for inv_chip in full_inventory} inventory_domain_bdfs: Dict[Tuple[str, Optional[int], str], set[str]] = {} for inv_chip in full_inventory: @@ -1762,7 +2415,11 @@ def _compute_topology_slices( not _is_supported_single_host_chip_count( len(slice_phys_indices), slice_gens, subhost_slice=True ) - or not _has_complete_chip_functions(d_chips, bdf_to_phys) + or not _has_complete_chip_functions( + d_chips, + bdf_to_phys, + expected_fns_by_bdf=per_chip_by_bdf, + ) ): continue slice_logical_indices = tuple(_logical_device_indices(d_chips, slice_phys_indices)) @@ -1792,6 +2449,8 @@ def _compute_topology_slices( bdf_to_phys, chip_id_map=chip_id_map, host_pci_inventory=host_pci_inventory, + expected_fns_by_bdf=per_chip_by_bdf, + observed_domain_bdfs=observed_domain_bdfs, ) if verified_vis is not None: vis_chips, _vis_devs = verified_vis @@ -1900,25 +2559,122 @@ def _parse_observed_domain_bdfs( continue numa_val = None if kind_tok == "numa": - if not numa_tok.isdigit(): + numa_val = _parse_bounded_ascii_uint(numa_tok) + if numa_val is None: continue - numa_val = int(numa_tok, 10) bdfs = {b.strip().lower() for b in bdfs_part.split(",") if b.strip()} if bdfs: out.setdefault((kind_tok, numa_val, root_val), set()).update(bdfs) return out +def _format_observed_bdf_generations(bdf_generations: Dict[str, str]) -> str: + """Serialize boot-observed `{pci_bdf: generation}` map deterministically.""" + return ";".join( + f"{bdf.strip().lower()}={gen.strip()}" + for bdf, gen in sorted(bdf_generations.items()) + if bdf and bdf.strip() and gen and gen.strip() + ) + + +def _extract_observed_bdf_generations_from_spec(spec: Any) -> Dict[str, str]: + """Recover per-BDF generations recorded in root or device annotations of a CDI spec.""" + out: Dict[str, str] = {} + if not isinstance(spec, dict): + return out + root_ann = spec.get("annotations") + if isinstance(root_ann, dict): + raw = root_ann.get("freetpu.dev/observed-bdf-generations") + if isinstance(raw, str) and raw.strip(): + for entry in raw.split(";"): + entry = entry.strip() + if "=" in entry: + bdf_s, gen_s = entry.split("=", 1) + b = bdf_s.strip().lower() + g = gen_s.strip() + if b and g: + out[b] = g + devices = spec.get("devices") + if isinstance(devices, list): + for dev in devices: + if not isinstance(dev, dict): + continue + ann = dev.get("annotations") + if not isinstance(ann, dict): + continue + single_bdf = ann.get("freetpu.dev/pci-bdf") + single_gen = ann.get("freetpu.dev/generation") + if isinstance(single_bdf, str) and isinstance(single_gen, str): + b = single_bdf.strip().lower() + g = single_gen.strip() + if b and g: + out.setdefault(b, g) + raw_bdfs = ann.get("freetpu.dev/pci-bdfs") + raw_gens = ann.get("freetpu.dev/generations") + if isinstance(raw_bdfs, str) and isinstance(raw_gens, str): + gens_set = {tok.strip() for tok in raw_gens.split(",") if tok.strip()} + if len(gens_set) == 1: + only_gen = next(iter(gens_set)) + for b_tok in raw_bdfs.split(","): + b = b_tok.strip().lower() + if b: + out.setdefault(b, only_gen) + return out + + +def _extract_observed_generations_from_spec(spec: Any) -> set[str]: + """Recover observed TPU generations from root and device annotations in a CDI spec.""" + gens: set[str] = set() + if not isinstance(spec, dict): + return gens + root_ann = spec.get("annotations") + if isinstance(root_ann, dict): + raw_obs_gens = root_ann.get("freetpu.dev/observed-generations") + if isinstance(raw_obs_gens, str) and raw_obs_gens.strip(): + for tok in raw_obs_gens.split(","): + if tok.strip(): + gens.add(tok.strip()) + for gen_s in _extract_observed_bdf_generations_from_spec(spec).values(): + if gen_s: + gens.add(gen_s) + devices = spec.get("devices") + if isinstance(devices, list): + for s_dev in devices: + if not isinstance(s_dev, dict): + continue + s_ann = s_dev.get("annotations") + if not isinstance(s_ann, dict): + continue + s_gen = s_ann.get("freetpu.dev/generation") + if isinstance(s_gen, str) and s_gen.strip(): + gens.add(s_gen.strip()) + s_gens = s_ann.get("freetpu.dev/generations") + if isinstance(s_gens, str) and s_gens.strip(): + for g_tok in s_gens.split(","): + if g_tok.strip(): + gens.add(g_tok.strip()) + return gens + + +class _ObservedDomainBdfs(Dict[Tuple[str, Optional[int], str], set[str]]): + """Domain-to-BDF mapping carrying same-boot `tpu7x` 2-fn history.""" + + def __init__(self, *args: Any, tpu7x_two_fn: bool = False, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.tpu7x_two_fn: bool = bool(tpu7x_two_fn) + + def _extract_observed_domain_bdfs_from_spec( spec: Any, ) -> Dict[Tuple[str, Optional[int], str], set[str]]: """Recover boot-observed domain PCI BDFs from an existing CDI spec.""" - out: Dict[Tuple[str, Optional[int], str], set[str]] = {} + two_fn = _extract_observed_tpu7x_two_fn_from_spec(spec) + out = _ObservedDomainBdfs(tpu7x_two_fn=two_fn) if not isinstance(spec, dict): return out root_ann = spec.get("annotations") if isinstance(root_ann, dict): - out = _parse_observed_domain_bdfs(root_ann.get("freetpu.dev/observed-domain-bdfs")) + out.update(_parse_observed_domain_bdfs(root_ann.get("freetpu.dev/observed-domain-bdfs"))) if out: return out # Backward-compatible fallback for specs written without the root annotation. @@ -1945,9 +2701,7 @@ def _extract_observed_domain_bdfs_from_spec( if not bdfs: continue raw_numa = ann.get("freetpu.dev/numa-node") - numa_val: Optional[int] = None - if isinstance(raw_numa, str) and raw_numa.strip().isdigit(): - numa_val = int(raw_numa.strip(), 10) + numa_val = _parse_bounded_ascii_uint(raw_numa.strip()) if isinstance(raw_numa, str) else None raw_root = ann.get("freetpu.dev/pcie-root") if isinstance(raw_root, str) and raw_root.strip(): root_val = raw_root.strip().lower() @@ -1971,40 +2725,283 @@ def _read_host_boot_id() -> Optional[str]: return None -def _load_same_boot_observed_domains( - spec_path: Path, -) -> Dict[Tuple[str, Optional[int], str], set[str]]: - """Load boot-observed per-domain PCI BDFs from an existing spec file if from the same boot.""" - try: - if not spec_path.exists(): - return {} - existing_spec = _load_json_strict_keys(spec_path.read_text(encoding="utf-8")) - if not isinstance(existing_spec, dict): - return {} - root_ann = existing_spec.get("annotations") - existing_boot_id = ( - root_ann.get("freetpu.dev/boot-id") if isinstance(root_ann, dict) else None - ) - current_boot_id = _read_host_boot_id() - if ( - isinstance(existing_boot_id, str) - and existing_boot_id.strip() - and current_boot_id - and existing_boot_id.strip() != current_boot_id - ): - return {} - return _extract_observed_domain_bdfs_from_spec(existing_spec) - except Exception: # noqa: BLE001 - return {} - - -def _merge_observed_domain_bdfs( - existing: Optional[Dict[Tuple[str, Optional[int], str], set[str]]], +def _spec_matches_current_boot( + spec: Any, + *, + require_explicit_when_available: bool = False, +) -> bool: + """Return True when `spec` belongs to the current kernel boot (when known).""" + if not isinstance(spec, dict): + return False + root_ann = spec.get("annotations") + if not isinstance(root_ann, dict): + root_ann = {} + existing_boot_id = root_ann.get("freetpu.dev/boot-id") + current_boot_id = _read_host_boot_id() + if isinstance(existing_boot_id, str) and existing_boot_id.strip(): + if not current_boot_id or existing_boot_id.strip() != current_boot_id: + return False + return True + if require_explicit_when_available and current_boot_id: + return False + return True + + +def _spec_has_boot_scoped_annotations(spec: Any) -> bool: + """Return True when `spec` carries current-format boot-scoped layout/history annotations.""" + if not isinstance(spec, dict): + return False + root_ann = spec.get("annotations") + if not isinstance(root_ann, dict): + return False + return any( + k in root_ann + for k in ( + "freetpu.dev/tpu7x-layout-source", + "freetpu.dev/tpu7x-pci-functions-per-chip", + "freetpu.dev/observed-domain-bdfs", + "freetpu.dev/observed-bdf-generations", + "freetpu.dev/observed-generations", + ) + ) + + +def _extract_observed_tpu7x_two_fn_from_spec(spec: Any) -> bool: + """Return True when `spec` records verified hardware/sysfs 2-fn Ironwood (`tpu7x`) history.""" + if not isinstance(spec, dict): + return False + root_ann = spec.get("annotations") + if isinstance(root_ann, dict): + if root_ann.get("freetpu.dev/tpu7x-layout-source") == "chip-id-map": + return False + recorded = root_ann.get("freetpu.dev/tpu7x-pci-functions-per-chip") + if recorded == "2": + return True + if recorded == "1": + return False + devices = spec.get("devices") + if not isinstance(devices, list): + return False + for dev in devices: + if not isinstance(dev, dict): + continue + ann = dev.get("annotations") + if not isinstance(ann, dict): + continue + if ann.get("freetpu.dev/chip-id-source") == "chip-id-map": + continue + gen = ann.get("freetpu.dev/generation") + gens = ann.get("freetpu.dev/generations") + gens_set: set[str] = set() + if isinstance(gen, str) and gen.strip(): + gens_set.add(gen.strip()) + if isinstance(gens, str): + for g in gens.split(","): + if g.strip(): + gens_set.add(g.strip()) + if gens_set != {"tpu7x"}: + continue + # Only objective paired function-count evidence (cc >= 1 with fc == 2*cc) + # proves 2-fn hardware in legacy specs without root layout metadata; + # legacy `single-chiplet` / `incomplete-pci-functions` labels were + # unconditionally written even on healthy 4 x 1-fn hosts. + cc = _parse_bounded_ascii_uint(ann.get("freetpu.dev/chip-count")) + fc = _parse_bounded_ascii_uint(ann.get("freetpu.dev/pci-function-count")) + if cc is not None and fc is not None and cc >= 1 and fc == 2 * cc: + return True + return False + + +def _spec_has_same_boot_hw_tpu7x_two_fn( + spec: Any, + live_pci_inventory: Sequence[DiscoveredChip], + merged_live_observed: Dict[Tuple[str, Optional[int], str], set[str]], +) -> bool: + """Return True when a standalone `spec` carries same-boot hardware/sysfs 2-fn history. + + Requires explicit `tpu7x-pci-functions-per-chip='2'`, + `tpu7x-layout-source='hardware'` (never `'chip-id-map'`), strict same-boot + `boot-id` match (never admitting a mismatched or unreadable host `boot_id` + when `spec` records `freetpu.dev/boot-id`), and observed Ironwood/host BDF + records from that same boot (whether endpoints remain present without sysfs + `chip_id` or some have since disappeared). + """ + if not isinstance(spec, dict): + return False + root_ann = spec.get("annotations") + if not isinstance(root_ann, dict): + return False + if root_ann.get("freetpu.dev/tpu7x-pci-functions-per-chip") != "2": + return False + if root_ann.get("freetpu.dev/tpu7x-layout-source") != "hardware": + return False + current_boot_id = _read_host_boot_id() + existing_boot_id = root_ann.get("freetpu.dev/boot-id") + if ( + not current_boot_id + or not isinstance(existing_boot_id, str) + or existing_boot_id.strip() != current_boot_id + ): + return False + obs_bdfs = {b for bset in merged_live_observed.values() for b in bset} + return bool(obs_bdfs) and any(c.generation == "tpu7x" for c in live_pci_inventory) + + +def _spec_has_positive_boot_match(spec: Any) -> bool: + """Return True iff `spec` records a non-empty `boot-id` matching readable host boot_id.""" + if not isinstance(spec, dict): + return False + root_ann = spec.get("annotations") + if not isinstance(root_ann, dict): + return False + existing_boot_id = root_ann.get("freetpu.dev/boot-id") + current_boot_id = _read_host_boot_id() + return bool( + current_boot_id + and isinstance(existing_boot_id, str) + and existing_boot_id.strip() == current_boot_id + ) + + +def _load_same_boot_spec_if_matching( + spec_path: Path, + *, + require_positive_boot_match: bool = False, +) -> Optional[Dict[str, Any]]: + """Read an existing spec file only when its recorded `boot-id` positively matches the live kernel boot.""" + del require_positive_boot_match + try: + if not spec_path.exists(): + return None + existing_spec = _load_json_strict_keys(spec_path.read_text(encoding="utf-8")) + if not isinstance(existing_spec, dict): + return None + if not _spec_has_positive_boot_match(existing_spec): + return None + return existing_spec + except Exception: # noqa: BLE001 + return None + + +def _load_same_boot_observed_domains( + spec_path: Path, +) -> Dict[Tuple[str, Optional[int], str], set[str]]: + """Load boot-observed per-domain PCI BDFs from an existing spec file if from the same boot.""" + existing_spec = _load_same_boot_spec_if_matching(spec_path) + return ( + _extract_observed_domain_bdfs_from_spec(existing_spec) + if existing_spec + else _ObservedDomainBdfs() + ) + + +def _load_same_boot_observed_generations(spec_path: Path) -> Dict[str, str]: + """Load boot-observed `{pci_bdf: generation}` from an existing spec file if same boot.""" + existing_spec = _load_same_boot_spec_if_matching(spec_path) + return _extract_observed_bdf_generations_from_spec(existing_spec) if existing_spec else {} + + +def _load_same_boot_observed_gen_names(spec_path: Path) -> set[str]: + """Load boot-observed generation set (including aggregate legacy annotations) if same boot.""" + existing_spec = _load_same_boot_spec_if_matching(spec_path) + return _extract_observed_generations_from_spec(existing_spec) if existing_spec else set() + + +def _load_same_boot_observed_tpu7x_two_fn(spec_path: Path) -> bool: + """Return True iff an existing spec proves 2-fn Ironwood history with a positive boot-ID match.""" + existing_spec = _load_same_boot_spec_if_matching( + spec_path, require_positive_boot_match=True + ) + return _extract_observed_tpu7x_two_fn_from_spec(existing_spec) if existing_spec else False + + +def _load_disk_same_boot_history( + spec_path: Path, +) -> Tuple[ + Dict[Tuple[str, Optional[int], str], set[str]], + Dict[str, str], + set[str], + bool, + bool, +]: + """Load persisted disk topology/history, gating `tpu7x` layout promotion on a positive boot match.""" + existing_spec = _load_same_boot_spec_if_matching(spec_path) + if not existing_spec: + return _ObservedDomainBdfs(), {}, set(), False, False + pos_boot = _spec_has_positive_boot_match(existing_spec) + disk_domains = _extract_observed_domain_bdfs_from_spec(existing_spec) + disk_gens = _extract_observed_bdf_generations_from_spec(existing_spec) + disk_gen_names = _extract_observed_generations_from_spec(existing_spec) + disk_two_fn = ( + _extract_observed_tpu7x_two_fn_from_spec(existing_spec) if pos_boot else False + ) + return disk_domains, disk_gens, disk_gen_names, disk_two_fn, pos_boot + + +def _filter_disk_history_for_inventory( + disk_domains: Dict[Tuple[str, Optional[int], str], set[str]], + disk_gens: Dict[str, str], + disk_gen_names: set[str], + disk_two_fn: bool, + disk_pos_boot: bool, + live_inventory: Sequence[DiscoveredChip], + *, + chip_id_map: Optional[Dict[str, int]] = None, + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, +) -> Tuple[ + Dict[Tuple[str, Optional[int], str], set[str]], + Dict[str, str], + set[str], + bool, +]: + """Discard unverified persisted disk history if it would alter live `tpu7x` layout without a positive boot match.""" + if disk_pos_boot: + return disk_domains, disk_gens, disk_gen_names, disk_two_fn + if not any(c.generation == "tpu7x" for c in live_inventory): + return disk_domains, disk_gens, disk_gen_names, False + fresh_doms = _merge_observed_domain_bdfs(None, live_inventory, preserve_tpu7x_two_fn=False) + fresh_gens = {c.pci_bdf: c.generation for c in live_inventory} + fresh_names = sorted(set(fresh_gens.values())) + fresh_layout = _resolve_tpu7x_pci_functions_per_chip( + live_inventory, + chip_id_map=chip_id_map, + host_pci_inventory=live_inventory, + observed_domain_bdfs=fresh_doms, + observed_bdf_generations=fresh_gens, + spec_generations=fresh_names or None, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=False, + ) + hist_doms = _merge_observed_domain_bdfs(disk_domains, live_inventory, preserve_tpu7x_two_fn=False) + hist_gens = dict(disk_gens) + hist_gens.update(fresh_gens) + hist_names = sorted(set(disk_gen_names) | set(fresh_names)) + hist_layout = _resolve_tpu7x_pci_functions_per_chip( + live_inventory, + chip_id_map=chip_id_map, + host_pci_inventory=live_inventory, + observed_domain_bdfs=hist_doms, + observed_bdf_generations=hist_gens, + spec_generations=hist_names or None, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=False, + ) + if hist_layout != fresh_layout: + return _ObservedDomainBdfs(), {}, set(), False + return disk_domains, disk_gens, disk_gen_names, False + + +def _merge_observed_domain_bdfs( + existing: Optional[Dict[Tuple[str, Optional[int], str], set[str]]], inventory: Sequence[DiscoveredChip], + *, + preserve_tpu7x_two_fn: bool = True, ) -> Dict[Tuple[str, Optional[int], str], set[str]]: - merged: Dict[Tuple[str, Optional[int], str], set[str]] = { - k: set(v) for k, v in (existing or {}).items() - } + two_fn = bool(preserve_tpu7x_two_fn and getattr(existing, "tpu7x_two_fn", False)) + merged = _ObservedDomainBdfs( + {k: set(v) for k, v in (existing or {}).items()}, + tpu7x_two_fn=two_fn, + ) unplaced = merged.get(_UNPLACED_OBSERVED_DOMAIN_KEY) for chip in inventory: merged.setdefault(_topology_domain_key(chip), set()).add(chip.pci_bdf) @@ -2027,7 +3024,10 @@ def build_cdi_spec( omit_visible_env: bool = False, host_pci_inventory: Optional[Sequence[DiscoveredChip]] = None, observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + observed_bdf_generations: Optional[Dict[str, str]] = None, + observed_generations: Optional[Sequence[str]] = None, bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, + observed_tpu7x_two_fn: bool = False, ) -> Dict[str, Any]: """Build a CNCF CDI JSON specification dictionary (default: CDI v0.6.0, host-safe env). @@ -2086,7 +3086,67 @@ def build_cdi_spec( ], } - bdf_to_phys = _map_physical_chip_indices(chips, chip_id_map=chip_id_map) + merged_observed_domains = _merge_observed_domain_bdfs( + observed_domain_bdfs, + host_pci_inventory if host_pci_inventory is not None else chips, + ) + merged_observed_gens: Dict[str, str] = dict(observed_bdf_generations or {}) + merged_observed_gen_names: set[str] = { + str(g).strip() for g in (observed_generations or ()) if isinstance(g, str) and str(g).strip() + } + merged_observed_gen_names.update(g for g in merged_observed_gens.values() if g) + inv_for_gens = host_pci_inventory if host_pci_inventory is not None else chips + for inv_c in inv_for_gens: + merged_observed_gens[inv_c.pci_bdf] = inv_c.generation + merged_observed_gen_names.add(inv_c.generation) + spec_gen_names = sorted(merged_observed_gen_names) if merged_observed_gen_names else None + per_chip_by_bdf = _resolve_pci_functions_per_chip( + chips, + chip_id_map=chip_id_map, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=merged_observed_domains, + observed_bdf_generations=merged_observed_gens, + spec_generations=spec_gen_names, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + bdf_to_phys = _map_physical_chip_indices( + chips, + chip_id_map=chip_id_map, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=merged_observed_domains, + expected_fns_by_bdf=per_chip_by_bdf, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + + per_chip_by_bdf_nomap = ( + _resolve_pci_functions_per_chip( + chips, + chip_id_map=None, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=merged_observed_domains, + observed_bdf_generations=merged_observed_gens, + spec_generations=spec_gen_names, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + if chip_id_map + else per_chip_by_bdf + ) + bdf_to_phys_nomap = ( + _map_physical_chip_indices( + chips, + chip_id_map=None, + host_pci_inventory=host_pci_inventory, + observed_domain_bdfs=merged_observed_domains, + expected_fns_by_bdf=per_chip_by_bdf_nomap, + bridge_bus_to_roots=bridge_bus_to_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + if chip_id_map + else bdf_to_phys + ) devices: List[Dict[str, Any]] = [] seen_group_nodes: Dict[str, Dict[str, Any]] = {} @@ -2132,7 +3192,9 @@ def build_cdi_spec( if len(unit_chips) == 1: selector = _single_chip_selector(rep.pci_bdf) - per_chip = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(rep.generation, 1) + per_chip = per_chip_by_bdf.get( + rep.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(rep.generation, 1) + ) unit_label = "single-chiplet" if per_chip > 1 else "single-chip" ann: Dict[str, str] = { "freetpu.dev/allocation-unit": unit_label, @@ -2147,10 +3209,24 @@ def build_cdi_spec( "freetpu.dev/optional-cap-add": "IPC_LOCK", "freetpu.dev/required-ulimit-memlock": "-1", } + _tpu_meta = tpu_topology_metadata(rep.generation) + ann["freetpu.dev/chiplets-per-pkg"] = str(_tpu_meta["chiplets_per_pkg"]) + if _tpu_meta["hbm_gib_per_logical_device"] is not None: + ann["freetpu.dev/hbm-gib-per-logical-device"] = str( + _tpu_meta["hbm_gib_per_logical_device"] + ) if rep.numa_node is not None: ann["freetpu.dev/numa-node"] = str(rep.numa_node) if devnums_str: ann["freetpu.dev/vfio-devnums"] = devnums_str + per_chip_nomap = per_chip_by_bdf_nomap.get( + rep.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(rep.generation, 1) + ) + unit_label_nomap = "single-chiplet" if per_chip_nomap > 1 else "single-chip" + if chip_id_map and ( + rep.pci_bdf in chip_id_map or unit_label != unit_label_nomap + ): + ann["freetpu.dev/chip-id-source"] = "chip-id-map" devices.append( { "name": selector, @@ -2165,7 +3241,9 @@ def build_cdi_spec( # Emit locality annotations (`pcie-root` / `numa-node`) ONLY when every # member of the shared group agrees on that domain. unit_complete_chips, unit_incomplete_fns = _count_complete_chips( - unit_chips, bdf_to_phys + unit_chips, + bdf_to_phys, + expected_fns_by_bdf=per_chip_by_bdf, ) unit_roots = {c.pcie_root or _pcie_root_complex(c.pci_bdf) for c in unit_chips} unit_numas = {c.numa_node for c in unit_chips} @@ -2191,8 +3269,24 @@ def build_cdi_spec( only_numa = next(iter(unit_numas)) if only_numa is not None: ann["freetpu.dev/numa-node"] = str(only_numa) + # Emit topology metadata for homogeneous shared groups (Ironwood dual-chiplet). + if len(set(unit_gens)) == 1: + _shared_meta = tpu_topology_metadata(unit_gens[0]) + ann["freetpu.dev/chiplets-per-pkg"] = str(_shared_meta["chiplets_per_pkg"]) + if _shared_meta["hbm_gib_per_logical_device"] is not None: + ann["freetpu.dev/hbm-gib-per-logical-device"] = str( + _shared_meta["hbm_gib_per_logical_device"] + ) if devnums_str: ann["freetpu.dev/vfio-devnums"] = devnums_str + if chip_id_map: + nomap_counts = _count_complete_chips( + unit_chips, + bdf_to_phys_nomap, + expected_fns_by_bdf=per_chip_by_bdf_nomap, + ) + if (unit_complete_chips, unit_incomplete_fns) != nomap_counts: + ann["freetpu.dev/chip-id-source"] = "chip-id-map" devices.append( { "name": selector, @@ -2204,15 +3298,6 @@ def build_cdi_spec( # Emit NUMA / PCIe-root-complex-aware capacity-pinned sub-host slice presets # (e.g. `numa0-pcie-0000-00-4`, `numa1-pcie-0000-80-4`, `0-3`, `4-7` on `v6e-8`) # strictly within matching NUMA / PCIe root complex boundaries. - bdf_to_phys_nomap = ( - _map_physical_chip_indices(chips, chip_id_map=None) - if chip_id_map - else bdf_to_phys - ) - merged_observed_domains = _merge_observed_domain_bdfs( - observed_domain_bdfs, - host_pci_inventory if host_pci_inventory is not None else chips, - ) used_names = {d["name"] for d in devices} for topo_slice in _compute_topology_slices( chips, @@ -2222,6 +3307,7 @@ def build_cdi_spec( host_pci_inventory=host_pci_inventory, observed_domain_bdfs=merged_observed_domains, bridge_bus_to_roots=bridge_bus_to_roots, + expected_fns_by_bdf=per_chip_by_bdf, ): slice_nodes, slice_devnums = _dedup_device_nodes(topo_slice.chips) slice_visibility = _resolve_verified_visibility_ordinals( @@ -2230,6 +3316,8 @@ def build_cdi_spec( bdf_to_phys, chip_id_map=chip_id_map, host_pci_inventory=host_pci_inventory, + expected_fns_by_bdf=per_chip_by_bdf, + observed_domain_bdfs=merged_observed_domains, ) slice_visibility_nomap = ( _resolve_verified_visibility_ordinals( @@ -2238,6 +3326,8 @@ def build_cdi_spec( bdf_to_phys_nomap, chip_id_map=None, host_pci_inventory=host_pci_inventory, + expected_fns_by_bdf=per_chip_by_bdf_nomap, + observed_domain_bdfs=merged_observed_domains, ) if chip_id_map else slice_visibility @@ -2260,6 +3350,15 @@ def build_cdi_spec( "freetpu.dev/optional-cap-add": "IPC_LOCK", "freetpu.dev/required-ulimit-memlock": "-1", } + if len(set(topo_slice.generations)) == 1: + _slice_meta = tpu_topology_metadata(topo_slice.generations[0]) + slice_ann_base["freetpu.dev/chiplets-per-pkg"] = str( + _slice_meta["chiplets_per_pkg"] + ) + if _slice_meta["hbm_gib_per_logical_device"] is not None: + slice_ann_base["freetpu.dev/hbm-gib-per-logical-device"] = str( + _slice_meta["hbm_gib_per_logical_device"] + ) # Record freetpu.dev/numa-node ONLY with the actual sysfs NUMA node; # never substitute a PCIe domain ordinal or invent a node when sysfs has none. if topo_slice.numa_node is not None: @@ -2297,14 +3396,25 @@ def build_cdi_spec( and any(c.pci_bdf not in all_bdfs for c in host_pci_inventory) ) if not has_unavailable_pci_groups: - all_complete_chips, all_incomplete_fns = _count_complete_chips(chips, bdf_to_phys) - all_supported_topology = _is_supported_all_topology(chips, bdf_to_phys, all_generations) + all_complete_chips, all_incomplete_fns = _count_complete_chips( + chips, + bdf_to_phys, + expected_fns_by_bdf=per_chip_by_bdf, + ) + all_supported_topology = _is_supported_all_topology( + chips, + bdf_to_phys, + all_generations, + expected_fns_by_bdf=per_chip_by_bdf, + ) all_visibility = _resolve_verified_visibility_ordinals( chips, chips, bdf_to_phys, chip_id_map=chip_id_map, host_pci_inventory=host_pci_inventory, + expected_fns_by_bdf=per_chip_by_bdf, + observed_domain_bdfs=merged_observed_domains, ) observed_host_bdfs: set[str] = set() for dom_bdfs in merged_observed_domains.values(): @@ -2337,10 +3447,17 @@ def build_cdi_spec( bdf_to_phys_nomap, chip_id_map=None, host_pci_inventory=host_pci_inventory, + expected_fns_by_bdf=per_chip_by_bdf_nomap, + observed_domain_bdfs=merged_observed_domains, ) if chip_id_map else all_visibility ) + all_nomap_counts = _count_complete_chips( + chips, + bdf_to_phys_nomap, + expected_fns_by_bdf=per_chip_by_bdf_nomap, + ) all_ann: Dict[str, str] = { "freetpu.dev/allocation-unit": "all-devices", "freetpu.dev/chip-count": str(all_complete_chips), @@ -2349,6 +3466,13 @@ def build_cdi_spec( "freetpu.dev/optional-cap-add": "IPC_LOCK", "freetpu.dev/required-ulimit-memlock": "-1", } + if len(all_generations) == 1: + _all_meta = tpu_topology_metadata(all_generations[0]) + all_ann["freetpu.dev/chiplets-per-pkg"] = str(_all_meta["chiplets_per_pkg"]) + if _all_meta["hbm_gib_per_logical_device"] is not None: + all_ann["freetpu.dev/hbm-gib-per-logical-device"] = str( + _all_meta["hbm_gib_per_logical_device"] + ) if len(chips) != all_complete_chips or all_incomplete_fns > 0: all_ann["freetpu.dev/pci-function-count"] = str(len(chips)) if all_incomplete_fns > 0: @@ -2359,6 +3483,7 @@ def build_cdi_spec( all_ann["freetpu.dev/vfio-devnums"] = all_devnums if chip_id_map and ( any(c.pci_bdf in chip_id_map for c in chips) + or (all_complete_chips, all_incomplete_fns) != all_nomap_counts or all_visibility != all_visibility_nomap ): all_ann["freetpu.dev/chip-id-source"] = "chip-id-map" @@ -2401,6 +3526,33 @@ def build_cdi_spec( observed_domains_str = _format_observed_domain_bdfs(merged_observed_domains) if observed_domains_str: root_ann["freetpu.dev/observed-domain-bdfs"] = observed_domains_str + observed_gens_str = _format_observed_bdf_generations(merged_observed_gens) + if observed_gens_str: + root_ann["freetpu.dev/observed-bdf-generations"] = observed_gens_str + live_gen_names = {c.generation for c in inv_for_gens if c.generation} + if merged_observed_gen_names - live_gen_names: + root_ann["freetpu.dev/observed-generations"] = ",".join( + sorted(merged_observed_gen_names) + ) + tpu7x_per_chips = { + per_chip_by_bdf.get(c.pci_bdf, 2) + for c in list(host_pci_inventory if host_pci_inventory is not None else chips) + if c.generation == "tpu7x" + } + tpu7x_nomap_per_chips = { + per_chip_by_bdf_nomap.get(c.pci_bdf, 2) + for c in list(host_pci_inventory if host_pci_inventory is not None else chips) + if c.generation == "tpu7x" + } + if tpu7x_per_chips: + root_ann["freetpu.dev/tpu7x-pci-functions-per-chip"] = str(max(tpu7x_per_chips)) + map_changed_layout = bool(chip_id_map and max(tpu7x_per_chips) != max(tpu7x_nomap_per_chips)) + root_ann["freetpu.dev/tpu7x-layout-source"] = ( + "chip-id-map" if map_changed_layout else "hardware" + ) + elif observed_tpu7x_two_fn: + root_ann["freetpu.dev/tpu7x-pci-functions-per-chip"] = "2" + root_ann["freetpu.dev/tpu7x-layout-source"] = "hardware" boot_id = _read_host_boot_id() if boot_id: root_ann["freetpu.dev/boot-id"] = boot_id @@ -2767,6 +3919,7 @@ def validate_cdi_spec(spec: Any) -> List[str]: errors.append("annotations must be a string-to-string map") global_paths: set[str] = set() + global_env: Dict[str, str] = {} global_net_by_name: Dict[str, str] = {} global_net_by_host: Dict[str, str] = {} if "containerEdits" in spec: @@ -2777,6 +3930,12 @@ def validate_cdi_spec(spec: Any) -> List[str]: cdi_version=effective_version, ) if isinstance(spec["containerEdits"], dict): + g_env_list = spec["containerEdits"].get("env") + if isinstance(g_env_list, list): + for entry in g_env_list: + if isinstance(entry, str) and "=" in entry: + ek, ev = entry.split("=", 1) + global_env[ek] = ev nodes = spec["containerEdits"].get("deviceNodes") if isinstance(nodes, list): for n in nodes: @@ -2856,6 +4015,32 @@ def validate_cdi_spec(spec: Any) -> List[str]: effective_paths = global_paths | dev_paths label = name if isinstance(name, str) else dc + eff_env = dict(global_env) + if isinstance(dev.get("containerEdits"), dict): + d_env_list = dev["containerEdits"].get("env") + if isinstance(d_env_list, list): + for entry in d_env_list: + if isinstance(entry, str) and "=" in entry: + ek, ev = entry.split("=", 1) + eff_env[ek] = ev + if isinstance(name, str) and (name.startswith("pci-") or name.startswith("group-pci-")): + for ek in ( + "TPU_CHIPS_PER_HOST_BOUNDS", + "TPU_ACCELERATOR_TYPE", + "TPU_SKIP_MDS_QUERY", + "TPU_VISIBLE_CHIPS", + "TPU_VISIBLE_DEVICES", + ): + if ek in eff_env: + errors.append( + f"{dc} ({label!r}): composable PCI selector must not inject {ek}={eff_env[ek]!r}" + ) + if eff_env.get("TPU_SKIP_MDS_QUERY", "").strip() == "true": + for ck in ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE"): + if not eff_env.get(ck) or not eff_env[ck].strip(): + errors.append( + f"{dc} ({label!r}): TPU_SKIP_MDS_QUERY='true' requires companion {ck}" + ) has_iommufd = "/dev/iommu" in effective_paths has_vfio_ctrl = "/dev/vfio/vfio" in effective_paths if not has_iommufd and not has_vfio_ctrl: @@ -2978,6 +4163,8 @@ def _verify_spec_against_host_detailed( vfio_mode: str = "auto", chip_id_map: Optional[Dict[str, int]] = None, observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + observed_generations: Optional[Sequence[str]] = None, + observed_tpu7x_two_fn: bool = False, ) -> Tuple[List[str], List[str]]: """Revalidate all effective global and per-device CDI nodes against live host VFIO/iommufd state. @@ -3037,15 +4224,347 @@ def _verify_spec_against_host_detailed( else _shared_group_selector(sorted(c.pci_bdf for c in u)) for u in live_units.values() } - spec_observed_domains = _extract_observed_domain_bdfs_from_spec(spec) + spec_is_current_boot = _spec_matches_current_boot( + spec, + require_explicit_when_available=_spec_has_boot_scoped_annotations(spec), + ) + spec_root_ann = spec.get("annotations") + rec_boot_id = ( + spec_root_ann.get("freetpu.dev/boot-id").strip() + if isinstance(spec_root_ann, dict) + and isinstance(spec_root_ann.get("freetpu.dev/boot-id"), str) + else "" + ) + has_positive_boot_match = False + if rec_boot_id: + host_boot_id = _read_host_boot_id() + if host_boot_id and rec_boot_id != host_boot_id: + errors.append( + f"stale CDI spec: recorded freetpu.dev/boot-id={rec_boot_id!r} " + f"does not match host boot_id={host_boot_id!r}" + ) + elif not host_boot_id: + unverifiable.append( + f"CDI spec records freetpu.dev/boot-id={rec_boot_id!r} which cannot be " + "verified because host boot_id is unreadable" + ) + else: + has_positive_boot_match = True + raw_spec_domains = _extract_observed_domain_bdfs_from_spec(spec) + raw_spec_gens = _extract_observed_bdf_generations_from_spec(spec) + raw_spec_gen_names = _extract_observed_generations_from_spec(spec) + spec_observed_domains = ( + _ObservedDomainBdfs( + {k: set(v) for k, v in raw_spec_domains.items()}, + tpu7x_two_fn=bool(getattr(raw_spec_domains, "tpu7x_two_fn", False)), + ) + if has_positive_boot_match + else _ObservedDomainBdfs() + ) if observed_domain_bdfs: for d_k, bdfs_s in observed_domain_bdfs.items(): spec_observed_domains.setdefault(d_k, set()).update(bdfs_s) merged_live_observed = _merge_observed_domain_bdfs( - spec_observed_domains, live_pci_inventory + spec_observed_domains, + live_pci_inventory, + preserve_tpu7x_two_fn=bool(getattr(observed_domain_bdfs, "tpu7x_two_fn", False)), + ) + merged_live_observed_gens = dict(raw_spec_gens) if has_positive_boot_match else {} + for inv_c in live_pci_inventory: + merged_live_observed_gens[inv_c.pci_bdf] = inv_c.generation + spec_gens_set: set[str] = set(raw_spec_gen_names) if has_positive_boot_match else set() + if observed_generations: + for g_tok in observed_generations: + if isinstance(g_tok, str) and g_tok.strip(): + spec_gens_set.add(g_tok.strip()) + spec_generations: Optional[List[str]] = sorted(spec_gens_set) if spec_gens_set else None + + spec_observed_two_fn = bool( + observed_tpu7x_two_fn + or _spec_has_same_boot_hw_tpu7x_two_fn( + spec, live_pci_inventory, merged_live_observed + ) ) live_bridge_roots = _scan_pcie_bridge_roots(sysfs_root) - live_bdf_to_phys = _map_physical_chip_indices(live_chips, chip_id_map=chip_id_map) + if not has_positive_boot_match and any(c.generation == "tpu7x" for c in live_pci_inventory): + fresh_domains = _merge_observed_domain_bdfs( + observed_domain_bdfs, + live_pci_inventory, + preserve_tpu7x_two_fn=bool(getattr(observed_domain_bdfs, "tpu7x_two_fn", False)), + ) + fresh_gens = {inv_c.pci_bdf: inv_c.generation for inv_c in live_pci_inventory} + fresh_spec_gens = sorted({g for g in (observed_generations or ()) if g} | set(fresh_gens.values())) + fresh_tpu7x = _resolve_tpu7x_pci_functions_per_chip( + live_chips, + chip_id_map=chip_id_map, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=fresh_domains, + observed_bdf_generations=fresh_gens, + spec_generations=fresh_spec_gens or None, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, + ) + raw_hist_domains = _merge_observed_domain_bdfs( + raw_spec_domains, + live_pci_inventory, + preserve_tpu7x_two_fn=bool(getattr(observed_domain_bdfs, "tpu7x_two_fn", False)), + ) + if observed_domain_bdfs: + for d_k, bdfs_s in observed_domain_bdfs.items(): + raw_hist_domains.setdefault(d_k, set()).update(bdfs_s) + raw_hist_gens = dict(raw_spec_gens) + raw_hist_gens.update(fresh_gens) + raw_hist_gen_names = sorted(set(raw_spec_gen_names) | set(fresh_spec_gens)) + hist_tpu7x = _resolve_tpu7x_pci_functions_per_chip( + live_chips, + chip_id_map=chip_id_map, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=raw_hist_domains, + observed_bdf_generations=raw_hist_gens, + spec_generations=raw_hist_gen_names or None, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=spec_observed_two_fn, + ) + # Persisted layout history cannot promote 1-fn Ironwood to 2-fn unless a positive + # kernel boot-id match confirms the spec was generated on this same boot. + if hist_tpu7x != fresh_tpu7x: + unverifiable.append( + "CDI spec carries persisted Ironwood history changing tpu7x layout " + "without a verifiable host boot_id" + ) + merged_live_observed = fresh_domains + merged_live_observed_gens = fresh_gens + spec_generations = fresh_spec_gens or None + spec_observed_two_fn = bool(observed_tpu7x_two_fn) + live_per_chip_by_bdf = _resolve_pci_functions_per_chip( + live_chips, + chip_id_map=chip_id_map, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=merged_live_observed, + observed_bdf_generations=merged_live_observed_gens, + spec_generations=spec_generations, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=spec_observed_two_fn, + ) + live_bdf_to_phys = _map_physical_chip_indices( + live_chips, + chip_id_map=chip_id_map, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=merged_live_observed, + expected_fns_by_bdf=live_per_chip_by_bdf, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=spec_observed_two_fn, + ) + inv_slot_counts: Dict[Tuple[str, str], int] = {} + for c in live_pci_inventory: + skey = (c.generation, c.pci_bdf.rsplit(".", 1)[0]) + inv_slot_counts[skey] = inv_slot_counts.get(skey, 0) + 1 + has_live_tpu7x = any(c.generation == "tpu7x" for c in live_pci_inventory) + live_tpu7x_nomap_per_chip = ( + _resolve_tpu7x_pci_functions_per_chip( + live_chips, + chip_id_map=None, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=merged_live_observed, + observed_bdf_generations=merged_live_observed_gens, + spec_generations=spec_generations, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=spec_observed_two_fn, + ) + if has_live_tpu7x + else 2 + ) + host_nomap_per_by_bdf = _resolve_pci_functions_per_chip( + live_pci_inventory, + chip_id_map=None, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=merged_live_observed, + observed_bdf_generations=merged_live_observed_gens, + spec_generations=spec_generations, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=spec_observed_two_fn, + ) + host_nomap_phys_by_bdf = _map_physical_chip_indices( + live_pci_inventory, + chip_id_map=None, + host_pci_inventory=live_pci_inventory, + observed_domain_bdfs=merged_live_observed, + expected_fns_by_bdf=host_nomap_per_by_bdf, + bridge_bus_to_roots=live_bridge_roots, + observed_tpu7x_two_fn=spec_observed_two_fn, + ) + inv_forced_packages: Dict[str, frozenset[str]] = {} + host_forced_orphans: set[str] = set() + host_forced_tpu7x_pair = False + host_forced_tpu7x_orphan = False + inv_nomap_by_phys: Dict[int, List[DiscoveredChip]] = {} + for inv_c in live_pci_inventory: + if inv_c.generation not in ("tpu7x", "v2-v3"): + continue + base_slot = inv_c.pci_bdf.rsplit(".", 1)[0] + exp_inv_p = host_nomap_per_by_bdf.get( + inv_c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(inv_c.generation, 1) + ) + slot_inv_cnt = inv_slot_counts.get((inv_c.generation, base_slot), 0) + if slot_inv_cnt > 2 or (exp_inv_p > 1 and slot_inv_cnt < exp_inv_p and not inv_c.pci_bdf.endswith(".0")): + host_forced_orphans.add(inv_c.pci_bdf) + if inv_c.generation == "tpu7x": + host_forced_tpu7x_orphan = True + continue + inv_nomap_by_phys.setdefault(host_nomap_phys_by_bdf[inv_c.pci_bdf], []).append(inv_c) + for inv_grp in inv_nomap_by_phys.values(): + rep_inv = inv_grp[0] + exp_p = host_nomap_per_by_bdf.get( + rep_inv.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(rep_inv.generation, 1) + ) + if exp_p > 1 and len(inv_grp) == exp_p: + pkg_bdfs = frozenset(x.pci_bdf for x in inv_grp) + for x in inv_grp: + inv_forced_packages[x.pci_bdf] = pkg_bdfs + if rep_inv.generation == "tpu7x": + host_forced_tpu7x_pair = True + + allowed_tpu7x_modes: set[int] = ( + { + live_per_chip_by_bdf[c.pci_bdf] + for c in live_pci_inventory + if c.generation == "tpu7x" + } + if ( + chip_id_map is not None + or live_tpu7x_nomap_per_chip == 2 + or host_forced_tpu7x_pair + or host_forced_tpu7x_orphan + ) + else ({1, 2} if has_live_tpu7x else set()) + ) + + # Bucket factorizable free functions by `(generation, topology_domain)` and + # record per-selector constraints (`scope_constraints`) so overlapping or + # split-slot selectors cannot rely on contradictory hypothetical maps, even + # across large multi-bucket hosts exceeding 4,096 naive global states. + free_buckets: Dict[Tuple[str, Tuple[str, Optional[int], str]], List[str]] = {} + if chip_id_map is None: + for c in live_chips: + if ( + c.generation in ("tpu7x", "v2-v3") + and c.pci_bdf not in host_forced_orphans + and c.pci_bdf not in inv_forced_packages + ): + free_buckets.setdefault( + (c.generation, _topology_domain_key(c)), [] + ).append(c.pci_bdf) + + mode1_allowed = bool( + has_live_tpu7x + and live_tpu7x_nomap_per_chip == 1 + and not host_forced_tpu7x_pair + and not host_forced_tpu7x_orphan + ) + if has_live_tpu7x and isinstance(spec_root_ann, dict): + rec_root_src = spec_root_ann.get("freetpu.dev/tpu7x-layout-source") + if ( + "freetpu.dev/tpu7x-layout-source" in spec_root_ann + and rec_root_src not in ("hardware", "chip-id-map") + ): + errors.append( + f"invalid root freetpu.dev/tpu7x-layout-source {rec_root_src!r} " + "(expected 'hardware' or 'chip-id-map')" + ) + if "freetpu.dev/tpu7x-pci-functions-per-chip" in spec_root_ann: + rec_root_fns = spec_root_ann.get("freetpu.dev/tpu7x-pci-functions-per-chip") + if rec_root_fns not in ("1", "2"): + errors.append( + f"invalid root freetpu.dev/tpu7x-pci-functions-per-chip {rec_root_fns!r}" + ) + else: + if chip_id_map is None and rec_root_src == "chip-id-map": + exp_root_modes = { + str(m) + for m in allowed_tpu7x_modes + if (m != 1 or mode1_allowed) + } + else: + exp_root_modes = { + str(live_per_chip_by_bdf[c.pci_bdf]) + for c in live_pci_inventory + if c.generation == "tpu7x" + } + if rec_root_fns not in exp_root_modes: + errors.append( + f"stale root freetpu.dev/tpu7x-pci-functions-per-chip {rec_root_fns!r} " + f"(host expects {sorted(exp_root_modes)!r})" + ) + else: + root_mode_int = int(rec_root_fns) + allowed_tpu7x_modes &= {root_mode_int} + if ( + chip_id_map is None + and rec_root_src == "chip-id-map" + and root_mode_int != live_tpu7x_nomap_per_chip + ): + unverifiable.append( + f"root freetpu.dev/tpu7x-pci-functions-per-chip {rec_root_fns!r} " + "was generated with --chip-id-map and cannot be verified without that map" + ) + + def _eval_scope_layout( + scope_chips: Sequence[DiscoveredChip], + layout_mode: Optional[int], + partner_map: Dict[str, frozenset[str]], + ) -> Tuple[int, int, Dict[Tuple[str, Optional[int], str], int]]: + scope_bdfs = {c.pci_bdf for c in scope_chips} + complete = 0 + incomplete = 0 + seen_pkgs: set[frozenset[str]] = set() + dom_complete: Dict[Tuple[str, Optional[int], str], int] = {} + for c in scope_chips: + dkey = _topology_domain_key(c) + if c.generation not in ("tpu7x", "v2-v3") or ( + c.generation == "tpu7x" and layout_mode == 1 + ): + complete += 1 + dom_complete[dkey] = dom_complete.get(dkey, 0) + 1 + continue + if c.pci_bdf in host_forced_orphans: + incomplete += 1 + continue + pkg = inv_forced_packages.get(c.pci_bdf) + if pkg is None: + pkg = partner_map.get(c.pci_bdf) + if pkg is not None and pkg.issubset(scope_bdfs): + if pkg not in seen_pkgs: + seen_pkgs.add(pkg) + complete += 1 + dom_complete[dkey] = dom_complete.get(dkey, 0) + 1 + else: + incomplete += 1 + return complete, incomplete, dom_complete + + scope_constraints: List[ + Tuple[ + frozenset[str], + Callable[[Optional[int], Dict[str, frozenset[str]]], bool], + ] + ] = [] + + def _add_scope_constraint( + scope_chips: Sequence[DiscoveredChip], + pred: Callable[[Optional[int], Dict[str, frozenset[str]]], bool], + ) -> None: + if chip_id_map is None: + scope_constraints.append((frozenset(c.pci_bdf for c in scope_chips), pred)) + + # Track explicit physical/logical visibility claims (`scope_bdfs`, `chips`, `devs`) + # across selectors to reject provable ordinal contradictions without `--chip-id-map`. + vis_claims: List[ + Tuple[ + str, + frozenset[str], + Optional[frozenset[int]], + Optional[frozenset[int]], + ] + ] = [] expected_slices_by_name: Dict[str, _TopologySlice] = {} expected_slices_by_bdfs: Dict[Tuple[str, ...], _TopologySlice] = {} for topo_slice in _compute_topology_slices( @@ -3056,6 +4575,7 @@ def _verify_spec_against_host_detailed( host_pci_inventory=live_pci_inventory, observed_domain_bdfs=merged_live_observed, bridge_bus_to_roots=live_bridge_roots, + expected_fns_by_bdf=live_per_chip_by_bdf, ): expected_slices_by_bdfs[topo_slice.pci_bdfs] = topo_slice for alias in topo_slice.aliases: @@ -3117,7 +4637,7 @@ def _verify_spec_against_host_detailed( devices = spec.get("devices") if not isinstance(devices, list) or not devices: - return errors + ["devices must be a non-empty list"] + return errors + ["devices must be a non-empty list"], unverifiable # 2. Validate every device's effective containerEdits and deviceNodes (global + per-device). for idx, dev in enumerate(devices): @@ -3223,8 +4743,410 @@ def _verify_spec_against_host_detailed( f"(spec expects PCI BDF(s) {recorded_bdfs}, host currently exposes {expected_live_bdfs})" ) + def _check_topology_meta_annotations( + sel_name: str, + sel_ann: Dict[str, Any], + sel_bdfs: Sequence[str], + ) -> None: + sel_live_chips = [ + live_chips_by_bdf[b] + for b in sel_bdfs + if b in live_chips_by_bdf + ] + sel_gens = {c.generation for c in sel_live_chips} + if "freetpu.dev/vendor-id" in sel_ann: + rec_vid = str(sel_ann.get("freetpu.dev/vendor-id") or "").strip().lower() + live_vids = {c.vendor_id.lower() for c in sel_live_chips} + if len(sel_live_chips) != 1 or rec_vid not in live_vids: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/vendor-id " + f"{sel_ann.get('freetpu.dev/vendor-id')!r} (host expects {sorted(live_vids)!r})" + ) + if "freetpu.dev/device-id" in sel_ann: + rec_did = str(sel_ann.get("freetpu.dev/device-id") or "").strip().lower() + live_dids = {c.device_id.lower() for c in sel_live_chips} + if len(sel_live_chips) != 1 or rec_did not in live_dids: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/device-id " + f"{sel_ann.get('freetpu.dev/device-id')!r} (host expects {sorted(live_dids)!r})" + ) + if "freetpu.dev/generation" in sel_ann: + rec_gen = str(sel_ann.get("freetpu.dev/generation") or "").strip() + if len(sel_live_chips) != 1 or rec_gen != sel_live_chips[0].generation: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/generation " + f"{sel_ann.get('freetpu.dev/generation')!r} (host expects {sorted(sel_gens)!r})" + ) + if "freetpu.dev/generations" in sel_ann: + rec_gens_set = { + g.strip() + for g in str(sel_ann.get("freetpu.dev/generations") or "").split(",") + if g.strip() + } + if not sel_gens or rec_gens_set != sel_gens: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/generations " + f"{sel_ann.get('freetpu.dev/generations')!r} (host expects {','.join(sorted(sel_gens))!r})" + ) + if len(sel_bdfs) == 1 and len(sel_live_chips) == 1: + sc = sel_live_chips[0] + sc_root = sc.pcie_root or _pcie_root_complex(sc.pci_bdf) + if "freetpu.dev/iommu-group" in sel_ann and sel_ann.get("freetpu.dev/iommu-group") != sc.iommu_group: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/iommu-group " + f"{sel_ann.get('freetpu.dev/iommu-group')!r} (host expects {sc.iommu_group!r})" + ) + if "freetpu.dev/pcie-root" in sel_ann and sel_ann.get("freetpu.dev/pcie-root") != sc_root: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/pcie-root " + f"{sel_ann.get('freetpu.dev/pcie-root')!r} (host expects {sc_root!r})" + ) + if "freetpu.dev/driver" in sel_ann and sel_ann.get("freetpu.dev/driver") != sc.driver: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/driver " + f"{sel_ann.get('freetpu.dev/driver')!r} (host expects {sc.driver!r})" + ) + if "freetpu.dev/model" in sel_ann and sel_ann.get("freetpu.dev/model") != sc.model_name: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/model " + f"{sel_ann.get('freetpu.dev/model')!r} (host expects {sc.model_name!r})" + ) + if sc.numa_node is None and "freetpu.dev/numa-node" in sel_ann: + errors.append( + f"device {sel_name!r}: unexpected freetpu.dev/numa-node " + f"{sel_ann.get('freetpu.dev/numa-node')!r} when host sysfs reports no NUMA node" + ) + elif ( + sc.numa_node is not None + and "freetpu.dev/numa-node" in sel_ann + and sel_ann.get("freetpu.dev/numa-node") != str(sc.numa_node) + ): + errors.append( + f"device {sel_name!r}: stale freetpu.dev/numa-node " + f"{sel_ann.get('freetpu.dev/numa-node')!r} (host expects {str(sc.numa_node)!r})" + ) + if len(sel_gens) != 1: + for mixed_k in ( + "freetpu.dev/chiplets-per-pkg", + "freetpu.dev/hbm-gib-per-logical-device", + ): + if mixed_k in sel_ann: + errors.append( + f"device {sel_name!r}: invalid {mixed_k}={sel_ann.get(mixed_k)!r} " + f"for mixed/non-uniform generations {sorted(sel_gens)}" + ) + return + meta = tpu_topology_metadata(next(iter(sel_gens))) + if "freetpu.dev/chiplets-per-pkg" in sel_ann: + exp_cpp = str(meta["chiplets_per_pkg"]) + if sel_ann.get("freetpu.dev/chiplets-per-pkg") != exp_cpp: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/chiplets-per-pkg " + f"{sel_ann.get('freetpu.dev/chiplets-per-pkg')!r} (host expects {exp_cpp!r})" + ) + if "freetpu.dev/hbm-gib-per-logical-device" in sel_ann: + exp_hbm = ( + str(meta["hbm_gib_per_logical_device"]) + if meta["hbm_gib_per_logical_device"] is not None + else None + ) + if exp_hbm is None or sel_ann.get("freetpu.dev/hbm-gib-per-logical-device") != exp_hbm: + errors.append( + f"device {sel_name!r}: stale freetpu.dev/hbm-gib-per-logical-device " + f"{sel_ann.get('freetpu.dev/hbm-gib-per-logical-device')!r} " + f"(host expects {exp_hbm!r})" + ) + + _ASCII_UINT_RE = re.compile(r"^[0-9]+$") + + def _parse_ascii_uint(raw_val: Any) -> Optional[int]: + if ( + not isinstance(raw_val, str) + or len(raw_val) > 5 + or not _ASCII_UINT_RE.match(raw_val) + ): + return None + val = int(raw_val, 10) + return val if 0 <= val <= 65535 else None + + def _collect_capacity_mismatches( + sel_ann: Dict[str, Any], + complete: int, + incomplete: int, + total_fns: int, + scope_noun: str, + *, + require_capacity_complete: bool = True, + ) -> List[str]: + mismatches: List[str] = [] + if "freetpu.dev/chip-count" in sel_ann: + rec_cc = _parse_ascii_uint(sel_ann.get("freetpu.dev/chip-count")) + if rec_cc != complete: + mismatches.append( + f"stale freetpu.dev/chip-count {sel_ann.get('freetpu.dev/chip-count')!r} " + f"(live {scope_noun} has {complete} complete chip(s))" + ) + if "freetpu.dev/capacity-complete" in sel_ann: + rec_cap = sel_ann.get("freetpu.dev/capacity-complete") + if rec_cap not in ("true", "false"): + mismatches.append( + f"invalid freetpu.dev/capacity-complete {rec_cap!r} " + "(expected 'true' or 'false')" + ) + elif incomplete > 0 and rec_cap != "false": + mismatches.append( + f"live {scope_noun} has {incomplete} incomplete PCI endpoint(s) " + "not reflected in freetpu.dev/capacity-complete" + ) + elif incomplete == 0 and rec_cap != "true": + mismatches.append( + f"stale freetpu.dev/capacity-complete='false' on complete {scope_noun}" + ) + elif incomplete > 0 and require_capacity_complete: + mismatches.append( + f"live {scope_noun} has {incomplete} incomplete PCI endpoint(s) " + "not reflected in freetpu.dev/capacity-complete" + ) + if "freetpu.dev/incomplete-pci-functions" in sel_ann: + rec_inc = _parse_ascii_uint(sel_ann.get("freetpu.dev/incomplete-pci-functions")) + if rec_inc != incomplete: + mismatches.append( + f"stale freetpu.dev/incomplete-pci-functions " + f"{sel_ann.get('freetpu.dev/incomplete-pci-functions')!r} " + f"(live {scope_noun} has {incomplete})" + ) + if "freetpu.dev/pci-function-count" in sel_ann: + rec_fn_cnt = _parse_ascii_uint(sel_ann.get("freetpu.dev/pci-function-count")) + if rec_fn_cnt != total_fns: + mismatches.append( + f"stale freetpu.dev/pci-function-count {sel_ann.get('freetpu.dev/pci-function-count')!r} " + f"(live {scope_noun} exposes {total_fns} PCI function(s))" + ) + return mismatches + + def _feasible_paired_outcomes_with_modes( + scope_chips: Sequence[DiscoveredChip], + sel_ann: Optional[Dict[str, Any]], + *, + require_capacity_complete: bool = True, + all_domain_gens: Optional[Sequence[str]] = None, + missing_obs: bool = False, + ) -> List[Tuple[int, int, Optional[int]]]: + if not scope_chips: + return [] + scope_bdfs = {c.pci_bdf for c in scope_chips} + all_doms_set = {_topology_domain_key(c) for c in scope_chips} + fixed_by_dom: Dict[Tuple[str, Optional[int], str], int] = { + dk: 0 for dk in all_doms_set + } + forced_pair_by_dom: Dict[Tuple[str, Optional[int], str], int] = { + dk: 0 for dk in all_doms_set + } + seen_forced_pkgs: set[frozenset[str]] = set() + forced_orphans = 0 + has_tpu7x_in_scope = False + forced_tpu7x_pair = False + tpu7x_forced_orphan = False + free_tpu7x_by_dom: Dict[Tuple[str, Optional[int], str], int] = { + dk: 0 for dk in all_doms_set + } + free_legacy_by_dom: Dict[Tuple[str, Optional[int], str], int] = { + dk: 0 for dk in all_doms_set + } + + for c in scope_chips: + dkey = _topology_domain_key(c) + if c.generation == "tpu7x": + has_tpu7x_in_scope = True + if c.generation not in ("tpu7x", "v2-v3"): + fixed_by_dom[dkey] += 1 + continue + if c.pci_bdf in host_forced_orphans: + forced_orphans += 1 + if c.generation == "tpu7x": + tpu7x_forced_orphan = True + continue + forced_pkg = inv_forced_packages.get(c.pci_bdf) + if forced_pkg is not None: + if forced_pkg.issubset(scope_bdfs): + if forced_pkg not in seen_forced_pkgs: + seen_forced_pkgs.add(forced_pkg) + forced_pair_by_dom[dkey] += 1 + if c.generation == "tpu7x": + forced_tpu7x_pair = True + else: + forced_orphans += 1 + if c.generation == "tpu7x": + tpu7x_forced_orphan = True + continue + if c.generation == "tpu7x": + free_tpu7x_by_dom[dkey] += 1 + else: + free_legacy_by_dom[dkey] += 1 + + tpu7x_one_fn_feasible = bool( + has_tpu7x_in_scope + and live_tpu7x_nomap_per_chip == 1 + and not host_forced_tpu7x_pair + and not host_forced_tpu7x_orphan + and not forced_tpu7x_pair + and not tpu7x_forced_orphan + ) + + def _combine_outcomes(tpu7x_mode: Optional[int]) -> set[Tuple[int, int, Optional[int]]]: + if all_domain_gens is None: + dom_states: set[Tuple[int, int]] = {(0, 0)} + for dk in sorted(all_doms_set): + base_c = fixed_by_dom[dk] + forced_pair_by_dom[dk] + f_leg = free_legacy_by_dom[dk] + f_t7x = free_tpu7x_by_dom[dk] + per_dom_pairs: set[Tuple[int, int]] = set() + t7x_opts = ( + [(f_t7x, 0)] + if tpu7x_mode == 1 + else [ + (tp, f_t7x - 2 * tp) + for tp in range(f_t7x // 2 + 1) + ] + ) + for lp in range(f_leg // 2 + 1): + li = f_leg - 2 * lp + for tc, ti in t7x_opts: + per_dom_pairs.add((base_c + tc + lp, ti + li)) + nxt: set[Tuple[int, int]] = set() + for dc, di in per_dom_pairs: + for ac, ai in dom_states: + nxt.add((ac + dc, ai + di)) + dom_states = nxt + return {(cc, forced_orphans + ci, tpu7x_mode) for cc, ci in dom_states} + + # When `all_domain_gens` is supplied, retain exact sorted per-domain + # complete chip counts so cross-root split checks apply per layout. + full_states: set[Tuple[int, int, Tuple[int, ...]]] = {(0, 0, ())} + for dk in sorted(all_doms_set): + base_c = fixed_by_dom[dk] + forced_pair_by_dom[dk] + f_leg = free_legacy_by_dom[dk] + f_t7x = free_tpu7x_by_dom[dk] + per_dom_pairs = set() + t7x_opts = ( + [(f_t7x, 0)] + if tpu7x_mode == 1 + else [(tp, f_t7x - 2 * tp) for tp in range(f_t7x // 2 + 1)] + ) + for lp in range(f_leg // 2 + 1): + li = f_leg - 2 * lp + for tc, ti in t7x_opts: + per_dom_pairs.add((base_c + tc + lp, ti + li)) + nxt_full: set[Tuple[int, int, Tuple[int, ...]]] = set() + for dc, di in per_dom_pairs: + for ac, ai, d_tup in full_states: + nd = tuple(sorted(d_tup + (dc,))) if dc > 0 else d_tup + nxt_full.add((ac + dc, ai + di, nd)) + full_states = nxt_full + return { + (cc, forced_orphans + ci, tpu7x_mode) + for cc, ci, d_tup in full_states + if forced_orphans + ci == 0 + and (cc < 2 or not missing_obs) + and _is_supported_all_domain_counts(cc, list(d_tup), all_domain_gens) + } + + raw_with_modes: set[Tuple[int, int, Optional[int]]] = set() + if not has_tpu7x_in_scope: + raw_with_modes |= _combine_outcomes(None) + else: + raw_with_modes |= _combine_outcomes(2) + if tpu7x_one_fn_feasible: + raw_with_modes |= _combine_outcomes(1) + + full_outcomes = sorted(raw_with_modes, reverse=True) + if sel_ann is None: + return full_outcomes + return [ + (cc, ci, md) + for cc, ci, md in full_outcomes + if not _collect_capacity_mismatches( + sel_ann, + cc, + ci, + len(scope_chips), + "scope", + require_capacity_complete=require_capacity_complete, + ) + ] + + def _feasible_paired_outcomes( + scope_chips: Sequence[DiscoveredChip], + sel_ann: Optional[Dict[str, Any]], + *, + require_capacity_complete: bool = True, + ) -> List[Tuple[int, int]]: + return sorted( + { + (cc, ci) + for cc, ci, _md in _feasible_paired_outcomes_with_modes( + scope_chips, + sel_ann, + require_capacity_complete=require_capacity_complete, + ) + }, + reverse=True, + ) + + def _collect_effective_env_keys(keys: Sequence[str]) -> Dict[str, str]: + out_env: Dict[str, str] = {} + for env_src in ( + global_edits.get("env") if isinstance(global_edits, dict) else None, + edits.get("env") if isinstance(edits, dict) else None, + ): + if isinstance(env_src, list): + for entry in env_src: + if isinstance(entry, str) and "=" in entry: + ek, ev = entry.split("=", 1) + if ek in keys: + out_env[ek] = ev + return out_env + + _topo_env_keys = ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE", "TPU_SKIP_MDS_QUERY") + _composable_forbidden_env_keys = _topo_env_keys + ("TPU_VISIBLE_CHIPS", "TPU_VISIBLE_DEVICES") + _mds_companions = ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE") + + def _topo_env_matches(inj: Dict[str, str], exp: Dict[str, str]) -> bool: + if any(exp.get(ek) is None or ev != exp.get(ek) for ek, ev in inj.items()): + return False + if inj.get("TPU_SKIP_MDS_QUERY") == "true": + if any( + ck not in inj or exp.get(ck) is None or inj[ck] != exp[ck] + for ck in _mds_companions + ): + return False + return True + + def _collect_topo_env_mismatches( + inj: Dict[str, str], + exp: Dict[str, str], + exp_label: str, + ) -> List[str]: + mismatches: List[str] = [] + for ek, ev in inj.items(): + exp_v = exp.get(ek) + if exp_v is None or ev != exp_v: + mismatches.append(f"stale injected {ek}={ev!r} ({exp_label} {exp_v!r})") + if inj.get("TPU_SKIP_MDS_QUERY") == "true": + for ck in _mds_companions: + if ck not in inj: + mismatches.append( + f"injected TPU_SKIP_MDS_QUERY='true' requires companion {ck}={exp.get(ck)!r}" + ) + return mismatches + if isinstance(name, str): + _check_topology_meta_annotations(name, ann, expected_live_bdfs) if name.startswith("pci-"): + for ek, ev in _collect_effective_env_keys(_composable_forbidden_env_keys).items(): + errors.append( + f"device {name!r}: composable PCI selector must not inject {ek}={ev!r}" + ) if len(expected_live_bdfs) != 1 or name != _single_chip_selector(expected_live_bdfs[0]): expected_sel = ( _single_chip_selector(expected_live_bdfs[0]) @@ -3235,14 +5157,237 @@ def _verify_spec_against_host_detailed( f"device {name!r}: PCI selector name does not match verified VFIO group " f"membership {expected_live_bdfs} (expected selector {expected_sel!r})" ) + elif expected_live_bdfs[0] in live_chips_by_bdf: + single_live = live_chips_by_bdf[expected_live_bdfs[0]] + exp_per_chip = live_per_chip_by_bdf.get( + single_live.pci_bdf, + _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(single_live.generation, 1), + ) + exp_unit_label = "single-chiplet" if exp_per_chip > 1 else "single-chip" + rec_unit = ann.get("freetpu.dev/allocation-unit") + live_tpu7x_count = sum( + 1 for c in live_pci_inventory if c.generation == "tpu7x" + ) + forced_tpu7x_two_fn = single_live.generation == "tpu7x" and ( + single_live.device_id == "0x0076" + or not single_live.pci_bdf.endswith(".0") + or live_tpu7x_count > 4 + or host_forced_tpu7x_pair + or host_forced_tpu7x_orphan + or (chip_id_map is None and exp_per_chip == 2) + ) + sgl_complete, sgl_inc = _count_complete_chips( + [single_live], + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, + ) + baseline_mode: Optional[int] = ( + (2 if exp_per_chip > 1 else 1) + if single_live.generation == "tpu7x" + else None + ) + baseline_state = (exp_unit_label, sgl_complete, sgl_inc, baseline_mode) + cand_sgl_states = [baseline_state] + if ( + chip_id_map is None + and ann.get("freetpu.dev/chip-id-source") == "chip-id-map" + and single_live.generation == "tpu7x" + and not forced_tpu7x_two_fn + ): + cand_sgl_states = [("single-chip", 1, 0, 1), ("single-chiplet", 0, 1, 2)] + + matching_sgl_states = [ + st + for st in cand_sgl_states + if (rec_unit is None or rec_unit == st[0]) + and not _collect_capacity_mismatches( + ann, + st[1], + st[2], + 1, + "device", + require_capacity_complete=False, + ) + ] + if matching_sgl_states: + if has_live_tpu7x and single_live.generation == "tpu7x": + allowed_tpu7x_modes &= { + st[3] for st in matching_sgl_states if st[3] is not None + } + def _pci_pred( + lm: Optional[int], + _pm: Dict[str, frozenset[str]], + *, + _sgl: DiscoveredChip = single_live, + _ann: Dict[str, Any] = ann, + _rec_unit: Optional[str] = rec_unit, + _exp_p: int = exp_per_chip, + ) -> bool: + if _sgl.generation == "tpu7x": + eff_p = lm if lm is not None else 2 + else: + eff_p = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get( + _sgl.generation, 1 + ) + if ( + _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and eff_p != _exp_p + ): + return False + eff_u = "single-chiplet" if eff_p > 1 else "single-chip" + if _rec_unit is not None and _rec_unit != eff_u: + return False + s_c, s_i = (0, 1) if eff_p > 1 else (1, 0) + return not _collect_capacity_mismatches( + _ann, s_c, s_i, 1, "device", require_capacity_complete=False + ) + + _add_scope_constraint([single_live], _pci_pred) + if baseline_state not in matching_sgl_states: + unverifiable.append( + f"device {name!r}: map-dependent allocation-unit/capacity " + "cannot be verified without --chip-id-map" + ) + else: + if has_live_tpu7x and single_live.generation == "tpu7x": + allowed_tpu7x_modes.clear() + if rec_unit is not None and rec_unit != exp_unit_label: + errors.append( + f"device {name!r}: stale freetpu.dev/allocation-unit {rec_unit!r} " + f"(host expects {exp_unit_label!r})" + ) + for s_err in _collect_capacity_mismatches( + ann, + sgl_complete, + sgl_inc, + 1, + "device", + require_capacity_complete=False, + ): + errors.append(f"device {name!r}: {s_err}") elif name.startswith("group-pci-"): + for ek, ev in _collect_effective_env_keys(_composable_forbidden_env_keys).items(): + errors.append( + f"device {name!r}: composable PCI selector must not inject {ek}={ev!r}" + ) expected_sel = _shared_group_selector(expected_live_bdfs) if name != expected_sel: errors.append( f"device {name!r}: shared-group PCI selector name does not match verified " f"VFIO group membership {expected_live_bdfs} (expected selector {expected_sel!r})" ) + elif all(b in live_chips_by_bdf for b in expected_live_bdfs): + grp_live_chips = [live_chips_by_bdf[b] for b in expected_live_bdfs] + grp_complete, grp_incomplete = _count_complete_chips( + grp_live_chips, + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, + ) + grp_mismatches = _collect_capacity_mismatches( + ann, grp_complete, grp_incomplete, len(grp_live_chips), "group" + ) + grp_modes_with = _feasible_paired_outcomes_with_modes(grp_live_chips, ann) + if grp_mismatches: + if ( + chip_id_map is None + and ann.get("freetpu.dev/chip-id-source") == "chip-id-map" + and grp_modes_with + ): + if has_live_tpu7x and any(c.generation == "tpu7x" for c in grp_live_chips): + allowed_tpu7x_modes &= { + md for _cc, _ci, md in grp_modes_with if md is not None + } + def _grp_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _grp: List[DiscoveredChip] = list(grp_live_chips), + _ann: Dict[str, Any] = ann, + ) -> bool: + cc, ci, _dom = _eval_scope_layout(_grp, lm, pm) + return not _collect_capacity_mismatches( + _ann, cc, ci, len(_grp), "group" + ) + + _add_scope_constraint(grp_live_chips, _grp_pred) + unverifiable.append( + f"device {name!r}: map-dependent shared-group chip pairing " + "cannot be verified without --chip-id-map" + ) + else: + for g_err in grp_mismatches: + errors.append(f"device {name!r}: {g_err}") + else: + if has_live_tpu7x and any(c.generation == "tpu7x" for c in grp_live_chips): + grp_md = {md for _cc, _ci, md in grp_modes_with if md is not None} + if grp_md: + allowed_tpu7x_modes &= grp_md + + def _grp_direct_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _grp: List[DiscoveredChip] = list(grp_live_chips), + _ann: Dict[str, Any] = ann, + ) -> bool: + if ( + _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and any(c.generation == "tpu7x" for c in _grp) + and lm != live_tpu7x_nomap_per_chip + ): + return False + cc, ci, _dom = _eval_scope_layout(_grp, lm, pm) + return not _collect_capacity_mismatches( + _ann, cc, ci, len(_grp), "group" + ) + + _add_scope_constraint(grp_live_chips, _grp_direct_pred) elif name.startswith("numa") or name.startswith("pcie") or _RANGE_SLICE_RE.match(name): + sl_live_chips: List[DiscoveredChip] = [] + sl_modes_with: List[Tuple[int, int, Optional[int]]] = [] + if all(b in live_chips_by_bdf for b in expected_live_bdfs): + sl_live_chips = [live_chips_by_bdf[b] for b in expected_live_bdfs] + sl_complete, sl_inc = _count_complete_chips( + sl_live_chips, + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, + ) + sl_mismatches = _collect_capacity_mismatches( + ann, sl_complete, sl_inc, len(sl_live_chips), "slice" + ) + sl_modes_with = _feasible_paired_outcomes_with_modes(sl_live_chips, ann) + sl_map_fallback_ok = bool( + chip_id_map is None + and ann.get("freetpu.dev/chip-id-source") == "chip-id-map" + and sl_modes_with + ) + if sl_mismatches and not sl_map_fallback_ok: + for sl_err in sl_mismatches: + errors.append(f"device {name!r}: {sl_err}") + else: + if has_live_tpu7x and any(c.generation == "tpu7x" for c in sl_live_chips): + sl_md = {md for _cc, _ci, md in sl_modes_with if md is not None} + if sl_md: + allowed_tpu7x_modes &= sl_md + def _sl_cap_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _sl: List[DiscoveredChip] = list(sl_live_chips), + _ann: Dict[str, Any] = ann, + ) -> bool: + if ( + _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and any(c.generation == "tpu7x" for c in _sl) + and lm != live_tpu7x_nomap_per_chip + ): + return False + cc, ci, _dom = _eval_scope_layout(_sl, lm, pm) + return not _collect_capacity_mismatches( + _ann, cc, ci, len(_sl), "slice" + ) + + _add_scope_constraint(sl_live_chips, _sl_cap_pred) slice_domains = { _topology_domain_key(live_chips_by_bdf[b]) for b in expected_live_bdfs @@ -3262,9 +5407,13 @@ def _verify_spec_against_host_detailed( ) range_width_matches = False if range_match is not None and live_slice_for_bdfs is not None: - start_idx, end_idx = (int(p) for p in name.split("-", 1)) + r_parts = name.split("-", 1) + start_idx = _parse_ascii_uint(r_parts[0]) + end_idx = _parse_ascii_uint(r_parts[1]) range_width_matches = ( - end_idx >= start_idx + start_idx is not None + and end_idx is not None + and end_idx >= start_idx and (end_idx - start_idx + 1) == len(live_slice_for_bdfs.physical_indices) ) @@ -3282,7 +5431,10 @@ def _verify_spec_against_host_detailed( unpaired_map_match = False if ( chip_id_map is None - and live_slice_for_bdfs is None + and ( + live_slice_for_bdfs is None + or (not range_width_matches and uses_explicit_chip_map) + ) and len(slice_domains) == 1 and expected_live_bdfs and all(b in live_chips_by_bdf for b in expected_live_bdfs) @@ -3308,17 +5460,31 @@ def _verify_spec_against_host_detailed( for c in slice_live_chips ) slice_per_chip_set = { - _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + live_per_chip_by_bdf.get( + c.pci_bdf, _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + ) for c in slice_live_chips } slice_gens_live: List[str] = [] for c in slice_live_chips: if c.generation not in slice_gens_live: slice_gens_live.append(c.generation) - needs_map_pairing = ( - len(slice_per_chip_set) == 1 - and next(iter(slice_per_chip_set)) > 1 - and not _has_complete_chip_functions(slice_live_chips, live_bdf_to_phys) + base_per_chip_set = ( + slice_per_chip_set if len(slice_per_chip_set) == 1 else set() + ) + cand_per_chips = sorted(base_per_chip_set) + if ( + base_per_chip_set == {1} + and slice_gens_live == ["tpu7x"] + and live_tpu7x_nomap_per_chip == 1 + and not host_forced_tpu7x_pair + and not host_forced_tpu7x_orphan + ): + cand_per_chips = [1, 2] + slice_is_nomap_complete = _has_complete_chip_functions( + slice_live_chips, + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, ) live_slice_vis_nomap = _resolve_verified_visibility_ordinals( slice_live_chips, @@ -3326,6 +5492,8 @@ def _verify_spec_against_host_detailed( live_bdf_to_phys, chip_id_map=None, host_pci_inventory=live_pci_inventory, + expected_fns_by_bdf=live_per_chip_by_bdf, + observed_domain_bdfs=merged_live_observed, ) needs_map_noncontig = bool( live_slice_vis_nomap is not None @@ -3337,64 +5505,116 @@ def _verify_spec_against_host_detailed( ) ) ) + valid_unpaired_states: set[Tuple[int, Optional[int]]] = set() if ( expected_live_bdfs == domain_expected_bdfs and not splits_iommu - and len(slice_per_chip_set) == 1 - and (needs_map_pairing or needs_map_noncontig) + and cand_per_chips ): - per_chip = next(iter(slice_per_chip_set)) - if len(slice_live_chips) % per_chip == 0: + sl_feas = sl_modes_with or _feasible_paired_outcomes_with_modes( + slice_live_chips, ann + ) + for per_chip in cand_per_chips: + needs_map_p = ( + per_chip > 1 + and (not slice_is_nomap_complete or per_chip not in slice_per_chip_set) + ) or ( + per_chip in slice_per_chip_set and needs_map_noncontig + ) + if not needs_map_p or len(slice_live_chips) % per_chip != 0: + continue inferred_chips = len(slice_live_chips) // per_chip - if _is_supported_single_host_chip_count( + if not any( + cc == inferred_chips + and ci == 0 + and (md is None or md == per_chip) + for cc, ci, md in sl_feas + ): + continue + if not _is_supported_single_host_chip_count( inferred_chips, slice_gens_live, subhost_slice=True ): - dom_numa = domain_key[1] - dom_root = domain_key[2] - dom_root_token = _pci_bdf_token(dom_root) - expected_hw_name = ( - f"numa{dom_numa}-pcie-{dom_root_token}-{inferred_chips}" - if dom_numa is not None - else f"pcie-{dom_root_token}-{inferred_chips}" + continue + dom_numa = domain_key[1] + dom_root = domain_key[2] + dom_root_token = _pci_bdf_token(dom_root) + expected_hw_name = ( + f"numa{dom_numa}-pcie-{dom_root_token}-{inferred_chips}" + if dom_numa is not None + else f"pcie-{dom_root_token}-{inferred_chips}" + ) + name_matches = name == expected_hw_name + if not name_matches and range_match is not None: + r_parts = name.split("-", 1) + start_idx = _parse_ascii_uint(r_parts[0]) + end_idx = _parse_ascii_uint(r_parts[1]) + name_matches = ( + start_idx is not None + and end_idx is not None + and end_idx >= start_idx + and (end_idx - start_idx + 1) == inferred_chips ) - name_matches = name == expected_hw_name - if not name_matches and range_match is not None: - start_idx, end_idx = (int(p) for p in name.split("-", 1)) - name_matches = ( - end_idx >= start_idx - and (end_idx - start_idx + 1) == inferred_chips - ) - chip_count_ok = ( - "freetpu.dev/chip-count" not in ann - or ann.get("freetpu.dev/chip-count") == str(inferred_chips) + chip_count_ok = ( + "freetpu.dev/chip-count" not in ann + or _parse_ascii_uint(ann.get("freetpu.dev/chip-count")) + == inferred_chips + ) + exp_slice_topo = dict( + kv.split("=", 1) + for kv in _build_device_env( + inferred_chips, + slice_gens_live, + single_host_env=True, + include_bounds_env=True, + verified_visibility=None, + omit_visible_env=True, ) - exp_slice_topo = dict( - kv.split("=", 1) - for kv in _build_device_env( + if "=" in kv + ) + topo_env_ok = True + for env_src in ( + global_edits.get("env") if isinstance(global_edits, dict) else None, + edits.get("env") if isinstance(edits, dict) else None, + ): + if isinstance(env_src, list): + for entry in env_src: + if isinstance(entry, str) and "=" in entry: + ek, ev = entry.split("=", 1) + if ek in ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE", "TPU_SKIP_MDS_QUERY"): + if ev != exp_slice_topo.get(ek): + topo_env_ok = False + if name_matches and chip_count_ok and topo_env_ok: + valid_unpaired_states.add( + ( inferred_chips, - slice_gens_live, - single_host_env=True, - include_bounds_env=True, - verified_visibility=None, - omit_visible_env=True, + per_chip if "tpu7x" in slice_gens_live else None, ) - if "=" in kv ) - topo_env_ok = True - for env_src in ( - global_edits.get("env") if isinstance(global_edits, dict) else None, - edits.get("env") if isinstance(edits, dict) else None, - ): - if isinstance(env_src, list): - for entry in env_src: - if isinstance(entry, str) and "=" in entry: - ek, ev = entry.split("=", 1) - if ek in ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE", "TPU_SKIP_MDS_QUERY"): - if ev.strip() != exp_slice_topo.get(ek): - topo_env_ok = False - if name_matches and chip_count_ok and topo_env_ok: - unpaired_map_match = True - unpaired_domain_check = (dom_numa, dom_root) + unpaired_domain_check = (dom_numa, dom_root) + if valid_unpaired_states: + unpaired_map_match = True + if has_live_tpu7x and "tpu7x" in slice_gens_live: + allowed_tpu7x_modes &= { + st_md + for _st_cc, st_md in valid_unpaired_states + if st_md is not None + } + + def _unp_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _sl: List[DiscoveredChip] = list(slice_live_chips), + _valid: frozenset[Tuple[int, Optional[int]]] = frozenset( + valid_unpaired_states + ), + _has_t7x: bool = "tpu7x" in slice_gens_live, + ) -> bool: + cc, ci, _dom = _eval_scope_layout(_sl, lm, pm) + eff_md = lm if _has_t7x else None + return ci == 0 and (cc, eff_md) in _valid + + _add_scope_constraint(slice_live_chips, _unp_pred) if ( range_width_matches @@ -3492,24 +5712,11 @@ def _verify_spec_against_host_detailed( ) if "=" in kv ) - slice_injected_topo: Dict[str, str] = {} - for env_src in ( - global_edits.get("env") if isinstance(global_edits, dict) else None, - edits.get("env") if isinstance(edits, dict) else None, + slice_injected_topo = _collect_effective_env_keys(_topo_env_keys) + for sl_topo_err in _collect_topo_env_mismatches( + slice_injected_topo, slice_expected_topo, "live host slice expects" ): - if isinstance(env_src, list): - for entry in env_src: - if isinstance(entry, str) and "=" in entry: - ek, ev = entry.split("=", 1) - if ek in ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE", "TPU_SKIP_MDS_QUERY"): - slice_injected_topo[ek] = ev.strip() - for ek, ev in slice_injected_topo.items(): - exp_v = slice_expected_topo.get(ek) - if exp_v is None or ev != exp_v: - errors.append( - f"device {name!r}: stale injected {ek}={ev!r} " - f"(live host slice expects {exp_v!r})" - ) + errors.append(f"device {name!r}: {sl_topo_err}") elif name == "all": all_pci_bdfs = sorted(c.pci_bdf for c in live_pci_inventory) if expected_live_bdfs != all_pci_bdfs: @@ -3527,10 +5734,15 @@ def _verify_spec_against_host_detailed( if c.generation not in live_all_gens: live_all_gens.append(c.generation) live_all_complete, live_all_incomplete = _count_complete_chips( - live_chips, live_bdf_to_phys + live_chips, + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, ) live_all_supported_base = _is_supported_all_topology( - live_chips, live_bdf_to_phys, live_all_gens + live_chips, + live_bdf_to_phys, + live_all_gens, + expected_fns_by_bdf=live_per_chip_by_bdf, ) live_all_supported = live_all_supported_base live_all_vis = _resolve_verified_visibility_ordinals( @@ -3539,6 +5751,8 @@ def _verify_spec_against_host_detailed( live_bdf_to_phys, chip_id_map=chip_id_map, host_pci_inventory=live_pci_inventory, + expected_fns_by_bdf=live_per_chip_by_bdf, + observed_domain_bdfs=merged_live_observed, ) live_obs_bdfs: set[str] = set() for dom_bdfs in merged_live_observed.values(): @@ -3591,31 +5805,17 @@ def _verify_spec_against_host_detailed( if isinstance(entry, str) and "=" in entry: ek, ev = entry.split("=", 1) if ek in ("TPU_CHIPS_PER_HOST_BOUNDS", "TPU_ACCELERATOR_TYPE", "TPU_SKIP_MDS_QUERY"): - all_injected_topo[ek] = ev.strip() - all_mismatches: List[str] = [] - if ( - "freetpu.dev/chip-count" in ann - and ann.get("freetpu.dev/chip-count") != str(live_all_complete) - ): - all_mismatches.append( - f"stale freetpu.dev/chip-count {ann.get('freetpu.dev/chip-count')!r} " - f"(live host has {live_all_complete} complete chip(s))" - ) - if ( - live_all_incomplete > 0 - and ann.get("freetpu.dev/capacity-complete") != "false" - ): - all_mismatches.append( - f"live host has {live_all_incomplete} incomplete multi-function PCI " - "endpoint(s) not reflected in freetpu.dev/capacity-complete" + all_injected_topo[ek] = ev + all_mismatches = _collect_capacity_mismatches( + ann, live_all_complete, live_all_incomplete, len(live_chips), "host" + ) + all_mismatches.extend( + _collect_topo_env_mismatches( + all_injected_topo, + expected_all_topo if live_all_supported else {}, + "live host topology authorizes", ) - for ek, ev in all_injected_topo.items(): - exp_v = expected_all_topo.get(ek) - if not live_all_supported or exp_v is None or ev != exp_v: - all_mismatches.append( - f"stale injected {ek}={ev!r} " - f"(live host topology authorizes {exp_v!r})" - ) + ) if all_mismatches: uses_explicit_chip_map_all = ( ann.get("freetpu.dev/chip-id-source") == "chip-id-map" @@ -3636,21 +5836,144 @@ def _verify_spec_against_host_detailed( live_noncontig_sysfs and live_all_supported_base and not live_missing_obs - and ( - "freetpu.dev/chip-count" not in ann - or ann.get("freetpu.dev/chip-count") == str(live_all_complete) - ) - and all( - ev == base_topo_env.get(ek) - for ek, ev in all_injected_topo.items() + and not _collect_capacity_mismatches( + ann, live_all_complete, live_all_incomplete, len(live_chips), "host" ) + and _topo_env_matches(all_injected_topo, base_topo_env) ) + plausible_paired_all = False + plausible_all_modes: set[int] = set() + if chip_id_map is None and uses_explicit_chip_map_all: + def _all_map_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _ann: Dict[str, Any] = ann, + _inj: Dict[str, str] = dict(all_injected_topo), + _noncontig: bool = noncontig_map_only, + ) -> bool: + cc, ci, dom_counts = _eval_scope_layout(live_chips, lm, pm) + if ( + _noncontig + and (lm is None or lm == live_tpu7x_nomap_per_chip) + and (cc, ci) == (live_all_complete, live_all_incomplete) + ): + return True + if _collect_capacity_mismatches( + _ann, cc, ci, len(live_chips), "host" + ): + return False + dom_list = sorted(v for v in dom_counts.values() if v > 0) + p_sup = ( + cc >= 1 + and ci == 0 + and (cc < 2 or not live_missing_obs) + and _is_supported_all_domain_counts(cc, dom_list, live_all_gens) + ) + p_env = dict( + kv.split("=", 1) + for kv in _build_device_env( + cc, + live_all_gens, + single_host_env=True, + include_bounds_env=p_sup, + verified_visibility=None, + omit_visible_env=True, + ) + if "=" in kv + ) + return _topo_env_matches(_inj, p_env) + + all_bk_keys = sorted(free_buckets) + test_all_modes = ( + ([1] if mode1_allowed else []) + [2] + if has_live_tpu7x + else [None] + ) + rep_comb_total = 0 + for tm in test_all_modes: + mode_prod = 1 + for bk in all_bk_keys: + if bk[0] == "tpu7x" and tm == 1: + continue + mode_prod *= len(free_buckets[bk]) // 2 + 1 + rep_comb_total += mode_prod + + if rep_comb_total <= 4096: + for tm in test_all_modes: + bk_reps: List[Dict[str, frozenset[str]]] = [{}] + for bk in all_bk_keys: + items = free_buckets[bk] + if bk[0] == "tpu7x" and tm == 1: + continue + choices: List[Dict[str, frozenset[str]]] = [] + for p_cnt in range(len(items) // 2 + 1): + pm_part: Dict[str, frozenset[str]] = {} + for pi in range(p_cnt): + pr = frozenset( + (items[2 * pi], items[2 * pi + 1]) + ) + pm_part[items[2 * pi]] = pr + pm_part[items[2 * pi + 1]] = pr + choices.append(pm_part) + nxt_reps: List[Dict[str, frozenset[str]]] = [] + for cur_r in bk_reps: + for ch_r in choices: + if not ch_r: + nxt_reps.append(cur_r) + elif not cur_r: + nxt_reps.append(ch_r) + else: + merged_r = dict(cur_r) + merged_r.update(ch_r) + nxt_reps.append(merged_r) + bk_reps = nxt_reps + if any(_all_map_pred(tm, rpm) for rpm in bk_reps): + plausible_paired_all = True + if tm is not None: + plausible_all_modes.add(tm) + else: + sup_dom_matches = _feasible_paired_outcomes_with_modes( + live_chips, + ann, + all_domain_gens=live_all_gens, + missing_obs=live_missing_obs, + ) + for paired_chips, paired_inc, md in _feasible_paired_outcomes_with_modes( + live_chips, ann + ): + paired_supported = any( + sc == paired_chips and si == paired_inc and sm == md + for sc, si, sm in sup_dom_matches + ) + paired_topo_env = dict( + kv.split("=", 1) + for kv in _build_device_env( + paired_chips, + live_all_gens, + single_host_env=True, + include_bounds_env=paired_supported, + verified_visibility=None, + omit_visible_env=True, + ) + if "=" in kv + ) + if _topo_env_matches(all_injected_topo, paired_topo_env): + plausible_paired_all = True + if md is not None: + plausible_all_modes.add(md) + if plausible_paired_all: + _add_scope_constraint(live_chips, _all_map_pred) if ( chip_id_map is None and uses_explicit_chip_map_all - and not live_missing_obs - and (live_all_incomplete > 0 or noncontig_map_only) + and (plausible_paired_all or noncontig_map_only) ): + if has_live_tpu7x: + if plausible_paired_all and not noncontig_map_only: + allowed_tpu7x_modes &= plausible_all_modes + elif live_tpu7x_nomap_per_chip in (1, 2): + allowed_tpu7x_modes &= {live_tpu7x_nomap_per_chip} unverifiable.append( "device 'all': map-dependent chip pairing/topology " "cannot be verified without --chip-id-map " @@ -3659,12 +5982,254 @@ def _verify_spec_against_host_detailed( else: for m_err in all_mismatches: errors.append(f"device 'all': {m_err}") + else: + if has_live_tpu7x: + direct_all_modes = { + md + for cc, ci, md in _feasible_paired_outcomes_with_modes(live_chips, ann) + if cc == live_all_complete + and ci == live_all_incomplete + and md is not None + } + if direct_all_modes: + allowed_tpu7x_modes &= direct_all_modes + + def _all_direct_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _ann: Dict[str, Any] = ann, + _inj: Dict[str, str] = dict(all_injected_topo), + ) -> bool: + if ( + has_live_tpu7x + and _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and lm != live_tpu7x_nomap_per_chip + ): + return False + cc, ci, dom_counts = _eval_scope_layout(live_chips, lm, pm) + if _collect_capacity_mismatches( + _ann, cc, ci, len(live_chips), "host" + ): + return False + dom_list = sorted(v for v in dom_counts.values() if v > 0) + p_sup = ( + cc >= 1 + and ci == 0 + and (cc < 2 or not live_missing_obs) + and _is_supported_all_domain_counts(cc, dom_list, live_all_gens) + ) + if ( + _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and cc >= 2 + and (live_missing_obs or live_missing_map or live_noncontig_sysfs) + ): + p_sup = False + p_env = dict( + kv.split("=", 1) + for kv in _build_device_env( + cc, + live_all_gens, + single_host_env=True, + include_bounds_env=p_sup, + verified_visibility=None, + omit_visible_env=True, + ) + if "=" in kv + ) + return _topo_env_matches(_inj, p_env) + + _add_scope_constraint(live_chips, _all_direct_pred) + else: + if expected_live_bdfs and all(b in live_chips_by_bdf for b in expected_live_bdfs): + cust_chips = [live_chips_by_bdf[b] for b in expected_live_bdfs] + cust_gens = list(dict.fromkeys(c.generation for c in cust_chips)) + cust_complete, cust_inc = _count_complete_chips( + cust_chips, + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, + ) + cust_doms = {_topology_domain_key(c) for c in cust_chips} + cust_bdfs_set = {c.pci_bdf for c in cust_chips} + cust_covers_all = cust_bdfs_set == {c.pci_bdf for c in live_chips} + cust_obs_bdfs = ( + {b for bset in merged_live_observed.values() for b in bset} + if cust_covers_all + else {b for dk in cust_doms for b in merged_live_observed.get(dk, set())} + ) + cust_missing_obs = bool( + cust_obs_bdfs and not cust_obs_bdfs.issubset(cust_bdfs_set) + ) + cust_extra_map_missing = bool( + chip_id_map and any(b not in cust_bdfs_set for b in chip_id_map) + ) + cust_all_mapped = bool( + chip_id_map and all(c.pci_bdf in chip_id_map for c in cust_chips) + ) + cust_noncontig_sysfs = bool( + not cust_all_mapped + and cust_complete >= 2 + and all(c.runtime_chip_id is not None for c in cust_chips) + and len({c.runtime_chip_id for c in cust_chips}) >= 2 + ) + if cust_noncontig_sysfs: + cust_vis = _resolve_verified_visibility_ordinals( + cust_chips, + live_chips, + live_bdf_to_phys, + chip_id_map=chip_id_map, + host_pci_inventory=live_pci_inventory, + expected_fns_by_bdf=live_per_chip_by_bdf, + observed_domain_bdfs=merged_live_observed, + ) + cust_noncontig_sysfs = bool( + cust_vis is not None + and len(cust_vis[0]) >= 2 + and cust_vis[0] + != list(range(cust_vis[0][0], cust_vis[0][0] + len(cust_vis[0]))) + ) + cust_supported_base = _is_supported_all_topology( + cust_chips, + live_bdf_to_phys, + cust_gens, + expected_fns_by_bdf=live_per_chip_by_bdf, + ) + cust_supported = cust_supported_base and not ( + cust_complete >= 2 + and ( + cust_missing_obs + or (cust_covers_all and cust_extra_map_missing) + or cust_noncontig_sysfs + ) + ) + cust_expected_topo = dict( + kv.split("=", 1) + for kv in _build_device_env( + cust_complete, + cust_gens, + single_host_env=True, + include_bounds_env=cust_supported, + verified_visibility=None, + omit_visible_env=True, + ) + if "=" in kv + ) + cust_injected_topo = _collect_effective_env_keys(_topo_env_keys) + cust_mismatches = _collect_capacity_mismatches( + ann, + cust_complete, + cust_inc, + len(cust_chips), + "selector", + require_capacity_complete=False, + ) + cust_mismatches.extend( + _collect_topo_env_mismatches( + cust_injected_topo, + cust_expected_topo if cust_supported else {}, + "live host selector authorizes", + ) + ) + cust_modes_with = _feasible_paired_outcomes_with_modes( + cust_chips, + ann, + require_capacity_complete=False, + all_domain_gens=cust_gens if cust_injected_topo else None, + missing_obs=cust_missing_obs, + ) + cust_matching_modes: List[Optional[int]] = [] + for pc, pi, md in cust_modes_with: + p_sup_c = pc >= 1 and pi == 0 and (pc < 2 or not cust_missing_obs) + p_topo = dict( + kv.split("=", 1) + for kv in _build_device_env( + pc, + cust_gens, + single_host_env=True, + include_bounds_env=p_sup_c, + verified_visibility=None, + omit_visible_env=True, + ) + if "=" in kv + ) + if _topo_env_matches(cust_injected_topo, p_topo): + cust_matching_modes.append(md) + cust_map_fallback_ok = bool( + chip_id_map is None + and ann.get("freetpu.dev/chip-id-source") == "chip-id-map" + and cust_matching_modes + ) + if cust_mismatches and not cust_map_fallback_ok: + for c_err in cust_mismatches: + errors.append(f"device {name!r}: {c_err}") + else: + if has_live_tpu7x and any(c.generation == "tpu7x" for c in cust_chips): + cust_md = {md for md in cust_matching_modes if md is not None} + if cust_md: + allowed_tpu7x_modes &= cust_md + def _cust_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _cust: List[DiscoveredChip] = list(cust_chips), + _ann: Dict[str, Any] = ann, + _gens: List[str] = list(cust_gens), + _inj: Dict[str, str] = dict(cust_injected_topo), + _miss_obs: bool = cust_missing_obs, + ) -> bool: + if ( + _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and any(c.generation == "tpu7x" for c in _cust) + and lm != live_tpu7x_nomap_per_chip + ): + return False + cc, ci, dom_counts = _eval_scope_layout(_cust, lm, pm) + if _collect_capacity_mismatches( + _ann, + cc, + ci, + len(_cust), + "selector", + require_capacity_complete=False, + ): + return False + if _inj: + dom_list = sorted(v for v in dom_counts.values() if v > 0) + p_sup = ( + cc >= 1 + and ci == 0 + and (cc < 2 or not _miss_obs) + and _is_supported_all_domain_counts(cc, dom_list, _gens) + ) + p_env = dict( + kv.split("=", 1) + for kv in _build_device_env( + cc, + _gens, + single_host_env=True, + include_bounds_env=p_sup, + verified_visibility=None, + omit_visible_env=True, + ) + if "=" in kv + ) + return _topo_env_matches(_inj, p_env) + return True + + _add_scope_constraint(cust_chips, _cust_pred) + if cust_mismatches: + unverifiable.append( + f"device {name!r}: map-dependent selector capacity " + "cannot be verified without --chip-id-map" + ) # Revalidate any injected `TPU_VISIBLE_CHIPS` / `TPU_VISIBLE_DEVICES` env # masks against live verified runtime ordinals for this selector's PCI BDFs # so non-range slices whose chip IDs changed (e.g. `0,1,4,5` -> `2,3,6,7`) # are detected as stale instead of remaining published. injected_vis: Dict[str, str] = {} + dev_parsed_chips_vis: Optional[List[int]] = None + dev_parsed_devs_vis: Optional[List[int]] = None for env_src in ( global_edits.get("env") if isinstance(global_edits, dict) else None, edits.get("env") if isinstance(edits, dict) else None, @@ -3674,7 +6239,7 @@ def _verify_spec_against_host_detailed( if isinstance(entry, str) and "=" in entry: ek, ev = entry.split("=", 1) if ek in ("TPU_VISIBLE_CHIPS", "TPU_VISIBLE_DEVICES"): - injected_vis[ek] = ev.strip() + injected_vis[ek] = ev if injected_vis and expected_live_bdfs and all( b in live_chips_by_bdf for b in expected_live_bdfs @@ -3686,9 +6251,183 @@ def _verify_spec_against_host_detailed( live_bdf_to_phys, chip_id_map=chip_id_map, host_pci_inventory=live_pci_inventory, + expected_fns_by_bdf=live_per_chip_by_bdf, + observed_domain_bdfs=merged_live_observed, ) + def _parse_vis_ordinals(raw_list: str) -> Optional[List[int]]: + parts = [p.strip() for p in raw_list.split(",")] + if not parts: + return None + vals: List[int] = [] + for p in parts: + v = _parse_ascii_uint(p) + if v is None: + return None + vals.append(v) + if len(set(vals)) != len(vals): + return None + return vals + uses_explicit_chip_map_env = ann.get("freetpu.dev/chip-id-source") == "chip-id-map" - if live_vis is not None: + vis_structural_errors: List[str] = [] + parsed_chips_vis = ( + _parse_vis_ordinals(injected_vis["TPU_VISIBLE_CHIPS"]) + if "TPU_VISIBLE_CHIPS" in injected_vis + else None + ) + parsed_devs_vis = ( + _parse_vis_ordinals(injected_vis["TPU_VISIBLE_DEVICES"]) + if "TPU_VISIBLE_DEVICES" in injected_vis + else None + ) + if "TPU_VISIBLE_CHIPS" in injected_vis and parsed_chips_vis is None: + vis_structural_errors.append( + f"device {name!r}: invalid TPU_VISIBLE_CHIPS={injected_vis['TPU_VISIBLE_CHIPS']!r}" + ) + if "TPU_VISIBLE_DEVICES" in injected_vis and parsed_devs_vis is None: + vis_structural_errors.append( + f"device {name!r}: invalid TPU_VISIBLE_DEVICES={injected_vis['TPU_VISIBLE_DEVICES']!r}" + ) + chiplets_set = { + max( + TPU_CHIPLETS_PER_PKG.get(c.generation, 1), + _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1), + ) + for c in dev_live_chips + } + if not vis_structural_errors and len(chiplets_set) != 1: + vis_structural_errors.append( + f"device {name!r}: cannot inject visibility ordinals across mixed-generation devices" + ) + if not vis_structural_errors and len(chiplets_set) == 1: + chiplets = next(iter(chiplets_set)) + req_cc_vis = not name.startswith("pci-") + if chip_id_map is None and uses_explicit_chip_map_env: + feasible_outcomes_modes = _feasible_paired_outcomes_with_modes( + dev_live_chips, + ann, + require_capacity_complete=req_cc_vis, + ) + else: + lc, li = _count_complete_chips( + dev_live_chips, + live_bdf_to_phys, + expected_fns_by_bdf=live_per_chip_by_bdf, + ) + base_md: Optional[int] = ( + live_tpu7x_nomap_per_chip + if (has_live_tpu7x and any(c.generation == "tpu7x" for c in dev_live_chips)) + else None + ) + feasible_outcomes_modes = [(lc, li, base_md)] + rec_cc_raw = ann.get("freetpu.dev/chip-count") + rec_cc = _parse_ascii_uint(rec_cc_raw) if "freetpu.dev/chip-count" in ann else None + matching_vis_outcomes = [ + (cc, ci, md) + for cc, ci, md in feasible_outcomes_modes + if cc > 0 and ("freetpu.dev/chip-count" not in ann or rec_cc == cc) + ] + allowed_pkg_counts = {cc for cc, _ci, _md in matching_vis_outcomes} + if parsed_chips_vis is not None and not ( + 1 <= len(parsed_chips_vis) <= len(dev_live_chips) + and len(parsed_chips_vis) in allowed_pkg_counts + ): + vis_structural_errors.append( + f"device {name!r}: TPU_VISIBLE_CHIPS length {len(parsed_chips_vis)} " + f"does not match selector chip count {sorted(allowed_pkg_counts)}" + ) + elif ( + parsed_chips_vis is not None + and chiplets > 1 + and any( + c_ord * chiplets + (chiplets - 1) > 65535 + for c_ord in parsed_chips_vis + ) + ): + vis_structural_errors.append( + f"device {name!r}: TPU_VISIBLE_CHIPS={injected_vis['TPU_VISIBLE_CHIPS']!r} " + f"exceeds maximum derived TPU_VISIBLE_DEVICES ordinal 65535 " + f"for chiplets-per-pkg={chiplets}" + ) + if parsed_devs_vis is not None: + if len(parsed_devs_vis) % chiplets != 0 or not ( + 1 <= len(parsed_devs_vis) // chiplets <= len(dev_live_chips) + and (len(parsed_devs_vis) // chiplets) in allowed_pkg_counts + ): + vis_structural_errors.append( + f"device {name!r}: TPU_VISIBLE_DEVICES length {len(parsed_devs_vis)} " + f"incompatible with chiplets-per-pkg={chiplets} and chip count" + ) + elif chiplets > 1 and parsed_chips_vis is None and any( + parsed_devs_vis[i * chiplets + off] + != (parsed_devs_vis[i * chiplets] // chiplets) * chiplets + off + or parsed_devs_vis[i * chiplets] % chiplets != 0 + for i in range(len(parsed_devs_vis) // chiplets) + for off in range(chiplets) + ): + vis_structural_errors.append( + f"device {name!r}: TPU_VISIBLE_DEVICES={injected_vis['TPU_VISIBLE_DEVICES']!r} " + "violates intra-package chiplet pairing" + ) + if parsed_chips_vis is not None and parsed_devs_vis is not None: + expected_paired_devs = [ + c_ord * chiplets + off + for c_ord in parsed_chips_vis + for off in range(chiplets) + ] + if parsed_devs_vis != expected_paired_devs: + vis_structural_errors.append( + f"device {name!r}: TPU_VISIBLE_DEVICES={injected_vis['TPU_VISIBLE_DEVICES']!r} " + f"does not match TPU_VISIBLE_CHIPS={injected_vis['TPU_VISIBLE_CHIPS']!r} " + f"(expected {','.join(str(x) for x in expected_paired_devs)!r})" + ) + if not vis_structural_errors: + dev_parsed_chips_vis = parsed_chips_vis + dev_parsed_devs_vis = parsed_devs_vis + vis_target_cc: Optional[int] = None + if parsed_chips_vis is not None: + vis_target_cc = len(parsed_chips_vis) + elif parsed_devs_vis is not None: + vis_target_cc = len(parsed_devs_vis) // chiplets + if vis_target_cc is not None: + if has_live_tpu7x and any(c.generation == "tpu7x" for c in dev_live_chips): + vis_modes = { + md + for cc, _ci, md in matching_vis_outcomes + if cc == vis_target_cc and md is not None + } + if vis_modes: + allowed_tpu7x_modes &= vis_modes + + def _vis_pred( + lm: Optional[int], + pm: Dict[str, frozenset[str]], + *, + _dev_chips: List[DiscoveredChip] = list(dev_live_chips), + _ann: Dict[str, Any] = ann, + _target_cc: int = vis_target_cc, + _req_cc: bool = req_cc_vis, + _rec_cc: Optional[int] = rec_cc, + _has_rec_cc: bool = "freetpu.dev/chip-count" in ann, + ) -> bool: + if ( + _ann.get("freetpu.dev/chip-id-source") != "chip-id-map" + and any(c.generation == "tpu7x" for c in _dev_chips) + and lm != live_tpu7x_nomap_per_chip + ): + return False + cc, ci, _dom = _eval_scope_layout(_dev_chips, lm, pm) + return ( + cc == _target_cc + and (not _req_cc or ci == 0) + and (not _has_rec_cc or _rec_cc == cc) + ) + + _add_scope_constraint(dev_live_chips, _vis_pred) + + if vis_structural_errors: + errors.extend(vis_structural_errors) + elif live_vis is not None: exp_chips, exp_devs = live_vis expected_env_map = { "TPU_VISIBLE_CHIPS": ",".join(str(x) for x in exp_chips), @@ -3723,6 +6462,65 @@ def _verify_spec_against_host_detailed( "verified against supplied --chip-id-map and live host topology" ) + if isinstance(name, str) and expected_live_bdfs and all( + b in live_chips_by_bdf for b in expected_live_bdfs + ): + scope_chips_vc = [live_chips_by_bdf[b] for b in expected_live_bdfs] + vc_chiplets_set = { + max( + TPU_CHIPLETS_PER_PKG.get(c.generation, 1), + _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1), + ) + for c in scope_chips_vc + } + vc_chiplets = next(iter(vc_chiplets_set)) if len(vc_chiplets_set) == 1 else None + range_chip_set: Optional[frozenset[int]] = None + if _RANGE_SLICE_RE.match(name): + rp_vc = name.split("-", 1) + s_vc = _parse_ascii_uint(rp_vc[0]) + e_vc = _parse_ascii_uint(rp_vc[1]) + if ( + s_vc is not None + and e_vc is not None + and e_vc >= s_vc + and (e_vc - s_vc + 1) <= len(expected_live_bdfs) + ): + range_chip_set = frozenset(range(s_vc, e_vc + 1)) + vis_chip_set: Optional[frozenset[int]] = ( + frozenset(dev_parsed_chips_vis) + if dev_parsed_chips_vis is not None + else None + ) + vis_dev_set: Optional[frozenset[int]] = ( + frozenset(dev_parsed_devs_vis) + if dev_parsed_devs_vis is not None + else None + ) + if ( + range_chip_set is not None + and vis_chip_set is not None + and vis_chip_set != range_chip_set + ): + errors.append( + f"device {name!r}: TPU_VISIBLE_CHIPS={injected_vis['TPU_VISIBLE_CHIPS']!r} " + f"conflicts with numeric range slice bounds {name!r}" + ) + elif vis_chip_set is None and range_chip_set is not None: + vis_chip_set = range_chip_set + if vc_chiplets is not None: + if vis_chip_set is not None and vis_dev_set is None: + vis_dev_set = frozenset( + p * vc_chiplets + off + for p in vis_chip_set + for off in range(vc_chiplets) + ) + elif vis_dev_set is not None and vis_chip_set is None: + vis_chip_set = frozenset(d // vc_chiplets for d in vis_dev_set) + if vis_chip_set is not None or vis_dev_set is not None: + vis_claims.append( + (name, frozenset(expected_live_bdfs), vis_chip_set, vis_dev_set) + ) + recorded_dev_dn = _parse_vfio_devnums_annotation(ann.get("freetpu.dev/vfio-devnums")) for cp in matched_group_paths: live_dn = live_devnums_by_container_path.get(cp) @@ -3732,6 +6530,552 @@ def _verify_spec_against_host_detailed( f"(spec recorded {recorded_dev_dn.get(cp)!r}, host has {live_dn!r})" ) + def _scope_phys_dev_bounds( + bdfs_set: frozenset[str], + *, + for_outside: bool = False, + ) -> Tuple[int, int]: + """Upper-bound complete physical packages and logical devices inside `bdfs_set`.""" + phys_ub = 0 + devs_ub = 0 + seen_forced_pkgs_b: set[frozenset[str]] = set() + free_v2_cnt = 0 + free_t7x_cnt = 0 + t7x_nomap_two_fn_fixed = bool( + chip_id_map is None and (live_tpu7x_nomap_per_chip == 2 or not mode1_allowed) + ) + for b in bdfs_set: + c_b = live_chips_by_bdf.get(b) + if c_b is None: + phys_ub += 1 + devs_ub += 1 + continue + gen_b = c_b.generation + chip_mult = TPU_CHIPLETS_PER_PKG.get(gen_b, 1) + fn_mult = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(gen_b, 1) + if b in inv_forced_packages: + f_pkg = inv_forced_packages[b] + if f_pkg not in seen_forced_pkgs_b: + seen_forced_pkgs_b.add(f_pkg) + if for_outside or f_pkg.issubset(bdfs_set): + phys_ub += 1 + devs_ub += 1 + continue + if gen_b not in ("tpu7x", "v2-v3"): + phys_ub += 1 + devs_ub += chip_mult + elif gen_b == "v2-v3": + free_v2_cnt += 1 + devs_ub += max(chip_mult, fn_mult) // 2 + else: + if chip_id_map is not None: + per_fn_b = live_per_chip_by_bdf.get(b, 2) + if per_fn_b == 1: + phys_ub += 1 + devs_ub += chip_mult + else: + free_t7x_cnt += 1 + devs_ub += 1 + elif t7x_nomap_two_fn_fixed: + free_t7x_cnt += 1 + devs_ub += 1 + else: + phys_ub += 1 + devs_ub += chip_mult + phys_ub += (free_v2_cnt + 1) // 2 if for_outside else free_v2_cnt // 2 + phys_ub += (free_t7x_cnt + 1) // 2 if for_outside else free_t7x_cnt // 2 + return phys_ub, devs_ub + + for ci, (n1, s1, c1, d1) in enumerate(vis_claims): + for n2, s2, c2, d2 in vis_claims[ci + 1 :]: + same_scope = s1 == s2 + sub_12 = s1 < s2 + sub_21 = s2 < s1 + disjoint = s1.isdisjoint(s2) + chip_conflict = False + dev_conflict = False + inter_phys_ub = 0 + inter_devs_ub = 0 + out1_phys_ub = 0 + out2_phys_ub = 0 + out1_devs_ub = 0 + out2_devs_ub = 0 + if not disjoint and not same_scope and not sub_12 and not sub_21: + inter_phys_ub, inter_devs_ub = _scope_phys_dev_bounds(s1 & s2, for_outside=False) + out1_phys_ub, out1_devs_ub = _scope_phys_dev_bounds(s1 - s2, for_outside=True) + out2_phys_ub, out2_devs_ub = _scope_phys_dev_bounds(s2 - s1, for_outside=True) + + if c1 is not None and c2 is not None: + if same_scope: + if c1 != c2: + chip_conflict = True + elif sub_12: + if not c1.issubset(c2): + chip_conflict = True + elif sub_21: + if not c2.issubset(c1): + chip_conflict = True + elif disjoint: + if not c1.isdisjoint(c2): + chip_conflict = True + else: + min_sh_1 = max(0, len(c1) - out1_phys_ub) + min_sh_2 = max(0, len(c2) - out2_phys_ub) + inter_len_c = len(c1 & c2) + if ( + inter_len_c < (min_sh_1 + min_sh_2 - inter_phys_ub) + or inter_len_c > inter_phys_ub + ): + chip_conflict = True + if d1 is not None and d2 is not None: + if same_scope: + if d1 != d2: + dev_conflict = True + elif sub_12: + if not d1.issubset(d2): + dev_conflict = True + elif sub_21: + if not d2.issubset(d1): + dev_conflict = True + elif disjoint: + if not d1.isdisjoint(d2): + dev_conflict = True + else: + if len(d1 & d2) > inter_devs_ub: + dev_conflict = True + elif c1 is None or c2 is None: + min_sh_d1 = max(0, len(d1) - out1_devs_ub) + min_sh_d2 = max(0, len(d2) - out2_devs_ub) + if len(d1 & d2) < (min_sh_d1 + min_sh_d2 - inter_devs_ub): + dev_conflict = True + if chip_conflict or dev_conflict: + errors.append( + f"conflicting visible ordinal assumptions between selectors {n1!r} and {n2!r}" + ) + + def _kuhn_matches_all(adj: Dict[int, List[int]], n_slots: int) -> bool: + if len(adj) > n_slots: + return False + match_slot = [-1] * n_slots + + def _dfs_k(u_ord: int, vis_slots: set[int]) -> bool: + for sl in adj[u_ord]: + if sl in vis_slots: + continue + vis_slots.add(sl) + if match_slot[sl] == -1 or _dfs_k(match_slot[sl], vis_slots): + match_slot[sl] = u_ord + return True + return False + + for u_ord in sorted(adj): + if not _dfs_k(u_ord, set()): + return False + return True + + if vis_claims: + phys_units: List[Tuple[frozenset[str], bool, int]] = [] + seen_fp_units: set[frozenset[str]] = set() + t7x_nomap_two_fn_u = bool( + chip_id_map is None and (live_tpu7x_nomap_per_chip == 2 or not mode1_allowed) + ) + for c in live_chips: + if c.pci_bdf in inv_forced_packages: + f_pkg = inv_forced_packages[c.pci_bdf] + if f_pkg not in seen_fp_units: + seen_fp_units.add(f_pkg) + ch_u = TPU_CHIPLETS_PER_PKG.get(c.generation, 1) + fn_u = _PCI_FUNCTIONS_PER_PHYSICAL_CHIP.get(c.generation, 1) + phys_units.append((f_pkg, True, max(ch_u, fn_u))) + elif c.generation not in ("tpu7x", "v2-v3"): + phys_units.append((frozenset((c.pci_bdf,)), True, TPU_CHIPLETS_PER_PKG.get(c.generation, 1))) + else: + if c.generation == "tpu7x" and ( + (chip_id_map is not None and live_per_chip_by_bdf.get(c.pci_bdf, 2) == 1) + or (chip_id_map is None and not t7x_nomap_two_fn_u) + ): + d_cap = TPU_CHIPLETS_PER_PKG.get("tpu7x", 2) + else: + d_cap = 1 + phys_units.append((frozenset((c.pci_bdf,)), False, d_cap)) + + full_c_selectors: List[Tuple[frozenset[str], frozenset[int]]] = [] + full_d_selectors: List[Tuple[frozenset[str], frozenset[int]]] = [] + for _n, s_k, c_k, d_k in vis_claims: + s_exact = all( + (not u_b.issubset(s_k)) or is_exact + for u_b, is_exact, _dc in phys_units + ) + if s_exact: + exact_comp = sum(1 for u_b, _ie, _dc in phys_units if u_b.issubset(s_k)) + exact_devs = sum(dc for u_b, _ie, dc in phys_units if u_b.issubset(s_k)) + if c_k is not None and exact_comp == len(c_k): + full_c_selectors.append((s_k, c_k)) + if d_k is not None and exact_devs == len(d_k): + full_d_selectors.append((s_k, d_k)) + + all_c_ords = sorted({o for _n, _s, c_k, _d in vis_claims if c_k for o in c_k}) + if all_c_ords: + c_adj: Dict[int, List[int]] = {} + for o in all_c_ords: + req_scopes = [s_k for _n, s_k, c_k, _d in vis_claims if c_k is not None and o in c_k] + c_adj[o] = [ + ui + for ui, (u_b, _ie, _dc) in enumerate(phys_units) + if all(u_b.issubset(s_k) for s_k in req_scopes) + and all(o in fs_c for fs_s, fs_c in full_c_selectors if u_b.issubset(fs_s)) + ] + if not _kuhn_matches_all(c_adj, len(phys_units)): + errors.append( + "conflicting visible ordinal assumptions across spec selectors " + "(physical chip ordinals have no valid multi-selector assignment)" + ) + + all_d_ords = sorted({o for _n, _s, _c, d_k in vis_claims if d_k for o in d_k}) + if all_d_ords: + dev_slot_units: List[frozenset[str]] = [] + for u_b, _ie, d_cap in phys_units: + for _ in range(d_cap): + dev_slot_units.append(u_b) + d_adj: Dict[int, List[int]] = {} + for o in all_d_ords: + req_scopes_d = [s_k for _n, s_k, _c, d_k in vis_claims if d_k is not None and o in d_k] + d_adj[o] = [ + si + for si, u_b in enumerate(dev_slot_units) + if all(u_b.issubset(s_k) for s_k in req_scopes_d) + and all(o in fs_d for fs_s, fs_d in full_d_selectors if u_b.issubset(fs_s)) + ] + if not _kuhn_matches_all(d_adj, len(dev_slot_units)): + errors.append( + "conflicting visible ordinal assumptions across spec selectors " + "(logical device ordinals have no valid multi-selector assignment)" + ) + + def _has_consistent_host_layout() -> str: + def _matching_count_small(n_items: int) -> int: + a, b = 1, 1 + for k in range(2, n_items + 1): + a, b = b, b + (k - 1) * a + return b + + def _enum_matchings(items: Tuple[str, ...]) -> List[Dict[str, frozenset[str]]]: + if len(items) < 2: + return [{}] + first = items[0] + rest = items[1:] + res = _enum_matchings(rest) + for p_idx, partner in enumerate(rest): + rem = rest[:p_idx] + rest[p_idx + 1 :] + pair = frozenset((first, partner)) + for sub in _enum_matchings(rem): + merged_pm = dict(sub) + merged_pm[first] = pair + merged_pm[partner] = pair + res.append(merged_pm) + return res + + def _pair_list_pm( + pairs_list: Sequence[Tuple[str, str]], + ) -> Dict[str, frozenset[str]]: + pm: Dict[str, frozenset[str]] = {} + for u, v in pairs_list: + pr = frozenset((u, v)) + pm[u] = pr + pm[v] = pr + return pm + + all_bk_keys = sorted(free_buckets) + bucket_sets = {bk: frozenset(free_buckets[bk]) for bk in all_bk_keys} + zero_preds: List[Callable[[Optional[int], Dict[str, frozenset[str]]], bool]] = [] + sym_global_preds: List[ + Callable[[Optional[int], Dict[str, frozenset[str]]], bool] + ] = [] + comp_parent = {bk: bk for bk in all_bk_keys} + + def _find_comp(x: Tuple[str, Tuple[str, Optional[int], str]]) -> Tuple[str, Tuple[str, Optional[int], str]]: + while comp_parent[x] != x: + comp_parent[x] = comp_parent[comp_parent[x]] + x = comp_parent[x] + return x + + def _union_comp( + a: Tuple[str, Tuple[str, Optional[int], str]], + b: Tuple[str, Tuple[str, Optional[int], str]], + ) -> None: + ra, rb = _find_comp(a), _find_comp(b) + if ra != rb: + comp_parent[rb] = ra + + raw_sub_preds: List[ + Tuple[ + List[Tuple[str, Tuple[str, Optional[int], str]]], + frozenset[str], + Callable[[Optional[int], Dict[str, frozenset[str]]], bool], + ] + ] = [] + for s_bdfs, pred in scope_constraints: + touched = [bk for bk in all_bk_keys if s_bdfs & bucket_sets[bk]] + # Any singleton scope (<= 1 BDF, e.g. `pci-*`) cannot contain a + # 2-function pair, so partner maps never affect it; keep it in + # `zero_preds` so per-BDF singletons never defeat symmetry reduction. + if not touched or len(s_bdfs) <= 1: + zero_preds.append(pred) + elif all(bucket_sets[bk].issubset(s_bdfs) for bk in touched): + sym_global_preds.append(pred) + else: + for bk in touched[1:]: + _union_comp(touched[0], bk) + raw_sub_preds.append((touched, s_bdfs, pred)) + + comp_buckets: Dict[ + Tuple[str, Tuple[str, Optional[int], str]], + List[Tuple[str, Tuple[str, Optional[int], str]]], + ] = {} + for bk in all_bk_keys: + comp_buckets.setdefault(_find_comp(bk), []).append(bk) + + comp_preds_map: Dict[ + Tuple[str, Tuple[str, Optional[int], str]], + List[ + Tuple[ + frozenset[str], + Callable[[Optional[int], Dict[str, frozenset[str]]], bool], + ] + ], + ] = {ck: [] for ck in comp_buckets} + for touched, s_bdfs, pred in raw_sub_preds: + comp_preds_map[_find_comp(touched[0])].append((s_bdfs, pred)) + + def _solve_component( + comp_bks: Sequence[Tuple[str, Tuple[str, Optional[int], str]]], + lm: Optional[int], + comp_preds: Sequence[ + Tuple[ + frozenset[str], + Callable[[Optional[int], Dict[str, frozenset[str]]], bool], + ] + ], + ) -> Tuple[Dict[Tuple[int, ...], Dict[str, frozenset[str]]], bool]: + active_bks = [ + bk + for bk in comp_bks + if not (bk[0] == "tpu7x" and lm == 1) and len(free_buckets[bk]) >= 2 + ] + if not active_bks: + if all(p(lm, {}) for _sb, p in comp_preds): + return {(): {}}, False + return {}, False + bk_idx_map = {bk: i for i, bk in enumerate(active_bks)} + comp_prod = 1 + for bk in active_bks: + comp_prod *= _matching_count_small(len(free_buckets[bk])) + if comp_prod > 4096: + break + if comp_prod <= 4096: + acc_s: List[Tuple[List[int], Dict[str, frozenset[str]]]] = [ + ([0] * len(active_bks), {}) + ] + for bk in active_bks: + bi = bk_idx_map[bk] + items = tuple(free_buckets[bk]) + part_maps = ( + _enum_matchings(items) + if comp_preds + else [ + _pair_list_pm( + [(items[2 * j], items[2 * j + 1]) for j in range(pc)] + ) + for pc in range(len(items) // 2 + 1) + ] + ) + nxt_s: List[Tuple[List[int], Dict[str, frozenset[str]]]] = [] + for p_part in part_maps: + pc = len(p_part) // 2 + for cnts, pm in acc_s: + nc = list(cnts) + nc[bi] = pc + nm = dict(pm) + nm.update(p_part) + nxt_s.append((nc, nm)) + acc_s = nxt_s + out_reps: Dict[Tuple[int, ...], Dict[str, frozenset[str]]] = {} + for cnts, pm in acc_s: + kt = tuple(cnts) + if kt not in out_reps and all(p(lm, pm) for _sb, p in comp_preds): + out_reps[kt] = pm + return out_reps, False + + # > 4096 component states: exact signature-symmetry collapsing backtracking. + sig_by_bdf: Dict[str, Tuple[int, ...]] = {} + ordered_items: Dict[ + Tuple[str, Tuple[str, Optional[int], str]], Tuple[str, ...] + ] = {} + for bk in active_bks: + for b in free_buckets[bk]: + sig_by_bdf[b] = tuple( + pi for pi, (sb, _fn) in enumerate(comp_preds) if b in sb + ) + ordered_items[bk] = tuple( + sorted( + free_buckets[bk], + key=lambda b: (not bool(sig_by_bdf[b]), sig_by_bdf[b], b), + ) + ) + bt_results: Dict[Tuple[int, ...], Dict[str, frozenset[str]]] = {} + bt_work = [20000] + bt_exhausted = [False] + + def _bt( + bi_pos: int, + rem: Tuple[str, ...], + cur_pm: Dict[str, frozenset[str]], + cur_cnts: List[int], + ) -> None: + if bt_work[0] <= 0: + bt_exhausted[0] = True + return + bt_work[0] -= 1 + if bi_pos >= len(active_bks): + kt = tuple(cur_cnts) + if kt not in bt_results and all( + p(lm, cur_pm) for _sb, p in comp_preds + ): + bt_results[kt] = dict(cur_pm) + return + next_rem = ( + ordered_items[active_bks[bi_pos + 1]] + if bi_pos + 1 < len(active_bks) + else () + ) + if len(rem) < 2: + _bt(bi_pos + 1, next_rem, cur_pm, cur_cnts) + return + rem_sigs = {sig_by_bdf[b] for b in rem} + if len(rem_sigs) == 1: + base_c = cur_cnts[bi_pos] + for pc in range(len(rem) // 2 + 1): + added = _pair_list_pm( + [(rem[2 * j], rem[2 * j + 1]) for j in range(pc)] + ) + cur_pm.update(added) + cur_cnts[bi_pos] = base_c + pc + _bt(bi_pos + 1, next_rem, cur_pm, cur_cnts) + for rk in added: + cur_pm.pop(rk, None) + if bt_exhausted[0]: + break + cur_cnts[bi_pos] = base_c + return + first = rem[0] + rest = rem[1:] + _bt(bi_pos, rest, cur_pm, cur_cnts) + if bt_exhausted[0]: + return + tried_sigs: set[Tuple[int, ...]] = set() + for p_i, partner in enumerate(rest): + if bt_exhausted[0]: + break + psig = sig_by_bdf[partner] + if psig in tried_sigs: + continue + tried_sigs.add(psig) + pair = frozenset((first, partner)) + cur_pm[first] = pair + cur_pm[partner] = pair + cur_cnts[bi_pos] += 1 + _bt(bi_pos, rest[:p_i] + rest[p_i + 1 :], cur_pm, cur_cnts) + cur_cnts[bi_pos] -= 1 + cur_pm.pop(first, None) + cur_pm.pop(partner, None) + + _bt(0, ordered_items[active_bks[0]], {}, [0] * len(active_bks)) + return bt_results, bt_exhausted[0] + + cand_modes: List[Optional[int]] + if has_live_tpu7x: + cand_modes = [ + m + for m in sorted(allowed_tpu7x_modes) + if (m != 1 or mode1_allowed) + ] + else: + cand_modes = [None] + + comp_keys_sorted = sorted(comp_buckets) + any_exhausted = False + for lm in cand_modes: + if not all(p(lm, {}) for p in zero_preds): + continue + comp_rep_lists: List[List[Dict[str, frozenset[str]]]] = [] + possible = True + for ck in comp_keys_sorted: + solved, comp_exh = _solve_component( + comp_buckets[ck], lm, comp_preds_map[ck] + ) + if comp_exh: + any_exhausted = True + if not solved: + possible = False + break + comp_rep_lists.append(list(solved.values())) + if not possible: + continue + if not sym_global_preds: + return "consistent" + comp_rep_lists.sort(key=len) + global_work = [20000] + global_exhausted = [False] + + def _dfs_global( + comp_pos: int, cur_gpm: Dict[str, frozenset[str]] + ) -> bool: + if global_work[0] <= 0: + global_exhausted[0] = True + return False + if comp_pos >= len(comp_rep_lists): + global_work[0] -= 1 + return all(gp(lm, cur_gpm) for gp in sym_global_preds) + for c_pm in comp_rep_lists[comp_pos]: + if global_work[0] <= 0: + global_exhausted[0] = True + return False + if c_pm: + cur_gpm.update(c_pm) + if _dfs_global(comp_pos + 1, cur_gpm): + return True + if c_pm: + for rk in c_pm: + cur_gpm.pop(rk, None) + if global_exhausted[0]: + return False + return False + + if _dfs_global(0, {}): + return "consistent" + if global_exhausted[0]: + any_exhausted = True + return "budget_exhausted" if any_exhausted else "contradiction" + + tpu7x_mode_conflict = has_live_tpu7x and not allowed_tpu7x_modes + if tpu7x_mode_conflict: + errors.append( + "conflicting Ironwood tpu7x PCI layout assumptions across spec selectors " + "(1-fn and 2-fn layouts cannot hold simultaneously on live host)" + ) + elif chip_id_map is None and scope_constraints: + layout_status = _has_consistent_host_layout() + if layout_status == "budget_exhausted": + unverifiable.append( + "cross-selector chip-pairing verification exceeded search budget; " + "supply --chip-id-map to verify" + ) + elif layout_status != "consistent": + errors.append( + "conflicting chip-pairing or capacity assumptions across spec selectors " + "(no single physical chip assignment satisfies all selectors simultaneously)" + ) + return errors, unverifiable @@ -3744,6 +7088,8 @@ def verify_spec_against_host( vfio_mode: str = "auto", chip_id_map: Optional[Dict[str, int]] = None, observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + observed_generations: Optional[Sequence[str]] = None, + observed_tpu7x_two_fn: bool = False, ) -> List[str]: """Revalidate all effective global and per-device CDI nodes against live host VFIO/iommufd state.""" confirmed, unverifiable = _verify_spec_against_host_detailed( @@ -3754,6 +7100,8 @@ def verify_spec_against_host( vfio_mode=vfio_mode, chip_id_map=chip_id_map, observed_domain_bdfs=observed_domain_bdfs, + observed_generations=observed_generations, + observed_tpu7x_two_fn=observed_tpu7x_two_fn, ) return confirmed + unverifiable @@ -3810,6 +7158,9 @@ def reconcile_cdi_spec( chip_id_map: Optional[Dict[str, int]] = None, omit_visible_env: bool = False, observed_domain_bdfs: Optional[Dict[Tuple[str, Optional[int], str], set[str]]] = None, + observed_bdf_generations: Optional[Dict[str, str]] = None, + observed_generations: Optional[set[str] | Sequence[str]] = None, + observed_tpu7x_two_fn: bool = False, ) -> Tuple[bool, str]: """Generate, validate, and atomically publish a live CDI spec, invalidating stale files on error.""" if not isinstance(kind, str) or not _CDI_KIND_RE.match(kind): @@ -3821,21 +7172,26 @@ def reconcile_cdi_spec( if vfio_mode not in VFIO_MODES: return False, f"Invalid vfio_mode {vfio_mode!r} (existing spec preserved)" - # Carry forward boot-observed PCI domain inventory from any existing spec at - # `output_path` (and caller-provided sync state) so PCI function hot-unplug / - # link-down inside a single-domain host (e.g. v6e-8 dropping to 4 PCI devices) - # cannot republish an unverified 4-chip slice or fabricated `2,2,1` bounds. - prior_observed: Dict[Tuple[str, Optional[int], str], set[str]] = { - k: set(v) for k, v in (observed_domain_bdfs or {}).items() + # Keep caller-managed in-memory `sync` observations separate from disk + # history so persisted specs without a verified boot-id match never + # promote `tpu7x` topology into fresh discovery or host validation. + disk_domains, disk_gens, disk_gen_names, disk_two_fn, disk_pos_boot = ( + _load_disk_same_boot_history(output_path) + ) + caller_observed: _ObservedDomainBdfs = _ObservedDomainBdfs( + {k: set(v) for k, v in (observed_domain_bdfs or {}).items()}, + tpu7x_two_fn=bool( + observed_tpu7x_two_fn + or getattr(observed_domain_bdfs, "tpu7x_two_fn", False) + ), + ) + caller_gens: Dict[str, str] = dict(observed_bdf_generations or {}) + caller_gen_names: set[str] = { + str(g).strip() + for g in (observed_generations or ()) + if isinstance(g, str) and str(g).strip() } - for d_k, bdfs_s in _load_same_boot_observed_domains(output_path).items(): - prior_observed.setdefault(d_k, set()).update(bdfs_s) - # Persist recovered same-boot PCI inventory into caller-managed sync state - # BEFORE discovery can fail and unlink `output_path`, so a failed tick 1 - # (e.g. 0 VFIO nodes) never erases previously observed endpoints before tick 2. - if observed_domain_bdfs is not None: - for d_k, bdfs_s in prior_observed.items(): - observed_domain_bdfs.setdefault(d_k, set()).update(bdfs_s) + caller_gen_names.update(g for g in caller_gens.values() if g) try: chips, vfio_container, full_pci_inventory = _discover_tpu_chips_with_inventory( @@ -3845,11 +7201,50 @@ def reconcile_cdi_spec( iommu_dev_path=iommu_dev_path, vfio_mode=vfio_mode, ) + live_bridges = _scan_pcie_bridge_roots(sysfs_root) + f_disk_doms, f_disk_gens, f_disk_gen_names, f_disk_two_fn = ( + _filter_disk_history_for_inventory( + disk_domains, + disk_gens, + disk_gen_names, + disk_two_fn, + disk_pos_boot, + full_pci_inventory, + chip_id_map=chip_id_map, + bridge_bus_to_roots=live_bridges, + ) + ) + prior_observed: _ObservedDomainBdfs = _ObservedDomainBdfs( + {k: set(v) for k, v in caller_observed.items()}, + tpu7x_two_fn=bool(caller_observed.tpu7x_two_fn or f_disk_two_fn), + ) + for d_k, bdfs_s in f_disk_doms.items(): + prior_observed.setdefault(d_k, set()).update(bdfs_s) + prior_observed_gens: Dict[str, str] = dict(caller_gens) + for b_k, g_v in f_disk_gens.items(): + prior_observed_gens.setdefault(b_k, g_v) + prior_observed_gen_names = set(caller_gen_names) | set(f_disk_gen_names) + prior_tpu7x_two_fn = bool(caller_observed.tpu7x_two_fn or f_disk_two_fn) + merged_observed = _merge_observed_domain_bdfs(prior_observed, full_pci_inventory) - if observed_domain_bdfs is not None: - observed_domain_bdfs.clear() - for d_k, bdfs_s in merged_observed.items(): - observed_domain_bdfs[d_k] = set(bdfs_s) + merged_observed_gens = dict(prior_observed_gens) + merged_observed_gen_names = set(prior_observed_gen_names) + verify_observed = _merge_observed_domain_bdfs(caller_observed, full_pci_inventory) + verify_gen_names = set(caller_gen_names) + if disk_pos_boot: + for d_k, bdfs_s in f_disk_doms.items(): + verify_observed.setdefault(d_k, set()).update(bdfs_s) + verify_gen_names.update(f_disk_gen_names) + verify_two_fn = bool(caller_observed.tpu7x_two_fn or f_disk_two_fn) + + for inv_c in full_pci_inventory: + merged_observed_gens[inv_c.pci_bdf] = inv_c.generation + merged_observed_gen_names.add(inv_c.generation) + verify_gen_names.add(inv_c.generation) + if observed_bdf_generations is not None: + observed_bdf_generations.update(merged_observed_gens) + if isinstance(observed_generations, set): + observed_generations.update(merged_observed_gen_names) spec = build_cdi_spec( chips, vfio_container, @@ -3861,8 +7256,27 @@ def reconcile_cdi_spec( omit_visible_env=omit_visible_env, host_pci_inventory=full_pci_inventory, observed_domain_bdfs=merged_observed, - bridge_bus_to_roots=_scan_pcie_bridge_roots(sysfs_root), + observed_bdf_generations=merged_observed_gens, + observed_generations=sorted(merged_observed_gen_names), + bridge_bus_to_roots=live_bridges, + observed_tpu7x_two_fn=prior_tpu7x_two_fn, + ) + built_two_fn = bool( + prior_tpu7x_two_fn or _extract_observed_tpu7x_two_fn_from_spec(spec) ) + if isinstance(merged_observed, _ObservedDomainBdfs): + merged_observed.tpu7x_two_fn = built_two_fn + if isinstance(verify_observed, _ObservedDomainBdfs): + verify_observed.tpu7x_two_fn = bool( + verify_two_fn or _extract_observed_tpu7x_two_fn_from_spec(spec) + ) + if observed_domain_bdfs is not None: + observed_domain_bdfs.clear() + for d_k, bdfs_s in merged_observed.items(): + observed_domain_bdfs[d_k] = set(bdfs_s) + if isinstance(observed_domain_bdfs, _ObservedDomainBdfs): + observed_domain_bdfs.tpu7x_two_fn = built_two_fn + verify_two_fn = bool(verify_two_fn or _extract_observed_tpu7x_two_fn_from_spec(spec)) except Exception as exc: # noqa: BLE001 removed, cleanup_err = _invalidate_spec(output_path) suffix = _format_invalidation_suffix(output_path, removed, cleanup_err) @@ -3878,7 +7292,9 @@ def reconcile_cdi_spec( iommu_dev_path=iommu_dev_path, vfio_mode=vfio_mode, chip_id_map=chip_id_map, - observed_domain_bdfs=merged_observed, + observed_domain_bdfs=verify_observed, + observed_generations=sorted(verify_gen_names), + observed_tpu7x_two_fn=verify_two_fn, ) ) if errors: @@ -4283,11 +7699,20 @@ def main(argv: Optional[Sequence[str]] = None) -> int: ) return 1 - prior_gen_observed: Dict[Tuple[str, Optional[int], str], set[str]] = ( - _load_same_boot_observed_domains(args.output) - if not args.stdout and not args.allow_missing_vfio - else {} - ) + if not args.stdout and not args.allow_missing_vfio: + ( + disk_gen_observed, + disk_gen_observed_gens, + disk_gen_observed_names, + disk_gen_tpu7x_two_fn, + disk_gen_pos_boot, + ) = _load_disk_same_boot_history(args.output) + else: + disk_gen_observed = {} + disk_gen_observed_gens = {} + disk_gen_observed_names = set() + disk_gen_tpu7x_two_fn = False + disk_gen_pos_boot = False try: chips, vfio_container, full_pci_inventory = _discover_tpu_chips_with_inventory( sysfs_root=args.sysfs_root, @@ -4296,9 +7721,30 @@ def main(argv: Optional[Sequence[str]] = None) -> int: iommu_dev_path=args.iommu_dev, vfio_mode=args.vfio_mode, ) + gen_bridges = _scan_pcie_bridge_roots(args.sysfs_root) + ( + prior_gen_observed, + prior_gen_observed_gens, + prior_gen_observed_gen_names, + prior_gen_tpu7x_two_fn, + ) = _filter_disk_history_for_inventory( + disk_gen_observed, + disk_gen_observed_gens, + disk_gen_observed_names, + disk_gen_tpu7x_two_fn, + disk_gen_pos_boot, + full_pci_inventory, + chip_id_map=parsed_chip_map, + bridge_bus_to_roots=gen_bridges, + ) merged_gen_observed = _merge_observed_domain_bdfs( prior_gen_observed, full_pci_inventory ) + merged_gen_observed_gens = dict(prior_gen_observed_gens) + merged_gen_observed_gen_names = set(prior_gen_observed_gen_names) + for inv_c in full_pci_inventory: + merged_gen_observed_gens[inv_c.pci_bdf] = inv_c.generation + merged_gen_observed_gen_names.add(inv_c.generation) spec = build_cdi_spec( chips, vfio_container, @@ -4310,7 +7756,10 @@ def main(argv: Optional[Sequence[str]] = None) -> int: omit_visible_env=args.omit_visible_env, host_pci_inventory=full_pci_inventory, observed_domain_bdfs=merged_gen_observed, - bridge_bus_to_roots=_scan_pcie_bridge_roots(args.sysfs_root), + observed_bdf_generations=merged_gen_observed_gens, + observed_generations=sorted(merged_gen_observed_gen_names), + bridge_bus_to_roots=gen_bridges, + observed_tpu7x_two_fn=prior_gen_tpu7x_two_fn, ) except Exception as exc: # noqa: BLE001 if not args.stdout and not args.allow_missing_vfio: @@ -4334,6 +7783,8 @@ def main(argv: Optional[Sequence[str]] = None) -> int: vfio_mode=args.vfio_mode, chip_id_map=parsed_chip_map, observed_domain_bdfs=merged_gen_observed, + observed_generations=sorted(merged_gen_observed_gen_names), + observed_tpu7x_two_fn=prior_gen_tpu7x_two_fn, ) ) if errors: @@ -4488,8 +7939,16 @@ def _handle_signal(_signum: int, _frame: Any) -> None: last_msg = "" interval = max(1.0, float(args.interval)) - sync_observed_domains: Dict[Tuple[str, Optional[int], str], set[str]] = ( - _load_same_boot_observed_domains(args.output) + ( + sync_doms_raw, + sync_observed_gens, + sync_observed_gen_names, + sync_two_fn, + _sync_pos_boot, + ) = _load_disk_same_boot_history(args.output) + sync_observed_domains = _ObservedDomainBdfs( + {k: set(v) for k, v in sync_doms_raw.items()}, + tpu7x_two_fn=sync_two_fn, ) while not stop_requested: tick_chip_map = parsed_chip_map @@ -4531,6 +7990,8 @@ def _handle_signal(_signum: int, _frame: Any) -> None: chip_id_map=tick_chip_map, omit_visible_env=args.omit_visible_env, observed_domain_bdfs=sync_observed_domains, + observed_bdf_generations=sync_observed_gens, + observed_generations=sync_observed_gen_names, ) except Exception as exc: # noqa: BLE001 removed, cleanup_err = _invalidate_spec(args.output) diff --git a/ops/tpu-cdi/test_freetpu_cdi.py b/ops/tpu-cdi/test_freetpu_cdi.py index 602878fb..18b02bae 100755 --- a/ops/tpu-cdi/test_freetpu_cdi.py +++ b/ops/tpu-cdi/test_freetpu_cdi.py @@ -4,11 +4,13 @@ from __future__ import annotations import contextlib +import copy import io import json import os from pathlib import Path import re +import shutil import stat import subprocess import sys @@ -5592,35 +5594,36 @@ def test_degraded_single_root_v6e_domain_withholds_4chip_slice_and_2x2_bounds(se create_vfio_nodes=[str(i) for i in range(8)], ) pci_loss_spec = root / "cdi" / "pci_loss_freetpu.json" - ok_p1, msg_p1 = freetpu_cdi.reconcile_cdi_spec( - pci_loss_spec, - sysfs_root=pci_loss_sys, - dev_root=pci_loss_dev, - single_host_env=True, - ) - self.assertTrue(ok_p1, msg_p1) - for idx in range(4, 8): - shutil.rmtree( - pci_loss_sys / "bus" / "pci" / "devices" / f"0000:00:{4 + idx:02x}.0" - ) - (pci_loss_dev / "vfio" / str(idx)).unlink() - - for tick_label in ("tick2", "tick3"): - ok_pt, msg_pt = freetpu_cdi.reconcile_cdi_spec( + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-pci-loss"): + ok_p1, msg_p1 = freetpu_cdi.reconcile_cdi_spec( pci_loss_spec, sysfs_root=pci_loss_sys, dev_root=pci_loss_dev, single_host_env=True, ) - self.assertTrue(ok_pt, f"{tick_label}: {msg_pt}") - pt_spec = json.loads(pci_loss_spec.read_text(encoding="utf-8")) - pt_names = {d["name"] for d in pt_spec["devices"]} - self.assertNotIn("pcie-0000-00-4", pt_names, tick_label) - self.assertNotIn("0-3", pt_names, tick_label) - for dev_entry in pt_spec["devices"]: - env_list = dev_entry.get("containerEdits", {}).get("env", []) - self.assertNotIn("TPU_CHIPS_PER_HOST_BOUNDS=2,2,1", env_list, tick_label) - self.assertNotIn("TPU_ACCELERATOR_TYPE=v6e-4", env_list, tick_label) + self.assertTrue(ok_p1, msg_p1) + for idx in range(4, 8): + shutil.rmtree( + pci_loss_sys / "bus" / "pci" / "devices" / f"0000:00:{4 + idx:02x}.0" + ) + (pci_loss_dev / "vfio" / str(idx)).unlink() + + for tick_label in ("tick2", "tick3"): + ok_pt, msg_pt = freetpu_cdi.reconcile_cdi_spec( + pci_loss_spec, + sysfs_root=pci_loss_sys, + dev_root=pci_loss_dev, + single_host_env=True, + ) + self.assertTrue(ok_pt, f"{tick_label}: {msg_pt}") + pt_spec = json.loads(pci_loss_spec.read_text(encoding="utf-8")) + pt_names = {d["name"] for d in pt_spec["devices"]} + self.assertNotIn("pcie-0000-00-4", pt_names, tick_label) + self.assertNotIn("0-3", pt_names, tick_label) + for dev_entry in pt_spec["devices"]: + env_list = dev_entry.get("containerEdits", {}).get("env", []) + self.assertNotIn("TPU_CHIPS_PER_HOST_BOUNDS=2,2,1", env_list, tick_label) + self.assertNotIn("TPU_ACCELERATOR_TYPE=v6e-4", env_list, tick_label) # Even on a fresh scan with no prior spec, 4 surviving chips with # non-contiguous sysfs `chip_id`s (`0, 2, 5, 7`) MUST NOT emit `pcie-0000-00-4` @@ -5669,39 +5672,40 @@ def test_degraded_single_root_v6e_domain_withholds_4chip_slice_and_2x2_bounds(se create_vfio_nodes=[str(i) for i in range(8)], ) gen_loss_spec_path = root / "cdi" / "gen_loss_freetpu.json" - rc_g1, _o1, err_g1 = _run_cli_inproc( - [ - "generate", - "--output", - str(gen_loss_spec_path), - "--validate", - "--single-host-env", - "--sysfs-root", - str(gen_loss_sys), - "--dev-root", - str(gen_loss_dev), - ] - ) - self.assertEqual(rc_g1, 0, err_g1) - for idx in range(4, 8): - shutil.rmtree( - gen_loss_sys / "bus" / "pci" / "devices" / f"0000:00:{4 + idx:02x}.0" + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-gen-loss"): + rc_g1, _o1, err_g1 = _run_cli_inproc( + [ + "generate", + "--output", + str(gen_loss_spec_path), + "--validate", + "--single-host-env", + "--sysfs-root", + str(gen_loss_sys), + "--dev-root", + str(gen_loss_dev), + ] ) - (gen_loss_dev / "vfio" / str(idx)).unlink() - rc_g2, _o2, err_g2 = _run_cli_inproc( - [ - "generate", - "--output", - str(gen_loss_spec_path), - "--validate", - "--single-host-env", - "--sysfs-root", - str(gen_loss_sys), - "--dev-root", - str(gen_loss_dev), - ] - ) - self.assertEqual(rc_g2, 0, err_g2) + self.assertEqual(rc_g1, 0, err_g1) + for idx in range(4, 8): + shutil.rmtree( + gen_loss_sys / "bus" / "pci" / "devices" / f"0000:00:{4 + idx:02x}.0" + ) + (gen_loss_dev / "vfio" / str(idx)).unlink() + rc_g2, _o2, err_g2 = _run_cli_inproc( + [ + "generate", + "--output", + str(gen_loss_spec_path), + "--validate", + "--single-host-env", + "--sysfs-root", + str(gen_loss_sys), + "--dev-root", + str(gen_loss_dev), + ] + ) + self.assertEqual(rc_g2, 0, err_g2) g2_spec = json.loads(gen_loss_spec_path.read_text(encoding="utf-8")) g2_names = {d["name"] for d in g2_spec["devices"]} self.assertNotIn("pcie-0000-00-4", g2_names) @@ -5816,36 +5820,37 @@ def test_degraded_single_root_v6e_domain_withholds_4chip_slice_and_2x2_bounds(se ) sr2_map = {shared_root_2numa_devs[i]["bdf"]: i for i in range(8)} sr2_spec_path = root / "cdi" / "sr2_freetpu.json" - ok_sr1, msg_sr1 = freetpu_cdi.reconcile_cdi_spec( - sr2_spec_path, - sysfs_root=sr2_sys, - dev_root=sr2_dev, - single_host_env=True, - chip_id_map=sr2_map, - ) - self.assertTrue(ok_sr1, msg_sr1) - sr1_names = { - d["name"] for d in json.loads(sr2_spec_path.read_text(encoding="utf-8"))["devices"] - } - self.assertIn("numa0-pcie-0000-00-4", sr1_names) - self.assertIn("numa1-pcie-0000-00-4", sr1_names) - - # Remove 1 TPU from `numa1` (`0000:00:0b.0`) from sysfs while keeping it in `sr2_map`. - shutil.rmtree(sr2_sys / "bus" / "pci" / "devices" / "0000:00:0b.0") - (sr2_dev / "vfio" / "7").unlink() - ok_sr2, msg_sr2 = freetpu_cdi.reconcile_cdi_spec( - sr2_spec_path, - sysfs_root=sr2_sys, - dev_root=sr2_dev, - single_host_env=True, - chip_id_map=sr2_map, - ) - self.assertTrue(ok_sr2, msg_sr2) - sr2_names = { - d["name"] for d in json.loads(sr2_spec_path.read_text(encoding="utf-8"))["devices"] - } - self.assertIn("numa0-pcie-0000-00-4", sr2_names) - self.assertNotIn("numa1-pcie-0000-00-4", sr2_names) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-sr2"): + ok_sr1, msg_sr1 = freetpu_cdi.reconcile_cdi_spec( + sr2_spec_path, + sysfs_root=sr2_sys, + dev_root=sr2_dev, + single_host_env=True, + chip_id_map=sr2_map, + ) + self.assertTrue(ok_sr1, msg_sr1) + sr1_names = { + d["name"] for d in json.loads(sr2_spec_path.read_text(encoding="utf-8"))["devices"] + } + self.assertIn("numa0-pcie-0000-00-4", sr1_names) + self.assertIn("numa1-pcie-0000-00-4", sr1_names) + + # Remove 1 TPU from `numa1` (`0000:00:0b.0`) from sysfs while keeping it in `sr2_map`. + shutil.rmtree(sr2_sys / "bus" / "pci" / "devices" / "0000:00:0b.0") + (sr2_dev / "vfio" / "7").unlink() + ok_sr2, msg_sr2 = freetpu_cdi.reconcile_cdi_spec( + sr2_spec_path, + sysfs_root=sr2_sys, + dev_root=sr2_dev, + single_host_env=True, + chip_id_map=sr2_map, + ) + self.assertTrue(ok_sr2, msg_sr2) + sr2_names = { + d["name"] for d in json.loads(sr2_spec_path.read_text(encoding="utf-8"))["devices"] + } + self.assertIn("numa0-pcie-0000-00-4", sr2_names) + self.assertNotIn("numa1-pcie-0000-00-4", sr2_names) # Bridged single-root v6e-8 (root `0000:00`, bridged endpoints on buses # `0000:04..0b`): on a FRESH scan where 4 endpoints disappeared while a @@ -6348,7 +6353,10 @@ def test_legacy_spec_upgrade_without_domain_annotations_withholds_degraded_bridg legacy_spec = { "cdiVersion": "0.6.0", "kind": "freetpu.dev/tpu", - "annotations": {"freetpu.dev/generated-by": "freetpu-cdi"}, + "annotations": { + "freetpu.dev/generated-by": "freetpu-cdi", + "freetpu.dev/boot-id": "boot-legacy-upgrade", + }, "containerEdits": {"deviceNodes": [{"path": "/dev/vfio/vfio"}]}, "devices": [ { @@ -6378,7 +6386,10 @@ def test_legacy_spec_upgrade_without_domain_annotations_withholds_degraded_bridg shutil.rmtree(bridge_dir / bdf) (dev_root / "vfio" / str(idx)).unlink() - with _mock_vfio_char_devices(): + with ( + _mock_vfio_char_devices(), + mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-legacy-upgrade"), + ): for _pass in range(2): rc_up, _ou, err_up = _run_cli_inproc( [ @@ -6431,7 +6442,10 @@ def test_legacy_spec_upgrade_without_domain_annotations_withholds_degraded_bridg legacy_dual_spec = { "cdiVersion": "0.6.0", "kind": "freetpu.dev/tpu", - "annotations": {"freetpu.dev/generated-by": "freetpu-cdi"}, + "annotations": { + "freetpu.dev/generated-by": "freetpu-cdi", + "freetpu.dev/boot-id": "boot-legacy-upgrade", + }, "containerEdits": {"deviceNodes": [{"path": "/dev/vfio/vfio"}]}, "devices": [ { @@ -6443,7 +6457,10 @@ def test_legacy_spec_upgrade_without_domain_annotations_withholds_degraded_bridg ], } spec_path2.write_text(json.dumps(legacy_dual_spec, indent=2) + "\n", encoding="utf-8") - with _mock_vfio_char_devices(): + with ( + _mock_vfio_char_devices(), + mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-legacy-upgrade"), + ): rc_dr2, _odr2, err_dr2 = _run_cli_inproc( [ "generate", @@ -6461,6 +6478,9 @@ def test_legacy_spec_upgrade_without_domain_annotations_withholds_degraded_bridg upgraded2 = json.loads(spec_path2.read_text(encoding="utf-8")) dev_names2 = {d["name"] for d in upgraded2["devices"]} self.assertIn("numa0-pcie-0000-00-4", dev_names2) + obs_ann2 = upgraded2["annotations"].get("freetpu.dev/observed-domain-bdfs", "") + for gone_dual in dual_root_legacy_bdfs[4:]: + self.assertIn(gone_dual, obs_ann2) def test_sync_restart_retains_observed_inventory_when_first_tick_fails_and_deletes_spec(self) -> None: import shutil @@ -6485,7 +6505,10 @@ def test_sync_restart_retains_observed_inventory_when_first_tick_fails_and_delet ) spec_path = root / "cdi" / "v6e8_sync.json" - with _mock_vfio_char_devices(): + with ( + _mock_vfio_char_devices(), + mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-sync-restart"), + ): # Publish healthy initial v6e-8 spec recording all 8 BDFs. rc_init, _oi, err_init = _run_cli_inproc( [ @@ -6580,6 +6603,3636 @@ def _fake_mono() -> float: for d_rec in all_devs: self.assertIn(d_rec["bdf"], obs_ann) + def test_tpu7x_dual_chiplet_topology_metadata(self) -> None: + # Issue #21: tpu7x Ironwood exposes 8 logical devices (2 chiplets per + # 192 GiB package) x 96 GiB HBM3e each. 0x1ae0:0x0075 is provisional + # pending Day-1 `lspci -nn` capture. + self.assertEqual(freetpu_cdi.TPU_PCI_DEVICES["0x0075"][0], "tpu7x") + self.assertEqual(freetpu_cdi.TPU_PCI_DEVICES["0x0076"][0], "tpu7x") + self.assertEqual(freetpu_cdi.TPU_CHIPLETS_PER_PKG["tpu7x"], 2) + self.assertEqual(freetpu_cdi.TPU_HBM_GIB_PER_LOGICAL_DEVICE["tpu7x"], 96) + self.assertEqual( + freetpu_cdi.tpu_topology_metadata("tpu7x"), + {"chiplets_per_pkg": 2, "hbm_gib_per_logical_device": 96}, + ) + # Single-chiplet generations default to 1; non-str fails closed. + self.assertEqual(freetpu_cdi.tpu_topology_metadata("v6e")["chiplets_per_pkg"], 1) + self.assertEqual( + freetpu_cdi.tpu_topology_metadata(None), + {"chiplets_per_pkg": 1, "hbm_gib_per_logical_device": None}, + ) + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + + # 1. 4-package (4 x 1-fn dual-chiplet) 0x0075 layout across 2 NUMA roots: + # must yield 4 complete chips, 0 incomplete functions, tpu7x-8, and + # 8 logical visible devices (0..7) across 4 physical chips (0..3). + pf4_devices = [ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + "chip_id": "0", + }, + { + "bdf": "0000:00:05.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "0", + "chip_id": "1", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "1", + "chip_id": "2", + }, + { + "bdf": "0000:80:01.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "3", + "numa_node": "1", + "chip_id": "3", + }, + ] + pf4_sys, pf4_dev = _make_mock_pci_vfio( + root / "pf4", + devices=pf4_devices, + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_devices(): + pf4_chips, pf4_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=pf4_sys, dev_root=pf4_dev + ) + self.assertEqual(len(pf4_chips), 4) + pf4_phys = freetpu_cdi._map_physical_chip_indices(pf4_chips) + self.assertEqual( + freetpu_cdi._count_complete_chips(pf4_chips, pf4_phys), (4, 0) + ) + pf4_spec = freetpu_cdi.build_cdi_spec( + pf4_chips, pf4_ctrl, single_host_env=True + ) + self.assertEqual(freetpu_cdi.validate_cdi_spec(pf4_spec), []) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + pf4_spec, sysfs_root=pf4_sys, dev_root=pf4_dev + ), + ([], []), + ) + pf4_by_name = {d["name"]: d for d in pf4_spec["devices"]} + pf4_pci = pf4_by_name["pci-0000-00-04-0"] + self.assertEqual( + pf4_pci["annotations"]["freetpu.dev/allocation-unit"], "single-chip" + ) + self.assertEqual( + pf4_pci["annotations"]["freetpu.dev/chiplets-per-pkg"], "2" + ) + self.assertEqual( + pf4_pci["annotations"]["freetpu.dev/hbm-gib-per-logical-device"], + "96", + ) + pf4_all = pf4_by_name["all"] + self.assertEqual(pf4_all["annotations"]["freetpu.dev/chip-count"], "4") + self.assertNotIn("freetpu.dev/pci-function-count", pf4_all["annotations"]) + self.assertNotIn("freetpu.dev/capacity-complete", pf4_all["annotations"]) + self.assertNotIn( + "freetpu.dev/incomplete-pci-functions", pf4_all["annotations"] + ) + self.assertEqual( + pf4_all["annotations"]["freetpu.dev/chiplets-per-pkg"], "2" + ) + self.assertEqual( + pf4_all["annotations"]["freetpu.dev/hbm-gib-per-logical-device"], + "96", + ) + pf4_env = dict( + kv.split("=", 1) for kv in pf4_all["containerEdits"]["env"] + ) + self.assertEqual(pf4_env["TPU_CHIPS_PER_HOST_BOUNDS"], "2,2,1") + self.assertEqual(pf4_env["TPU_ACCELERATOR_TYPE"], "tpu7x-8") + self.assertEqual(pf4_env["TPU_VISIBLE_CHIPS"], "0,1,2,3") + self.assertEqual(pf4_env["TPU_VISIBLE_DEVICES"], "0,1,2,3,4,5,6,7") + self.assertEqual(pf4_env["TPU_SKIP_MDS_QUERY"], "true") + + # 2. Single-root 4 x 1-fn 0x0075 layout emits contiguous slice + 0-3 alias + # with 8 logical devices and dual-chiplet metadata. + pf4_single_root = [ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i), + } + for i in range(4) + ] + pf4s_sys, pf4s_dev = _make_mock_pci_vfio( + root / "pf4_single_root", + devices=pf4_single_root, + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_devices(): + pf4s_chips, pf4s_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + pf4s_spec = freetpu_cdi.build_cdi_spec( + pf4s_chips, pf4s_ctrl, single_host_env=True + ) + self.assertEqual(freetpu_cdi.validate_cdi_spec(pf4s_spec), []) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + pf4s_spec, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ), + ([], []), + ) + pf4s_by_name = {d["name"]: d for d in pf4s_spec["devices"]} + self.assertIn("numa0-pcie-0000-00-4", pf4s_by_name) + self.assertIn("0-3", pf4s_by_name) + slice_env = dict( + kv.split("=", 1) + for kv in pf4s_by_name["numa0-pcie-0000-00-4"]["containerEdits"]["env"] + ) + self.assertEqual(slice_env["TPU_ACCELERATOR_TYPE"], "tpu7x-8") + self.assertEqual(slice_env["TPU_VISIBLE_CHIPS"], "0,1,2,3") + self.assertEqual(slice_env["TPU_VISIBLE_DEVICES"], "0,1,2,3,4,5,6,7") + + # 3. 4-package (4 x 2-fn, 8 functions) 0x0075 multifunction layout also + # maps cleanly to 4 complete chips, 0 incomplete functions, tpu7x-8. + pf8_devices = [ + { + "bdf": f"0000:00:0{4 + (i // 2):x}.{i % 2}", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ] + [ + { + "bdf": f"0000:80:0{i // 2:x}.{i % 2}", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(4 + i), + "numa_node": "1", + } + for i in range(4) + ] + pf8_sys, pf8_dev = _make_mock_pci_vfio( + root / "pf8", + devices=pf8_devices, + create_vfio_nodes=[str(i) for i in range(8)], + ) + with _mock_vfio_char_devices(): + pf8_chips, pf8_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=pf8_sys, dev_root=pf8_dev + ) + self.assertEqual(len(pf8_chips), 8) + pf8_phys = freetpu_cdi._map_physical_chip_indices(pf8_chips) + self.assertEqual( + freetpu_cdi._count_complete_chips(pf8_chips, pf8_phys), (4, 0) + ) + pf8_spec = freetpu_cdi.build_cdi_spec( + pf8_chips, pf8_ctrl, single_host_env=True + ) + self.assertEqual(freetpu_cdi.validate_cdi_spec(pf8_spec), []) + pf8_by_name = {d["name"]: d for d in pf8_spec["devices"]} + self.assertEqual( + pf8_by_name["pci-0000-00-04-0"]["annotations"][ + "freetpu.dev/allocation-unit" + ], + "single-chiplet", + ) + self.assertEqual( + pf8_by_name["all"]["annotations"]["freetpu.dev/chip-count"], "4" + ) + self.assertEqual( + pf8_by_name["all"]["annotations"]["freetpu.dev/pci-function-count"], + "8", + ) + pf8_env = dict( + kv.split("=", 1) for kv in pf8_by_name["all"]["containerEdits"]["env"] + ) + self.assertEqual(pf8_env["TPU_ACCELERATOR_TYPE"], "tpu7x-8") + self.assertEqual(pf8_env["TPU_CHIPS_PER_HOST_BOUNDS"], "2,2,1") + + # 4. Degraded 2-fn 0x0075 (1 multifunction pair + 1 orphan) still detects + # the 2-fn layout and reports the unpaired function as incomplete. + deg_0075_sys, deg_0075_dev = _make_mock_pci_vfio( + root / "pf_deg_2fn", + devices=pf8_devices[:3], + create_vfio_nodes=["0", "1", "2"], + ) + with _mock_vfio_char_devices(): + deg_chips, _deg_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=deg_0075_sys, dev_root=deg_0075_dev + ) + deg_phys = freetpu_cdi._map_physical_chip_indices(deg_chips) + self.assertEqual( + freetpu_cdi._count_complete_chips(deg_chips, deg_phys), (1, 1) + ) + + # 5. `.1`-only 0x0075 orphans (all non-.0 functions) resolve as 2-fn -> (0, 4). + dot1_sys, dot1_dev = _make_mock_pci_vfio( + root / "pf_dot1_orphans", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "numa_node": "0" if idx < 2 else "1", + "chip_id": str(idx), + } + for idx, bdf in enumerate( + ( + "0000:00:04.1", + "0000:00:05.1", + "0000:80:00.1", + "0000:80:01.1", + ) + ) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_devices(): + dot1_chips, _dot1_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=dot1_sys, dev_root=dot1_dev + ) + dot1_phys = freetpu_cdi._map_physical_chip_indices(dot1_chips) + self.assertEqual( + freetpu_cdi._count_complete_chips(dot1_chips, dot1_phys), (0, 4) + ) + + # 6. Cross-root repeated sysfs chip_id (`0,1` on bus 00 and `0,1` on bus 80) + # still yields (4, 0) on 4 x 1-fn 0x0075 (domain/root-bus scoped). + xroot_sys, xroot_dev = _make_mock_pci_vfio( + root / "pf_xroot", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "numa_node": "0" if idx < 2 else "1", + "chip_id": str(idx % 2), + } + for idx, bdf in enumerate( + ( + "0000:00:04.0", + "0000:00:05.0", + "0000:80:00.0", + "0000:80:01.0", + ) + ) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_devices(): + xroot_chips, _xroot_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=xroot_sys, dev_root=xroot_dev + ) + xroot_phys = freetpu_cdi._map_physical_chip_indices(xroot_chips) + self.assertEqual( + freetpu_cdi._count_complete_chips(xroot_chips, xroot_phys), (4, 0) + ) + + # 7. Map-paired 4-fn 0x0075 (`chip_id_map` pairs same-domain .0 functions + # sharing an IOMMU group into 2 physical packages) records + # `chip-id-source`, verifies cleanly with `chip_id_map`, becomes + # unverifiable without `chip_id_map`, and rejects bogus `chip-count` + # / `chiplets-per-pkg` annotations. + pair4_sys, pair4_dev = _make_mock_pci_vfio( + root / "pf_map_paired", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + for i in range(4) + ], + create_vfio_nodes=["0"], + ) + pair4_map = { + "0000:00:04.0": 0, + "0000:00:05.0": 0, + "0000:00:06.0": 1, + "0000:00:07.0": 1, + } + with _mock_vfio_char_devices(): + pair4_chips, pair4_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=pair4_sys, dev_root=pair4_dev + ) + pair4_spec = freetpu_cdi.build_cdi_spec( + pair4_chips, pair4_ctrl, single_host_env=True, chip_id_map=pair4_map + ) + pair4_by_name = {d["name"]: d for d in pair4_spec["devices"]} + group_names = [ + n for n in pair4_by_name if n.startswith("group-pci-") + ] + self.assertEqual(len(group_names), 1) + self.assertIn( + "freetpu.dev/chip-id-source", + pair4_by_name[group_names[0]]["annotations"], + ) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + pair4_spec, + sysfs_root=pair4_sys, + dev_root=pair4_dev, + chip_id_map=pair4_map, + ), + ([], []), + ) + no_map_errs, no_map_unver = ( + freetpu_cdi._verify_spec_against_host_detailed( + pair4_spec, sysfs_root=pair4_sys, dev_root=pair4_dev + ) + ) + self.assertEqual(no_map_errs, []) + self.assertGreater(len(no_map_unver), 0) + + bad_ann_spec = copy.deepcopy(pf4s_spec) + bad_ann_all = next( + d for d in bad_ann_spec["devices"] if d["name"] == "all" + ) + bad_ann_all["annotations"]["freetpu.dev/chip-count"] = "99" + bad_ann_all["annotations"]["freetpu.dev/chiplets-per-pkg"] = "-1" + bad_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + bad_ann_spec, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + self.assertGreaterEqual(len(bad_errs), 2) + + # 8. Missing sibling fails stale `TPU_VISIBLE_DEVICES` and scrambled + # chiplet pairing `(0,2)` fails per-package visibility check. + deg3_sys, deg3_dev = _make_mock_pci_vfio( + root / "pf_deg3", + devices=pf4_single_root[:3], + create_vfio_nodes=["0", "1", "2"], + ) + with _mock_vfio_char_devices(): + deg3_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + pf4s_spec, sysfs_root=deg3_sys, dev_root=deg3_dev + ) + self.assertGreater(len(deg3_errs), 0) + + pf4s_phys = freetpu_cdi._map_physical_chip_indices(pf4s_chips) + self.assertEqual( + freetpu_cdi._resolve_verified_visibility_ordinals( + [pf4s_chips[0]], pf4s_chips, pf4s_phys + ), + ([0], [0, 1]), + ) + self.assertEqual( + freetpu_cdi._resolve_verified_visibility_ordinals( + [pf4s_chips[2]], pf4s_chips, pf4s_phys + ), + ([2], [4, 5]), + ) + + scrambled_spec = copy.deepcopy(pf4s_spec) + scrambled_dev = next( + d + for d in scrambled_spec["devices"] + if d["name"] == "0-3" + ) + scrambled_dev["containerEdits"]["env"] = [ + "TPU_VISIBLE_DEVICES=0,2,1,3,4,5,6,7" + if kv.startswith("TPU_VISIBLE_DEVICES=") + else kv + for kv in scrambled_dev["containerEdits"]["env"] + ] + scr_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + scrambled_spec, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + self.assertGreater(len(scr_errs), 0) + + # 9. Three separate .0 functions mapped (0,0,1) verify cleanly with map + # and return unverifiable (never confirmed errors) without map; two + # shared IOMMU groups with only group 0 mapped also mark group 1 map-dependent. + p3_sys, p3_dev = _make_mock_pci_vfio( + root / "pf3_map", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(3) + ], + create_vfio_nodes=["0", "1", "2"], + ) + p3_map = { + "0000:00:04.0": 0, + "0000:00:05.0": 0, + "0000:00:06.0": 1, + } + with _mock_vfio_char_devices(): + p3_chips, p3_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=p3_sys, dev_root=p3_dev + ) + p3_spec = freetpu_cdi.build_cdi_spec( + p3_chips, p3_ctrl, single_host_env=True, chip_id_map=p3_map + ) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + p3_spec, sysfs_root=p3_sys, dev_root=p3_dev, chip_id_map=p3_map + ), + ([], []), + ) + p3_errs, p3_unver = freetpu_cdi._verify_spec_against_host_detailed( + p3_spec, sysfs_root=p3_sys, dev_root=p3_dev + ) + self.assertEqual(p3_errs, []) + self.assertGreater(len(p3_unver), 0) + + two_grp_sys, two_grp_dev = _make_mock_pci_vfio( + root / "two_grp_one_mapped", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i // 2), + "numa_node": "0", + } + for i in range(4) + ], + create_vfio_nodes=["0", "1"], + ) + with _mock_vfio_char_devices(): + tg_chips, tg_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=two_grp_sys, dev_root=two_grp_dev + ) + tg_spec = freetpu_cdi.build_cdi_spec( + tg_chips, + tg_ctrl, + single_host_env=True, + chip_id_map={"0000:00:04.0": 0, "0000:00:05.0": 0}, + ) + tg_by_name = {d["name"]: d for d in tg_spec["devices"]} + self.assertEqual( + tg_by_name["group-pci-0000-00-06-0_0000-00-07-0"]["annotations"].get( + "freetpu.dev/chip-id-source" + ), + "chip-id-map", + ) + + # 10. Structural bounds / tampered capacity annotations & singleton + # allocation-unit and broken TPU_VISIBLE_* pairs MUST fail with errors + # even when --chip-id-map is omitted. + with _mock_vfio_char_devices(): + bad_meta = copy.deepcopy(pf4s_spec) + bad_all = next(d for d in bad_meta["devices"] if d["name"] == "all") + bad_all["annotations"]["freetpu.dev/pci-function-count"] = "99" + bad_all["annotations"]["freetpu.dev/incomplete-pci-functions"] = "99" + bad_all["annotations"]["freetpu.dev/capacity-complete"] = "false" + bad_sgl = next( + d for d in bad_meta["devices"] if d["name"] == "pci-0000-00-04-0" + ) + bad_sgl["annotations"]["freetpu.dev/allocation-unit"] = "single-chiplet" + meta_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + bad_meta, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + self.assertGreaterEqual(len(meta_errs), 4) + + bad_vis = copy.deepcopy(pf4s_spec) + bad_vis_all = next(d for d in bad_vis["devices"] if d["name"] == "all") + bad_vis_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + bad_vis_all["containerEdits"]["env"] = [ + "TPU_VISIBLE_CHIPS=0,1" + if kv.startswith("TPU_VISIBLE_CHIPS=") + else ( + "TPU_VISIBLE_DEVICES=99" + if kv.startswith("TPU_VISIBLE_DEVICES=") + else kv + ) + for kv in bad_vis_all["containerEdits"]["env"] + ] + vis_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + bad_vis, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + self.assertGreater(len(vis_errs), 0) + + # 11. Domain-scoped physical pairing, 3-fn slot inventory guard, subset + # _count_complete_chips, and generation-scoped historical BDF tracking. + dom_pair_sys, dom_pair_dev = _make_mock_pci_vfio( + root / "dom_pair_local0", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + "chip_id": "0", + }, + { + "bdf": "0000:00:05.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "0", + "chip_id": "0", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "1", + "chip_id": "0", + }, + { + "bdf": "0000:80:01.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "3", + "numa_node": "1", + "chip_id": "0", + }, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with _mock_vfio_char_devices(): + dp_chips, _ = freetpu_cdi.discover_tpu_chips( + sysfs_root=dom_pair_sys, dev_root=dom_pair_dev + ) + dp_phys = freetpu_cdi._map_physical_chip_indices(dp_chips) + self.assertEqual( + freetpu_cdi._count_complete_chips(dp_chips, dp_phys), (2, 0) + ) + self.assertEqual( + freetpu_cdi._count_complete_chips([dp_chips[0]], dp_phys), (0, 1) + ) + + slot3_sys, slot3_dev = _make_mock_pci_vfio( + root / "slot3_inv", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + }, + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "1", + }, + { + "bdf": "0000:00:04.2", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "2", + }, + ], + create_vfio_nodes=["0", "1"], + ) + with _mock_vfio_char_devices(): + s3_chips, _, s3_inv = freetpu_cdi._discover_tpu_chips_with_inventory( + sysfs_root=slot3_sys, dev_root=slot3_dev + ) + s3_phys = freetpu_cdi._map_physical_chip_indices( + s3_chips, host_pci_inventory=s3_inv + ) + self.assertEqual( + freetpu_cdi._count_complete_chips( + s3_chips, s3_phys, host_pci_inventory=s3_inv + ), + (0, 2), + ) + + with _mock_vfio_char_devices(): + # Absent historical v5e does not turn 4 healthy 1-fn tpu7x into orphans; + # live v5e alongside 4 surviving .0 tpu7x with absent .1 sibling still flags (1, 4). + v5e_per = freetpu_cdi._resolve_pci_functions_per_chip( + pf4s_chips, + observed_domain_bdfs={("numa", 0, "0000:00"): {"0000:00:08.0"}}, + observed_bdf_generations={"0000:00:08.0": "v5e"}, + ) + self.assertEqual(v5e_per["0000:00:04.0"], 1) + + mix_sys, mix_dev = _make_mock_pci_vfio( + root / "mix_v5e_tpu7x", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ] + + [ + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "4", + "numa_node": "1", + } + ], + create_vfio_nodes=[str(i) for i in range(5)], + ) + mix_chips, _, mix_inv = freetpu_cdi._discover_tpu_chips_with_inventory( + sysfs_root=mix_sys, dev_root=mix_dev + ) + obs_mix = {("numa", 0, "0000:00"): {"0000:00:04.1"}} + obs_mix_gens = {"0000:00:04.1": "tpu7x"} + mix_per = freetpu_cdi._resolve_pci_functions_per_chip( + mix_chips, + host_pci_inventory=mix_inv, + observed_domain_bdfs=obs_mix, + observed_bdf_generations=obs_mix_gens, + ) + mix_phys = freetpu_cdi._map_physical_chip_indices( + mix_chips, + host_pci_inventory=mix_inv, + observed_domain_bdfs=obs_mix, + expected_fns_by_bdf=mix_per, + ) + self.assertEqual( + freetpu_cdi._count_complete_chips( + mix_chips, mix_phys, expected_fns_by_bdf=mix_per + ), + (1, 4), + ) + + # 12. Round-3 regressions: + # (a) Single surviving .0 with absent .1 in map preserves without map; + # (b) 3 Ironwood (0,0,1) + 1 live or absent v5e preserves without map; + # (c) Two NUMA nodes sharing 1 root keep (4, 0) and unrelated absent key + # does not flip layout; + # (d) Forced 0x0076 pair relabeling, slice count tampering, banana bool, + # shortened masks, and unicode superscript `²` all fail closed while + # accurate explicit `pci-function-count="4"` on `all` passes; + # (e) Overfull 3-fn slot rejects ID/map pairing, legacy group recovery + # extracts homogeneous generation, and orphan subset returns (0, 1). + one_sys, one_dev = _make_mock_pci_vfio( + root / "one_surviving_0075", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + with _mock_vfio_char_devices(): + one_c, one_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=one_sys, dev_root=one_dev + ) + one_spec = freetpu_cdi.build_cdi_spec( + one_c, + one_ctrl, + single_host_env=True, + chip_id_map={"0000:00:04.1": 0}, + ) + one_all = next(d for d in one_spec["devices"] if d["name"] == "all") + self.assertEqual( + one_all["annotations"].get("freetpu.dev/chip-id-source"), + "chip-id-map", + ) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + one_spec, + sysfs_root=one_sys, + dev_root=one_dev, + chip_id_map={"0000:00:04.1": 0}, + ), + ([], []), + ) + one_e, one_u = freetpu_cdi._verify_spec_against_host_detailed( + one_spec, sysfs_root=one_sys, dev_root=one_dev + ) + self.assertEqual(one_e, []) + self.assertGreater(len(one_u), 0) + + mix3_sys, mix3_dev = _make_mock_pci_vfio( + root / "mix3_iw_v5e", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(3) + ] + + [ + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "3", + "numa_node": "1", + } + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + mix3_c, mix3_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=mix3_sys, dev_root=mix3_dev + ) + mix3_spec = freetpu_cdi.build_cdi_spec( + mix3_c, mix3_ctrl, single_host_env=True, chip_id_map=p3_map + ) + m3_e, m3_u = freetpu_cdi._verify_spec_against_host_detailed( + mix3_spec, sysfs_root=mix3_sys, dev_root=mix3_dev + ) + self.assertEqual(m3_e, []) + self.assertGreater(len(m3_u), 0) + + p3_hist_spec = freetpu_cdi.build_cdi_spec( + p3_chips, + p3_ctrl, + single_host_env=True, + chip_id_map=p3_map, + observed_domain_bdfs={("numa", 1, "0000:80"): {"0000:80:00.0"}}, + observed_bdf_generations={"0000:80:00.0": "v5e"}, + ) + ph_e, ph_u = freetpu_cdi._verify_spec_against_host_detailed( + p3_hist_spec, sysfs_root=p3_sys, dev_root=p3_dev + ) + self.assertEqual(ph_e, []) + self.assertGreater(len(ph_u), 0) + + same_root_2numa_sys, same_root_2numa_dev = _make_mock_pci_vfio( + root / "one_root_two_numa", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0" if i < 2 else "1", + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with _mock_vfio_char_devices(): + sr_c, _ = freetpu_cdi.discover_tpu_chips( + sysfs_root=same_root_2numa_sys, dev_root=same_root_2numa_dev + ) + sr_per = freetpu_cdi._resolve_pci_functions_per_chip( + sr_c, + chip_id_map={ + "0000:00:04.0": 0, + "0000:00:05.0": 1, + "0000:00:06.0": 0, + "0000:00:07.0": 1, + }, + ) + self.assertEqual(sr_per["0000:00:04.0"], 1) + unrel_per = freetpu_cdi._resolve_pci_functions_per_chip( + pf4s_chips, chip_id_map={"0000:c0:00.0": 9} + ) + self.assertEqual(unrel_per["0000:00:04.0"], 1) + + f76_sys, f76_dev = _make_mock_pci_vfio( + root / "forced_0076_pairs", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": str(idx), + "numa_node": "0", + } + for idx, bdf in enumerate( + ("0000:00:04.0", "0000:00:04.1", "0000:00:05.0", "0000:00:05.1") + ) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with _mock_vfio_char_devices(): + f76_c, f76_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=f76_sys, dev_root=f76_dev + ) + f76_spec = freetpu_cdi.build_cdi_spec( + f76_c, f76_ctrl, single_host_env=True + ) + bad76 = copy.deepcopy(f76_spec) + b76_all = next(d for d in bad76["devices"] if d["name"] == "all") + b76_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + b76_all["annotations"]["freetpu.dev/chip-count"] = "1" + b76_all["annotations"]["freetpu.dev/incomplete-pci-functions"] = "2" + b76_all["annotations"]["freetpu.dev/capacity-complete"] = "false" + b76_sgl = next( + d for d in bad76["devices"] if d["name"] == "pci-0000-00-04-0" + ) + b76_sgl["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + b76_sgl["annotations"]["freetpu.dev/allocation-unit"] = "single-chip" + b76_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + bad76, sysfs_root=f76_sys, dev_root=f76_dev + ) + self.assertGreaterEqual(len(b76_errs), 2) + + tamper_spec = copy.deepcopy(pf4s_spec) + t_sl = next(d for d in tamper_spec["devices"] if d["name"] == "0-3") + t_sl["annotations"]["freetpu.dev/pci-function-count"] = "99" + t_all = next(d for d in tamper_spec["devices"] if d["name"] == "all") + t_all["annotations"]["freetpu.dev/capacity-complete"] = "banana" + t_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + t_all["containerEdits"]["env"] = [ + "TPU_VISIBLE_CHIPS=²" + if kv.startswith("TPU_VISIBLE_CHIPS=") + else kv + for kv in t_all["containerEdits"]["env"] + ] + t_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + tamper_spec, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + self.assertGreaterEqual(len(t_errs), 3) + + acc_fn_spec = copy.deepcopy(pf4s_spec) + acc_all = next(d for d in acc_fn_spec["devices"] if d["name"] == "all") + acc_all["annotations"]["freetpu.dev/pci-function-count"] = "4" + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + acc_fn_spec, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ), + ([], []), + ) + + short_mask = copy.deepcopy(pf4s_spec) + sm_all = next(d for d in short_mask["devices"] if d["name"] == "all") + sm_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + sm_all["containerEdits"]["env"] = [ + "TPU_VISIBLE_CHIPS=0" + if kv.startswith("TPU_VISIBLE_CHIPS=") + else ( + "TPU_VISIBLE_DEVICES=0,1" + if kv.startswith("TPU_VISIBLE_DEVICES=") + else kv + ) + for kv in sm_all["containerEdits"]["env"] + ] + sm_errs, _ = freetpu_cdi._verify_spec_against_host_detailed( + short_mask, sysfs_root=pf4s_sys, dev_root=pf4s_dev + ) + self.assertGreater(len(sm_errs), 0) + + slot3_id_sys, slot3_id_dev = _make_mock_pci_vfio( + root / "slot3_shared_ids", + devices=[ + { + "bdf": f"0000:00:04.{fn_i}", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(fn_i), + **({"chip_id": "0"} if fn_i < 2 else {}), + } + for fn_i in range(3) + ], + create_vfio_nodes=["0", "1"], + ) + with _mock_vfio_char_devices(): + s3i_c, _, s3i_inv = freetpu_cdi._discover_tpu_chips_with_inventory( + sysfs_root=slot3_id_sys, dev_root=slot3_id_dev + ) + s3i_phys = freetpu_cdi._map_physical_chip_indices( + s3i_c, + chip_id_map={"0000:00:04.0": 0, "0000:00:04.1": 0}, + host_pci_inventory=s3i_inv, + ) + self.assertEqual( + freetpu_cdi._count_complete_chips( + s3i_c, s3i_phys, host_pci_inventory=s3i_inv + ), + (0, 2), + ) + + legacy_grp_spec = { + "cdiVersion": "0.6.0", + "kind": "freetpu.dev/tpu", + "devices": [ + { + "name": "group-pci-0000-80-00-0_0000-80-01-0", + "annotations": { + "freetpu.dev/pci-bdfs": "0000:80:00.0,0000:80:01.0", + "freetpu.dev/generations": "v5e,v5e", + }, + "containerEdits": {}, + } + ], + } + self.assertEqual( + freetpu_cdi._extract_observed_bdf_generations_from_spec( + legacy_grp_spec + ), + {"0000:80:00.0": "v5e", "0000:80:01.0": "v5e"}, + ) + + p3_full_phys = freetpu_cdi._map_physical_chip_indices( + p3_chips, chip_id_map=p3_map + ) + self.assertEqual( + freetpu_cdi._count_complete_chips([p3_chips[2]], p3_full_phys), + (0, 1), + ) + + # 13. Round-4 regressions: + # (a) 4 x 1-fn Ironwood + 2 separate-slot v2-v3 mapped to 1 legacy chip -> chip-count=5 preserved without map; + # (b) Surviving .0 with absent .1 recording single-chiplet + chip-count=0 preserved without map; + # (c) Same-boot 2-fn sysfs history (0,0,1,1 -> 2 survivors) retains single-chiplet (0,2); + # (d) Same-bus / bridged absent mapped partner keeps 2-fn while unrelated BDF stays excluded; + # (e) Overfull .0/.1/.2, lone 0x0076 chip-count=0 with masks, and cross-selector 4-chip vs single-chiplet reject cleanly; + # (f) Custom alias capacity annotations, 5000-digit decimal string, high map 32765..32768, and mixed iw+v2 _count_complete_chips. + mix_v2_sys, mix_v2_dev = _make_mock_pci_vfio( + root / "mix_iw_v2", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ] + + [ + { + "bdf": f"0000:80:0{i:x}.0", + "vendor": "0x1ae0", + "device": "0x0027", + "subsystem_device": "0x004e", + "driver": "vfio-pci", + "iommu_group": str(10 + i), + "numa_node": "1", + } + for i in range(2) + ], + create_vfio_nodes=["0", "1", "2", "3", "10", "11"], + ) + mix_v2_chips, mix_v2_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=mix_v2_sys, dev_root=mix_v2_dev + ) + mix_v2_map = {"0000:80:00.0": 4, "0000:80:01.0": 4} + mix_v2_spec = freetpu_cdi.build_cdi_spec( + mix_v2_chips, + mix_v2_ctrl, + single_host_env=True, + chip_id_map=mix_v2_map, + ) + mix_v2_all = next(d for d in mix_v2_spec["devices"] if d["name"] == "all") + self.assertEqual(mix_v2_all["annotations"]["freetpu.dev/chip-count"], "5") + mix_v2_spec_path = root / "mix_v2_spec.json" + mix_v2_spec_path.write_text(json.dumps(mix_v2_spec), encoding="utf-8") + mv2_e, mv2_u = freetpu_cdi._verify_spec_against_host_detailed( + mix_v2_spec, sysfs_root=mix_v2_sys, dev_root=mix_v2_dev + ) + self.assertEqual(mv2_e, []) + self.assertGreater(len(mv2_u), 0) + self.assertEqual( + freetpu_cdi.main( + [ + "validate", + str(mix_v2_spec_path), + "--sysfs-root", + str(mix_v2_sys), + "--dev-root", + str(mix_v2_dev), + "--check-host", + "--remove-if-stale", + ] + ), + 1, + ) + self.assertTrue(mix_v2_spec_path.exists()) + + sgl_zero_spec = json.loads(json.dumps(one_spec)) + sgl_p0 = next( + d for d in sgl_zero_spec["devices"] if d["name"] == "pci-0000-00-04-0" + ) + sgl_p0["annotations"]["freetpu.dev/chip-count"] = "0" + sgl_p0["annotations"]["freetpu.dev/incomplete-pci-functions"] = "1" + sgl_p0["annotations"]["freetpu.dev/capacity-complete"] = "false" + sz_e, sz_u = freetpu_cdi._verify_spec_against_host_detailed( + sgl_zero_spec, sysfs_root=one_sys, dev_root=one_dev + ) + self.assertEqual(sz_e, []) + self.assertGreater(len(sz_u), 0) + sgl_zero_bad = json.loads(json.dumps(sgl_zero_spec)) + next( + d for d in sgl_zero_bad["devices"] if d["name"] == "pci-0000-00-04-0" + )["annotations"]["freetpu.dev/allocation-unit"] = "single-chip" + szb_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + sgl_zero_bad, sysfs_root=one_sys, dev_root=one_dev + ) + self.assertTrue(any("chip-count" in err or "allocation-unit" in err for err in szb_e)) + + boot4_sys, boot4_dev = _make_mock_pci_vfio( + root / "boot4_sysfs_drop", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i // 2), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + boot4_spec_path = root / "boot4_sync.json" + with mock.patch.object( + freetpu_cdi, "_read_host_boot_id", return_value="boot-4" + ): + ok_sync1, _ = freetpu_cdi.reconcile_cdi_spec( + boot4_spec_path, + sysfs_root=boot4_sys, + dev_root=boot4_dev, + single_host_env=True, + ) + self.assertTrue(ok_sync1) + spec_boot1 = json.loads(boot4_spec_path.read_text(encoding="utf-8")) + self.assertEqual( + spec_boot1["annotations"].get("freetpu.dev/tpu7x-pci-functions-per-chip"), + "2", + ) + for drop_bdf in ("0000:00:05.0", "0000:00:07.0"): + dev_p = boot4_sys / "bus" / "pci" / "devices" / drop_bdf + if dev_p.is_dir() and not dev_p.is_symlink(): + shutil.rmtree(dev_p) + elif dev_p.is_symlink() or dev_p.exists(): + dev_p.unlink() + (boot4_dev / "vfio" / "1").unlink() + (boot4_dev / "vfio" / "3").unlink() + ok_sync2, _ = freetpu_cdi.reconcile_cdi_spec( + boot4_spec_path, + sysfs_root=boot4_sys, + dev_root=boot4_dev, + single_host_env=True, + ) + self.assertTrue(ok_sync2) + spec_boot2 = json.loads(boot4_spec_path.read_text(encoding="utf-8")) + sb2_by_name = {d["name"]: d for d in spec_boot2["devices"]} + self.assertEqual( + sb2_by_name["pci-0000-00-04-0"]["annotations"]["freetpu.dev/allocation-unit"], + "single-chiplet", + ) + self.assertEqual(sb2_by_name["all"]["annotations"]["freetpu.dev/chip-count"], "0") + self.assertEqual( + sb2_by_name["all"]["annotations"]["freetpu.dev/incomplete-pci-functions"], + "2", + ) + # Direct in-memory regeneration using extracted observed domains also preserves 2-fn. + surv_chips, surv_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=boot4_sys, dev_root=boot4_dev + ) + surv_spec_mem = freetpu_cdi.build_cdi_spec( + surv_chips, + surv_ctrl, + observed_domain_bdfs=freetpu_cdi._extract_observed_domain_bdfs_from_spec( + spec_boot1 + ), + observed_bdf_generations=freetpu_cdi._extract_observed_bdf_generations_from_spec( + spec_boot1 + ), + ) + self.assertEqual( + next(d for d in surv_spec_mem["devices"] if d["name"] == "all")[ + "annotations" + ]["freetpu.dev/chip-count"], + "0", + ) + + # Same-bus absent sibling (0000:00:05.0 on bus 0000:00 with live 0000:00:04.0 numa=0) + samebus_phys = freetpu_cdi._map_physical_chip_indices( + one_c, chip_id_map={"0000:00:04.0": 0, "0000:00:05.0": 0} + ) + self.assertEqual(freetpu_cdi._count_complete_chips(one_c, samebus_phys), (0, 1)) + # Bridged absent sibling placed onto live root via secondary/subordinate bridge scan + br_sys, br_dev = _make_mock_pci_vfio( + root / "bridged_absent", + devices=[ + { + "bdf": "0000:04:00.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + br_rp = br_sys / "devices" / "pci0000:00" / "0000:00:01.0" + br_rp.mkdir(parents=True, exist_ok=True) + (br_rp / "secondary_bus_number").write_text("0x04\n", encoding="utf-8") + (br_rp / "subordinate_bus_number").write_text("0x04\n", encoding="utf-8") + src_ep = br_sys / "bus" / "pci" / "devices" / "0000:04:00.0" + dst_ep = br_rp / "0000:04:00.0" + shutil.move(str(src_ep), str(dst_ep)) + src_ep.symlink_to(dst_ep) + igrp_ep = br_sys / "kernel" / "iommu_groups" / "0" / "devices" / "0000:04:00.0" + igrp_ep.unlink() + igrp_ep.symlink_to(dst_ep) + (br_sys / "bus" / "pci" / "devices" / "0000:00:01.0").symlink_to(br_rp) + br_dir = br_sys / "devices" / "pci0000:00" / "0000:00:02.0" + br_dir.mkdir(parents=True, exist_ok=True) + (br_dir / "secondary_bus_number").write_text("0x05\n", encoding="utf-8") + (br_dir / "subordinate_bus_number").write_text("0x05\n", encoding="utf-8") + (br_sys / "bus" / "pci" / "devices" / "0000:00:02.0").symlink_to(br_dir) + br_chips, _ = freetpu_cdi.discover_tpu_chips(sysfs_root=br_sys, dev_root=br_dev) + self.assertEqual(br_chips[0].pcie_root, "0000:00") + br_phys = freetpu_cdi._map_physical_chip_indices( + br_chips, + chip_id_map={"0000:04:00.0": 0, "0000:05:00.0": 0}, + bridge_bus_to_roots=freetpu_cdi._scan_pcie_bridge_roots(br_sys), + ) + self.assertEqual(freetpu_cdi._count_complete_chips(br_chips, br_phys), (0, 1)) + + # Reject provable contradictions even with chip-id-source=chip-id-map: + # 1) overfull .0/.1/.2 slot claiming chip-count=1 + ovf_spec = freetpu_cdi.build_cdi_spec(s3i_c, one_ctrl) + ovf_all = next(d for d in ovf_spec["devices"] if d["name"] == "all") + ovf_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + ovf_all["annotations"]["freetpu.dev/chip-count"] = "1" + ovf_all["annotations"]["freetpu.dev/incomplete-pci-functions"] = "1" + ovf_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + ovf_spec, sysfs_root=slot3_sys, dev_root=slot3_dev + ) + self.assertTrue(len(ovf_e) > 0) + + # 2) lone 0x0076 with chip-count=0 + injected TPU_VISIBLE_CHIPS / DEVICES + lone76_sys, lone76_dev = _make_mock_pci_vfio( + root / "lone_0076_vis", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + lone76_c, lone76_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=lone76_sys, dev_root=lone76_dev + ) + lone76_spec = freetpu_cdi.build_cdi_spec(lone76_c, lone76_ctrl) + l76_all = next(d for d in lone76_spec["devices"] if d["name"] == "all") + l76_all["containerEdits"]["env"] = [ + "TPU_VISIBLE_CHIPS=0", + "TPU_VISIBLE_DEVICES=0,1", + ] + l76_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + lone76_spec, sysfs_root=lone76_sys, dev_root=lone76_dev + ) + self.assertTrue(any("TPU_VISIBLE" in err for err in l76_e)) + + # 3) 4-fn spec claiming chip-count=4 on 'all' + single-chiplet on pci-0000-00-04-0 + cross_spec = freetpu_cdi.build_cdi_spec(pf4_chips, pf4_ctrl, single_host_env=True) + cross_spec["annotations"].pop("freetpu.dev/tpu7x-pci-functions-per-chip", None) + c_p0 = next(d for d in cross_spec["devices"] if d["name"] == "pci-0000-00-04-0") + c_p0["annotations"]["freetpu.dev/allocation-unit"] = "single-chiplet" + c_p0["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + c_all = next(d for d in cross_spec["devices"] if d["name"] == "all") + c_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + cross_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + cross_spec, sysfs_root=pf4_sys, dev_root=pf4_dev + ) + self.assertTrue(len(cross_e) > 0) + + # 4) Custom alias 'worker-a' checks capacity annotations, and 5000-digit integer never throws ValueError. + cust_spec = freetpu_cdi.build_cdi_spec(pf4_chips, pf4_ctrl, single_host_env=True) + cust_slice = json.loads( + json.dumps(next(d for d in cust_spec["devices"] if d["name"] == "all")) + ) + cust_slice["name"] = "worker-a" + cust_slice["annotations"]["freetpu.dev/pci-function-count"] = "99" + cust_slice["annotations"]["freetpu.dev/capacity-complete"] = "banana" + cust_slice["annotations"]["freetpu.dev/chip-count"] = "9" * 5000 + cust_spec["devices"].append(cust_slice) + cust_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + cust_spec, sysfs_root=pf4_sys, dev_root=pf4_dev + ) + self.assertTrue(any("worker-a" in err and "pci-function-count" in err for err in cust_e)) + self.assertTrue(any("worker-a" in err and "capacity-complete" in err for err in cust_e)) + self.assertTrue(any("worker-a" in err and "chip-count" in err for err in cust_e)) + + # 5) High physical IDs 32765..32768 never emit >65535 masks and pass same-map validation. + high_map = {f"0000:00:0{4 + i:x}.0": 32765 + i for i in range(4)} + high_spec = freetpu_cdi.build_cdi_spec( + pf4_chips, pf4_ctrl, single_host_env=True, chip_id_map=high_map + ) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + high_spec, sysfs_root=pf4_sys, dev_root=pf4_dev, chip_id_map=high_map + ), + ([], []), + ) + + # 6) Mixed 1-fn Ironwood + paired v2-v3 _count_complete_chips without expected_fns_by_bdf -> (1, 0). + mixed_iw_v2 = [ + pf4_chips[0], + freetpu_cdi.DiscoveredChip( + index=1, + pci_bdf="0000:80:00.0", + vendor_id="0x1ae0", + device_id="0x0027", + generation="v2-v3", + model_name="TPU v2/v3", + driver="vfio-pci", + iommu_group="10", + vfio_mode="vfio-group", + vfio_container_path="/dev/vfio/10", + vfio_host_path=Path("/dev/vfio/10"), + ), + freetpu_cdi.DiscoveredChip( + index=2, + pci_bdf="0000:80:00.1", + vendor_id="0x1ae0", + device_id="0x0027", + generation="v2-v3", + model_name="TPU v2/v3", + driver="vfio-pci", + iommu_group="11", + vfio_mode="vfio-group", + vfio_container_path="/dev/vfio/11", + vfio_host_path=Path("/dev/vfio/11"), + ), + ] + mixed_phys = freetpu_cdi._map_physical_chip_indices(mixed_iw_v2) + self.assertEqual( + freetpu_cdi._count_complete_chips([mixed_iw_v2[0]], mixed_phys), + (1, 0), + ) + + # Round 5 regressions: + # 7) Standalone `validate --check-host --remove-if-stale` preserves hardware 2-fn spec after drop. + with mock.patch.object( + freetpu_cdi, "_read_host_boot_id", return_value="boot-4" + ): + self.assertEqual( + freetpu_cdi.main( + [ + "validate", + str(boot4_spec_path), + "--sysfs-root", + str(boot4_sys), + "--dev-root", + str(boot4_dev), + "--check-host", + "--remove-if-stale", + ] + ), + 0, + ) + self.assertTrue(boot4_spec_path.exists()) + + # 8) 3-tick `sync` loop: tick 1 discovers 0,0,1,1; tick 2 loses all VFIO & unlinks spec; + # tick 3 restores surviving 04.0+06.0 (chip_id=0,1) -> STILL retains 2-fn mode! + loop_sys, loop_dev = _make_mock_pci_vfio( + root / "loop_tpu7x_sync", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i // 2), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + loop_spec_path = root / "loop_sync_spec.json" + loop_sigs: dict[int, object] = {} + loop_sleeps = [0] + loop_mono = [0.0] + + def _loop_sig(signum: int, handler: object) -> None: + loop_sigs[signum] = handler + + def _loop_sleep(_secs: float) -> None: + loop_sleeps[0] += 1 + loop_mono[0] += 2.0 + if loop_sleeps[0] == 1: + for drop_b in ("0000:00:05.0", "0000:00:07.0"): + dp = loop_sys / "bus" / "pci" / "devices" / drop_b + if dp.is_dir() and not dp.is_symlink(): + shutil.rmtree(dp) + elif dp.exists() or dp.is_symlink(): + dp.unlink() + for g_rm in ("0", "1", "2", "3"): + (loop_dev / "vfio" / g_rm).unlink() + elif loop_sleeps[0] == 2: + for g_add in ("0", "2"): + (loop_dev / "vfio" / g_add).touch() + elif loop_sleeps[0] >= 3: + h = loop_sigs.get(freetpu_cdi.signal.SIGTERM) + if callable(h): + h(freetpu_cdi.signal.SIGTERM, None) + + with ( + mock.patch.object(freetpu_cdi.signal, "signal", side_effect=_loop_sig), + mock.patch.object(freetpu_cdi.time, "sleep", side_effect=_loop_sleep), + mock.patch.object( + freetpu_cdi.time, "monotonic", side_effect=lambda: loop_mono[0] + ), + ): + rc_loop, _ol, err_loop = _run_cli_inproc( + [ + "sync", + "--interval", + "1", + "--output", + str(loop_spec_path), + "--single-host-env", + "--sysfs-root", + str(loop_sys), + "--dev-root", + str(loop_dev), + ] + ) + self.assertEqual(rc_loop, 0, msg=err_loop) + loop_spec_final = json.loads(loop_spec_path.read_text(encoding="utf-8")) + self.assertEqual( + next(d for d in loop_spec_final["devices"] if d["name"] == "all")[ + "annotations" + ]["freetpu.dev/chip-count"], + "0", + ) + + # 9) Overlapping Ironwood logical IDs (0,1 -> 0..3) + v5e IDs (2,3 -> 2,3) withheld by unified table. + ov_iw_v5e_sys, ov_iw_v5e_dev = _make_mock_pci_vfio( + root / "overlap_iw_v5e_vis", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + "chip_id": "0", + }, + { + "bdf": "0000:00:05.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "0", + "chip_id": "1", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "1", + "chip_id": "2", + }, + { + "bdf": "0000:80:01.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "3", + "numa_node": "1", + "chip_id": "3", + }, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + ov_chips, _ = freetpu_cdi.discover_tpu_chips( + sysfs_root=ov_iw_v5e_sys, dev_root=ov_iw_v5e_dev + ) + ov_phys = freetpu_cdi._map_physical_chip_indices(ov_chips) + self.assertIsNone( + freetpu_cdi._resolve_verified_visibility_ordinals( + ov_chips[2:], ov_chips, ov_phys + ) + ) + + # 10) Unannotated legacy mixed-gen device history does NOT taint tpu7x into 2-fn mode. + leg_tpu7x_chips = [ + freetpu_cdi.DiscoveredChip( + index=i, + pci_bdf=f"0000:00:0{4 + i:x}.0", + vendor_id="0x1ae0", + device_id="0x0075", + generation="tpu7x", + model_name="TPU 7x", + driver="vfio-pci", + iommu_group=str(i), + vfio_mode="vfio-group", + vfio_container_path=f"/dev/vfio/{i}", + vfio_host_path=Path(f"/dev/vfio/{i}"), + pcie_root="0000:00", + numa_node=0, + ) + for i in range(2) + ] + [ + freetpu_cdi.DiscoveredChip( + index=2 + j, + pci_bdf=f"0000:80:0{j}.0", + vendor_id="0x1ae0", + device_id="0x0063", + generation="v5e", + model_name="TPU v5e", + driver="vfio-pci", + iommu_group=str(2 + j), + vfio_mode="vfio-group", + vfio_container_path=f"/dev/vfio/{2 + j}", + vfio_host_path=Path(f"/dev/vfio/{2 + j}"), + pcie_root="0000:80", + numa_node=1, + ) + for j in range(2) + ] + legacy_mix_spec = freetpu_cdi.build_cdi_spec( + leg_tpu7x_chips, one_dev / "vfio" / "vfio" + ) + legacy_mix_spec["annotations"].pop("freetpu.dev/observed-bdf-generations", None) + legacy_mix_spec["annotations"]["freetpu.dev/observed-domain-bdfs"] = ( + "numa|0|0000:00=0000:00:04.0,0000:00:05.0;unplaced||=0000:80:00.0" + ) + self.assertFalse( + freetpu_cdi._extract_observed_tpu7x_two_fn_from_spec(legacy_mix_spec) + ) + self.assertEqual( + freetpu_cdi._resolve_tpu7x_pci_functions_per_chip( + leg_tpu7x_chips, + observed_domain_bdfs={ + ("numa", 0, "0000:00"): {"0000:00:04.0", "0000:00:05.0"}, + ("numa", 1, "0000:80"): {"0000:80:00.0", "0000:80:01.0"}, + freetpu_cdi._UNPLACED_OBSERVED_DOMAIN_KEY: {"0000:80:00.0"}, + }, + observed_bdf_generations={"0000:80:00.0": "v5e"}, + ), + 1, + ) + + # 11) Global CSP + bounds + forced-partner + Unicode/5000-digit + TPU_VISIBLE_CHIPS=32768 regressions: + # 11a) Overlapping selectors on {04.0, 05.0} claiming 1 complete vs 0 complete/2 incomplete -> rejected. + ovl_spec = freetpu_cdi.build_cdi_spec(one_c, one_ctrl) + base_node = json.loads( + json.dumps( + next( + d for d in ovl_spec["devices"] if d["name"] == "pci-0000-00-04-0" + ) + ) + ) + g_nodes = [ + {"path": f"/dev/vfio/{i}", "hostPath": str(one_dev / "vfio" / str(i))} + for i in range(2) + ] + sel_a = json.loads(json.dumps(base_node)) + sel_a["name"] = "slice-a" + sel_a["containerEdits"]["deviceNodes"] = list(g_nodes) + sel_a["annotations"].pop("freetpu.dev/allocation-unit", None) + sel_a["annotations"].pop("freetpu.dev/pci-bdf", None) + sel_a["annotations"]["freetpu.dev/pci-bdfs"] = "0000:00:04.0,0000:00:05.0" + sel_a["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + sel_a["annotations"]["freetpu.dev/chip-count"] = "1" + sel_a["annotations"]["freetpu.dev/capacity-complete"] = "true" + sel_a["annotations"]["freetpu.dev/incomplete-pci-functions"] = "0" + sel_b = json.loads(json.dumps(sel_a)) + sel_b["name"] = "slice-b" + sel_b["annotations"]["freetpu.dev/chip-count"] = "0" + sel_b["annotations"]["freetpu.dev/capacity-complete"] = "false" + sel_b["annotations"]["freetpu.dev/incomplete-pci-functions"] = "2" + for d_item in ovl_spec["devices"]: + d_item["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + ovl_spec["devices"].extend([sel_a, sel_b]) + ovl_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + ovl_spec, sysfs_root=one_sys, dev_root=one_dev + ) + self.assertTrue(len(ovl_e) > 0) + + # 11b) Forced slot pair split: {04.0, 05.0} over 0x0076 (.0/.1 on 04 and 05) claiming chip-count=1 -> rejected. + f76_split_spec = freetpu_cdi.build_cdi_spec(f76_c, f76_ctrl) + f76_split_sel = json.loads(json.dumps(sel_a)) + f76_split_sel["containerEdits"]["deviceNodes"] = [ + {"path": "/dev/vfio/0", "hostPath": str(f76_dev / "vfio" / "0")}, + {"path": "/dev/vfio/2", "hostPath": str(f76_dev / "vfio" / "2")}, + ] + f76_split_sel["annotations"].pop("freetpu.dev/observed-domain-bdfs", None) + f76_split_spec["devices"].append(f76_split_sel) + f76_sp_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + f76_split_spec, sysfs_root=f76_sys, dev_root=f76_dev + ) + self.assertTrue(len(f76_sp_e) > 0) + + # 11c) Cross-root 3+1 split on 4x 1-fn 0x0075 claiming tpu7x-8 bounds -> rejected by _is_supported_all_domain_counts. + split31_sys, split31_dev = _make_mock_pci_vfio( + root / "split_3_1_tpu7x", + devices=[ + { + "bdf": f"0000:{'00' if i < 3 else '80'}:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0" if i < 3 else "1", + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + s31_c, s31_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=split31_sys, dev_root=split31_dev + ) + s31_spec = freetpu_cdi.build_cdi_spec(s31_c, s31_ctrl, single_host_env=True) + s31_all = next(d for d in s31_spec["devices"] if d["name"] == "all") + s31_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + s31_all["containerEdits"]["env"] = [ + "TPU_ACCELERATOR_TYPE=tpu7x-8", + "TPU_CHIPS_PER_HOST_BOUNDS=2,2,1", + "TPU_SKIP_MDS_QUERY=true", + ] + s31_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + s31_spec, sysfs_root=split31_sys, dev_root=split31_dev + ) + self.assertTrue(any("tpu7x-8" in err or "BOUNDS" in err for err in s31_e)) + + # 11d) 5000-digit range endpoint + Unicode '²' numa-node + TPU_VISIBLE_CHIPS=32768 -> clean error, no exception. + dos_spec = json.loads(json.dumps(one_spec)) + dos_spec["annotations"]["freetpu.dev/observed-domain-bdfs"] = "numa|²|0000:00=0000:00:04.0" + dos_slice = json.loads(json.dumps(next(d for d in dos_spec["devices"] if d["name"] == "all"))) + dos_slice["name"] = "0-" + ("9" * 5000) + dos_slice["annotations"]["freetpu.dev/numa-node"] = "²" + dos_slice["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + dos_spec["devices"].append(dos_slice) + dos_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + dos_spec, sysfs_root=one_sys, dev_root=one_dev + ) + self.assertTrue(len(dos_e) > 0) + + hi_vis_spec = freetpu_cdi.build_cdi_spec(one_c, one_ctrl) + hv_all = next(d for d in hi_vis_spec["devices"] if d["name"] == "all") + hv_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + hv_all["annotations"]["freetpu.dev/chip-count"] = "1" + hv_all["containerEdits"]["env"] = ["TPU_VISIBLE_CHIPS=32768"] + hv_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + hi_vis_spec, sysfs_root=one_sys, dev_root=one_dev + ) + self.assertTrue(any("65535" in err for err in hv_e)) + + # Round 6 regressions: + # R6-3: Sync must NOT promote chip-id-map 2-fn pairing into permanent hardware history. + r6_sys, r6_dev = _make_mock_pci_vfio( + root / "r6_sync_no_promote", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(2) + ], + create_vfio_nodes=["0", "1"], + ) + r6_spec_p = root / "r6_sync.json" + r6_obs = freetpu_cdi._ObservedDomainBdfs() + ok1, _ = freetpu_cdi.reconcile_cdi_spec( + r6_spec_p, + sysfs_root=r6_sys, + dev_root=r6_dev, + chip_id_map={"0000:00:04.0": 0, "0000:00:05.0": 0}, + observed_domain_bdfs=r6_obs, + ) + self.assertTrue(ok1) + self.assertFalse(r6_obs.tpu7x_two_fn) + ok2, _ = freetpu_cdi.reconcile_cdi_spec( + r6_spec_p, + sysfs_root=r6_sys, + dev_root=r6_dev, + chip_id_map={"0000:00:04.0": 0, "0000:00:05.0": 0}, + observed_domain_bdfs=r6_obs, + ) + self.assertTrue(ok2) + s2_ann = json.loads(r6_spec_p.read_text(encoding="utf-8"))["annotations"] + self.assertEqual(s2_ann.get("freetpu.dev/tpu7x-layout-source"), "chip-id-map") + ok3, _ = freetpu_cdi.reconcile_cdi_spec( + r6_spec_p, + sysfs_root=r6_sys, + dev_root=r6_dev, + chip_id_map={"0000:00:04.0": 0, "0000:00:05.0": 1}, + observed_domain_bdfs=r6_obs, + ) + self.assertTrue(ok3) + s3_all = next( + d + for d in json.loads(r6_spec_p.read_text(encoding="utf-8"))["devices"] + if d["name"] == "all" + ) + self.assertEqual(s3_all["annotations"]["freetpu.dev/chip-count"], "2") + + # R6-4: Cross-boot or stripped-boot-id 2-fn history cannot validate stale single-chiplet on new boot. + one1_sys, one1_dev = _make_mock_pci_vfio( + root / "r6_one_0075", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + one1_c, one1_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=one1_sys, dev_root=one1_dev + ) + stale_twofn_spec = freetpu_cdi.build_cdi_spec(one1_c, one1_ctrl) + stale_twofn_spec["annotations"]["freetpu.dev/tpu7x-pci-functions-per-chip"] = "2" + stale_twofn_spec["annotations"]["freetpu.dev/tpu7x-layout-source"] = "hardware" + stale_twofn_spec["annotations"]["freetpu.dev/observed-domain-bdfs"] = ( + "numa|0|0000:00=0000:00:04.0,0000:00:04.1" + ) + stale_twofn_spec["annotations"]["freetpu.dev/observed-bdf-generations"] = ( + "0000:00:04.0=tpu7x;0000:00:04.1=tpu7x" + ) + stale_p0 = next( + d for d in stale_twofn_spec["devices"] if d["name"] == "pci-0000-00-04-0" + ) + stale_p0["annotations"]["freetpu.dev/allocation-unit"] = "single-chiplet" + with mock.patch.object( + freetpu_cdi, "_read_host_boot_id", return_value="boot-new" + ): + old_boot_s = json.loads(json.dumps(stale_twofn_spec)) + old_boot_s["annotations"]["freetpu.dev/boot-id"] = "boot-old" + ob_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + old_boot_s, sysfs_root=one1_sys, dev_root=one1_dev + ) + self.assertTrue(len(ob_e) > 0) + nob_s = json.loads(json.dumps(stale_twofn_spec)) + nob_s["annotations"].pop("freetpu.dev/boot-id", None) + self.assertFalse( + freetpu_cdi._spec_has_same_boot_hw_tpu7x_two_fn( + nob_s, one1_c, {("numa", 0, "0000:00"): {"0000:00:04.0", "0000:00:04.1"}} + ) + ) + nb_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + nob_s, sysfs_root=one1_sys, dev_root=one1_dev + ) + self.assertTrue(len(nb_e) > 0) + + # R6-5: Surviving single v5e with missing historical endpoint preserves single-chip bounds. + v5e1_sys, v5e1_dev = _make_mock_pci_vfio( + root / "r6_v5e_deg1", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + v5e1_c, v5e1_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=v5e1_sys, dev_root=v5e1_dev + ) + v5e1_spec = freetpu_cdi.build_cdi_spec( + v5e1_c, + v5e1_ctrl, + single_host_env=True, + observed_domain_bdfs={("numa", 0, "0000:00"): {"0000:00:04.0", "0000:00:05.0"}}, + ) + self.assertEqual( + freetpu_cdi._verify_spec_against_host_detailed( + v5e1_spec, sysfs_root=v5e1_sys, dev_root=v5e1_dev + ), + ([], []), + ) + + # R6-6: Bucket factorization & >4096 symmetry solver catch overlapping {A,B} vs {A,C} conflicts. + mix8_sys, mix8_dev = _make_mock_pci_vfio( + root / "r6_mix8_iw_v2", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(8) + ] + + [ + { + "bdf": f"0000:80:0{j:x}.0", + "vendor": "0x1ae0", + "device": "0x0027", + "driver": "vfio-pci", + "iommu_group": str(8 + j), + "numa_node": "1", + } + for j in range(4) + ], + create_vfio_nodes=[str(k) for k in range(12)], + ) + m8_c, m8_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=mix8_sys, dev_root=mix8_dev + ) + m8_map = {f"0000:00:0{4 + i:x}.0": i // 2 for i in range(8)} + m8_map.update({f"0000:80:0{j:x}.0": 4 + (j // 2) for j in range(4)}) + m8_spec = freetpu_cdi.build_cdi_spec(m8_c, m8_ctrl, chip_id_map=m8_map) + s_ab = { + "name": "pair-ab", + "annotations": { + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:05.0", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/chip-count": "1", + "freetpu.dev/capacity-complete": "true", + "freetpu.dev/incomplete-pci-functions": "0", + }, + "containerEdits": { + "deviceNodes": [ + {"path": f"/dev/vfio/{g}", "hostPath": str(mix8_dev / "vfio" / str(g))} + for g in (0, 1) + ] + }, + } + s_ac = { + "name": "pair-ac", + "annotations": { + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:06.0", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/chip-count": "1", + "freetpu.dev/capacity-complete": "true", + "freetpu.dev/incomplete-pci-functions": "0", + }, + "containerEdits": { + "deviceNodes": [ + {"path": f"/dev/vfio/{g}", "hostPath": str(mix8_dev / "vfio" / str(g))} + for g in (0, 2) + ] + }, + } + m8_spec["devices"].extend([s_ab, s_ac]) + m8_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + m8_spec, sysfs_root=mix8_sys, dev_root=mix8_dev + ) + self.assertTrue(any("conflicting chip-pairing" in err for err in m8_e)) + + # 10 free functions in a SINGLE bucket (> 4096 matchings) also solved symmetrically. + ten_sys, ten_dev = _make_mock_pci_vfio( + root / "r6_ten_iw_bucket", + devices=[ + { + "bdf": f"0000:00:{4 + i:02x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(10) + ], + create_vfio_nodes=[str(k) for k in range(10)], + ) + t10_c, t10_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=ten_sys, dev_root=ten_dev + ) + t10_spec = freetpu_cdi.build_cdi_spec(t10_c, t10_ctrl) + for sel in (s_ab, s_ac): + sel_c = json.loads(json.dumps(sel)) + for dn in sel_c["containerEdits"]["deviceNodes"]: + dn["hostPath"] = str(ten_dev / "vfio" / Path(dn["path"]).name) + t10_spec["devices"].append(sel_c) + t10_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + t10_spec, sysfs_root=ten_sys, dev_root=ten_dev + ) + self.assertTrue(any("conflicting chip-pairing" in err for err in t10_e)) + + # R6-7: Cross-selector visible ordinal disagreement (4-7 vs 8-11) on same BDFs -> rejected. + r67_sys, r67_dev = _make_mock_pci_vfio( + root / "r6_ord_conflict", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(4 + i), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + r67_c, r67_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=r67_sys, dev_root=r67_dev + ) + r67_spec = freetpu_cdi.build_cdi_spec(r67_c, r67_ctrl, single_host_env=True) + d47 = next(d for d in r67_spec["devices"] if d["name"] == "4-7") + d47["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + d47["containerEdits"]["env"] = [ + "TPU_VISIBLE_CHIPS=8,9,10,11", + "TPU_VISIBLE_DEVICES=16,17,18,19,20,21,22,23", + ] + r67_e, _ = freetpu_cdi._verify_spec_against_host_detailed( + r67_spec, sysfs_root=r67_sys, dev_root=r67_dev + ) + self.assertTrue(len(r67_e) > 0) + + # R6-8: Orphaned 0x0076 chip_id=1 protects BOTH {0,1} and {2,3} from colliding v6e masks. + orph_mix_sys, orph_mix_dev = _make_mock_pci_vfio( + root / "r6_orph_0076_vis", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + "chip_id": "1", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "1", + "chip_id": "2", + }, + { + "bdf": "0000:80:01.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "1", + "chip_id": "3", + }, + ], + create_vfio_nodes=["0", "1", "2"], + ) + om_c, _ = freetpu_cdi.discover_tpu_chips( + sysfs_root=orph_mix_sys, dev_root=orph_mix_dev + ) + om_phys = freetpu_cdi._map_physical_chip_indices(om_c) + self.assertIsNone( + freetpu_cdi._resolve_verified_visibility_ordinals(om_c[1:], om_c, om_phys) + ) + + # R6-9: Legacy mixed-gen spec listing 'tpu7x,v5e' with departed v5e preserves 4x1-fn Ironwood. + lmix_sys, lmix_dev = _make_mock_pci_vfio( + root / "r6_leg_mixed_tpu7x_v5e", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + lmix_c, lmix_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=lmix_sys, dev_root=lmix_dev + ) + self.assertEqual( + freetpu_cdi._resolve_tpu7x_pci_functions_per_chip( + lmix_c, + observed_domain_bdfs={ + ("numa", 0, "0000:00"): { + "0000:00:04.0", + "0000:00:05.0", + "0000:00:06.0", + "0000:00:07.0", + "0000:00:08.0", + } + }, + observed_bdf_generations={}, + spec_generations=["tpu7x", "v5e"], + ), + 1, + ) + + # R6-10: CDI rejects out-of-range and non-ASCII chip IDs symmetrically with exporter. + bad_id_sys, bad_id_dev = _make_mock_pci_vfio( + root / "r6_bad_id_sys", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "chip_id": "65536", + } + ], + create_vfio_nodes=["0"], + ) + bi_c, _ = freetpu_cdi.discover_tpu_chips(sysfs_root=bad_id_sys, dev_root=bad_id_dev) + self.assertIsNone(bi_c[0].runtime_chip_id) + for bad_map in ('{"0000:00:04.0": "12"}', '{"0000:00:04.0": 65536}'): + with self.assertRaises(ValueError): + freetpu_cdi._load_chip_id_map(bad_map) + + # R7-1: Upgrading legacy `origin/main` 4 x 1-fn 0x0075 spec promotes to 1-fn (chip-count=4). + upg_sys, upg_dev = _make_mock_pci_vfio( + root / "r7_upgrade_legacy_4x1fn", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + upg_spec_path = root / "r7_upgrade_legacy.json" + legacy_1fn_spec = { + "cdiVersion": "0.6.0", + "kind": "freetpu.dev/tpu", + "annotations": {"freetpu.dev/generated-by": "freetpu-cdi"}, + "containerEdits": {}, + "devices": [ + { + "name": f"pci-0000-00-0{4 + i:x}-0", + "annotations": { + "freetpu.dev/allocation-unit": "single-chiplet", + "freetpu.dev/pci-bdf": f"0000:00:0{4 + i:x}.0", + "freetpu.dev/generation": "tpu7x", + }, + "containerEdits": {}, + } + for i in range(4) + ] + + [ + { + "name": "all", + "annotations": { + "freetpu.dev/allocation-unit": "all-devices", + "freetpu.dev/chip-count": "0", + "freetpu.dev/pci-function-count": "4", + "freetpu.dev/incomplete-pci-functions": "4", + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:05.0,0000:00:06.0,0000:00:07.0", + "freetpu.dev/generations": "tpu7x", + }, + "containerEdits": {}, + } + ], + } + upg_spec_path.write_text(json.dumps(legacy_1fn_spec), encoding="utf-8") + self.assertEqual( + freetpu_cdi.main( + [ + "generate", + "--output", + str(upg_spec_path), + "--sysfs-root", + str(upg_sys), + "--dev-root", + str(upg_dev), + ] + ), + 0, + ) + upgraded = json.loads(upg_spec_path.read_text(encoding="utf-8")) + self.assertEqual(upgraded["annotations"]["freetpu.dev/tpu7x-pci-functions-per-chip"], "1") + self.assertEqual( + next(d for d in upgraded["devices"] if d["name"] == "all")["annotations"][ + "freetpu.dev/chip-count" + ], + "4", + ) + + # R7-2: 0x0076 slot [8, missing] reserves {8, 9, 16, 17} so colocated v6e 9 withholds visibility. + miss_sib_sys, miss_sib_dev = _make_mock_pci_vfio( + root / "r7_missing_sib_id", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + "chip_id": "8", + }, + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "1", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": "2", + "chip_id": "9", + }, + ], + create_vfio_nodes=["0", "1", "2"], + ) + ms_c, ms_ctrl = freetpu_cdi.discover_tpu_chips( + sysfs_root=miss_sib_sys, dev_root=miss_sib_dev + ) + ms_phys = freetpu_cdi._map_physical_chip_indices(ms_c) + self.assertIsNone( + freetpu_cdi._resolve_verified_visibility_ordinals([ms_c[2]], ms_c, ms_phys) + ) + + # R7-3: Partially overlapping selectors ({A,B} vs {B,C}) with disjoint chip masks fail confirmed verification. + ov_sys, ov_dev = _make_mock_pci_vfio( + root / "r7_partial_overlap_sel", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(3) + ], + create_vfio_nodes=["0", "1", "2"], + ) + ov_c, ov_ctrl = freetpu_cdi.discover_tpu_chips(sysfs_root=ov_sys, dev_root=ov_dev) + ov_spec = freetpu_cdi.build_cdi_spec(ov_c, ov_ctrl) + ov_spec["devices"].extend( + [ + { + "name": "sel-ab", + "annotations": { + "freetpu.dev/allocation-unit": "slice", + "freetpu.dev/chip-count": "2", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:05.0", + "freetpu.dev/generations": "v6e", + }, + "containerEdits": { + "deviceNodes": [ + {"path": ov_c[0].vfio_container_path, "hostPath": str(ov_c[0].vfio_host_path)}, + {"path": ov_c[1].vfio_container_path, "hostPath": str(ov_c[1].vfio_host_path)}, + ], + "env": ["TPU_VISIBLE_CHIPS=0,1", "TPU_VISIBLE_DEVICES=0,1"], + }, + }, + { + "name": "sel-bc", + "annotations": { + "freetpu.dev/allocation-unit": "slice", + "freetpu.dev/chip-count": "2", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/pci-bdfs": "0000:00:05.0,0000:00:06.0", + "freetpu.dev/generations": "v6e", + }, + "containerEdits": { + "deviceNodes": [ + {"path": ov_c[1].vfio_container_path, "hostPath": str(ov_c[1].vfio_host_path)}, + {"path": ov_c[2].vfio_container_path, "hostPath": str(ov_c[2].vfio_host_path)}, + ], + "env": ["TPU_VISIBLE_CHIPS=2,3", "TPU_VISIBLE_DEVICES=2,3"], + }, + }, + ] + ) + ov_conf, _ov_unv = freetpu_cdi._verify_spec_against_host_detailed( + ov_spec, sysfs_root=ov_sys, dev_root=ov_dev + ) + self.assertTrue(any("conflicting visible ordinal assumptions" in e for e in ov_conf)) + + # R7-4: Legacy mixed-gen aggregate annotation ("tpu7x,v5e") survives generate & sync on same boot when v5e departs. + lmg_spec_path = root / "r7_legacy_mixed_gen.json" + lmg_spec_path.write_text( + json.dumps( + { + "cdiVersion": "0.6.0", + "kind": "freetpu.dev/tpu", + "annotations": { + "freetpu.dev/generated-by": "freetpu-cdi", + "freetpu.dev/boot-id": "boot-r7-4", + }, + "containerEdits": {}, + "devices": [ + { + "name": "all", + "annotations": { + "freetpu.dev/allocation-unit": "all-devices", + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:05.0,0000:00:06.0,0000:00:07.0,0000:00:08.0", + "freetpu.dev/generations": "tpu7x,v5e", + }, + "containerEdits": {}, + } + ], + } + ), + encoding="utf-8", + ) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-r7-4"): + self.assertEqual( + freetpu_cdi.main( + [ + "generate", + "--output", + str(lmg_spec_path), + "--sysfs-root", + str(lmix_sys), + "--dev-root", + str(lmix_dev), + ] + ), + 0, + ) + lmg_out1 = json.loads(lmg_spec_path.read_text(encoding="utf-8")) + self.assertEqual(lmg_out1["annotations"]["freetpu.dev/tpu7x-pci-functions-per-chip"], "1") + self.assertEqual( + next(d for d in lmg_out1["devices"] if d["name"] == "all")["annotations"][ + "freetpu.dev/chip-count" + ], + "4", + ) + self.assertEqual(lmg_out1["annotations"].get("freetpu.dev/observed-generations"), "tpu7x,v5e") + ok_lmg_sync, _ = freetpu_cdi.reconcile_cdi_spec( + lmg_spec_path, sysfs_root=lmix_sys, dev_root=lmix_dev + ) + self.assertTrue(ok_lmg_sync) + lmg_out2 = json.loads(lmg_spec_path.read_text(encoding="utf-8")) + self.assertEqual(lmg_out2["annotations"]["freetpu.dev/tpu7x-pci-functions-per-chip"], "1") + self.assertEqual( + next(d for d in lmg_out2["devices"] if d["name"] == "all")["annotations"][ + "freetpu.dev/chip-count" + ], + "4", + ) + + # R7-5: Unreadable host boot_id rejects stale spec carrying explicit old boot-id. + stale_hw_spec = { + "annotations": { + "freetpu.dev/tpu7x-pci-functions-per-chip": "2", + "freetpu.dev/tpu7x-layout-source": "hardware", + "freetpu.dev/boot-id": "boot-old", + } + } + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + self.assertFalse( + freetpu_cdi._spec_has_same_boot_hw_tpu7x_two_fn( + stale_hw_spec, + surv_chips, + {("pcie", None, "0000:00"): {"0000:00:04.0", "0000:00:05.0"}}, + ) + ) + self.assertFalse( + freetpu_cdi._spec_matches_current_boot( + stale_hw_spec, require_explicit_when_available=True + ) + ) + + # R7-6: Host validation accepts valid legacy v2-v3 (0x0027) mask CHIPS=4 DEVICES=8,9. + v2_sys, v2_dev = _make_mock_pci_vfio( + root / "r7_v2_mask_valid", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0027", + "driver": "vfio-pci", + "iommu_group": "0", + "chip_id": "4", + }, + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0027", + "driver": "vfio-pci", + "iommu_group": "1", + "chip_id": "4", + }, + ], + create_vfio_nodes=["0", "1"], + ) + v2_c, v2_ctrl = freetpu_cdi.discover_tpu_chips(sysfs_root=v2_sys, dev_root=v2_dev) + v2_phys = freetpu_cdi._map_physical_chip_indices(v2_c) + v2_vis = freetpu_cdi._resolve_verified_visibility_ordinals(v2_c, v2_c, v2_phys) + self.assertEqual(v2_vis, ([4], [8, 9])) + v2_spec = freetpu_cdi.build_cdi_spec(v2_c, v2_ctrl, single_host_env=False) + v2_all_ann = next(d for d in v2_spec["devices"] if d["name"] == "all")["annotations"] + v2_spec["devices"].append( + { + "name": "sel-v2", + "annotations": { + "freetpu.dev/allocation-unit": "slice", + "freetpu.dev/chip-count": "1", + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:04.1", + "freetpu.dev/generations": "v2-v3", + "freetpu.dev/vfio-devnums": v2_all_ann["freetpu.dev/vfio-devnums"], + }, + "containerEdits": { + "deviceNodes": [ + {"path": v2_c[0].vfio_container_path, "hostPath": str(v2_c[0].vfio_host_path)}, + {"path": v2_c[1].vfio_container_path, "hostPath": str(v2_c[1].vfio_host_path)}, + ], + "env": ["TPU_VISIBLE_CHIPS=4", "TPU_VISIBLE_DEVICES=8,9"], + }, + } + ) + self.assertEqual( + freetpu_cdi.verify_spec_against_host(v2_spec, sysfs_root=v2_sys, dev_root=v2_dev), + [], + ) + + # R7-7: 10 x 0x0075 + custom slice + pci-* singletons collapses cleanly under symmetry + bounded DFS. + ten_sys, ten_dev = _make_mock_pci_vfio( + root / "r7_ten_0075", + devices=[ + { + "bdf": f"0000:00:{0x10 + i:02x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(10) + ], + create_vfio_nodes=[str(i) for i in range(10)], + ) + ten_c, ten_ctrl = freetpu_cdi.discover_tpu_chips(sysfs_root=ten_sys, dev_root=ten_dev) + ten_map = {c.pci_bdf: idx // 2 for idx, c in enumerate(ten_c)} + ten_spec = freetpu_cdi.build_cdi_spec(ten_c, ten_ctrl, chip_id_map=ten_map) + # Inject a partial-bucket 4-fn (2-chip) selector + keep all 10 pci-* singletons so >4096 _bt runs. + ten_root_dn = freetpu_cdi._parse_vfio_devnums_annotation( + next(d for d in ten_spec["devices"] if d["name"] == "all")["annotations"][ + "freetpu.dev/vfio-devnums" + ] + ) + ten_spec["devices"].append( + { + "name": "sel-ten-4", + "annotations": { + "freetpu.dev/allocation-unit": "slice", + "freetpu.dev/chip-count": "2", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/pci-bdfs": ",".join(c.pci_bdf for c in ten_c[:4]), + "freetpu.dev/generations": "tpu7x", + "freetpu.dev/vfio-devnums": freetpu_cdi._format_vfio_devnums( + [(c.vfio_container_path, ten_root_dn[c.vfio_container_path]) for c in ten_c[:4]] + ), + }, + "containerEdits": { + "deviceNodes": [ + {"path": c.vfio_container_path, "hostPath": str(c.vfio_host_path)} + for c in ten_c[:4] + ] + }, + } + ) + ten_conf, _ten_unv = freetpu_cdi._verify_spec_against_host_detailed( + ten_spec, sysfs_root=ten_sys, dev_root=ten_dev + ) + self.assertEqual(ten_conf, []) + # Multi-component host (6 NUMA domains x 2 0x0075 + partial slices + 'all') avoids Cartesian blowup. + mc_sys, mc_dev = _make_mock_pci_vfio( + root / "r7_multi_comp_dfs", + devices=[ + { + "bdf": f"0000:{0x10 * d:02x}:0{f + 4:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(d * 2 + f), + "numa_node": str(d), + } + for d in range(6) + for f in range(2) + ], + create_vfio_nodes=[str(i) for i in range(12)], + ) + mc_c, mc_ctrl = freetpu_cdi.discover_tpu_chips(sysfs_root=mc_sys, dev_root=mc_dev) + mc_map = {c.pci_bdf: idx // 2 for idx, c in enumerate(mc_c)} + mc_spec = freetpu_cdi.build_cdi_spec(mc_c, mc_ctrl, chip_id_map=mc_map) + mc_conf, _mc_unv = freetpu_cdi._verify_spec_against_host_detailed( + mc_spec, sysfs_root=mc_sys, dev_root=mc_dev + ) + self.assertEqual(mc_conf, []) + + # R8-3: Over-overlapping partial selectors ({A,B} {0,1} vs {B,C} {0,1}) fail confirmed check. + over_ov_spec = freetpu_cdi.build_cdi_spec(ov_c, ov_ctrl) + over_ov_spec["devices"].extend( + [ + { + "name": "over-ab", + "annotations": { + "freetpu.dev/allocation-unit": "slice", + "freetpu.dev/chip-count": "2", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/pci-bdfs": "0000:00:04.0,0000:00:05.0", + "freetpu.dev/generations": "v6e", + }, + "containerEdits": { + "deviceNodes": [ + {"path": ov_c[0].vfio_container_path, "hostPath": str(ov_c[0].vfio_host_path)}, + {"path": ov_c[1].vfio_container_path, "hostPath": str(ov_c[1].vfio_host_path)}, + ], + "env": ["TPU_VISIBLE_CHIPS=0,1", "TPU_VISIBLE_DEVICES=0,1"], + }, + }, + { + "name": "over-bc", + "annotations": { + "freetpu.dev/allocation-unit": "slice", + "freetpu.dev/chip-count": "2", + "freetpu.dev/chip-id-source": "chip-id-map", + "freetpu.dev/pci-bdfs": "0000:00:05.0,0000:00:06.0", + "freetpu.dev/generations": "v6e", + }, + "containerEdits": { + "deviceNodes": [ + {"path": ov_c[1].vfio_container_path, "hostPath": str(ov_c[1].vfio_host_path)}, + {"path": ov_c[2].vfio_container_path, "hostPath": str(ov_c[2].vfio_host_path)}, + ], + "env": ["TPU_VISIBLE_CHIPS=0,1", "TPU_VISIBLE_DEVICES=0,1"], + }, + }, + ] + ) + over_conf, _over_unv = freetpu_cdi._verify_spec_against_host_detailed( + over_ov_spec, sysfs_root=ov_sys, dev_root=ov_dev + ) + self.assertTrue(any("conflicting visible ordinal assumptions" in e for e in over_conf)) + + # R8-5: `validate --check-host` fails non-zero when spec carries explicit boot-id and host boot_id is unreadable. + unr_boot_spec = freetpu_cdi.build_cdi_spec(ov_c, ov_ctrl) + unr_boot_spec["annotations"]["freetpu.dev/boot-id"] = "boot-old" + unr_boot_path = root / "r8_unr_boot.json" + unr_boot_path.write_text(json.dumps(unr_boot_spec), encoding="utf-8") + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + rc_unr, _out_u, err_u = _run_cli_inproc( + [ + "validate", + str(unr_boot_path), + "--sysfs-root", + str(ov_sys), + "--dev-root", + str(ov_dev), + "--check-host", + ] + ) + self.assertNotEqual(rc_unr, 0) + self.assertIn("boot-old", err_u) + + # R8-7: CSP budget exhaustion (15 domains x 2 fns = 32768 global states > 20000) reports unverifiable, not confirmed. + exh_sys, exh_dev = _make_mock_pci_vfio( + root / "r8_csp_budget_15d", + devices=[ + { + "bdf": f"0000:{0x10 + d:02x}:0{f + 4:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(d * 2 + f), + "numa_node": str(d), + } + for d in range(15) + for f in range(2) + ], + create_vfio_nodes=[str(i) for i in range(30)], + ) + exh_c, exh_ctrl = freetpu_cdi.discover_tpu_chips(sysfs_root=exh_sys, dev_root=exh_dev) + exh_map = {c.pci_bdf: idx // 2 for idx, c in enumerate(exh_c)} + exh_spec = freetpu_cdi.build_cdi_spec(exh_c, exh_ctrl, chip_id_map=exh_map) + # Keep `all` and `pci-*` (removing per-domain slices so global product = 2^15 > 20000). + exh_spec["devices"] = [ + d + for d in exh_spec["devices"] + if d["name"].startswith("pci-") or d["name"] == "all" + ] + self.assertEqual( + freetpu_cdi.verify_spec_against_host( + exh_spec, sysfs_root=exh_sys, dev_root=exh_dev, chip_id_map=exh_map + ), + [], + ) + exh_conf, exh_unv = freetpu_cdi._verify_spec_against_host_detailed( + exh_spec, sysfs_root=exh_sys, dev_root=exh_dev + ) + self.assertEqual(exh_conf, []) + self.assertTrue(any("exceeded search budget" in u for u in exh_unv)) + + # R8-sameboot: 4 separate-slot 0x0075 functions (0,0,1,1) -> sync -> strip chip_ids -> standalone validate passes. + sb4_sys, sb4_dev = _make_mock_pci_vfio( + root / "r8_sameboot_strip_cids", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i // 2), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + sb4_spec_path = root / "r8_sb4_sync.json" + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-sb4"): + ok_sb1, _ = freetpu_cdi.reconcile_cdi_spec( + sb4_spec_path, sysfs_root=sb4_sys, dev_root=sb4_dev + ) + self.assertTrue(ok_sb1) + for i in range(4): + cid_f = sb4_sys / "bus" / "pci" / "devices" / f"0000:00:0{4 + i:x}.0" / "chip_id" + cid_f.unlink() + ok_sb2, _ = freetpu_cdi.reconcile_cdi_spec( + sb4_spec_path, sysfs_root=sb4_sys, dev_root=sb4_dev + ) + self.assertTrue(ok_sb2) + sb4_conf, sb4_unv = freetpu_cdi._verify_spec_against_host_detailed( + json.loads(sb4_spec_path.read_text(encoding="utf-8")), + sysfs_root=sb4_sys, + dev_root=sb4_dev, + ) + self.assertEqual(sb4_conf, []) + self.assertEqual(sb4_unv, []) + + # R9-1: forged/missing `boot-id` + stripped live sysfs `chip_id`s on 4 separate-slot + # `0x0075` functions must NOT pass standalone `validate --check-host` as 2-fn. + r9_1_sys, r9_1_dev = _make_mock_pci_vfio( + root / "r9_1_missing_boot_id", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i // 2), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + r9_1_chips, r9_1_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r9_1_sys, dev_root=r9_1_dev + ) + r9_1_spec = freetpu_cdi.build_cdi_spec( + r9_1_chips, r9_1_cn, single_host_env=True + ) + self.assertEqual( + r9_1_spec["annotations"].get("freetpu.dev/tpu7x-pci-functions-per-chip"), + "2", + ) + r9_1_spec["annotations"].pop("freetpu.dev/boot-id", None) + for i in range(4): + ( + r9_1_sys / "bus" / "pci" / "devices" / f"0000:00:0{4 + i:x}.0" / "chip_id" + ).unlink() + r9_1_path = root / "r9_1_forged.json" + r9_1_path.write_text(json.dumps(r9_1_spec, indent=2), encoding="utf-8") + self.assertNotEqual( + freetpu_cdi.verify_spec_against_host( + r9_1_spec, sysfs_root=r9_1_sys, dev_root=r9_1_dev + ), + [], + ) + self.assertNotEqual( + freetpu_cdi.main( + [ + "validate", + str(r9_1_path), + "--sysfs-root", + str(r9_1_sys), + "--dev-root", + str(r9_1_dev), + "--check-host", + ] + ), + 0, + ) + + # R9-2: 3 proved 2-fn `0x0076` packages A={04.0,04.1}, B={05.0,05.1}, C={06.0,06.1} + # with selectors {A,B} and {B,C} both claiming CHIPS=0,1 must fail pairwise + # partial-overlap package bounds (B can hold at most 1 complete 2-fn package). + r9_2_sys, r9_2_dev = _make_mock_pci_vfio( + root / "r9_2_two_fn_overlap", + devices=[ + { + "bdf": f"0000:00:0{4 + pkg:x}.{fn}", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": str(pkg * 2 + fn), + "numa_node": "0", + "chip_id": str(pkg), + } + for pkg in range(3) + for fn in range(2) + ], + create_vfio_nodes=[str(i) for i in range(6)], + ) + r9_2_chips, r9_2_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r9_2_sys, dev_root=r9_2_dev + ) + r9_2_spec = freetpu_cdi.build_cdi_spec(r9_2_chips, r9_2_cn, single_host_env=True) + r9_2_by_bdf_nodes = {} + for d in r9_2_spec["devices"]: + if d["name"].startswith("pci-"): + r9_2_by_bdf_nodes[d["annotations"]["freetpu.dev/pci-bdf"]] = d[ + "containerEdits" + ]["deviceNodes"] + for sel_name, bdf_list in ( + ("sel-ab", ["0000:00:04.0", "0000:00:04.1", "0000:00:05.0", "0000:00:05.1"]), + ("sel-bc", ["0000:00:05.0", "0000:00:05.1", "0000:00:06.0", "0000:00:06.1"]), + ): + r9_2_spec["devices"].append( + { + "name": sel_name, + "annotations": { + "freetpu.dev/chip-count": "2", + "freetpu.dev/pci-bdfs": ",".join(bdf_list), + "freetpu.dev/chiplets-per-pkg": "2", + }, + "containerEdits": { + "deviceNodes": [ + node + for b in bdf_list + for node in r9_2_by_bdf_nodes[b] + ], + "env": [ + "TPU_VISIBLE_CHIPS=0,1", + "TPU_VISIBLE_DEVICES=0,1,2,3", + ], + }, + } + ) + r9_2_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r9_2_spec, sysfs_root=r9_2_sys, dev_root=r9_2_dev + ) + self.assertTrue( + any( + "conflicting visible ordinal assumptions between selectors 'sel-ab' and 'sel-bc'" + in e + for e in r9_2_conf + ), + r9_2_conf, + ) + + # R9-3: 3 v6e chips A,B,C with multi-selector global impossibilities: + # 1) 4 distinct ordinals AB->{0,1}, BC->{0,2}, AC->{0,3} across 3 chips; + # 2) 3 ordinals AB->{0,1}, BC->{0,1}, AC->{0,2} (Hall bottleneck on B). + r9_3_sys, r9_3_dev = _make_mock_pci_vfio( + root / "r9_3_kuhn_v6e", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(3) + ], + create_vfio_nodes=["0", "1", "2"], + ) + r9_3_chips, r9_3_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r9_3_sys, dev_root=r9_3_dev + ) + r9_3_base = freetpu_cdi.build_cdi_spec(r9_3_chips, r9_3_cn, single_host_env=True) + r9_3_nodes = { + d["annotations"]["freetpu.dev/pci-bdf"]: d["containerEdits"]["deviceNodes"] + for d in r9_3_base["devices"] + if d["name"].startswith("pci-") + } + for vis_triples in ( + (("sel-ab", ["0000:00:04.0", "0000:00:05.0"], "0,1"), ("sel-bc", ["0000:00:05.0", "0000:00:06.0"], "0,2"), ("sel-ac", ["0000:00:04.0", "0000:00:06.0"], "0,3")), + (("sel-ab", ["0000:00:04.0", "0000:00:05.0"], "0,1"), ("sel-bc", ["0000:00:05.0", "0000:00:06.0"], "0,1"), ("sel-ac", ["0000:00:04.0", "0000:00:06.0"], "0,2")), + ): + r9_3_spec = copy.deepcopy(r9_3_base) + for sel_name, bdf_list, vis_str in vis_triples: + r9_3_spec["devices"].append( + { + "name": sel_name, + "annotations": { + "freetpu.dev/chip-count": "2", + "freetpu.dev/pci-bdfs": ",".join(bdf_list), + }, + "containerEdits": { + "deviceNodes": [ + node + for b in bdf_list + for node in r9_3_nodes[b] + ], + "env": [ + f"TPU_VISIBLE_CHIPS={vis_str}", + f"TPU_VISIBLE_DEVICES={vis_str}", + ], + }, + } + ) + r9_3_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r9_3_spec, sysfs_root=r9_3_sys, dev_root=r9_3_dev + ) + self.assertTrue( + any("valid multi-selector assignment" in e for e in r9_3_conf), + (vis_triples, r9_3_conf), + ) + + # R9-7: root `tpu7x-pci-functions-per-chip: "1"` rejected on proved `0x0076` pair, + # and mixed-gen `all` selector rejects `chiplets-per-pkg` / `hbm-gib-per-logical-device`. + r9_7_root_bad = freetpu_cdi.build_cdi_spec(r9_2_chips[:2], r9_2_cn, single_host_env=True) + r9_7_root_bad["annotations"]["freetpu.dev/tpu7x-pci-functions-per-chip"] = "1" + r9_7_root_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r9_7_root_bad, sysfs_root=r9_2_sys, dev_root=r9_2_dev + ) + self.assertTrue( + any("tpu7x-pci-functions-per-chip" in e for e in r9_7_root_conf), + r9_7_root_conf, + ) + + r9_7_mix_sys, r9_7_mix_dev = _make_mock_pci_vfio( + root / "r9_7_mixed_meta", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + }, + { + "bdf": "0000:00:05.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "0", + "chip_id": "0", + }, + { + "bdf": "0000:00:05.1", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "0", + "chip_id": "0", + }, + ], + create_vfio_nodes=["0", "1", "2"], + ) + r9_7_mix_chips, r9_7_mix_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r9_7_mix_sys, dev_root=r9_7_mix_dev + ) + r9_7_mix_spec = freetpu_cdi.build_cdi_spec( + r9_7_mix_chips, r9_7_mix_cn, single_host_env=True + ) + r9_7_all = next(d for d in r9_7_mix_spec["devices"] if d["name"] == "all") + r9_7_all["annotations"]["freetpu.dev/chiplets-per-pkg"] = "999" + r9_7_all["annotations"]["freetpu.dev/hbm-gib-per-logical-device"] = "999" + r9_7_mix_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r9_7_mix_spec, sysfs_root=r9_7_mix_sys, dev_root=r9_7_mix_dev + ) + self.assertTrue( + any("freetpu.dev/chiplets-per-pkg" in e for e in r9_7_mix_conf) + and any("freetpu.dev/hbm-gib-per-logical-device" in e for e in r9_7_mix_conf), + r9_7_mix_conf, + ) + + # Round-10 regressions: + # R10-1: `reconcile_cdi_spec`, `generate`, and `sync` must NOT republish 2-fn disk history + # without a matching boot_id when live `chip_id`s are removed and host boot_id is None. + r10_1_sys, r10_1_dev = _make_mock_pci_vfio( + root / "r10_1_reconcile_noboot", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i // 2), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + r10_1_path = root / "r10_1_spec.json" + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + ok_10_1a, msg_10_1a = freetpu_cdi.reconcile_cdi_spec( + r10_1_path, sysfs_root=r10_1_sys, dev_root=r10_1_dev, single_host_env=True + ) + self.assertTrue(ok_10_1a, msg_10_1a) + s10_1a = json.loads(r10_1_path.read_text(encoding="utf-8")) + self.assertNotIn("freetpu.dev/boot-id", s10_1a["annotations"]) + self.assertEqual( + s10_1a["annotations"].get("freetpu.dev/tpu7x-pci-functions-per-chip"), + "2", + ) + for i in range(4): + ( + r10_1_sys / "bus" / "pci" / "devices" / f"0000:00:0{4 + i:x}.0" / "chip_id" + ).unlink() + ok_10_1b, msg_10_1b = freetpu_cdi.reconcile_cdi_spec( + r10_1_path, sysfs_root=r10_1_sys, dev_root=r10_1_dev, single_host_env=True + ) + self.assertTrue(ok_10_1b, msg_10_1b) + s10_1b = json.loads(r10_1_path.read_text(encoding="utf-8")) + self.assertEqual( + s10_1b["annotations"].get("freetpu.dev/tpu7x-pci-functions-per-chip"), + "1", + ) + s10_1b_all = next(d for d in s10_1b["devices"] if d["name"] == "all") + self.assertEqual(s10_1b_all["annotations"].get("freetpu.dev/chip-count"), "4") + + # R10-4: Contradictory disk/spec history (`0000:00:04.1` observed without matching boot_id) + # flags unverifiable history on standalone `validate --check-host` (non-zero exit). + r10_4_sys, r10_4_dev = _make_mock_pci_vfio( + root / "r10_4_contra_hist", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + "chip_id": str(i), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + r10_4_c, r10_4_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r10_4_sys, dev_root=r10_4_dev + ) + r10_4_spec = freetpu_cdi.build_cdi_spec( + r10_4_c, r10_4_cn, single_host_env=True + ) + r10_4_spec["annotations"].pop("freetpu.dev/boot-id", None) + r10_4_spec["annotations"]["freetpu.dev/observed-domain-bdfs"] = ( + r10_4_spec["annotations"]["freetpu.dev/observed-domain-bdfs"] + + ",0000:00:04.1" + ) + r10_4_spec["annotations"]["freetpu.dev/observed-bdf-generations"] = ( + r10_4_spec["annotations"]["freetpu.dev/observed-bdf-generations"] + + ";0000:00:04.1=tpu7x" + ) + r10_4_conf, r10_4_unv = freetpu_cdi._verify_spec_against_host_detailed( + r10_4_spec, sysfs_root=r10_4_sys, dev_root=r10_4_dev + ) + self.assertEqual(r10_4_conf, []) + self.assertTrue(any("boot_id" in u for u in r10_4_unv), r10_4_unv) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-readable"): + r10_4_conf_r, r10_4_unv_r = freetpu_cdi._verify_spec_against_host_detailed( + r10_4_spec, sysfs_root=r10_4_sys, dev_root=r10_4_dev + ) + self.assertEqual(r10_4_conf_r, []) + self.assertTrue(any("boot_id" in u for u in r10_4_unv_r), r10_4_unv_r) + + # R10-5: Root `chip-id-map` + `tpu7x-pci-functions-per-chip="2"` with 1-fn selectors + # produces a confirmed contradiction (and unverifiable root warning) when map omitted. + r10_5_sys, r10_5_dev = _make_mock_pci_vfio( + root / "r10_5_root_vs_selectors", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + r10_5_c, r10_5_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r10_5_sys, dev_root=r10_5_dev + ) + r10_5_spec = freetpu_cdi.build_cdi_spec(r10_5_c, r10_5_cn, single_host_env=True) + r10_5_spec["annotations"]["freetpu.dev/tpu7x-layout-source"] = "chip-id-map" + r10_5_spec["annotations"]["freetpu.dev/tpu7x-pci-functions-per-chip"] = "2" + r10_5_conf, r10_5_unv = freetpu_cdi._verify_spec_against_host_detailed( + r10_5_spec, sysfs_root=r10_5_sys, dev_root=r10_5_dev + ) + self.assertTrue(len(r10_5_conf) > 0, r10_5_conf) + self.assertTrue(len(r10_5_unv) > 0, r10_5_unv) + + # R10-9: Composable `pci-*` / `group-pci-*` reject topology env overrides and + # custom selectors validate injected topology env overrides against live scope. + r10_9_sys, r10_9_dev = _make_mock_pci_vfio( + root / "r10_9_topo_env_guards", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + r10_9_c, r10_9_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r10_9_sys, dev_root=r10_9_dev + ) + r10_9_pci_spec = freetpu_cdi.build_cdi_spec( + r10_9_c, r10_9_cn, single_host_env=True + ) + r10_9_pci = next(d for d in r10_9_pci_spec["devices"] if d["name"].startswith("pci-")) + r10_9_pci["containerEdits"]["env"].extend( + ["TPU_CHIPS_PER_HOST_BOUNDS=9,9,9", "TPU_ACCELERATOR_TYPE=tpu7x-4t"] + ) + r10_9_pci_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r10_9_pci_spec, sysfs_root=r10_9_sys, dev_root=r10_9_dev + ) + self.assertTrue( + any("TPU_CHIPS_PER_HOST_BOUNDS" in e for e in r10_9_pci_conf) + and any("TPU_ACCELERATOR_TYPE" in e for e in r10_9_pci_conf), + r10_9_pci_conf, + ) + + r10_9_cust_spec = freetpu_cdi.build_cdi_spec( + r10_9_c, r10_9_cn, single_host_env=True + ) + r10_9_cust_spec["devices"].append( + { + "name": "sel-custom", + "annotations": { + "freetpu.dev/chip-count": "1", + "freetpu.dev/pci-bdfs": "0000:00:04.0", + }, + "containerEdits": { + "deviceNodes": list(r10_9_pci["containerEdits"]["deviceNodes"]), + "env": [ + "TPU_CHIPS_PER_HOST_BOUNDS=9,9,9", + "TPU_ACCELERATOR_TYPE=tpu7x-4t", + ], + }, + } + ) + r10_9_cust_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r10_9_cust_spec, sysfs_root=r10_9_sys, dev_root=r10_9_dev + ) + self.assertTrue( + any("TPU_CHIPS_PER_HOST_BOUNDS" in e for e in r10_9_cust_conf) + and any("TPU_ACCELERATOR_TYPE" in e for e in r10_9_cust_conf), + r10_9_cust_conf, + ) + + # R10-10: Changing live PCI device ID / generation (v4 0x005e -> v6e 0x006f) at + # the same BDF and VFIO group fails host validation cleanly. + r10_10_sys, r10_10_dev = _make_mock_pci_vfio( + root / "r10_10_gen_swap", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x005e", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + r10_10_c, r10_10_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r10_10_sys, dev_root=r10_10_dev + ) + r10_10_spec = freetpu_cdi.build_cdi_spec( + r10_10_c, r10_10_cn, single_host_env=True + ) + (r10_10_sys / "bus" / "pci" / "devices" / "0000:00:04.0" / "device").write_text( + "0x006f\n", encoding="utf-8" + ) + r10_10_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r10_10_spec, sysfs_root=r10_10_sys, dev_root=r10_10_dev + ) + self.assertTrue( + any("device-id" in e for e in r10_10_conf) + and any("generation" in e for e in r10_10_conf) + and any("generations" in e for e in r10_10_conf), + r10_10_conf, + ) + + # Round-11 regressions: + # R11-1: Boot-unverified disk history (`0000:00:04.1` and 5-dev v6e) ignored by `sync` first tick. + r11_1_sys, r11_1_dev = _make_mock_pci_vfio( + root / "r11_1_sync_disk_noboot", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ] + + [ + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "4", + "numa_node": "0", + } + ], + create_vfio_nodes=[str(i) for i in range(5)], + ) + r11_1_path = root / "r11_1_sync.json" + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + rc_11_1, _o11, err_11_1 = _run_cli_inproc( + [ + "generate", + "--output", + str(r11_1_path), + "--single-host-env", + "--sysfs-root", + str(r11_1_sys), + "--dev-root", + str(r11_1_dev), + ] + ) + self.assertEqual(rc_11_1, 0, err_11_1) + shutil.rmtree(r11_1_sys / "bus" / "pci" / "devices" / "0000:00:04.1") + (r11_1_dev / "vfio" / "4").unlink() + r11_sigs: dict[int, object] = {} + r11_sleeps = [0] + + def _r11_sig(signum: int, handler: object) -> None: + r11_sigs[signum] = handler + + def _r11_sleep(_secs: float) -> None: + r11_sleeps[0] += 1 + h = r11_sigs.get(freetpu_cdi.signal.SIGTERM) + if callable(h): + h(freetpu_cdi.signal.SIGTERM, None) + + with ( + mock.patch.object(freetpu_cdi.signal, "signal", side_effect=_r11_sig), + mock.patch.object(freetpu_cdi.time, "sleep", side_effect=_r11_sleep), + ): + rc_11_s, _os, err_11_s = _run_cli_inproc( + [ + "sync", + "--interval", + "1", + "--output", + str(r11_1_path), + "--single-host-env", + "--sysfs-root", + str(r11_1_sys), + "--dev-root", + str(r11_1_dev), + ] + ) + self.assertEqual(rc_11_s, 0, err_11_s) + s11_1 = json.loads(r11_1_path.read_text(encoding="utf-8")) + self.assertEqual( + s11_1["annotations"].get("freetpu.dev/tpu7x-pci-functions-per-chip"), + "1", + ) + self.assertEqual( + next(d for d in s11_1["devices"] if d["name"] == "all")["annotations"].get( + "freetpu.dev/chip-count" + ), + "4", + ) + + r11_v6_sys, r11_v6_dev = _make_mock_pci_vfio( + root / "r11_1_v6e5_noboot", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(5) + ], + create_vfio_nodes=[str(i) for i in range(5)], + ) + r11_v6_path = root / "r11_1_v6e.json" + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + self.assertEqual( + freetpu_cdi.main( + [ + "generate", + "--output", + str(r11_v6_path), + "--single-host-env", + "--sysfs-root", + str(r11_v6_sys), + "--dev-root", + str(r11_v6_dev), + ] + ), + 0, + ) + shutil.rmtree(r11_v6_sys / "bus" / "pci" / "devices" / "0000:00:08.0") + (r11_v6_dev / "vfio" / "4").unlink() + self.assertEqual( + freetpu_cdi.main( + [ + "generate", + "--output", + str(r11_v6_path), + "--single-host-env", + "--sysfs-root", + str(r11_v6_sys), + "--dev-root", + str(r11_v6_dev), + ] + ), + 0, + ) + s11_v6 = json.loads(r11_v6_path.read_text(encoding="utf-8")) + self.assertIn("numa0-pcie-0000-00-4", {d["name"] for d in s11_v6["devices"]}) + + # R11-8: Composable `pci-*` rejects injected TPU_VISIBLE_CHIPS / TPU_VISIBLE_DEVICES. + r11_8_spec = copy.deepcopy(r10_9_c) + r11_8_cdi = freetpu_cdi.build_cdi_spec(r11_8_spec, r10_9_cn, single_host_env=True) + r11_8_pci = next(d for d in r11_8_cdi["devices"] if d["name"].startswith("pci-")) + r11_8_pci["containerEdits"]["env"].extend( + ["TPU_VISIBLE_CHIPS=0", "TPU_VISIBLE_DEVICES=0"] + ) + r11_8_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r11_8_cdi, sysfs_root=r10_9_sys, dev_root=r10_9_dev + ) + self.assertTrue( + any("TPU_VISIBLE_CHIPS" in e for e in r11_8_conf) + and any("TPU_VISIBLE_DEVICES" in e for e in r11_8_conf), + r11_8_conf, + ) + + # R11-9: Renaming split-NUMA `all` to custom `worker` with `2,2,1` / `v6e-4` rejected. + r11_9_sys, r11_9_dev = _make_mock_pci_vfio( + root / "r11_9_worker_split_numa", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(2) + ] + + [ + { + "bdf": f"0000:80:0{i:x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(2 + i), + "numa_node": "1", + } + for i in range(2) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + r11_9_c, r11_9_cn = freetpu_cdi.discover_tpu_chips( + sysfs_root=r11_9_sys, dev_root=r11_9_dev + ) + r11_9_spec = freetpu_cdi.build_cdi_spec(r11_9_c, r11_9_cn, single_host_env=True) + r11_9_all = copy.deepcopy(next(d for d in r11_9_spec["devices"] if d["name"] == "all")) + r11_9_all["name"] = "worker" + r11_9_all["containerEdits"]["env"].extend( + [ + "TPU_CHIPS_PER_HOST_BOUNDS=2,2,1", + "TPU_ACCELERATOR_TYPE=v6e-4", + "TPU_SKIP_MDS_QUERY=true", + ] + ) + r11_9_spec["devices"].append(r11_9_all) + r11_9_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r11_9_spec, sysfs_root=r11_9_sys, dev_root=r11_9_dev + ) + self.assertTrue( + any("TPU_CHIPS_PER_HOST_BOUNDS" in e for e in r11_9_conf) + and any("TPU_ACCELERATOR_TYPE" in e for e in r11_9_conf) + and any("TPU_SKIP_MDS_QUERY" in e for e in r11_9_conf), + r11_9_conf, + ) + + # R11-10: `TPU_SKIP_MDS_QUERY=true` without companion bounds/type rejected on `all`. + r11_10_spec = freetpu_cdi.build_cdi_spec(r10_9_c, r10_9_cn, single_host_env=True) + r11_10_all = next(d for d in r11_10_spec["devices"] if d["name"] == "all") + r11_10_all["containerEdits"]["env"] = [ + e + for e in r11_10_all["containerEdits"]["env"] + if not e.startswith(("TPU_CHIPS_PER_HOST_BOUNDS=", "TPU_ACCELERATOR_TYPE=")) + ] + r11_10_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r11_10_spec, sysfs_root=r10_9_sys, dev_root=r10_9_dev + ) + self.assertTrue( + any("TPU_CHIPS_PER_HOST_BOUNDS" in e for e in r11_10_conf) + and any("TPU_ACCELERATOR_TYPE" in e for e in r11_10_conf), + r11_10_conf, + ) + + # R11-11: Stale singleton annotations (`iommu-group`, `pcie-root`, `numa-node`, `driver`, `model`) rejected. + r11_11_spec = freetpu_cdi.build_cdi_spec(r10_9_c, r10_9_cn, single_host_env=True) + r11_11_pci = next(d for d in r11_11_spec["devices"] if d["name"].startswith("pci-")) + r11_11_pci["annotations"].update( + { + "freetpu.dev/iommu-group": "99", + "freetpu.dev/pcie-root": "0001:00", + "freetpu.dev/numa-node": "7", + "freetpu.dev/driver": "unbound", + "freetpu.dev/model": "Cloud TPU v4", + } + ) + r11_11_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r11_11_spec, sysfs_root=r10_9_sys, dev_root=r10_9_dev + ) + for bad_key in ("iommu-group", "pcie-root", "numa-node", "driver", "model"): + self.assertTrue( + any(f"freetpu.dev/{bad_key}" in e for e in r11_11_conf), + (bad_key, r11_11_conf), + ) + + # R12-8: Bootless 5-device legacy spec (no root history, no boot-id) NEVER suppresses live 0-3 slice. + r12_v6_sys, r12_v6_dev = _make_mock_pci_vfio( + root / "r12_8_v6e4", + devices=[ + { + "bdf": f"0000:00:{4 + i:02x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + r12_8_path = root / "r12_8_legacy_bootless.json" + r12_8_bdfs = [f"0000:00:{4 + i:02x}.0" for i in range(5)] + r12_8_path.write_text( + json.dumps( + { + "cdiVersion": "0.6.0", + "kind": "freetpu.dev/tpu", + "annotations": {"freetpu.dev/generated-by": "freetpu-cdi"}, + "containerEdits": {"deviceNodes": [{"path": "/dev/vfio/vfio"}]}, + "devices": [ + { + "name": f"pci-{b.replace(':', '-').replace('.', '-')}", + "annotations": {"freetpu.dev/pci-bdf": b}, + "containerEdits": {"deviceNodes": [{"path": f"/dev/vfio/{idx}"}]}, + } + for idx, b in enumerate(r12_8_bdfs) + ], + } + ), + encoding="utf-8", + ) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-r12-8"): + ok_12_8, msg_12_8 = freetpu_cdi.reconcile_cdi_spec( + r12_8_path, sysfs_root=r12_v6_sys, dev_root=r12_v6_dev, single_host_env=True + ) + self.assertTrue(ok_12_8, msg_12_8) + s12_8 = json.loads(r12_8_path.read_text(encoding="utf-8")) + self.assertIn("numa0-pcie-0000-00-4", {d["name"] for d in s12_8["devices"]}) + + # R12-9: Same-boot `4+4` NUMA domain loss still caught when `all` is renamed `worker`. + r12_9_devs = [ + { + "bdf": f"0000:00:{4 + i:02x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(i), + "numa_node": "0", + } + for i in range(4) + ] + [ + { + "bdf": f"0000:80:{i:02x}.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": str(4 + i), + "numa_node": "1", + } + for i in range(4) + ] + r12_9_sys, r12_9_dev = _make_mock_pci_vfio( + root / "r12_9_numa_loss", + devices=r12_9_devs, + create_vfio_nodes=[str(i) for i in range(8)], + ) + r12_9_path = root / "r12_9_spec.json" + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value="boot-r12-9"): + ok_9a, msg_9a = freetpu_cdi.reconcile_cdi_spec( + r12_9_path, sysfs_root=r12_9_sys, dev_root=r12_9_dev, single_host_env=True + ) + self.assertTrue(ok_9a, msg_9a) + for i in range(4, 8): + shutil.rmtree(r12_9_sys / "bus" / "pci" / "devices" / f"0000:80:{i - 4:02x}.0") + (r12_9_dev / "vfio" / str(i)).unlink() + ok_9b, msg_9b = freetpu_cdi.reconcile_cdi_spec( + r12_9_path, sysfs_root=r12_9_sys, dev_root=r12_9_dev, single_host_env=True + ) + self.assertTrue(ok_9b, msg_9b) + s12_9 = json.loads(r12_9_path.read_text(encoding="utf-8")) + s12_9_worker = copy.deepcopy(next(d for d in s12_9["devices"] if d["name"] == "all")) + s12_9_worker["name"] = "worker" + s12_9_worker["containerEdits"]["env"].extend( + [ + "TPU_CHIPS_PER_HOST_BOUNDS=2,2,1", + "TPU_ACCELERATOR_TYPE=v6e-4", + "TPU_SKIP_MDS_QUERY=true", + ] + ) + s12_9["devices"].append(s12_9_worker) + r12_9_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + s12_9, sysfs_root=r12_9_sys, dev_root=r12_9_dev + ) + self.assertTrue( + any("TPU_CHIPS_PER_HOST_BOUNDS" in e for e in r12_9_conf) + and any("TPU_ACCELERATOR_TYPE" in e for e in r12_9_conf) + and any("TPU_SKIP_MDS_QUERY" in e for e in r12_9_conf), + r12_9_conf, + ) + + # R12-10: Plain `validate_cdi_spec()` catches composable `TPU_VISIBLE_*` & orphan `TPU_SKIP_MDS_QUERY`. + r12_10_c, r12_10_cn = freetpu_cdi.discover_tpu_chips(sysfs_root=r12_v6_sys, dev_root=r12_v6_dev) + r12_10_pci_bad = freetpu_cdi.build_cdi_spec(r12_10_c, r12_10_cn, single_host_env=True) + next(d for d in r12_10_pci_bad["devices"] if d["name"].startswith("pci-"))["containerEdits"][ + "env" + ].append("TPU_VISIBLE_CHIPS=0") + self.assertTrue( + any("TPU_VISIBLE_CHIPS" in e for e in freetpu_cdi.validate_cdi_spec(r12_10_pci_bad)) + ) + r12_10_mds_bad = freetpu_cdi.build_cdi_spec(r12_10_c, r12_10_cn, single_host_env=True) + r12_10_all = next(d for d in r12_10_mds_bad["devices"] if d["name"] == "all") + r12_10_all["containerEdits"]["env"] = [ + e + for e in r12_10_all["containerEdits"]["env"] + if not e.startswith(("TPU_CHIPS_PER_HOST_BOUNDS=", "TPU_ACCELERATOR_TYPE=")) + ] + self.assertTrue( + any("TPU_ACCELERATOR_TYPE" in e for e in freetpu_cdi.validate_cdi_spec(r12_10_mds_bad)) + ) + + # R12-11: Host validation compares topology env values verbatim (rejects `" v6e-4 "`). + r12_11_spec = freetpu_cdi.build_cdi_spec(r12_10_c, r12_10_cn, single_host_env=True) + r12_11_all = next(d for d in r12_11_spec["devices"] if d["name"] == "all") + r12_11_all["containerEdits"]["env"] = [ + "TPU_ACCELERATOR_TYPE= v6e-4 " if e.startswith("TPU_ACCELERATOR_TYPE=") else e + for e in r12_11_all["containerEdits"]["env"] + ] + r12_11_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r12_11_spec, sysfs_root=r12_v6_sys, dev_root=r12_v6_dev + ) + self.assertTrue(any("TPU_ACCELERATOR_TYPE=' v6e-4 '" in e for e in r12_11_conf), r12_11_conf) + + # R12-12: Malformed non-ASCII / 0xff sysfs `chip_id` never pairs or raises. + r12_12_sys, r12_12_dev = _make_mock_pci_vfio( + root / "r12_12_bad_cid", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + }, + { + "bdf": "0000:00:05.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "1", + "chip_id": "1", + }, + ], + create_vfio_nodes=["0", "1"], + ) + (r12_12_sys / "bus" / "pci" / "devices" / "0000:00:04.0" / "chip_id").write_bytes( + b"\xc2\xa01\xc2\xa0" + ) + c12_a, _ = freetpu_cdi.discover_tpu_chips(sysfs_root=r12_12_sys, dev_root=r12_12_dev) + self.assertIsNone(c12_a[0].runtime_chip_id) + (r12_12_sys / "bus" / "pci" / "devices" / "0000:00:04.0" / "chip_id").write_bytes(b"\xff") + c12_b, _ = freetpu_cdi.discover_tpu_chips(sysfs_root=r12_12_sys, dev_root=r12_12_dev) + self.assertIsNone(c12_b[0].runtime_chip_id) + + # R12-13: Separate nonzero functions `04.1` and `05.1` sharing sysfs `chip_id` do NOT pair. + r12_13_sys, r12_13_dev = _make_mock_pci_vfio( + root / "r12_13_sep_fn1", + devices=[ + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + "chip_id": "1", + }, + { + "bdf": "0000:00:05.1", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "1", + "chip_id": "1", + }, + ], + create_vfio_nodes=["0", "1"], + ) + c12_13, cn12_13 = freetpu_cdi.discover_tpu_chips(sysfs_root=r12_13_sys, dev_root=r12_13_dev) + s12_13 = freetpu_cdi.build_cdi_spec(c12_13, cn12_13) + all_13 = next(d for d in s12_13["devices"] if d["name"] == "all") + self.assertEqual(all_13["annotations"]["freetpu.dev/chip-count"], "0") + self.assertEqual(all_13["annotations"]["freetpu.dev/incomplete-pci-functions"], "2") + + # R13-1: Renaming `all` -> `worker` without `all` in spec succeeds on healthy host (no NameError). + r13_1_spec = freetpu_cdi.build_cdi_spec(r12_10_c, r12_10_cn, single_host_env=True) + for d in r13_1_spec["devices"]: + if d["name"] == "all": + d["name"] = "worker" + r13_1_conf, r13_1_unv = freetpu_cdi._verify_spec_against_host_detailed( + r13_1_spec, sysfs_root=r12_v6_sys, dev_root=r12_v6_dev + ) + self.assertEqual(r13_1_conf, []) + self.assertEqual(r13_1_unv, []) + + # R13-7: 3rd nonzero claimant (`06.1` sharing `chip_id=1`) blocks `04.0`+`05.0` pairing too. + r13_7_sys, r13_7_dev = _make_mock_pci_vfio( + root / "r13_7_three_claimants", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + {"bdf": "0000:00:06.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + c13_7, cn13_7 = freetpu_cdi.discover_tpu_chips(sysfs_root=r13_7_sys, dev_root=r13_7_dev) + s13_7 = freetpu_cdi.build_cdi_spec(c13_7, cn13_7) + all_13_7 = next(d for d in s13_7["devices"] if d["name"] == "all") + self.assertEqual(all_13_7["annotations"]["freetpu.dev/chip-count"], "0") + self.assertEqual(all_13_7["annotations"]["freetpu.dev/incomplete-pci-functions"], "3") + + # R13-8: Impossible map-derived `04.1`+`05.1` claim (`chip-count=1`, complete) is confirmed error, not recoverable warning. + r13_8_spec = copy.deepcopy(s12_13) + r13_8_spec["annotations"]["freetpu.dev/tpu7x-layout-source"] = "chip-id-map" + r13_8_all = next(d for d in r13_8_spec["devices"] if d["name"] == "all") + r13_8_all["annotations"]["freetpu.dev/chip-id-source"] = "chip-id-map" + r13_8_all["annotations"]["freetpu.dev/chip-count"] = "1" + r13_8_all["annotations"].pop("freetpu.dev/incomplete-pci-functions", None) + r13_8_all["annotations"]["freetpu.dev/capacity-complete"] = "true" + r13_8_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r13_8_spec, sysfs_root=r12_13_sys, dev_root=r12_13_dev + ) + self.assertTrue(any("chip-count" in e for e in r13_8_conf), r13_8_conf) + + # R13-9: Bootless 5-BDF `observed-domain-bdfs` never poisons host validation when boot_id is unreadable. + r13_9_spec = freetpu_cdi.build_cdi_spec(r12_10_c, r12_10_cn, single_host_env=True) + r13_9_spec["annotations"].pop("freetpu.dev/boot-id", None) + r13_9_spec["annotations"]["freetpu.dev/observed-domain-bdfs"] = ( + "numa:0:0000:00=0000:00:04.0,0000:00:05.0,0000:00:06.0,0000:00:07.0,0000:00:08.0" + ) + with mock.patch.object(freetpu_cdi, "_read_host_boot_id", return_value=None): + r13_9_conf, _ = freetpu_cdi._verify_spec_against_host_detailed( + r13_9_spec, sysfs_root=r12_v6_sys, dev_root=r12_v6_dev + ) + self.assertEqual(r13_9_conf, []) + + # R14-8: Ineligible `.1` sibling sharing sysfs `chip_id=1` does NOT block explicit map pairing `04.0`+`06.0`. + r14_8_sys, r14_8_dev = _make_mock_pci_vfio( + root / "r14_8_ineligible_sysfs_sib", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:05.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + {"bdf": "0000:00:06.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "2"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + c14_8, cn14_8 = freetpu_cdi.discover_tpu_chips(sysfs_root=r14_8_sys, dev_root=r14_8_dev) + s14_8 = freetpu_cdi.build_cdi_spec( + c14_8, cn14_8, chip_id_map={"0000:00:04.0": 0, "0000:00:06.0": 0} + ) + all_14_8 = next(d for d in s14_8["devices"] if d["name"] == "all") + self.assertEqual(all_14_8["annotations"]["freetpu.dev/chip-count"], "1") + self.assertEqual(all_14_8["annotations"]["freetpu.dev/incomplete-pci-functions"], "1") + self.assertIn("pending live hardware confirmation", c14_8[0].model_name) + + # R15-3: Over-claimed package ID `0` across slot `04.0/.1` + `05.0` + `06.0` must NOT + # advertise 2 complete packages (`05.0` and `06.0` remain incomplete). + r15_3_sys, r15_3_dev = _make_mock_pci_vfio( + root / "r15_3_overclaimed_pkg_id", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2"}, + {"bdf": "0000:00:06.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "3"}, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + c15_3, cn15_3 = freetpu_cdi.discover_tpu_chips(sysfs_root=r15_3_sys, dev_root=r15_3_dev) + s15_3 = freetpu_cdi.build_cdi_spec( + c15_3, + cn15_3, + chip_id_map={ + "0000:00:04.0": 0, + "0000:00:04.1": 0, + "0000:00:05.0": 0, + "0000:00:06.0": 0, + }, + ) + all_15_3 = next(d for d in s15_3["devices"] if d["name"] == "all") + self.assertEqual(all_15_3["annotations"]["freetpu.dev/chip-count"], "1") + self.assertEqual(all_15_3["annotations"]["freetpu.dev/incomplete-pci-functions"], "2") + + # R16-1: Cross-source package ID `0` conflict (sysfs on 04.0/.1 + explicit map on 05.0/06.0, + # and vice versa) must NOT count package `0` twice. + r16_1a_sys, r16_1a_dev = _make_mock_pci_vfio( + root / "r16_1a_cross_source", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "0"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2"}, + {"bdf": "0000:00:06.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "3"}, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + c16_1a, cn16_1a = freetpu_cdi.discover_tpu_chips(sysfs_root=r16_1a_sys, dev_root=r16_1a_dev) + s16_1a = freetpu_cdi.build_cdi_spec( + c16_1a, cn16_1a, chip_id_map={"0000:00:05.0": 0, "0000:00:06.0": 0} + ) + all_16_1a = next(d for d in s16_1a["devices"] if d["name"] == "all") + self.assertEqual(all_16_1a["annotations"]["freetpu.dev/chip-count"], "1") + self.assertEqual(all_16_1a["annotations"]["freetpu.dev/incomplete-pci-functions"], "2") + + r16_1b_sys, r16_1b_dev = _make_mock_pci_vfio( + root / "r16_1b_cross_source_rev", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "0"}, + {"bdf": "0000:00:06.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "3", "chip_id": "0"}, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + c16_1b, cn16_1b = freetpu_cdi.discover_tpu_chips(sysfs_root=r16_1b_sys, dev_root=r16_1b_dev) + s16_1b = freetpu_cdi.build_cdi_spec( + c16_1b, cn16_1b, chip_id_map={"0000:00:04.0": 0, "0000:00:04.1": 0} + ) + all_16_1b = next(d for d in s16_1b["devices"] if d["name"] == "all") + self.assertEqual(all_16_1b["annotations"]["freetpu.dev/chip-count"], "1") + self.assertEqual(all_16_1b["annotations"]["freetpu.dev/incomplete-pci-functions"], "2") + + # R17-2: Mixed full-slot 04.0/04.1 (chip_id=0) + separate .0 slots (chip_id=1..3) + # with a valid 1-to-1 logical chip_id_map (0..7) MUST keep all 4 packages complete. + r17_2_bdfs = ("04.0", "04.1", "05.0", "06.0", "07.0", "08.0", "09.0", "0a.0") + r17_2_sys, r17_2_dev = _make_mock_pci_vfio( + root / "r17_2_mixed_slots_logical_map", + devices=[ + { + "bdf": f"0000:00:{bdf}", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": str(idx), + "numa_node": "0", + "chip_id": str(idx // 2), + } + for idx, bdf in enumerate(r17_2_bdfs) + ], + create_vfio_nodes=[str(i) for i in range(len(r17_2_bdfs))], + ) + c17_2, cn17_2 = freetpu_cdi.discover_tpu_chips(sysfs_root=r17_2_sys, dev_root=r17_2_dev) + s17_2 = freetpu_cdi.build_cdi_spec( + c17_2, + cn17_2, + single_host_env=True, + chip_id_map={f"0000:00:{bdf}": idx for idx, bdf in enumerate(r17_2_bdfs)}, + ) + all_17_2 = next(d for d in s17_2["devices"] if d["name"] == "all") + self.assertEqual(all_17_2["annotations"]["freetpu.dev/chip-count"], "4") + self.assertNotIn("freetpu.dev/incomplete-pci-functions", all_17_2["annotations"]) + all_17_2_env = dict(kv.split("=", 1) for kv in all_17_2["containerEdits"]["env"]) + self.assertEqual(all_17_2_env["TPU_VISIBLE_DEVICES"], "0,1,2,3,4,5,6,7") + + # R18-1: Full-slot 04.0/04.1 with distinct sysfs logical IDs (0, 1) + separate .0 slots + # with sysfs package IDs (1,1,2,2,3,3) + explicit 1-to-1 logical map (0..7) -> 4 complete chips. + r18_1_sys, r18_1_dev = _make_mock_pci_vfio( + root / "r18_1_full_logical_plus_pkg", + devices=[ + { + "bdf": f"0000:00:{bdf}", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": str(idx), + "numa_node": "0", + "chip_id": str(idx if idx < 2 else idx // 2), + } + for idx, bdf in enumerate(r17_2_bdfs) + ], + create_vfio_nodes=[str(i) for i in range(len(r17_2_bdfs))], + ) + c18_1, cn18_1 = freetpu_cdi.discover_tpu_chips(sysfs_root=r18_1_sys, dev_root=r18_1_dev) + s18_1 = freetpu_cdi.build_cdi_spec( + c18_1, + cn18_1, + single_host_env=True, + chip_id_map={f"0000:00:{bdf}": idx for idx, bdf in enumerate(r17_2_bdfs)}, + ) + all_18_1 = next(d for d in s18_1["devices"] if d["name"] == "all") + self.assertEqual(all_18_1["annotations"]["freetpu.dev/chip-count"], "4") + self.assertNotIn("freetpu.dev/incomplete-pci-functions", all_18_1["annotations"]) + all_18_1_env = dict(kv.split("=", 1) for kv in all_18_1["containerEdits"]["env"]) + self.assertEqual(all_18_1_env["TPU_VISIBLE_DEVICES"], "0,1,2,3,4,5,6,7") + if __name__ == "__main__": unittest.main() diff --git a/ops/tpu-exporter/README.md b/ops/tpu-exporter/README.md index 2bbcd1a2..232ad9bb 100644 --- a/ops/tpu-exporter/README.md +++ b/ops/tpu-exporter/README.md @@ -5,7 +5,7 @@ ## What It Discovers & Exports 1. **PCI & VFIO Topology (`/sys/bus/pci/devices/*` + `/dev/vfio/*`)** - - Filters Google PCI vendor `0x1ae0` and maps known TPU device IDs (`0x0027`, `0x0056`, `0x005e`, `0x0062`, `0x0063`, `0x006e`, `0x006f`, and `0x0076` / `0x0075` for `tpu7x` Ironwood). Note: upstream `tpu-info` CLI discovery omits v6e PF `0x006e` (recognizing v6e VF `0x006f`), while `tpu_exporter.py` maps `0x006e` directly to `TpuChip.V6E` and queries `127.0.0.1:8431` via direct gRPC or `tpu_info.metrics` fallback. + - Filters Google PCI vendor `0x1ae0` and maps known TPU device IDs (`0x0027`, `0x0056`, `0x005e`, `0x0062`, `0x0063`, `0x006e`, `0x006f`) plus provisional `0x0075` / `0x0076` candidates for `tpu7x` Ironwood (pending live Day-1 `lspci -nn` confirmation). Note: upstream `tpu-info` CLI discovery omits v6e PF `0x006e` (recognizing v6e VF `0x006f`), while `tpu_exporter.py` maps `0x006e` directly to `TpuChip.V6E` and queries `127.0.0.1:8431` via direct gRPC or `tpu_info.metrics` fallback. - Resolves IOMMU group, bound kernel driver (`vfio-pci`), `/dev/vfio/` node, `/dev/vfio/vfio` container readiness, and pure `libtpu`-free sysfs PCIe AER error counters (`aer_dev_correctable` -> `freetpu_pcie_aer_correctable_total`, `aer_dev_fatal` -> `freetpu_pcie_aer_fatal_total`). 2. **Runtime Telemetry (Direct gRPC + SeqLock SHM + `tpu-info` / `/proc/*/fd` fallback)** - **Direct `libtpu` gRPC (`RuntimeMetricService` on `127.0.0.1:8431`):** Queries `GetRuntimeMetric` in-process over a reused channel when `grpcio` and `tpu_metric_service` proto stubs are installed (eliminating `tpu-info` subprocess churn) for HBM usage/total, MXU duty cycle `%`, and HBM bandwidth utilization `%` (`tpu.runtime.hbm.utilization.percent`). diff --git a/ops/tpu-exporter/test_tpu_exporter.py b/ops/tpu-exporter/test_tpu_exporter.py index 4746a25c..d7f21591 100755 --- a/ops/tpu-exporter/test_tpu_exporter.py +++ b/ops/tpu-exporter/test_tpu_exporter.py @@ -4,10 +4,12 @@ from __future__ import annotations import contextlib +import io import json import os from pathlib import Path import re +import shutil import stat import subprocess import sys @@ -7244,6 +7246,2337 @@ def _run_with_pypath(cmd: list[str], *, timeout_s: float) -> subprocess.Complete f"Duty RPC timeout must subtract startup+import time from parent deadline: {seen_t}", ) + def test_tpu7x_dual_chiplet_topology_metadata(self) -> None: + # Issue #21: tpu7x Ironwood exposes 8 logical devices (2 chiplets per + # 192 GiB package) x 96 GiB HBM3e each. 0x1ae0:0x0075 is provisional + # pending Day-1 `lspci -nn` capture. + self.assertEqual(tpu_exporter.TPU_PCI_DEVICES["0x0075"][0], "tpu7x") + self.assertEqual(tpu_exporter.TPU_PCI_DEVICES["0x0076"][0], "tpu7x") + self.assertEqual(tpu_exporter.TPU_PCI_DEVICES["0x0075"][2], 96 * 1024**3) + self.assertEqual(tpu_exporter.TPU_PCI_DEVICES["0x0076"][2], 96 * 1024**3) + self.assertEqual(tpu_exporter.TPU_CHIPLETS_PER_PKG["tpu7x"], 2) + self.assertEqual(tpu_exporter.TPU_HBM_GIB_PER_LOGICAL_DEVICE["tpu7x"], 96) + self.assertEqual(tpu_exporter.TPU_CHIPLETS_PER_PKG["v6e"], 1) + self.assertEqual(tpu_exporter.TPU_HBM_GIB_PER_LOGICAL_DEVICE["v6e"], 32) + + def _sum_hbm_total_prom_bytes(prom_text: str) -> Tuple[int, List[int]]: + vals: List[int] = [] + for ln in prom_text.splitlines(): + if ln.startswith("freetpu_tpu_hbm_total_bytes{"): + vals.append(int(ln.rsplit(" ", 1)[1])) + return sum(vals), vals + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + # 1. 4-function (4 x 1-fn dual-chiplet) 0x0075 host: each PCI function + # represents a 192 GiB package (2 chiplets x 96 GiB) -> 768 GiB total + # in both snapshot fields and rendered Prometheus output. + pf4_sysfs, pf4_dev, pf4_proc = _make_mock_pci_tree( + root / "pf4", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "chip_id": str(idx), + } + for idx, bdf in enumerate( + ( + "0000:00:04.0", + "0000:00:05.0", + "0000:80:00.0", + "0000:80:01.0", + ) + ) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_lstat(): + pf4_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual(len(pf4_snap.devices), 4) + self.assertEqual( + [d.hbm_nominal_bytes for d in pf4_snap.devices], + [192 * 1024**3] * 4, + ) + self.assertEqual( + [d.hbm_total_bytes for d in pf4_snap.devices], + [192 * 1024**3] * 4, + ) + self.assertEqual( + sum(d.hbm_total_bytes or 0 for d in pf4_snap.devices), + 768 * 1024**3, + ) + pf4_prom = tpu_exporter.format_prometheus_metrics(pf4_snap) + self._assert_valid_prometheus_text(pf4_prom) + self.assertIn("freetpu_tpu_devices_discovered 4", pf4_prom) + pf4_sum, pf4_vals = _sum_hbm_total_prom_bytes(pf4_prom) + self.assertEqual(pf4_vals, [192 * 1024**3] * 4) + self.assertEqual(pf4_sum, 768 * 1024**3) + + # 2. 8-function (4 x 2-fn) 0x0075 multifunction host: each PCI function + # exposes 1 logical chiplet (96 GiB) -> 8 x 96 GiB = 768 GiB total. + pf8_sysfs, pf8_dev, pf8_proc = _make_mock_pci_tree( + root / "pf8", + devices=[ + { + "bdf": f"0000:00:0{4 + (i // 2):x}.{i % 2}", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + } + for i in range(8) + ], + create_vfio_nodes=[str(i) for i in range(8)], + ) + with _mock_vfio_char_lstat(): + pf8_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf8_sysfs, + dev_root=pf8_dev, + proc_root=pf8_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual(len(pf8_snap.devices), 8) + self.assertEqual( + [d.hbm_nominal_bytes for d in pf8_snap.devices], + [96 * 1024**3] * 8, + ) + pf8_prom = tpu_exporter.format_prometheus_metrics(pf8_snap) + self._assert_valid_prometheus_text(pf8_prom) + self.assertIn("freetpu_tpu_devices_discovered 8", pf8_prom) + pf8_sum, pf8_vals = _sum_hbm_total_prom_bytes(pf8_prom) + self.assertEqual(pf8_vals, [96 * 1024**3] * 8) + self.assertEqual(pf8_sum, 768 * 1024**3) + + # 3. 4 x 1-fn 0x0075 with mapped 8-chiplet runtime telemetry keeps + # package hbm_total_bytes at 192 GiB (4 x 192 = 768 GiB, never clobbered + # to single-chiplet 96 GiB). + pf4_cli = root / "mock-pf4-8chip-tpu-info.sh" + pf4_rows = "\n".join( + f"| {i:<9} | 12.0 GiB / 96.0 GiB | [##........] 12.5% | 10.0% | 25.0% |" + for i in range(8) + ) + pf4_cli.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + f"{pf4_rows}\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + pf4_cli.chmod(0o755) + pf4_map = { + "0000:00:04.0": "0", + "0000:00:05.0": "2", + "0000:80:00.0": "4", + "0000:80:01.0": "6", + } + with _mock_vfio_char_lstat(): + pf4_rt_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=str(pf4_cli), + runtime_metrics_addr="", + shm_root=root / "no-shm", + chip_id_map=pf4_map, + ) + self.assertEqual( + [d.hbm_total_bytes for d in pf4_rt_snap.devices], + [192 * 1024**3] * 4, + ) + self.assertEqual( + sum(d.hbm_total_bytes or 0 for d in pf4_rt_snap.devices), + 768 * 1024**3, + ) + + # 4. Partial 4-row runtime output for 4 x 1-fn 0x0075 (expects 8 logical + # devices): both sidecar (4-row gRPC -> Python fallback) and host mode + # (4-row CLI -> Python/gRPC fallback) keep trying until 8 rows arrive, + # while package `hbm_total_bytes` stays 192 GiB per PCI function. + eight_rows = { + str(i): tpu_exporter._TpuInfoRow( + chip_key=str(i), + hbm_used_bytes=4 * 1024**3, + hbm_total_bytes=96 * 1024**3, + hbm_bw_util_percent=5.0, + duty_cycle_percent=10.0, + in_util_table=True, + ) + for i in range(8) + } + four_rows = {str(i): eight_rows[str(i)] for i in range(4)} + + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, four_rows), + ) as spy_grpc, + mock.patch.object( + tpu_exporter, + "_query_tpu_info_python_metrics", + return_value=(True, None, eight_rows), + ) as spy_py, + ): + pf4_fb_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=str(pf4_cli), + skip_pid_scan=True, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + chip_id_map=pf4_map, + ) + self.assertEqual(spy_grpc.call_count, 1) + self.assertEqual(spy_py.call_count, 1) + self.assertEqual(len(pf4_fb_snap.runtime_utilization), 8) + self.assertEqual( + [d.hbm_total_bytes for d in pf4_fb_snap.devices], + [192 * 1024**3] * 4, + ) + + pf4_partial_cli = root / "mock-pf4-partial4-tpu-info.sh" + pf4_partial_rows = "\n".join( + f"| {i:<9} | 12.0 GiB / 96.0 GiB | [##........] 12.5% | 10.0% | 25.0% |" + for i in range(4) + ) + pf4_partial_cli.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + f"{pf4_partial_rows}\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + pf4_partial_cli.chmod(0o755) + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_tpu_info_python_metrics", + return_value=(True, None, eight_rows), + ) as spy_host_py, + ): + pf4_host_fb_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=str(pf4_partial_cli), + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + chip_id_map=pf4_map, + ) + self.assertEqual(spy_host_py.call_count, 1) + self.assertEqual(len(pf4_host_fb_snap.runtime_utilization), 8) + self.assertEqual( + [d.hbm_total_bytes for d in pf4_host_fb_snap.devices], + [192 * 1024**3] * 4, + ) + + # 5. `.1`-only 0x0075 orphans fall back to single-chiplet (96 GiB/fn); + # sentinel "-1" sysfs chip_id and canonical "00" vs "0" still resolve + # dual-chiplet (192 GiB/fn) cleanly. + dot1_sysfs, dot1_dev, dot1_proc = _make_mock_pci_tree( + root / "dot1", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "chip_id": str(idx), + } + for idx, bdf in enumerate( + ( + "0000:00:04.1", + "0000:00:05.1", + "0000:80:00.1", + "0000:80:01.1", + ) + ) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_lstat(): + dot1_snap = tpu_exporter.collect_snapshot( + sysfs_root=dot1_sysfs, + dev_root=dot1_dev, + proc_root=dot1_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in dot1_snap.devices], + [96 * 1024**3] * 4, + ) + + sent_sysfs, sent_dev, sent_proc = _make_mock_pci_tree( + root / "sentinel", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "chip_id": cid, + } + for idx, (bdf, cid) in enumerate( + ( + ("0000:00:04.0", "-1"), + ("0000:00:05.0", "-1"), + ("0000:80:00.0", "00"), + ("0000:80:01.0", "01"), + ) + ) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_lstat(): + sent_snap = tpu_exporter.collect_snapshot( + sysfs_root=sent_sysfs, + dev_root=sent_dev, + proc_root=sent_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in sent_snap.devices], + [192 * 1024**3] * 4, + ) + + # 6. Two PCIe roots sharing NUMA node 0 keep distinct root domains (768 GiB); + # two downstream buses under one root link cleanly to 2-fn (384 GiB). + roots_sys, roots_dev, roots_proc = _make_mock_pci_tree( + root / "two_roots_numa0", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "numa_node": "0", + "chip_id": str(idx % 2), + } + for idx, bdf in enumerate( + ( + "0000:00:04.0", + "0000:00:05.0", + "0000:80:00.0", + "0000:80:01.0", + ) + ) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + with _mock_vfio_char_lstat(): + roots_snap = tpu_exporter.collect_snapshot( + sysfs_root=roots_sys, + dev_root=roots_dev, + proc_root=roots_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in roots_snap.devices], + [192 * 1024**3] * 4, + ) + + # Two downstream switch buses under single PCIe root pci0000:00 (`numa_node=-1`). + br_root = root / "bridged_root" + br_sys = br_root / "sys" + br_dev = br_root / "dev" + br_proc = br_root / "proc" + (br_sys / "bus" / "pci" / "devices").mkdir(parents=True, exist_ok=True) + (br_sys / "kernel" / "iommu_groups").mkdir(parents=True, exist_ok=True) + (br_dev / "vfio").mkdir(parents=True, exist_ok=True) + br_proc.mkdir(parents=True, exist_ok=True) + for idx, (bdf, sub_bus, cid) in enumerate( + [ + ("0000:01:00.0", "0000:00:01.0", "0"), + ("0000:02:00.0", "0000:00:02.0", "0"), + ("0000:03:00.0", "0000:00:03.0", "1"), + ("0000:04:00.0", "0000:00:04.0", "1"), + ] + ): + ep = br_sys / "devices" / "pci0000:00" / sub_bus / bdf + ep.mkdir(parents=True, exist_ok=True) + (ep / "vendor").write_text("0x1ae0\n", encoding="utf-8") + (ep / "device").write_text("0x0075\n", encoding="utf-8") + (ep / "subsystem_device").write_text("0x0000\n", encoding="utf-8") + (ep / "numa_node").write_text("-1\n", encoding="utf-8") + (ep / "chip_id").write_text(f"{cid}\n", encoding="utf-8") + drv = br_sys / "bus" / "pci" / "drivers" / "vfio-pci" + drv.mkdir(parents=True, exist_ok=True) + (ep / "driver").symlink_to(drv) + grp_dir = br_sys / "kernel" / "iommu_groups" / str(idx) + (grp_dir / "devices").mkdir(parents=True, exist_ok=True) + (grp_dir / "devices" / bdf).symlink_to(ep) + (ep / "iommu_group").symlink_to(grp_dir) + (br_dev / "vfio" / str(idx)).write_text("", encoding="utf-8") + (br_sys / "bus" / "pci" / "devices" / bdf).symlink_to(ep) + (br_dev / "vfio" / "vfio").write_text("", encoding="utf-8") + with _mock_vfio_char_lstat(): + br_snap = tpu_exporter.collect_snapshot( + sysfs_root=br_sys, + dev_root=br_dev, + proc_root=br_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in br_snap.devices], + [96 * 1024**3] * 4, + ) + + # 7. Canonicalized `0,00` and `1,01` sysfs IDs collapse to shared pairs, + # physical_chip_map / tpu7x_pci_layout="2fn" matches CDI 384 GiB, and + # `0,2,4,6` mapped packages missing device 7 trigger fallback! + pad_sys, pad_dev, pad_proc = _make_mock_pci_tree( + root / "pad_ids", + devices=[ + { + "bdf": bdf, + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(idx), + "chip_id": cid, + } + for idx, (bdf, cid) in enumerate( + [ + ("0000:00:04.0", "0"), + ("0000:00:05.0", "00"), + ("0000:00:06.0", "1"), + ("0000:00:07.0", "01"), + ] + ) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with _mock_vfio_char_lstat(): + pad_snap = tpu_exporter.collect_snapshot( + sysfs_root=pad_sys, + dev_root=pad_dev, + proc_root=pad_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertTrue(all(d.runtime_chip_id is None for d in pad_snap.devices)) + self.assertEqual( + [d.hbm_nominal_bytes for d in pad_snap.devices], + [96 * 1024**3] * 4, + ) + + nosid_sys, nosid_dev, nosid_proc = _make_mock_pci_tree( + root / "nosid_4fn", + devices=[ + { + "bdf": f"0000:00:0{4 + i:x}.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": str(i), + } + for i in range(4) + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + with _mock_vfio_char_lstat(): + pmap_snap = tpu_exporter.collect_snapshot( + sysfs_root=nosid_sys, + dev_root=nosid_dev, + proc_root=nosid_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + physical_chip_map={ + "0000:00:04.0": 0, + "0000:00:05.0": 0, + "0000:00:06.0": 1, + "0000:00:07.0": 1, + }, + ) + l2_snap = tpu_exporter.collect_snapshot( + sysfs_root=nosid_sys, + dev_root=nosid_dev, + proc_root=nosid_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + tpu7x_pci_layout="2fn", + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in pmap_snap.devices], + [96 * 1024**3] * 4, + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in l2_snap.devices], + [96 * 1024**3] * 4, + ) + + base_even_map = { + "0000:00:04.0": "0", + "0000:00:05.0": "2", + "0000:80:00.0": "4", + "0000:80:01.0": "6", + } + missing7_rows = { + str(cid): tpu_exporter._TpuInfoRow( + chip_key=str(cid), + hbm_used_bytes=4 * 1024**3, + hbm_total_bytes=96 * 1024**3, + hbm_bw_util_percent=5.0, + duty_cycle_percent=10.0, + in_util_table=True, + ) + for cid in (0, 1, 2, 3, 4, 5, 6, 8) + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, missing7_rows), + ) as spy_even_grpc, + mock.patch.object( + tpu_exporter, + "_query_tpu_info_python_metrics", + return_value=(True, None, eight_rows), + ) as spy_even_py, + ): + miss7_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=str(pf4_cli), + skip_pid_scan=True, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + chip_id_map=base_even_map, + ) + self.assertEqual(spy_even_grpc.call_count, 1) + self.assertEqual(spy_even_py.call_count, 1) + self.assertTrue( + {str(i) for i in range(8)}.issubset( + {r.runtime_chip for r in miss7_snap.runtime_utilization} + ) + ) + + # 8. Reject negative `-1` and conflicting D2D-pair logical IDs (`0` & `1`), + # physical_chip_map deterministically attributes all 8 chiplets (0..7) + # to 4 packages, single entry `3` expects `(2,3)`, CLI `"00"` canonicalizes + # to `"0"`, and unrelated absent BDF does not flip 4x1-fn layout. + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + pf4_rt_snap.devices, {"0000:00:04.0": "-1"} + ) + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + pf4_rt_snap.devices, + {"0000:00:04.0": "0", "0000:00:05.0": "1"}, + ) + + phys_map = { + "0000:00:04.0": 0, + "0000:00:05.0": 1, + "0000:80:00.0": 2, + "0000:80:01.0": 3, + } + with _mock_vfio_char_lstat(): + phys_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=str(pf4_cli), + runtime_metrics_addr="", + shm_root=root / "no-shm", + physical_chip_map=phys_map, + ) + rt_bdf_map = { + r.runtime_chip: r.mapped_pci_bdf for r in phys_snap.runtime_utilization + } + self.assertEqual(rt_bdf_map["0"], "0000:00:04.0") + self.assertEqual(rt_bdf_map["1"], "0000:00:04.0") + self.assertEqual(rt_bdf_map["6"], "0000:80:01.0") + self.assertEqual(rt_bdf_map["7"], "0000:80:01.0") + self.assertEqual( + [d.hbm_used_bytes for d in phys_snap.devices], + [24 * 1024**3] * 4, + ) + + single_3_expected = tpu_exporter._expected_runtime_ids_for_devices( + pf4_rt_snap.devices, + set(), + {"0000:80:01.0": "3"}, + dual_chiplet_pkg_bdfs={d.pci_bdf for d in pf4_rt_snap.devices}, + ) + self.assertEqual(single_3_expected, {"2", "3"}) + + dup_zero_cli = root / "mock-dup00-tpu-info.sh" + dup_zero_rows = "\n".join( + f"| {cid:<9} | 12.0 GiB / 96.0 GiB | [##........] 12.5% | 10.0% | 25.0% |" + for cid in ("00", "0", "1", "2", "3", "4", "5", "6") + ) + dup_zero_cli.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + f"{dup_zero_rows}\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + dup_zero_cli.chmod(0o755) + parsed_dup = tpu_exporter.parse_tpu_info_output( + dup_zero_cli.read_text(encoding="utf-8").split("<<'EOF'\n", 1)[1].rsplit("\nEOF", 1)[0] + ) + self.assertEqual(len(parsed_dup), 7) + self.assertFalse( + tpu_exporter._has_complete_utilization( + parsed_dup, expected_runtime_ids=None, min_expected_rows=8 + ) + ) + + with _mock_vfio_char_lstat(): + unrel_abs_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin=None, + runtime_metrics_addr="", + shm_root=root / "no-shm", + physical_chip_map={"0000:c0:00.0": 9}, + ) + self.assertEqual( + [d.hbm_nominal_bytes for d in unrel_abs_snap.devices], + [192 * 1024**3] * 4, + ) + + # Round-4 regressions: + # (a) CLI startup passes --physical-chip-map and --tpu7x-pci-layout to validate_chip_id_map. + pf4_bdfs = [d.pci_bdf for d in pf4_snap.devices] + cli4_map = json.dumps({bdf: i for i, bdf in enumerate(pf4_bdfs)}) + cli4_phys = json.dumps({bdf: i // 2 for i, bdf in enumerate(pf4_bdfs)}) + with _mock_vfio_char_lstat(), mock.patch.object(sys, "stdout", new_callable=io.StringIO): + rc_2fn = tpu_exporter.main( + [ + "--sysfs-root", + str(pf4_sysfs), + "--dev-root", + str(pf4_dev), + "--proc-root", + str(pf4_proc), + "--tpu-info-bin", + "", + "--runtime-metrics-addr", + "", + "--shm-root", + str(root / "no-shm"), + "--chip-id-map", + cli4_map, + "--tpu7x-pci-layout", + "2fn", + "--once", + ] + ) + rc_phys = tpu_exporter.main( + [ + "--sysfs-root", + str(pf4_sysfs), + "--dev-root", + str(pf4_dev), + "--proc-root", + str(pf4_proc), + "--tpu-info-bin", + "", + "--runtime-metrics-addr", + "", + "--shm-root", + str(root / "no-shm"), + "--chip-id-map", + cli4_map, + "--physical-chip-map", + cli4_phys, + "--once", + ] + ) + self.assertEqual(rc_2fn, 0) + self.assertEqual(rc_phys, 0) + + # (b) Same-bus and bridged absent mapped partners drop 1-fn dual-chiplet 192->96 GiB. + sb_sysfs, sb_dev, sb_proc = _make_mock_pci_tree( + root / "sb_abs_env", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + sb_devs = tpu_exporter.discover_tpu_devices( + sysfs_root=sb_sysfs, + dev_root=sb_dev, + physical_chip_map={"0000:00:04.0": 0, "0000:00:05.0": 0}, + ) + self.assertEqual([d.hbm_nominal_bytes for d in sb_devs], [96 * 1024**3]) + br_sysfs, br_dev, br_proc = _make_mock_pci_tree( + root / "br_abs_env", + devices=[ + { + "bdf": "0000:04:00.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + } + ], + create_vfio_nodes=["0"], + ) + br_rp = br_sysfs / "devices" / "pci0000:00" / "0000:00:01.0" + br_rp.mkdir(parents=True, exist_ok=True) + (br_rp / "secondary_bus_number").write_text("0x04\n", encoding="utf-8") + (br_rp / "subordinate_bus_number").write_text("0x04\n", encoding="utf-8") + src_ep = br_sysfs / "bus" / "pci" / "devices" / "0000:04:00.0" + dst_ep = br_rp / "0000:04:00.0" + shutil.move(str(src_ep), str(dst_ep)) + src_ep.symlink_to(dst_ep) + igrp_ep = br_sysfs / "kernel" / "iommu_groups" / "0" / "devices" / "0000:04:00.0" + igrp_ep.unlink() + igrp_ep.symlink_to(dst_ep) + (br_sysfs / "bus" / "pci" / "devices" / "0000:00:01.0").symlink_to(br_rp) + br_dev_node = br_sysfs / "devices" / "pci0000:00" / "0000:00:02.0" + br_dev_node.mkdir(parents=True, exist_ok=True) + (br_dev_node / "secondary_bus_number").write_text("0x05\n", encoding="utf-8") + (br_dev_node / "subordinate_bus_number").write_text("0x05\n", encoding="utf-8") + (br_sysfs / "bus" / "pci" / "devices" / "0000:00:02.0").symlink_to(br_dev_node) + br_devs = tpu_exporter.discover_tpu_devices( + sysfs_root=br_sysfs, + dev_root=br_dev, + physical_chip_map={"0000:04:00.0": 0, "0000:05:00.0": 0}, + ) + self.assertEqual(br_devs[0].pcie_root, "0000:00") + self.assertEqual([d.hbm_nominal_bytes for d in br_devs], [96 * 1024**3]) + + # (c) Physical ID 32768 exceeds bounded logical runtime IDs (<= 65535), omitted from expected IDs. + self.assertEqual( + tpu_exporter._expected_runtime_ids_for_devices( + pf4_rt_snap.devices, + set(), + None, + dual_chiplet_pkg_bdfs={d.pci_bdf for d in pf4_rt_snap.devices}, + physical_chip_map={ + pf4_rt_snap.devices[0].pci_bdf: 32765, + pf4_rt_snap.devices[3].pci_bdf: 32768, + }, + ), + {"65530", "65531"}, + ) + + # (d) Malformed utilization keys ('000000', '-1', '²', '65536') excluded from coverage. + for bad_k in ("000000", "-1", "²", "65536"): + bad_rows_txt = "\n".join( + f"| {cid:<9} | 12.0 GiB / 96.0 GiB | [##........] 12.5% | 10.0% | 25.0% |" + for cid in ("0", "1", "2", "3", "4", "5", "6", bad_k) + ) + parsed_bad = tpu_exporter.parse_tpu_info_output( + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + f"{bad_rows_txt}\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + ) + self.assertFalse( + tpu_exporter._has_complete_utilization(parsed_bad, min_expected_rows=8) + ) + + # (e) Expanded D2D pair vs single-device runtime ID collision checked in one ownership table. + mix_sysfs, mix_dev, mix_proc = _make_mock_pci_tree( + root / "mix_d2d_v5e_env", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "1", + }, + ], + create_vfio_nodes=["0", "1"], + ) + mix_devs = tpu_exporter.discover_tpu_devices(sysfs_root=mix_sysfs, dev_root=mix_dev) + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + mix_devs, {"0000:00:04.0": "0", "0000:80:00.0": "1"} + ) + col_cli = root / "mock-collision-tpu-info.sh" + col_cli.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| 0 | 10.0 GiB / 96.0 GiB | [##........] 10.4% | 10.0% | 25.0% |\n" + "| 1 | 12.0 GiB / 96.0 GiB | [##........] 12.5% | 10.0% | 25.0% |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + col_cli.chmod(0o755) + with _mock_vfio_char_lstat(): + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=mix_sysfs, + dev_root=mix_dev, + proc_root=mix_proc, + tpu_info_bin=str(col_cli), + runtime_metrics_addr="", + shm_root=root / "no-shm", + physical_chip_map={"0000:00:04.0": 0}, + chip_id_map={"0000:80:00.0": "1"}, + ) + with mock.patch.object(tpu_exporter, "validate_chip_id_map"): + col_snap = tpu_exporter.collect_snapshot( + sysfs_root=mix_sysfs, + dev_root=mix_dev, + proc_root=mix_proc, + tpu_info_bin=str(col_cli), + runtime_metrics_addr="", + shm_root=root / "no-shm", + physical_chip_map={"0000:00:04.0": 0}, + chip_id_map={"0000:80:00.0": "1"}, + ) + # Neither device steals colliding row '1' and runtime row '1' stays unmapped. + self.assertIsNone(col_snap.devices[0].hbm_used_bytes) + self.assertIsNone(col_snap.devices[1].hbm_used_bytes) + self.assertIsNone( + next(r for r in col_snap.runtime_utilization if r.runtime_chip == "1").mapped_pci_bdf + ) + + # (f) Direct BDF / exclusive VFIO utilization row on 1-fn Ironwood retains attribution. + bdf_row_cli = root / "mock-direct-bdf-tpu-info.sh" + bdf_row_cli.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+--------------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+--------------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| 0000:00:04.0 | 48.0 GiB / 192.0 GiB | [###.......] 25.0% | 15.0% | 50.0% |\n" + "+--------------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + bdf_row_cli.chmod(0o755) + with _mock_vfio_char_lstat(): + bdf_row_snap = tpu_exporter.collect_snapshot( + sysfs_root=sb_sysfs, + dev_root=sb_dev, + proc_root=sb_proc, + tpu_info_bin=str(bdf_row_cli), + runtime_metrics_addr="", + shm_root=root / "no-shm", + ) + self.assertEqual(bdf_row_snap.devices[0].hbm_used_bytes, 48 * 1024**3) + self.assertEqual( + next( + r + for r in bdf_row_snap.runtime_utilization + if r.runtime_chip == "0000:00:04.0" + ).mapped_pci_bdf, + "0000:00:04.0", + ) + + # Round 5 exporter regressions: + # (g) End-to-end bridged collect_snapshot resolves PCIe root before validate_chip_id_map & HBM accounting. + with _mock_vfio_char_lstat(): + br_snap = tpu_exporter.collect_snapshot( + sysfs_root=br_sysfs, + dev_root=br_dev, + proc_root=br_proc, + tpu_info_bin="", + shm_root=root / "no-shm", + physical_chip_map={"0000:04:00.0": 0, "0000:05:00.0": 0}, + ) + self.assertEqual([d.hbm_nominal_bytes for d in br_snap.devices], [96 * 1024**3]) + self.assertEqual([d.pcie_root for d in br_snap.devices], ["0000:00"]) + + # (h) Folded legacy 0x0027 sibling_pci_bdfs excluded when inferring 1-fn Ironwood pairs alongside 0x0075. + leg_sysfs, leg_dev, _leg_proc = _make_mock_pci_tree( + root / "leg_sibling_bdf", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0027", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + }, + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0027", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "0", + }, + { + "bdf": "0000:00:05.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "0", + }, + ], + create_vfio_nodes=["0", "1", "2"], + ) + leg_devs = tpu_exporter.discover_tpu_devices( + sysfs_root=leg_sysfs, + dev_root=leg_dev, + physical_chip_map={ + "0000:00:04.0": 0, + "0000:00:04.1": 0, + "0000:00:05.0": 0, + }, + ) + self.assertEqual( + leg_devs[0].sibling_pci_bdfs, + ["0000:00:04.0", "0000:00:04.1"], + ) + self.assertEqual(leg_devs[1].pci_bdf, "0000:00:05.0") + self.assertEqual(leg_devs[1].hbm_nominal_bytes, 192 * 1024**3) + self.assertEqual( + tpu_exporter._tpu7x_dual_chiplet_pkg_bdfs( + leg_devs, + physical_chip_map={ + "0000:00:04.0": 0, + "0000:00:04.1": 0, + "0000:00:05.0": 0, + }, + ), + {"0000:00:05.0"}, + ) + + # (i) Incomplete gRPC (7 chiplet rows 0..6 + package BDF row) falls back to full 0..7 CLI rows; + # and dual BDF + exclusive VFIO rows merge onto one package BDF on 1-fn Ironwood. + grpc_partial_with_pkg_bdf = { + str(cid): tpu_exporter._TpuInfoRow( + chip_key=str(cid), + hbm_used_bytes=12 * 1024**3, + hbm_total_bytes=96 * 1024**3, + duty_cycle_percent=25.0, + in_util_table=True, + ) + for cid in range(7) + } + grpc_partial_with_pkg_bdf["0000:00:07.0"] = tpu_exporter._TpuInfoRow( + chip_key="0000:00:07.0", + hbm_used_bytes=24 * 1024**3, + hbm_total_bytes=192 * 1024**3, + duty_cycle_percent=25.0, + in_util_table=True, + ) + cli_full_8 = ( + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + + "\n".join( + f"| {cid:<9} | 20.0 GiB / 96.0 GiB | [##........] 20.8% | 10.0% | 40.0% |" + for cid in range(8) + ) + + "\n+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + ) + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, grpc_partial_with_pkg_bdf), + ), + mock.patch.object( + tpu_exporter, + "_run_tpu_info", + return_value=( + True, + None, + tpu_exporter.parse_tpu_info_output(cli_full_8), + ), + ) as mock_cli_fall, + ): + fb_snap = tpu_exporter.collect_snapshot( + sysfs_root=pf4_sysfs, + dev_root=pf4_dev, + proc_root=pf4_proc, + tpu_info_bin="tpu-info", + tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + chip_id_map=pf4_map, + ) + self.assertEqual(mock_cli_fall.call_count, 1) + self.assertEqual( + [d.hbm_used_bytes for d in fb_snap.devices], + [24 * 1024**3, 24 * 1024**3, 24 * 1024**3, 32 * 1024**3], + ) + + grpc_bdf_duty = { + "0000:00:04.0": tpu_exporter._TpuInfoRow( + chip_key="0000:00:04.0", + duty_cycle_percent=66.0, + in_util_table=True, + ) + } + cli_vfio_hbm = ( + "TPU Device Status\n" + "+------------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+------------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| /dev/vfio/0| 50.0 GiB / 192.0 GiB | [###.......] 26.0% | N/A | N/A |\n" + "+------------+---------------------------+--------------------+--------------------+-----------------------+\n" + ) + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, grpc_bdf_duty), + ), + mock.patch.object( + tpu_exporter, + "_run_tpu_info", + return_value=( + True, + None, + tpu_exporter.parse_tpu_info_output(cli_vfio_hbm), + ), + ), + ): + alias_snap = tpu_exporter.collect_snapshot( + sysfs_root=sb_sysfs, + dev_root=sb_dev, + proc_root=sb_proc, + tpu_info_bin="tpu-info", + tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + ) + self.assertEqual(alias_snap.devices[0].hbm_used_bytes, 50 * 1024**3) + self.assertEqual(alias_snap.devices[0].duty_cycle_percent, 66.0) + self.assertEqual(len(alias_snap.runtime_utilization), 1) + self.assertEqual(alias_snap.runtime_utilization[0].mapped_pci_bdf, "0000:00:04.0") + + # (j) Non-exclusive IOMMU group (shared with non-TPU PCI device) rejected for /dev/vfio/ mapping & attribution. + ne_sysfs, ne_dev, ne_proc = _make_mock_pci_tree( + root / "non_excl_vfio", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "7", + "numa_node": "0", + } + ], + create_vfio_nodes=["7"], + ) + extra_dev = ne_sysfs / "devices" / "0000:00:05.0" + extra_dev.mkdir(parents=True, exist_ok=True) + (ne_sysfs / "kernel" / "iommu_groups" / "7" / "devices" / "0000:00:05.0").symlink_to( + extra_dev + ) + ne_devs = tpu_exporter.discover_tpu_devices(sysfs_root=ne_sysfs, dev_root=ne_dev) + self.assertFalse(ne_devs[0].vfio_group_exclusive) + with self.assertRaisesRegex(ValueError, "non-exclusive VFIO group"): + tpu_exporter.validate_chip_id_map(ne_devs, {"/dev/vfio/7": "0"}) + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=( + True, + None, + { + "/dev/vfio/7": tpu_exporter._TpuInfoRow( + chip_key="/dev/vfio/7", + hbm_used_bytes=10 * 1024**3, + hbm_total_bytes=192 * 1024**3, + duty_cycle_percent=10.0, + in_util_table=True, + ) + }, + ), + ), + ): + ne_snap = tpu_exporter.collect_snapshot( + sysfs_root=ne_sysfs, + dev_root=ne_dev, + proc_root=ne_proc, + tpu_info_bin="tpu-info", + tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + ) + self.assertIsNone(ne_snap.devices[0].hbm_used_bytes) + self.assertIsNone(ne_snap.runtime_utilization[0].mapped_pci_bdf) + + # (k) Unified ownership collision on chiplet 2 ALSO marks D2D sibling 3 ambiguous, + # and `_verified_row_alias_map` retains explicit BDF rows on colliding v5e. + r6_col_sysfs, r6_col_dev, r6_col_proc = _make_mock_pci_tree( + root / "r6_col_sib", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + "chip_id": "2", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "1", + "chip_id": "2", + }, + { + "bdf": "0000:80:01.0", + "vendor": "0x1ae0", + "device": "0x0063", + "driver": "vfio-pci", + "iommu_group": "2", + "numa_node": "1", + "chip_id": "3", + }, + ], + create_vfio_nodes=["0", "1", "2"], + ) + r6_col_grpc = { + "3": tpu_exporter._TpuInfoRow( + chip_key="3", + hbm_used_bytes=10 * 1024**3, + hbm_total_bytes=16 * 1024**3, + duty_cycle_percent=50.0, + in_util_table=True, + ), + "0000:80:01.0": tpu_exporter._TpuInfoRow( + chip_key="0000:80:01.0", + hbm_used_bytes=11 * 1024**3, + hbm_total_bytes=16 * 1024**3, + duty_cycle_percent=77.0, + in_util_table=True, + ), + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, r6_col_grpc), + ), + mock.patch.object( + tpu_exporter, "_run_tpu_info", return_value=(False, "disabled", {}) + ), + ): + for map_kwargs in ( + {"physical_chip_map": {"0000:00:04.0": 1}}, + {"chip_id_map": {"0000:00:04.0": "2"}}, + ): + r6_col_snap = tpu_exporter.collect_snapshot( + sysfs_root=r6_col_sysfs, + dev_root=r6_col_dev, + proc_root=r6_col_proc, + tpu_info_bin="tpu-info", + tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + **map_kwargs, + ) + self.assertIsNone(r6_col_snap.devices[0].hbm_used_bytes) + self.assertIsNone(r6_col_snap.devices[1].hbm_used_bytes) + self.assertEqual(r6_col_snap.devices[2].duty_cycle_percent, 77.0) + self.assertEqual(r6_col_snap.devices[2].hbm_used_bytes, 11 * 1024**3) + self.assertIsNone( + next( + r for r in r6_col_snap.runtime_utilization if r.runtime_chip == "3" + ).mapped_pci_bdf + ) + + # (l) `_has_complete_utilization`: ignores unknown /dev/vfio/999 AND counts verified unmapped BDF on mixed host. + self.assertFalse( + tpu_exporter._has_complete_utilization( + { + "/dev/vfio/999": tpu_exporter._TpuInfoRow( + chip_key="/dev/vfio/999", + hbm_used_bytes=1024, + hbm_total_bytes=1024, + duty_cycle_percent=1.0, + in_util_table=True, + ) + }, + min_expected_rows=1, + verified_row_aliases={"0000:00:04.0": "0000:00:04.0"}, + ) + ) + self.assertTrue( + tpu_exporter._has_complete_utilization( + { + "0": tpu_exporter._TpuInfoRow( + chip_key="0", + hbm_used_bytes=1024, + hbm_total_bytes=1024, + duty_cycle_percent=1.0, + in_util_table=True, + ), + "0000:00:05.0": tpu_exporter._TpuInfoRow( + chip_key="0000:00:05.0", + hbm_used_bytes=1024, + hbm_total_bytes=1024, + duty_cycle_percent=2.0, + in_util_table=True, + ), + }, + expected_runtime_ids={"0"}, + min_expected_rows=2, + verified_row_aliases={ + "0000:00:04.0": "0", + "0": "0", + "0000:00:05.0": "0000:00:05.0", + }, + ) + ) + + # (m) Empty /sys/kernel/iommu_groups//devices dir fails exclusivity cleanly. + empty_grp_sys, empty_grp_dev, _ = _make_mock_pci_tree( + root / "empty_iommu_grp_devs", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "8", + "numa_node": "0", + } + ], + create_vfio_nodes=["8"], + ) + shutil.rmtree(empty_grp_sys / "kernel" / "iommu_groups" / "8" / "devices") + (empty_grp_sys / "kernel" / "iommu_groups" / "8" / "devices").mkdir(parents=True) + eg_devs = tpu_exporter.discover_tpu_devices( + sysfs_root=empty_grp_sys, dev_root=empty_grp_dev + ) + self.assertFalse(eg_devs[0].vfio_group_exclusive) + + # (n) Summed chiplet HBM + package BDF duty/bandwidth readings combine without dropping package duty/bw. + combo_grpc = { + "0": tpu_exporter._TpuInfoRow( + chip_key="0", + hbm_used_bytes=10 * 1024**3, + hbm_total_bytes=96 * 1024**3, + in_util_table=True, + ), + "1": tpu_exporter._TpuInfoRow( + chip_key="1", + hbm_used_bytes=20 * 1024**3, + hbm_total_bytes=96 * 1024**3, + in_util_table=True, + ), + "0000:00:04.0": tpu_exporter._TpuInfoRow( + chip_key="0000:00:04.0", + hbm_total_bytes=192 * 1024**3, + duty_cycle_percent=65.0, + hbm_bw_util_percent=42.0, + in_util_table=True, + ), + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, combo_grpc), + ), + ): + combo_snap = tpu_exporter.collect_snapshot( + sysfs_root=sb_sysfs, + dev_root=sb_dev, + proc_root=sb_proc, + tpu_info_bin="tpu-info", + tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + physical_chip_map={"0000:00:04.0": 0}, + ) + self.assertEqual(combo_snap.devices[0].hbm_used_bytes, 30 * 1024**3) + self.assertEqual(combo_snap.devices[0].duty_cycle_percent, 65.0) + self.assertEqual(combo_snap.devices[0].hbm_bandwidth_utilization_percent, 42.0) + + # (o) Orphaned 0x0076 reporting chip_id="1" reserves plausible logical IDs {0,1,2,3} + # so colocated unmapped v6e reporting chip_id="2" does not steal runtime row "2". + orp_sysfs, orp_dev, orp_proc = _make_mock_pci_tree( + root / "r7_orphan_76", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + "chip_id": "1", + }, + { + "bdf": "0000:80:00.0", + "vendor": "0x1ae0", + "device": "0x006f", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "1", + "chip_id": "2", + }, + ], + create_vfio_nodes=["0", "1"], + ) + orp_grpc = { + "2": tpu_exporter._TpuInfoRow( + chip_key="2", + hbm_used_bytes=22 * 1024**3, + hbm_total_bytes=32 * 1024**3, + duty_cycle_percent=55.0, + in_util_table=True, + ), + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object( + tpu_exporter, + "_query_grpc_runtime_metrics", + return_value=(True, None, orp_grpc), + ), + mock.patch.object( + tpu_exporter, "_run_tpu_info", return_value=(False, "disabled", {}) + ), + ): + orp_snap = tpu_exporter.collect_snapshot( + sysfs_root=orp_sysfs, + dev_root=orp_dev, + proc_root=orp_proc, + tpu_info_bin="tpu-info", + tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", + shm_root=root / "no-shm", + ) + self.assertIsNone(orp_snap.devices[1].runtime_chip_id) + self.assertIsNone(orp_snap.devices[1].hbm_used_bytes) + self.assertIsNone( + next(r for r in orp_snap.runtime_utilization if r.runtime_chip == "2").mapped_pci_bdf + ) + + # (p) Contradictory physical_chip_map and chip_id_map rejected on 2-fn 0x0076 pair. + _make_mock_pci_tree( + root / "r7_phys_contra", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "0", + "numa_node": "0", + }, + { + "bdf": "0000:00:04.1", + "vendor": "0x1ae0", + "device": "0x0076", + "driver": "vfio-pci", + "iommu_group": "1", + "numa_node": "0", + }, + ], + create_vfio_nodes=["0", "1"], + ) + c_sysfs = root / "r7_phys_contra" / "sys" + c_dev = root / "r7_phys_contra" / "dev" + c_devs = tpu_exporter.discover_tpu_devices(sysfs_root=c_sysfs, dev_root=c_dev) + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + c_devs, + {"0000:00:04.0": "0", "0000:00:04.1": "1"}, + physical_chip_map={"0000:00:04.0": 4, "0000:00:04.1": 4}, + ) + _c_res, c_amb, _c_pairs, _c_amb_p = tpu_exporter._collect_unified_logical_ownership( + c_devs, + set(), + {"0000:00:04.0": "0", "0000:00:04.1": "1"}, + set(), + physical_chip_map={"0000:00:04.0": 4, "0000:00:04.1": 4}, + ) + self.assertTrue({"0", "1", "8", "9"}.issubset(c_amb)) + + # (q) _has_complete_utilization preserves verified BDF coverage when extra numeric row "7" is added. + r7_rows = { + "0": tpu_exporter._TpuInfoRow( + chip_key="0", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True + ), + "0000:00:05.0": tpu_exporter._TpuInfoRow( + chip_key="0000:00:05.0", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True + ), + "0000:00:06.0": tpu_exporter._TpuInfoRow( + chip_key="0000:00:06.0", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True + ), + } + r7_aliases = {"0": "0", "0000:00:05.0": "0000:00:05.0", "0000:00:06.0": "0000:00:06.0"} + self.assertTrue( + tpu_exporter._has_complete_utilization( + r7_rows, + expected_runtime_ids={"0"}, + min_expected_rows=3, + verified_row_aliases=r7_aliases, + ) + ) + r7_rows_extra = dict(r7_rows) + r7_rows_extra["7"] = tpu_exporter._TpuInfoRow( + chip_key="7", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True + ) + self.assertTrue( + tpu_exporter._has_complete_utilization( + r7_rows_extra, + expected_runtime_ids={"0"}, + min_expected_rows=3, + verified_row_aliases=r7_aliases, + ) + ) + + # (r) Incomplete kernel IOMMU group listing only a bridge yields healthy=False and non-exclusive. + br_only_sys, br_only_dev, _ = _make_mock_pci_tree( + root / "r7_iommu_bridge_only", + devices=[ + { + "bdf": "0000:00:04.0", + "vendor": "0x1ae0", + "device": "0x0075", + "driver": "vfio-pci", + "iommu_group": "9", + "numa_node": "0", + } + ], + create_vfio_nodes=["9"], + ) + iommu_devs_dir = br_only_sys / "kernel" / "iommu_groups" / "9" / "devices" + for item in list(iommu_devs_dir.iterdir()): + item.unlink() + bridge_node = br_only_sys / "bus" / "pci" / "devices" / "0000:00:01.0" + bridge_node.mkdir(parents=True) + (bridge_node / "class").write_text("0x060400\n", encoding="utf-8") + (bridge_node / "driver").symlink_to("pcieport") + (iommu_devs_dir / "0000:00:01.0").symlink_to(bridge_node) + with _mock_vfio_char_lstat(): + br_only_devs = tpu_exporter.discover_tpu_devices( + sysfs_root=br_only_sys, dev_root=br_only_dev + ) + self.assertFalse(br_only_devs[0].healthy) + self.assertFalse(br_only_devs[0].vfio_group_exclusive) + + # (s) Proved per-core 0x0076 slot (2,3) + orphaned slot (0) reserves sibling "1" against v6e sysfs "1". + osib_sys, osib_dev, osib_proc = _make_mock_pci_tree( + root / "r8_orphan_sib", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "2"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "3"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "0"}, + {"bdf": "0000:80:00.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "3", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + osib_grpc = { + "1": tpu_exporter._TpuInfoRow( + chip_key="1", hbm_used_bytes=9 * 1024**3, hbm_total_bytes=32 * 1024**3, duty_cycle_percent=40.0, in_util_table=True + ), + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object(tpu_exporter, "_query_grpc_runtime_metrics", return_value=(True, None, osib_grpc)), + mock.patch.object(tpu_exporter, "_run_tpu_info", return_value=(False, "disabled", {})), + ): + osib_snap = tpu_exporter.collect_snapshot( + sysfs_root=osib_sys, dev_root=osib_dev, proc_root=osib_proc, + tpu_info_bin="tpu-info", tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", shm_root=root / "no-shm", + ) + self.assertIsNone(osib_snap.devices[3].runtime_chip_id) + self.assertIsNone(osib_snap.devices[3].hbm_used_bytes) + + # (t) Slot-level physical_chip_map vs sibling chip_id_map + conflicting sysfs physical ID (1,1 vs phys 4). + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + c_devs, + {"0000:00:04.1": "1"}, + physical_chip_map={"0000:00:04.0": 4}, + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=c_sysfs, dev_root=c_dev, proc_root=root / "no-proc", + tpu_info_bin="tpu-info", tpu_info_timeout_s=2.0, + chip_id_map={"0000:00:04.1": "1"}, + physical_chip_map={"0000:00:04.0": 4}, + runtime_metrics_addr="127.0.0.1:8431", shm_root=root / "no-shm", + ) + _s_res, s_amb, _s_p, _s_ap = tpu_exporter._collect_unified_logical_ownership( + c_devs, set(), {"0000:00:04.1": "1"}, set(), + physical_chip_map={"0000:00:04.0": 4}, + ) + self.assertTrue({"0", "1", "8", "9"}.issubset(s_amb)) + conf_sys, conf_dev, conf_proc = _make_mock_pci_tree( + root / "r8_sysfs_vs_phys", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + {"bdf": "0000:80:00.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "2"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + conf_grpc = { + "2": tpu_exporter._TpuInfoRow( + chip_key="2", hbm_used_bytes=12 * 1024**3, hbm_total_bytes=32 * 1024**3, duty_cycle_percent=50.0, in_util_table=True + ), + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object(tpu_exporter, "_query_grpc_runtime_metrics", return_value=(True, None, conf_grpc)), + mock.patch.object(tpu_exporter, "_run_tpu_info", return_value=(False, "disabled", {})), + ): + conf_snap = tpu_exporter.collect_snapshot( + sysfs_root=conf_sys, dev_root=conf_dev, proc_root=conf_proc, + tpu_info_bin="tpu-info", tpu_info_timeout_s=2.0, + physical_chip_map={"0000:00:04.0": 4, "0000:00:04.1": 4}, + runtime_metrics_addr="127.0.0.1:8431", shm_root=root / "no-shm", + ) + self.assertIsNone(conf_snap.devices[2].runtime_chip_id) + self.assertIsNone(conf_snap.devices[2].hbm_used_bytes) + + # (u) `_has_complete_utilization(..., verified_row_aliases=None)` stays monotonic with extra numeric row. + r8_noalias_rows = { + "0000:00:04.0": tpu_exporter._TpuInfoRow(chip_key="0000:00:04.0", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True), + "0000:00:05.0": tpu_exporter._TpuInfoRow(chip_key="0000:00:05.0", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True), + } + self.assertTrue(tpu_exporter._has_complete_utilization(r8_noalias_rows, min_expected_rows=2)) + r8_noalias_rows["7"] = tpu_exporter._TpuInfoRow(chip_key="7", hbm_used_bytes=1, hbm_total_bytes=2, duty_cycle_percent=10.0, in_util_table=True) + self.assertTrue(tpu_exporter._has_complete_utilization(r8_noalias_rows, min_expected_rows=2)) + + # (v) Conflicting sysfs physical ID (1,1) + explicit physical=4 & logical=8,9 retains {2,3} reservation against v6e "2". + with ( + _mock_vfio_char_lstat(), + mock.patch.object(tpu_exporter, "_query_grpc_runtime_metrics", return_value=(True, None, conf_grpc)), + mock.patch.object(tpu_exporter, "_run_tpu_info", return_value=(False, "disabled", {})), + ): + conf_both_snap = tpu_exporter.collect_snapshot( + sysfs_root=conf_sys, dev_root=conf_dev, proc_root=conf_proc, + tpu_info_bin="tpu-info", tpu_info_timeout_s=2.0, + physical_chip_map={"0000:00:04.0": 4, "0000:00:04.1": 4}, + chip_id_map={"0000:00:04.0": "8", "0000:00:04.1": "9"}, + runtime_metrics_addr="127.0.0.1:8431", shm_root=root / "no-shm", + ) + self.assertEqual(conf_both_snap.devices[0].runtime_chip_id, "8") + self.assertEqual(conf_both_snap.devices[1].runtime_chip_id, "9") + self.assertIsNone(conf_both_snap.devices[2].runtime_chip_id) + self.assertIsNone(conf_both_snap.devices[2].hbm_used_bytes) + + # (w) Slot physical mapping still constrains 04.1 when sibling 04.0 is absent from PCI sysfs. + abs0_sys, abs0_dev, abs0_proc = _make_mock_pci_tree( + root / "r9_abs_sib0", + devices=[ + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["1"], + ) + abs0_devs = tpu_exporter.discover_tpu_devices(sysfs_root=abs0_sys, dev_root=abs0_dev) + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + abs0_devs, {"0000:00:04.1": "1"}, physical_chip_map={"0000:00:04.0": 4} + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=abs0_sys, dev_root=abs0_dev, proc_root=abs0_proc, + tpu_info_bin="tpu-info", tpu_info_timeout_s=2.0, + chip_id_map={"0000:00:04.1": "1"}, + physical_chip_map={"0000:00:04.0": 4}, + runtime_metrics_addr="127.0.0.1:8431", shm_root=root / "no-shm", + ) + + # (x) Cross-package chip_id_map on proved 0x0076 sibling slot rejected even without physical_chip_map. + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + c_devs, {"0000:00:04.0": "0", "0000:00:04.1": "2"} + ) + _x_res, x_amb, _x_p, _x_ap = tpu_exporter._collect_unified_logical_ownership( + c_devs, set(), {"0000:00:04.0": "0", "0000:00:04.1": "2"}, set() + ) + self.assertTrue({"0", "1", "2", "3"}.issubset(x_amb)) + + # Round-10 regressions: + # (y) Proved 2-fn slot 04 mapped to 0 reserves sibling row 1 against outside slot 05->1, + # and separate-slot 0x0075 functions sharing sysfs chip_id=1 reject cross-package maps 0,4. + y_sys, y_dev, y_proc = _make_mock_pci_tree( + root / "r10_slot_reserve", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + y_devs = tpu_exporter.discover_tpu_devices(sysfs_root=y_sys, dev_root=y_dev) + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + y_devs, {"0000:00:04.0": "0", "0000:00:05.0": "1"} + ) + _y_res, y_amb, _y_p, _y_ap = tpu_exporter._collect_unified_logical_ownership( + y_devs, set(), {"0000:00:04.0": "0", "0000:00:05.0": "1"}, set() + ) + self.assertIn("1", y_amb) + + sep_sib_sys, sep_sib_dev, sep_sib_proc = _make_mock_pci_tree( + root / "r10_sep_slot_siblings", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + sep_sib_devs = tpu_exporter.discover_tpu_devices(sysfs_root=sep_sib_sys, dev_root=sep_sib_dev) + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + sep_sib_devs, {"0000:00:04.0": "0", "0000:00:05.0": "4"} + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=sep_sib_sys, dev_root=sep_sib_dev, proc_root=sep_sib_proc, + tpu_info_bin=None, chip_id_map={"0000:00:04.0": "0", "0000:00:05.0": "4"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (z) 1-fn Ironwood reporting sysfs chip_id=1 retains claim on {2,3} against v6e sysfs chip_id=2. + mix_1fn_sys, mix_1fn_dev, mix_1fn_proc = _make_mock_pci_tree( + root / "r10_1fn_vs_v6e", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "2"}, + ], + create_vfio_nodes=["0", "1"], + ) + mix_1fn_grpc = { + "2": tpu_exporter._TpuInfoRow( + chip_key="2", hbm_used_bytes=3 * 1024**3, hbm_total_bytes=32 * 1024**3, duty_cycle_percent=20.0, in_util_table=True + ), + } + with ( + _mock_vfio_char_lstat(), + mock.patch.object(tpu_exporter, "_query_grpc_runtime_metrics", return_value=(True, None, mix_1fn_grpc)), + mock.patch.object(tpu_exporter, "_run_tpu_info", return_value=(False, "disabled", {})), + ): + mix_snap = tpu_exporter.collect_snapshot( + sysfs_root=mix_1fn_sys, dev_root=mix_1fn_dev, proc_root=mix_1fn_proc, + tpu_info_bin="tpu-info", tpu_info_timeout_s=2.0, + runtime_metrics_addr="127.0.0.1:8431", shm_root=root / "no-shm", + ) + self.assertIsNone(mix_snap.devices[1].runtime_chip_id) + self.assertIsNone(mix_snap.devices[1].hbm_used_bytes) + + # (aa) Hot-unplugged 04.0 still catches conflicting 04.0->0, 04.1->2 in chip_id_map on 0x0076 04.1. + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + abs0_devs, {"0000:00:04.0": "0", "0000:00:04.1": "2"} + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=abs0_sys, dev_root=abs0_dev, proc_root=abs0_proc, + tpu_info_bin=None, chip_id_map={"0000:00:04.0": "0", "0000:00:04.1": "2"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (ab) Physical map alone (slot conflict or >2 functions on one package) rejected at startup and snapshot. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=y_sys, dev_root=y_dev, proc_root=y_proc, + tpu_info_bin=None, physical_chip_map={"0000:00:04.0": 0, "0000:00:04.1": 4}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=y_sys, dev_root=y_dev, proc_root=y_proc, + tpu_info_bin=None, + physical_chip_map={"0000:00:04.0": 4, "0000:00:04.1": 4, "0000:00:05.0": 4}, + chip_id_map={"0000:00:05.0": "8"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + with _mock_vfio_char_lstat(): + self.assertEqual( + tpu_exporter.main( + [ + "--sysfs-root", str(y_sys), + "--dev-root", str(y_dev), + "--proc-root", str(y_proc), + "--physical-chip-map", '{"0000:00:04.0":0,"0000:00:04.1":4}', + ] + ), + 1, + ) + + # (ac) Contradictory BDF + VFIO alias keys targeting one exclusive device rejected. + with self.assertRaises(ValueError): + tpu_exporter.validate_chip_id_map( + y_devs, + { + "0000:00:04.0": "0", + "/dev/vfio/0": "2", + "0000:00:04.1": "1", + }, + ) + + # Round-11 regressions: + # (ad) Complete 2-fn slot 04.{0,1} excludes members from cross-slot sysfs pairing (7,8,7). + ad_sys, ad_dev, ad_proc = _make_mock_pci_tree( + root / "r11_slot_before_cross", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "7"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "8"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "7"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=ad_sys, dev_root=ad_dev, proc_root=ad_proc, + tpu_info_bin=None, chip_id_map={"0000:00:04.0": "0", "0000:00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + _ad_r, ad_amb, _ad_p, _ad_ap = tpu_exporter._collect_unified_logical_ownership( + tpu_exporter.discover_tpu_devices(sysfs_root=ad_sys, dev_root=ad_dev), + set(), + {"0000:00:04.0": "0", "0000:00:05.0": "1"}, + set(), + ) + self.assertIn("1", ad_amb) + + # (ae) Hot-unplugged 04.0 mapped to 0 with 04.1 & 05.0 visible reserves {0,1} for slot 04. + ae_sys, ae_dev, ae_proc = _make_mock_pci_tree( + root / "r11_absent_sib_reserve", + devices=[ + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2"}, + ], + create_vfio_nodes=["1", "2"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=ae_sys, dev_root=ae_dev, proc_root=ae_proc, + tpu_info_bin=None, chip_id_map={"00:04.0": "0", "00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + _ae_r, ae_amb, _ae_p, _ae_ap = tpu_exporter._collect_unified_logical_ownership( + tpu_exporter.discover_tpu_devices(sysfs_root=ae_sys, dev_root=ae_dev), + set(), + {"00:04.0": "0", "00:05.0": "1"}, + set(), + ) + self.assertIn("1", ae_amb) + + # (af) Unmapped 1-fn Ironwood with chip_id=1 reserves {2,3} even against explicit v6e->2 map. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=mix_1fn_sys, dev_root=mix_1fn_dev, proc_root=mix_1fn_proc, + tpu_info_bin=None, chip_id_map={"0000:00:05.0": "2"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + _af_r, af_amb, _af_p, _af_ap = tpu_exporter._collect_unified_logical_ownership( + tpu_exporter.discover_tpu_devices(sysfs_root=mix_1fn_sys, dev_root=mix_1fn_dev), + set(), + {"0000:00:05.0": "2"}, + {"0000:00:04.0"}, + ) + self.assertIn("2", af_amb) + + # (ag) Separate-slot siblings proved by shared chip_id=7 propagate --physical-chip-map and reject conflict. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=sep_sib_sys, dev_root=sep_sib_dev, proc_root=sep_sib_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 4}, + chip_id_map={"00:05.0": "2"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=sep_sib_sys, dev_root=sep_sib_dev, proc_root=sep_sib_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 1, "00:05.0": 2}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (ah) --tpu7x-pci-layout=1fn contradicts 0x0076 / multifunction slot and is rejected. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=y_sys, dev_root=y_dev, proc_root=y_proc, + tpu_info_bin=None, + chip_id_map={"0000:00:04.0": "0", "0000:00:04.1": "2"}, + tpu7x_pci_layout="1fn", + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (ai) Physical package spanning two distinct NUMA domains is rejected. + cross_dom_sys, cross_dom_dev, cross_dom_proc = _make_mock_pci_tree( + root / "r11_cross_dom_phys", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "numa_node": "0"}, + {"bdf": "0000:80:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "numa_node": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=cross_dom_sys, dev_root=cross_dom_dev, proc_root=cross_dom_proc, + tpu_info_bin=None, + physical_chip_map={"0000:00:04.0": 4, "0000:80:05.0": 4}, + chip_id_map={"0000:00:04.0": "8", "0000:80:05.0": "9"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (aj) Legacy v2/v3 0x0027 sibling pair accepts identical physical IDs and rejects mismatch. + v2_sys, v2_dev, v2_proc = _make_mock_pci_tree( + root / "r11_v2_phys", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0027", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0027", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with _mock_vfio_char_lstat(): + v2_snap = tpu_exporter.collect_snapshot( + sysfs_root=v2_sys, dev_root=v2_dev, proc_root=v2_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0, "00:04.1": 0}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + self.assertEqual(len(v2_snap.devices), 1) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=v2_sys, dev_root=v2_dev, proc_root=v2_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0, "00:04.1": 1}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (ak) Direct collect_snapshot rejects short-BDF physical-chip-map slot conflicts. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=y_sys, dev_root=y_dev, proc_root=y_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0, "00:04.1": 4}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (al) R12-1: `--tpu7x-pci-layout=1fn` rejects 0x0075 separate slots proved 2-fn by shared chip_id. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=sep_sib_sys, dev_root=sep_sib_dev, proc_root=sep_sib_proc, + tpu_info_bin=None, + chip_id_map={"00:04.0": "0", "00:05.0": "2"}, + tpu7x_pci_layout="1fn", + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (am) R12-2: Absent mapped sibling `04.1->0` marks live `0x0075` `04.0` as 2-fn & blocks v6e->1. + mix_absent_sys, mix_absent_dev, mix_absent_proc = _make_mock_pci_tree( + root / "r12_mix_0075_absent_sib", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=mix_absent_sys, dev_root=mix_absent_dev, proc_root=mix_absent_proc, + tpu_info_bin=None, + chip_id_map={"00:04.1": "0", "00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + _am_devs = tpu_exporter.discover_tpu_devices( + sysfs_root=mix_absent_sys, dev_root=mix_absent_dev, + chip_id_map={"00:04.1": "0", "00:05.0": "1"}, + ) + self.assertEqual(_am_devs[0].hbm_nominal_bytes, 96 * (1024**3)) + _am_r, am_amb, _am_p, _am_ap = tpu_exporter._collect_unified_logical_ownership( + _am_devs, set(), {"00:04.1": "0", "00:05.0": "1"}, set(), + ) + self.assertIn("1", am_amb) + + # (an) R12-3: Physical map on `04.0->0` reserves `{0,1}` against unrelated `05.0->1` in collect_snapshot. + sep2_sys, sep2_dev, sep2_proc = _make_mock_pci_tree( + root / "r12_sep_phys_res", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + an_cli_sh = root / "mock-an-tpu-info.sh" + an_cli_sh.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| 0 | 2.0 GiB / 96.0 GiB | [##........] 2.1% | 5.0% | 10.0% |\n" + "| 1 | 3.0 GiB / 96.0 GiB | [##........] 3.1% | 6.0% | 20.0% |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + an_cli_sh.chmod(0o755) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=sep2_sys, dev_root=sep2_dev, proc_root=sep2_proc, + tpu_info_bin=str(an_cli_sh), + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + with _mock_vfio_char_lstat(), mock.patch.object(tpu_exporter, "validate_chip_id_map"): + an_snap = tpu_exporter.collect_snapshot( + sysfs_root=sep2_sys, dev_root=sep2_dev, proc_root=sep2_proc, + tpu_info_bin=str(an_cli_sh), + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + self.assertTrue(all(d.hbm_used_bytes is None for d in an_snap.devices)) + self.assertIsNone( + next(rt for rt in an_snap.runtime_utilization if rt.runtime_chip == "1").mapped_pci_bdf + ) + _an_r, an_amb, _an_p, _an_ap = tpu_exporter._collect_unified_logical_ownership( + tpu_exporter.discover_tpu_devices(sysfs_root=sep2_sys, dev_root=sep2_dev), + set(), {"00:05.0": "1"}, set(), physical_chip_map={"00:04.0": 0}, + ) + self.assertIn("1", an_amb) + + # (ao) R12-4: Proved `0x0076` siblings sharing `chip_id=1` reserve `{2,3}` against explicit v6e->2. + mix_slot_sys, mix_slot_dev, mix_slot_proc = _make_mock_pci_tree( + root / "r12_proved_0076_res", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "2"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=mix_slot_sys, dev_root=mix_slot_dev, proc_root=mix_slot_proc, + tpu_info_bin=None, chip_id_map={"00:05.0": "2"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + _ao_r, ao_amb, _ao_p, _ao_ap = tpu_exporter._collect_unified_logical_ownership( + tpu_exporter.discover_tpu_devices(sysfs_root=mix_slot_sys, dev_root=mix_slot_dev), + set(), {"00:05.0": "2"}, set(), + ) + self.assertIn("2", ao_amb) + + # (ap) R12-5: Oversized 3-function slot excluded from pairing and runtime joins. + ov3_sys, ov3_dev, ov3_proc = _make_mock_pci_tree( + root / "r12_oversized3", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1"}, + {"bdf": "0000:00:04.2", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + ov3_cli_sh = root / "mock-ov3-tpu-info.sh" + ov3_cli_sh.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| 0 | 2.0 GiB / 96.0 GiB | [##........] 2.1% | 5.0% | 10.0% |\n" + "| 1 | 3.0 GiB / 96.0 GiB | [##........] 3.1% | 6.0% | 20.0% |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + ov3_cli_sh.chmod(0o755) + with _mock_vfio_char_lstat(): + ov3_snap = tpu_exporter.collect_snapshot( + sysfs_root=ov3_sys, dev_root=ov3_dev, proc_root=ov3_proc, + tpu_info_bin=str(ov3_cli_sh), + chip_id_map={"00:04.0": "0", "00:04.2": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + self.assertEqual(len(ov3_snap.runtime_utilization), 2) + self.assertTrue(all(d.runtime_chip_id is None and d.hbm_used_bytes is None for d in ov3_snap.devices)) + self.assertTrue(all(rt.mapped_pci_bdf is None for rt in ov3_snap.runtime_utilization)) + + # (aq) R12-6/7/12/13: NUMA-split D2D logical map rejected; 0x0027 sibling physical conflict rejected; + # malformed UTF-8/0xff sysfs chip_id ignored; separate `.1` siblings NOT paired. + numa_split_sys, numa_split_dev, numa_split_proc = _make_mock_pci_tree( + root / "r12_numa_split_map", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "numa_node": "0"}, + {"bdf": "0000:80:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "numa_node": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=numa_split_sys, dev_root=numa_split_dev, proc_root=numa_split_proc, + tpu_info_bin=None, chip_id_map={"0000:00:04.0": "0", "0000:80:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=v2_sys, dev_root=v2_dev, proc_root=v2_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.1": 0}, + chip_id_map={"00:04.0": "2"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + (sep2_sys / "bus" / "pci" / "devices" / "0000:00:04.0" / "chip_id").write_bytes(b"\xc2\xa01\xc2\xa0") + (sep2_sys / "bus" / "pci" / "devices" / "0000:00:05.0" / "chip_id").write_bytes(b"\xff") + mal_devs = tpu_exporter.discover_tpu_devices(sysfs_root=sep2_sys, dev_root=sep2_dev) + self.assertIsNone(mal_devs[0].runtime_chip_id) + self.assertIsNone(mal_devs[1].runtime_chip_id) + fn1_sys, fn1_dev, _fn1_proc = _make_mock_pci_tree( + root / "r12_sep_fn1", + devices=[ + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "1"}, + {"bdf": "0000:00:05.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + fn1_devs = tpu_exporter.discover_tpu_devices(sysfs_root=fn1_sys, dev_root=fn1_dev) + _f1, _f2, fn1_ptok, *_rest = tpu_exporter._resolve_tpu7x_slot_and_pkg_maps(fn1_devs, set(), None) + self.assertEqual(fn1_ptok, {}) + + # (ar) R13-2: Explicit physical_chip_map=0 on 0x0076 04.0 reserves row 1 even when 04.0->0 mapped. + r13_2_sys, r13_2_dev, r13_2_proc = _make_mock_pci_tree( + root / "r13_2_phys_res", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=r13_2_sys, dev_root=r13_2_dev, proc_root=r13_2_proc, + tpu_info_bin=str(an_cli_sh), + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:04.0": "0", "00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + with _mock_vfio_char_lstat(), mock.patch.object(tpu_exporter, "validate_chip_id_map"): + r13_2_snap = tpu_exporter.collect_snapshot( + sysfs_root=r13_2_sys, dev_root=r13_2_dev, proc_root=r13_2_proc, + tpu_info_bin=str(an_cli_sh), + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:04.0": "0", "00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + self.assertIsNone(r13_2_snap.devices[1].hbm_used_bytes) + self.assertIsNone( + next(rt for rt in r13_2_snap.runtime_utilization if rt.runtime_chip == "1").mapped_pci_bdf + ) + + # (as) R13-3: Invalid slot IDs `4,6` do NOT prove per-core numbering for `05.0` (`chip_id=1`). + r13_3_sys, r13_3_dev, r13_3_proc = _make_mock_pci_tree( + root / "r13_3_bad_slot_ids", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "4"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "6"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + r13_3_devs = tpu_exporter.discover_tpu_devices(sysfs_root=r13_3_sys, dev_root=r13_3_dev) + r13_3_rt, _ = tpu_exporter._resolve_raw_device_runtime_ids(r13_3_devs, set(), None) + self.assertIsNone(r13_3_rt.get("0000:00:05.0")) + + # (at) R13-4: Logical map pairing separate nonzero functions `04.1->0`, `05.1->1` rejected. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=fn1_sys, dev_root=fn1_dev, proc_root=r13_3_proc, + tpu_info_bin=None, chip_id_map={"00:04.1": "0", "00:05.1": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (au) R13-5: Absent third function `04.2->1` on live `04.0/.1` rejected as oversized slot. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=y_sys, dev_root=y_dev, proc_root=y_proc, + tpu_info_bin=None, chip_id_map={"00:04.0": "0", "00:04.2": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (av) R13-6: Collapsed 0x0027 sibling logical key `04.1->2` collides with v6e `05.0->2`. + v2_mix_sys, v2_mix_dev, v2_mix_proc = _make_mock_pci_tree( + root / "r13_6_v2_mix", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0027", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0027", "driver": "vfio-pci", "iommu_group": "1"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "2"}, + ], + create_vfio_nodes=["0", "1", "2"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=v2_mix_sys, dev_root=v2_mix_dev, proc_root=v2_mix_proc, + tpu_info_bin=None, chip_id_map={"00:04.1": "2", "00:05.0": "2"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (aw) R13-19: Explicit `--tpu7x-pci-layout 1fn` fails closed at startup without maps. + self.assertEqual( + tpu_exporter.main( + [ + "--sysfs-root", str(y_sys), + "--dev-root", str(y_dev), + "--tpu7x-pci-layout", "1fn", + ] + ), + 1, + ) + + # (ax) R14-7: Oversized 3-fn slot (`04.0/.1/.2` with `4, 5, missing`) must NOT establish + # per-core numbering for separate `05.0` (`chip_id=1`) either directly or in full snapshot. + r14_7_sys, r14_7_dev, r14_7_proc = _make_mock_pci_tree( + root / "r14_7_oversized_missing", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "4"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "5"}, + {"bdf": "0000:00:04.2", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "2"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "3", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1", "2", "3"], + ) + r14_7_devs = tpu_exporter.discover_tpu_devices(sysfs_root=r14_7_sys, dev_root=r14_7_dev) + r14_7_rt, _ = tpu_exporter._resolve_raw_device_runtime_ids(r14_7_devs, set(), None) + self.assertIsNone(r14_7_rt.get("0000:00:05.0")) + with _mock_vfio_char_lstat(): + r14_7_snap = tpu_exporter.collect_snapshot( + sysfs_root=r14_7_sys, dev_root=r14_7_dev, proc_root=r14_7_proc, + tpu_info_bin=str(ov3_cli_sh), runtime_metrics_addr="", shm_root=root / "no-shm", + ) + d5_14 = next(d for d in r14_7_snap.devices if d.pci_bdf == "0000:00:05.0") + self.assertIsNone(d5_14.hbm_used_bytes) + self.assertIsNone( + next(rt for rt in r14_7_snap.runtime_utilization if rt.runtime_chip == "1").mapped_pci_bdf + ) + self.assertIn("pending live hardware confirmation", d5_14.model_name) + + # (ay) R14-9: `--physical-chip-map` accepts 4x 1-fn `0x0075` `.0` mapped to 0..3 -> pairs (0,1)..(6,7). + r14_9_sys, r14_9_dev, r14_9_proc = _make_mock_pci_tree( + root / "r14_9_1fn_phys_map", + devices=[ + {"bdf": f"0000:00:{4 + i:02x}.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": str(i)} + for i in range(4) + ], + create_vfio_nodes=[str(i) for i in range(4)], + ) + r14_9_cli_sh = root / "mock-r14-9-tpu-info.sh" + r14_9_cli_sh.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + + "".join( + f"| {idx} | 1.0 GiB / 96.0 GiB | [#.........] 1.0% | 5.0% | 10.0% |\n" + for idx in range(8) + ) + + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + r14_9_cli_sh.chmod(0o755) + with _mock_vfio_char_lstat(): + r14_9_snap = tpu_exporter.collect_snapshot( + sysfs_root=r14_9_sys, dev_root=r14_9_dev, proc_root=r14_9_proc, + tpu_info_bin=str(r14_9_cli_sh), + physical_chip_map={"00:04.0": 0, "00:05.0": 1, "00:06.0": 2, "00:07.0": 3}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + self.assertEqual(len(r14_9_snap.runtime_utilization), 8) + self.assertTrue(all(rt.mapped_pci_bdf is not None for rt in r14_9_snap.runtime_utilization)) + + # (az) R15-7 & R16-6: Conflicting `--physical-chip-map {"04.0": 0}` vs `--chip-id-map {"05.0": "1"}` + # AND mixed-gen v6e `08.0->1` rejected cleanly at startup validation (`ValueError`). + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=r14_9_sys, dev_root=r14_9_dev, proc_root=r14_9_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + r16_6_sys, r16_6_dev, r16_6_proc = _make_mock_pci_tree( + root / "r16_6_mixed_gen_conflict", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:08.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=r16_6_sys, dev_root=r16_6_dev, proc_root=r16_6_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:08.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + + # (ba) R17-3: Consistent `--physical-chip-map` on `0x0076` with sysfs logical IDs + # `04.0->0, 04.1->1` preserves both telemetry-to-BDF joins without ambiguity. + r17_3_sys, r17_3_dev, r17_3_proc = _make_mock_pci_tree( + root / "r17_3_sysfs_phys_consistent", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0", "chip_id": "0"}, + {"bdf": "0000:00:04.1", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "1", "chip_id": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + r17_3_cli = root / "mock-r17-3-tpu-info.sh" + r17_3_cli.write_text( + "#!/bin/sh\n" + "cat <<'EOF'\n" + "TPU Device Status\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| Device ID | Memory Usage (Used/Total) | Memory Bar Gauge | HBM Bandwidth Util | TensorCore Duty Cycle |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "| 0 | 1.0 GiB / 96.0 GiB | [#.........] 1.0% | 5.0% | 10.0% |\n" + "| 1 | 2.0 GiB / 96.0 GiB | [#.........] 2.0% | 6.0% | 12.0% |\n" + "+-----------+---------------------------+--------------------+--------------------+-----------------------+\n" + "EOF\n", + encoding="utf-8", + ) + r17_3_cli.chmod(0o755) + with _mock_vfio_char_lstat(): + r17_3_snap = tpu_exporter.collect_snapshot( + sysfs_root=r17_3_sys, dev_root=r17_3_dev, proc_root=r17_3_proc, + tpu_info_bin=str(r17_3_cli), + physical_chip_map={"00:04.0": 0}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + by_dev_r17 = {rt.runtime_chip: rt.mapped_pci_bdf for rt in r17_3_snap.runtime_utilization} + self.assertEqual(by_dev_r17, {"0": "0000:00:04.0", "1": "0000:00:04.1"}) + self.assertEqual([d.hbm_used_bytes for d in r17_3_snap.devices], [1 * 1024**3, 2 * 1024**3]) + + # (bb) R17-4: Mixed-gen physical-vs-logical map collisions fail validation symmetrically + # for v6e physical + 1-fn Ironwood logical AND lone 2-fn Ironwood physical + v6e logical. + r17_4a_sys, r17_4a_dev, r17_4a_proc = _make_mock_pci_tree( + root / "r17_4a_v6e_phys_tpu7x_1fn_map", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x0075", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=r17_4a_sys, dev_root=r17_4a_dev, proc_root=r17_4a_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:05.0": "0"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + r17_4b_sys, r17_4b_dev, r17_4b_proc = _make_mock_pci_tree( + root / "r17_4b_lone_2fn_phys_v6e_map", + devices=[ + {"bdf": "0000:00:04.0", "vendor": "0x1ae0", "device": "0x0076", "driver": "vfio-pci", "iommu_group": "0"}, + {"bdf": "0000:00:05.0", "vendor": "0x1ae0", "device": "0x006f", "driver": "vfio-pci", "iommu_group": "1"}, + ], + create_vfio_nodes=["0", "1"], + ) + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=r17_4b_sys, dev_root=r17_4b_dev, proc_root=r17_4b_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:05.0": "0"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + # R18-2: Consistent logical map on lone 0x0076 `04.0->0` + physical `04.0->0` still reserves `1`. + with self.assertRaises(ValueError): + tpu_exporter.collect_snapshot( + sysfs_root=r17_4b_sys, dev_root=r17_4b_dev, proc_root=r17_4b_proc, + tpu_info_bin=None, + physical_chip_map={"00:04.0": 0}, + chip_id_map={"00:04.0": "0", "00:05.0": "1"}, + runtime_metrics_addr="", shm_root=root / "no-shm", + ) + def _assert_valid_prometheus_text(self, text: str) -> None: lines = [ln for ln in text.splitlines() if ln.strip()] self.assertGreater(len(lines), 0) diff --git a/ops/tpu-exporter/tpu_exporter.py b/ops/tpu-exporter/tpu_exporter.py index 8e5de33a..f767a0a1 100755 --- a/ops/tpu-exporter/tpu_exporter.py +++ b/ops/tpu-exporter/tpu_exporter.py @@ -61,11 +61,13 @@ GOOGLE_PCI_VENDOR_ID = "0x1ae0" -# Known Google Cloud TPU PCI device IDs under vendor 0x1ae0. -# Values: (generation_slug, display_name, nominal_hbm_bytes_per_pci_device) +# Google Cloud TPU PCI device IDs under vendor 0x1ae0 (provisional `tpu7x` +# `0x0075`/`0x0076` candidates pending live Day-1 `lspci -nn`). +# Values: (generation_slug, display_name, nominal_hbm_bytes_per_logical_chiplet) # Note: Ironwood (`tpu7x`, `0x0075`/`0x0076`) uses a dual-chiplet architecture -# (192 GiB per physical chip = 96 GiB per exposed PCI function/chiplet, so a -# 4-chip / 8-PCI-function VM aggregates to 8 * 96 GiB = 768 GiB). +# (96 GiB HBM3e per logical chiplet = 192 GiB per physical package; both +# 4-package 1-fn dual-chiplet `4 * 2 * 96 GiB` and 2-fn `8 * 96 GiB` layouts +# aggregate to 768 GiB total HBM3e). TPU_PCI_DEVICES: Dict[str, Tuple[str, str, int]] = { "0x0027": ("v2-v3", "TPU v2/v3", 16 * 1024**3), "0x0056": ("v4lite", "TPU v4lite", 8 * 1024**3), @@ -75,7 +77,7 @@ "0x006e": ("v6e-pf", "TPU v6e (PF)", 32 * 1024**3), "0x006f": ("v6e", "TPU v6e (Trillium)", 32 * 1024**3), "0x0075": ("tpu7x", "TPU tpu7x (Ironwood, pending live hardware confirmation #21)", 96 * 1024**3), - "0x0076": ("tpu7x", "TPU tpu7x (Ironwood)", 96 * 1024**3), + "0x0076": ("tpu7x", "TPU tpu7x (Ironwood, pending live hardware confirmation #21)", 96 * 1024**3), } # Legacy Cloud TPU v2/v3 (0x0027) expose two PCI core functions per physical chip @@ -159,12 +161,14 @@ class TpuTelemetry: hbm_bandwidth_utilization_percent: Optional[float] = None aer_correctable_total: Optional[int] = None aer_fatal_total: Optional[int] = None + sibling_pci_bdfs: List[str] = field(default_factory=list) sibling_aer_counters: Dict[str, Tuple[Optional[int], Optional[int]]] = field(default_factory=dict) sibling_iommu_groups: List[str] = field(default_factory=list) unverified_sibling_vfio: bool = False shm_hbm_allocated_bytes: Optional[int] = None mxu_active_cycles: Optional[int] = None dma_bytes_transferred: Optional[int] = None + pcie_root: str = "" @dataclass @@ -207,6 +211,25 @@ def _read_text(path: Path) -> Optional[str]: return None +def _read_sysfs_chip_id(path: Path) -> Optional[int]: + """Read sysfs `chip_id` strictly as bounded non-negative ASCII decimal (`0..65535`).""" + try: + raw = path.read_bytes() + except OSError: + return None + if b"\x00" in raw: + return None + try: + text = raw.decode("ascii") + except UnicodeDecodeError: + return None + stripped = text.strip(" \t\r\n") + if not stripped or len(stripped) > 5 or not stripped.isdigit(): + return None + val = int(stripped, 10) + return val if 0 <= val <= _MAX_RUNTIME_DEVICE_ID else None + + def _read_symlink_name(path: Path) -> Optional[str]: try: if path.is_symlink(): @@ -255,6 +278,31 @@ def _parse_bytes(value_str: str, unit_str: str) -> int: "tpu7x": 2, } +# Dual-chiplet topology metadata per generation (Issue #21, Ironwood Day-1): +# `chiplets_per_pkg` = logical TensorCore chiplets per physical package (2 on +# tpu7x Ironwood: 4 packages x 2 chiplets = 8 logical devices on +# `tpu7x-standard-4t`); `hbm_gib_per_logical_device` = HBM3e GiB per logical +# device (96 GiB on tpu7x). `0x1ae0:0x0075` is provisional pending Day-1 +# `lspci -nn` capture. +TPU_CHIPLETS_PER_PKG: Dict[str, int] = { + "tpu7x": 2, + "v5e": 1, + "v6e": 1, + "v6e-pf": 1, + "v5p": 1, + "v4": 1, + "v4lite": 1, +} +TPU_HBM_GIB_PER_LOGICAL_DEVICE: Dict[str, int] = { + "tpu7x": 96, + "v5e": 16, + "v6e": 32, + "v6e-pf": 32, + "v5p": 95, + "v4": 32, + "v4lite": 8, +} + def _read_fdinfo_flags(fdinfo_path: Path) -> Tuple[Optional[int], bool]: """Read octal open `flags:` from `/proc//fdinfo/`. @@ -280,6 +328,75 @@ def _read_fdinfo_flags(fdinfo_path: Path) -> Tuple[Optional[int], bool]: _VFIO_DEVNUM_RE = re.compile(r"^[0-9]+:[0-9]+$") +_SYSFS_PCI_ROOT_RE = re.compile(r"^pci([0-9a-fA-F]{4}:[0-9a-fA-F]{2})$") +_PCI_BDF_RE = re.compile(r"^[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-7]$") +_VFIO_PATH_RE = re.compile(r"^/dev/vfio/(?:[0-9]+|devices/vfio[0-9]+)$") +VALID_TPU7X_PCI_LAYOUTS = ("auto", "1fn", "2fn") + + +def _parse_pci_domain_bus(pci_bdf: str) -> Optional[Tuple[str, int]]: + parts = pci_bdf.strip().lower().split(":") + if len(parts) < 2: + return None + try: + return parts[0], int(parts[1], 16) + except ValueError: + return None + + +def _scan_pcie_bridge_roots(sysfs_root: Optional[Path]) -> Dict[Tuple[str, int], set[str]]: + """Map `(pci_domain_hex, bus_num)` -> set of PCIe root complexes via sysfs bridges.""" + if sysfs_root is None: + return {} + pci_devices_dir = sysfs_root / "bus" / "pci" / "devices" + bus_to_roots: Dict[Tuple[str, int], set[str]] = {} + if not pci_devices_dir.is_dir(): + return bus_to_roots + try: + entries = list(pci_devices_dir.iterdir()) + except OSError: + return bus_to_roots + for entry in entries: + sec_txt = _read_text(entry / "secondary_bus_number") + sub_txt = _read_text(entry / "subordinate_bus_number") + if not sec_txt or not sub_txt: + continue + parsed = _parse_pci_domain_bus(entry.name) + if parsed is None: + continue + dom_hex, _bridge_bus = parsed + try: + sec_bus = int(sec_txt, 0) + sub_bus = int(sub_txt, 0) + except ValueError: + continue + if not (0 <= sec_bus <= sub_bus <= 255): + continue + root = _resolve_pcie_root_complex(entry) + for bus_num in range(sec_bus, sub_bus + 1): + bus_to_roots.setdefault((dom_hex, bus_num), set()).add(root) + return bus_to_roots + + +def _pcie_root_complex(pci_bdf: str) -> str: + """Return `:` prefix from a PCI BDF when sysfs root bridge is absent.""" + parts = pci_bdf.strip().split(":") + if len(parts) >= 2: + return f"{parts[0]}:{parts[1]}" + return pci_bdf.strip() + + +def _resolve_pcie_root_complex(pci_entry: Path) -> str: + """Derive PCIe root complex (`:`) from resolved sysfs ancestry.""" + try: + resolved = Path(os.path.realpath(pci_entry)) + except OSError: + resolved = pci_entry + for part in resolved.parts: + m = _SYSFS_PCI_ROOT_RE.match(part) + if m: + return m.group(1).lower() + return _pcie_root_complex(pci_entry.name) def _read_kernel_vfio_devnum(sysfs_root: Path, group: Optional[str] = None) -> Optional[str]: @@ -594,6 +711,30 @@ def _split_table_cells(line: str) -> Optional[List[str]]: return cells +def _classify_util_row_key(raw_key: str) -> Optional[Tuple[str, str]]: + """Classify valid runtime row keys as `('id'|'bdf'|'vfio', canonical_key)`.""" + stripped = raw_key.strip() + if not stripped: + return None + parsed = _parse_runtime_device_id(stripped) + if parsed is not None: + return ("id", str(parsed)) + if _PCI_BDF_RE.fullmatch(stripped): + return ("bdf", stripped.lower()) + if _VFIO_PATH_RE.fullmatch(stripped): + return ("vfio", stripped) + return None + + +def _canonical_runtime_row_key(raw_key: str) -> str: + """Canonicalize bounded numeric IDs and recognized BDF/VFIO aliases.""" + stripped = raw_key.strip() + classified = _classify_util_row_key(stripped) + if classified is not None: + return classified[1] + return stripped + + def parse_tpu_info_output(output: str) -> Dict[str, _TpuInfoRow]: """Parse `tpu-info` stdout tables (both Unicode box and ASCII pipe styles). @@ -663,7 +804,7 @@ def parse_tpu_info_output(output: str) -> Dict[str, _TpuInfoRow]: if section not in ("chips", "utilization", "device_status", "process_monitor"): continue - chip_key = cells[0] + chip_key = _canonical_runtime_row_key(cells[0]) if cells[0] else "" if not chip_key: # Handle wrapped multi-line Rich headers where col 0 is blank. for idx, col_hdr in enumerate(cells): @@ -2393,18 +2534,278 @@ def _resolve_tpu_device_spec(device_id: str, subsystem_device: str) -> Tuple[str return TPU_PCI_DEVICES[device_id] +_SHORT_PCI_BDF_RE = re.compile(r"^[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$") +_CANON_PCI_BDF_RE = re.compile(r"^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$") + + +def _canon_map_bdf(raw_key: str) -> str: + norm = raw_key.strip().lower() + if _SHORT_PCI_BDF_RE.match(norm): + return f"0000:{norm}" + return norm + + +def _canon_physical_chip_map( + raw_map: Optional[Dict[str, int]], +) -> Optional[Dict[str, int]]: + """Validate and canonicalize `--physical-chip-map` keys (`00:04.0` -> `0000:00:04.0`).""" + if not raw_map: + return None + out: Dict[str, int] = {} + raw_sources: Dict[str, str] = {} + for raw_k, raw_v in raw_map.items(): + if not isinstance(raw_k, str) or not raw_k.strip(): + raise ValueError(f"Invalid --physical-chip-map key {raw_k!r}: expected PCI BDF") + if raw_k.strip().startswith("/"): + raise ValueError( + f"Invalid --physical-chip-map key {raw_k!r}: expected PCI BDF, not VFIO path" + ) + cb = _canon_map_bdf(raw_k) + if not _CANON_PCI_BDF_RE.match(cb): + raise ValueError( + f"Invalid --physical-chip-map PCI BDF key {raw_k!r}: expected DDDD:BB:DD.F" + ) + if isinstance(raw_v, bool): + raise ValueError( + f"Invalid --physical-chip-map value {raw_v!r} for {raw_k!r}: expected non-negative integer" + ) + parsed_v = _parse_runtime_device_id(str(raw_v).strip()) + if parsed_v is None: + raise ValueError( + f"Invalid --physical-chip-map value {raw_v!r} for {raw_k!r}: " + "expected non-negative physical chip integer" + ) + if cb in out and out[cb] != parsed_v: + raise ValueError( + f"--physical-chip-map assigns conflicting physical IDs ({out[cb]} via {raw_sources[cb]!r} " + f"and {parsed_v} via {raw_k!r}) to PCI BDF {cb}" + ) + out[cb] = parsed_v + raw_sources[cb] = raw_k + return out + + +def _tpu7x_dom_key(dev: TpuTelemetry) -> Tuple[str, Optional[int], str]: + root = dev.pcie_root or _pcie_root_complex(dev.pci_bdf) + if dev.numa_node is not None and dev.numa_node >= 0: + return ("numa", dev.numa_node, root) + return ("pcie", None, root) + + +def _tpu7x_dual_chiplet_pkg_bdfs( + devices: Sequence[TpuTelemetry], + *, + physical_chip_map: Optional[Dict[str, int]] = None, + chip_id_map: Optional[Dict[str, str]] = None, + tpu7x_pci_layout: str = "auto", + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, +) -> set[str]: + """Return BDFs of Ironwood (`tpu7x`) devices representing full 1-fn dual-chiplet packages. + + Returns an empty set when `tpu7x_pci_layout=="2fn"` or the host exhibits a + 2-function-per-package layout (provisional `0x0076` 2-fn candidate pending + Day-1 `lspci -nn`, non-`.0` PCI functions, >4 `tpu7x` PCI functions, + multifunction slot siblings, absent mapped same-slot siblings, or + same-domain shared non-negative integer sysfs `chip_id` / + `physical_chip_map` pairs). When `tpu7x_pci_layout=="1fn"`, raises + `ValueError` if any of those 2-fn topology indicators contradicts 1-fn mode. + """ + physical_chip_map = _canon_physical_chip_map(physical_chip_map) + tpu7x_devs = [d for d in devices if d.generation == "tpu7x"] + if not tpu7x_devs: + return set() + if tpu7x_pci_layout == "2fn": + return set() + + slot_counts_all: Dict[str, int] = {} + for d in tpu7x_devs: + sl = d.pci_bdf.rsplit(".", 1)[0] + slot_counts_all[sl] = slot_counts_all.get(sl, 0) + 1 + hw_two_fn = ( + any(d.device_id == "0x0076" for d in tpu7x_devs) + or any(not d.pci_bdf.endswith(".0") for d in tpu7x_devs) + or len(tpu7x_devs) > 4 + or any(cnt > 1 for cnt in slot_counts_all.values()) + ) + + slot_counts: Dict[str, int] = {} + rid_counts: Dict[Tuple[Any, int], int] = {} + phys_counts: Dict[Tuple[Any, int], int] = {} + non_tpu7x_bdfs: set[str] = set() + for d in devices: + if d.generation != "tpu7x": + non_tpu7x_bdfs.add(d.pci_bdf) + non_tpu7x_bdfs.update(d.sibling_pci_bdfs) + by_bdf = {d.pci_bdf: d for d in tpu7x_devs} + + def _dom_key(dev: Optional[TpuTelemetry], bdf: str) -> Tuple[str, Optional[int], str]: + root = (dev.pcie_root or _pcie_root_complex(bdf)) if dev else _pcie_root_complex(bdf) + if dev is not None and dev.numa_node is not None and dev.numa_node >= 0: + return ("numa", dev.numa_node, root) + return ("pcie", None, root) + + live_slot_doms: Dict[str, set[Tuple[str, Optional[int], str]]] = {} + live_bus_roots: Dict[Tuple[str, int], set[str]] = {} + live_bus_doms: Dict[Tuple[str, int], set[Tuple[str, Optional[int], str]]] = {} + live_root_doms: Dict[str, set[Tuple[str, Optional[int], str]]] = {} + for d in tpu7x_devs: + slot = d.pci_bdf.rsplit(".", 1)[0] + slot_counts[slot] = slot_counts.get(slot, 0) + 1 + dom = _dom_key(d, d.pci_bdf) + root = dom[2] + live_slot_doms.setdefault(slot, set()).add(dom) + live_root_doms.setdefault(root, set()).add(dom) + parsed_cb = _parse_pci_domain_bus(d.pci_bdf) + if parsed_cb is not None: + live_bus_roots.setdefault(parsed_cb, set()).add(root) + live_bus_doms.setdefault(parsed_cb, set()).add(dom) + parsed_rid = _parse_runtime_device_id(d.runtime_chip_id) + if parsed_rid is not None: + rid_counts[(dom, parsed_rid)] = rid_counts.get((dom, parsed_rid), 0) + 1 + + # Mapped absent siblings on a live Ironwood slot (e.g. `04.1 -> 0` when only `04.0` + # is visible) prove that slot is a 2-function package rather than a 1-fn card. + if chip_id_map: + for raw_k in chip_id_map: + if not isinstance(raw_k, str) or raw_k.strip().startswith("/"): + continue + cb = _canon_map_bdf(raw_k) + if cb in by_bdf or cb in non_tpu7x_bdfs or not _CANON_PCI_BDF_RE.match(cb): + continue + c_slot = cb.rsplit(".", 1)[0] + if c_slot in live_slot_doms: + slot_counts[c_slot] = slot_counts.get(c_slot, 0) + 1 + + map_two_fn = False + if physical_chip_map: + tpu7x_map_bdfs = {b for b in physical_chip_map if b not in non_tpu7x_bdfs} + live_roots = {d.pcie_root or _pcie_root_complex(d.pci_bdf) for d in tpu7x_devs} + + def _place_absent_map_bdf( + bdf: str, + ) -> Optional[Tuple[Tuple[str, Optional[int], str], ...]]: + slot = bdf.rsplit(".", 1)[0] + if slot in live_slot_doms: + return tuple(sorted(live_slot_doms[slot])) + parsed_cb = _parse_pci_domain_bus(bdf) + placed_root: Optional[str] = None + b_bridge_roots = ( + bridge_bus_to_roots.get(parsed_cb, set()) + if bridge_bus_to_roots and parsed_cb is not None + else set() + ) + if b_bridge_roots: + if len(b_bridge_roots) == 1: + cand = next(iter(b_bridge_roots)) + if cand in live_roots: + placed_root = cand + else: + if parsed_cb is not None and len(live_bus_roots.get(parsed_cb, set())) == 1: + cand = next(iter(live_bus_roots[parsed_cb])) + if cand in live_roots: + placed_root = cand + elif not bdf.endswith(".0"): + cand = _pcie_root_complex(bdf) + if cand in live_roots: + placed_root = cand + if placed_root is None: + return None + if parsed_cb is not None and len(live_bus_doms.get(parsed_cb, set())) == 1: + return (next(iter(live_bus_doms[parsed_cb])),) + if len(live_root_doms.get(placed_root, set())) == 1: + return (next(iter(live_root_doms[placed_root])),) + return (("pcie", None, placed_root),) + + placed_absent: Dict[str, Tuple[Tuple[str, Optional[int], str], ...]] = {} + relevant_map_bdfs: set[str] = set() + for b in tpu7x_map_bdfs: + if b in by_bdf: + relevant_map_bdfs.add(b) + continue + doms = _place_absent_map_bdf(b) + if doms: + placed_absent[b] = doms + relevant_map_bdfs.add(b) + + combined_bdfs = {d.pci_bdf for d in tpu7x_devs} | relevant_map_bdfs + if len(combined_bdfs) > 4 or any(not b.endswith(".0") for b in combined_bdfs): + map_two_fn = True + for b in relevant_map_bdfs: + dev_obj = by_bdf.get(b) + pid = int(physical_chip_map[b]) + if dev_obj is not None: + dom = _dom_key(dev_obj, b) + phys_counts[(dom, pid)] = phys_counts.get((dom, pid), 0) + 1 + else: + slot = b.rsplit(".", 1)[0] + slot_counts[slot] = slot_counts.get(slot, 0) + 1 + for dom in placed_absent.get(b, ()): + phys_counts[(dom, pid)] = phys_counts.get((dom, pid), 0) + 1 + + detected_two_fn = ( + hw_two_fn + or map_two_fn + or any(cnt >= 2 for cnt in slot_counts.values()) + or any(cnt >= 2 for cnt in rid_counts.values()) + or any(cnt >= 2 for cnt in phys_counts.values()) + ) + if detected_two_fn: + if tpu7x_pci_layout == "1fn": + raise ValueError( + "--tpu7x-pci-layout=1fn contradicts detected 2-fn Ironwood topology " + "(0x0076, non-.0 function, >4 functions, multifunction slot, or shared package evidence)" + ) + return set() + return {d.pci_bdf for d in tpu7x_devs} + + +def _apply_tpu_nominal_hbm_topology( + devices: List[TpuTelemetry], + *, + physical_chip_map: Optional[Dict[str, int]] = None, + chip_id_map: Optional[Dict[str, str]] = None, + tpu7x_pci_layout: str = "auto", + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, +) -> None: + """Compute nominal HBM bytes from `TPU_CHIPLETS_PER_PKG` and `TPU_HBM_GIB_PER_LOGICAL_DEVICE`.""" + dual_chiplet_pkg_bdfs = _tpu7x_dual_chiplet_pkg_bdfs( + devices, + physical_chip_map=physical_chip_map, + chip_id_map=chip_id_map, + tpu7x_pci_layout=tpu7x_pci_layout, + bridge_bus_to_roots=bridge_bus_to_roots, + ) + + for d in devices: + if d.hbm_nominal_bytes <= 0: + continue + per_device_gib = TPU_HBM_GIB_PER_LOGICAL_DEVICE.get(d.generation) + if per_device_gib is None or per_device_gib <= 0: + continue + chiplets = ( + max(1, TPU_CHIPLETS_PER_PKG.get(d.generation, 1)) + if d.pci_bdf in dual_chiplet_pkg_bdfs + else 1 + ) + nominal = int(per_device_gib) * int(chiplets) * (1024**3) + d.hbm_nominal_bytes = nominal + d.hbm_total_bytes = nominal if nominal > 0 else None + + def _collect_iommu_group_membership( sysfs_root: Path, pci_entries: Sequence[Path], -) -> Tuple[Dict[str, set[str]], Dict[str, bool]]: +) -> Tuple[Dict[str, set[str]], Dict[str, bool], Dict[str, set[str]]]: """Collect full PCI member sets per IOMMU group across sysfs. - Returns `(members_by_group, group_devices_dir_readable)`. A group is only - considered verifiable for exclusivity when its authoritative - `/sys/kernel/iommu_groups//devices` directory was present and readable. + Returns `(members_by_group, group_devices_dir_readable, kernel_members_by_group)`. + A group is only considered verifiable for exclusivity when its authoritative + `/sys/kernel/iommu_groups//devices` directory was present, readable, + non-empty, and explicitly lists the candidate endpoint itself. """ members: Dict[str, set[str]] = {} readable: Dict[str, bool] = {} + kernel_members: Dict[str, set[str]] = {} for entry in pci_entries: grp = _read_symlink_name(entry / "iommu_group") or "" @@ -2425,10 +2826,12 @@ def _collect_iommu_group_membership( grp_members = {m.name for m in dev_dir.iterdir()} except OSError: continue - readable[grp_dir.name] = True - members.setdefault(grp_dir.name, set()).update(grp_members) + if grp_members: + readable[grp_dir.name] = True + kernel_members[grp_dir.name] = set(grp_members) + members.setdefault(grp_dir.name, set()).update(grp_members) - return members, readable + return members, readable, kernel_members _VFIO_VIABLE_DRIVERS = frozenset({"vfio-pci", "pci-stub", "pcieport"}) @@ -2474,14 +2877,24 @@ def _is_vfio_group_viable( def discover_tpu_devices( sysfs_root: Path = Path("/sys"), dev_root: Path = Path("/dev"), + *, + physical_chip_map: Optional[Dict[str, int]] = None, + chip_id_map: Optional[Dict[str, str]] = None, + tpu7x_pci_layout: str = "auto", + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, ) -> List[TpuTelemetry]: """Scan sysfs PCI devices for vendor 0x1ae0 and resolve VFIO nodes.""" + if tpu7x_pci_layout not in VALID_TPU7X_PCI_LAYOUTS: + raise ValueError( + f"Invalid --tpu7x-pci-layout {tpu7x_pci_layout!r}; " + f"expected one of {', '.join(VALID_TPU7X_PCI_LAYOUTS)}" + ) pci_dir = sysfs_root / "bus" / "pci" / "devices" if not pci_dir.is_dir(): return [] pci_entries = sorted(pci_dir.iterdir(), key=lambda p: p.name) - group_members, group_dir_readable = _collect_iommu_group_membership( + group_members, group_dir_readable, group_kernel_members = _collect_iommu_group_membership( sysfs_root, pci_entries ) @@ -2520,7 +2933,9 @@ def discover_tpu_devices( pci_enabled = int(enable_raw, 0) > 0 except ValueError: pci_enabled = False - runtime_chip_id = _read_text(entry / "chip_id") or None + parsed_chip_id = _read_sysfs_chip_id(entry / "chip_id") + runtime_chip_id = str(parsed_chip_id) if parsed_chip_id is not None else None + pcie_root = _resolve_pcie_root_complex(entry) numa_raw = _read_text(entry / "numa_node") numa_node: Optional[int] = None @@ -2546,12 +2961,14 @@ def discover_tpu_devices( # vfio-pci binding, a viable IOMMU group (no sibling endpoint bound to # a conflicting host driver), and verified non-symlink character device # nodes matching kernel sysfs major:minor for /dev/vfio/vfio and /dev/vfio/. + kernel_grp = group_kernel_members.get(iommu_group, set()) vfio_group_viable = _is_vfio_group_viable( sysfs_root, iommu_group, group_members, group_dir_readable ) healthy = ( driver == "vfio-pci" and bool(iommu_group) + and entry.name in kernel_grp and vfio_group_viable and vfio_group_verified and vfio_container_verified @@ -2567,6 +2984,7 @@ def discover_tpu_devices( driver == "vfio-pci" and bool(iommu_group) and group_dir_readable.get(iommu_group, False) + and entry.name in kernel_grp and full_members == {entry.name} ) @@ -2586,6 +3004,10 @@ def discover_tpu_devices( existing.model_name = model_name existing.hbm_nominal_bytes = nominal_hbm existing.hbm_total_bytes = nominal_hbm if nominal_hbm > 0 else None + if existing.pci_bdf and existing.pci_bdf not in existing.sibling_pci_bdfs: + existing.sibling_pci_bdfs.append(existing.pci_bdf) + if entry.name not in existing.sibling_pci_bdfs: + existing.sibling_pci_bdfs.append(entry.name) if aer_correctable is not None or aer_fatal is not None: existing.sibling_aer_counters[entry.name] = (aer_correctable, aer_fatal) if iommu_group and iommu_group != existing.iommu_group: @@ -2605,6 +3027,8 @@ def discover_tpu_devices( and existing.driver == "vfio-pci" and bool(iommu_group) and group_dir_readable.get(iommu_group, False) + and entry.name in kernel_grp + and (not existing.pci_bdf or existing.pci_bdf in kernel_grp) and full_members <= {existing.pci_bdf, entry.name} ) existing.vfio_group_exclusive = ( @@ -2638,11 +3062,23 @@ def discover_tpu_devices( vfio_group_exclusive=vfio_group_exclusive, aer_correctable_total=aer_correctable, aer_fatal_total=aer_fatal, + pcie_root=pcie_root, ) discovered.append(chip) if device_id in LEGACY_DUAL_FUNCTION_DEVICE_IDS: legacy_by_base_addr[entry.name.rsplit(".", 1)[0]] = chip + _apply_tpu_nominal_hbm_topology( + discovered, + physical_chip_map=physical_chip_map, + chip_id_map=chip_id_map, + tpu7x_pci_layout=tpu7x_pci_layout, + bridge_bus_to_roots=( + bridge_bus_to_roots + if bridge_bus_to_roots is not None + else _scan_pcie_bridge_roots(sysfs_root) + ), + ) return discovered @@ -2655,38 +3091,698 @@ def _shared_vfio_paths(devices: Sequence[TpuTelemetry]) -> set[str]: return {vp for vp, count in counts.items() if count > 1} +def _has_exclusive_vfio_device(dev: TpuTelemetry, shared_vfio: set[str]) -> bool: + """Return True when `dev.vfio_device` is verified exclusive to this single TPU package.""" + return bool( + dev.vfio_device + and dev.vfio_group_exclusive + and not dev.unverified_sibling_vfio + and dev.vfio_device not in shared_vfio + ) + + +def _lookup_chip_map_matches( + dev: TpuTelemetry, + chip_id_map: Optional[Dict[str, str]], + shared_vfio: set[str], +) -> List[Tuple[str, int]]: + """Collect `(key, parsed_id)` entries targeting `dev` via BDF or exclusive VFIO path.""" + if not chip_id_map: + return [] + excl_vfio = ( + os.path.normpath(dev.vfio_device) + if _has_exclusive_vfio_device(dev, shared_vfio) + else None + ) + dev_bdfs = (dev.pci_bdf,) + tuple(dev.sibling_pci_bdfs) + matches: List[Tuple[str, int]] = [] + for k, raw_v in chip_id_map.items(): + if not isinstance(k, str): + continue + k_s = k.strip() + is_bdf_hit = not k_s.startswith("/") and _canon_map_bdf(k_s) in dev_bdfs + is_vfio_hit = ( + excl_vfio is not None + and k_s.startswith("/") + and os.path.normpath(k_s) == excl_vfio + ) + if not (is_bdf_hit or is_vfio_hit): + continue + parsed_v = _parse_runtime_device_id(str(raw_v).strip()) + if parsed_v is not None: + matches.append((k, parsed_v)) + return matches + + +def _resolve_tpu7x_slot_and_pkg_maps( + devices: Sequence[TpuTelemetry], + dual_set: set[str], + physical_chip_map: Optional[Dict[str, int]], + chip_id_map: Optional[Dict[str, str]] = None, +) -> Tuple[ + Dict[str, set[int]], + Dict[str, Optional[int]], + Dict[str, str], + Dict[str, str], + set[int], + set[int], + set[str], +]: + """Resolve proved 2-fn Ironwood packages, slot/cross-slot/legacy physical propagation, and domain/conflict sets. + + Resolution order: + 1. Complete 2-function PCI slots (`len == 2` on one slot), excluding their members + and oversized slots (`len > 2`) from cross-slot sysfs pairing and runtime joins. + 2. Visible single-function slots proved 2-fn by a mapped absent sibling (`chip_id_map` + or `physical_chip_map` on that same PCI slot). + 3. Remaining separate `.0` slots sharing an exact 2-member same-domain sysfs `chip_id`. + 4. Propagate `physical_chip_map` across ALL members of each proved package (and + collapsed non-Ironwood `0x0027` sibling pairs onto their representative) and reject + cross-domain physical pairings or intra-package physical ID disagreements. + """ + canon_phys = _canon_physical_chip_map(physical_chip_map) + nondual = [ + d + for d in devices + if d.generation == "tpu7x" + and ( + d.pci_bdf not in dual_set + or d.device_id == "0x0076" + or not d.pci_bdf.endswith(".0") + ) + ] + tpu7x_nondual_slots = {d.pci_bdf.rsplit(".", 1)[0] for d in nondual} + live_nondual_bdfs = {d.pci_bdf for d in nondual} + + by_slot: Dict[str, List[TpuTelemetry]] = {} + for d in nondual: + by_slot.setdefault(d.pci_bdf.rsplit(".", 1)[0], []).append(d) + + proved_pkg_tokens: Dict[str, str] = {} + pkg_members: Dict[str, List[TpuTelemetry]] = {} + slot_pkg_tokens: Dict[str, str] = {} + slot_assigned: set[str] = set() + oversized_bdfs: set[str] = set() + + slot_mapped_bdfs: Dict[str, set[str]] = {} + for m_src in (chip_id_map, canon_phys): + if not m_src: + continue + for raw_k in m_src: + if not isinstance(raw_k, str) or raw_k.strip().startswith("/"): + continue + cb = _canon_map_bdf(raw_k) + if not _CANON_PCI_BDF_RE.match(cb): + continue + ms = cb.rsplit(".", 1)[0] + if ms in tpu7x_nondual_slots: + slot_mapped_bdfs.setdefault(ms, set()).add(cb) + + # Step 1: Complete 2-function PCI slots FIRST (`len(union) == 2`); exclude oversized slots (`>2`). + for slot, sdevs in sorted(by_slot.items()): + slot_union = {d.pci_bdf for d in sdevs} | slot_mapped_bdfs.get(slot, set()) + if len(slot_union) > 2: + for d in sdevs: + oversized_bdfs.add(d.pci_bdf) + slot_assigned.add(d.pci_bdf) + elif len(sdevs) == 2: + tok = f"pkg:{sorted(d.pci_bdf for d in sdevs)[0]}" + slot_pkg_tokens[slot] = tok + for d in sdevs: + proved_pkg_tokens[d.pci_bdf] = tok + slot_assigned.add(d.pci_bdf) + pkg_members[tok] = list(sdevs) + + # Step 2: Visible singleton 2-fn slots that also have an absent sibling mapped. + absent_mapped_slots: set[str] = { + slot + for slot, mbdfs in slot_mapped_bdfs.items() + if any(b not in live_nondual_bdfs for b in mbdfs) + } + for slot, sdevs in sorted(by_slot.items()): + if ( + len(sdevs) == 1 + and slot in absent_mapped_slots + and sdevs[0].pci_bdf not in oversized_bdfs + ): + tok = f"slot:{slot}" + slot_pkg_tokens[slot] = tok + proved_pkg_tokens[sdevs[0].pci_bdf] = tok + slot_assigned.add(sdevs[0].pci_bdf) + pkg_members[tok] = list(sdevs) + + # Step 3: Remaining separate `.0` slots proved siblings by exact 2-member (dom, chip_id). + by_dom_rid: Dict[Tuple[Tuple[str, Optional[int], str], int], List[TpuTelemetry]] = {} + for d in nondual: + if d.pci_bdf in slot_assigned or not d.runtime_chip_id: + continue + pr = _parse_runtime_device_id(d.runtime_chip_id) + if pr is not None: + by_dom_rid.setdefault((_tpu7x_dom_key(d), pr), []).append(d) + for ddevs in by_dom_rid.values(): + if len(ddevs) == 2 and all(d.pci_bdf.endswith(".0") for d in ddevs): + tok = f"pkg:{sorted(d.pci_bdf for d in ddevs)[0]}" + for d in ddevs: + proved_pkg_tokens[d.pci_bdf] = tok + pkg_members[tok] = list(ddevs) + + # Step 4: Slot, proved-package, and collapsed non-Ironwood sibling physical ID propagation. + non_tpu7x_sib_to_rep: Dict[str, TpuTelemetry] = {} + non_tpu7x_bdfs: set[str] = set() + for d in devices: + if d.generation != "tpu7x": + non_tpu7x_sib_to_rep[d.pci_bdf] = d + non_tpu7x_bdfs.add(d.pci_bdf) + for sb in d.sibling_pci_bdfs: + non_tpu7x_sib_to_rep[sb] = d + non_tpu7x_bdfs.add(sb) + + non_tpu7x_rep_phys: Dict[str, set[int]] = {} + non_tpu7x_conflict_phys: set[int] = set() + slot_phys_sets: Dict[str, set[int]] = {} + direct_phys_by_bdf: Dict[str, int] = {} + phys_doms: Dict[int, set[Tuple[str, Optional[int], str]]] = {} + live_nondual_by_bdf = {d.pci_bdf: d for d in nondual} + if canon_phys: + for map_bdf, map_phys in canon_phys.items(): + rep_non = non_tpu7x_sib_to_rep.get(map_bdf) + if rep_non is not None: + non_tpu7x_rep_phys.setdefault(rep_non.pci_bdf, set()).add(int(map_phys)) + continue + if map_bdf in non_tpu7x_bdfs or map_bdf in dual_set: + continue + direct_phys_by_bdf[map_bdf] = int(map_phys) + if map_bdf in live_nondual_by_bdf: + phys_doms.setdefault(int(map_phys), set()).add( + _tpu7x_dom_key(live_nondual_by_bdf[map_bdf]) + ) + m_slot = map_bdf.rsplit(".", 1)[0] + if m_slot in tpu7x_nondual_slots: + slot_phys_sets.setdefault(m_slot, set()).add(int(map_phys)) + for _rep_bdf, pset in non_tpu7x_rep_phys.items(): + if len(pset) > 1: + non_tpu7x_conflict_phys.update(pset) + + cross_domain_phys: set[int] = { + p_id for p_id, dset in phys_doms.items() if len(dset) > 1 + } + pkg_conflict_phys: set[int] = set() + pkg_phys_val: Dict[str, int] = {} + for tok, members in pkg_members.items(): + pset: set[int] = set() + for m in members: + if m.pci_bdf in direct_phys_by_bdf: + pset.add(direct_phys_by_bdf[m.pci_bdf]) + ms = m.pci_bdf.rsplit(".", 1)[0] + pset.update(slot_phys_sets.get(ms, set())) + if len(pset) > 1: + pkg_conflict_phys.update(pset) + elif len(pset) == 1: + only_p = next(iter(pset)) + if only_p not in cross_domain_phys: + pkg_phys_val[tok] = only_p + + # Also treat unproved same-domain `.0` pairs sharing one physical map ID as a proved package. + phys_to_rem: Dict[int, List[TpuTelemetry]] = {} + for d in nondual: + if d.pci_bdf in proved_pkg_tokens or d.pci_bdf in oversized_bdfs: + continue + p_d = direct_phys_by_bdf.get(d.pci_bdf) + if p_d is None: + ss = slot_phys_sets.get(d.pci_bdf.rsplit(".", 1)[0], set()) + p_d = next(iter(ss)) if len(ss) == 1 else None + if p_d is not None and p_d not in cross_domain_phys and p_d not in pkg_conflict_phys: + phys_to_rem.setdefault(p_d, []).append(d) + for p_d, pdevs in phys_to_rem.items(): + # Guard against merging an already-allocated package ID or non-.0 orphan functions. + if ( + len(pdevs) == 2 + and all(d.pci_bdf.endswith(".0") for d in pdevs) + and len({_tpu7x_dom_key(d) for d in pdevs}) == 1 + and all(p_d != pv for pv in pkg_phys_val.values()) + ): + tok = f"pkg:{sorted(d.pci_bdf for d in pdevs)[0]}" + for d in pdevs: + proved_pkg_tokens[d.pci_bdf] = tok + pkg_members[tok] = list(pdevs) + pkg_phys_val[tok] = p_d + + eff_phys: Dict[str, Optional[int]] = {} + for dev in devices: + if dev.generation != "tpu7x": + pset = non_tpu7x_rep_phys.get(dev.pci_bdf, set()) + if len(pset) == 1: + only_np = next(iter(pset)) + eff_phys[dev.pci_bdf] = None if only_np in non_tpu7x_conflict_phys else only_np + else: + eff_phys[dev.pci_bdf] = None + elif canon_phys and dev.pci_bdf in canon_phys: + p_v = int(canon_phys[dev.pci_bdf]) + tok = proved_pkg_tokens.get(dev.pci_bdf) + if p_v in cross_domain_phys or ( + tok is not None and tok not in pkg_phys_val + ): + eff_phys[dev.pci_bdf] = None + else: + eff_phys[dev.pci_bdf] = p_v + elif ( + dev.pci_bdf not in dual_set + or dev.device_id == "0x0076" + or not dev.pci_bdf.endswith(".0") + ): + tok = proved_pkg_tokens.get(dev.pci_bdf) + if tok is not None: + eff_phys[dev.pci_bdf] = pkg_phys_val.get(tok) + else: + ss = slot_phys_sets.get(dev.pci_bdf.rsplit(".", 1)[0], set()) + only_p = next(iter(ss)) if len(ss) == 1 else None + eff_phys[dev.pci_bdf] = ( + only_p if only_p not in cross_domain_phys else None + ) + else: + eff_phys[dev.pci_bdf] = None + + return ( + slot_phys_sets, + eff_phys, + proved_pkg_tokens, + slot_pkg_tokens, + pkg_conflict_phys, + cross_domain_phys, + oversized_bdfs, + ) + + def validate_chip_id_map( devices: Sequence[TpuTelemetry], chip_id_map: Optional[Dict[str, str]], + *, + physical_chip_map: Optional[Dict[str, int]] = None, + tpu7x_pci_layout: str = "auto", + bridge_bus_to_roots: Optional[Dict[Tuple[str, int], set[str]]] = None, ) -> None: - """Validate that `--chip-id-map` never uses a shared VFIO path or duplicates a runtime ID.""" + """Validate `--physical-chip-map` and `--chip-id-map` consistency, exclusivity, and capacity.""" + physical_chip_map = _canon_physical_chip_map(physical_chip_map) + if not chip_id_map and not physical_chip_map: + return + + dual_chiplet_pkg_bdfs = _tpu7x_dual_chiplet_pkg_bdfs( + devices, + physical_chip_map=physical_chip_map, + chip_id_map=chip_id_map, + tpu7x_pci_layout=tpu7x_pci_layout, + bridge_bus_to_roots=bridge_bus_to_roots, + ) + ( + slot_phys_sets, + eff_phys_map, + proved_pkg_tokens, + slot_pkg_tokens, + pkg_conflict_phys, + cross_domain_phys, + oversized_bdfs, + ) = _resolve_tpu7x_slot_and_pkg_maps( + devices, + dual_chiplet_pkg_bdfs, + physical_chip_map, + chip_id_map=chip_id_map, + ) + for slot, pset in sorted(slot_phys_sets.items()): + if len(pset) > 1: + raise ValueError( + f"--physical-chip-map assigns conflicting physical chip IDs {sorted(pset)} " + f"to functions on slot {slot}" + ) + if cross_domain_phys: + raise ValueError( + f"--physical-chip-map assigns same package ID {sorted(cross_domain_phys)} across " + "distinct NUMA/PCIe topology domains" + ) + if pkg_conflict_phys: + raise ValueError( + f"--physical-chip-map assigns conflicting physical chip IDs {sorted(pkg_conflict_phys)} " + "to functions of the same proved Ironwood package" + ) + if physical_chip_map: + sib_to_rep: Dict[str, TpuTelemetry] = {} + for d in devices: + sib_to_rep[d.pci_bdf] = d + for sb in d.sibling_pci_bdfs: + sib_to_rep[sb] = d + rep_phys_seen: Dict[str, Tuple[int, str]] = {} + phys_members: Dict[int, set[str]] = {} + phys_twofn_slots: Dict[int, set[str]] = {} + phys_dual_bdfs: Dict[int, set[str]] = {} + for d in devices: + p_val = eff_phys_map.get(d.pci_bdf) + if p_val is None: + continue + phys_members.setdefault(p_val, set()).add(d.pci_bdf) + if d.pci_bdf in dual_chiplet_pkg_bdfs or d.generation != "tpu7x": + phys_dual_bdfs.setdefault(p_val, set()).add(d.pci_bdf) + if d.generation == "tpu7x" and not d.pci_bdf.endswith(".0"): + phys_twofn_slots.setdefault(p_val, set()).add(d.pci_bdf.rsplit(".", 1)[0]) + for cb, p_val in physical_chip_map.items(): + live_d = sib_to_rep.get(cb) + if live_d is not None and live_d.generation != "tpu7x": + prev_rep = rep_phys_seen.get(live_d.pci_bdf) + if prev_rep is not None and prev_rep[0] != p_val: + raise ValueError( + f"--physical-chip-map assigns conflicting physical IDs " + f"({prev_rep[0]} via {prev_rep[1]} and {p_val} via {cb}) to siblings of {live_d.pci_bdf}" + ) + rep_phys_seen[live_d.pci_bdf] = (p_val, cb) + phys_members.setdefault(p_val, set()).add(live_d.pci_bdf) + phys_dual_bdfs.setdefault(p_val, set()).add(live_d.pci_bdf) + else: + phys_members.setdefault(p_val, set()).add(cb) + if live_d is not None and cb in dual_chiplet_pkg_bdfs: + phys_dual_bdfs.setdefault(p_val, set()).add(cb) + elif not cb.endswith(".0"): + phys_twofn_slots.setdefault(p_val, set()).add(cb.rsplit(".", 1)[0]) + for s_k, s_p in slot_phys_sets.items(): + if len(s_p) == 1: + only_p = next(iter(s_p)) + s_devs = [d for d in devices if d.pci_bdf.rsplit(".", 1)[0] == s_k] + if len(s_devs) > 1 or any(not d.pci_bdf.endswith(".0") for d in s_devs): + phys_twofn_slots.setdefault(only_p, set()).add(s_k) + for p_val, members in sorted(phys_members.items()): + slots = {b.rsplit(".", 1)[0] for b in members} + dual_hits = phys_dual_bdfs.get(p_val, set()) + if dual_hits and len(members) > 1: + raise ValueError( + f"--physical-chip-map assigns package {p_val} to 1-fn device {sorted(dual_hits)} " + f"alongside {sorted(members)}" + ) + if len(members) > 2 or (phys_twofn_slots.get(p_val) and len(slots) > 1): + raise ValueError( + f"--physical-chip-map exceeds 2-function package capacity for physical chip {p_val}: " + f"{sorted(members)}" + ) + if not chip_id_map: return shared_vfio = _shared_vfio_paths(devices) - for raw_key in chip_id_map: + non_exclusive_vfio = { + d.vfio_device + for d in devices + if d.vfio_device and not _has_exclusive_vfio_device(d, shared_vfio) + } + for raw_key, raw_val in chip_id_map.items(): norm_key = os.path.normpath(raw_key) if raw_key.startswith("/") else raw_key - if raw_key in shared_vfio or norm_key in shared_vfio: + if ( + raw_key in shared_vfio + or norm_key in shared_vfio + or raw_key in non_exclusive_vfio + or norm_key in non_exclusive_vfio + ): + reason = ( + "shared VFIO group" + if (raw_key in shared_vfio or norm_key in shared_vfio) + else "non-exclusive VFIO group" + ) + raise ValueError( + f"--chip-id-map key {raw_key!r} targets a {reason}; " + "use explicit PCI BDF keys for chips without an exclusive VFIO group" + ) + if _parse_runtime_device_id(str(raw_val).strip()) is None: raise ValueError( - f"--chip-id-map key {raw_key!r} targets a shared VFIO group; " - "use explicit PCI BDF keys for chips sharing a VFIO group" + f"--chip-id-map value {raw_val!r} for {raw_key!r} must be a non-negative integer runtime ID" ) - seen_runtime_targets: Dict[str, str] = {} + tpu7x_nondual_slots = { + d.pci_bdf.rsplit(".", 1)[0] + for d in devices + if d.generation == "tpu7x" + and ( + d.pci_bdf not in dual_chiplet_pkg_bdfs + or d.device_id == "0x0076" + or not d.pci_bdf.endswith(".0") + ) + } + + seen_logical_claims: Dict[str, str] = {} + seen_pkg_logical_owner: Dict[str, Tuple[str, str]] = {} + pkg_token_logical_pkgs: Dict[str, Tuple[int, str]] = {} + tpu7x_logical_pkg_owner: Dict[int, Tuple[str, str]] = {} + cand_pkg_doms: Dict[int, set[Tuple[str, Optional[int], str]]] = {} + cand_pkg_bdfs: Dict[int, set[str]] = {} + oversized_slots_val = {b.rsplit(".", 1)[0] for b in oversized_bdfs} + slot_doms_by_slot: Dict[str, set[Tuple[str, Optional[int], str]]] = {} + for d in devices: + if d.generation == "tpu7x": + slot_doms_by_slot.setdefault(d.pci_bdf.rsplit(".", 1)[0], set()).add( + _tpu7x_dom_key(d) + ) + matched_live_bdfs: set[str] = set() for dev in devices: - mapped = chip_id_map.get(dev.pci_bdf) - if mapped is None and dev.vfio_device and dev.vfio_device not in shared_vfio: - mapped = chip_id_map.get(dev.vfio_device) - if mapped is None: + matches = _lookup_chip_map_matches(dev, chip_id_map, shared_vfio) + if not matches: + continue + matched_live_bdfs.add(dev.pci_bdf) + distinct_vals = sorted({val for _k, val in matches}) + if len(distinct_vals) > 1: + raise ValueError( + f"--chip-id-map assigns conflicting runtime IDs {distinct_vals} " + f"to {dev.pci_bdf} via multiple alias keys ({[k for k, _v in matches]})" + ) + parsed_rt = distinct_vals[0] + dpc = max(1, _GEN_DEVICES_PER_CHIP.get(dev.generation, 1)) + phys_idx = eff_phys_map.get(dev.pci_bdf) + if phys_idx is not None and (parsed_rt // dpc) != phys_idx: + raise ValueError( + f"--chip-id-map {parsed_rt!r} for {dev.pci_bdf} conflicts with " + f"--physical-chip-map={phys_idx}" + ) + if dev.generation == "tpu7x" and ( + dev.pci_bdf not in dual_chiplet_pkg_bdfs or dev.pci_bdf in proved_pkg_tokens + ): + dev_slot = dev.pci_bdf.rsplit(".", 1)[0] + pkg_tok = proved_pkg_tokens.get(dev.pci_bdf) + cand_pkg = parsed_rt // 2 + dom_set = cand_pkg_doms.setdefault(cand_pkg, set()) + dom_set.add(_tpu7x_dom_key(dev)) + if len(dom_set) > 1: + raise ValueError( + f"--chip-id-map assigns package {cand_pkg} logical IDs across distinct " + "NUMA/PCIe topology domains" + ) + bset = cand_pkg_bdfs.setdefault(cand_pkg, set()) + bset.add(dev.pci_bdf) + if len({b.rsplit(".", 1)[0] for b in bset}) > 1 and any(not b.endswith(".0") for b in bset): + raise ValueError( + f"--chip-id-map pairs non-zero PCI functions {sorted(bset)} across distinct " + f"PCI slots for Ironwood package {cand_pkg}" + ) + slot_key = pkg_tok if pkg_tok is not None else f"slot:{dev_slot}" + prev_tok_pkg = pkg_token_logical_pkgs.get(slot_key) + if prev_tok_pkg is not None and prev_tok_pkg[0] != cand_pkg: + raise ValueError( + f"--chip-id-map assigns logical IDs from different packages " + f"({prev_tok_pkg[0]} for {prev_tok_pkg[1]} and {cand_pkg} for {dev.pci_bdf}) " + f"on Ironwood package {slot_key}" + ) + pkg_token_logical_pkgs[slot_key] = (cand_pkg, dev.pci_bdf) + if pkg_tok is not None: + prev_pkg_owner = tpu7x_logical_pkg_owner.get(cand_pkg) + if prev_pkg_owner is not None and prev_pkg_owner[0] != pkg_tok: + raise ValueError( + f"--chip-id-map assigns package {cand_pkg} logical IDs to multiple " + f"proved Ironwood packages ({prev_pkg_owner[1]} and {dev.pci_bdf})" + ) + tpu7x_logical_pkg_owner[cand_pkg] = (pkg_tok, dev.pci_bdf) + prev_exact = seen_logical_claims.get(str(parsed_rt)) + if prev_exact is not None and prev_exact != dev.pci_bdf: + raise ValueError( + f"--chip-id-map assigns logical runtime ID {str(parsed_rt)!r} to multiple PCI BDFs " + f"({prev_exact} and {dev.pci_bdf})" + ) + seen_logical_claims[str(parsed_rt)] = dev.pci_bdf + if dev.pci_bdf in proved_pkg_tokens: + cand_pkg = parsed_rt // 2 + pkg_owner_tok = proved_pkg_tokens[dev.pci_bdf] + pkg_claimed_ids: Tuple[str, ...] = (str(2 * cand_pkg), str(2 * cand_pkg + 1)) + elif dev.pci_bdf in dual_chiplet_pkg_bdfs: + pair_idx = parsed_rt // 2 + pkg_owner_tok = f"bdf:{dev.pci_bdf}" + pkg_claimed_ids = (str(2 * pair_idx), str(2 * pair_idx + 1)) + prev_pkg_owner = tpu7x_logical_pkg_owner.get(pair_idx) + if prev_pkg_owner is not None and prev_pkg_owner[0] != pkg_owner_tok: + raise ValueError( + f"--chip-id-map assigns package {pair_idx} logical IDs to multiple " + f"Ironwood packages ({prev_pkg_owner[1]} and {dev.pci_bdf})" + ) + tpu7x_logical_pkg_owner[pair_idx] = (pkg_owner_tok, dev.pci_bdf) + else: + pkg_owner_tok = f"bdf:{dev.pci_bdf}" + pkg_claimed_ids = (str(parsed_rt),) + for cid in pkg_claimed_ids: + prev_owner = seen_pkg_logical_owner.get(cid) + if prev_owner is not None and prev_owner[0] != pkg_owner_tok: + raise ValueError( + f"--chip-id-map assigns logical runtime ID {cid!r} to multiple packages/devices " + f"({prev_owner[1]} and {dev.pci_bdf})" + ) + seen_pkg_logical_owner[cid] = (pkg_owner_tok, dev.pci_bdf) + + proved_sysfs_pkgs: Dict[str, List[TpuTelemetry]] = {} + for d in devices: + ptok = proved_pkg_tokens.get(d.pci_bdf) + if ptok is not None: + proved_sysfs_pkgs.setdefault(ptok, []).append(d) + + def _reserve_phys_owner( + pkg_val: int, + dpc_val: int, + owner_tok: str, + owner_bdf: str, + src_desc: str, + track_tpu7x_pkg: bool, + ) -> None: + if track_tpu7x_pkg: + prev_pkg_owner = tpu7x_logical_pkg_owner.get(pkg_val) + if prev_pkg_owner is not None and prev_pkg_owner[0] != owner_tok: + raise ValueError( + f"--chip-id-map assigns package {pkg_val} logical IDs to {prev_pkg_owner[1]}, " + f"conflicting with {src_desc}" + ) + tpu7x_logical_pkg_owner[pkg_val] = (owner_tok, owner_bdf) + if 0 <= pkg_val and (dpc_val * pkg_val + dpc_val - 1) <= _MAX_RUNTIME_DEVICE_ID: + for off in range(dpc_val): + cid = str(dpc_val * pkg_val + off) + prev_owner = seen_pkg_logical_owner.get(cid) + if prev_owner is not None and prev_owner[0] != owner_tok: + raise ValueError( + f"--chip-id-map assigns logical runtime ID {cid!r} to {prev_owner[1]}, " + f"conflicting with {src_desc}" + ) + seen_pkg_logical_owner[cid] = (owner_tok, owner_bdf) + + for d_check in devices: + p_idx = eff_phys_map.get(d_check.pci_bdf) + is_matched = d_check.pci_bdf in matched_live_bdfs + if d_check.pci_bdf in dual_chiplet_pkg_bdfs: + if is_matched and p_idx is None: + continue + pkg_num = p_idx + if pkg_num is None and d_check.runtime_chip_id: + pkg_num = _parse_runtime_device_id(d_check.runtime_chip_id) + if pkg_num is not None: + src = ( + f"--physical-chip-map={pkg_num} for 1-fn Ironwood {d_check.pci_bdf}" + if p_idx is not None + else f"sysfs chip_id={pkg_num} for 1-fn Ironwood {d_check.pci_bdf}" + ) + _reserve_phys_owner(pkg_num, 2, f"bdf:{d_check.pci_bdf}", d_check.pci_bdf, src, True) + continue + if p_idx is not None: + pkg_tok = proved_pkg_tokens.get(d_check.pci_bdf) + owner_tok = pkg_tok if pkg_tok is not None else f"bdf:{d_check.pci_bdf}" + dpc = max(1, _GEN_DEVICES_PER_CHIP.get(d_check.generation, 1)) + src = ( + f"--physical-chip-map={p_idx} for " + f"{'2-fn Ironwood package ' + d_check.pci_bdf if pkg_tok is not None else d_check.pci_bdf}" + ) + _reserve_phys_owner( + p_idx, dpc, owner_tok, d_check.pci_bdf, src, d_check.generation == "tpu7x" + ) + continue + if is_matched or d_check.pci_bdf not in proved_pkg_tokens: + continue + pkg_tok = proved_pkg_tokens[d_check.pci_bdf] + pmems = proved_sysfs_pkgs.get(pkg_tok, []) + if len(pmems) == 2 and pkg_tok not in pkg_token_logical_pkgs and all( + eff_phys_map.get(m.pci_bdf) is None for m in pmems + ): + sys_rids = [ + _parse_runtime_device_id(m.runtime_chip_id) + for m in pmems + if m.runtime_chip_id is not None + ] + if len(sys_rids) == 2 and sys_rids[0] is not None and sys_rids[0] == sys_rids[1]: + pr_sys = sys_rids[0] + _reserve_phys_owner( + pr_sys, + 2, + pkg_tok, + pmems[0].pci_bdf, + f"unmapped 2-fn Ironwood package {pkg_tok} (sysfs chip_id={pr_sys})", + False, + ) + + for raw_k, raw_v in chip_id_map.items(): + if raw_k.strip().startswith("/"): continue - rt_id = str(mapped) - prev_bdf = seen_runtime_targets.get(rt_id) - if prev_bdf is not None and prev_bdf != dev.pci_bdf: + cb = _canon_map_bdf(raw_k) + if cb in {d.pci_bdf for d in devices} or not _CANON_PCI_BDF_RE.match(cb): + continue + m_slot = cb.rsplit(".", 1)[0] + if m_slot in oversized_slots_val: + raise ValueError( + f"--chip-id-map targets absent function {cb} exceeding 2-function slot capacity " + f"on {m_slot}" + ) + if m_slot not in tpu7x_nondual_slots: + continue + parsed_rt = _parse_runtime_device_id(str(raw_v).strip()) + if parsed_rt is None: + continue + s_phys = slot_phys_sets.get(m_slot, set()) + if len(s_phys) == 1 and (parsed_rt // 2) != next(iter(s_phys)): + raise ValueError( + f"--chip-id-map {parsed_rt!r} for absent sibling {cb} conflicts with " + f"--physical-chip-map={next(iter(s_phys))}" + ) + cand_pkg = parsed_rt // 2 + bset = cand_pkg_bdfs.setdefault(cand_pkg, set()) + bset.add(cb) + if len({b.rsplit(".", 1)[0] for b in bset}) > 1 and any(not b.endswith(".0") for b in bset): + raise ValueError( + f"--chip-id-map pairs non-zero PCI functions {sorted(bset)} across distinct " + f"PCI slots for Ironwood package {cand_pkg}" + ) + if len(slot_doms_by_slot.get(m_slot, set())) == 1: + dom_set = cand_pkg_doms.setdefault(cand_pkg, set()) + dom_set.update(slot_doms_by_slot[m_slot]) + if len(dom_set) > 1: + raise ValueError( + f"--chip-id-map assigns package {cand_pkg} logical IDs across distinct " + "NUMA/PCIe topology domains" + ) + slot_key = slot_pkg_tokens.get(m_slot, f"slot:{m_slot}") + prev_tok_pkg = pkg_token_logical_pkgs.get(slot_key) + if prev_tok_pkg is not None and prev_tok_pkg[0] != cand_pkg: + raise ValueError( + f"--chip-id-map assigns logical IDs from different packages " + f"({prev_tok_pkg[0]} for {prev_tok_pkg[1]} and {cand_pkg} for {cb}) " + f"on Ironwood sibling slot {m_slot}" + ) + pkg_token_logical_pkgs[slot_key] = (cand_pkg, cb) + if m_slot in slot_pkg_tokens: + pkg_tok = slot_pkg_tokens[m_slot] + prev_pkg_owner = tpu7x_logical_pkg_owner.get(cand_pkg) + if prev_pkg_owner is not None and prev_pkg_owner[0] != pkg_tok: + raise ValueError( + f"--chip-id-map assigns package {cand_pkg} logical IDs to multiple " + f"proved Ironwood packages ({prev_pkg_owner[1]} and {cb})" + ) + tpu7x_logical_pkg_owner[cand_pkg] = (pkg_tok, cb) + for cid in (str(2 * cand_pkg), str(2 * cand_pkg + 1)): + prev_owner = seen_pkg_logical_owner.get(cid) + if prev_owner is not None and prev_owner[0] != pkg_tok: + raise ValueError( + f"--chip-id-map assigns logical runtime ID {cid!r} to multiple packages/devices " + f"({prev_owner[1]} and {cb})" + ) + seen_pkg_logical_owner[cid] = (pkg_tok, cb) + prev_bdf = seen_logical_claims.get(str(parsed_rt)) + if prev_bdf is not None and prev_bdf != cb: raise ValueError( - f"--chip-id-map assigns runtime chip {rt_id!r} to multiple PCI BDFs " - f"({prev_bdf} and {dev.pci_bdf})" + f"--chip-id-map assigns logical runtime ID {str(parsed_rt)!r} to multiple PCI BDFs " + f"({prev_bdf} and {cb})" ) - seen_runtime_targets[rt_id] = dev.pci_bdf + seen_logical_claims[str(parsed_rt)] = cb DEFAULT_RUNTIME_METRICS_ADDR = "127.0.0.1:8431" @@ -2721,6 +3817,7 @@ def _resolve_raw_device_runtime_ids( devices: Sequence[TpuTelemetry], shared_vfio: set[str], chip_id_map: Optional[Dict[str, str]], + oversized_bdfs: Optional[set[str]] = None, ) -> Tuple[Dict[str, Optional[str]], set[str]]: """Resolve per-BDF runtime IDs and post-override ambiguous IDs. @@ -2733,8 +3830,16 @@ def _resolve_raw_device_runtime_ids( """ raw_sysfs_counts: Dict[str, int] = {} raw_sysfs_gen_counts: Dict[Tuple[str, str], int] = {} + tpu7x_slot_total_counts: Dict[str, int] = {} tpu7x_slot_rids: Dict[str, List[str]] = {} tpu7x_distinct_int_rids: set[int] = set() + oversized_slots = {b.rsplit(".", 1)[0] for b in (oversized_bdfs or set())} + for dev in devices: + if dev.generation == "tpu7x": + base_slot = dev.pci_bdf.rsplit(".", 1)[0] + tpu7x_slot_total_counts[base_slot] = ( + tpu7x_slot_total_counts.get(base_slot, 0) + 1 + ) for dev in devices: if dev.runtime_chip_id: raw_sysfs_counts[dev.runtime_chip_id] = ( @@ -2745,10 +3850,16 @@ def _resolve_raw_device_runtime_ids( ) if dev.generation == "tpu7x": base_slot = dev.pci_bdf.rsplit(".", 1)[0] - tpu7x_slot_rids.setdefault(base_slot, []).append(dev.runtime_chip_id) - parsed_rid = _parse_runtime_device_id(dev.runtime_chip_id) - if parsed_rid is not None: - tpu7x_distinct_int_rids.add(parsed_rid) + is_oversized = ( + base_slot in oversized_slots + or tpu7x_slot_total_counts.get(base_slot, 0) + > _GEN_DEVICES_PER_CHIP["tpu7x"] + ) + if not is_oversized: + tpu7x_slot_rids.setdefault(base_slot, []).append(dev.runtime_chip_id) + parsed_rid = _parse_runtime_device_id(dev.runtime_chip_id) + if parsed_rid is not None: + tpu7x_distinct_int_rids.add(parsed_rid) shared_raw_sysfs_ids = {rid for rid, cnt in raw_sysfs_counts.items() if cnt > 1} physical_sysfs_gens = { gen @@ -2760,17 +3871,28 @@ def _resolve_raw_device_runtime_ids( # function per chip makes physical sysfs `chip_id`s appear unique even # though they are NOT logical core IDs. Require positive host-level # evidence that `tpu7x` sysfs `chip_id` is per-core — either (a) at least - # one multifunction sibling pair on the same PCI slot reporting distinct - # non-empty `chip_id`s, or (b) strictly more than 4 distinct non-negative - # integer `chip_id`s (e.g. `0..7` across 8 separate PCI slots, ruling out - # physical-chip numbering by pigeonhole), with zero shared `tpu7x` raw - # `chip_id`s — before trusting raw sysfs `chip_id` without `--chip-id-map`. + # one valid 2-function slot pair on the same PCI slot reporting distinct + # non-empty `chip_id`s `{2p, 2p+1}`, or (b) strictly more than 4 distinct + # non-negative integer `chip_id`s across non-oversized slots (e.g. `0..7` + # across 8 separate PCI slots, ruling out physical-chip numbering by + # pigeonhole), with zero shared `tpu7x` raw `chip_id`s — before trusting + # raw sysfs `chip_id` without `--chip-id-map`. + def _slot_is_paired_per_core_ids(raw_rids: Sequence[str]) -> bool: + if len(raw_rids) != _GEN_DEVICES_PER_CHIP["tpu7x"]: + return False + parsed = [_parse_runtime_device_id(r) for r in raw_rids] + if len(parsed) != 2 or parsed[0] is None or parsed[1] is None: + return False + lo, hi = sorted((parsed[0], parsed[1])) + return (lo % 2) == 0 and hi == lo + 1 + tpu7x_sysfs_proved_per_core = ( "tpu7x" not in physical_sysfs_gens and ( any( - len(rids) == _GEN_DEVICES_PER_CHIP["tpu7x"] and len(set(rids)) == len(rids) - for rids in tpu7x_slot_rids.values() + tpu7x_slot_total_counts.get(slot, 0) == _GEN_DEVICES_PER_CHIP["tpu7x"] + and _slot_is_paired_per_core_ids(rids) + for slot, rids in tpu7x_slot_rids.items() ) or len(tpu7x_distinct_int_rids) > 4 ) @@ -2778,15 +3900,19 @@ def _resolve_raw_device_runtime_ids( resolved_by_bdf: Dict[str, Optional[str]] = {} claimants: Dict[str, List[str]] = {} + conflicting_map_ids: set[str] = set() for dev in devices: - is_shared_vfio = bool(dev.vfio_device and dev.vfio_device in shared_vfio) rt_id: Optional[str] = None - if chip_id_map: - mapped = chip_id_map.get(dev.pci_bdf) - if mapped is None and not is_shared_vfio and dev.vfio_device: - mapped = chip_id_map.get(dev.vfio_device) - if mapped is not None: - rt_id = str(mapped).strip() or None + map_hits = _lookup_chip_map_matches(dev, chip_id_map, shared_vfio) + if map_hits: + distinct_vals = sorted({v for _k, v in map_hits}) + if len(distinct_vals) == 1: + rt_id = str(distinct_vals[0]) + else: + for dv in distinct_vals: + conflicting_map_ids.add(str(dv)) + resolved_by_bdf[dev.pci_bdf] = None + continue if not rt_id and dev.runtime_chip_id: if ( dev.runtime_chip_id not in shared_raw_sysfs_ids @@ -2797,29 +3923,424 @@ def _resolve_raw_device_runtime_ids( resolved_by_bdf[dev.pci_bdf] = rt_id if rt_id: claimants.setdefault(rt_id, []).append(dev.pci_bdf) - ambiguous = {rt for rt, bdfs in claimants.items() if len(bdfs) > 1} + ambiguous = {rt for rt, bdfs in claimants.items() if len(bdfs) > 1} | conflicting_map_ids return resolved_by_bdf, ambiguous +def _tpu7x_slot_physical_chip_map( + devices: Sequence[TpuTelemetry], + dual_set: set[str], + physical_chip_map: Optional[Dict[str, int]], +) -> Tuple[Dict[str, set[int]], Dict[str, Optional[int]]]: + """Propagate `--physical-chip-map` across 2-fn Ironwood PCI slots and proved separate-slot packages.""" + slot_phys_sets, eff_phys, _pt, _sp, _cp, _cd, _ov = _resolve_tpu7x_slot_and_pkg_maps( + devices, dual_set, physical_chip_map + ) + return slot_phys_sets, eff_phys + + +def _collect_unified_logical_ownership( + devices: Sequence[TpuTelemetry], + shared_vfio: set[str], + chip_id_map: Optional[Dict[str, str]], + dual_chiplet_pkg_bdfs: Optional[set[str]], + physical_chip_map: Optional[Dict[str, int]] = None, +) -> Tuple[ + Dict[str, Optional[str]], + set[str], + Dict[str, Tuple[str, str]], + set[str], +]: + """Resolve single-device IDs and `1-fn` Ironwood D2D pairs in one ownership table.""" + dual_set = dual_chiplet_pkg_bdfs or set() + ( + slot_phys_sets, + eff_phys_map, + proved_pkg_tokens, + slot_pkg_tokens, + pkg_conflict_phys, + cross_domain_phys, + oversized_bdfs, + ) = _resolve_tpu7x_slot_and_pkg_maps( + devices, dual_set, physical_chip_map, chip_id_map=chip_id_map + ) + resolved_by_bdf, base_ambiguous_rt = _resolve_raw_device_runtime_ids( + devices, shared_vfio, chip_id_map, oversized_bdfs=oversized_bdfs + ) + raw_pairs: Dict[str, Tuple[str, str]] = {} + ambiguous_pair_bdfs: set[str] = set() + logical_claimants: Dict[str, List[str]] = {} + speculative_claimants: Dict[str, List[str]] = {} + extra_ambiguous_rt: set[str] = set() + explicit_mapped_bdfs: set[str] = set() + tpu7x_slot_raw_ids: Dict[str, List[int]] = {} + tpu7x_all_resolved_ids: set[str] = set() + tpu7x_slot_resolved_pkgs: Dict[str, set[int]] = {} + tpu7x_pkg_mapped_ids: Dict[int, set[str]] = {} + tpu7x_nondual_slots: set[str] = set() + proved_pkg_resolved_pkgs: Dict[str, set[int]] = {} + proved_pkg_members: Dict[str, List[TpuTelemetry]] = {} + for d in devices: + ptok = proved_pkg_tokens.get(d.pci_bdf) + if ptok is not None: + proved_pkg_members.setdefault(ptok, []).append(d) + owner_mapped_ids: Dict[str, set[str]] = {} + tpu7x_logical_pkg_doms: Dict[int, set[Tuple[str, Optional[int], str]]] = {} + tpu7x_logical_pkg_bdfs: Dict[int, set[str]] = {} + oversized_slots_own = {b.rsplit(".", 1)[0] for b in oversized_bdfs} + for b_ov in oversized_bdfs: + ambiguous_pair_bdfs.add(b_ov) + resolved_by_bdf[b_ov] = None + for slot, pset in slot_phys_sets.items(): + if len(pset) > 1: + for p_bad in pset: + if 0 <= p_bad and (2 * p_bad + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * p_bad)) + extra_ambiguous_rt.add(str(2 * p_bad + 1)) + for p_bad in pkg_conflict_phys | cross_domain_phys: + if 0 <= p_bad and (2 * p_bad + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * p_bad)) + extra_ambiguous_rt.add(str(2 * p_bad + 1)) + + for dev in devices: + owner_tok = proved_pkg_tokens.get(dev.pci_bdf) or f"bdf:{dev.pci_bdf}" + map_hits = _lookup_chip_map_matches(dev, chip_id_map, shared_vfio) + if map_hits: + distinct_hits = {v for _k, v in map_hits} + if dev.pci_bdf in oversized_bdfs: + for dh in distinct_hits: + extra_ambiguous_rt.add(str(dh)) + extra_ambiguous_rt.add(str(dh ^ 1)) + elif len(distinct_hits) == 1: + explicit_mapped_bdfs.add(dev.pci_bdf) + m_rt = next(iter(distinct_hits)) + owner_mapped_ids.setdefault(owner_tok, set()).add(str(m_rt)) + if dev.generation == "tpu7x": + tpu7x_pkg_mapped_ids.setdefault(m_rt // 2, set()).add(str(m_rt)) + else: + for dh in distinct_hits: + extra_ambiguous_rt.add(str(dh)) + if dev.generation == "tpu7x": + extra_ambiguous_rt.add(str(dh ^ 1)) + if dev.pci_bdf in oversized_bdfs: + ov_phys = eff_phys_map.get(dev.pci_bdf) + if ov_phys is not None and 0 <= ov_phys and (2 * ov_phys + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * ov_phys)) + extra_ambiguous_rt.add(str(2 * ov_phys + 1)) + continue + if dev.generation == "tpu7x" and ( + dev.pci_bdf not in dual_set or dev.pci_bdf in proved_pkg_tokens + ): + slot = dev.pci_bdf.rsplit(".", 1)[0] + tpu7x_nondual_slots.add(slot) + if dev.runtime_chip_id: + pr_raw = _parse_runtime_device_id(dev.runtime_chip_id) + if pr_raw is not None: + tpu7x_slot_raw_ids.setdefault(slot, []).append(pr_raw) + res_d = resolved_by_bdf.get(dev.pci_bdf) + if res_d is not None: + tpu7x_all_resolved_ids.add(res_d) + p_res = _parse_runtime_device_id(res_d) + if p_res is not None: + tpu7x_slot_resolved_pkgs.setdefault(slot, set()).add(p_res // 2) + tpu7x_logical_pkg_doms.setdefault(p_res // 2, set()).add(_tpu7x_dom_key(dev)) + tpu7x_logical_pkg_bdfs.setdefault(p_res // 2, set()).add(dev.pci_bdf) + pkg_tok = proved_pkg_tokens.get(dev.pci_bdf) + if pkg_tok is not None: + proved_pkg_resolved_pkgs.setdefault(pkg_tok, set()).add(p_res // 2) + + pkg_logical_owners: Dict[str, set[str]] = {} + if chip_id_map: + for raw_k, raw_v in chip_id_map.items(): + if raw_k.strip().startswith("/"): + continue + cb = _canon_map_bdf(raw_k) + if cb in {d.pci_bdf for d in devices}: + continue + c_slot = cb.rsplit(".", 1)[0] + if c_slot in oversized_slots_own: + c_rt = _parse_runtime_device_id(str(raw_v).strip()) + if c_rt is not None: + extra_ambiguous_rt.add(str(c_rt)) + extra_ambiguous_rt.add(str(c_rt ^ 1)) + elif c_slot in tpu7x_nondual_slots: + c_rt = _parse_runtime_device_id(str(raw_v).strip()) + if c_rt is not None: + tpu7x_all_resolved_ids.add(str(c_rt)) + tpu7x_slot_resolved_pkgs.setdefault(c_slot, set()).add(c_rt // 2) + tpu7x_logical_pkg_bdfs.setdefault(c_rt // 2, set()).add(cb) + slot_tok = slot_pkg_tokens.get(c_slot) + if slot_tok is not None: + proved_pkg_resolved_pkgs.setdefault(slot_tok, set()).add(c_rt // 2) + owner_mapped_ids.setdefault(slot_tok, set()).add(str(c_rt)) + p_absent = c_rt // 2 + pkg_logical_owners.setdefault(str(2 * p_absent), set()).add(slot_tok) + pkg_logical_owners.setdefault(str(2 * p_absent + 1), set()).add(slot_tok) + logical_claimants.setdefault(str(c_rt), []).append(cb) + + for p_bad, bset in tpu7x_logical_pkg_bdfs.items(): + if ( + len({b.rsplit(".", 1)[0] for b in bset}) > 1 + and any(not b.endswith(".0") for b in bset) + and 0 <= p_bad + and (2 * p_bad + 1) <= _MAX_RUNTIME_DEVICE_ID + ): + extra_ambiguous_rt.add(str(2 * p_bad)) + extra_ambiguous_rt.add(str(2 * p_bad + 1)) + + for p_bad, dset in tpu7x_logical_pkg_doms.items(): + if len(dset) > 1 and 0 <= p_bad and (2 * p_bad + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * p_bad)) + extra_ambiguous_rt.add(str(2 * p_bad + 1)) + + for pkg_tok, pset in proved_pkg_resolved_pkgs.items(): + if len(pset) > 1: + for p_bad in pset: + if 0 <= p_bad and (2 * p_bad + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * p_bad)) + extra_ambiguous_rt.add(str(2 * p_bad + 1)) + + owner_resolved_ids: Dict[str, set[str]] = { + tok: set(ids) for tok, ids in owner_mapped_ids.items() + } + for d_res in devices: + if d_res.pci_bdf in oversized_bdfs: + continue + r_res = resolved_by_bdf.get(d_res.pci_bdf) + if r_res is None: + continue + pt_res = proved_pkg_tokens.get(d_res.pci_bdf) + ot_res = pt_res if pt_res is not None else f"bdf:{d_res.pci_bdf}" + owner_resolved_ids.setdefault(ot_res, set()).add(r_res) + + reserved_phys_owner_cands: set[Tuple[str, str]] = set() + reserved_sysfs_pkg_tokens: set[str] = set() + for dev in devices: + if dev.pci_bdf in oversized_bdfs: + continue + phys_pair = eff_phys_map.get(dev.pci_bdf) + dpc = max(1, _GEN_DEVICES_PER_CHIP.get(dev.generation, 1)) + if dev.pci_bdf not in dual_set or dev.pci_bdf in proved_pkg_tokens: + rt_id = resolved_by_bdf.get(dev.pci_bdf) + slot = dev.pci_bdf.rsplit(".", 1)[0] + slot_rids = tpu7x_slot_raw_ids.get(slot, []) + pkg_tok = proved_pkg_tokens.get(dev.pci_bdf) + owner_tok = pkg_tok if pkg_tok is not None else f"bdf:{dev.pci_bdf}" + if phys_pair is not None: + if 0 <= phys_pair and (dpc * phys_pair + dpc - 1) <= _MAX_RUNTIME_DEVICE_ID: + already_self_resolved = owner_resolved_ids.get(owner_tok, set()) + for off in range(dpc): + cand = str(dpc * phys_pair + off) + pkg_logical_owners.setdefault(cand, set()).add(owner_tok) + if ( + cand not in already_self_resolved + and (owner_tok, cand) not in reserved_phys_owner_cands + ): + reserved_phys_owner_cands.add((owner_tok, cand)) + logical_claimants.setdefault(cand, []).append(dev.pci_bdf) + if rt_id is not None: + logical_claimants.setdefault(rt_id, []).append(dev.pci_bdf) + pkg_logical_owners.setdefault(rt_id, set()).add(owner_tok) + parsed_rt = _parse_runtime_device_id(rt_id) + if dev.generation == "tpu7x": + if parsed_rt is not None: + sib_str = str(parsed_rt ^ 1) + if pkg_tok is not None: + pkg_logical_owners.setdefault(sib_str, set()).add(pkg_tok) + elif sib_str not in tpu7x_all_resolved_ids: + speculative_claimants.setdefault(sib_str, []).append(dev.pci_bdf) + if len(tpu7x_slot_resolved_pkgs.get(slot, set())) > 1: + extra_ambiguous_rt.add(rt_id) + extra_ambiguous_rt.add(sib_str) + if phys_pair is not None and (parsed_rt is None or (parsed_rt // dpc) != phys_pair): + extra_ambiguous_rt.add(rt_id) + if parsed_rt is not None and dpc == 2: + extra_ambiguous_rt.add(str(parsed_rt ^ 1)) + if 0 <= phys_pair and (dpc * phys_pair + dpc - 1) <= _MAX_RUNTIME_DEVICE_ID: + for off in range(dpc): + rcand = str(dpc * phys_pair + off) + extra_ambiguous_rt.add(rcand) + logical_claimants.setdefault(rcand, []).append(dev.pci_bdf) + pkg_logical_owners.setdefault(rcand, set()).add(owner_tok) + if dev.generation == "tpu7x" and dev.runtime_chip_id: + pr = _parse_runtime_device_id(dev.runtime_chip_id) + eff_pkg = parsed_rt // 2 if parsed_rt is not None else phys_pair + if pr is not None and eff_pkg is not None: + same_slot_pair = len(slot_rids) == 2 and slot_rids[0] == slot_rids[1] + if same_slot_pair and pr != eff_pkg: + if (2 * pr + 1) <= _MAX_RUNTIME_DEVICE_ID: + speculative_claimants.setdefault(str(2 * pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(2 * pr + 1), []).append(dev.pci_bdf) + elif not same_slot_pair and (pr // 2) != eff_pkg and pr != eff_pkg: + speculative_claimants.setdefault(str(pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(pr ^ 1), []).append(dev.pci_bdf) + if (2 * pr + 1) <= _MAX_RUNTIME_DEVICE_ID: + speculative_claimants.setdefault(str(2 * pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(2 * pr + 1), []).append(dev.pci_bdf) + else: + if phys_pair is None and dev.generation == "tpu7x" and pkg_tok is not None and not proved_pkg_resolved_pkgs.get(pkg_tok): + pmems = proved_pkg_members.get(pkg_tok, []) + sys_rids = [ + _parse_runtime_device_id(m.runtime_chip_id) + for m in pmems + if m.runtime_chip_id is not None + ] + if ( + len(pmems) == 2 + and len(sys_rids) == 2 + and sys_rids[0] is not None + and sys_rids[0] == sys_rids[1] + and pkg_tok not in reserved_sysfs_pkg_tokens + ): + pr_pkg = sys_rids[0] + if 0 <= pr_pkg and (2 * pr_pkg + 1) <= _MAX_RUNTIME_DEVICE_ID: + reserved_sysfs_pkg_tokens.add(pkg_tok) + pkg_logical_owners.setdefault(str(2 * pr_pkg), set()).add(pkg_tok) + pkg_logical_owners.setdefault(str(2 * pr_pkg + 1), set()).add(pkg_tok) + if dev.generation == "tpu7x" and dev.runtime_chip_id: + pr = _parse_runtime_device_id(dev.runtime_chip_id) + if pr is not None: + same_slot_pair = len(slot_rids) == 2 and slot_rids[0] == slot_rids[1] + if phys_pair is None or (same_slot_pair and pr != phys_pair) or ( + not same_slot_pair and (pr // 2) != phys_pair and pr != phys_pair + ): + if same_slot_pair: + if (2 * pr + 1) <= _MAX_RUNTIME_DEVICE_ID: + speculative_claimants.setdefault(str(2 * pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(2 * pr + 1), []).append(dev.pci_bdf) + else: + speculative_claimants.setdefault(str(pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(pr ^ 1), []).append(dev.pci_bdf) + if (2 * pr + 1) <= _MAX_RUNTIME_DEVICE_ID: + speculative_claimants.setdefault(str(2 * pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(2 * pr + 1), []).append(dev.pci_bdf) + if phys_pair is not None and 0 <= phys_pair and (2 * phys_pair + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * phys_pair)) + extra_ambiguous_rt.add(str(2 * phys_pair + 1)) + if same_slot_pair and (2 * pr + 1) <= _MAX_RUNTIME_DEVICE_ID: + extra_ambiguous_rt.add(str(2 * pr)) + extra_ambiguous_rt.add(str(2 * pr + 1)) + continue + rt_id = resolved_by_bdf.get(dev.pci_bdf) + rt_pair: Optional[int] = None + if rt_id is not None: + parsed_rt = _parse_runtime_device_id(rt_id) + if parsed_rt is not None: + rt_pair = parsed_rt // 2 + if rt_id in base_ambiguous_rt: + ambiguous_pair_bdfs.add(dev.pci_bdf) + if rt_pair is not None and phys_pair is not None and rt_pair != phys_pair: + ambiguous_pair_bdfs.add(dev.pci_bdf) + if 0 <= rt_pair and (2 * rt_pair + 1) <= _MAX_RUNTIME_DEVICE_ID: + logical_claimants.setdefault(str(2 * rt_pair), []).append(dev.pci_bdf) + logical_claimants.setdefault(str(2 * rt_pair + 1), []).append(dev.pci_bdf) + pkg_logical_owners.setdefault(str(2 * rt_pair), set()).add(f"bdf:{dev.pci_bdf}") + pkg_logical_owners.setdefault(str(2 * rt_pair + 1), set()).add(f"bdf:{dev.pci_bdf}") + if 0 <= phys_pair and (2 * phys_pair + 1) <= _MAX_RUNTIME_DEVICE_ID: + logical_claimants.setdefault(str(2 * phys_pair), []).append(dev.pci_bdf) + logical_claimants.setdefault(str(2 * phys_pair + 1), []).append(dev.pci_bdf) + pkg_logical_owners.setdefault(str(2 * phys_pair), set()).add(f"bdf:{dev.pci_bdf}") + pkg_logical_owners.setdefault(str(2 * phys_pair + 1), set()).add(f"bdf:{dev.pci_bdf}") + continue + chosen = rt_pair if rt_pair is not None else phys_pair + if dev.runtime_chip_id: + pr = _parse_runtime_device_id(dev.runtime_chip_id) + if pr is not None and 0 <= pr and (2 * pr + 1) <= _MAX_RUNTIME_DEVICE_ID: + if chosen is None: + # Unmapped 1-fn Ironwood owns `{2*pr, 2*pr+1}` unconditionally against + # outside claimants (both inferred and explicit maps) unless itself remapped. + logical_claimants.setdefault(str(2 * pr), []).append(dev.pci_bdf) + logical_claimants.setdefault(str(2 * pr + 1), []).append(dev.pci_bdf) + pkg_logical_owners.setdefault(str(2 * pr), set()).add(f"bdf:{dev.pci_bdf}") + pkg_logical_owners.setdefault(str(2 * pr + 1), set()).add(f"bdf:{dev.pci_bdf}") + elif pr != chosen: + speculative_claimants.setdefault(str(2 * pr), []).append(dev.pci_bdf) + speculative_claimants.setdefault(str(2 * pr + 1), []).append(dev.pci_bdf) + if chosen is not None: + if chosen < 0 or (2 * chosen + 1) > _MAX_RUNTIME_DEVICE_ID: + ambiguous_pair_bdfs.add(dev.pci_bdf) + continue + pair = (str(2 * chosen), str(2 * chosen + 1)) + logical_claimants.setdefault(pair[0], []).append(dev.pci_bdf) + logical_claimants.setdefault(pair[1], []).append(dev.pci_bdf) + pkg_logical_owners.setdefault(pair[0], set()).add(f"bdf:{dev.pci_bdf}") + pkg_logical_owners.setdefault(pair[1], set()).add(f"bdf:{dev.pci_bdf}") + if dev.pci_bdf not in ambiguous_pair_bdfs: + raw_pairs[dev.pci_bdf] = pair + + ambiguous_rt_ids = set(base_ambiguous_rt) | extra_ambiguous_rt + for cid, owners in pkg_logical_owners.items(): + if len(owners) > 1: + ambiguous_rt_ids.add(cid) + for bdf in logical_claimants.get(cid, ()): + if bdf in raw_pairs or bdf in dual_set: + ambiguous_pair_bdfs.add(bdf) + for cid, claim_bdfs in logical_claimants.items(): + spec_bdfs = speculative_claimants.get(cid, []) + has_spec_conflict = bool(spec_bdfs) and any( + bdf not in explicit_mapped_bdfs and any(sb != bdf for sb in spec_bdfs) + for bdf in claim_bdfs + ) + if len(claim_bdfs) > 1 or has_spec_conflict: + ambiguous_rt_ids.add(cid) + for bdf in claim_bdfs: + if bdf in raw_pairs or bdf in dual_set: + ambiguous_pair_bdfs.add(bdf) + for bdf in list(raw_pairs): + if bdf in ambiguous_pair_bdfs: + raw_pairs.pop(bdf, None) + return resolved_by_bdf, ambiguous_rt_ids, raw_pairs, ambiguous_pair_bdfs + + +def _resolve_tpu7x_pkg_d2d_pairs( + devices: Sequence[TpuTelemetry], + shared_vfio: set[str], + chip_id_map: Optional[Dict[str, str]], + dual_chiplet_pkg_bdfs: Optional[set[str]], + physical_chip_map: Optional[Dict[str, int]] = None, +) -> Tuple[Dict[str, Tuple[str, str]], set[str]]: + """Derive each `1-fn` Ironwood package's D2D logical pair `(2*p, 2*p+1)` ONCE.""" + _res, _amb_rt, raw_pairs, ambiguous_bdfs = _collect_unified_logical_ownership( + devices, + shared_vfio, + chip_id_map, + dual_chiplet_pkg_bdfs, + physical_chip_map=physical_chip_map, + ) + return raw_pairs, ambiguous_bdfs + + def _verified_row_alias_map( devices: Sequence[TpuTelemetry], shared_vfio: set[str], chip_id_map: Optional[Dict[str, str]], + dual_chiplet_pkg_bdfs: Optional[set[str]] = None, + physical_chip_map: Optional[Dict[str, int]] = None, ) -> Dict[str, str]: """Map every verified non-ambiguous alias for a TPU (`pci_bdf`, unique `/dev/vfio/`, verified `runtime_id`) to one canonical row key so multi-backend fallback merges combine fields onto the same device row.""" - resolved_by_bdf, ambiguous = _resolve_raw_device_runtime_ids( - devices, shared_vfio, chip_id_map + resolved_by_bdf, ambiguous, _raw_pairs, _amb_pairs = _collect_unified_logical_ownership( + devices, + shared_vfio, + chip_id_map, + dual_chiplet_pkg_bdfs, + physical_chip_map=physical_chip_map, ) aliases: Dict[str, str] = {} for dev in devices: + has_excl_vfio = _has_exclusive_vfio_device(dev, shared_vfio) + if dual_chiplet_pkg_bdfs and dev.pci_bdf in dual_chiplet_pkg_bdfs: + aliases[dev.pci_bdf] = dev.pci_bdf + if has_excl_vfio: + aliases[dev.vfio_device] = dev.pci_bdf + continue rt_id = resolved_by_bdf.get(dev.pci_bdf) if rt_id in ambiguous: rt_id = None canonical = rt_id if rt_id else dev.pci_bdf aliases[dev.pci_bdf] = canonical - if dev.vfio_device and dev.vfio_device not in shared_vfio: + if has_excl_vfio: aliases[dev.vfio_device] = canonical if rt_id: aliases[rt_id] = canonical @@ -2830,39 +4351,85 @@ def _expected_runtime_ids_for_devices( devices: Sequence[TpuTelemetry], shared_vfio: set[str], chip_id_map: Optional[Dict[str, str]], + dual_chiplet_pkg_bdfs: Optional[set[str]] = None, + physical_chip_map: Optional[Dict[str, int]] = None, ) -> set[str]: - """Return the set of non-ambiguous expected runtime IDs established by - verified sysfs `chip_id` and/or explicit `--chip-id-map`.""" - resolved_by_bdf, ambiguous = _resolve_raw_device_runtime_ids( - devices, shared_vfio, chip_id_map + """Return non-ambiguous expected logical runtime IDs from sysfs `chip_id`, `--chip-id-map`, and `--physical-chip-map`.""" + resolved_by_bdf, ambiguous, pkg_pairs, _ = _collect_unified_logical_ownership( + devices, + shared_vfio, + chip_id_map, + dual_chiplet_pkg_bdfs, + physical_chip_map=physical_chip_map, ) - return { - rt - for rt in resolved_by_bdf.values() - if rt is not None and rt not in ambiguous - } + expected: set[str] = set() + for dev in devices: + if dual_chiplet_pkg_bdfs and dev.pci_bdf in dual_chiplet_pkg_bdfs: + pair = pkg_pairs.get(dev.pci_bdf) + if pair is not None: + expected.add(pair[0]) + expected.add(pair[1]) + continue + rt = resolved_by_bdf.get(dev.pci_bdf) + if rt is not None and rt not in ambiguous: + expected.add(rt) + return expected def _has_complete_utilization( rows: Dict[str, _TpuInfoRow], expected_runtime_ids: Optional[set[str]] = None, min_expected_rows: int = 0, + *, + verified_row_aliases: Optional[Dict[str, str]] = None, + dual_chiplet_pkg_bdfs: Optional[set[str]] = None, ) -> bool: - """Return True when every observed runtime device row (and every expected - runtime ID established by PCI inventory / `--chip-id-map`, plus at least - `min_expected_rows` logical runtime rows derived from visible PCI devices) - has both HBM usage/total and duty-cycle.""" - util_rows = {k: r for k, r in rows.items() if r.in_util_table} + """Return True when every valid observed runtime device row (and logical + runtime chiplet coverage counted separately from package-level BDF/VFIO + rows and deduplicated across verified aliases) has both HBM usage/total and + duty-cycle. Malformed/unrecognized row keys are excluded from coverage.""" + recognized_rows: List[Tuple[str, str, _TpuInfoRow]] = [] + util_rows: Dict[str, _TpuInfoRow] = {} + for raw_k, r in rows.items(): + if not r.in_util_table: + continue + classified = _classify_util_row_key(raw_k) + if classified is None: + continue + recognized_rows.append((classified[0], classified[1], r)) + util_rows[classified[1]] = r if not util_rows: return False - if not all(_row_has_complete_utilization(r) for r in util_rows.values()): + if not all(_row_has_complete_utilization(r) for _, _, r in recognized_rows): return False - complete_ids = { - k for k, r in util_rows.items() if _row_has_complete_utilization(r) - } - if min_expected_rows > 0 and len(complete_ids) < min_expected_rows: + dual_set = dual_chiplet_pkg_bdfs or set() + aliases = verified_row_aliases if verified_row_aliases is not None else {} + complete_logical_ids: set[str] = set() + complete_single_pkg_rows: set[str] = set() + for key_type, canon_k, r in recognized_rows: + if not _row_has_complete_utilization(r): + continue + if key_type == "id": + complete_logical_ids.add(canon_k) + else: + if verified_row_aliases is not None and canon_k not in aliases: + continue + aliased = aliases.get(canon_k, canon_k) + if aliased in dual_set: + continue + if _parse_runtime_device_id(aliased) is not None: + complete_logical_ids.add(aliased) + else: + complete_single_pkg_rows.add(aliased) + exp_ids = expected_runtime_ids or set() + if exp_ids and not exp_ids.issubset(complete_logical_ids): return False - if expected_runtime_ids and not expected_runtime_ids.issubset(complete_ids): + exp_satisfied = complete_logical_ids & exp_ids + extra_numeric = complete_logical_ids - exp_ids + effective_count = len(exp_satisfied) + max( + len(complete_single_pkg_rows), len(extra_numeric) + ) + if min_expected_rows > 0 and effective_count < min_expected_rows: return False return True @@ -3049,7 +4616,8 @@ def _merge_one( *, keep_existing: bool, ) -> None: - k = alias_to_canonical.get(raw_key, raw_key) if alias_to_canonical else raw_key + norm_key = _canonical_runtime_row_key(raw_key) + k = alias_to_canonical.get(norm_key, norm_key) if alias_to_canonical else norm_key existing = target.get(k) if existing is not None: used_extra = False @@ -3107,39 +4675,66 @@ def _resolve_device_runtime_mapping( parsed_rows: Dict[str, _TpuInfoRow], shared_vfio: set[str], chip_id_map: Optional[Dict[str, str]], + *, + dual_chiplet_pkg_bdfs: Optional[set[str]] = None, + physical_chip_map: Optional[Dict[str, int]] = None, ) -> Tuple[ Dict[str, Optional[str]], set[str], Dict[str, Optional[str]], set[str], + Dict[str, Tuple[str, str]], + set[str], ]: - """Resolve authoritative runtime chip IDs and utilization row keys for discovered PCI devices. - - Only authoritative sources are accepted for runtime-ordinal-to-PCI mapping: - 1. Verified sysfs `chip_id` (`dev.runtime_chip_id`) - 2. Explicit `--chip-id-map` (`pci_bdf` or non-shared `/dev/vfio/`) - - `tpu-info` CLI Process Monitor guesses `/dev/vfio/` when runtime IDs - differ from IOMMU groups, so it is NEVER treated as authoritative PCI identity. - Any runtime ID or utilization row claimed by >1 physical PCI device is flagged - ambiguous so it remains keyed strictly by runtime ID (`pci_bdf="unmapped"`). - """ - util_rows = {k: r for k, r in parsed_rows.items() if r.in_util_table} - resolved_rt_ids, ambiguous_rt_ids = _resolve_raw_device_runtime_ids( - devices, shared_vfio, chip_id_map + """Resolve authoritative runtime chip IDs, `1-fn` D2D pairs, and utilization row keys.""" + util_rows = { + k: r + for k, r in parsed_rows.items() + if r.in_util_table and _classify_util_row_key(k) is not None + } + dual_set = dual_chiplet_pkg_bdfs or set() + resolved_rt_ids, ambiguous_rt_ids, pkg_d2d_pairs, ambiguous_pair_bdfs = ( + _collect_unified_logical_ownership( + devices, + shared_vfio, + chip_id_map, + dual_set, + physical_chip_map=physical_chip_map, + ) ) prospective_util_key: Dict[str, Optional[str]] = {} util_key_claimants: Dict[str, List[str]] = {} + tpu7x_slot_union: Dict[str, set[str]] = {} + for d in devices: + if d.generation == "tpu7x": + sl = d.pci_bdf.rsplit(".", 1)[0] + tpu7x_slot_union.setdefault(sl, set()).add(d.pci_bdf) + for m_src in (chip_id_map, physical_chip_map): + if not m_src: + continue + for raw_k in m_src: + if not isinstance(raw_k, str) or raw_k.strip().startswith("/"): + continue + cb = _canon_map_bdf(raw_k) + if not _CANON_PCI_BDF_RE.match(cb): + continue + sl = cb.rsplit(".", 1)[0] + if sl in tpu7x_slot_union: + tpu7x_slot_union[sl].add(str(cb)) + oversized_slots = {sl for sl, bset in tpu7x_slot_union.items() if len(bset) > 2} for dev in devices: - is_shared_vfio = bool(dev.vfio_device and dev.vfio_device in shared_vfio) + if dev.generation == "tpu7x" and dev.pci_bdf.rsplit(".", 1)[0] in oversized_slots: + prospective_util_key[dev.pci_bdf] = None + continue + has_excl_vfio = _has_exclusive_vfio_device(dev, shared_vfio) rt_id = resolved_rt_ids.get(dev.pci_bdf) if rt_id in ambiguous_rt_ids: rt_id = None util_candidates: List[str] = [dev.pci_bdf] - if dev.vfio_device and not is_shared_vfio: + if has_excl_vfio: util_candidates.append(dev.vfio_device) - if rt_id: + if rt_id and dev.pci_bdf not in dual_set: util_candidates.append(rt_id) matched_key: Optional[str] = None @@ -3152,7 +4747,14 @@ def _resolve_device_runtime_mapping( util_key_claimants.setdefault(matched_key, []).append(dev.pci_bdf) ambiguous_util_keys = {k for k, bdfs in util_key_claimants.items() if len(bdfs) > 1} - return resolved_rt_ids, ambiguous_rt_ids, prospective_util_key, ambiguous_util_keys + return ( + resolved_rt_ids, + ambiguous_rt_ids, + prospective_util_key, + ambiguous_util_keys, + pkg_d2d_pairs, + ambiguous_pair_bdfs, + ) def collect_snapshot( @@ -3173,6 +4775,8 @@ def collect_snapshot( gcp_metadata_url: str = DEFAULT_GCP_METADATA_PREEMPTED_URL, gcp_metadata_timeout_s: float = 0.5, trust_tpu_info_cli_duty: bool = False, + physical_chip_map: Optional[Dict[str, int]] = None, + tpu7x_pci_layout: str = "auto", ) -> ExporterSnapshot: """Collect PCI/VFIO discovery, SeqLock SHM, AER counters, optional procfs PIDs, and gRPC/`tpu-info` metrics.""" if grpc_duty_layout not in VALID_GRPC_DUTY_LAYOUTS: @@ -3180,10 +4784,30 @@ def collect_snapshot( f"Invalid --grpc-duty-layout {grpc_duty_layout!r}; " f"expected one of {', '.join(VALID_GRPC_DUTY_LAYOUTS)}" ) + if tpu7x_pci_layout not in VALID_TPU7X_PCI_LAYOUTS: + raise ValueError( + f"Invalid --tpu7x-pci-layout {tpu7x_pci_layout!r}; " + f"expected one of {', '.join(VALID_TPU7X_PCI_LAYOUTS)}" + ) t0 = time.monotonic() - devices = discover_tpu_devices(sysfs_root=sysfs_root, dev_root=dev_root) + bridge_bus_to_roots = _scan_pcie_bridge_roots(sysfs_root) + physical_chip_map = _canon_physical_chip_map(physical_chip_map) + devices = discover_tpu_devices( + sysfs_root=sysfs_root, + dev_root=dev_root, + physical_chip_map=physical_chip_map, + chip_id_map=chip_id_map, + tpu7x_pci_layout=tpu7x_pci_layout, + bridge_bus_to_roots=bridge_bus_to_roots, + ) shared_vfio = _shared_vfio_paths(devices) - validate_chip_id_map(devices, chip_id_map) + validate_chip_id_map( + devices, + chip_id_map, + physical_chip_map=physical_chip_map, + tpu7x_pci_layout=tpu7x_pci_layout, + bridge_bus_to_roots=bridge_bus_to_roots, + ) # Scan /proc//fd for open handles to /vfio/ (including # any separate-group sibling PCI functions collapsed onto legacy v2/v3 chips) @@ -3208,10 +4832,27 @@ def collect_snapshot( proc_root, real_vfio_paths, expected_devnums=expected_vfio_devnums ) + dual_chiplet_pkg_bdfs = _tpu7x_dual_chiplet_pkg_bdfs( + devices, + physical_chip_map=physical_chip_map, + chip_id_map=chip_id_map, + tpu7x_pci_layout=tpu7x_pci_layout, + bridge_bus_to_roots=bridge_bus_to_roots, + ) expected_runtime_ids = _expected_runtime_ids_for_devices( - devices, shared_vfio, chip_id_map + devices, + shared_vfio, + chip_id_map, + dual_chiplet_pkg_bdfs=dual_chiplet_pkg_bdfs, + physical_chip_map=physical_chip_map, + ) + verified_row_aliases = _verified_row_alias_map( + devices, + shared_vfio, + chip_id_map, + dual_chiplet_pkg_bdfs=dual_chiplet_pkg_bdfs, + physical_chip_map=physical_chip_map, ) - verified_row_aliases = _verified_row_alias_map(devices, shared_vfio, chip_id_map) runtime_budget_s = max(0.05, float(tpu_info_timeout_s)) runtime_deadline = time.monotonic() + runtime_budget_s runtime_addr_err: Optional[str] = None @@ -3225,6 +4866,12 @@ def collect_snapshot( explicit_non_default_runtime_addr = bool( runtime_metrics_addr and runtime_metrics_addr != DEFAULT_RUNTIME_METRICS_ADDR ) + min_expected_runtime_rows = sum( + max(1, TPU_CHIPLETS_PER_PKG.get(d.generation, 1)) + if d.pci_bdf in dual_chiplet_pkg_bdfs + else 1 + for d in devices + ) if not tpu_info_bin: # Empty/None `--tpu-info-bin` explicitly disables `libtpu` runtime # telemetry (direct gRPC, `tpu_info.metrics`, and CLI) across every mode. @@ -3257,7 +4904,9 @@ def collect_snapshot( or not _has_complete_utilization( parsed_rows, expected_runtime_ids=expected_runtime_ids, - min_expected_rows=len(devices), + min_expected_rows=min_expected_runtime_rows, + verified_row_aliases=verified_row_aliases, + dual_chiplet_pkg_bdfs=dual_chiplet_pkg_bdfs, ) ) ): @@ -3334,7 +4983,9 @@ def collect_snapshot( or not _has_complete_utilization( parsed_rows, expected_runtime_ids=expected_runtime_ids, - min_expected_rows=len(devices), + min_expected_rows=min_expected_runtime_rows, + verified_row_aliases=verified_row_aliases, + dual_chiplet_pkg_bdfs=dual_chiplet_pkg_bdfs, ) ) and cli_has_budget: cli_ok, cli_err, cli_rows = _run_tpu_info( @@ -3373,7 +5024,9 @@ def collect_snapshot( or not _has_complete_utilization( parsed_rows, expected_runtime_ids=expected_runtime_ids, - min_expected_rows=len(devices), + min_expected_rows=min_expected_runtime_rows, + verified_row_aliases=verified_row_aliases, + dual_chiplet_pkg_bdfs=dual_chiplet_pkg_bdfs, ) ) and valid_runtime_metrics_addr @@ -3403,7 +5056,11 @@ def collect_snapshot( alias_to_canonical=verified_row_aliases, ) tpu_info_ok, tpu_info_err = True, None - util_rows = {k: r for k, r in parsed_rows.items() if r.in_util_table} + util_rows = { + k: r + for k, r in parsed_rows.items() + if r.in_util_table and _classify_util_row_key(k) is not None + } mapped_util_keys: Dict[str, str] = {} overall_pid_available = True @@ -3412,7 +5069,16 @@ def collect_snapshot( ambiguous_rt_ids, prospective_util_key, ambiguous_util_keys, - ) = _resolve_device_runtime_mapping(devices, parsed_rows, shared_vfio, chip_id_map) + pkg_d2d_pairs, + ambiguous_pair_bdfs, + ) = _resolve_device_runtime_mapping( + devices, + parsed_rows, + shared_vfio, + chip_id_map, + dual_chiplet_pkg_bdfs=dual_chiplet_pkg_bdfs, + physical_chip_map=physical_chip_map, + ) for dev in devices: dev_groups = ([dev.iommu_group] if dev.iommu_group else []) + [ @@ -3439,10 +5105,11 @@ def collect_snapshot( dev.runtime_chip_id = rt_id verified_rt_id = rt_id - # Attach `TPU Chips` rows strictly by verified /dev/vfio/, PCI BDF, + # Attach `TPU Chips` rows strictly by exclusive /dev/vfio/, PCI BDF, # or canonicalized verified runtime ID for this device. chips_row: Optional[_TpuInfoRow] = None - for key in (dev.vfio_device, dev.pci_bdf, verified_rt_id): + excl_vfio_key = dev.vfio_device if _has_exclusive_vfio_device(dev, shared_vfio) else None + for key in (excl_vfio_key, dev.pci_bdf, verified_rt_id): if key and key in parsed_rows and parsed_rows[key].in_chips_table: chips_row = parsed_rows[key] break @@ -3452,19 +5119,47 @@ def collect_snapshot( matched_key = prospective_util_key.get(dev.pci_bdf) matched_util: Optional[_TpuInfoRow] = None - if matched_key is not None and matched_key not in ambiguous_util_keys: + used_pkg_pair = False + if dev.pci_bdf in dual_chiplet_pkg_bdfs: + pkg_pair = ( + pkg_d2d_pairs.get(dev.pci_bdf) + if dev.pci_bdf not in ambiguous_pair_bdfs + else None + ) + if pkg_pair is not None: + pair_rows: List[_TpuInfoRow] = [] + for cid in pkg_pair: + if cid in util_rows: + mapped_util_keys[cid] = dev.pci_bdf + pair_rows.append(util_rows[cid]) + if len(pair_rows) == 2 and all( + r.hbm_used_bytes is not None for r in pair_rows + ): + dev.hbm_used_bytes = sum(r.hbm_used_bytes or 0 for r in pair_rows) + dev.telemetry_source = _format_row_source(pair_rows[0]) + used_pkg_pair = True + if matched_key is not None and matched_key not in ambiguous_util_keys: + mapped_util_keys[matched_key] = dev.pci_bdf + matched_util = util_rows[matched_key] + elif matched_key is not None and matched_key not in ambiguous_util_keys: matched_util = util_rows[matched_key] mapped_util_keys[matched_key] = dev.pci_bdf if matched_util is not None: - if ( + if not used_pkg_pair and ( matched_util.hbm_used_bytes is not None or matched_util.hbm_total_bytes is not None or matched_util.duty_cycle_percent is not None or matched_util.hbm_bw_util_percent is not None ): dev.telemetry_source = _format_row_source(matched_util) - if matched_util.hbm_used_bytes is not None: + elif used_pkg_pair and ( + matched_util.duty_cycle_percent is not None + or matched_util.hbm_bw_util_percent is not None + or matched_util.hbm_total_bytes is not None + ) and dev.telemetry_source in ("sysfs-fallback", "libopentpu-shm"): + dev.telemetry_source = _format_row_source(matched_util) + if not used_pkg_pair and matched_util.hbm_used_bytes is not None: dev.hbm_used_bytes = matched_util.hbm_used_bytes if matched_util.hbm_total_bytes is not None: dev.hbm_total_bytes = matched_util.hbm_total_bytes @@ -4001,6 +5696,8 @@ def __init__( gcp_metadata_timeout_s: float = 0.5, max_workers: int = DEFAULT_MAX_HTTP_WORKERS, scrape_timeout_s: float = 10.0, + physical_chip_map: Optional[Dict[str, int]] = None, + tpu7x_pci_layout: str = "auto", ) -> None: self.sysfs_root = sysfs_root self.dev_root = dev_root @@ -4019,6 +5716,8 @@ def __init__( self.gcp_metadata_url = gcp_metadata_url self.gcp_metadata_timeout_s = gcp_metadata_timeout_s self.scrape_timeout_s = scrape_timeout_s + self.physical_chip_map = physical_chip_map + self.tpu7x_pci_layout = tpu7x_pci_layout self._scrape_lock = threading.Lock() scrape_cap = max(1, max_workers) self._scrape_sem = threading.BoundedSemaphore(scrape_cap) @@ -4077,6 +5776,8 @@ def scrape(self) -> ExporterSnapshot: gcp_metadata_preemption=self.gcp_metadata_preemption, gcp_metadata_url=self.gcp_metadata_url, gcp_metadata_timeout_s=self.gcp_metadata_timeout_s, + physical_chip_map=self.physical_chip_map, + tpu7x_pci_layout=self.tpu7x_pci_layout, ) finally: self._scrape_lock.release() @@ -4245,6 +5946,26 @@ def _no_duplicate_keys(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]: return {str(k): str(v).strip() for k, v in parsed.items()} +def _load_physical_chip_map(raw: Optional[Path | str]) -> Optional[Dict[str, int]]: + loaded = _load_chip_id_map(raw) + if loaded is None: + return None + out: Dict[str, int] = {} + for key, val in loaded.items(): + if key.startswith("/"): + raise ValueError( + f"Invalid --physical-chip-map key {key!r}: expected PCI BDF, not VFIO path" + ) + parsed_val = _parse_runtime_device_id(val) + if parsed_val is None: + raise ValueError( + f"Invalid --physical-chip-map value {val!r} for {key!r}: " + "expected non-negative physical chip integer" + ) + out[key] = parsed_val + return out + + def build_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="tpu-exporter", @@ -4316,8 +6037,28 @@ def build_arg_parser() -> argparse.ArgumentParser: type=str, default=None, help=( - "Optional inline JSON or file path mapping {pci_bdf_or_unique_vfio_path: runtime_chip_id} " - "for verified tpu-info joins (shared VFIO groups require explicit PCI BDF keys)." + "Optional inline JSON or file path mapping {pci_bdf_or_unique_vfio_path: logical_runtime_chip_id} " + "for verified tpu-info joins (shared VFIO groups require explicit PCI BDF keys; " + "per-core freetpu-cdi --chip-id-map maps assigning distinct logical 0..7 IDs belong here)." + ), + ) + parser.add_argument( + "--physical-chip-map", + type=str, + default=None, + help=( + "Optional inline JSON or file path mapping {pci_bdf: physical_chip_id} " + "assigning physical package IDs (e.g. 0..3 per physical chip on 1-fn dual-chiplet 0x0075 " + "or shared 0..3 package IDs across 2-fn Ironwood pairs; pass per-core 0..7 CDI maps to --chip-id-map)." + ), + ) + parser.add_argument( + "--tpu7x-pci-layout", + choices=VALID_TPU7X_PCI_LAYOUTS, + default="auto", + help=( + "Ironwood (tpu7x) PCI function layout override for nominal HBM accounting " + "(`auto`, `1fn` dual-chiplet per PF, or `2fn` single-chiplet per PF; default: auto)." ), ) parser.add_argument( @@ -4435,12 +6176,21 @@ def main(argv: Optional[Sequence[str]] = None) -> int: runtime_metrics_addr = args.runtime_metrics_addr if args.runtime_metrics_addr else None try: chip_id_map = _load_chip_id_map(args.chip_id_map) - if chip_id_map: + physical_chip_map = _load_physical_chip_map(args.physical_chip_map) + if chip_id_map or physical_chip_map or args.tpu7x_pci_layout != "auto": initial_devices = discover_tpu_devices( sysfs_root=args.sysfs_root, dev_root=args.dev_root, + physical_chip_map=physical_chip_map, + tpu7x_pci_layout=args.tpu7x_pci_layout, + ) + validate_chip_id_map( + initial_devices, + chip_id_map, + physical_chip_map=physical_chip_map, + tpu7x_pci_layout=args.tpu7x_pci_layout, + bridge_bus_to_roots=_scan_pcie_bridge_roots(args.sysfs_root), ) - validate_chip_id_map(initial_devices, chip_id_map) except ValueError as exc: sys.stderr.write(f"freetpu tpu-exporter error: {exc}\n") return 1 @@ -4464,6 +6214,8 @@ def main(argv: Optional[Sequence[str]] = None) -> int: gcp_metadata_preemption=args.gcp_metadata_preemption, gcp_metadata_url=args.gcp_metadata_url, gcp_metadata_timeout_s=args.gcp_metadata_timeout, + physical_chip_map=physical_chip_map, + tpu7x_pci_layout=args.tpu7x_pci_layout, ) except ValueError as exc: sys.stderr.write(f"freetpu tpu-exporter error: {exc}\n") @@ -4494,6 +6246,8 @@ def main(argv: Optional[Sequence[str]] = None) -> int: gcp_metadata_url=args.gcp_metadata_url, gcp_metadata_timeout_s=args.gcp_metadata_timeout, max_workers=args.max_workers, + physical_chip_map=physical_chip_map, + tpu7x_pci_layout=args.tpu7x_pci_layout, ) health_server: Optional[_HealthServer] = None health_thread: Optional[threading.Thread] = None diff --git a/tools/ironwood-day1/00_pci_vfio_survey.sh b/tools/ironwood-day1/00_pci_vfio_survey.sh index 10cda562..423266d1 100755 --- a/tools/ironwood-day1/00_pci_vfio_survey.sh +++ b/tools/ironwood-day1/00_pci_vfio_survey.sh @@ -97,8 +97,8 @@ while [[ $# -gt 0 ]]; do done for _count_var in EXPECTED_PCI_PACKAGES EXPECTED_LOGICAL_DEVICES; do - if [[ ! "${!_count_var}" =~ ^[0-9]+$ ]]; then - echo "ERROR: ${_count_var} must be a non-negative integer (got '${!_count_var}')" >&2 + if [[ ! "${!_count_var}" =~ ^[0-9]+$ || "${#EXPECTED_PCI_PACKAGES}" -gt 6 || "${#EXPECTED_LOGICAL_DEVICES}" -gt 6 ]]; then + echo "ERROR: ${_count_var} must be a non-negative integer <= 999999 (got '${!_count_var}')" >&2 exit 2 fi done @@ -120,13 +120,17 @@ log() { } emit_topology_status() { - local obs_pci="$1" - local obs_pjrt="$2" - if [[ "${obs_pjrt}" =~ ^[0-9]+$ && "${obs_pci}" -eq "${EXPECTED_PCI_PACKAGES}" && "${obs_pjrt}" -eq "${EXPECTED_LOGICAL_DEVICES}" ]]; then - log "STATUS: PJRT_TOPOLOGY_CAPTURED (pci_tpu_functions=${obs_pci} expected_packages=${EXPECTED_PCI_PACKAGES} pjrt_logical_devices=${obs_pjrt} expected_devices=${EXPECTED_LOGICAL_DEVICES})" + local obs_pkg="$1" + local obs_pci="$2" + local obs_inc="$3" + local obs_pkg_ok="$4" + local obs_pjrt="$5" + local obs_ironwood_ok="$6" + if [[ "${obs_pkg_ok}" -eq 1 && "${obs_ironwood_ok}" -eq 1 && "${obs_inc}" -eq 0 && "${obs_pjrt}" =~ ^[0-9]+$ && "${obs_pkg}" -eq "${EXPECTED_PCI_PACKAGES}" && "${obs_pjrt}" -eq "${EXPECTED_LOGICAL_DEVICES}" ]]; then + log "STATUS: PJRT_TOPOLOGY_CAPTURED (pci_tpu_packages=${obs_pkg} pci_tpu_functions=${obs_pci} incomplete_pci_functions=${obs_inc} expected_packages=${EXPECTED_PCI_PACKAGES} pjrt_logical_devices=${obs_pjrt} expected_devices=${EXPECTED_LOGICAL_DEVICES})" else - log "WARN: TOPOLOGY_COUNT_MISMATCH observed_pci_functions=${obs_pci} expected_packages=${EXPECTED_PCI_PACKAGES} observed_pjrt_devices=${obs_pjrt:-unknown} expected_devices=${EXPECTED_LOGICAL_DEVICES}" - log "STATUS: PJRT_TOPOLOGY_MISMATCH (pci_tpu_functions=${obs_pci} expected_packages=${EXPECTED_PCI_PACKAGES} pjrt_logical_devices=${obs_pjrt:-unknown} expected_devices=${EXPECTED_LOGICAL_DEVICES})" + log "WARN: TOPOLOGY_COUNT_MISMATCH observed_pci_packages=${obs_pkg} observed_pci_functions=${obs_pci} incomplete_pci_functions=${obs_inc} pkg_count_verified=${obs_pkg_ok} ironwood_evidence=${obs_ironwood_ok} expected_packages=${EXPECTED_PCI_PACKAGES} observed_pjrt_devices=${obs_pjrt:-unknown} expected_devices=${EXPECTED_LOGICAL_DEVICES}" + log "STATUS: PJRT_TOPOLOGY_MISMATCH (pci_tpu_packages=${obs_pkg} pci_tpu_functions=${obs_pci} incomplete_pci_functions=${obs_inc} pkg_count_verified=${obs_pkg_ok} ironwood_evidence=${obs_ironwood_ok} expected_packages=${EXPECTED_PCI_PACKAGES} pjrt_logical_devices=${obs_pjrt:-unknown} expected_devices=${EXPECTED_LOGICAL_DEVICES})" fi } @@ -292,7 +296,7 @@ if [[ "${MOCK_MODE}" -eq 1 || ( "$(uname -s)" != "Linux" && "${PCI_SYSFS_DIR}" = log "PJRT_DEVICE index=6 id=6 local_hardware_id=6 kind=\"TPU v7x\" coords=[0,1,0] core_on_chip=0" log "PJRT_DEVICE index=7 id=7 local_hardware_id=7 kind=\"TPU v7x\" coords=[0,1,0] core_on_chip=1" log "PJRT_LOGICAL_DEVICES=8 (4 packages x 2 chiplets)" - emit_topology_status 4 8 + emit_topology_status 4 4 0 1 8 1 exit 0 fi @@ -315,7 +319,14 @@ log "--- /dev/vfio and /dev/iommu nodes ---" ls -la /dev/vfio /dev/iommu 2>&1 | tee -a "${REPORT}" || true tpu_count=0 +tpu_package_count=0 +tpu_incomplete_count=0 +tpu_pkg_verified=1 +tpu_ironwood_package_count=0 +tpu_ironwood_fn_count=0 +tpu_legacy_non_ironwood_count=0 non_tpu_google_count=0 +tpu_entries=() for dev_path in "${PCI_SYSFS_DIR}"/*; do [[ -e "${dev_path}/vendor" ]] || continue vid="$(tr '[:upper:]' '[:lower:]' < "${dev_path}/vendor" 2>/dev/null || echo unknown)" @@ -338,7 +349,11 @@ for dev_path in "${PCI_SYSFS_DIR}"/*; do else grp="none" fi - numa="$(cat "${dev_path}/numa_node" 2>/dev/null || echo -1)" + numa="-1" + if [[ -r "${dev_path}/numa_node" ]]; then + numa="$(LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt " " $0) } END { gsub(/^[ \t\r]+|[ \t\r]+$/, "", txt); print (txt == "" ? "-1" : txt) }' "${dev_path}/numa_node" 2>/dev/null || echo -1)" + fi + pcie_real="$(readlink -f "${dev_path}" 2>/dev/null || echo "${dev_path}")" log "--- TPU BDF=${bdf} vid=${vid} did=${did} class=${cls} driver=${drv} iommu_group=${grp} numa=${numa} ---" if [[ -r "${dev_path}/resource" ]]; then nl -ba "${dev_path}/resource" | head -n 7 | tee -a "${REPORT}" @@ -373,9 +388,267 @@ for dev_path in "${PCI_SYSFS_DIR}"/*; do fi fi fi + tpu_entries+=("${bdf}|${did}|${numa}|${pcie_real}|${dev_path}") tpu_count=$((tpu_count + 1)) done -log "total_tpu_pci_functions=${tpu_count} skipped_non_tpu_0x1ae0=${non_tpu_google_count}" +if [[ "${#tpu_entries[@]}" -eq 0 ]]; then + tpu_package_count=0 + tpu_incomplete_count=0 + tpu_pkg_verified=1 +elif command -v python3 >/dev/null 2>&1; then + pkg_summary="$(printf '%s\n' "${tpu_entries[@]}" | python3 -c ' +import re, sys +from collections import defaultdict +from pathlib import Path + +def read_chip_id_u16(dev_dir: str): + p = Path(dev_dir) / "chip_id" + try: + raw = p.read_bytes() + except OSError: + return None + if b"\x00" in raw: + return None + try: + text = raw.decode("utf-8").strip(" \t\r\n") + except UnicodeDecodeError: + return None + if not text or len(text) > 5 or not text.isascii() or not text.isdigit(): + return None + v = int(text, 10) + return v if 0 <= v <= 65535 else None + +rows = [] +for raw in sys.stdin: + line = raw.rstrip("\r\n") + if not line: + continue + bdf, did, numa, realp, dev_dir = (line.split("|", 4) + ["", "", "", "", ""])[:5] + root = bdf[:7] + m = re.search(r"/pci([0-9a-fA-F]{4}:[0-9a-fA-F]{2})", realp) + if m: + root = m.group(1).lower() + cid = read_chip_id_u16(dev_dir) + try: + numa_strip = (Path(dev_dir) / "numa_node").read_bytes().decode("ascii", errors="surrogateescape").strip(" \t\r\n") + except OSError: + numa_strip = numa.strip(" \t\r\n") + numa_v = int(numa_strip, 10) if re.fullmatch(r"[0-9]+", numa_strip) and len(numa_strip) <= 9 else -1 + dom = ("numa", numa_v, root) if numa_v >= 0 else ("pcie", None, root) + rows.append((bdf, did.lower(), dom, cid)) + +LEGACY_DIDS = {"0x0027", "0x0056", "0x005e", "0x0062", "0x0063", "0x006e", "0x006f"} +t7x = [r for r in rows if r[1] in ("0x0075", "0x0076")] +legacy_other = [r for r in rows if r[1] in LEGACY_DIDS] +unlisted_other = [r for r in rows if r[1] not in ("0x0075", "0x0076") and r[1] not in LEGACY_DIDS] + +def count_two_fn_packages(group_rows): + slot_map = defaultdict(list) + all_cid_counts = defaultdict(int) + for r in group_rows: + slot_map[r[0].rsplit(".", 1)[0]].append(r) + if r[3] is not None: + all_cid_counts[(r[2], r[3])] += 1 + g_pkgs = 0 + g_inc = 0 + g_rem = [] + for _slot, srows in sorted(slot_map.items()): + if len(srows) == 2: + g_pkgs += 1 + elif len(srows) > 2: + g_inc += len(srows) + else: + g_rem.extend(srows) + rem_cid_counts = defaultdict(int) + for _b, _d, dom, cid in g_rem: + if cid is not None: + rem_cid_counts[(dom, cid)] += 1 + pair_buckets = defaultdict(list) + for bdf, _d, dom, cid in g_rem: + if ( + cid is not None + and rem_cid_counts[(dom, cid)] == 2 + and all_cid_counts[(dom, cid)] == 2 + ): + pair_buckets[(dom, cid)].append(bdf) + else: + g_inc += 1 + for _k, pbdfs in pair_buckets.items(): + if len(pbdfs) == 2 and all(b.endswith(".0") for b in pbdfs): + g_pkgs += 1 + else: + g_inc += len(pbdfs) + return g_pkgs, g_inc + +def has_two_fn_signals(group_rows, require_0076=False): + if not group_rows: + return False + slot_map = defaultdict(list) + cid_counts = defaultdict(int) + for bdf, did, dom, cid in group_rows: + slot_map[bdf.rsplit(".", 1)[0]].append(bdf) + if cid is not None: + cid_counts[(dom, cid)] += 1 + return bool( + (require_0076 and any(did == "0x0076" for _, did, _, _ in group_rows)) + or any(not bdf.endswith(".0") for bdf, _, _, _ in group_rows) + or len(group_rows) > 4 + or any(len(v) > 1 for v in slot_map.values()) + or any(cnt > 1 for cnt in cid_counts.values()) + ) + +pkgs = 0 +incomplete = 0 +ironwood_pkgs = 0 +ironwood_fns = len(t7x) +legacy_non_iw = len(legacy_other) +if has_two_fn_signals(t7x, require_0076=True): + t7x_pkgs, t7x_inc = count_two_fn_packages(t7x) + pkgs += t7x_pkgs + incomplete += t7x_inc + ironwood_pkgs += t7x_pkgs +else: + pkgs += len(t7x) + ironwood_pkgs += len(t7x) + +v23_slots = defaultdict(list) +for r in legacy_other: + if r[1] == "0x0027": + v23_slots[r[0].rsplit(".", 1)[0]].append(r) + else: + pkgs += 1 +for _s, srows in v23_slots.items(): + if len(srows) == 2: + pkgs += 1 + else: + incomplete += len(srows) + +if has_two_fn_signals(unlisted_other, require_0076=False): + unl_pkgs, unl_inc = count_two_fn_packages(unlisted_other) + pkgs += unl_pkgs + incomplete += unl_inc +else: + pkgs += len(unlisted_other) +print(f"{pkgs}|{incomplete}|1|{ironwood_pkgs}|{ironwood_fns}|{legacy_non_iw}") +')" + IFS='|' read -r tpu_package_count tpu_incomplete_count tpu_pkg_verified tpu_ironwood_package_count tpu_ironwood_fn_count tpu_legacy_non_ironwood_count <<< "${pkg_summary}" +else + sh_rows=() + for _ent in "${tpu_entries[@]}"; do + IFS='|' read -r _ebdf _edid _enuma _erealp _edevdir <<< "${_ent}" + _eroot="$(printf '%s' "${_erealp}" | sed -n 's#.*/pci\([0-9a-fA-F]\{4\}:[0-9a-fA-F]\{2\}\)/.*#\1#p' | tr '[:upper:]' '[:lower:]')" + [[ -n "${_eroot}" ]] || _eroot="$(printf '%s' "${_ebdf:0:7}" | tr '[:upper:]' '[:lower:]')" + _enuma_trim="$(printf '%s' "${_enuma}" | LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt "\n" $0) } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", txt); printf "%s", txt }')" + if [[ "${_enuma_trim}" =~ ^[0-9]+$ && "${#_enuma_trim}" -le 9 ]]; then + _enuma_v=$((10#${_enuma_trim})) + _edom="numa:${_enuma_v}:${_eroot}" + else + _edom="pcie:none:${_eroot}" + fi + _ecid="" + if [[ -r "${_edevdir}/chip_id" ]]; then + _ecid="$(LC_ALL=C tr '\000' 'X' < "${_edevdir}/chip_id" 2>/dev/null | LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt "\n" $0) } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", txt); if (txt ~ /^[0-9]+$/ && length(txt) <= 5 && (txt + 0) <= 65535) print (txt + 0) }' || true)" + fi + sh_rows+=("${_ebdf}|${_edid}|${_edom}|${_ecid}") + done + pkg_summary_sh="$(printf '%s\n' "${sh_rows[@]}" | LC_ALL=C awk -F'|' ' + function eval_group(kind, req76, i, s, dk, scnt, all_cid, rem_cnt, dot0_cnt, n, g_non0, g_sha, g_dup, two_fn, gp, gi) { + n = g_n[kind] + 0 + if (n == 0) return "0|0" + for (i = 1; i <= n; i++) { + s = g_slot[kind, i] + scnt[s]++ + if (scnt[s] > 1) g_sha = 1 + if (g_bdf[kind, i] !~ /\.0$/) g_non0 = 1 + if (g_cid[kind, i] != "") { + dk = g_dom[kind, i] "|" g_cid[kind, i] + all_cid[dk]++ + if (all_cid[dk] > 1) g_dup = 1 + } + } + two_fn = ((req76 && g_has76[kind]) || g_non0 || n > 4 || g_sha || g_dup) ? 1 : 0 + if (!two_fn) return n "|0" + for (s in scnt) { + if (scnt[s] == 2) gp++ + else if (scnt[s] > 2) gi += scnt[s] + } + for (i = 1; i <= n; i++) { + if (scnt[g_slot[kind, i]] == 1) { + if (g_cid[kind, i] != "") { + dk = g_dom[kind, i] "|" g_cid[kind, i] + rem_cnt[dk]++ + } else { + gi++ + } + } + } + for (i = 1; i <= n; i++) { + if (scnt[g_slot[kind, i]] == 1 && g_cid[kind, i] != "") { + dk = g_dom[kind, i] "|" g_cid[kind, i] + if (rem_cnt[dk] == 2 && all_cid[dk] == 2 && g_bdf[kind, i] ~ /\.0$/) { + dot0_cnt[dk]++ + } else if (rem_cnt[dk] != 2 || all_cid[dk] != 2) { + gi++ + } + } + } + for (dk in rem_cnt) { + if (rem_cnt[dk] == 2 && all_cid[dk] == 2) { + if (dot0_cnt[dk] == 2) gp++ + else gi += 2 + } + } + return (gp + 0) "|" (gi + 0) + } + NF && $1 != "" { + bdf = $1 + did = tolower($2) + dom = $3 + cid = $4 + slot = bdf + sub(/\.[^.]+$/, "", slot) + if (did == "0x0075" || did == "0x0076") { + idx = ++g_n["t7x"] + g_bdf["t7x", idx] = bdf + g_did["t7x", idx] = did + g_dom["t7x", idx] = dom + g_cid["t7x", idx] = cid + g_slot["t7x", idx] = slot + if (did == "0x0076") g_has76["t7x"] = 1 + iw_fns++ + } else if (did == "0x0027") { + leg_cnt++ + v23_slot_cnt[slot]++ + } else if (did == "0x0056" || did == "0x005e" || did == "0x0062" || did == "0x0063" || did == "0x006e" || did == "0x006f") { + leg_cnt++ + pkgs++ + } else { + idx = ++g_n["unl"] + g_bdf["unl", idx] = bdf + g_did["unl", idx] = did + g_dom["unl", idx] = dom + g_cid["unl", idx] = cid + g_slot["unl", idx] = slot + } + } + END { + split(eval_group("t7x", 1), t7x_res, "|") + iw_pkgs = t7x_res[1] + 0 + pkgs += iw_pkgs + inc += t7x_res[2] + 0 + for (s in v23_slot_cnt) { + if (v23_slot_cnt[s] == 2) pkgs++ + else inc += v23_slot_cnt[s] + } + split(eval_group("unl", 0), unl_res, "|") + pkgs += unl_res[1] + 0 + inc += unl_res[2] + 0 + printf "%d|%d|1|%d|%d|%d", pkgs + 0, inc + 0, iw_pkgs + 0, iw_fns + 0, leg_cnt + 0 + } + ')" + IFS='|' read -r tpu_package_count tpu_incomplete_count tpu_pkg_verified tpu_ironwood_package_count tpu_ironwood_fn_count tpu_legacy_non_ironwood_count <<< "${pkg_summary_sh}" +fi +log "total_tpu_pci_packages=${tpu_package_count} total_tpu_pci_functions=${tpu_count} incomplete_pci_functions=${tpu_incomplete_count} pkg_count_verified=${tpu_pkg_verified} ironwood_pci_packages=${tpu_ironwood_package_count} ironwood_pci_functions=${tpu_ironwood_fn_count} legacy_non_ironwood_functions=${tpu_legacy_non_ironwood_count} skipped_non_tpu_0x1ae0=${non_tpu_google_count}" if [[ -f "${REPO_ROOT}/experimental/cloud-tpu/vfio_pci_survey.py" ]] && command -v python3 >/dev/null 2>&1; then log "--- Running experimental/cloud-tpu/vfio_pci_survey.py ---" @@ -386,8 +659,20 @@ extract_pjrt_logical_devices() { printf '%s\n' "$1" | sed -n 's/^PJRT_LOGICAL_DEVICES=\([0-9][0-9]*\).*/\1/p' | tail -n 1 } +classify_pjrt_ironwood_kind() { + local out="$1" + if printf '%s\n' "${out}" | grep -qiE '^PJRT_DEVICE .*kind="[^"]*(v[23456]|tpu[-_ ]?v?[23456]|lite)'; then + printf 'no' + elif printf '%s\n' "${out}" | grep -qiE '^PJRT_DEVICE .*kind="[^"]*(v7x|tpu7x|ironwood)'; then + printf 'yes' + else + printf 'unknown' + fi +} + probe_live_pjrt_topology() { PJRT_LOGICAL_DEVICES_COUNT="" + PJRT_IRONWOOD_KIND="unknown" PJRT_NATIVE_FAIL_REASON="" local pjrt_header="${REPO_ROOT}/libopentpu/third_party/openxla/pjrt_c_api.h" local libtpu_path="${LIBTPU_PATH:-${TPU_LIBRARY_PATH:-}}" @@ -561,6 +846,7 @@ CPPEOF if [[ "${probe_rc}" -eq 0 ]]; then printf '%s\n' "${probe_out}" | tee -a "${REPORT}" PJRT_LOGICAL_DEVICES_COUNT="$(extract_pjrt_logical_devices "${probe_out}")" + PJRT_IRONWOOD_KIND="$(classify_pjrt_ironwood_kind "${probe_out}")" return 0 fi printf '%s\n' "${probe_out}" | tee -a "${REPORT}" @@ -588,6 +874,7 @@ except Exception as exc: print(f"JAX TPU backend unavailable: {exc}") raise SystemExit(10) if not devs: + print("PJRT_LOGICAL_DEVICES=0") print("JAX TPU backend returned 0 devices") raise SystemExit(9) print("PJRT_BACKEND=jax-tpu") @@ -604,6 +891,7 @@ PYEOF if [[ "${py_rc}" -eq 0 ]]; then printf '%s\n' "${py_out}" | tee -a "${REPORT}" PJRT_LOGICAL_DEVICES_COUNT="$(extract_pjrt_logical_devices "${py_out}")" + PJRT_IRONWOOD_KIND="$(classify_pjrt_ironwood_kind "${py_out}")" if [[ -n "${PJRT_NATIVE_FAIL_REASON}" ]]; then log "NOTE: JAX fallback succeeded after native PJRT probe failure (${PJRT_NATIVE_FAIL_REASON})" fi @@ -624,8 +912,17 @@ log "--- Live PJRT Logical Device & Chiplet Topology ---" PJRT_FAIL_REASON="" PJRT_NATIVE_FAIL_REASON="" PJRT_LOGICAL_DEVICES_COUNT="" +PJRT_IRONWOOD_KIND="unknown" if probe_live_pjrt_topology; then - emit_topology_status "${tpu_count}" "${PJRT_LOGICAL_DEVICES_COUNT}" + tpu_ironwood_ok=0 + if [[ "${tpu_legacy_non_ironwood_count}" -eq 0 && "${PJRT_IRONWOOD_KIND}" != "no" ]]; then + if [[ "${tpu_ironwood_package_count}" -eq "${EXPECTED_PCI_PACKAGES}" && "${EXPECTED_PCI_PACKAGES}" -gt 0 ]]; then + tpu_ironwood_ok=1 + elif [[ "${tpu_package_count}" -eq "${EXPECTED_PCI_PACKAGES}" && "${EXPECTED_PCI_PACKAGES}" -gt 0 && "${PJRT_IRONWOOD_KIND}" == "yes" ]]; then + tpu_ironwood_ok=1 + fi + fi + emit_topology_status "${tpu_package_count}" "${tpu_count}" "${tpu_incomplete_count}" "${tpu_pkg_verified}" "${PJRT_LOGICAL_DEVICES_COUNT}" "${tpu_ironwood_ok}" else log "STATUS: PJRT_TOPOLOGY_UNAVAILABLE (${PJRT_FAIL_REASON})" if [[ "${ALLOW_NO_PJRT}" -ne 1 ]]; then diff --git a/tools/ironwood-day1/01_ggml_cloudtpu_ops_bench.sh b/tools/ironwood-day1/01_ggml_cloudtpu_ops_bench.sh index f5a02e3f..caccc398 100755 --- a/tools/ironwood-day1/01_ggml_cloudtpu_ops_bench.sh +++ b/tools/ironwood-day1/01_ggml_cloudtpu_ops_bench.sh @@ -108,6 +108,14 @@ while [[ $# -gt 0 ]]; do esac done +if [[ "${SPMD_CHIPS}" == "AUTO" ]]; then + SPMD_CHIPS="auto" +fi +if [[ "${SPMD_CHIPS}" != "auto" && ( ! "${SPMD_CHIPS}" =~ ^[1-9][0-9]*$ || "${#SPMD_CHIPS}" -gt 2 || "${SPMD_CHIPS}" -gt 16 ) ]]; then + echo "ERROR: --spmd must be 'auto' or an integer between 1 and 16 (got '${SPMD_CHIPS}')" >&2 + exit 2 +fi + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" if [[ -z "${STAGED_RUNS_ROOT}" ]]; then @@ -172,7 +180,23 @@ print(best_path) PYEOF )" else - latest_so="$(ls -t "${search_dirs[@]/%//libtpu*.so}" 2>/dev/null | head -n 1 || true)" + local had_nullglob=0 cand_dir="" cand_so="" + local cand_files=() + shopt -q nullglob && had_nullglob=1 + shopt -s nullglob + for cand_dir in "${search_dirs[@]}"; do + for cand_so in "${cand_dir}"/libtpu*.so; do + if [[ -s "${cand_so}" ]]; then + cand_files+=("${cand_so}") + fi + done + done + if [[ "${had_nullglob}" -eq 0 ]]; then + shopt -u nullglob + fi + if [[ "${#cand_files[@]}" -gt 0 ]]; then + latest_so="$(ls -t -- "${cand_files[@]}" 2>/dev/null | head -n 1 || true)" + fi fi if [[ -n "${latest_so}" && -s "${latest_so}" ]]; then export LIBTPU_PATH="${latest_so}" @@ -182,23 +206,167 @@ PYEOF fi } -resolve_effective_chips() { - if [[ "${SPMD_CHIPS}" =~ ^[0-9]+$ ]]; then - printf '%s' "${SPMD_CHIPS}" - return 0 - fi - local survey_file="${OUT_DIR}/00_pci_vfio_survey.txt" - if [[ -r "${survey_file}" ]]; then - local pjrt_n="" - pjrt_n="$(sed -n 's/^PJRT_LOGICAL_DEVICES=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" - if [[ "${pjrt_n}" =~ ^[0-9]+$ && "${pjrt_n}" -gt 0 ]]; then - printf '%s' "${pjrt_n}" - return 0 +resolve_chip_counts() { + local survey_file="${SURVEY_FILE:-${OUT_DIR}/00_pci_vfio_survey.txt}" + if [[ "${MOCK_MODE}" -eq 1 ]]; then + local avail=8 eff=8 iw=8 + if [[ "${SPMD_CHIPS}" =~ ^[0-9]+$ ]]; then + eff="${SPMD_CHIPS}" fi + printf '%s|%s|%s' "${eff}" "${iw}" "${avail}" + return 0 fi - local chips=0 - if [[ -d "${PCI_SYSFS_DIR}" ]]; then - local dev_path="" vid="" did="" cls="" + + local eff=0 iw=0 sysfs_t7x_seen=0 sysfs_legacy_other_seen=0 sysfs_unlisted_other_seen=0 sysfs_other_seen=0 + local sysfs_total_fns=0 sysfs_iw_pkgs=0 sysfs_unlisted_pkgs=0 sysfs_total_pkgs=0 sysfs_incomplete_fns=0 sysfs_bdf_did_sig="" + + if [[ -d "${PCI_SYSFS_DIR}" ]] && command -v python3 >/dev/null 2>&1; then + local py_res="" + py_res="$(python3 - "${PCI_SYSFS_DIR}" <<'PYEOF' +import re, sys +from collections import defaultdict +from pathlib import Path + +sysfs_dir = Path(sys.argv[1]) +LEGACY_DIDS = {"0x0027", "0x0056", "0x005e", "0x0062", "0x0063", "0x006e", "0x006f"} + +def is_tpu_cls(c: str) -> bool: + c = c.lower() + if c.startswith("0x02"): + return False + return c.startswith(("0xff", "0x12", "0x0b", "0x08")) + +def read_cid(p: Path): + try: + raw = (p / "chip_id").read_bytes() + except OSError: + return None + if b"\x00" in raw: + return None + try: + s = raw.decode("ascii") + except UnicodeDecodeError: + return None + s = s.strip(" \t\r\n") + if not s or len(s) > 5 or not s.isdigit(): + return None + v = int(s, 10) + return v if 0 <= v <= 65535 else None + +t7x = [] +legacy_rows = [] +unlisted = [] +bdf_did_pairs = [] +for ep in sorted(sysfs_dir.iterdir()): + try: + vid = (ep / "vendor").read_text().strip().lower() + except OSError: + continue + if vid != "0x1ae0": + continue + try: + cls = (ep / "class").read_text().strip().lower() + did = (ep / "device").read_text().strip().lower() + except OSError: + continue + if not is_tpu_cls(cls): + continue + bdf = ep.name + bdf_did_pairs.append((bdf, did)) + if did in ("0x0075", "0x0076") or did not in LEGACY_DIDS: + root = bdf[:7] + m = re.search(r"/pci([0-9a-fA-F]{4}:[0-9a-fA-F]{2})", str(ep.resolve())) + if m: + root = m.group(1).lower() + try: + nt = (ep / "numa_node").read_bytes().decode("ascii", errors="surrogateescape").strip(" \t\r\n") + numa_v = int(nt, 10) if re.fullmatch(r"[0-9]+", nt) and len(nt) <= 9 else -1 + except OSError: + numa_v = -1 + dom = ("numa", numa_v, root) if numa_v >= 0 else ("pcie", None, root) + row = (bdf, did, dom, read_cid(ep)) + if did in ("0x0075", "0x0076"): + t7x.append(row) + else: + unlisted.append(row) + else: + legacy_rows.append((bdf, did)) + +def count_verified_pkgs(group_rows, require_0076=False): + if not group_rows: + return 0, 0 + slot_groups = defaultdict(list) + cid_cnt = defaultdict(int) + for row in group_rows: + bdf, _did, dom, cid = row + slot_groups[bdf.rsplit(".", 1)[0]].append(row) + if cid is not None: + cid_cnt[(dom, cid)] += 1 + two_fn = bool( + (require_0076 and any(d == "0x0076" for _, d, _, _ in group_rows)) + or any(not b.endswith(".0") for b, _, _, _ in group_rows) + or len(group_rows) > 4 + or any(len(v) > 1 for v in slot_groups.values()) + or any(v > 1 for v in cid_cnt.values()) + ) + if not two_fn: + return len(group_rows), 0 + verified_pkgs = 0 + incomplete = 0 + remaining = [] + for _slot, srows in sorted(slot_groups.items()): + if len(srows) == 2: + verified_pkgs += 1 + elif len(srows) > 2: + incomplete += len(srows) + else: + remaining.extend(srows) + rem_cid_counts = defaultdict(int) + for _b, _d, dom, cid in remaining: + if cid is not None: + rem_cid_counts[(dom, cid)] += 1 + pair_buckets = defaultdict(list) + for bdf, _d, dom, cid in remaining: + if cid is not None and rem_cid_counts[(dom, cid)] == 2 and cid_cnt[(dom, cid)] == 2: + pair_buckets[(dom, cid)].append(bdf) + else: + incomplete += 1 + for _k, pbdfs in pair_buckets.items(): + if len(pbdfs) == 2 and all(b.endswith(".0") for b in pbdfs): + verified_pkgs += 1 + else: + incomplete += len(pbdfs) + return verified_pkgs, incomplete + +verified_iw_pkgs, iw_inc = count_verified_pkgs(t7x, require_0076=True) +unlisted_pkgs, unl_inc = count_verified_pkgs(unlisted, require_0076=False) +v23_slots = defaultdict(list) +leg_pkgs = 0 +leg_inc = 0 +for bdf, did in legacy_rows: + if did == "0x0027": + v23_slots[bdf.rsplit(".", 1)[0]].append(bdf) + else: + leg_pkgs += 1 +for _s, srows in v23_slots.items(): + if len(srows) == 2: + leg_pkgs += 1 + else: + leg_inc += len(srows) +total_pkgs = verified_iw_pkgs + unlisted_pkgs + leg_pkgs +total_inc = iw_inc + unl_inc + leg_inc +iw_chips = 2 * verified_iw_pkgs +other_cnt = len(legacy_rows) + len(unlisted) +sig = ";".join(f"{b}={d}" for b, d in sorted(bdf_did_pairs)) +print(f"{other_cnt + iw_chips}|{iw_chips}|{len(t7x)}|{len(legacy_rows)}|{len(unlisted)}|{other_cnt}|{verified_iw_pkgs}|{unlisted_pkgs}|{total_pkgs}|{total_inc}|{sig}") +PYEOF +)" + IFS='|' read -r eff iw sysfs_t7x_seen sysfs_legacy_other_seen sysfs_unlisted_other_seen sysfs_other_seen sysfs_iw_pkgs sysfs_unlisted_pkgs sysfs_total_pkgs sysfs_incomplete_fns sysfs_bdf_did_sig <<< "${py_res}" + sysfs_total_fns=$((sysfs_t7x_seen + sysfs_other_seen)) + elif [[ -d "${PCI_SYSFS_DIR}" ]]; then + local dev_path="" vid="" did="" cls="" bdf="" cid="" root="" realp="" numa_raw="" numa_v="" dom="" + local t7x_rows=() unlisted_rows=() v23_slots_seen="" bdf_did_pairs=() + local leg_1fn_pkgs=0 leg_v23_pkgs=0 leg_v23_inc=0 for dev_path in "${PCI_SYSFS_DIR}"/*; do [[ -e "${dev_path}/vendor" ]] || continue vid="$(tr '[:upper:]' '[:lower:]' < "${dev_path}/vendor" 2>/dev/null || echo unknown)" @@ -210,18 +378,279 @@ resolve_effective_chips() { *) continue ;; esac did="$(tr '[:upper:]' '[:lower:]' < "${dev_path}/device" 2>/dev/null || echo unknown)" - case "${did}" in - 0x0075|0x0076) chips=$((chips + 2)) ;; - *) chips=$((chips + 1)) ;; - esac + bdf="$(basename "${dev_path}")" + bdf_did_pairs+=("${bdf}=${did}") + if [[ "${did}" == "0x0075" || "${did}" == "0x0076" ]]; then + sysfs_t7x_seen=$((sysfs_t7x_seen + 1)) + cid="" + if [[ -r "${dev_path}/chip_id" ]]; then + cid="$(LC_ALL=C tr '\000' 'X' < "${dev_path}/chip_id" 2>/dev/null | LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt "\n" $0) } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", txt); if (txt ~ /^[0-9]+$/ && length(txt) <= 5 && (txt + 0) <= 65535) print (txt + 0) }' || true)" + fi + realp="$(cd -P "${dev_path}" 2>/dev/null && pwd -P || printf '%s' "${dev_path}")" + root="$(printf '%s' "${realp}" | sed -n 's#.*/pci\([0-9a-fA-F]\{4\}:[0-9a-fA-F]\{2\}\)/.*#\1#p' | tr '[:upper:]' '[:lower:]')" + [[ -n "${root}" ]] || root="$(printf '%s' "${bdf:0:7}" | tr '[:upper:]' '[:lower:]')" + numa_raw="" + if [[ -r "${dev_path}/numa_node" ]]; then + numa_raw="$(LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt "\n" $0) } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", txt); printf "%s", txt }' < "${dev_path}/numa_node" 2>/dev/null || true)" + fi + if [[ "${numa_raw}" =~ ^[0-9]+$ && "${#numa_raw}" -le 9 ]]; then + numa_v=$((10#${numa_raw})) + dom="numa:${numa_v}:${root}" + else + dom="pcie:none:${root}" + fi + t7x_rows+=("${bdf}|${did}|${dom}|${cid}") + else + case "${did}" in + 0x0027) + sysfs_legacy_other_seen=$((sysfs_legacy_other_seen + 1)) + v23_slots_seen+="${bdf%.*}"$'\n' + ;; + 0x0056|0x005e|0x0062|0x0063|0x006e|0x006f) + sysfs_legacy_other_seen=$((sysfs_legacy_other_seen + 1)) + leg_1fn_pkgs=$((leg_1fn_pkgs + 1)) + ;; + *) + sysfs_unlisted_other_seen=$((sysfs_unlisted_other_seen + 1)) + cid="" + if [[ -r "${dev_path}/chip_id" ]]; then + cid="$(LC_ALL=C tr '\000' 'X' < "${dev_path}/chip_id" 2>/dev/null | LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt "\n" $0) } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", txt); if (txt ~ /^[0-9]+$/ && length(txt) <= 5 && (txt + 0) <= 65535) print (txt + 0) }' || true)" + fi + realp="$(cd -P "${dev_path}" 2>/dev/null && pwd -P || printf '%s' "${dev_path}")" + root="$(printf '%s' "${realp}" | sed -n 's#.*/pci\([0-9a-fA-F]\{4\}:[0-9a-fA-F]\{2\}\)/.*#\1#p' | tr '[:upper:]' '[:lower:]')" + [[ -n "${root}" ]] || root="$(printf '%s' "${bdf:0:7}" | tr '[:upper:]' '[:lower:]')" + numa_raw="" + if [[ -r "${dev_path}/numa_node" ]]; then + numa_raw="$(LC_ALL=C awk '{ txt = (NR == 1 ? $0 : txt "\n" $0) } END { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", txt); printf "%s", txt }' < "${dev_path}/numa_node" 2>/dev/null || true)" + fi + if [[ "${numa_raw}" =~ ^[0-9]+$ && "${#numa_raw}" -le 9 ]]; then + numa_v=$((10#${numa_raw})) + dom="numa:${numa_v}:${root}" + else + dom="pcie:none:${root}" + fi + unlisted_rows+=("${bdf}|${did}|${dom}|${cid}") + ;; + esac + fi done + sysfs_other_seen=$((sysfs_legacy_other_seen + sysfs_unlisted_other_seen)) + sysfs_total_fns=$((sysfs_t7x_seen + sysfs_other_seen)) + if [[ "${#bdf_did_pairs[@]}" -gt 0 ]]; then + sysfs_bdf_did_sig="$(printf '%s\n' "${bdf_did_pairs[@]}" | LC_ALL=C sort | LC_ALL=C awk '{ printf "%s%s", (NR > 1 ? ";" : ""), $0 }')" + fi + _awk_count_pkgs() { + local req76="$1" + shift + printf '%s\n' "$@" | LC_ALL=C awk -F'|' -v req76="${req76}" ' + { + n++ + bdf[n] = $1 + did[n] = $2 + dom[n] = $3 + cid[n] = $4 + slot[n] = $1 + sub(/\.[^.]+$/, "", slot[n]) + slot_cnt[slot[n]]++ + if (req76 && did[n] == "0x0076") has_0076 = 1 + if (bdf[n] !~ /\.0$/) has_non_dot0 = 1 + if (slot_cnt[slot[n]] > 1) has_shared_slot = 1 + if (cid[n] != "") { + dk = dom[n] "|" cid[n] + dom_cid_cnt[dk]++ + if (dom_cid_cnt[dk] > 1) has_dup_cid = 1 + } + } + END { + two_fn = (has_0076 || has_non_dot0 || n > 4 || has_shared_slot || has_dup_cid) ? 1 : 0 + pkgs = 0 + inc = 0 + if (!two_fn) { + pkgs = n + } else { + for (s in slot_cnt) { + if (slot_cnt[s] == 2) pkgs++ + else if (slot_cnt[s] > 2) inc += slot_cnt[s] + } + for (i = 1; i <= n; i++) { + if (slot_cnt[slot[i]] == 1) { + if (cid[i] != "") { + dk = dom[i] "|" cid[i] + rem_cnt[dk]++ + } else { + inc++ + } + } + } + for (i = 1; i <= n; i++) { + if (slot_cnt[slot[i]] == 1 && cid[i] != "") { + dk = dom[i] "|" cid[i] + if (rem_cnt[dk] == 2 && dom_cid_cnt[dk] == 2 && bdf[i] ~ /\.0$/) { + dot0_cnt[dk]++ + } else if (rem_cnt[dk] != 2 || dom_cid_cnt[dk] != 2) { + inc++ + } + } + } + for (dk in rem_cnt) { + if (rem_cnt[dk] == 2 && dom_cid_cnt[dk] == 2) { + if (dot0_cnt[dk] == 2) pkgs++ + else inc += 2 + } + } + } + printf "%d|%d|%d", pkgs + 0, inc + 0, 2 * (pkgs + 0) + } + ' + } + local iw_inc_sh=0 unl_inc_sh=0 + if [[ "${#t7x_rows[@]}" -gt 0 ]]; then + local awk_iw_res="" + awk_iw_res="$(_awk_count_pkgs 1 "${t7x_rows[@]}")" + IFS='|' read -r sysfs_iw_pkgs iw_inc_sh iw <<< "${awk_iw_res}" + else + sysfs_iw_pkgs=0 + iw=0 + fi + if [[ "${#unlisted_rows[@]}" -gt 0 ]]; then + local awk_unl_res="" _unused_unl_chips="" + awk_unl_res="$(_awk_count_pkgs 0 "${unlisted_rows[@]}")" + IFS='|' read -r sysfs_unlisted_pkgs unl_inc_sh _unused_unl_chips <<< "${awk_unl_res}" + else + sysfs_unlisted_pkgs=0 + fi + if [[ -n "${v23_slots_seen}" ]]; then + local v23_res="" + v23_res="$(printf '%s' "${v23_slots_seen}" | LC_ALL=C awk 'NF { c[$1]++ } END { for (s in c) { if (c[s] == 2) p++; else inc += c[s] } printf "%d|%d", p + 0, inc + 0 }')" + IFS='|' read -r leg_v23_pkgs leg_v23_inc <<< "${v23_res}" + fi + sysfs_total_pkgs=$((sysfs_iw_pkgs + sysfs_unlisted_pkgs + leg_1fn_pkgs + leg_v23_pkgs)) + sysfs_incomplete_fns=$((iw_inc_sh + unl_inc_sh + leg_v23_inc)) + eff=$((sysfs_other_seen + iw)) fi - printf '%s' "${chips}" + + if [[ -r "${survey_file}" ]]; then + # Never let a mock survey override live hardware counts/tiers unless MOCK_MODE=1. + if ! grep -qE '(^mock_mode=1|^\[MOCK\])' "${survey_file}"; then + local survey_pjrt_n="" survey_pjrt_kind="unknown" survey_non_ironwood=0 survey_mismatch=0 survey_ironwood_ok=0 + local survey_total_fns="" survey_iw_fns="" survey_iw_pkgs="" survey_total_pkgs="" survey_inc_fns="" survey_pkg_verified="" survey_bdf_did_sig="" + local survey_matches_live=0 + + survey_pjrt_n="$(sed -n 's/^PJRT_LOGICAL_DEVICES=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + if [[ -z "${survey_pjrt_n}" ]] && grep -qF "JAX TPU backend returned 0 devices" "${survey_file}"; then + survey_pjrt_n="0" + fi + if grep -qiE '^PJRT_DEVICE .*kind="[^"]*(v[23456]|tpu[-_ ]?v?[23456]|lite)' "${survey_file}"; then + survey_pjrt_kind="no" + elif grep -qiE '^PJRT_DEVICE .*kind="[^"]*(v7x|tpu7x|ironwood)' "${survey_file}"; then + survey_pjrt_kind="yes" + fi + if [[ "${survey_pjrt_kind}" == "no" ]] || \ + LC_ALL=C awk '/(vendor|vid)=0x1ae0/ && !/(class|cls)=0x02/ && /(^|[[:space:]])(device|did)=0x00(27|56|5e|62|63|6e|6f)([[:space:]]|$)/ { f = 1; exit } END { exit (f ? 0 : 1) }' "${survey_file}" || \ + grep -qE 'legacy_non_ironwood_functions=[1-9][0-9]*' "${survey_file}"; then + survey_non_ironwood=1 + fi + if grep -qE '^(STATUS: PJRT_TOPOLOGY_MISMATCH|.*incomplete_pci_functions=[1-9])' "${survey_file}"; then + survey_mismatch=1 + fi + if [[ "${survey_non_ironwood}" -eq 0 && "${survey_mismatch}" -eq 0 ]] && ( \ + [[ "${survey_pjrt_kind}" == "yes" ]] || \ + LC_ALL=C awk '/(vendor|vid)=0x1ae0/ && !/(class|cls)=0x02/ && /(^|[[:space:]])(device|did)=0x007[56]([[:space:]]|$)/ { f = 1; exit } END { exit (f ? 0 : 1) }' "${survey_file}" || \ + grep -qE 'ironwood_pci_packages=[1-9][0-9]*' "${survey_file}"); then + survey_ironwood_ok=1 + fi + + survey_total_fns="$(sed -n 's/.*total_tpu_pci_functions=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + if [[ -z "${survey_total_fns}" ]]; then + survey_total_fns="$(sed -n 's/.*pci_tpu_functions=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + fi + survey_total_pkgs="$(sed -n 's/.*total_tpu_pci_packages=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + if [[ -z "${survey_total_pkgs}" ]]; then + survey_total_pkgs="$(sed -n 's/.*pci_tpu_packages=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + fi + survey_inc_fns="$(sed -n 's/.*incomplete_pci_functions=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + survey_iw_fns="$(sed -n 's/.*ironwood_pci_functions=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + survey_iw_pkgs="$(sed -n 's/.*ironwood_pci_packages=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + survey_pkg_verified="$(sed -n 's/.*pkg_count_verified=\([0-9][0-9]*\).*/\1/p' "${survey_file}" | tail -n 1)" + survey_bdf_did_sig="$(LC_ALL=C awk ' + /^--- TPU BDF=/ { + bdf=""; did="" + for (i = 1; i <= NF; i++) { + if ($i ~ /^BDF=/) { bdf = substr($i, 5) } + else if ($i ~ /^did=/) { did = tolower(substr($i, 5)) } + } + if (bdf != "" && did != "") print bdf "=" did + } + ' "${survey_file}" | LC_ALL=C sort | LC_ALL=C awk '{ printf "%s%s", (NR > 1 ? ";" : ""), $0 }')" + + if [[ -d "${PCI_SYSFS_DIR}" ]]; then + survey_matches_live=1 + if [[ -n "${survey_bdf_did_sig}" && "${survey_bdf_did_sig}" != "${sysfs_bdf_did_sig}" ]]; then + survey_matches_live=0 + elif [[ -z "${survey_total_fns}" || "${survey_total_fns}" != "${sysfs_total_fns}" ]]; then + survey_matches_live=0 + elif [[ -n "${survey_iw_fns}" && "${survey_iw_fns}" != "${sysfs_t7x_seen}" ]]; then + survey_matches_live=0 + elif [[ "${survey_pkg_verified}" == "1" && -n "${survey_iw_pkgs}" && "${survey_iw_pkgs}" != "${sysfs_iw_pkgs}" ]]; then + survey_matches_live=0 + elif [[ "${survey_pkg_verified}" == "1" && -n "${survey_total_pkgs}" && "${survey_total_pkgs}" != "${sysfs_total_pkgs}" ]]; then + survey_matches_live=0 + elif [[ "${survey_pkg_verified}" == "1" && -n "${survey_inc_fns}" && "${survey_inc_fns}" != "${sysfs_incomplete_fns}" ]]; then + survey_matches_live=0 + fi + fi + + if [[ "${survey_matches_live}" -eq 1 ]]; then + local total_iw_cap=$((2 * (sysfs_iw_pkgs + sysfs_unlisted_pkgs))) + if [[ "${survey_pjrt_n}" == "0" ]]; then + eff=0 + iw=0 + elif [[ "${survey_pjrt_kind}" == "no" ]]; then + # Contradictory PJRT evidence (e.g. TPU v6 lite) invalidates speculative sysfs Ironwood counts. + iw=0 + if [[ "${survey_pjrt_n}" =~ ^[0-9]+$ && "${survey_pjrt_n}" -gt 0 ]]; then + eff="${survey_pjrt_n}" + fi + elif [[ "${survey_non_ironwood}" -eq 1 || "${sysfs_legacy_other_seen}" -gt 0 ]]; then + if [[ "${survey_pjrt_n}" =~ ^[0-9]+$ && "${survey_pjrt_n}" -gt 0 ]]; then + eff="${survey_pjrt_n}" + fi + elif [[ "${survey_mismatch}" -eq 1 && "${survey_pjrt_kind}" != "yes" ]]; then + iw=0 + if [[ "${survey_pjrt_n}" =~ ^[0-9]+$ && "${survey_pjrt_n}" -gt 0 ]]; then + eff="${survey_pjrt_n}" + fi + elif [[ "${survey_pjrt_n}" =~ ^[0-9]+$ && "${survey_pjrt_n}" -gt 0 ]]; then + eff="${survey_pjrt_n}" + if [[ "${survey_ironwood_ok}" -eq 1 ]] && ( \ + [[ "${sysfs_t7x_seen}" -gt 0 ]] || \ + [[ "${sysfs_unlisted_other_seen}" -gt 0 && "${survey_pjrt_kind}" == "yes" ]]); then + iw="${survey_pjrt_n}" + if [[ -d "${PCI_SYSFS_DIR}" && "${iw}" -gt "${total_iw_cap}" ]]; then + iw="${total_iw_cap}" + fi + elif [[ "${survey_pjrt_n}" -lt "${iw}" ]]; then + iw="${survey_pjrt_n}" + fi + fi + fi + fi + fi + local avail="${eff}" + if [[ "${SPMD_CHIPS}" =~ ^[0-9]+$ ]]; then + eff="${SPMD_CHIPS}" + fi + printf '%s|%s|%s' "${eff}" "${iw}" "${avail}" } should_run_671b_tier() { - local eff_chips="$1" - if [[ "${INCLUDE_671B}" -eq 1 || "${eff_chips}" -ge 8 ]]; then + local ironwood_chips="$1" + local effective_chips="${2:-${ironwood_chips}}" + local gate_chips="${ironwood_chips}" + if [[ "${effective_chips}" =~ ^[0-9]+$ && "${effective_chips}" -lt "${gate_chips}" ]]; then + gate_chips="${effective_chips}" + fi + if [[ "${INCLUDE_671B}" -eq 1 || "${gate_chips}" -ge 8 ]]; then return 0 fi return 1 @@ -307,12 +736,20 @@ sync_gcs_models() { : > "${LOG}" log "=== FreeTPU Ironwood (tpu7x) Day-1 ggml-cloudtpu Ops & Bench ===" -EFFECTIVE_CHIPS="$(resolve_effective_chips)" +CHIP_COUNTS="$(resolve_chip_counts)" +IFS='|' read -r EFFECTIVE_CHIPS IRONWOOD_CHIPS AVAIL_CHIPS <<< "${CHIP_COUNTS}" +EFFECTIVE_CHIPS="${EFFECTIVE_CHIPS:-0}" +IRONWOOD_CHIPS="${IRONWOOD_CHIPS:-0}" +AVAIL_CHIPS="${AVAIL_CHIPS:-0}" +if [[ "${SPMD_CHIPS}" =~ ^[0-9]+$ && "${SPMD_CHIPS}" -gt "${AVAIL_CHIPS}" ]]; then + log "ERROR: --spmd=${SPMD_CHIPS} exceeds available devices (avail=${AVAIL_CHIPS}); backend rejects width ${SPMD_CHIPS}." + exit 2 +fi RUN_671B_TIER=0 -if should_run_671b_tier "${EFFECTIVE_CHIPS}"; then +if should_run_671b_tier "${IRONWOOD_CHIPS}" "${EFFECTIVE_CHIPS}"; then RUN_671B_TIER=1 fi -log "timestamp_utc=${TIMESTAMP} spmd_chips=${SPMD_CHIPS} effective_chips=${EFFECTIVE_CHIPS} run_671b_tier=${RUN_671B_TIER} models_dir=${MODELS_DIR} tpu_zone=${TPU_ZONE:-unset} gcs_model_bucket=${GCS_MODEL_BUCKET:-unset} run_mosaic=${RUN_MOSAIC} include_671b=${INCLUDE_671B}" +log "timestamp_utc=${TIMESTAMP} spmd_chips=${SPMD_CHIPS} effective_chips=${EFFECTIVE_CHIPS} ironwood_chips=${IRONWOOD_CHIPS} run_671b_tier=${RUN_671B_TIER} models_dir=${MODELS_DIR} tpu_zone=${TPU_ZONE:-unset} gcs_model_bucket=${GCS_MODEL_BUCKET:-unset} run_mosaic=${RUN_MOSAIC} include_671b=${INCLUDE_671B}" resolve_staged_libtpu @@ -333,7 +770,7 @@ log "XLA_COMPILATION_CACHE_DIR=${XLA_COMPILATION_CACHE_DIR}" if [[ "${DRY_RUN}" -eq 1 ]]; then sync_gcs_models - log "[DRY-RUN] Would run test_cloudtpu_host, BF16 pure StableHLO test-backend-ops (CLOUDTPU_MATMUL_FP8=0 CLOUDTPU_FREETILE_MOSAIC=0), live FP8 1e-2 NMSE parity gate (test_cloudtpu_host --fp8-parity-only), FreeTile Mosaic Q4_K/Q6_K pass (CLOUDTPU_FREETILE_MOSAIC=1 CLOUDTPU_VERBOSE=1 verifying mosaic_compiles>0), and llama-bench for named 1t bracket tiers (8B / Qwen3-32B / Llama-3.3-70B / gpt-oss-120b / Qwen3-235B) + DeepSeek-V3/R1 671B FP8/Q4 (when effective_chips>=8 or --include-671b)." + log "[DRY-RUN] Would run test_cloudtpu_host, BF16 pure StableHLO test-backend-ops (CLOUDTPU_MATMUL_FP8=0 CLOUDTPU_FREETILE_MOSAIC=0), live FP8 1e-2 NMSE parity gate (test_cloudtpu_host --fp8-parity-only), FreeTile Mosaic Q4_K/Q6_K pass (CLOUDTPU_FREETILE_MOSAIC=1 CLOUDTPU_VERBOSE=1 verifying mosaic_compiles>0), and llama-bench for named 1t bracket tiers (8B / Qwen3-32B / Llama-3.3-70B / gpt-oss-120b / Qwen3-235B) + DeepSeek-V3/R1 671B FP8/Q4 (when ironwood_chips>=8 or --include-671b)." exit 0 fi @@ -517,7 +954,7 @@ run_bench_tier "Qwen3-235B (1t bracket)" "qwen[-_.]?3" "235b" "q4_k_m" "distill" if [[ "${RUN_671B_TIER}" -eq 1 ]]; then run_bench_tier "DeepSeek-V3/R1-671B (4t hero 768GiB)" "deepseek[-_.]?(v3|r1)" "(671b|deepseek[-_.]?(v3|r1))" "(q4_k_m|q4_k|q4_0|iq4|fp8|f8e4m3)" "(distill|1\.5b|7b|8b|14b|32b|70b)" else - log "SKIP: 671B tier requires >=8 Ironwood chiplets (768 GiB HBM) or --include-671b (effective_chips=${EFFECTIVE_CHIPS}, spmd=${SPMD_CHIPS})" + log "SKIP: 671B tier requires >=8 Ironwood chiplets (768 GiB HBM) or --include-671b (ironwood_chips=${IRONWOOD_CHIPS}, effective_chips=${EFFECTIVE_CHIPS}, spmd=${SPMD_CHIPS})" fi echo "Benchmark log written to: ${LOG}" diff --git a/tools/ironwood-day1/02_libopentpu_vfio_probe.sh b/tools/ironwood-day1/02_libopentpu_vfio_probe.sh index d87b9d0a..30578562 100755 --- a/tools/ironwood-day1/02_libopentpu_vfio_probe.sh +++ b/tools/ironwood-day1/02_libopentpu_vfio_probe.sh @@ -17,7 +17,8 @@ Usage: 02_libopentpu_vfio_probe.sh [--out-dir DIR] [--live-vfio] [--dry-run] [-- Verifies libopentpu clean-room build, multi-gen HAL geometry, and MAPS_LIBTPU=0 / MAPS_LIBPYTHON=0 capture. Live /dev/vfio/* device probing requires explicit --live-vfio on Linux and only accepts either: - PASS with MAPS_LIBTPU=0 and MAPS_LIBPYTHON=0 verified, or - - Explicit pre-reset refusal ("Refusing to reset/program unsupported VFIO PCI device") + - Explicit pre-open/pre-reset refusal ("Unsupported TPU PCI device" or + "Refusing to reset/program unsupported VFIO PCI device") with MAPS_LIBTPU=0 and MAPS_LIBPYTHON=0 verified. EOF } @@ -122,7 +123,8 @@ if [[ "${MOCK_MODE}" -eq 1 || "${LIVE_VFIO}" -eq 0 || ( "$(uname -s)" != "Linux" exit 0 fi -first_vfio_tpu_bdf="" +first_vfio_0xff_bdf="" +first_vfio_accel_bdf="" for dev_path in "${PCI_SYSFS_DIR}"/*; do [[ -r "${dev_path}/vendor" && -L "${dev_path}/driver" ]] || continue vid="$(tr '[:upper:]' '[:lower:]' < "${dev_path}/vendor" 2>/dev/null || true)" @@ -134,10 +136,15 @@ for dev_path in "${PCI_SYSFS_DIR}"/*; do *) continue ;; esac if [[ "${vid}" == "0x1ae0" && "${drv}" == "vfio-pci" ]]; then - first_vfio_tpu_bdf="$(basename "${dev_path}")" - break + cand_bdf="$(basename "${dev_path}")" + if [[ "${cls}" == "0xff0000" && -z "${first_vfio_0xff_bdf}" ]]; then + first_vfio_0xff_bdf="${cand_bdf}" + elif [[ -z "${first_vfio_accel_bdf}" ]]; then + first_vfio_accel_bdf="${cand_bdf}" + fi fi done +first_vfio_tpu_bdf="${first_vfio_0xff_bdf:-${first_vfio_accel_bdf}}" probe_cmd=("${SMOKE_BIN}") if [[ -n "${first_vfio_tpu_bdf}" ]]; then @@ -156,7 +163,10 @@ fi if [[ "${probe_rc}" -eq 0 ]]; then log "LIVE_VFIO_PROBE_STATUS=PASS" -elif [[ "${probe_rc}" -eq 1 ]] && printf '%s\n' "${probe_out}" | grep -Fq "Refusing to reset/program unsupported VFIO PCI device"; then +elif [[ "${probe_rc}" -eq 1 ]] && ( + printf '%s\n' "${probe_out}" | grep -Eq 'Unsupported TPU PCI device .*only validated' || + printf '%s\n' "${probe_out}" | grep -Fq "Refusing to reset/program unsupported VFIO PCI device" +); then log "LIVE_VFIO_PROBE_STATUS=EXPECTED_UNVALIDATED_DEVICE_REFUSAL (exit=${probe_rc})" else log "LIVE_VFIO_PROBE_STATUS=UNEXPECTED_FAILURE (exit=${probe_rc})" diff --git a/tools/ironwood-day1/03_ops_and_router_smoke.sh b/tools/ironwood-day1/03_ops_and_router_smoke.sh index 296ccaf9..2e034986 100755 --- a/tools/ironwood-day1/03_ops_and_router_smoke.sh +++ b/tools/ironwood-day1/03_ops_and_router_smoke.sh @@ -181,29 +181,31 @@ misc_vfio.write_text("10:196\n", encoding="utf-8") drv = sysfs_root / "bus" / "pci" / "drivers" / "vfio-pci" drv.mkdir(parents=True, exist_ok=True) -for idx in range(4): - bdf = f"0000:00:0{idx + 4}.0" - grp_id = str(idx) - (vfio_dir / grp_id).write_text("", encoding="utf-8") - grp_dev = sysfs_root / "class" / "vfio" / grp_id / "dev" - grp_dev.parent.mkdir(parents=True, exist_ok=True) - grp_dev.write_text(f"242:{idx}\n", encoding="utf-8") - - d = pci_devices / bdf - d.mkdir(parents=True, exist_ok=True) - (d / "vendor").write_text("0x1ae0\n", encoding="utf-8") - (d / "device").write_text("0x0076\n", encoding="utf-8") - (d / "class").write_text("0xff0000\n", encoding="utf-8") - (d / "numa_node").write_text("0\n", encoding="utf-8") - (d / "aer_dev_correctable").write_text("RxErr 0\nBadTLP 0\nTOTAL_ERR_COR 0\n", encoding="utf-8") - (d / "aer_dev_fatal").write_text("DLP 0\nTOTAL_ERR_FATAL 0\n", encoding="utf-8") - - grp_path = iommu_groups / grp_id - grp_devs = grp_path / "devices" - grp_devs.mkdir(parents=True, exist_ok=True) - os.symlink(str(d), grp_devs / bdf) - os.symlink(str(grp_path), d / "iommu_group") - os.symlink(str(drv), d / "driver") +for pkg in range(4): + for fn in range(2): + bdf = f"0000:00:0{pkg + 4}.{fn}" + grp_id = str(pkg * 2 + fn) + (vfio_dir / grp_id).write_text("", encoding="utf-8") + grp_dev = sysfs_root / "class" / "vfio" / grp_id / "dev" + grp_dev.parent.mkdir(parents=True, exist_ok=True) + grp_dev.write_text(f"242:{grp_id}\n", encoding="utf-8") + + d = pci_devices / bdf + d.mkdir(parents=True, exist_ok=True) + (d / "vendor").write_text("0x1ae0\n", encoding="utf-8") + (d / "device").write_text("0x0076\n", encoding="utf-8") + (d / "class").write_text("0xff0000\n", encoding="utf-8") + (d / "numa_node").write_text("0\n", encoding="utf-8") + (d / "chip_id").write_text(f"{pkg}\n", encoding="utf-8") + (d / "aer_dev_correctable").write_text("RxErr 0\nBadTLP 0\nTOTAL_ERR_COR 0\n", encoding="utf-8") + (d / "aer_dev_fatal").write_text("DLP 0\nTOTAL_ERR_FATAL 0\n", encoding="utf-8") + + grp_path = iommu_groups / grp_id + grp_devs = grp_path / "devices" + grp_devs.mkdir(parents=True, exist_ok=True) + os.symlink(str(d), grp_devs / bdf) + os.symlink(str(grp_path), d / "iommu_group") + os.symlink(str(drv), d / "driver") # Write a clean v1 SeqLock SHM telemetry snapshot for device 0 (0000:00:04.0) # Layout matches ops/tpu-exporter/freetpu_metrics_shm.h (56-byte struct freetpu_shm_metrics_v1) @@ -263,11 +265,11 @@ else "${CDI_SPEC}" 2>&1 | tee -a "${LOG}" fi -python3 - "${CDI_SPEC}" "${CDI_VERSION}" <<'PYEOF' 2>&1 | tee -a "${LOG}" +python3 - "${CDI_SPEC}" "${CDI_VERSION}" "${EFFECTIVE_MOCK}" <<'PYEOF' 2>&1 | tee -a "${LOG}" import json import sys -spec_path, expected_ver = sys.argv[1], sys.argv[2] +spec_path, expected_ver, is_mock = sys.argv[1], sys.argv[2], sys.argv[3] == "1" with open(spec_path, encoding="utf-8") as f: spec = json.load(f) got_ver = spec.get("cdiVersion") @@ -276,6 +278,21 @@ if got_ver != expected_ver: raise SystemExit(f"CDI version mismatch: expected={expected_ver} got={got_ver}") if not devices: raise SystemExit("CDI spec contains 0 devices") +if is_mock: + root_ann = spec.get("annotations", {}) + if root_ann.get("freetpu.dev/tpu7x-pci-functions-per-chip") != "2": + raise SystemExit(f"Expected 2-fn Ironwood root metadata, got {root_ann!r}") + all_dev = next((d for d in devices if d.get("name") == "all"), None) + if all_dev is None: + raise SystemExit("Mock CDI spec missing 'all' selector") + all_ann = all_dev.get("annotations", {}) + if ( + all_ann.get("freetpu.dev/chip-count") != "4" + or all_ann.get("freetpu.dev/pci-function-count") != "8" + or all_ann.get("freetpu.dev/capacity-complete") == "false" + or "freetpu.dev/incomplete-pci-functions" in all_ann + ): + raise SystemExit(f"Unexpected mock CDI 'all' capacity annotations: {all_ann!r}") print(f"CDI_SMOKE_STATUS=PASS cdiVersion={got_ver} devices={len(devices)}") PYEOF @@ -354,15 +371,15 @@ aer_status = "PASS" if (aer_corr_samples > 0 and aer_fatal_samples > 0) else "UN if is_mock: errors = [] - if devices_discovered != 4: - errors.append(f"devices_discovered={devices_discovered} (expected 4)") - if tpu7x_info_samples < 4: - errors.append(f"tpu7x_info_samples={tpu7x_info_samples} (expected >= 4)") + if devices_discovered != 8: + errors.append(f"devices_discovered={devices_discovered} (expected 8)") + if tpu7x_info_samples < 8: + errors.append(f"tpu7x_info_samples={tpu7x_info_samples} (expected >= 8)") if shm_mxu_samples < 1 or shm_dma_samples < 1 or shm_info_samples < 1: errors.append( f"shm_samples incomplete (mxu={shm_mxu_samples} dma={shm_dma_samples} info={shm_info_samples})" ) - if aer_corr_samples < 4 or aer_fatal_samples < 4: + if aer_corr_samples < 8 or aer_fatal_samples < 8: errors.append(f"aer_samples incomplete (correctable={aer_corr_samples} fatal={aer_fatal_samples})") if errors: raise SystemExit("tpu-exporter mock sample verification failed: " + "; ".join(errors)) diff --git a/tools/ironwood-day1/test_ironwood_day1.py b/tools/ironwood-day1/test_ironwood_day1.py new file mode 100644 index 00000000..090f00f6 --- /dev/null +++ b/tools/ironwood-day1/test_ironwood_day1.py @@ -0,0 +1,802 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Offline regression tests for Ironwood Day-1 qualification scripts.""" + +import os +import pathlib +import shutil +import subprocess +import tempfile +import unittest + + +DAY1_DIR = pathlib.Path(__file__).resolve().parent +REPO_ROOT = DAY1_DIR.parent.parent +PJRT_INC_DIR = REPO_ROOT / "libopentpu" / "third_party" / "openxla" +STEP00 = str(DAY1_DIR / "00_pci_vfio_survey.sh") +STEP01 = str(DAY1_DIR / "01_ggml_cloudtpu_ops_bench.sh") +STEP02 = str(DAY1_DIR / "02_libopentpu_vfio_probe.sh") +BASH_BIN = shutil.which("bash") or "/bin/bash" +CXX_BIN = shutil.which("c++") or shutil.which("clang++") or shutil.which("g++") + + +_FAKE_PJRT_CPP = r""" +#include +#include +#include +#include +#include +#include + +#include "pjrt_c_api.h" + +struct PJRT_DeviceDescription { + int id = 0; + std::string kind; + std::array coords{}; + int64_t core_on_chip = 0; + std::vector attrs; +}; + +struct PJRT_Device { + PJRT_DeviceDescription desc; +}; + +struct PJRT_Client { + std::vector> devices; + std::vector dev_ptrs; +}; + +namespace { + +void fake_err_destroy(PJRT_Error_Destroy_Args*) {} + +void fake_err_msg(PJRT_Error_Message_Args* args) { + static const char kMsg[] = "simulated fake pjrt failure"; + if (!args) return; + args->message = kMsg; + args->message_size = sizeof(kMsg) - 1; +} + +PJRT_Error* fake_plugin_init(PJRT_Plugin_Initialize_Args*) { return nullptr; } + +PJRT_Error* fake_client_create(PJRT_Client_Create_Args* args) { + const char* n_env = std::getenv("FAKE_PJRT_N"); + const char* kind_env = std::getenv("FAKE_PJRT_KIND"); + const int n = n_env ? std::atoi(n_env) : 8; + const std::string kind = (kind_env && kind_env[0]) ? kind_env : "TPU v7x"; + if (n < 0) { + static PJRT_Error kStaticErr{}; + return &kStaticErr; + } + auto* c = new PJRT_Client(); + for (int i = 0; i < n; ++i) { + auto d = std::make_unique(); + const int pkg = i / 2; + const int y = pkg / 2; + const int x = (y % 2 == 0) ? (pkg % 2) : (1 - (pkg % 2)); + d->desc.id = i; + d->desc.kind = kind; + d->desc.coords = {x, y, 0}; + d->desc.core_on_chip = i % 2; + + PJRT_NamedValue c_attr{}; + c_attr.struct_size = PJRT_NamedValue_STRUCT_SIZE; + c_attr.name = "coords"; + c_attr.name_size = 6; + c_attr.type = PJRT_NamedValue_kInt64List; + c_attr.int64_array_value = d->desc.coords.data(); + c_attr.value_size = d->desc.coords.size(); + d->desc.attrs.push_back(c_attr); + + PJRT_NamedValue core_attr{}; + core_attr.struct_size = PJRT_NamedValue_STRUCT_SIZE; + core_attr.name = "core_on_chip"; + core_attr.name_size = 12; + core_attr.type = PJRT_NamedValue_kInt64; + core_attr.int64_value = d->desc.core_on_chip; + core_attr.value_size = 1; + d->desc.attrs.push_back(core_attr); + + c->dev_ptrs.push_back(d.get()); + c->devices.push_back(std::move(d)); + } + args->client = c; + return nullptr; +} + +PJRT_Error* fake_client_destroy(PJRT_Client_Destroy_Args* args) { + if (args) delete args->client; + return nullptr; +} + +PJRT_Error* fake_client_addr_devs(PJRT_Client_AddressableDevices_Args* args) { + args->addressable_devices = args->client->dev_ptrs.data(); + args->num_addressable_devices = args->client->dev_ptrs.size(); + return nullptr; +} + +PJRT_Error* fake_dev_local_hw_id(PJRT_Device_LocalHardwareId_Args* args) { + args->local_hardware_id = args->device->desc.id; + return nullptr; +} + +PJRT_Error* fake_dev_get_desc(PJRT_Device_GetDescription_Args* args) { + args->device_description = &args->device->desc; + return nullptr; +} + +PJRT_Error* fake_desc_id(PJRT_DeviceDescription_Id_Args* args) { + args->id = args->device_description->id; + return nullptr; +} + +PJRT_Error* fake_desc_kind(PJRT_DeviceDescription_Kind_Args* args) { + args->device_kind = args->device_description->kind.c_str(); + args->device_kind_size = args->device_description->kind.size(); + return nullptr; +} + +PJRT_Error* fake_desc_attrs(PJRT_DeviceDescription_Attributes_Args* args) { + args->attributes = args->device_description->attrs.data(); + args->num_attributes = args->device_description->attrs.size(); + return nullptr; +} + +} // namespace + +extern "C" __attribute__((visibility("default"))) const PJRT_Api* GetPjrtApi() { + static PJRT_Api api = []() { + PJRT_Api a{}; + a.struct_size = PJRT_Api_STRUCT_SIZE; + a.pjrt_api_version.struct_size = PJRT_Api_Version_STRUCT_SIZE; + a.pjrt_api_version.major_version = PJRT_API_MAJOR; + a.pjrt_api_version.minor_version = PJRT_API_MINOR; + a.PJRT_Error_Destroy = fake_err_destroy; + a.PJRT_Error_Message = fake_err_msg; + a.PJRT_Plugin_Initialize = fake_plugin_init; + a.PJRT_Client_Create = fake_client_create; + a.PJRT_Client_Destroy = fake_client_destroy; + a.PJRT_Client_AddressableDevices = fake_client_addr_devs; + a.PJRT_Device_LocalHardwareId = fake_dev_local_hw_id; + a.PJRT_Device_GetDescription = fake_dev_get_desc; + a.PJRT_DeviceDescription_Id = fake_desc_id; + a.PJRT_DeviceDescription_Kind = fake_desc_kind; + a.PJRT_DeviceDescription_Attributes = fake_desc_attrs; + return a; + }(); + return &api; +} +""" + + +def _compile_fake_pjrt(tmp_dir: pathlib.Path) -> pathlib.Path: + src = tmp_dir / "fake_pjrt.cpp" + so = tmp_dir / "libfake_pjrt.so" + src.write_text(_FAKE_PJRT_CPP, encoding="utf-8") + subprocess.run( + [ + CXX_BIN, + "-std=c++17", + "-O2", + "-shared", + "-fPIC", + f"-I{PJRT_INC_DIR}", + str(src), + "-o", + str(so), + ], + check=True, + capture_output=True, + text=True, + ) + return so + + +def _make_ep( + root: pathlib.Path, + bdf: str, + did: str, + *, + cls: str = "0xff0000", + chip_id=None, + numa_node=None, +): + d = root / bdf + d.mkdir(parents=True, exist_ok=True) + (d / "vendor").write_text("0x1ae0\n", encoding="utf-8") + (d / "device").write_text(f"{did}\n", encoding="utf-8") + (d / "class").write_text(f"{cls}\n", encoding="utf-8") + if chip_id is not None: + if isinstance(chip_id, bytes): + (d / "chip_id").write_bytes(chip_id) + else: + (d / "chip_id").write_text(f"{chip_id}\n", encoding="utf-8") + if numa_node is not None: + if isinstance(numa_node, bytes): + (d / "numa_node").write_bytes(numa_node) + else: + (d / "numa_node").write_text(f"{numa_node}\n", encoding="utf-8") + return d + + +def _build_no_python_path(dst: pathlib.Path) -> pathlib.Path: + dst.mkdir(parents=True, exist_ok=True) + for tool in ( + "bash", "tr", "awk", "sed", "grep", "date", "tee", "mkdir", + "dirname", "basename", "cat", "head", "tail", "find", "sort", "wc", + "ls", "readlink", "hostname", "uname", + ): + pt = shutil.which(tool) + if pt and not (dst / tool).exists(): + (dst / tool).symlink_to(pt) + return dst + + +def _build_offline_py_env(root: pathlib.Path) -> dict: + """Return an env dict that isolates offline tests from any host jax/libtpu installation.""" + stub_dir = root / "offline_no_jax" + jax_pkg = stub_dir / "jax" + jax_pkg.mkdir(parents=True, exist_ok=True) + (jax_pkg / "__init__.py").write_text( + 'raise ImportError("offline test: host JAX TPU backend disabled")\n', + encoding="utf-8", + ) + dummy_so = root / "no_host_libtpu.so" + if not dummy_so.exists(): + dummy_so.write_bytes(b"\x00") + return { + **os.environ, + "LIBTPU_PATH": str(dummy_so), + "LIBTPU_DEST": str(dummy_so), + "PYTHONPATH": str(stub_dir), + } + + +class IronwoodDay1Tests(unittest.TestCase): + def test_step01_capacity_surveys_spmd_and_fallbacks(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = pathlib.Path(td) + fake_bin = _build_no_python_path(root / "no_py_bin") + nopy_env = {"PATH": str(fake_bin), "HOME": os.environ.get("HOME", "/tmp")} + py_env = _build_offline_py_env(root) + + pci_4x75 = root / "pci_4x75" + for i in range(4): + _make_ep(pci_4x75, f"0000:00:{4 + i:02x}.0", "0x0075", cls="0x120000") + + # Stale 4-pkg live survey does NOT enable 671B on 1-pkg 0x0076 host. + out_stale = root / "out_stale" + subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_stale), "--allow-no-pjrt"], + env={**py_env, "PCI_SYSFS_DIR": str(pci_4x75)}, + check=True, + capture_output=True, + ) + with open(out_stale / "00_pci_vfio_survey.txt", "a", encoding="utf-8") as fh: + fh.write('PJRT_DEVICE index=0 id=0 local_hardware_id=0 kind="TPU v7x" coords=[0,0,0] core_on_chip=0\n') + fh.write("PJRT_LOGICAL_DEVICES=8\n") + fh.write("STATUS: PJRT_TOPOLOGY_CAPTURED (pci_tpu_packages=4 pci_tpu_functions=4 incomplete_pci_functions=0)\n") + pci_1x76 = root / "pci_1x76" + for fn in (0, 1): + _make_ep(pci_1x76, f"0000:00:04.{fn}", "0x0076", cls="0x120000") + p_stale = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_stale)], + env={**py_env, "PCI_SYSFS_DIR": str(pci_1x76)}, + text=True, + capture_output=True, + ) + self.assertEqual(p_stale.returncode, 0, p_stale.stderr + p_stale.stdout) + self.assertIn( + "effective_chips=2 ironwood_chips=2 run_671b_tier=0", + (out_stale / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # Missing sysfs directory with saved survey NEVER enables 671B automatically in live mode. + p_missing = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_stale)], + env={**py_env, "PCI_SYSFS_DIR": str(root / "no_such_sysfs")}, + text=True, + capture_output=True, + ) + self.assertEqual(p_missing.returncode, 0, p_missing.stderr + p_missing.stdout) + self.assertIn( + "effective_chips=0 ironwood_chips=0 run_671b_tier=0", + (out_stale / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # Mock mode reports 8|8|1 regardless of empty host sysfs. + pci_empty = root / "pci_empty" + pci_empty.mkdir() + out_mock = root / "out_mock" + p_mock = subprocess.run( + [BASH_BIN, STEP01, "--mock", "--dry-run", "--out-dir", str(out_mock)], + env={**py_env, "PCI_SYSFS_DIR": str(pci_empty)}, + text=True, + capture_output=True, + ) + self.assertEqual(p_mock.returncode, 0, p_mock.stderr + p_mock.stdout) + self.assertIn( + "effective_chips=8 ironwood_chips=8 run_671b_tier=1", + (out_mock / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # 8 unpaired 0x0076 .0 slots without chip_ids -> 0|0|0 (Python + shell fallback). + pci_unp = root / "pci_8unp" + for i in range(8): + _make_ep(pci_unp, f"0000:00:{4 + i:02x}.0", "0x0076", cls="0x120000") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_unp)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_unp)})): + out_unp = root / f"out_unp_{tag}" + pu = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_unp)], + env=env, + text=True, + capture_output=True, + ) + self.assertEqual(pu.returncode, 0, pu.stderr + pu.stdout) + self.assertIn( + "effective_chips=0 ironwood_chips=0 run_671b_tier=0", + (out_unp / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # Contradictory PJRT (TPU v6 lite) or explicit PJRT_LOGICAL_DEVICES=0 disables 671B. + for tag, lines in ( + ( + "v6lite", + 'PJRT_DEVICE index=0 id=0 local_hardware_id=0 kind="TPU v6 lite" coords=[0,0,0] core_on_chip=-1\n' + "PJRT_LOGICAL_DEVICES=8\nSTATUS: PJRT_TOPOLOGY_MISMATCH\n", + ), + ( + "zero_devs", + "PJRT_LOGICAL_DEVICES=0\nSTATUS: PJRT_TOPOLOGY_UNAVAILABLE\n", + ), + ): + out_neg = root / f"out_{tag}" + subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_neg), "--allow-no-pjrt"], + env={**py_env, "PCI_SYSFS_DIR": str(pci_4x75)}, + check=True, + capture_output=True, + ) + with open(out_neg / "00_pci_vfio_survey.txt", "a", encoding="utf-8") as fh: + fh.write(lines) + pn = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_neg)], + env={**py_env, "PCI_SYSFS_DIR": str(pci_4x75)}, + text=True, + capture_output=True, + ) + self.assertEqual(pn.returncode, 0, pn.stderr + pn.stdout) + self.assertIn( + "ironwood_chips=0 run_671b_tier=0", + (out_neg / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # Unlisted DID 0x0077: 4x 2-fn slots -> 4 pkgs & 8|8|1; 2x 2-fn slots -> 2 pkgs (MISMATCH) & tier=0. + for n_slots, exp_status, exp_tier in ((4, "STATUS: PJRT_TOPOLOGY_CAPTURED", "run_671b_tier=1"), (2, "STATUS: PJRT_TOPOLOGY_MISMATCH", "run_671b_tier=0")): + pci_unl = root / f"pci_unl_{n_slots}" + for s in range(n_slots): + for fn in (0, 1): + _make_ep(pci_unl, f"0000:00:{4 + s:02x}.{fn}", "0x0077") + out_u = root / f"out_unl_{n_slots}" + subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_u), "--allow-no-pjrt"], + env={**py_env, "PCI_SYSFS_DIR": str(pci_unl)}, + check=True, + capture_output=True, + ) + txt00 = (out_u / "00_pci_vfio_survey.txt").read_text() + self.assertIn(f"total_tpu_pci_packages={n_slots} total_tpu_pci_functions={2 * n_slots}", txt00) + with open(out_u / "00_pci_vfio_survey.txt", "a", encoding="utf-8") as fh: + fh.write('PJRT_DEVICE index=0 id=0 local_hardware_id=0 kind="TPU v7x" coords=[0,0,0] core_on_chip=0\n') + fh.write("PJRT_LOGICAL_DEVICES=8\n") + fh.write(f"{exp_status} (pci_tpu_packages={n_slots} pci_tpu_functions={2 * n_slots} incomplete_pci_functions=0)\n") + pu = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_u)], + env={**py_env, "PCI_SYSFS_DIR": str(pci_unl)}, + text=True, + capture_output=True, + ) + self.assertEqual(pu.returncode, 0, pu.stderr + pu.stdout) + self.assertIn(exp_tier, (out_u / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + # --spmd rejects malformed ('1x'), >max ('17'), and >avail ('9' on 8-chip) before staging. + for bad_spmd in ("1x", "17", "9"): + out_bad = root / f"out_bad_{bad_spmd}" + pb = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--spmd", bad_spmd, "--out-dir", str(out_bad)], + env={**os.environ, "PCI_SYSFS_DIR": str(pci_4x75)}, + text=True, + capture_output=True, + ) + self.assertEqual(pb.returncode, 2, (bad_spmd, pb.returncode, pb.stderr, pb.stdout)) + + # No-Python: NUMA 0 vs 00 normalization + whitespace chip_id parity + libtpu*.so glob + Step 00 4-pkg verified. + pci_numa = root / "pci_numa" + for idx, (cid, numa) in enumerate((("0", "0"), ("0", "00"), ("1", "0"), ("1", "00"))): + _make_ep(pci_numa, f"0000:00:{4 + idx:02x}.0", "0x0075", cls="0x120000", chip_id=cid, numa_node=numa) + out_numa = root / "out_numa" + pn = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_numa)], + env={**nopy_env, "PCI_SYSFS_DIR": str(pci_numa)}, + text=True, + capture_output=True, + ) + self.assertEqual(pn.returncode, 0, pn.stderr + pn.stdout) + self.assertIn("effective_chips=4 ironwood_chips=4 run_671b_tier=0", (out_numa / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + pci_ws = root / "pci_ws" + for idx, raw_b in enumerate((b"\r1\n", b"\n1\n", b"2\n", b"2\n\n")): + _make_ep(pci_ws, f"0000:00:{4 + idx:02x}.0", "0x0075", cls="0x120000", chip_id=raw_b) + out_ws = root / "out_ws" + out_ws.mkdir() + fake_so = out_ws / "libtpu-0.0.53.1.so" + fake_so.write_bytes(b"ELF") + pw = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_ws)], + env={**nopy_env, "PCI_SYSFS_DIR": str(pci_ws)}, + text=True, + capture_output=True, + ) + self.assertEqual(pw.returncode, 0, pw.stderr + pw.stdout) + t_ws = (out_ws / "01_ggml_cloudtpu_ops_bench.txt").read_text() + self.assertIn("effective_chips=4 ironwood_chips=4 run_671b_tier=0", t_ws) + self.assertIn(f"LIBTPU_PATH={fake_so}", t_ws) + + pci_4x2_76 = root / "pci_4x2_76" + for s in range(4): + for fn in (0, 1): + _make_ep(pci_4x2_76, f"0000:00:{4 + s:02x}.{fn}", "0x0076") + out_s0 = root / "out_s0_nopy" + ps0 = subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_s0), "--allow-no-pjrt"], + env={**nopy_env, "PCI_SYSFS_DIR": str(pci_4x2_76)}, + text=True, + capture_output=True, + ) + self.assertEqual(ps0.returncode, 0, ps0.stderr + ps0.stdout) + self.assertIn( + "total_tpu_pci_packages=4 total_tpu_pci_functions=8 incomplete_pci_functions=0 pkg_count_verified=1 ironwood_pci_packages=4 ironwood_pci_functions=8", + (out_s0 / "00_pci_vfio_survey.txt").read_text(), + ) + + def test_step02_class_selection_and_pre_open_refusal(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = pathlib.Path(td) + drv_root = root / "drv" + (drv_root / "vfio-pci").mkdir(parents=True) + pci_s2 = root / "pci_s2" + ep_12 = _make_ep(pci_s2, "0000:00:04.0", "0x0075", cls="0x120000") + ep_ff = _make_ep(pci_s2, "0000:00:05.0", "0x0063", cls="0xff0000") + (ep_12 / "driver").symlink_to(drv_root / "vfio-pci") + (ep_ff / "driver").symlink_to(drv_root / "vfio-pci") + stub = root / "stub_smoke.sh" + stub.write_text( + "#!/bin/sh\n" + "echo 'BDFS_ARGS:' \"$*\"\n" + "echo 'MAPS_LIBTPU=0 MAPS_LIBPYTHON=0'\n" + "exit 0\n", + encoding="utf-8", + ) + stub.chmod(0o755) + out_sel = root / "out_sel" + ps = subprocess.run( + [BASH_BIN, STEP02, "--live-vfio", "--out-dir", str(out_sel)], + env={**os.environ, "SKIP_BUILD": "1", "SMOKE_BIN": str(stub), "PCI_SYSFS_DIR": str(pci_s2)}, + text=True, + capture_output=True, + ) + self.assertEqual(ps.returncode, 0, ps.stderr + ps.stdout) + log_sel = (out_sel / "02_libopentpu_vfio_probe.txt").read_text() + self.assertIn("BDFS_ARGS: --bdf 0000:00:05.0", log_sel) + self.assertIn("LIVE_VFIO_PROBE_STATUS=PASS", log_sel) + + # Pre-open Unsupported TPU PCI device refusal (0x0075/0x0076, class=0xff0000 or 0x120000) accepted cleanly. + pci_ref = root / "pci_ref" + ep_ref = _make_ep(pci_ref, "0000:00:04.0", "0x0075", cls="0x120000") + (ep_ref / "driver").symlink_to(drv_root / "vfio-pci") + stub_ref = root / "stub_ref.sh" + stub_ref.write_text( + "#!/bin/sh\n" + "echo 'MAPS_LIBTPU=0 MAPS_LIBPYTHON=0'\n" + "echo 'ot_context_create failed: UNSUPPORTED — Unsupported TPU PCI device 0000:00:04.0 (0x1ae0:0x0075 class=0x120000); only validated v5e (0x1ae0:0x0063 class=0xff0000) is supported' >&2\n" + "exit 1\n", + encoding="utf-8", + ) + stub_ref.chmod(0o755) + out_ref = root / "out_ref" + pr = subprocess.run( + [BASH_BIN, STEP02, "--live-vfio", "--out-dir", str(out_ref)], + env={**os.environ, "SKIP_BUILD": "1", "SMOKE_BIN": str(stub_ref), "PCI_SYSFS_DIR": str(pci_ref)}, + text=True, + capture_output=True, + ) + self.assertEqual(pr.returncode, 0, pr.stderr + pr.stdout) + self.assertIn("LIVE_VFIO_PROBE_STATUS=EXPECTED_UNVALIDATED_DEVICE_REFUSAL", (out_ref / "02_libopentpu_vfio_probe.txt").read_text()) + + def test_step00_native_pjrt_probe_and_jax_zero_fallback(self) -> None: + if not CXX_BIN: + self.skipTest("C++ compiler required for fake PJRT shared-library fixture") + with tempfile.TemporaryDirectory() as td: + root = pathlib.Path(td) + fake_pjrt = _compile_fake_pjrt(root / "pjrt_build" if (root / "pjrt_build").exists() else root) + pci_4x75 = root / "pci_4x75" + for i in range(4): + _make_ep(pci_4x75, f"0000:00:{4 + i:02x}.0", "0x0075", cls="0x120000") + + # Live native C++ PJRT probe: 8x TPU v7x -> PJRT_TOPOLOGY_CAPTURED + 671B tier=1. + out_ok = root / "out_native_ok" + p_ok = subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_ok)], + env={ + **os.environ, + "PCI_SYSFS_DIR": str(pci_4x75), + "LIBTPU_PATH": str(fake_pjrt), + "FAKE_PJRT_N": "8", + "FAKE_PJRT_KIND": "TPU v7x", + }, + text=True, + capture_output=True, + ) + self.assertEqual(p_ok.returncode, 0, p_ok.stderr + p_ok.stdout) + txt_ok = (out_ok / "00_pci_vfio_survey.txt").read_text() + self.assertIn(f"PJRT_LIBRARY={fake_pjrt}", txt_ok) + self.assertIn("PJRT_LOGICAL_DEVICES=8", txt_ok) + self.assertIn('PJRT_DEVICE index=7 id=7 local_hardware_id=7 kind="TPU v7x" coords=[0,1,0] core_on_chip=1', txt_ok) + self.assertIn("STATUS: PJRT_TOPOLOGY_CAPTURED (pci_tpu_packages=4 pci_tpu_functions=4 incomplete_pci_functions=0", txt_ok) + + p01_ok = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_ok)], + env={**os.environ, "PCI_SYSFS_DIR": str(pci_4x75), "LIBTPU_PATH": str(fake_pjrt)}, + text=True, + capture_output=True, + ) + self.assertEqual(p01_ok.returncode, 0, p01_ok.stderr + p01_ok.stdout) + self.assertIn( + "effective_chips=8 ironwood_chips=8 run_671b_tier=1", + (out_ok / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # Native C++ PJRT probe returning wrong device kind ("TPU v6 lite") -> MISMATCH & tier=0. + out_badkind = root / "out_native_badkind" + p_bk = subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_badkind)], + env={ + **os.environ, + "PCI_SYSFS_DIR": str(pci_4x75), + "LIBTPU_PATH": str(fake_pjrt), + "FAKE_PJRT_N": "8", + "FAKE_PJRT_KIND": "TPU v6 lite", + }, + text=True, + capture_output=True, + ) + self.assertEqual(p_bk.returncode, 0, p_bk.stderr + p_bk.stdout) + txt_bk = (out_badkind / "00_pci_vfio_survey.txt").read_text() + self.assertIn('kind="TPU v6 lite"', txt_bk) + self.assertIn("STATUS: PJRT_TOPOLOGY_MISMATCH", txt_bk) + p01_bk = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_badkind)], + env={**os.environ, "PCI_SYSFS_DIR": str(pci_4x75)}, + text=True, + capture_output=True, + ) + self.assertEqual(p01_bk.returncode, 0, p01_bk.stderr + p01_bk.stdout) + self.assertIn( + "ironwood_chips=0 run_671b_tier=0", + (out_badkind / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + # Stub jax returning [] guarantees FAKE_PJRT_N=0 cases never depend on host jax packages (R17 #6). + stub_jax = root / "stub_jax" / "jax" + stub_jax.mkdir(parents=True) + (stub_jax / "__init__.py").write_text("def local_devices(backend=None):\n return []\n", encoding="utf-8") + + # Native C++ PJRT probe returning 0 devices -> fails without --allow-no-pjrt; with --allow-no-pjrt disables 671B. + out_z_fail = root / "out_native_zero_fail" + p_zf = subprocess.run( + [BASH_BIN, STEP00, "--out-dir", str(out_z_fail)], + env={ + **os.environ, + "PCI_SYSFS_DIR": str(pci_4x75), + "LIBTPU_PATH": str(fake_pjrt), + "FAKE_PJRT_N": "0", + "PYTHONPATH": str(root / "stub_jax"), + }, + text=True, + capture_output=True, + ) + self.assertNotEqual(p_zf.returncode, 0) + out_z_allow = root / "out_native_zero_allow" + p_za = subprocess.run( + [BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_z_allow)], + env={ + **os.environ, + "PCI_SYSFS_DIR": str(pci_4x75), + "LIBTPU_PATH": str(fake_pjrt), + "FAKE_PJRT_N": "0", + "PYTHONPATH": str(root / "stub_jax"), + }, + text=True, + capture_output=True, + ) + self.assertEqual(p_za.returncode, 0, p_za.stderr + p_za.stdout) + txt_za = (out_z_allow / "00_pci_vfio_survey.txt").read_text() + self.assertIn("PJRT_LOGICAL_DEVICES=0", txt_za) + self.assertIn("STATUS: PJRT_TOPOLOGY_UNAVAILABLE", txt_za) + + # JAX fallback returning [] emits PJRT_LOGICAL_DEVICES=0 + zero-device message (R16 #4). + out_jax0 = root / "out_jax0" + pj0 = subprocess.run( + [BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_jax0)], + env={ + **os.environ, + "PCI_SYSFS_DIR": str(pci_4x75), + "LIBTPU_PATH": str(root / "nonexistent_libtpu.so"), + "PYTHONPATH": str(root / "stub_jax"), + }, + text=True, + capture_output=True, + ) + self.assertEqual(pj0.returncode, 0, pj0.stderr + pj0.stdout) + txt_j0 = (out_jax0 / "00_pci_vfio_survey.txt").read_text() + self.assertIn("PJRT_LOGICAL_DEVICES=0", txt_j0) + self.assertIn("JAX TPU backend returned 0 devices", txt_j0) + p01_j0 = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_jax0)], + env={**os.environ, "PCI_SYSFS_DIR": str(pci_4x75)}, + text=True, + capture_output=True, + ) + self.assertEqual(p01_j0.returncode, 0, p01_j0.stderr + p01_j0.stdout) + self.assertIn( + "ironwood_chips=0 run_671b_tier=0", + (out_jax0 / "01_ggml_cloudtpu_ops_bench.txt").read_text(), + ) + + def test_round16_regressions(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = pathlib.Path(td) + fake_bin = _build_no_python_path(root / "no_py_bin") + nopy_env = {"PATH": str(fake_bin), "HOME": os.environ.get("HOME", "/tmp")} + py_env = _build_offline_py_env(root) + + # R16 #2: chip_id=0 on a full 2-fn slot collides with separate .0 slots claiming chip_id=0 + # (3 verified pkgs -> effective_chips=6, NOT 4 pkgs / 8 chips / tier=1). + pci_reuse = root / "pci_reuse" + _make_ep(pci_reuse, "0000:00:04.0", "0x0076", chip_id="0") + _make_ep(pci_reuse, "0000:00:04.1", "0x0076", chip_id="0") + _make_ep(pci_reuse, "0000:00:05.0", "0x0076", chip_id="0") + _make_ep(pci_reuse, "0000:00:06.0", "0x0076", chip_id="0") + _make_ep(pci_reuse, "0000:00:07.0", "0x0076", chip_id="2") + _make_ep(pci_reuse, "0000:00:08.0", "0x0076", chip_id="2") + _make_ep(pci_reuse, "0000:00:09.0", "0x0076", chip_id="3") + _make_ep(pci_reuse, "0000:00:0a.0", "0x0076", chip_id="3") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_reuse)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_reuse)})): + out_r = root / f"out_reuse_{tag}" + p0 = subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_r)], env=env, text=True, capture_output=True) + self.assertEqual(p0.returncode, 0, p0.stderr + p0.stdout) + txt_r = (out_r / "00_pci_vfio_survey.txt").read_text() + self.assertIn("total_tpu_pci_packages=3 total_tpu_pci_functions=8 incomplete_pci_functions=2", txt_r) + self.assertIn("ironwood_pci_packages=3 ironwood_pci_functions=8", txt_r) + p1 = subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_r)], env=env, text=True, capture_output=True) + self.assertEqual(p1.returncode, 0, p1.stderr + p1.stdout) + self.assertIn("effective_chips=6 ironwood_chips=0 run_671b_tier=0", (out_r / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + # R16 #3: mixed 0x0075 + unlisted DID (0x0077 2-fn) -> stale 4-pkg survey does not promote; matching 3-pkg survey caps ironwood_chips at 6 (tier=0). + pci_4x75_ref = root / "pci_4x75_ref" + for i in range(4): + _make_ep(pci_4x75_ref, f"0000:00:{4 + i:02x}.0", "0x0075", cls="0x120000") + pci_mix3 = root / "pci_mix3" + _make_ep(pci_mix3, "0000:00:04.0", "0x0075", cls="0x120000") + _make_ep(pci_mix3, "0000:00:05.0", "0x0075", cls="0x120000") + _make_ep(pci_mix3, "0000:00:06.0", "0x0077") + _make_ep(pci_mix3, "0000:00:06.1", "0x0077") + for tag, env_prefix in (("py", py_env), ("sh", nopy_env)): + out_m_stale = root / f"out_mix3_stale_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_m_stale)], env={**env_prefix, "PCI_SYSFS_DIR": str(pci_4x75_ref)}, check=True, capture_output=True) + with open(out_m_stale / "00_pci_vfio_survey.txt", "a", encoding="utf-8") as fh: + fh.write('PJRT_DEVICE index=0 id=0 local_hardware_id=0 kind="TPU v7x" coords=[0,0,0] core_on_chip=0\n') + fh.write("PJRT_LOGICAL_DEVICES=8\n") + fh.write("STATUS: PJRT_TOPOLOGY_CAPTURED (pci_tpu_packages=4 pci_tpu_functions=4 incomplete_pci_functions=0)\n") + p_ms = subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_m_stale)], env={**env_prefix, "PCI_SYSFS_DIR": str(pci_mix3)}, text=True, capture_output=True) + self.assertEqual(p_ms.returncode, 0, p_ms.stderr + p_ms.stdout) + self.assertIn("effective_chips=6 ironwood_chips=4 run_671b_tier=0", (out_m_stale / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + out_m_cap = root / f"out_mix3_cap_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_m_cap)], env={**env_prefix, "PCI_SYSFS_DIR": str(pci_mix3)}, check=True, capture_output=True) + with open(out_m_cap / "00_pci_vfio_survey.txt", "a", encoding="utf-8") as fh: + fh.write('PJRT_DEVICE index=0 id=0 local_hardware_id=0 kind="TPU v7x" coords=[0,0,0] core_on_chip=0\n') + fh.write("PJRT_LOGICAL_DEVICES=8\n") + fh.write("STATUS: PJRT_TOPOLOGY_CAPTURED (pci_tpu_packages=3 pci_tpu_functions=4 incomplete_pci_functions=0)\n") + p_mc = subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_m_cap)], env={**env_prefix, "PCI_SYSFS_DIR": str(pci_mix3)}, text=True, capture_output=True) + self.assertEqual(p_mc.returncode, 0, p_mc.stderr + p_mc.stdout) + self.assertIn("effective_chips=8 ironwood_chips=6 run_671b_tier=0", (out_m_cap / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + # R16 #5: unrelated PCI lines (non-1ae0 or 0x02* network class) in survey are ignored. + pci_1x75 = root / "pci_1x75" + _make_ep(pci_1x75, "0000:00:04.0", "0x0075", cls="0x120000") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_1x75)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_1x75)})): + out_unrel = root / f"out_unrel_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_unrel)], env=env, check=True, capture_output=True) + with open(out_unrel / "00_pci_vfio_survey.txt", "a", encoding="utf-8") as fh: + fh.write("0000:00:08.0 vendor=0x1234 device=0x0063 class=0x020000\n") + fh.write("0000:00:09.0 vendor=0x1ae0 device=0x0075 class=0x020000\n") + fh.write("0000:00:0a.0 vendor=0x1ae0 device=0x0075 class=0x020001\n") + p_un = subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_unrel)], env=env, text=True, capture_output=True) + self.assertEqual(p_un.returncode, 0, p_un.stderr + p_un.stdout) + self.assertIn("effective_chips=2 ironwood_chips=2 run_671b_tier=0", (out_unrel / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + # R16 #7: Step 00 (Python + no-Python) verifies 4x 0x0075 (pkg_count_verified=1) and flags 4x unpaired 0x0076 (0 pkgs / 4 inc). + pci_4x75_s0 = root / "pci_4x75_s0" + pci_4x76_unp = root / "pci_4x76_unp" + for i in range(4): + _make_ep(pci_4x75_s0, f"0000:00:{4 + i:02x}.0", "0x0075", cls="0x120000") + _make_ep(pci_4x76_unp, f"0000:00:{4 + i:02x}.0", "0x0076") + for tag, env_prefix in (("py", py_env), ("sh", nopy_env)): + out_s0_75 = root / f"out_s0_{tag}_75" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_s0_75)], env={**env_prefix, "PCI_SYSFS_DIR": str(pci_4x75_s0)}, check=True, capture_output=True) + self.assertIn( + "total_tpu_pci_packages=4 total_tpu_pci_functions=4 incomplete_pci_functions=0 pkg_count_verified=1 ironwood_pci_packages=4 ironwood_pci_functions=4", + (out_s0_75 / "00_pci_vfio_survey.txt").read_text(), + ) + out_s0_76u = root / f"out_s0_{tag}_76u" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_s0_76u)], env={**env_prefix, "PCI_SYSFS_DIR": str(pci_4x76_unp)}, check=True, capture_output=True) + self.assertIn( + "total_tpu_pci_packages=0 total_tpu_pci_functions=4 incomplete_pci_functions=4 pkg_count_verified=1 ironwood_pci_packages=0 ironwood_pci_functions=4", + (out_s0_76u / "00_pci_vfio_survey.txt").read_text(), + ) + + # R16 #8: --spmd integer-overflow digit string exits 2 without bash overflow. + out_ovf = root / "out_ovf" + p_ovf = subprocess.run( + [BASH_BIN, STEP01, "--dry-run", "--spmd", "18446744073709551624", "--out-dir", str(out_ovf)], + env={**py_env, "PCI_SYSFS_DIR": str(pci_4x75_s0)}, + text=True, + capture_output=True, + ) + self.assertEqual(p_ovf.returncode, 2, p_ovf.stderr + p_ovf.stdout) + + # R16 #9 & R18 #3: NUMA "1 0" vs "10" and malformed b"1\xff\n" vs b"1\n" stay distinct; + # "\n1\n", " 1\n", and "1\r\n" normalize identically across Python and awk. + pci_numa_sp = root / "pci_numa_sp" + _make_ep(pci_numa_sp, "0000:00:04.0", "0x0076", cls="0xff0000", chip_id="0", numa_node="1 0") + _make_ep(pci_numa_sp, "0000:00:05.0", "0x0076", cls="0xff0000", chip_id="0", numa_node="10") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_numa_sp)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_numa_sp)})): + out_ns = root / f"out_numa_sp_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_ns)], env=env, check=True, capture_output=True) + self.assertIn("total_tpu_pci_packages=0 total_tpu_pci_functions=2 incomplete_pci_functions=2", (out_ns / "00_pci_vfio_survey.txt").read_text()) + subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_ns)], env=env, check=True, capture_output=True) + self.assertIn("effective_chips=0 ironwood_chips=0 run_671b_tier=0", (out_ns / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + pci_numa_badb = root / "pci_numa_badb" + _make_ep(pci_numa_badb, "0000:00:04.0", "0x0076", cls="0xff0000", chip_id="0", numa_node=b"1\xff\n") + _make_ep(pci_numa_badb, "0000:00:05.0", "0x0076", cls="0xff0000", chip_id="0", numa_node=b"1\n") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_numa_badb)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_numa_badb)})): + out_nb = root / f"out_numa_badb_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_nb)], env=env, check=True, capture_output=True) + self.assertIn("total_tpu_pci_packages=0 total_tpu_pci_functions=2 incomplete_pci_functions=2", (out_nb / "00_pci_vfio_survey.txt").read_text(encoding="utf-8", errors="replace")) + subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_nb)], env=env, check=True, capture_output=True) + self.assertIn("effective_chips=0 ironwood_chips=0 run_671b_tier=0", (out_nb / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + pci_numa_nl = root / "pci_numa_nl" + _make_ep(pci_numa_nl, "0000:00:04.0", "0x0075", cls="0x120000", numa_node=b"\n1\n") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_numa_nl)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_numa_nl)})): + out_nl = root / f"out_numa_nl_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_nl)], env=env, check=True, capture_output=True) + self.assertIn("total_tpu_pci_packages=1 total_tpu_pci_functions=1 incomplete_pci_functions=0 pkg_count_verified=1", (out_nl / "00_pci_vfio_survey.txt").read_text()) + + pci_numa_tr = root / "pci_numa_tr" + _make_ep(pci_numa_tr, "0000:00:04.0", "0x0076", cls="0xff0000", chip_id="0", numa_node=b" 1\n") + _make_ep(pci_numa_tr, "0000:00:05.0", "0x0076", cls="0xff0000", chip_id="0", numa_node=b"1\r\n") + for tag, env in (("py", {**py_env, "PCI_SYSFS_DIR": str(pci_numa_tr)}), ("sh", {**nopy_env, "PCI_SYSFS_DIR": str(pci_numa_tr)})): + out_nt = root / f"out_numa_tr_{tag}" + subprocess.run([BASH_BIN, STEP00, "--allow-no-pjrt", "--out-dir", str(out_nt)], env=env, check=True, capture_output=True) + self.assertIn("total_tpu_pci_packages=1 total_tpu_pci_functions=2 incomplete_pci_functions=0 pkg_count_verified=1", (out_nt / "00_pci_vfio_survey.txt").read_text()) + subprocess.run([BASH_BIN, STEP01, "--dry-run", "--out-dir", str(out_nt)], env=env, check=True, capture_output=True) + self.assertIn("effective_chips=2", (out_nt / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + self.assertIn("run_671b_tier=0", (out_nt / "01_ggml_cloudtpu_ops_bench.txt").read_text()) + + +if __name__ == "__main__": + unittest.main()