diff --git a/.claude/skills/transferbench-debug/SKILL.md b/.claude/skills/transferbench-debug/SKILL.md index d0da63ea..5720fe63 100644 --- a/.claude/skills/transferbench-debug/SKILL.md +++ b/.claude/skills/transferbench-debug/SKILL.md @@ -29,6 +29,7 @@ Only after that, branch by symptom — see the table below. | Bandwidth varies wildly run-to-run | Warmup too short, NUMA/clock policy | `NUM_WARMUPS=10`, `SHOW_ITERATIONS=1`, `SHOW_PERCENTILES=50,90,99` | `references/common-failures.md` §perf | | Crash / segfault | Bad memory code (e.g. `F` on a GPU without fine-grain), bad kernel for arch | Run with `dryrun` first; rebuild without optimization for symbol info | `references/common-failures.md` §crash | | "Unsupported" / executor missing | Build-time disable (e.g. `DISABLE_NIC_EXEC=1`, `DISABLE_POD_COMM=1`) | `./TransferBench` (no args) — its banner lists which executors are compiled in | `references/common-failures.md` §unsupported | +| Storage Transfer (`S` with `F`, or `nvme` preset) rejected or fails | `TB_STORAGE_PATHS` unset, hipFile unavailable, or hipFile direct I/O not usable on this host | `./TransferBench` (no args) — storage section shows paths and hipFile availability; retry with `HIPFILE_FORCE_COMPAT_MODE=true` | `references/common-failures.md` §storage | | Output is garbled / interleaved across ranks | MPI stderr buffering, no per-rank labels | `mpirun --tag-output` or pipe each rank into a per-rank log | `references/multi-rank-debug.md` §output | ## The four "always-on" introspection commands diff --git a/.claude/skills/transferbench-debug/references/common-failures.md b/.claude/skills/transferbench-debug/references/common-failures.md index e3af917d..dc163ac0 100644 --- a/.claude/skills/transferbench-debug/references/common-failures.md +++ b/.claude/skills/transferbench-debug/references/common-failures.md @@ -120,6 +120,41 @@ Catalog of the most common "it doesn't work" cases, organized by symptom. Each s --- +## §storage — storage Transfer (`S` with hipFile `F`) or `nvme` preset fails + +### Symptom +- "No storage paths are defined on rank N" or the `nvme` preset prints `TB_STORAGE_PATHS` instructions and exits. +- "Storage memory (S) can only be accessed by the hipFile (F) executor". +- "hipFile executor is requested but is not available". +- "hipFile read/write ... failed (...): ... hipFile's fastpath may not be usable here". +- "Storage N (...) is a block device. Writing to it destroys its contents and requires TB_STORAGE_ALLOW_BLOCK_WRITE=1". +- "Storage N (...) is an existing file that holds data. Writing to it destroys its contents and requires TB_STORAGE_ALLOW_OVERWRITE=1", or the `nvme` preset reports `UNVALIDATED` on a second run. +- "numBytes (...) and [data.byteOffset] (...) are not both multiples of 4096. hipFile will use its compatibility path for unaligned I/O" (warning). +- Suspiciously high bandwidth with I/O path `compat`. + +### Cause +- `TB_STORAGE_PATHS` is unset, or the storage index is beyond the list (`S1` with one path). +- A combination outside what storage Transfers allow: exactly one SRC and one DST, one of them `S`, the other `G` on the executor's GPU, same rank. +- The binary was built without hipFile support: `hipfile.h` from the hipFile development package (`amdrocm-hipfile-dev`) was not found at build time. The version line then has no `hipFile`. Rebuilding is the only fix. +- "error while loading shared libraries: libhipfile.so.0" at startup: the binary was built with hipFile support and the hipFile runtime package (`amdrocm-hipfile`) is missing on this host. +- A storage path under `/dev/` that does not exist is rejected ("Paths under /dev/ ... are not created"): almost always a mistyped device name. +- hipFile attempted direct I/O where it can't work (no AIS support in the GPU driver, no PCIe P2PDMA, storage not local NVMe, WSL2 with an older hipFile). It does not always fall back by itself. +- A write targets a raw block device without the opt-in. +- A storage file already holds data (a user's file, or the file an earlier run left behind) and `TB_STORAGE_ALLOW_OVERWRITE=1` is not set. +- Compatibility-path I/O goes through host memory and the page cache; it is not a direct storage ↔ GPU number. + +### Fix +1. `./TransferBench` with no args — the storage section lists the paths and whether hipFile is available on this host. +2. `./TransferBench dryrun 1M ""` to see the parsed Transfer; fix the SRC/EXE/DST combination. +3. `HIPFILE_FORCE_COMPAT_MODE=true` to confirm the Transfer itself is sound; then `ais-check` (ships with hipFile) to see why direct I/O is unavailable. +4. `TB_VERBOSE=1` and look for `storage I/O path:` — `HIPFILE_ALLOW_COMPAT_MODE=false` makes hipFile fail instead of silently using `compat`. +5. For direct I/O: use a byte count that is a multiple of 4096, `BYTE_OFFSET=0`, and a file on xfs / ext4 on a local NVMe drive (or the raw block device). +6. Block devices: **do not** set `TB_STORAGE_ALLOW_BLOCK_WRITE=1` unless the user confirms the device holds nothing of value. Read-only Transfers (`S0->F0->G0`) work without it, but skip validation. + Existing files: delete TransferBench's own scratch file or set `TB_STORAGE_ALLOW_OVERWRITE=1` to reuse it; **do not** set it for a file that may hold the user's data. +7. `TB_HIPFILE_SKIP_BUF_REGISTER=1` if it hangs or fails while registering the GPU buffer. + +--- + ## §parser — config-file parser rejects a line ### Symptom diff --git a/.claude/skills/transferbench-debug/references/verbose-introspection.md b/.claude/skills/transferbench-debug/references/verbose-introspection.md index b9079905..0a2e5666 100644 --- a/.claude/skills/transferbench-debug/references/verbose-introspection.md +++ b/.claude/skills/transferbench-debug/references/verbose-introspection.md @@ -76,6 +76,16 @@ The first one is especially valuable when debugging — its banner names every e | `NIC_CQ_POLL_BATCH=N` | CQ poll batch size | Reduce to 1 to expose race conditions | | `NIC_RELAX_ORDER=0\|1` | Relaxed ordering on the NIC | Disable when ordering bugs suspected | +## Storage (hipFile) debug + +| Variable | Effect | Use case | +|---|---|---| +| `TB_VERBOSE=1` | Logs storage open, hipFile handle / buffer registration, and `storage I/O path: fastpath\|compat\|mixed\|unknown` per executor (`unknown`: hipFile older than 0.5.0, or `HIPFILE_STATS_LEVEL=0`) | "Did this hipFile number come from direct I/O or from the compatibility path?" | +| `HIPFILE_FORCE_COMPAT_MODE=true` | hipFile's own variable: never attempt direct I/O | hipFile Transfers fail with "fastpath may not be usable here" | +| `HIPFILE_ALLOW_COMPAT_MODE=false` | hipFile's own variable: fail instead of falling back | Prove a result is direct I/O | +| `TB_HIPFILE_SKIP_BUF_REGISTER=1` | Skip `hipFileBufRegister` | Hang or failure while registering the GPU buffer with hipFile | +| `TB_STORAGE_TIMED_SYNC=1` | Include `fdatasync` in write timing | Compatibility-path write bandwidth looks too good | + ## Pod / multi-rank fallbacks | Variable | Effect | Use case | diff --git a/.claude/skills/transferbench-run/SKILL.md b/.claude/skills/transferbench-run/SKILL.md index 050eac54..a1d55399 100644 --- a/.claude/skills/transferbench-run/SKILL.md +++ b/.claude/skills/transferbench-run/SKILL.md @@ -5,7 +5,7 @@ description: Use when the user wants to *run* TransferBench (the ROCm/CUDA memor # TransferBench -TransferBench is a command-line utility for benchmarking simultaneous data transfers between CPU, GPU, and NIC memory locations using GPU kernels, DMA engines, RDMA NICs, or CPU threads. It runs on AMD (ROCm/HIP) and NVIDIA (CUDA) platforms. +TransferBench is a command-line utility for benchmarking simultaneous data transfers between CPU, GPU, and NIC memory locations using GPU kernels, DMA engines, RDMA NICs, or CPU threads. It can also benchmark I/O between storage (NVMe-backed files or block devices) and GPU memory using hipFile. It runs on AMD (ROCm/HIP) and NVIDIA (CUDA) platforms; the hipFile executor is HIP-only. The binary is named `TransferBench` (HIP build) or `TransferBenchCuda` (CUDA build). A prebuilt `TransferBenchCuda` may exist at the repo root; otherwise build with `make` (HIP) or `make TransferBenchCuda` (CUDA). @@ -25,7 +25,9 @@ A **SubExecutor (SE)** is the unit of parallelism inside an executor: - CPU executor → CPU thread - GPU executor → threadblock / Compute Unit (CU) - DMA / Batched-DMA → stream / batch item (must have a single SRC) -- NIC → Queue Pair +- TDM → threadblock / Compute Unit (CU) +- NIC / Nearest-NIC → Queue Pair +- hipFile (storage) → I/O thread ## Invocation @@ -76,6 +78,13 @@ Write a small `.cfg` file (see `references/config-format.md`) and pass it as the ./TransferBench nicrings # NIC ring tests ``` +### "How fast is NVMe ↔ GPU?" → nvme preset or storage Transfers +```bash +TB_STORAGE_PATHS=/mnt/nvme0/tb.dat ./TransferBench nvme 1G # write + read per GPU, validated +TB_STORAGE_PATHS=/mnt/nvme0/tb.dat ./TransferBench cmdline 1G "1 4 (S0->F0->G0)" # one hipFile read, 4 I/O threads +``` +`S0` is the first path in `TB_STORAGE_PATHS` (a file, or a block device such as `/dev/nvme1n1`). `F` is the hipFile executor. Check the reported I/O path (`fastpath` vs `compat`) before comparing numbers, and never set `TB_STORAGE_ALLOW_BLOCK_WRITE=1` without confirming with the user: it lets TransferBench overwrite the listed block devices. A file that already holds data is read-only (writes rejected, reads unvalidated) unless `TB_STORAGE_ALLOW_OVERWRITE=1` is set; use that only for TransferBench's own scratch file, such as the one an earlier run left behind. See `references/config-format.md` and `references/env-vars.md`. + ### "Pod-aware (multi-rank, single MNNVL/XGMI pod)" → pod presets ```bash ./TransferBench podp2p # within-pod P2P diff --git a/.claude/skills/transferbench-run/references/config-format.md b/.claude/skills/transferbench-run/references/config-format.md index f07c9131..a073072f 100644 --- a/.claude/skills/transferbench-run/references/config-format.md +++ b/.claude/skills/transferbench-run/references/config-format.md @@ -52,6 +52,10 @@ Example: | `B` | Batched-DMA | GPU device | `hipMemcpyBatchAsync`-based; HIP 7.1 / CUDA 12.8+ | | `I#.#` | NIC executor | NIC index `.` QP index | e.g. `I0.2` | | `N#.#` | Nearest-NIC executor | GPU index `.` QP index | Picks each end's closest NIC | +| `T` | TDM | GPU device | SubExecutor = threadblock / CU; AMD gfx1250 or NVIDIA sm_90+ | +| `F` | hipFile | GPU device | SubExecutor = I/O thread; storage ↔ GPU memory via `hipFileRead`/`hipFileWrite` | + +Executor and memory codes are independent: `F` as an executor is hipFile, `F` as a memory location is fine-grain device memory. ## Memory-location codes @@ -68,10 +72,36 @@ A memory location is ``. Multiple locations can be concatenated for | `G` | Global device memory | GPU | | `F` | Fine-grain device memory | GPU | | `U` | Uncached device memory | GPU | +| `M` | Managed memory | GPU | | `N` | Null (no read or no write) | ignored | +| `S` | Storage (regular file or raw block device) | position in `TB_STORAGE_PATHS` | `N` on the SRC side gives a "memset-like" write benchmark; `N` on the DST side gives a "read-only" benchmark. +## Storage transfers (`S` with `F`) + +`S` is the n-th path (0-based) in the comma-separated `TB_STORAGE_PATHS` environment variable. Rules: + +- `S` only works with the `F` (hipFile) executor, and that executor needs exactly one `S`. +- Exactly one SRC and one DST: one is `S`, the other is `G` on the executor's GPU (`S0->F1->G1` is valid, `S0->F0->G1` is not). Same rank for all three. +- The byte count and `BYTE_OFFSET` should be multiples of 4096. Other values are accepted with a warning (hipFile uses its compatibility path). +- A block device is only written to with `TB_STORAGE_ALLOW_BLOCK_WRITE=1` (destroys its contents). Without it, writes are rejected and reads skip validation. +- A file that already holds data (including one left by an earlier run) is only written to with `TB_STORAGE_ALLOW_OVERWRITE=1`. Without it, writes are rejected and reads skip validation. +- A missing regular file is created; a missing path under `/dev/` (other than `/dev/shm/`) is an error. +- `F` needs a binary built with hipFile support (the version line shows `hipFile`). +- No executor subindices, no PingPong, HIP builds only. + +``` +## hipFile read: storage 0 into GPU0 with 4 I/O threads +1 4 (S0->F0->G0) + +## hipFile write: GPU0 to storage 0 with 4 I/O threads +1 4 (G0->F0->S0) + +## Two GPUs each reading from their own drive in parallel +2 4 (S0->F0->G0) (S1->F1->G1) +``` + ## Idiomatic patterns ``` diff --git a/.claude/skills/transferbench-run/references/env-vars.md b/.claude/skills/transferbench-run/references/env-vars.md index 5013a1cd..a6522d8f 100644 --- a/.claude/skills/transferbench-run/references/env-vars.md +++ b/.claude/skills/transferbench-run/references/env-vars.md @@ -78,6 +78,30 @@ This is a curated guide to the most-used variables. For the authoritative comple | `NIC_RELAX_ORDER` | `1` | Relaxed ordering on the NIC. | | `TB_NIC_FILTER` | unset | Restrict which NICs participate. | +## Storage (hipFile executor) + +| Variable | Default | Effect | +|---|---|---| +| `TB_STORAGE_PATHS` | unset | Comma-separated files and/or block devices. `S` in a Transfer is the n-th path (0-based). Required for any storage Transfer and for the `nvme` preset. | +| `TB_STORAGE_ALLOW_BLOCK_WRITE` | unset | `1` allows writing to block devices in `TB_STORAGE_PATHS`. **Destroys their contents.** | +| `TB_STORAGE_ALLOW_OVERWRITE` | unset | `1` allows overwriting files in `TB_STORAGE_PATHS` that already hold data (needed to reuse the file an earlier run left behind). **Replaces their contents**, for reads too. | +| `TB_STORAGE_TIMED_SYNC` | unset | `1` includes flushing written data to storage (`fdatasync`) in write timing. | +| `TB_HIPFILE_SKIP_BUF_REGISTER` | unset | `1` skips `hipFileBufRegister` for the hipFile executor. | +| `HIPFILE_FORCE_COMPAT_MODE` | `false` | hipFile's own variable: `true` forces its compatibility path (POSIX I/O via host memory). | +| `HIPFILE_ALLOW_COMPAT_MODE` | `true` | hipFile's own variable: `false` fails instead of falling back, guaranteeing direct I/O. | +| `HIPFILE_UNSUPPORTED_FILE_SYSTEMS` | `false` | hipFile's own variable: `true` attempts direct I/O on file systems other than ext4 (`data=ordered`) / xfs. | + +The `HIPFILE_*` variables are read by hipFile once per process and are never set by TransferBench. + +Used by the `nvme` preset: + +| Variable | Default | Effect | +|---|---|---| +| `NUM_FILE_SE` | `4` | I/O threads per Transfer. | +| `NUM_GPU_DEVICES` | all | Limit GPUs tested. | +| `NVME_MODE` | `0` | `0` write + read, `1` write only, `2` read only. | +| `NVME_PAIRED` | `0` | `1` = GPU i only uses storage path (i mod #paths); `0` = every GPU × every path. | + ## Multi-rank / pod | Variable | Default | Effect | diff --git a/.claude/skills/transferbench-run/references/presets.md b/.claude/skills/transferbench-run/references/presets.md index 086979cc..5e1606e0 100644 --- a/.claude/skills/transferbench-run/references/presets.md +++ b/.claude/skills/transferbench-run/references/presets.md @@ -18,6 +18,7 @@ For the live list on a given build, run `./TransferBench presets`. | `gfxsweep` | Sweeps GFX kernel options for one Transfer. | | `hbm` | Local HBM read bandwidth on each GPU. | | `healthcheck` | Quick correctness/perf health check (AMD MI300 series only). | +| `nvme` | GPU → storage write and storage → GPU read per GPU and storage path, via hipFile, with validation. Needs `TB_STORAGE_PATHS`; non-zero exit on failure. | | `one2all` | All subsets of parallel transfers from one GPU to all others. | | `p2p` | Peer-to-peer device-memory matrix between every GPU pair. | | `pcopy` | Parallel copies from a single GPU to other GPUs. | @@ -70,5 +71,6 @@ These print and exit; they don't run transfers. - "All-pairs simultaneous" → `a2a`. - "How does perf scale with CUs?" → `scaling` or `gfxsweep`. - "Across two nodes via RDMA" → `nicp2p` for matrix, `nica2a` for collective-style. +- "How fast can a GPU load from / save to NVMe?" → `nvme` with `TB_STORAGE_PATHS` set. - "Within an MNNVL pod" → `podp2p` / `poda2a`. - "I want to capture what a preset does and tweak it" → run with `TB_DUMP_CFG_FILE=out.cfg`, then edit `out.cfg`. diff --git a/.github/workflows/README_BUILD_PACKAGES.md b/.github/workflows/README_BUILD_PACKAGES.md index 0db3be50..70a28183 100644 --- a/.github/workflows/README_BUILD_PACKAGES.md +++ b/.github/workflows/README_BUILD_PACKAGES.md @@ -47,6 +47,7 @@ The workflow always builds with: - `ENABLE_MPI_COMM=OFF` — MPI multi-node communicator disabled (would require OpenMPI at runtime; not bundled by TheRock SDK). Packages are built to run out of the box with only `numactl`/`libnuma1` from the OS. - `DISABLE_DMABUF=OFF` — DMA-BUF support for GPU Direct RDMA - `BUILD_RELOCATABLE_PACKAGE=ON` — RVS-style install prefix + package naming +- `ENABLE_HIPFILE` is left at its default (`AUTO`) — the hipFile executor is built when the SDK provides `hipfile.h` and `libhipfile`. The binary then needs `libhipfile.so.0` at runtime, and the DEB/RPM packages depend on the hipFile runtime package of the ROCm release they were built against (`amdrocm-hipfile.`). Pass `-DENABLE_HIPFILE=OFF` to build without it - `GPU_TARGETS` — full data-center + consumer set (gfx906, 908, 90a, 942, 950, 1030, 1100/01/02, 1150/51/52/53, 1200/01) ## Local builds diff --git a/CHANGELOG.md b/CHANGELOG.md index a8118e1f..444287c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,52 @@ Documentation for TransferBench is available at [https://rocm.docs.amd.com/projects/TransferBench](https://rocm.docs.amd.com/projects/TransferBench). +## v1.72.00 +### Added +- Added storage memory type [S] to benchmark I/O between storage and GPU memory. `SN` refers to the N-th path + (starting from 0) in the new comma-separated `TB_STORAGE_PATHS` environment variable. Each path is either a regular + file (typically on an NVMe-backed filesystem) or a raw block device such as `/dev/nvme1n1` + - Regular files are created and grown as needed, and are left in place afterwards. A path under `/dev/` (other + than `/dev/shm/`) that does not exist is rejected instead of being created, as it is most likely a mistyped + device name + - A file that already holds data when TransferBench first uses it (including one left behind by an earlier run) + is only written to if `TB_STORAGE_ALLOW_OVERWRITE=1` is set. Otherwise it is treated like a block device: + Transfers that write to it are rejected, and Transfers that read from it transfer the existing contents + without data validation + - Each entry must be a distinct file or device, and ranks on the same host need distinct paths (files are locked + while in use, and block devices that are written to are opened exclusively). An empty entry ahead of a path is + rejected, as it would renumber the storage indices that follow it + - Block devices are never created or resized, and are only written to if `TB_STORAGE_ALLOW_BLOCK_WRITE=1` is set + (this destroys their contents). Otherwise Transfers that write to them are rejected, and Transfers that read + from them transfer the existing contents without data validation +- Added hipFile executor [F], which moves data between storage memory and GPU memory using + `hipFileRead`/`hipFileWrite`. It is indexed by GPU, and its SubExecutors are I/O threads issuing blocking calls + - hipFile is an optional build-time dependency: the executor is built when `hipfile.h` (hipFile development + package, e.g. `amdrocm-hipfile-dev10.2`) is found, and TransferBench then links against `libhipfile` + - Makefile: detected under `HIPFILE_PATH` (defaults to `ROCM_PATH`); `DISABLE_HIPFILE=1` builds without it + - CMake: `-DENABLE_HIPFILE=AUTO|ON|OFF` (default `AUTO`: use hipFile if found under `ROCM_PATH`), with + `-DHIPFILE_PATH` (or the `HIPFILE_PATH` environment variable) to point at it. Packages built with hipFile support depend on the hipFile runtime package (e.g. `amdrocm-hipfile10.2`) + - Without hipFile support, [F] and [S] are still parsed, and a Transfer using the hipFile executor is rejected + with an error saying that TransferBench was built without hipFile support + - e.g. `1 4 (S0->F0->G0)` reads storage 0 into GPU 0 memory with 4 I/O threads, and `(G0->F0->S0)` writes + - A storage Transfer has exactly one SRC and one DST: one is storage memory and the other is GPU device memory [G] + on the Executor's GPU. Other combinations involving [S] or the executor [F] are rejected with a fatal error + - Wildcards for the Executor index and the GPU memory index follow each other, e.g. `(S0->F*->G*)` expands to one + Transfer per GPU + - If the number of bytes or `BYTE_OFFSET` is not a multiple of 4096, a warning is shown, as hipFile then uses its + compatibility path + - Timing uses CPU wall clock around the I/O calls only. Written data is flushed and the page cache dropped before + each timed pass. `TB_STORAGE_TIMED_SYNC=1` includes flushing written data to storage in write timing + - `TB_HIPFILE_SKIP_BUF_REGISTER=1` skips registering GPU buffers with hipFile + - Not supported on NVIDIA hardware +- Added "nvme" preset, which writes from each GPU to each storage path and then reads from each storage path into + each GPU using the hipFile executor, with data validation of every Transfer. It reports bandwidth and the I/O path + used (fastpath / compat) per Transfer, and returns a non-zero exit code if any Transfer fails + - Behavior can be modified with `NUM_FILE_SE`, `NUM_GPU_DEVICES`, `NVME_MODE` and `NVME_PAIRED` +- Topology output now lists storage paths and whether the hipFile executor is available +### Modified +- Help text and examples/example.cfg now list all eight Executors and the managed [M] and storage [S] memory types + ## v1.71.02 ### Added - LaunchTransferBench.sh now supports bracketed range wildcards in the host list, e.g. `node[1..4]` or diff --git a/CMakeLists.txt b/CMakeLists.txt index dcba63b8..a0140f07 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -203,6 +203,7 @@ option(ENABLE_MPI_COMM "Enable MPI Communicator support" option(ENABLE_AMD_SMI "Enable AMD-SMI pod membership queries" OFF) option(ENABLE_POD_COMM "Enable pod communication" OFF) option(BUILD_RELOCATABLE_PACKAGE "Build with RVS-style relocatable RPATH and amdrocm-transferbench package naming" OFF) +option(ENABLE_HIPFILE "Enable hipFile executor support" OFF) include(cmake/Dependencies.cmake) # rocm-cmake, rocm_local_targets, rocm_check_target_ids @@ -322,6 +323,13 @@ endif() ## Only libdl needs to be linked so that dlopen/dlsym resolve. message(STATUS "NIC executor: libibverbs is loaded dynamically at runtime (no -libverbs link, no build-host dependency)") +## Check for hipFile support +if(ENABLE_HIPFILE) + find_package(hipfile REQUIRED CONFIG PATHS "${ROCM_PATH}" NO_DEFAULT_PATH) + set(HIPFILE_FOUND 1) + message(STATUS "hipFile executor: found ${hipfile_VERSION}") +endif() + ## Check for MPI support set(MPI_PATH "" CACHE PATH "Path to MPI installation (takes priority over system MPI)") if(DEFINED ENV{DISABLE_MPI_COMM} AND "$ENV{DISABLE_MPI_COMM}" STREQUAL "1") @@ -465,6 +473,10 @@ if(MPI_COMM_FOUND) endif() target_compile_definitions(TransferBench PRIVATE MPI_COMM_ENABLED) endif() +if(HIPFILE_FOUND) + target_link_libraries(TransferBench PRIVATE hip::hipfile) + target_compile_definitions(TransferBench PRIVATE HIPFILE_ENABLED) +endif() if(AMD_SMI_FOUND) target_include_directories(TransferBench PRIVATE ${AMD_SMI_INCLUDE_DIR}) target_link_libraries(TransferBench PRIVATE ${AMD_SMI_LIBRARY}) @@ -526,6 +538,12 @@ if(BUILD_RELOCATABLE_PACKAGE) set(CMAKE_INSTALL_RPATH "\$ORIGIN:\$ORIGIN/../lib:/opt/rocm/extras-${ROCM_MAJOR_VERSION}/lib:/opt/rocm/lib:/opt/rocm/lib/llvm/lib:/opt/rocm/core-${ROCM_MAJOR_VERSION}/lib:/opt/rocm/core-${ROCM_MAJOR_VERSION}/lib/llvm/lib") set(CMAKE_BUILD_RPATH "${CMAKE_INSTALL_RPATH}") + # The CMAKE_* variables above only initialise targets created after this point + set_target_properties(TransferBench PROPERTIES + SKIP_BUILD_RPATH FALSE + INSTALL_RPATH_USE_LINK_PATH FALSE + INSTALL_RPATH "${CMAKE_INSTALL_RPATH}" + BUILD_RPATH "${CMAKE_INSTALL_RPATH}") # Strip implicit SDK-from-build-host paths on install so the ephemeral # $HOME/rocm-sdk/install path the CI script uses does not leak into the # packaged binary's RPATH. diff --git a/Makefile b/Makefile index 755598aa..46a805fd 100644 --- a/Makefile +++ b/Makefile @@ -24,6 +24,7 @@ DEBUG ?= 0 # DISABLE_NVML: Disable NVML pod membership detection for CUDA builds (default: 0) # DISABLE_POD_COMM: Disable pod communication support (default: 0) # DISABLE_CUMEM: Disable CUDA driver API (also disables pod on CUDA) (default: 0) +# DISABLE_HIPFILE: Disable hipFile executor support (default: 0) # ROCm device libraries can live in different locations depending on packaging. # hipcc/clang needs to find the amdgcn bitcode directory at link time. @@ -142,6 +143,39 @@ ifeq ($(filter clean,$(MAKECMDGOALS)),) endif endif + HIPFILE_ENABLED = 0 + # Compile with hipFile executor support if + # 1) DISABLE_HIPFILE is not set to 1 + # 2) Building TransferBench (hipFile is not available for TransferBenchCuda) + # 3) hipfile.h is found under HIPFILE_PATH (ROCM_PATH unless specified) + DISABLE_HIPFILE ?= 0 + HIPFILE_PATH ?= $(ROCM_PATH) + ifneq ($(DISABLE_HIPFILE), 1) + ifneq ($(MAKECMDGOALS),TransferBenchCuda) + $(info Attempting to build with hipFile executor support) + ifneq ($(wildcard $(HIPFILE_PATH)/include/hipfile.h),) + COMMON_FLAGS += -DHIPFILE_ENABLED + # HIPFILE_PATH takes priority over ROCM_PATH: its header is searched first and its + # library is linked by full path (ROCM_PATH may hold a different hipFile version). + # The path goes through -Wl, as "-x hip" would otherwise have it compiled as source + ifneq ($(HIPFILE_PATH),$(ROCM_PATH)) + CXXFLAGS := -I$(HIPFILE_PATH)/include $(CXXFLAGS) + endif + HIPFILE_LIB := $(firstword $(wildcard $(HIPFILE_PATH)/lib/libhipfile.so $(HIPFILE_PATH)/lib64/libhipfile.so)) + ifneq ($(HIPFILE_LIB),) + LDFLAGS += -Wl,$(HIPFILE_LIB) + else + LDFLAGS += -L$(HIPFILE_PATH)/lib -L$(HIPFILE_PATH)/lib64 -lhipfile + endif + HIPFILE_ENABLED = 1 + $(info - Building with hipFile executor support. Can set DISABLE_HIPFILE=1 to disable) + else + $(info - hipfile.h not found at $(HIPFILE_PATH)/include. Building without hipFile executor support) + $(info - To use the hipFile executor, install the hipFile development package (e.g. amdrocm-hipfile-dev) or specify appropriate HIPFILE_PATH) + endif + endif + endif + # TransferBenchCuda: CUDA driver API (libcuda). Independent of POD, but POD on CUDA requires CUMEM. DISABLE_CUMEM ?= 0 ifeq ($(MAKECMDGOALS),TransferBenchCuda) diff --git a/README.md b/README.md index 0638164b..ab15fc1a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # TransferBench TransferBench is a utility for benchmarking simultaneous copies between user-specified -CPU and GPU memory locations using CPUs/GPU kernels/DMA engines/NIC devices. +CPU and GPU memory locations using CPUs/GPU kernels/DMA engines/NIC devices. It can also +benchmark I/O between storage (NVMe-backed files or block devices) and GPU memory using +the hipFile library. > [!NOTE] > The published documentation is available at [TransferBench](https://rocm.docs.amd.com/projects/TransferBench/en/latest/index.html) in an organized, easy-to-read format, with search and a table of contents. The documentation source files reside in the `TransferBench/docs` folder of this repository. As with all ROCm projects, the documentation is open source. For more information on contributing to the documentation, see [Contribute to ROCm documentation](https://rocm.docs.amd.com/en/latest/contribute/contributing.html). diff --git a/docs/conceptual/transferbench-data-validation.rst b/docs/conceptual/transferbench-data-validation.rst index 4d60e749..2193e613 100644 --- a/docs/conceptual/transferbench-data-validation.rst +++ b/docs/conceptual/transferbench-data-validation.rst @@ -80,13 +80,27 @@ For each transfer, the SRC memory on the rank that owns it is filled from the co ``srcReference`` buffer via ``hipMemcpy`` (host-to-device or device-to-device as appropriate). DST memory is zeroed (or memset) before transfers run. +Storage memory (``S``) has no memory pointer, so TransferBench fills and clears it through an aligned +host buffer with ``pwrite``. Because O_DIRECT is required, writes bypass the host page cache and reach +storage directly. A storage destination keeps its contents between +runs, so it is cleared before the first iteration whenever validation is enabled. A write therefore +can't validate against data that an earlier run, or an earlier test, left in the same place. + +.. note:: + + A block device that TransferBench isn't allowed to write to (``TB_STORAGE_ALLOW_BLOCK_WRITE`` isn't + set to ``1``) is never filled, and neither is a file that already holds data + (``TB_STORAGE_ALLOW_OVERWRITE`` isn't set to ``1``). A transfer that reads from one transfers its + existing contents, and its data validation is skipped with a warning. + How validation is timed ======================== The timing of validation is controlled by the ``alwaysValidate`` option. By default (``alwaysValidate = 0``), validation runs once after all timed iterations complete, -minimizing overhead during benchmarking. When ``alwaysValidate = 1``, validation is -performed after every iteration; any detected error immediately stops the run. +minimizing overhead during benchmarking. When ``alwaysValidate > 0``, validation is +performed after every iteration; any detected error immediately stops the run. Setting +``alwaysValidate`` to a negative value disables validation entirely. .. list-table:: :header-rows: 1 @@ -95,11 +109,15 @@ performed after every iteration; any detected error immediately stops the run. - When - Behavior + * - ``alwaysValidate < 0`` + - Never + - Validation is disabled entirely; ``ValidateAllTransfers`` is never called. + * - ``alwaysValidate = 0`` (default) - Once at the end of all iterations - ``ValidateAllTransfers`` called after the iteration loop. - * - ``alwaysValidate = 1`` + * - ``alwaysValidate > 0`` - After every timed iteration - ``ValidateAllTransfers`` called inside the loop; any error stops the run. @@ -112,9 +130,12 @@ For each transfer and each DST, the following steps are performed: 2. **Get the actual output:** + - **GPU destination** and ``validateOnDevice = 1``: Compare on the device using a validation kernel; no host copy is made. - **CPU destination** or ``validateDirect = 1``: Point directly at the destination memory. - - **GPU destination** and ``validateDirect = 0``: Copy destination to a host ``outputBuffer`` + - **GPU destination**, ``validateOnDevice = 0``, and ``validateDirect = 0``: Copy destination to a host ``outputBuffer`` via ``hipMemcpy``, then compare against ``outputBuffer``. + - **Storage destination**: Read the storage region into a host ``outputBuffer`` via ``pread``, + then compare against ``outputBuffer``. 3. **Comparison:** Performed using ``memcmp(output, expected, numBytes)``. On mismatch, the code finds the first differing index and returns an error with the index, expected value, and actual value. @@ -135,7 +156,7 @@ environment variables or in a configuration file. * - ``alwaysValidate`` - ``ALWAYS_VALIDATE`` - - To validate after each iteration, set to ``1``. To validate once at the end, set to ``0``. + - To validate after each iteration, set to a value greater than ``0``. To validate once at the end (default), set to ``0``. To disable validation entirely, set to a negative value. * - ``validateDirect`` - ``VALIDATE_DIRECT`` diff --git a/docs/conceptual/transferbench-timing.rst b/docs/conceptual/transferbench-timing.rst index 216fdf67..a12dedf3 100644 --- a/docs/conceptual/transferbench-timing.rst +++ b/docs/conceptual/transferbench-timing.rst @@ -46,8 +46,8 @@ The following table provides a quick summary of the three timing levels: Timing methods ============== -The timing method used for each Executor and transfer depends on the Executor type and the value of -``USE_HIP_EVENTS``. +The timing method used for each Executor and transfer depends on the Executor type and the values of +``USE_HIP_EVENTS``, ``USE_SINGLE_STREAM``, and (for the DMA Executor) ``USE_HSA_DMA``. Executor timing --------------- @@ -61,14 +61,27 @@ Executor timing * - CPU - CPU wall-clock (``std::chrono::high_resolution_clock``) - * - GFX / DMA - - For ``USE_HIP_EVENTS=1`` (default): HIP events (``hipEventElapsedTime``) + * - GFX + - For ``USE_HIP_EVENTS=1`` and ``USE_SINGLE_STREAM=1`` (both defaults): HIP events (``hipEventElapsedTime``) around the single combined kernel launch. - For ``USE_HIP_EVENTS=0``: CPU wall-clock (``std::chrono::high_resolution_clock``) + Otherwise (``USE_HIP_EVENTS=0`` or ``USE_SINGLE_STREAM=0``): CPU wall-clock (``std::chrono::high_resolution_clock``), spanning from the first transfer's kernel launch to the last transfer's completion. Executor dispatch overhead (device selection, threadpool dispatch) is excluded. + + .. note:: + + When the Executor runs only PingPongs (no copy transfers), it instead reports CPU wall-clock over the whole executor call, regardless of ``USE_HIP_EVENTS``/``USE_SINGLE_STREAM``. + + * - TDM + - Same as GFX: for ``USE_HIP_EVENTS=1`` and ``USE_SINGLE_STREAM=1``, HIP events around the combined kernel launch; otherwise, CPU wall-clock over the whole executor call. + + * - DMA / BMA + - Always CPU wall-clock (``std::chrono::high_resolution_clock``) over the whole executor call. ``USE_HIP_EVENTS`` doesn't affect Executor-level timing for these Executor types. * - NIC - CPU wall-clock (``std::chrono::high_resolution_clock``) + * - hipFile + - CPU wall-clock (``std::chrono::high_resolution_clock``) around the storage I/O calls only. See :ref:`storage-timing`. + Transfer timing --------------- @@ -81,12 +94,17 @@ Transfer timing * - CPU - CPU wall-clock (``std::chrono::high_resolution_clock``) - * - GFX - - For ``USE_HIP_EVENTS=1`` (default): GPU wall-clock timestamp (``wall_clock64()``) + * - GFX / TDM + - For ``USE_SINGLE_STREAM=1`` (default): GPU wall-clock timestamps recorded inside the kernel (``wall_clock64()`` on AMD, the ``%globaltimer`` PTX register on NVIDIA), spanning from the earliest SubExecutor start to the latest SubExecutor stop of that transfer. Independent of ``USE_HIP_EVENTS``. - For ``USE_HIP_EVENTS=0``: CPU wall-clock (``std::chrono::high_resolution_clock``) + For ``USE_SINGLE_STREAM=0`` (each transfer on its own stream): with ``USE_HIP_EVENTS=1``, HIP events (``hipEventElapsedTime``); with ``USE_HIP_EVENTS=0``, CPU wall-clock around the launch and stream synchronize. * - DMA + - For ``USE_HIP_EVENTS=1``, ``USE_HSA_DMA=0``, and no sub-index specified: HIP events (``hipEventElapsedTime``). + + Otherwise: CPU wall-clock (``std::chrono::high_resolution_clock``). + + * - BMA - For ``USE_HIP_EVENTS=1`` (default): HIP events (``hipEventElapsedTime``) For ``USE_HIP_EVENTS=0``: CPU wall-clock (``std::chrono::high_resolution_clock``) @@ -94,6 +112,21 @@ Transfer timing * - NIC - CPU wall-clock (``std::chrono::high_resolution_clock``) + * - hipFile + - CPU wall-clock (``std::chrono::high_resolution_clock``) around the storage I/O calls only. See :ref:`storage-timing`. + +.. _storage-timing: + +Storage Executor timing +----------------------- + +The hipFile Executor is always timed with the CPU wall-clock, regardless of ``USE_HIP_EVENTS``. The timed region covers only the blocking read or write calls issued by the I/O threads. The time of a transfer ends when the last of its I/O threads finishes. + +The following steps run once, before the first iteration. They are part of neither the Test time nor the overhead: + +- Opening the storage path and registering the file and the GPU buffer with hipFile. +- Filling a storage source with data, and clearing a storage destination. + Overhead ======== diff --git a/docs/conceptual/transferbench-workflow.rst b/docs/conceptual/transferbench-workflow.rst index d23a3ac3..97162e79 100644 --- a/docs/conceptual/transferbench-workflow.rst +++ b/docs/conceptual/transferbench-workflow.rst @@ -101,11 +101,11 @@ Each iteration proceeds through the following steps: 5. **Stop CPU timing:** Stops the CPU timer. -6. **Validate (optional):** If ``ALWAYS_VALIDATE`` = 1, performs a correctness check after each iteration to verify that destination memory matches the expected reference results. +6. **Validate (optional):** Performs a correctness check to verify that destination memory matches the expected reference results. ``ALWAYS_VALIDATE`` > 0 validates after every iteration, ``= 0`` (default) validates once after all iterations, and ``< 0`` disables validation entirely. .. note:: - By default, validation runs only once after all iterations complete. Setting ``ALWAYS_VALIDATE`` = 1 validates after every iteration, which can help detect transient errors that would otherwise be masked by a passing final iteration. + By default, validation runs only once after all iterations complete. Setting ``ALWAYS_VALIDATE`` to a value greater than 0 validates after every iteration, which can help detect transient errors that would otherwise be masked by a passing final iteration. Setting it to a negative value disables validation entirely. Finalize -------- diff --git a/docs/conf.py b/docs/conf.py index 899e1966..04fdb520 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -11,6 +11,10 @@ if not match: raise ValueError("VERSION not found!") version_number = match[1] + # Pad a bare major.minor version (e.g. "1.71") to major.minor.patch (e.g. "1.71.0") + # for display purposes, without touching the VERSION string in the source itself. + if version_number.count('.') == 1: + version_number += ".0" # for PDF output on Read the Docs project = "TransferBench Documentation" diff --git a/docs/how to/storage-benchmarking.rst b/docs/how to/storage-benchmarking.rst new file mode 100644 index 00000000..f00352e5 --- /dev/null +++ b/docs/how to/storage-benchmarking.rst @@ -0,0 +1,248 @@ +.. meta:: + :description: How to benchmark I/O between NVMe storage and GPU memory with TransferBench using the hipFile Executor, including setup, safety, and alignment. + :keywords: TransferBench NVMe, TransferBench storage, TransferBench hipFile, AMD Infinity Storage, GPU storage benchmark, TB_STORAGE_PATHS + +.. _storage-benchmarking: + +============================================== +Benchmarking storage I/O using TransferBench +============================================== + +TransferBench can benchmark reads from storage into GPU memory and writes from GPU memory to storage. Storage is typically a file on an NVMe-backed file system or a raw NVMe block device. This topic describes how to set up and run these tests, and what to check before you trust the results. + +Storage is modeled as a memory type, ``S``, and the I/O is performed by the hipFile Executor: + +.. list-table:: + :header-rows: 1 + + * - Executor + - Letter + - How data is moved + - Requires + + * - hipFile + - ``F`` + - ``hipFileRead`` and ``hipFileWrite`` of the hipFile library. hipFile uses direct I/O between storage and GPU memory (its fastpath) when it can, and otherwise falls back to POSIX I/O through host memory (its compatibility path). + - TransferBench built with hipFile support, and ``libhipfile.so.0`` at runtime + +The hipFile Executor isn't supported on NVIDIA hardware. + +Checking availability +===================== + +The hipFile Executor is available when TransferBench was built with hipFile support, which happens automatically when the hipFile development package is installed at build time. See :ref:`source-build`. + +Run TransferBench without arguments to see what is available: + +.. code-block:: shell + + ./TransferBench + +The version line lists ``hipFile`` among the supported features, and the topology output includes a storage section: + +.. code-block:: shell + + Storage | Path (TB_STORAGE_PATHS) + ---------+------------------------- + S0 | /mnt/nvme0/tb.dat + hipFile | Available (hipFile 0.5.0) + +An available hipFile Executor doesn't guarantee that direct I/O (hipFile's fastpath) works for a particular GPU and storage device. Direct I/O also depends on the GPU kernel driver, on PCIe peer-to-peer DMA support in the kernel, and on the storage being a local NVMe device. The ``ais-check`` tool that ships with hipFile reports these requirements. + +Selecting the storage +===================== + +Set ``TB_STORAGE_PATHS`` to a comma-separated list of paths. Storage index ``N`` in a transfer (``SN``) refers to the N-th path, starting from 0: + +.. code-block:: shell + + export TB_STORAGE_PATHS=/mnt/nvme0/tb.dat,/mnt/nvme1/tb.dat + +Each path is one of the following: + +- **A regular file.** TransferBench creates the file if needed and grows it to the size the test requires. The file isn't deleted afterwards. A file that already holds data is only read from, unless you allow it to be overwritten. See :ref:`storage-existing-files`. For direct I/O, hipFile requires the file to be on xfs or on ext4 mounted with ``data=ordered``. + + A path under ``/dev/`` that doesn't exist is rejected instead of being created, because it's most likely a mistyped device name: creating it would put a regular file in the ``devtmpfs`` file system, in host memory. Paths under ``/dev/shm/`` are the exception. + +- **A raw block device**, such as ``/dev/nvme1n1``. TransferBench never creates or resizes a block device, and by default only reads from it. See :ref:`storage-block-devices`. + +Each entry must be a distinct file or device. TransferBench rejects two entries that refer to the same one, and an empty entry ahead of a path (for example ``,/mnt/nvme1/tb.dat``), which would renumber the indices that follow it. With multiple ranks, each rank reads its own ``TB_STORAGE_PATHS``, and ranks running on the same host need distinct paths: a file is locked while a rank uses it, and a block device that is written to is opened exclusively. + +.. warning:: + + Use a file or device on the NVMe drive you want to measure. A path on another kind of storage, such as a ``tmpfs`` mount or a network file system, runs, but it measures that storage, and direct I/O isn't available there. + +Running the nvme preset +======================= + +The :ref:`nvme preset ` writes from each GPU to each storage path and then reads from each storage path into each GPU, validating the data of every transfer, using the hipFile Executor. The write and the read are separate transfers: TransferBench fills the storage with fresh source data before the read, so the read doesn't depend on what the write left behind. A block device or an existing file that TransferBench isn't allowed to write to is the exception. See :ref:`storage-existing-files` and :ref:`storage-block-devices`. + +.. code-block:: shell + + TB_STORAGE_PATHS=/mnt/nvme0/tb.dat ./TransferBench nvme 1G + +The preset prints the bandwidth and the I/O path of every transfer, and exits with a non-zero exit code if any transfer fails. + +The file is left in place, and it now holds data. To run the preset on it again, delete the file first or allow it to be overwritten: + +.. code-block:: shell + + TB_STORAGE_PATHS=/mnt/nvme0/tb.dat TB_STORAGE_ALLOW_OVERWRITE=1 ./TransferBench nvme 1G + +Running custom storage transfers +================================ + +Storage transfers can be mixed with any other transfers in a configuration file or on the command line. See :ref:`storage-transfers` for the rules. + +.. code-block:: shell + + # hipFile read from storage 0 into GPU 0 with 4 I/O threads + ./TransferBench cmdline 1G "1 4 (S0->F0->G0)" + + # hipFile write from GPU 0 to storage 0 with 8 I/O threads + ./TransferBench cmdline 1G "1 8 (G0->F0->S0)" + + # Four GPUs each reading from their own drive at the same time + ./TransferBench cmdline 1G "4 4 (S0->F0->G0) (S1->F1->G1) (S2->F2->G2) (S3->F3->G3)" + +The number of SubExecutors is the number of threads that issue blocking I/O calls for the transfer. Each thread handles a contiguous part of the data. + +Several transfers in one test can use the same storage index. Each transfer gets its own region of the file or device, so they don't overwrite each other, and the file grows to the sum of the regions. + +Set ``TB_VERBOSE=1`` to see which I/O path each hipFile Executor used: + +.. code-block:: shell + + [INFO] Executor (R0F0) storage I/O path: compat + +Checking the I/O path +===================== + +The hipFile Executor reports one of the following I/O paths: + +.. list-table:: + :header-rows: 1 + + * - I/O path + - Meaning + + * - ``fastpath`` + - Direct I/O between storage and GPU memory. + + * - ``compat`` + - hipFile's compatibility path: POSIX I/O through host memory, followed by a copy to or from the GPU. + + * - ``mixed`` + - Both paths were used during the test. + + * - ``unknown`` + - hipFile doesn't provide the statistics needed to tell: hipFile is older than 0.5.0, or its statistics are turned off with ``HIPFILE_STATS_LEVEL=0``. + +A ``compat`` result measures something very different from a ``fastpath`` result, so always check the I/O path before comparing numbers. To control which path hipFile uses, set hipFile's own environment variables. TransferBench never sets them: + +.. code-block:: shell + + # Fail instead of falling back, so that a result is guaranteed to be direct I/O + HIPFILE_ALLOW_COMPAT_MODE=false ./TransferBench cmdline 1G "1 4 (S0->F0->G0)" + + # Measure the compatibility path only + HIPFILE_FORCE_COMPAT_MODE=true ./TransferBench cmdline 1G "1 4 (S0->F0->G0)" + +hipFile reads these variables once, when it is first used, so one process uses one setting for all its hipFile transfers. See :ref:`storage-env-vars` for the list. + +.. note:: + + If hipFile attempts direct I/O on a system where it can't work, the transfer fails with an error instead of falling back. Set ``HIPFILE_FORCE_COMPAT_MODE=true`` to run on such a system, for example on WSL2 with a hipFile version that doesn't detect it. + +Alignment +========= + +Direct I/O requires the file offset, the size, and the GPU buffer offset to be multiples of 4096 bytes. TransferBench therefore divides a storage transfer between its I/O threads in multiples of 4096 bytes, regardless of ``BLOCK_BYTES``. + +A transfer size or ``BYTE_OFFSET`` that isn't a multiple of 4096 bytes is accepted with a warning, because hipFile uses its compatibility path for unaligned I/O. Expect a ``compat`` or ``mixed`` I/O path in that case. + +A single I/O call moves at most ``0x7ffff000`` bytes. TransferBench issues as many calls as needed, so a transfer or a share of an I/O thread can be larger than that. + +See :ref:`storage-timing` for what is timed. + +.. _storage-existing-files: + +Existing files +============== + +TransferBench writes to storage even for a transfer that only reads from it, because it fills the storage source with known data first. A destination is also cleared before the test, so that data validation can't pass on what an earlier run left there. To keep this from destroying data, a regular file that already holds data when TransferBench first uses it is protected in the same way as a block device: + +- The file is opened read-only and isn't grown. The test fails if the file is smaller than the test requires. + +- A transfer that writes to it, such as ``(G0->F0->S0)``, is rejected before the file is opened. + +- A transfer that reads from it, such as ``(S0->F0->G0)``, transfers the existing contents. Data validation is skipped for that transfer, and a warning is printed. + +- Set ``TB_STORAGE_ALLOW_OVERWRITE=1`` to allow TransferBench to overwrite such files. Only the value ``1`` enables this. + +A file that doesn't exist or is empty when TransferBench first uses it has nothing to lose. TransferBench creates it, and it stays writable for the rest of that run, so that later tests in the same run can reuse it. A file left behind by an earlier run holds data: delete it or set ``TB_STORAGE_ALLOW_OVERWRITE=1`` to use it again. + +.. _storage-block-devices: + +Block devices +============= + +.. warning:: + + Writing to a raw block device destroys its contents, including any file system and partition table on it. Double-check the device name before you allow it. + +TransferBench protects block devices listed in ``TB_STORAGE_PATHS`` as follows: + +- By default, block devices are opened read-only. A transfer that writes to one, such as ``(G0->F0->S0)``, is rejected before the device is opened. + +- A transfer that reads from one, such as ``(S0->F0->G0)``, transfers the existing contents of the device. Because TransferBench can't fill the device with known data, data validation is skipped for that transfer, and a warning is printed. + +- Set ``TB_STORAGE_ALLOW_BLOCK_WRITE=1`` to allow TransferBench to write to block devices. Reads are then validated too, because TransferBench fills the device region with source data first. Only the value ``1`` enables this. + +- A block device that is written to is opened exclusively. The open fails if the device, or one of its partitions, is mounted or otherwise in use, for example as swap or as part of an LVM or RAID volume. It also fails if another rank on the same host has the device open for writing. + +- A block device is never created, truncated, or resized. The test fails if the device is smaller than the test requires. + +Reading or writing a block device usually requires root privileges or membership in the ``disk`` group. + +Troubleshooting +=============== + +.. list-table:: + :header-rows: 1 + + * - Message + - Cause and action + + * - ``No storage paths are defined on rank 0`` + - ``TB_STORAGE_PATHS`` isn't set. Set it to a comma-separated list of files or block devices. + + * - ``hipFile executor is requested but is not available`` + - TransferBench was built without hipFile support. Install the hipFile development package (for example ``amdrocm-hipfile-dev10.2``) and rebuild. See :ref:`source-build`. + + * - ``error while loading shared libraries: libhipfile.so.0`` + - TransferBench was built with hipFile support and the hipFile runtime library isn't installed on this machine. Install the hipFile runtime package (for example ``amdrocm-hipfile10.2``), or add the directory that holds the library to ``LD_LIBRARY_PATH``. + + * - ``hipFile's fastpath may not be usable here`` + - hipFile attempted direct I/O and the HIP runtime rejected it. Check the system with ``ais-check``, or set ``HIPFILE_FORCE_COMPAT_MODE=true`` to use the compatibility path. + + * - ``Storage 0 (...) does not exist. Paths under /dev/ ... are not created`` + - The path is under ``/dev/`` and doesn't exist. Check the device name with ``lsblk``. + + * - ``Storage 0 (...) is a block device. Writing to it destroys its contents`` + - A transfer writes to a block device without ``TB_STORAGE_ALLOW_BLOCK_WRITE=1``. See :ref:`storage-block-devices`. + + * - ``Storage 0 (...) is an existing file that holds data. Writing to it destroys its contents`` + - A transfer writes to a file that already holds data without ``TB_STORAGE_ALLOW_OVERWRITE=1``. See :ref:`storage-existing-files`. + + * - ``Storage 1 (...) and storage 0 (...) refer to the same file`` + - Two ``TB_STORAGE_PATHS`` entries name the same file or device. Give each storage index its own. + + * - ``Storage 0 (...) is locked by another process`` + - Another TransferBench rank or run on this host is using the file. Give each rank its own path. + + * - ``TB_STORAGE_PATHS has an empty entry ahead of a path`` + - The list has an empty entry before a path, usually from an unset variable in a script. Remove it. + + * - ``Storage memory (S) can only be accessed by the hipFile (F) executor`` + - Storage memory was used with another Executor. See :ref:`storage-transfers`. diff --git a/docs/how to/use-transferbench.rst b/docs/how to/use-transferbench.rst index c34bc357..9e41eae3 100644 --- a/docs/how to/use-transferbench.rst +++ b/docs/how to/use-transferbench.rst @@ -15,11 +15,12 @@ You can control the SRC and DST memory locations by indicating the memory type f * Coarse-grained, fine-grained, and uncached global device * Managed device * Null (for an empty transfer) +* Storage (a file or a block device listed in ``TB_STORAGE_PATHS``) In addition, you can determine the size of the transfer (number of bytes to copy) for the tests. -You can also specify transfer executors. The options are CPU, kernel-based GPU, and SDMA-based GPU (DMA) executors. TransferBench also provides the option to choose the number of Sub-Executors (SE). The number of SEs specifies the number of CPU threads in the case of a CPU executor and the number of compute units (CU) for a GPU executor. -For a DMA executor, the SE argument determines the number of streams to be used. +You can also specify transfer executors. The options are CPU, kernel-based GPU, SDMA-based GPU (DMA and Batched-DMA), TDM, NIC, and storage (hipFile) executors. TransferBench also provides the option to choose the number of Sub-Executors (SE). The number of SEs specifies the number of CPU threads in the case of a CPU executor and the number of compute units (CU) for a GPU executor. +For a DMA executor, the SE argument determines the number of streams to be used. For a hipFile executor, it determines the number of I/O threads. You can specify the transfers in a configuration file or use preset configurations for transfers. @@ -36,14 +37,19 @@ Here's a copy operation from a single SRC to DST: SRC 1 -> Executor -> DST 1 SRC X DST Y -Three executors are supported by TransferBench: +Eight executors are supported by TransferBench: .. code-block:: bash Executor: SubExecutor: 1. CPU CPU thread 2. GPU GPU threadblock/Compute Unit (CU) - 3. DMA N/A (Can only be used for a single SRC to DST copy) + 3. DMA N/A (Must have single SRC, at least one DST) + 4. NIC Queue Pair + 5. Nearest NIC Queue Pair (Uses NICs closest to SRC and DST) + 6. Batched-DMA Batch item (Must have single SRC, at least one DST) + 7. TDM GPU threadblock/Compute Unit (CU) (Requires hardware support: AMD gfx1250 or NVIDIA sm_90+) + 8. hipFile I/O thread (Storage <-> GPU device memory via hipFileRead/hipFileWrite) Each line in the configuration file defines a set of transfers, also known as a test, to run in parallel. @@ -99,7 +105,7 @@ Here is the list of arguments used to specify transfers in the config file: - Number of transfers to be run in parallel * - SE - - Number of SEs to use (CPU threads or GPU threadblocks) + - Number of SEs to use (CPU threads, GPU threadblocks, NIC queue pairs, or storage I/O threads) * - srcMemL - Source memory locations (where the data is read) @@ -109,6 +115,11 @@ Here is the list of arguments used to specify transfers in the config file: | - C: CPU-executed (indexed from 0 to NUMA nodes - 1) | - G: GPU-executed (indexed from 0 to GPUs - 1) | - D: DMA-executor (indexed from 0 to GPUs - 1) + | - B: Batched-DMA-executor (indexed from 0 to GPUs - 1) + | - I#.#: NIC executor (indexed from 0 to NICs - 1) + | - N#.#: Nearest NIC executor (indexed from 0 to GPUs - 1) + | - T: TDM-executor (indexed from 0 to GPUs - 1) + | - F: hipFile-executor (indexed from 0 to GPUs - 1) * - dstMemL - Destination memory locations (where the data is written) @@ -130,9 +141,15 @@ Here is the list of arguments used to specify transfers in the config file: | - U: Uncached device memory (on GPU device, indexed from 0 to [GPUs-1]) | - M: Managed device memory (on GPU device, indexed from 0 to [GPUs-1]) | - N: Null memory (index ignored) + | - S: Storage (file or block device) (indexed from 0 to [paths in TB_STORAGE_PATHS - 1]) | | ``D`` in an executor position is the DMA executor. ``D`` in a SRC/DST position is - | non-coherent pinned host memory. + | non-coherent pinned host memory. Likewise, ``F`` in an executor position is the + | hipFile executor, and ``F`` in a SRC/DST position is fine-grain device memory. + | + | Storage memory (``S``) can only be used with the hipFile (``F``) executor, + | together with global device memory (``G``) on the GPU of the executor. + | The hipFile executor requires TransferBench to be built with hipFile support. Round brackets and arrows "->" can be included for human clarity, but will be ignored. Lines starting with # are ignored while lines starting with ## are echoed to the output. @@ -167,6 +184,10 @@ Broadcast from GPU 0 to GPU 0 and GPU 1:: 1 16 (G0->G0->G0G1) +Read from storage 0 (the first path in ``TB_STORAGE_PATHS``) into GPU 0 using hipFile with 4 I/O threads:: + + 1 4 (S0->F0->G0) + .. note:: Running TransferBench with no arguments displays usage instructions and detected topology information. @@ -201,6 +222,9 @@ Here is the list of preset configurations that can be used instead of configurat * - ``nic_rings`` - Measure performance of NICs set up in a ring across ranks + * - ``nvme`` + - GPU to storage write and storage to GPU read benchmark test using the hipFile executor + * - ``p2p`` - Peer-to-peer benchmark test diff --git a/docs/index.rst b/docs/index.rst index 598ed208..fc4a3681 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,15 +1,19 @@ .. meta:: - :description: TransferBench documentation home. TransferBench is a utility for benchmarking simultaneous memory transfers between CPUs, GPUs, and NICs. + :description: TransferBench documentation home. TransferBench is a utility for benchmarking simultaneous memory transfers between CPUs, GPUs, NICs, and storage. :keywords: TransferBench, benchmarking utility, memory transfers, GPU transfers, NIC transfers, multinode benchmark **************************** TransferBench documentation **************************** -TransferBench is a utility for benchmarking simultaneous memory transfers between user-specified devices (CPUs, GPUs, and NICs). For more information, see :ref:`what-is-transferbench` +TransferBench is a utility for benchmarking simultaneous memory transfers between user-specified devices (CPUs, GPUs, NICs, and storage). For more information, see :ref:`what-is-transferbench` The source code is hosted at ``_. +.. note:: + + TransferBench is part of the `ROCmValidationSuite (RVS) `_ and is installed with it. + .. grid:: 2 :gutter: 3 @@ -20,6 +24,7 @@ The source code is hosted at ``_. .. grid-item-card:: How to * :ref:`running-transferbench-customized` + * :ref:`storage-benchmarking` .. grid-item-card:: Conceptual diff --git a/docs/install/build_from_source.rst b/docs/install/build_from_source.rst index 02a6e850..18d2e366 100644 --- a/docs/install/build_from_source.rst +++ b/docs/install/build_from_source.rst @@ -8,6 +8,10 @@ Building TransferBench from source =================================== +.. note:: + + TransferBench is part of the `ROCmValidationSuite (RVS) `_ and is installed with it. + To build TransferBench from source, install the following required dependencies first: Required dependencies @@ -36,7 +40,7 @@ Optional dependencies Depending on your requirement, you can install these optional dependencies: -- ``libibverbs``: Required for enabling NIC Executor for RDMA transfers. +- ``libibverbs``: Required at runtime for the NIC Executor (RDMA transfers). As of v1.70.0, it's loaded dynamically via ``dlopen``, so it isn't needed to build TransferBench, and NIC support is always compiled in. - For Ubuntu/Debian: @@ -80,6 +84,28 @@ Depending on your requirement, you can install these optional dependencies: sudo yum install mpich mpich-devel +- ``hipFile``: Required to build and run the hipFile Executor, which benchmarks I/O between storage and GPU memory. See :ref:`storage-benchmarking`. + + - hipFile is an optional build-time dependency. TransferBench includes ``hipfile.h`` and links against ``libhipfile``, both of which come with the hipFile development package of ROCm. The package is named after the ROCm release, for example ``amdrocm-hipfile-dev10.2``: + + - For Ubuntu/Debian: + + .. code-block:: shell + + sudo apt install amdrocm-hipfile-dev10.2 + + - For RHEL/CentOS: + + .. code-block:: shell + + sudo yum install amdrocm-hipfile-devel10.2 + + - Both build methods look for ``hipfile.h`` under ``ROCM_PATH`` and enable the hipFile Executor when they find it. If it isn't found, TransferBench builds without the hipFile Executor: the ``F`` Executor letter and the ``S`` memory type are still accepted, and a transfer that uses the hipFile Executor stops with an error saying that TransferBench was built without hipFile support. Only ``ROCM_PATH`` is searched. If hipFile is installed somewhere else, set the ``HIPFILE_PATH`` environment variable (for CMake, ``-DHIPFILE_PATH=`` works too): its header and library then take priority over any under ``ROCM_PATH``. Use ``DISABLE_HIPFILE=1`` (Makefile) or ``-DENABLE_HIPFILE=OFF`` (CMake) to build without it. + + - A binary built with hipFile support needs ``libhipfile.so.0`` (the hipFile runtime package, for example ``amdrocm-hipfile10.2``) on every machine that runs it. Packages built with CMake depend on it. + + - The hipFile Executor isn't supported on NVIDIA hardware. + You can build TransferBench from source using two methods: :ref:`Makefile ` and :ref:`CMake `. .. _makefile: @@ -139,6 +165,11 @@ To modify the Makefile behavior, use the following environment variables: MPI installation path (for mpi.h and MPI libraries). /usr/local/openmpi + + HIPFILE_PATH + hipFile installation path (for include/hipfile.h and lib/libhipfile.so). Takes priority over ROCM_PATH. + $(ROCM_PATH) + HIPCC HIP compiler. Falls back to hipcc if not found. @@ -155,34 +186,34 @@ To modify the Makefile behavior, use the following environment variables: (auto) - HIPCONFIG - Path to hipconfig, which is used to query the HIP version (for pod communication support check). - hipconfig + Feature flags - To control enabling features that require compile-time support. By default, these are enabled under the right conditions. + DISABLE_MPI_COMM + Disables MPI communication backend support for multinode TransferBench. + 0 - Feature flags - To control enabling features that require compile-time support. By default, these are enabled under the right conditions. - DISABLE_NIC_EXEC - Disables NIC Executor support. + DISABLE_AMD_SMI + Disables AMD-SMI pod membership checks. 0 - DISABLE_DMA_BUF - Disables DMA-BUF for GPU Direct RDMA. Requires NIC Executor support. - 1 + DISABLE_NVML + Disables NVML pod membership detection for CUDA builds. + 0 - DISABLE_MPI_COMM - Disables MPI communication backend support for multinode TransferBench. + DISABLE_POD_COMM + Disables pod communication support (UALoE / MNNVL). 0 - DISABLE_AMD_SMI - Disables AMD-SMI pod membership checks. + DISABLE_CUMEM + Disables the CUDA driver API. Also disables pod communication support on CUDA. 0 - DISABLE_POD_COMM - Disables pod communication support (UALoE / MNNVL). + DISABLE_HIPFILE + Disables hipFile Executor support. By default it is enabled when hipfile.h is found under HIPFILE_PATH. 0 @@ -251,7 +282,7 @@ To modify the CMake behavior, use the following environment variables: - Paths and compilers - To customize which compiler to use or the library to link against. + Paths and compilers - To customize which compiler to use or the library to link against. ROCM_PATH ROCm installation path. /opt/rocm @@ -271,6 +302,11 @@ To modify the CMake behavior, use the following environment variables: Path to MPI installation. Takes priority over find_package(MPI). + + HIPFILE_PATH + Path to hipFile installation, from the environment or as -DHIPFILE_PATH=<path>. Takes priority over ROCM_PATH. + + Build options (ON/OFF) - Pass -DVAR=value to set BUILD_LOCAL_GPU_TARGET_ONLY @@ -278,8 +314,8 @@ To modify the CMake behavior, use the following environment variables: OFF - ENABLE_NIC_EXEC - Enables RDMA NIC Executor. + BUILD_RELOCATABLE_PACKAGE + Builds with RVS-style relocatable RPATH and amdrocm<MAJOR>-transferbench package naming. OFF @@ -287,11 +323,6 @@ To modify the CMake behavior, use the following environment variables: Enables MPI communicator as backbone for multinode TransferBench. OFF - - ENABLE_DMA_BUF - Enables DMA-BUF for GPU Direct RDMA (requires NIC). - OFF - ENABLE_AMD_SMI Enables AMD-SMI pod membership queries. @@ -299,9 +330,14 @@ To modify the CMake behavior, use the following environment variables: ENABLE_POD_COMM - Enables pod communication (HIP >= 8.0). + Enables pod communication (HIP >= 8.0.0). OFF + + ENABLE_HIPFILE + Enables the hipFile Executor. AUTO enables it when hipFile is found, ON stops with an error when it isn't, and OFF builds without it. + AUTO + Build options SINGLE_KERNEL @@ -314,21 +350,11 @@ To modify the CMake behavior, use the following environment variables: 0 - CMake cache variables + CMake cache variables GPU_TARGETS Semicolon-separated GPU architectures. Overridden if BUILD_LOCAL_GPU_TARGET_ONLY is ON gfx906;gfx908;gfx90a;gfx942;gfx950;gfx1030;gfx1100;gfx1101;gfx1102;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201;gfx1250;gfx1250-strict - - AMD_SMI_EXECUTABLE - Path to amd-smi for AMD-SMI version check. - amd-smi - - - HIPCONFIG_EXECUTABLE - Path to hipconfig for HIP version or pod check. - hipconfig - @@ -344,9 +370,11 @@ To modify the CMake behavior, use the following environment variables: git clone https://github.com/ROCm/TransferBench.git cd TransferBench mkdir build && cd build - cmake .. -DENABLE_NIC_EXEC=ON -DENABLE_MPI_COMM=ON + cmake .. -DENABLE_MPI_COMM=ON make +.. _build-troubleshooting: + Troubleshooting common build errors ==================================== diff --git a/docs/reference/environment-variables.rst b/docs/reference/environment-variables.rst index 7228e6e9..12bbd516 100644 --- a/docs/reference/environment-variables.rst +++ b/docs/reference/environment-variables.rst @@ -43,6 +43,18 @@ General options - Untimed warmup iterations per test. - ``3`` + * - ``PNP_FLAG_BUFFER`` + - Size in bytes of the PingPong flag buffer. Each flag slot is 1 byte. Must be positive. + - ``1`` + + * - ``PNP_STRIDE`` + - Stride in bytes between flag slots on successive PingPong laps; wraps within the flag buffer. Must be positive, unless the flag buffer is 1 byte (then ``0`` is also allowed). + - ``1`` + + * - ``PNP_SPIN_LIMIT`` + - Polls per PingPong wait before giving up on a stalled partner; the transfer then fails with an error naming the lap. ``0`` disables the watchdog (waits never give up, and the kernel is built without the checks). + - ``67108864`` + * - ``SHOW_BORDERS`` - Shows ASCII box-drawing characters in tables. Set to ``1`` to show, ``0`` to hide. - ``1`` @@ -69,6 +81,18 @@ General options - Controls how many transfer sizes are sampled per power-of-2 range when ``num_bytes`` is set to ``0``. For example, ``SAMPLING_FACTOR=4`` produces four evenly spaced sizes between each power of 2. - ``1`` + * - ``SHOW_PERCENTILES`` + - Comma-separated percentiles of iteration duration to report. Leave unset to skip percentile reporting. Each value must be between 1 and 99. + - — + + * - ``SWEEP_MIN_POW2`` + - When ``num_bytes`` is set to ``0``, the starting power-of-two exponent for the transfer size sweep. Unrelated to ``GFX_WORD_SIZE``. + - ``10`` + + * - ``SWEEP_MAX_POW2`` + - When ``num_bytes`` is set to ``0``, the ending power-of-two exponent for the transfer size sweep. Unrelated to ``GFX_WORD_SIZE``. + - ``29`` + .. _data-validation-var: Data and validation options @@ -88,11 +112,11 @@ Data and validation options - ``0`` * - ``BLOCK_BYTES`` - - Granularity in bytes for dividing work across sub-executors. + - Granularity in bytes for dividing work across sub-executors. Not used by the hipFile Executor, which always divides work in multiples of 4096 bytes. - ``256`` * - ``BYTE_OFFSET`` - - Initial byte offset for allocations. Must be a multiple of 4. + - Initial byte offset for allocations. Must be a multiple of 4. For storage transfers, the same offset is applied to the storage region, and a value that isn't a multiple of 4096 makes hipFile use its compatibility path. - ``0`` * - ``FILL_COMPRESS`` @@ -210,7 +234,7 @@ GFX and kernel options - ``4`` * - ``USE_HIP_EVENTS`` - - Timing method for GFX and DMA transfers. ``1`` = use HIP events, ``0`` = use CPU wall time. + - Timing method for GFX and DMA transfers. ``1`` = use HIP events, ``0`` = use CPU wall time. The CPU, NIC, and hipFile Executors always use CPU wall time. - ``1`` * - ``USE_SINGLE_STREAM`` @@ -225,6 +249,10 @@ GFX and kernel options - Preferred XCC per source-by-destination GPU pair, specified as a comma-separated list. Supported on AMD hardware only. - — + * - ``GFX_KERNEL`` + - Selects the GFX kernel. ``-1`` = auto, ``0`` = force ``GpuReduceKernel``, ``1`` = force ``GpuCopyKernel`` (might error if the transfer is ineligible for this kernel). + - ``0`` + DMA options ----------- @@ -239,6 +267,32 @@ DMA options - DMA implementation. ``1`` = use ``hsa_amd_async_copy`` for direct HSA control, ``0`` = use ``hipMemcpy`` for the standard HIP path. - ``0`` +TDM options +----------- + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``TDM_BLOCK_ORDER`` + - How blocks for TDM transfers are ordered. ``0`` = sequential, ``1`` = interleaved, ``2`` = random. + - ``0`` + + * - ``TDM_BLOCK_SIZE`` + - Threads per threadblock for TDM (async tensor) kernels. Must be a multiple of 32. + - ``256`` + + * - ``TDM_LDS_BYTES`` + - LDS bytes per workgroup for TDM kernels. ``0`` = device max. Accepts ``K``, ``M``, and ``G`` suffixes. + - ``0`` + +.. note:: + + In this release, ``TDM_BLOCK_ORDER`` is validated and reported but doesn't change TDM execution order. A fix is planned for a future release. + Variable SubExecutor options ------------------------------ @@ -283,6 +337,8 @@ The following environment variables apply only when NIC support is enabled. To e * - ``NIC_CHUNK_BYTES`` - Bytes per NIC RDMA chunk. + + Since v1.71.0, a NIC transfer is rejected during validation if any queue pair's work request (the smaller of ``NIC_CHUNK_BYTES`` and the bytes assigned to that queue pair) exceeds the IBV ``max_msg_sz`` of either NIC. Each NIC's value is shown in the ``MaxMsgSz`` column of the topology output. To fix this, reduce ``NIC_CHUNK_BYTES`` or the transfer size, or use more queue pairs. - ``1073741824`` * - ``NIC_RELAX_ORDER`` @@ -293,6 +349,18 @@ The following environment variables apply only when NIC support is enabled. To e - RoCE version. - ``2`` + * - ``NIC_CQ_POLL_BATCH`` + - Number of completion queue entries to poll per ``ibv_poll_cq`` call. + - ``4`` + + * - ``NIC_SERVICE_LEVEL`` + - InfiniBand service level (``sl``) for IB queue pairs. Must be between 0 and 15. + - ``0`` + + * - ``NIC_TRAFFIC_CLASS`` + - DSCP / traffic-class byte for the RoCE GRH. Must be between 0 and 255. + - ``0`` + HIP runtime variables (client-read) ------------------------------------- @@ -338,6 +406,12 @@ Socket-related variables * - ``TB_SINGLE_LOG`` - When set, only rank 0 produces output. Useful for multinode socket mode. + * - ``TB_MASTER_IFACE`` + - When ``TB_MASTER_ADDR`` is unset on rank 0, the optional network interface used for IPv4 address detection (for example, ``eth0``). + + * - ``TB_SEND_USLEEP`` + - Microseconds to sleep after each socket ``SendData`` call. Default: ``0``. Useful for diagnosing socket stability. + Backend variables ----------------- @@ -407,6 +481,77 @@ Backend variables * - ``TB_FORCE_SINGLE_POD`` - Forces single pod mode, skipping AMD-SMI and NVML pod queries. This assumes that all GPUs are in the same pod and skips cluster membership API calls. + * - ``TB_SHOW_ALL_NUMA`` + - Shows all CPU NUMA nodes, including those with no cores. By default, coreless nodes are hidden, which changes the reported CPU indices. + + * - ``TB_WALLCLOCK_RATE`` + - Overrides the queried GPU wallclock rate when the query returns ``0``. + +.. _storage-env-vars: + +Storage variables +----------------- + +The following variables configure storage memory (``S``) and the hipFile (``F``) Executor. See :ref:`storage-benchmarking`. + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + + * - ``TB_STORAGE_PATHS`` + - Comma-separated list of storage paths. Storage memory index ``N`` (``SN``) refers to the N-th path, starting from 0. Each path is a regular file or a raw block device. With multiple ranks, each rank reads its own value. + + Each entry must be a distinct file or device, and ranks running on the same host need distinct paths. An empty entry ahead of a path (for example ``,/mnt/nvme1/tb.dat``) is rejected, because it would renumber the indices that follow it. A trailing comma is ignored. + + Regular files are created if needed, grown to the size required by the test, and left in place afterwards. A file that already holds data when TransferBench first uses it is read-only unless ``TB_STORAGE_ALLOW_OVERWRITE=1`` is set. Block devices are never created or resized. A path under ``/dev/`` (other than ``/dev/shm/``) that doesn't exist is rejected instead of being created as a regular file. + + For example: + + .. code-block:: shell + + TB_STORAGE_PATHS=/mnt/nvme0/tb.dat,/dev/nvme1n1 # S0 is the file, S1 is the block device + + * - ``TB_STORAGE_ALLOW_BLOCK_WRITE`` + - Set to ``1`` to allow TransferBench to write to block devices listed in ``TB_STORAGE_PATHS``. **This destroys the contents of those devices**, including any file system on them. Any other value, or leaving it unset, keeps block devices read-only: transfers that write to them are rejected, and transfers that read from them transfer the existing contents without data validation. + + * - ``TB_STORAGE_ALLOW_OVERWRITE`` + - Set to ``1`` to allow TransferBench to overwrite regular files listed in ``TB_STORAGE_PATHS`` that already hold data. **This replaces the contents of those files**, including for transfers that only read from storage, because the source data is written to the file first. Any other value, or leaving it unset, keeps such files read-only: they aren't grown, transfers that write to them are rejected, and transfers that read from them transfer the existing contents without data validation. + + A file that doesn't exist or is empty when TransferBench first uses it has nothing to lose, so it is always writable for the rest of that run. A file left behind by an earlier run holds data, so set this variable (or delete the file) to reuse it. + + * - ``TB_HIPFILE_SKIP_BUF_REGISTER`` + - Set to ``1`` to skip registering the GPU buffer with hipFile (``hipFileBufRegister``) for the hipFile Executor. hipFile then looks the buffer up on every I/O. + +hipFile library variables +------------------------- + +The following variables belong to the hipFile library, not to TransferBench. TransferBench never sets them. hipFile reads them once, when the hipFile Executor is first used, so they apply to every hipFile transfer in the process. Boolean values are ``true`` or ``false``. For the full list, see the hipFile documentation. + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``HIPFILE_FORCE_COMPAT_MODE`` + - Set to ``true`` to make hipFile always use its compatibility path (POSIX I/O through host memory followed by a copy to or from the GPU) instead of direct I/O between storage and GPU memory. + - ``false`` + + * - ``HIPFILE_ALLOW_COMPAT_MODE`` + - Set to ``false`` to make hipFile fail instead of using its compatibility path when direct I/O isn't possible. Use this to make sure that a result measures direct I/O. + - ``true`` + + * - ``HIPFILE_STATS_LEVEL`` + - Set to ``0`` to turn off hipFile's statistics. TransferBench derives the I/O path of a hipFile transfer from those statistics, so the path is then reported as ``unknown``. + - ``1`` + + * - ``HIPFILE_UNSUPPORTED_FILE_SYSTEMS`` + - Set to ``true`` to let hipFile attempt direct I/O on file systems other than ext4 (``data=ordered``) and xfs. + - ``false`` + HSA runtime variables --------------------- @@ -420,3 +565,6 @@ HSA runtime variables - Enables SDMA when set to ``1``. To disable, set to ``0``. This is a HIP runtime environment variable. When SDMA is disabled, the DMA Executor falls back to using blit kernels (GFX) internally. + + * - ``HSA_ENABLE_DXG_DETECTION`` + - On WSL2 the GPU is driven through ``/dev/dxg``, where direct I/O between storage and GPU memory isn't available. hipFile 0.7.0 and later therefore use their compatibility path when ``/dev/dxg`` exists. Set to ``0`` to skip this check. TransferBench doesn't read this variable itself. With hipFile 0.5.0 or 0.6.0 (ROCm 10.1 and 10.2), set ``HIPFILE_FORCE_COMPAT_MODE=true`` on WSL2. diff --git a/docs/reference/faq.rst b/docs/reference/faq.rst index 362691d0..9bc1e1f9 100644 --- a/docs/reference/faq.rst +++ b/docs/reference/faq.rst @@ -1,6 +1,6 @@ .. meta:: :description: Frequently asked questions about TransferBench, covering common errors, warnings, and configuration issues including IOMMU, memory types, and XGMI. - :keywords: TransferBench FAQ, TransferBench errors, TransferBench warnings, IOMMU, GPU_MAX_HW_QUEUES, GFX_UNROLL, validation, XGMI, UALoE, memory types + :keywords: TransferBench FAQ, TransferBench errors, TransferBench warnings, IOMMU, GPU_MAX_HW_QUEUES, GFX_UNROLL, validation, XGMI, UALoE, memory types, cmath, numactl, cpuset .. _faq: @@ -15,6 +15,18 @@ Error and warning messages This section describes common TransferBench error and warning messages and how to resolve them. +Could not find standard C++ header 'cmath' +-------------------------------------------- + +This occurs when the standard C++ headers aren't installed. Try installing ``g++-12`` or +``g++-14`` based on the OS version. For example: + +.. code-block:: shell + + apt-get install g++-12 + +For more build troubleshooting, see :ref:`build-troubleshooting`. + Unexpected mismatch at index ----------------------------- @@ -154,6 +166,57 @@ Setting ``GPU_MAX_HW_QUEUES=8``: ``GPU_MAX_HW_QUEUES=4`` case the CPU-timed aggregate bandwidth is roughly half the GPU-timed aggregate, while in the ``GPU_MAX_HW_QUEUES=8`` case the two are much closer. +.. _cpuset-allocation-error: + +Cannot allocate memory due to process memory policy/cpuset +------------------------------------------------------------- + +For example: + +.. code-block:: text + + [ERROR] ERROR: Transfer 0: SRC 0: CPU 0 on rank 0 cannot allocate memory due to process memory policy/cpuset + +This indicates that the memory policy on the node doesn't allow CPU memory allocations on +a particular NUMA node. Check the current policy: + +.. code-block:: shell + + numactl --show + +.. code-block:: text + + policy: default + preferred node: current + physcpubind: 0 1 2 3 4 5 6 7 8 9 10 ... 255 + cpubind: 1 # <-- 0 is not listed + nodebind: 1 # <-- 0 is not listed + membind: 1 # <-- 0 is not listed + preferred: + +If the NUMA node that TransferBench is trying to allocate on isn't listed under +``cpubind``, ``nodebind``, or ``membind``, the process is restricted from allocating memory +there. + +This can also be caused by a hardware misconfiguration, or by a NUMA node having no RAM +installed. Check installed memory per node with: + +.. code-block:: shell + + numactl --hardware + +.. code-block:: text + + available: 11 nodes (0-10) + node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 ... 191 + node 0 size: 0 MB # <-- No RAM installed on NUMA node 0 + node 0 free: 0 MB + node 1 cpus: 64 65 66 67 68 69 70 71 72 73 74 ... 255 + node 1 size: 257227 MB + node 1 free: 242799 MB + +A node with ``size: 0 MB`` has no RAM installed and can't be used for allocations. + Feature questions ================== diff --git a/docs/reference/presets.rst b/docs/reference/presets.rst index 4366a390..b9730b28 100644 --- a/docs/reference/presets.rst +++ b/docs/reference/presets.rst @@ -1,6 +1,6 @@ .. meta:: - :description: Reference for TransferBench presets, including all-to-all, peer-to-peer, NIC rings, sweep, and scaling tests with supported environment variables and example outputs. - :keywords: TransferBench presets, TransferBench a2a, TransferBench p2p, TransferBench nicrings, TransferBench nicp2p, TransferBench sweep, TransferBench scaling + :description: Reference for TransferBench presets, including all-to-all, peer-to-peer, NIC rings, NVMe storage, sweep, and scaling tests with supported environment variables and example outputs. + :keywords: TransferBench presets, TransferBench a2a, TransferBench p2p, TransferBench nicrings, TransferBench nicp2p, TransferBench nvme, TransferBench sweep, TransferBench scaling .. _running-presets: @@ -10,7 +10,7 @@ TransferBench presets Presets are a predefined series of transfers that can be used instead of manually configuring the transfers. -The following table lists the presets available on TransferBench 1.67.0: +The following table lists the presets available on TransferBench 1.71.0: .. list-table:: :header-rows: 1 @@ -23,6 +23,10 @@ The following table lists the presets available on TransferBench 1.67.0: - Tests parallel transfers between all pairs of GPU devices within a single node. - ✅ + * - :ref:`All-to-all latency preset (a2a_latency) ` + - Latency between all pairs of GPU executors, run in parallel. Cross-rank pairs require pod communication support. + - ✅ + * - :ref:`All-to-all via nearest NIC preset (a2a_n) ` - Tests parallel transfers between all pairs of GPU devices using nearest NIC RDMA. - ❌ @@ -31,6 +35,34 @@ The following table lists the presets available on TransferBench 1.67.0: - Performs a parameter sweep of GFX-based all-to-all transfers across different SubExecutor counts, unroll factors, and thread block sizes. - ❌ + * - :ref:`Batched-DMA sweep preset (bmasweep) ` + - Tests and compares the batched DMA executor for multi-destination copies. + - ❌ + + * - :ref:`Empty kernel launch latency preset (empty) ` + - Measures empty GFX kernel launch latency. + - ✅ + + * - :ref:`envvars ` + - Shows the list of environment variables that can be used to modify behavior. + - ✅ + + * - :ref:`GFX sweep preset (gfxsweep) ` + - Sweeps various GFX kernel options for a given GFX transfer. + - ✅ + + * - :ref:`HBM bandwidth preset (hbm) ` + - Tests HBM bandwidth. + - ✅ + + * - :ref:`Health check preset (healthcheck) ` + - Simple bandwidth health check (AMD Instinct™ MI300X series only). + - ❌ + + * - :ref:`help ` + - Shows example usage details. + - ✅ + * - :ref:`NIC all-to-all preset (nica2a) ` - NIC-executor all-to-all with plane/group partitioning via closest memory endpoint. - ✅ @@ -43,14 +75,26 @@ The following table lists the presets available on TransferBench 1.67.0: - Tests NIC rings created across identical NIC indices across ranks. - ✅ + * - :ref:`NVMe storage preset (nvme) ` + - Tests writes from GPU memory to storage and reads from storage to GPU memory using the hipFile Executor. + - ❌ + * - :ref:`One-to-all preset (one2all) ` - Tests all subsets of parallel transfers from one GPU to the others. - ❌ + * - :ref:`One-to-all latency preset (one2all_latency) ` + - Latency from one GPU executor to all others, run in parallel. Cross-rank pairs require pod communication support. + - ✅ + * - :ref:`Peer-to-peer preset (p2p) ` - Tests unidirectional and bidirectional transfers for CPU-to-CPU, CPU-to-GPU, and GPU-to-GPU combinations. - ❌ + * - :ref:`Peer-to-peer latency preset (p2p_latency) ` + - Latency between pairs of GPU executors, run serially. Cross-rank pairs require pod communication support. + - ✅ + * - :ref:`Pod all-to-all preset (poda2a) ` - Pod-aware all-to-all across GPUs within a single pod via UALoE path, with optional concurrent NIC ring. - ✅ @@ -59,6 +103,10 @@ The following table lists the presets available on TransferBench 1.67.0: - Pod-aware peer-to-peer bandwidth between every GPU pair in a pod (unidirectional and bidirectional). - ✅ + * - :ref:`Ring latency preset (ring_latency) ` + - Each GPU executor pingpongs with its ring neighbor, with all hops run in parallel. Cross-rank pairs require pod communication support. + - ✅ + * - :ref:`Intra-pod ring preset (rings) ` - Ring transfers within subgroups of ranks in a pod. - ✅ @@ -71,10 +119,22 @@ The following table lists the presets available on TransferBench 1.67.0: - Runs scaling tests for local and remote read, write, and copy operations between two GPUs. - ❌ + * - :ref:`Smoke test preset (smoketest) ` + - Simple correctness smoke-test. + - ✅ + * - :ref:`Sweep or random sweep preset (sweep/rsweep) ` - Stress tests by running through combinations of transfers. - ❌ + * - :ref:`TDM sweep preset (tdmsweep) ` + - Sweeps Tensor Data Mover (TDM) executor options (block size, LDS, order, SubExecutors) for a given TDM transfer. + - ✅ + + * - :ref:`Wallclock consistency preset (wallclock) ` + - Tests wallclock consistency across XCCs within a GPU. + - ✅ + .. note:: You can modify a preset using environment variables, which are detailed when running the preset. @@ -442,6 +502,222 @@ Example output 24 404.03 395.28 398.00 391.28 376.55 370.55 32 393.80 403.51 395.81 382.75 350.72 366.56 +.. _bmasweep: + +Batched-DMA sweep preset (bmasweep) +===================================== + +The bmasweep preset compares the Batched-DMA (BMA) executor against the single-engine DMA executor and, optionally, the GFX executor, for simultaneous copies from one GPU to all the others. It sweeps message size and reports a bandwidth table. + +.. note:: + + Requires ROCm 7.1.0 or newer (the BMA executor is compiled in only when ``BMA_EXEC_ENABLED`` is defined) and is single-node only. + +**Key features:** + +- Builds a single Transfer whose source is GPU ``EXE_INDEX`` and whose destinations are every other GPU (plus GPU ``EXE_INDEX`` itself when ``LOCAL_COPY=1``). + +- Sweeps message size from 4 KB (2:sup:`12`) to 1 GB (2:sup:`30`) in powers of two. If a byte count is given on the command line, only that one size is run. + +- At each size, runs the DMA executor with 1 sub-executor, then the BMA executor once per value in ``NUM_SUB_EXECS``, then the GFX executor once per value in ``GFX_SUB_EXECS``. + +- Prints a table with one row per message size and one column per executor configuration. + +- **One Transfer, many destinations:** All executors move the same single multi-destination Transfer, so the comparison is like-for-like across DMA, BMA, and GFX. + +- **GFX columns are opt-in:** ``GFX_SUB_EXECS`` is empty by default, so a plain run compares only DMA against BMA. + +**Restrictions:** + +- **Single-node only:** Running with more than one rank fails with ``[ERROR] BMA sweep preset currently not supported for multi-node``. + +- **ROCm 7.1.0+ required:** Builds without ``BMA_EXEC_ENABLED`` fail with ``[ERROR] BMA executor requires ROCm 7.1 or newer``. + +- **Any failed run aborts the sweep:** Errors are printed, and the preset returns a fatal error rather than continuing to the next size. + +**Usage:** + +.. code-block:: shell + + ./TransferBench bmasweep [numBytes] + +Full power-of-two sweep using the default BMA batch-item counts: + +.. code-block:: shell + + ./TransferBench bmasweep + +Compare BMA against GFX at a single 256 MB message size, including the local copy: + +.. code-block:: shell + + LOCAL_COPY=1 GFX_SUB_EXECS=8,16 ./TransferBench bmasweep 268435456 + +Environment variables +----------------------- + +To modify the behavior of the bmasweep preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``EXE_INDEX`` + - GPU that executes the Transfer and sources the data. Must be between 0 and ``NUM_GPU_DEVICES-1``. + - ``0`` + + * - ``GFX_SUB_EXECS`` + - CU counts to also test with the GFX executor, one column each. Empty by default, so no GFX columns appear. + - (empty) + + * - ``GPU_MEM_TYPE`` + - GPU memory type: 0=global, 1=fine-grained, 2=uncached, 3=managed. See :ref:`mem-type`. + - ``0`` + + * - ``LOCAL_COPY`` + - ``1`` also copies to GPU ``EXE_INDEX`` itself, adding a local-copy destination. ``0`` excludes it. + - ``0`` + + * - ``NUM_GPU_DEVICES`` + - Number of GPUs to use as destinations. + - (detected) + + * - ``NUM_SUB_EXECS`` + - Batch-item counts to test with the BMA executor, one column each. + - ``1,2,4,8`` + +Example output +---------------- + +One row per message size: a ``DMA`` column, one ``BMA(nn)`` column per value in ``NUM_SUB_EXECS``, and one ``GFX(nn)`` column per value in ``GFX_SUB_EXECS``: + +.. code-block:: shell + + Performing simultaneous DMA Transfers from GPU 0 to other GPUs + Executing: ................... + Bytes | DMA | BMA(01) | BMA(02) | BMA(04) | BMA(08) | + 4096 | ... | ... | ... | ... | ... | + 8192 | ... | ... | ... | ... | ... | + ... + 1073741824 | ... | ... | ... | ... | ... | + Reported numbers are all GB/s, normalized for per Transfer for Transfers + +.. note:: + + A capture from real hardware has not been added yet. + +.. _empty: + +Empty kernel launch latency preset (empty) +============================================= + +The empty preset measures GPU kernel launch latency by repeatedly launching a kernel that does no work, and reporting microseconds per launch. It transfers no data. The command-line byte count is ignored. + +Each cell is measured two ways so launch overhead can be separated from measurement overhead: ``Evt`` (hipEvent-measured) and ``Cpu`` (CPU wall-clock). + +**Key features:** + +- Sweeps the cartesian product of ``BATCHSIZES`` x ``GRIDSIZES`` x ``BLOCKSIZES``, for every GPU on every rank. + +- For each cell, launches the empty kernel the requested number of times per batch before calling ``hipStreamSynchronize``, repeated for ``NUM_ITERATIONS`` timed passes. + +- Reports Min/Avg/Max for both the hipEvent and CPU wall-clock measurements, in microseconds per launch. + +- Optionally adds per-iteration columns (``SHOW_ITERATIONS``) and percentile columns (``SHOW_PERCENTILES``). + +**Restrictions:** + +- **Requires uniform ranks:** Every rank must report the same number of GPUs, otherwise the preset fails with ``[ERROR] empty preset requires all ranks to have the same number of GPUs``. Cross-rank uniformity is also enforced for the sweep parameters, so all ranks must be given the same lists. + +- **``USE_EXT_LAUNCH`` is AMD-only:** Setting it on NVIDIA fails with ``[ERROR] USE_EXT_LAUNCH is not supported on NVIDIA hardware``. + +- **No data is transferred.** Any byte count given on the command line is ignored. + +- **Batch size 0 is accepted** and measures the launch path with no kernels in the batch, which is useful as a floor for the measurement overhead itself. + +**Usage:** + +.. code-block:: shell + + ./TransferBench empty + +Sweep only a single configuration across all GPUs: + +.. code-block:: shell + + BATCHSIZES=256 GRIDSIZES=1 BLOCKSIZES=256 ./TransferBench empty + +Show every timed pass plus p50/p99 for one GPU: + +.. code-block:: shell + + NUM_GPU_DEVICES=1 SHOW_ITERATIONS=1 SHOW_PERCENTILES=50,99 ./TransferBench empty + +Environment variables +----------------------- + +To modify the behavior of the empty preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``BATCHSIZES`` + - Kernels launched per batch before ``hipStreamSynchronize``. Entries must be >= 0; the list may not be empty. + - ``0,1,16,256`` + + * - ``BLOCKSIZES`` + - Thread-block width (``blockDim.x``). Each entry must be positive and <= 1024; the list may not be empty. + - ``256`` + + * - ``GRIDSIZES`` + - Grid X dimension (threadblocks per launch). Each entry must be in ``[1, 65535]``. Set to ``,`` to sweep all. + - (GPU 0 CU count) + + * - ``NUM_GPU_DEVICES`` + - GPUs per rank to benchmark. Must be between 1 and the detected count. + - (detected) + + * - ``NUM_ITERATIONS`` + - Timed passes per cell; hipEvent and CPU times are measured separately each pass. Must be > 0. + - ``5`` + + * - ``USE_EXT_LAUNCH`` + - Use ``hipExtLaunchKernelGGL`` so hipEvents are recorded as part of the launch. Not supported on NVIDIA hardware. + - ``1`` on AMD, ``0`` on NVIDIA + +.. note:: + + The global ``NUM_WARMUPS``, ``SHOW_ITERATIONS``, ``SHOW_PERCENTILES``, and ``OUTPUT_TO_CSV`` options also affect this preset. + +Example output +---------------- + +With ``SHOW_ITERATIONS=1`` the per-pass ``Evt0..EvtN`` / ``Cpu0..CpuN`` columns appear before Min/Avg/Max; with ``SHOW_PERCENTILES`` set, ``Evtp`` / ``Cpup`` columns are inserted as well. + +.. code-block:: shell + + EmptyKernel preset: times in microseconds per kernel launch (averaged across batch size). + + Evt = hipEvent measured time + Cpu = CPU wallclock measured time + + BatS GrdS BlkS Rank GPU EvtMin EvtAvg EvtMax CpuMin CpuAvg CpuMax + 0 ... 256 0 0 ... ... ... ... ... ... + 1 ... 256 0 0 ... ... ... ... ... ... + 16 ... 256 0 0 ... ... ... ... ... ... + 256 ... 256 0 0 ... ... ... ... ... ... + +.. note:: + + A capture from real hardware has not been added yet. + .. _rings: Intra-pod ring preset (rings) @@ -1088,6 +1364,108 @@ Example output │ 31.35 │ R01:bnxt_re7 │ R01:bnxt_re7 │ 31.30 │ R01:bnxt_re2 │ R01:bnxt_re6 │ └--------------------------┴--------------┴--------------┴--------------------------┴--------------┴--------------┘ +.. _nvme: + +NVMe storage preset (nvme) +=========================== + +The nvme preset measures the bandwidth of writes from GPU memory to storage and of reads from storage to GPU memory, with data validation. It runs each transfer with the hipFile Executor. For background and setup, see :ref:`storage-benchmarking`. + +**Key features:** + +- For each GPU and each storage path, runs a write ``(G->F->S)`` followed by a read ``(S->F->G)``. + +- By default, every GPU is tested against every path in ``TB_STORAGE_PATHS``. With ``NVME_PAIRED=1``, GPU ``i`` is only tested against path ``i`` modulo the number of paths. + +- Transfers run one at a time, so the results are not affected by contention between GPUs or between storage paths. + +- Validates the data of every transfer, following ``ALWAYS_VALIDATE``. + +- Reports the bandwidth and the I/O path of each transfer. The I/O path is ``fastpath`` for direct I/O between storage and GPU memory, ``compat`` for hipFile's compatibility path through host memory, ``mixed`` if both were used, or ``unknown`` if hipFile doesn't provide the statistics to tell (hipFile older than 0.5.0, or statistics turned off with ``HIPFILE_STATS_LEVEL=0``). + +- Returns a non-zero exit code if any transfer fails, so it can be used as a pass/fail test. + +**Restrictions:** + +- Single-node only. + +- **Storage paths required:** Prints instructions and exits with an error if ``TB_STORAGE_PATHS`` isn't set. + +- **hipFile required:** Exits with an error if TransferBench was built without hipFile support. See :ref:`source-build`. + +- **Block devices are read-only by default:** For a block device, the write is skipped and the read transfers the existing contents of the device without data validation (result ``UNVALIDATED``), unless ``TB_STORAGE_ALLOW_BLOCK_WRITE=1`` is set. Setting it destroys the contents of the device. + +- **Regular files are left in place:** Files are created if needed, grown to the transfer size, and not deleted afterwards. + +- **Existing files are read-only by default:** A file that already holds data when the preset starts, including one left behind by an earlier run, is treated like a block device: the write is skipped and the read transfers the existing contents without data validation (result ``UNVALIDATED``), unless ``TB_STORAGE_ALLOW_OVERWRITE=1`` is set. Setting it replaces the contents of the file, for reads as well as writes, because the source data of a read is written to the file first. + +- Not supported on NVIDIA hardware. + +**Usage:** + +.. code-block:: shell + + TB_STORAGE_PATHS=/mnt/nvme0/tb.dat ./TransferBench nvme 1G + +To test two drives with 8 I/O threads per transfer, using only hipFile's compatibility path: + +.. code-block:: shell + + TB_STORAGE_PATHS=/mnt/nvme0/tb.dat,/mnt/nvme1/tb.dat NUM_FILE_SE=8 HIPFILE_FORCE_COMPAT_MODE=true ./TransferBench nvme 1G + +Environment variables +---------------------- + +To modify the behavior of nvme preset, use the following environment variables. The storage paths come from ``TB_STORAGE_PATHS``. See :ref:`storage-env-vars`. + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``NUM_FILE_SE`` + - I/O threads per transfer. + - ``4`` + + * - ``NUM_GPU_DEVICES`` + - Number of GPUs. This can be modified to reduce the number of GPUs to test. + - (all detected) + + * - ``NVME_MODE`` + - 1=Write only, 2=Read only, 0=both. + - ``0`` + + * - ``NVME_PAIRED`` + - To test each GPU against a single storage path (GPU index modulo the number of paths), set to ``1``. To test each GPU against every storage path, set to ``0``. + - ``0`` + +Example output +--------------- + +The following output is from a system with hipFile forced to its compatibility path. The bandwidth values aren't representative of direct I/O. + +.. code-block:: shell + + [NVMe Related] + NUM_FILE_SE = 4 : Using 4 I/O thread(s) per Transfer + NUM_GPU_DEVICES = 1 : Using 1 GPUs + NVME_MODE = 0 : Running write + read transfers + NVME_PAIRED = 0 : Each GPU uses every storage path + + Storage 0 (S0): /mnt/nvme0/tb.dat (file) + Storage 1 (S1): /mnt/nvme1/tb.dat (file) + Bytes Per Transfer 268435456 + GPU <-> storage bandwidth GB/s (hipFile 0.5.0, 4 I/O thread(s) per Transfer) + ┌--------┬---------┬--------------┬------------┬-------------┬-----------┬--------┐ + │ GPU │ Storage │ Write (GB/s) │ Write path │ Read (GB/s) │ Read path │ Result │ + ├--------┼---------┼--------------┼------------┼-------------┼-----------┼--------┤ + │ GPU 00 │ S0 │ 0.689 │ compat │ 0.778 │ compat │ PASS │ + │ GPU 00 │ S1 │ 0.677 │ compat │ 0.829 │ compat │ PASS │ + └--------┴---------┴--------------┴------------┴-------------┴-----------┴--------┘ + All 4 Transfers passed + .. _one2all: One-to-all preset (one2all) @@ -1712,7 +2090,7 @@ Example output Pod all-to-all preset (poda2a) =============================== -The poda2a preset is the pod-aware sibling of :ref:`a2a`. It creates groups within a virtual pod, then conducts all-to-all among devices within a group through the UALoE path. It expands the all-to-all matrix beyond a single node so GFX and DMA Executors can reach SRC and DST memory on remote-rank GPUs that share the pod. It supports GFX or DMA as the Executor and an optional concurrent NIC ring, and is available since v1.67. +The poda2a preset is the pod-aware sibling of :ref:`a2a`. It creates groups within a virtual pod, then conducts all-to-all among devices within a group through the UALoE path. It expands the all-to-all matrix beyond a single node so GFX and DMA Executors can reach SRC and DST memory on remote-rank GPUs that share the pod. It supports GFX or DMA as the Executor and an optional concurrent NIC ring, and is available since v1.67.0. **Key features:** @@ -2615,3 +2993,1026 @@ Example output -------------------┼--------------┼------------┼-------------------┼-------------------- Aggregate (CPU) │ 295.108 GB/s │ 12.735 ms │ 3758096384 bytes │ Overhead 0.372 ms -------------------┴--------------┴------------┴-------------------┴-------------------- + +.. _gfxsweep: + +GFX sweep preset (gfxsweep) +============================= + +The gfxsweep preset sweeps every GFX-kernel tuning option for a single user-specified Transfer, and reports the combination that produced the highest bandwidth, along with a ready-to-paste command that reproduces it. :ref:`tdmsweep ` is its direct counterpart for the TDM executor. + +The sweep covers the cartesian product of six parameters, and for each combination runs every sub-executor count in ``NUM_SUB_EXECS``: + +- **Wave order:** sets ``GFX_WAVE_ORDER``. + +- **Word size:** sets ``GFX_WORD_SIZE`` (4=dwordx4, 2=dwordx2, 1=dwordx1). + +- **Temporal mode:** sets ``GFX_TEMPORAL`` (0=none, 1=load, 2=store, 3=both). + +- **Threadblock size:** sets ``GFX_BLOCK_SIZE``. + +- **Unroll factor:** sets ``GFX_UNROLL``. + +- **Kernel selector:** sets ``GFX_KERNEL`` (-1=auto, 0=reduce, 1=copy-only). + +**Key features:** + +- Parses ``GFX_TRANSFER`` into ``NUM_TRANSFERS`` Transfer(s). Every Transfer must use the ``G`` (GFX) executor. + +- Iterates ``WAVE_ORDERS`` x ``WORDSIZES`` x ``TEMPORAL_MODES`` x ``BLOCKSIZES`` x ``UNROLLS`` x ``KERNELS``. + +- For each combination, runs every value in ``NUM_SUB_EXECS``, which form the columns of the output matrix. + +- Prints the best bandwidth per sub-executor count, then the overall best combination with each corresponding ``GFX_*`` assignment and a command line that reproduces it. + +- **Automatic timing mode** (``TIMING_MODE=-1``): a single Transfer uses GPU-wallclock timing; multiple Transfers sharing one executor use HIP-event timing; otherwise aggregate CPU timing is used. + +- **Multi-node:** The default ``GFX_TRANSFER`` is rank-qualified (``R0G0->R0G0->R0G0``), and transfer strings are printed with their rank, so remote ranks may be swept. + +**Restrictions:** + +- **Executor check:** Every parsed Transfer must use the ``G`` executor. Anything else fails with ``[ERROR] gfxsweep preset only works on Transfers that are using GFX executor``. + +- **A failed combination is fatal:** If any combination fails to run, gfxsweep prints the errors and aborts the whole sweep. This differs from :ref:`tdmsweep `, which marks a rejected combination ``N/A`` and keeps going. + +- **Empty parameter lists:** If no combination ran, the preset reports ``[WARN] No transfers executed - make sure sweep parameters lists are not empty`` and returns a fatal error. + +**Usage:** + +.. code-block:: shell + + ./TransferBench gfxsweep [numBytes] + +Sweep the default parameter space for a local GPU 0 copy: + +.. code-block:: shell + + ./TransferBench gfxsweep + +Sweep a GPU0->GPU1 copy of 256 MB over a reduced search space: + +.. code-block:: shell + + GFX_TRANSFER="G0->G0->G1" BLOCKSIZES=256,512 UNROLLS=4,8 ./TransferBench gfxsweep 268435456 + +Environment variables +----------------------- + +To modify the behavior of the gfxsweep preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``BLOCKSIZES`` + - Threadblock sizes to sweep (sets ``GFX_BLOCK_SIZE``). + - ``256,512,768,1024`` + + * - ``GFX_TRANSFER`` + - The Transfer to sweep, using :ref:`Transfer definition syntax `. Must use the ``G`` (GFX) executor. + - ``R0G0->R0G0->R0G0`` + + * - ``KERNELS`` + - Kernel selectors to sweep (sets ``GFX_KERNEL``): -1=auto, 0=reduce, 1=copy-only. + - ``0`` + + * - ``NUM_SUB_EXECS`` + - Sub-executor (CU) counts to sweep; these form the columns of the output matrix. Must not be empty. + - ``4,8,16,32,64`` + + * - ``NUM_TRANSFERS`` + - Number of Transfers described by ``GFX_TRANSFER``. + - ``1`` + + * - ``TEMPORAL_MODES`` + - Non-temporal load and store modes to sweep (sets ``GFX_TEMPORAL``): 0=none, 1=load, 2=store, 3=both. + - ``0`` + + * - ``TIMING_MODE`` + - ``-1``\=auto, ``0``\=aggregate CPU time, ``1``\=executor time (HIP event), ``2``\=transfer time (GPU wallclock). + - ``-1`` + + * - ``UNROLLS`` + - Unroll factors to sweep (sets ``GFX_UNROLL``). See :ref:`gfx-unroll`. + - ``1,2,4,8,16`` + + * - ``WAVE_ORDERS`` + - Wavefront orderings to sweep (sets ``GFX_WAVE_ORDER``). + - ``0`` + + * - ``WORDSIZES`` + - Packed data sizes to sweep (sets ``GFX_WORD_SIZE``): 4=dwordx4, 2=dwordx2, 1=dwordx1. + - ``4`` + +.. note:: + + The sweep drives the global ``GFX_WAVE_ORDER``, ``GFX_WORD_SIZE``, ``GFX_TEMPORAL``, ``GFX_BLOCK_SIZE``, ``GFX_UNROLL``, and ``GFX_KERNEL`` options on each iteration, so setting those directly has no effect when running the gfxsweep preset. Use ``WAVE_ORDERS``, ``WORDSIZES``, ``TEMPORAL_MODES``, ``BLOCKSIZES``, ``UNROLLS``, and ``KERNELS`` instead. + +Example output +---------------- + +One row per parameter combination, one column per sub-executor count, then a summary row holding the best value in each column: + +.. code-block:: shell + + WvO WSz TpM BlkS UnR KrN SE 004 SE 008 SE 016 SE 032 SE 064 + ... ... ... ... ... ... ... ... ... ... ... + WvO WSz TpM BlkS UnR KrN + ======================================================================================= + Highest bandwidth found: GB/s (GPU wallclock-timed) + WaveOrder : [GFX_WAVE_ORDER=] + WordSize : [GFX_WORD_SIZE=] + Temporal Mode: [GFX_TEMPORAL=] + BlockSize : [GFX_BLOCK_SIZE=] + Unroll : [GFX_UNROLL=] + Kernel : [GFX_KERNEL=] + NumSubExec : + Command to run best result: + GFX_WAVE_ORDER= GFX_WORD_SIZE= GFX_TEMPORAL= GFX_BLOCK_SIZE= GFX_UNROLL= GFX_KERNEL= ./TransferBench cmdline " R0G0->R0G0->R0G0" + +.. note:: + + A capture from real hardware has not been added yet. + +.. _tdmsweep: + +TDM sweep preset (tdmsweep) +============================= + +The tdmsweep preset sweeps every parameter that affects Tensor Data Mover (TDM) copy performance for a single user-specified Transfer, and reports the best-performing combination. It mirrors the structure of the :ref:`gfxsweep ` preset. + +The TDM executor (``EXE_GPU_TDM``, the ``T`` executor in a Transfer expression) stages HBM -> LDS -> HBM without touching cache. Its throughput is governed by four parameters, and this preset sweeps their full cartesian product: + +- **Threadblock size:** ``TDM_BLOCK_SIZE``, threads per block (multiple of 32). + +- **LDS staging window:** ``TDM_LDS_BYTES``, bytes per block (``0`` = device max). + +- **Threadblock order:** ``TDM_BLOCK_ORDER`` (0=sequential, 1=interleaved, 2=random). + +- **Sub-executor count:** number of threadblocks/WGPs engaged. + +**Key features:** + +- Verifies that a TDM executor exists and that TDM copies are supported on device 0. + +- Parses ``TDM_TRANSFER`` into ``NUM_TRANSFERS``. Every Transfer must use the ``T`` executor. + +- Iterates over ``BLOCK_ORDERS`` x ``BLOCKSIZES`` x ``LDS_BYTES``, and for each combination over every value in ``NUM_SUB_EXECS``. + +- Prints a matrix of bandwidths: one row per (order, block size, LDS bytes) triple and one column per sub-executor count. + +- Reports the best bandwidth per sub-executor count, the overall best combination, and a ready-to-paste command that reproduces it. + +- **Automatic timing mode** (``TIMING_MODE=-1``): a single Transfer uses GPU-wallclock timing; multiple Transfers sharing one executor use HIP-event timing; otherwise aggregate CPU timing is used. + +**Restrictions:** + +- **Requires TDM-capable hardware:** AMD gfx1250 or NVIDIA sm_90+. + +- **Hardware gate:** If no TDM executor is present, or ``IsTdmCopySupported(0)`` is false, the preset prints ``[WARN] TDM executor is not supported on this device`` and returns a fatal error. + +- **Executor check:** Every parsed Transfer must use the ``T`` executor. Anything else fails with ``[ERROR] tdmsweep preset only works on Transfers that are using the TDM executor``. + +- **Rejected combinations are skipped, not fatal:** A combination the library refuses (for example, an LDS window larger than the device maximum) prints ``N/A`` in that cell, and the sweep continues. + +- **Threadblock order sweep has no effect:** In this release, ``TDM_BLOCK_ORDER`` (and so ``BLOCK_ORDERS``) is validated but doesn't change TDM execution order, so rows that differ only by order report the same underlying ordering. A fix is planned for a future release. + +- **No successful run:** If every combination fails, the preset reports ``[WARN] No transfers executed successfully`` and returns a fatal error. + +**Usage:** + +.. code-block:: shell + + ./TransferBench tdmsweep [numBytes] + +Sweep the default parameter space for a local GPU 0 TDM copy: + +.. code-block:: shell + + ./TransferBench tdmsweep + +Sweep a GPU0->GPU1 TDM copy of 256 MB over a reduced search space: + +.. code-block:: shell + + TDM_TRANSFER="G0->T0->G1" BLOCKSIZES=256,512 LDS_BYTES=32768,0 ./TransferBench tdmsweep 268435456 + +Environment variables +----------------------- + +To modify the behavior of the tdmsweep preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``BLOCKSIZES`` + - Threadblock sizes to sweep. Each value must be a positive multiple of 32. + - ``64,128,256,512,1024`` + + * - ``BLOCK_ORDERS`` + - Threadblock orderings to sweep: 0=sequential, 1=interleaved, 2=random. Values outside 0-2 are rejected. + - ``0`` + + * - ``LDS_BYTES`` + - LDS staging window sizes (bytes per threadblock) to sweep. ``0`` means the device maximum. Must be >= 0. + - ``8192,16384,32768,65536,0`` + + * - ``NUM_SUB_EXECS`` + - Sub-executor counts to sweep; these form the columns of the output matrix. Must not be empty. + - ``2,4,8,16,32,64`` + + * - ``NUM_TRANSFERS`` + - Number of Transfers described by ``TDM_TRANSFER``. + - ``1`` + + * - ``TIMING_MODE`` + - ``-1``\=auto, ``0``\=aggregate CPU time, ``1``\=executor time (HIP event), ``2``\=transfer time (GPU wallclock). + - ``-1`` + + * - ``TDM_TRANSFER`` + - The TDM Transfer to sweep, using :ref:`Transfer definition syntax `. Must use the ``T`` (TDM) executor. + - ``G0->T0->G0`` + +.. note:: + + The sweep sets the global ``TDM_BLOCK_ORDER``, ``TDM_BLOCK_SIZE``, and ``TDM_LDS_BYTES`` options on each iteration, so setting those directly has no effect when running the tdmsweep preset. Use ``BLOCK_ORDERS``, ``BLOCKSIZES``, and ``LDS_BYTES`` instead. + +Example output +---------------- + +The sweep prints one row per (BlkO, BlkS, LDSBytes) combination and one column per sub-executor count, followed by a summary row of the best value in each column: + +.. code-block:: shell + + BlkO BlkS LDSBytes SE 002 SE 004 SE 008 SE 016 SE 032 SE 064 + ... ... ... ... ... ... ... ... ... + BlkO BlkS LDSBytes + ======================================================================================= + Highest bandwidth found: GB/s (GPU wallclock-timed) + BlockOrder : [TDM_BLOCK_ORDER=] + BlockSize : [TDM_BLOCK_SIZE=] + LDS Bytes : [TDM_LDS_BYTES=] + NumSubExec : + Command to run best result: + TDM_BLOCK_ORDER= TDM_BLOCK_SIZE= TDM_LDS_BYTES= ./TransferBench cmdline " G0->T0->G0" + +.. note:: + + A capture from real TDM-capable hardware has not been added yet. + +.. _latency-presets: + +Latency presets (p2p_latency, one2all_latency, a2a_latency, ring_latency) +============================================================================ + +The four latency presets measure GPU-to-GPU round-trip latency using PingPong operations (added in v1.71.0). In a PingPong, a PING GPU executor writes a 1-byte flag to its partner and waits for the PONG executor to write one back. The result is the GPU-timed round-trip time per lap, in microseconds. No payload data is transferred, and the command-line byte count is ignored. + +All four presets share one implementation (``src/client/Presets/Latency.hpp``). They differ only in which (PING, PONG) pairs are measured together: + +.. list-table:: + :header-rows: 1 + + * - Preset + - Pairs measured + - How they run + + * - ``p2p_latency`` + - Every ordered pair, including a GPU paired with itself. + - One pair at a time (serially), so each latency is measured with the rest of the system idle. + + * - ``one2all_latency`` + - Every ordered pair of distinct GPUs. + - One PING GPU at a time, against all PONG GPUs in parallel. + + * - ``a2a_latency`` + - Every ordered pair of distinct GPUs (plus self-pairs with ``A2A_LOCAL=1``). + - All pairs in parallel, in a single run. + + * - ``ring_latency`` + - Each GPU and the next GPU in its ring. + - Every hop of every ring in parallel, in a single run. + +**Key features:** + +- Lists GPU executors rank-major (all of rank 0's GPUs, then rank 1's, and so on), limited to ``NUM_GPU_DEVICES`` per rank. + +- Builds one PingPong per selected pair. Each one exchanges flags through the DST buffers, which are allocated in ``GPU_MEM_TYPE`` memory on the PING and PONG GPUs. Each half runs as a single threadblock. + +- Before the timer starts, the PONG half signals that it's running, so the partner kernel's launch delay isn't counted. The PING half then times ``NUM_LAPS`` round trips with in-kernel GPU timestamps, and that total is divided by the lap count. + +- Prints a PING (rows) x PONG (columns) matrix of average latency per lap, followed by the average, minimum, and maximum over all measured pairs of distinct GPUs. + +- For ``ring_latency``, the GPU list is reordered with ``STRIDE``, split into rings of ``RING_SIZE``, and each GPU pings the next one in its ring (wrapping around). Ring membership is printed above the matrix. + +**Restrictions:** + +- **GFX executors only:** PingPong is currently implemented only for GPU GFX executors. + +- **Requires uniform ranks:** Every rank must report the same number of GPUs, and all latency env vars must be the same on every rank. + +- **Cross-rank pairs need pod support:** Pairs on different ranks are measured only when TransferBench is built with pod communication and both ranks are in the same pod. Otherwise they print as ``N/A``, with the warning ``[WARN] N cross-rank pair(s) are shown as N/A: this requires pod communication support and ranks in the same pod``. + +- **Not enough GPUs:** With a single GPU, ``one2all_latency`` and ``a2a_latency`` print a warning and measure nothing (``a2a_latency`` still works with ``A2A_LOCAL=1``). ``ring_latency`` fails with ``[ERROR] ring_latency requires at least 2 GPUs``. + +- **Ring constraints:** ``RING_SIZE`` must be greater than 1 and must evenly divide the total GPU count, or the preset fails. + +- **A failed run doesn't abort the matrix:** Affected cells show ``FAIL``, the remaining pairs are still measured, and the preset exits with an error at the end. A stalled partner is detected by the ``PNP_SPIN_LIMIT`` watchdog instead of hanging. + +- **Self-pairs** (the matrix diagonal) are measured only by ``p2p_latency``, or by ``a2a_latency`` with ``A2A_LOCAL=1``. They're shown in the matrix but excluded from the average, minimum, and maximum summary. + +- **Duplicate-hostname warning:** A trailing ``[WARN]`` is emitted if two ranks share a hostname, as running multiple ranks per host can cause Executor aliasing. + +**Usage:** + +.. code-block:: shell + + ./TransferBench p2p_latency + ./TransferBench one2all_latency + ./TransferBench a2a_latency + ./TransferBench ring_latency + +More laps per iteration, with fine-grained memory for the flags: + +.. code-block:: shell + + NUM_LAPS=10000 GPU_MEM_TYPE=1 ./TransferBench a2a_latency + +Include self-pairs in all-to-all: + +.. code-block:: shell + + A2A_LOCAL=1 ./TransferBench a2a_latency + +Two rings of 4 GPUs each, built from every other GPU: + +.. code-block:: shell + + RING_SIZE=4 STRIDE=2 ./TransferBench ring_latency + +Environment variables +----------------------- + +To modify the behavior of the latency presets, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``NUM_LAPS`` + - Round trips timed per iteration; the reported latency is the total time divided by this. Must be positive. + - ``1000`` + + * - ``GPU_MEM_TYPE`` + - GPU memory type for the flag buffers: 0=default GPU, 1=fine-grained GPU, 2=uncached GPU, 3=managed. See :ref:`mem-type`. + - ``0`` + + * - ``USE_REMOTE_READ`` + - ``0`` = each executor writes to its partner's memory and polls its own (remote write / local poll). ``1`` = each executor writes to its own memory and polls its partner's (local write / remote poll). + - ``0`` + + * - ``NUM_GPU_DEVICES`` + - GPUs per rank to include. Must be between 1 and the detected count. + - (detected) + + * - ``A2A_LOCAL`` + - ``a2a_latency`` only. ``1`` = also measure pairs where PING and PONG are the same GPU (the matrix diagonal). + - ``0`` + + * - ``RING_SIZE`` + - ``ring_latency`` only. GPUs per ring; defaults to #ranks x ``NUM_GPU_DEVICES``. Must be greater than 1 and evenly divide the total GPU count. + - (all GPUs) + + * - ``STRIDE`` + - ``ring_latency`` only. Reorders the rank-major GPU list by stepping through it with this stride (same ordering as the ``rings`` preset) before it's split into rings. + - ``1`` + +.. note:: + + The global ``PNP_FLAG_BUFFER``, ``PNP_STRIDE``, and ``PNP_SPIN_LIMIT`` options control the flag buffer and the stall watchdog. ``NUM_ITERATIONS``, ``NUM_WARMUPS``, and ``OUTPUT_TO_CSV`` also apply. ``NUM_SUBITERATIONS`` is ignored (forced to ``1`` with a warning) because every transfer in these tests is a PingPong. + +Example output +---------------- + +Layout for ``a2a_latency`` on a single rank with 4 GPUs, based on the preset's output: + +.. code-block:: shell + + Pingpong round-trip latency per lap (us), all pairs run in parallel + [1000 laps] [default GPU memory flags] [remote write / local poll] + PING\PONG GPU 00 GPU 01 GPU 02 GPU 03 + GPU 00 N/A ... ... ... + GPU 01 ... N/A ... ... + GPU 02 ... ... N/A ... + GPU 03 ... ... ... N/A + + Average latency: ... us over 12 pairs + Minimum latency: ... us (PING GPU xx, PONG GPU yy) + Maximum latency: ... us (PING GPU xx, PONG GPU yy) + +- Cells are in microseconds per round trip (3 decimals). ``N/A`` means the pair wasn't measured: the diagonal, or a cross-rank pair that can't be paired. ``FAIL`` means the run containing that pair failed. + +- With multiple ranks, labels become ``R GPU `` and columns widen from 10 to 12 characters. + +- The mode text on the first line is one of: "each pair run by itself" (p2p), "each PING executor run against all PONG executors in parallel" (one2all), "all pairs run in parallel" (a2a), or "N parallel ring(s) of M[ (stride S)], each GPU pinging its neighbor" (ring). ``ring_latency`` also prints one ``Ring NN: GPU 00 -> GPU 01 -> ... -> GPU 00`` line per ring. + +- The bracket line shows the lap count, the flag memory type, and the polling mode ("remote write / local poll" or "local write / remote poll"). + +.. note:: + + A capture from real hardware has not been added yet. + +.. _wallclock: + +Wallclock consistency preset (wallclock) +=========================================== + +The wallclock preset checks whether the GPU wall-clock counter (``wall_clock64()``) is consistent across the XCCs within a GPU. TransferBench uses that counter for transfer-level GFX and TDM timing, so a skew between XCCs would distort those measurements. + +It transfers no data. Each XCC records timestamps, and the preset reports the spread between them in both cycles and microseconds. + +**Key features:** + +- Queries the GPU wall-clock rate and reports it in kHz along with the derived microseconds-per-cycle. + +- Launches a kernel per GPU that records a wall-clock timestamp from each XCC, optionally synchronizing threadblocks with a barrier first (``USE_BARRIER``). + +- Repeats for ``NUM_ITERATIONS`` and reports, per rank and GPU, the per-XCC timestamps relative to the earliest, plus an ``AVG`` row giving the average delta in cycles and microseconds. + +- Separately times a tight loop of ``NUM_TIMESTAMPS`` reads to estimate the cost of taking a timestamp. + +- Finishes with the minimum and maximum delta observed across the whole run. + +**Restrictions:** + +- **Requires uniform ranks:** Every rank must report the same number of GPUs. + +- **Uniform XCC counts required:** If any GPU reports a different XCC count from GPU 0, the preset fails (heterogeneous XCC counts aren't supported). It also fails if GPU 0 reports zero XCCs, which usually means topology data is missing. + +- **``NUM_ITERATIONS`` must be positive:** The seconds-based (negative) and infinite (``0``) modes supported elsewhere are rejected here. + +- **Multi-rank hosts are flagged:** If two ranks report the same hostname, the preset warns that TransferBench should be run with one rank per host to avoid aliasing executors. + +- **No data is transferred;** any byte count on the command line is ignored. + +**Usage:** + +.. code-block:: shell + + ./TransferBench wallclock + +Show per-iteration detail (set to ``2`` for raw, un-normalized wall-clock values): + +.. code-block:: shell + + SHOW_ITERATIONS=1 ./TransferBench wallclock + +Check a single GPU with the barrier disabled: + +.. code-block:: shell + + NUM_GPU_DEVICES=1 USE_BARRIER=0 ./TransferBench wallclock + +Environment variables +----------------------- + +To modify the behavior of the wallclock preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``NUM_GPU_DEVICES`` + - GPUs per rank to check. Must be between 1 and the detected count. + - (detected) + + * - ``NUM_TIMESTAMPS`` + - Timestamps read in a loop to estimate per-timestamp cost. Must be non-negative. + - ``10000`` + + * - ``USE_BARRIER`` + - ``1`` synchronizes threadblocks before taking the timestamp. ``0`` takes it without a barrier. + - ``1`` + + * - ``USE_BLOCKCOUNT`` + - If non-zero, launch this many threadblocks instead of the default (one per XCC). + - ``0`` + + * - ``XCC_MASK`` + - Bit mask for disabling XCCs, to restrict the check to a subset. + - ``0`` + +.. note:: + + The global ``NUM_ITERATIONS``, ``NUM_WARMUPS``, and ``SHOW_ITERATIONS`` options also apply. ``TB_WALLCLOCK_RATE`` can override the clock rate if the query returns ``0``. + +Example output +---------------- + +With ``SHOW_ITERATIONS=1`` each iteration gets its own row, with per-XCC timestamps normalized against the earliest; ``SHOW_ITERATIONS=2`` shows the raw wall-clock values instead. An XCC that produced no timestamp is shown as ``SKIP``. + +.. code-block:: shell + + Running iterations on items. Detected wall clock rate of Khz = usec per cycle + + Rank | GPU | XCC | Cycles | usec | usec/timestamp | + 0 | 0 | 0 | ... | ... | ... | + 0 | 0 | 1 | ... | ... | ... | + 0 | 0 | AVG | ... | ... | ... | + ... + + Minimum Delta detected: cycles ( usec) + Maximum Delta detected: cycles ( usec) + +.. note:: + + A capture from real hardware has not been added yet. + +.. _smoketest: + +Smoke test preset (smoketest) +=============================== + +The smoketest preset is a correctness check rather than a benchmark. It runs a fixed matrix of 16 transfer patterns at several sizes, validates every result, and reports a pass or fail result. The process exits with a fatal status if any test fails. + +Test numbering +---------------- + +Tests 1-8 use the DMA executor (or BMA when ``USE_BDMA=1``); tests 9-16 run the same eight patterns on the GFX executor. The following table maps each transfer pattern to its test number: + +.. list-table:: + :header-rows: 1 + + * - Pattern + - DMA / BMA + - GFX + + * - Host to device (H2D) + - 1 + - 9 + + * - Device to host (D2H) + - 2 + - 10 + + * - Device to device, remote write + - 3 + - 11 + + * - Device to device, remote read + - 4 + - 12 + + * - Broadcast + - 5 + - 13 + + * - Gather + - 6 + - 14 + + * - All-to-all, remote write + - 7 + - 15 + + * - All-to-all, remote read + - 8 + - 16 + +**Restrictions:** + +- **Failure details go to a log file.** As of v1.70.0, when any test fails the preset writes per-failure detail (including the transfer string and any fatal error message) to ``/tmp/transferbench_smoketest_.log`` and names that path in the warning. If the log can't be written, it says so instead. + +- **Single pod only:** Running across more than one pod fails with ``[ERROR] smoketest preset can only be run within a single pod``. Pod membership can be forced with ``TB_FORCE_SINGLE_POD=1``. + +- **Uniform sub-executor counts required:** Every GPU on every rank must report the same number of sub-executors. + +- **Collective tests are off by default on multi-node.** Broadcast, gather, and all-to-all are skipped unless ``TEST_LIST`` enables them explicitly, and the preset warns when it does this. + +- **Cross-pod ranks skip patterns that need peer access:** D2D copy, broadcast, gather, and all-to-all are skipped when ranks aren't in the same pod. + +- **Exit status is meaningful:** The preset returns a fatal error if any test failed, so it can gate CI. + +- **Multi-rank hosts are flagged** with a recommendation to run one rank per host. + +**Usage:** + +.. code-block:: shell + + ./TransferBench smoketest [numBytes] + +Run the whole matrix at the default sizes: + +.. code-block:: shell + + ./TransferBench smoketest + +Run only the GFX device-to-device tests at one size: + +.. code-block:: shell + + TEST_LIST=11,12 SIZE_LIST=16M ./TransferBench smoketest + +Environment variables +----------------------- + +To modify the behavior of the smoketest preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``ALWAYS_VALIDATE`` + - Defaulted to ``1`` by this preset so every iteration is validated. A negative value disables validation, which defeats the point of the preset. + - ``1`` + + * - ``CPU_MEM_TYPE`` + - CPU memory type used for host-side buffers. See :ref:`mem-type`. + - ``0`` + + * - ``GFX_SE_LIST`` + - Sub-executor counts to test on the GFX executor. + - ``1,(GPU 0 CU count)`` + + * - ``GPU_MEM_TYPE`` + - GPU memory type: 0=global, 1=fine-grained, 2=uncached, 3=managed. See :ref:`mem-type`. + - ``0`` + + * - ``NUM_ITERATIONS`` + - Timed iterations per test (lowered from the global default). + - ``2`` + + * - ``NUM_WARMUPS`` + - Warmup iterations (lowered from the global default). + - ``0`` + + * - ``RUN_PARALLEL`` + - ``1`` exercises GPUs in parallel, ``0`` runs them serially. + - ``1`` + + * - ``SE_MAX_BYTES`` + - Maximum bytes a single sub-executor may work on. Accepts K/M/G suffixes. + - ``128M`` + + * - ``SIZE_LIST`` + - Transfer sizes to test. Overridden when a byte count is given on the command line. + - ``1K,16M,256M`` + + * - ``TEST_LIST`` + - Which test numbers to run, as a range list (for example, ``1-8``, ``11,12``). Empty means all supported tests. Also accepts ``dma``, ``gfx``, or ``fast`` as shortcuts. + - (all) + + * - ``USE_BDMA`` + - ``1`` runs tests 1-8 on the Batched-DMA executor instead of DMA. Requires a build with ``BMA_EXEC_ENABLED``. + - ``0`` + +Example output +---------------- + +Each test prints a pass, fail, or skip marker per size as it runs, then a summary: + +.. code-block:: shell + + ... per-test PASS / FAIL / SKIP markers ... + + All tests passed + + -- or -- + + [WARN] Tests FAILED — details written to /tmp/transferbench_smoketest_.log + +.. note:: + + A capture from real hardware has not been added yet. + +.. _healthcheck: + +Health check preset (healthcheck) +==================================== + +The healthcheck preset runs a fixed set of bandwidth tests against hard-coded pass-or-fail thresholds for a known hardware configuration, to flag a machine that's underperforming. Unlike the other presets, it reports PASS or FAIL rather than raw numbers, and exits with a fatal status if anything failed. + +.. note:: + + This is an experimental feature. The preset prints its own disclaimer at startup: a failure doesn't necessarily indicate a hardware fault, since a simultaneous workload on the machine can influence results. + +Hardware support +------------------ + +The preset detects the model by GPU count, architecture, and sub-executor count, and exits if the configuration isn't one it has thresholds for. The following table lists the currently recognized configurations: + +.. list-table:: + :header-rows: 1 + + * - GPUs + - Architecture + - Sub-executors per GPU + + * - 8 + - ``gfx942`` (MI300X series) + - 304 + + * - 8 + - ``gfx942`` (MI300X series) + - 64 + +All GPUs must be identical: mixed architectures or mixed sub-executor counts are rejected with ``[WARN] healthcheck preset is currently only supported when all GPUs are identical``, along with the two differing values detected. A uniform but otherwise unrecognized configuration prints ``[WARN] healthcheck preset is currently not supported on this hardware`` along with what it detected, and stops. + +**Key features:** + +Four groups of tests run in sequence, each compared against the model's threshold: + +- **HBM performance:** Several kernel configurations, each with its own block size, unroll factor, and temporal mode, run at 1000 iterations with 50 warmups. + +- **Unidirectional copies:** Host to device, and device to host, each GPU paired with its closest CPU NUMA node. + +- **Bidirectional host<->device copies.** + +- **All-to-all XGMI copies** between every GPU pair. + +**Restrictions:** + +- **Single-node only:** Running with more than one rank fails with ``[ERROR] Healthcheck preset currently not supported for multi-node``. + +- **AMD only:** On NVIDIA builds, it prints ``[WARN] healthcheck preset not supported on NVIDIA hardware`` and returns without testing. + +- **Unsupported hardware stops the run** rather than falling back to a generic check, because the thresholds are specific to the detected model. + +- **Thresholds are built in,** not configurable via environment variables. + +- **Exit status is meaningful:** A fatal error is returned if any test failed, so it can gate automated fleet checks. + +- **Needs CPU NUMA topology:** If the closest NUMA node to a GPU can't be determined, the affected copy test reports an error. + +**Usage:** + +.. code-block:: shell + + ./TransferBench healthcheck + +Show the measured value and threshold for every GPU rather than just a progress dot: + +.. code-block:: shell + + VERBOSE=1 ./TransferBench healthcheck + +Environment variables +----------------------- + +This preset sets its own iteration counts and kernel parameters, so the usual global tuning variables don't apply. + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``VERBOSE`` + - ``1`` prints the measured value and limit for every GPU (and GPU pair) as each test runs, instead of a single progress line. Also prints the block size, unroll factor, and temporal mode used by each HBM test. + - ``0`` + +Example output +---------------- + +.. code-block:: shell + + Disclaimer: + ================================================================== + NOTE: This is an experimental feature and may be subject to change + Failures do not necessarily indicate hardware issues, as other factors + such as simultaneous workloads may influence results + + Testing HBM performance [] ........ PASS + Testing unidirectional host to device copy ....... PASS + Testing unidirectional device to host copy ....... PASS + Testing bidirectional host<->device copies ....... PASS + Testing all-to-all XGMI copies ........ FAIL ( test(s)) + GPU 00 to GPU 01: GB/s Criteria: GB/s + +.. note:: + + A capture from real hardware has not been added yet. + +.. _hbm: + +HBM bandwidth preset (hbm) +============================ + +The hbm preset measures local HBM bandwidth on each GPU. Rather than reporting a single number for one kernel configuration, it sweeps threadblock size, unroll factor, element size, sub-executor count, and temporal mode, and reports the best result each GPU achieved. + +It uses its own kernels and doesn't move data between devices, so it measures what a GPU can sustain against its own memory. + +**Key features:** + +- Sweeps ``NUM_SUB_EXECS`` x ``BLOCKSIZES`` x ``UNROLLS`` x ``ELEM_BYTES`` x temporal modes (per ``TEMPORAL_MASK``) on every selected GPU. + +- Rotates through ``NUM_BUFFERS`` buffers, one per iteration, so results aren't served from cache. + +- Prewarms for ``PREWARM_MSEC`` before timing, then times ``NUM_ITERATIONS`` iterations. + +- Picks the best configuration per GPU according to ``CRITERIA`` (max, average, or min bandwidth). + +- Prints one row per GPU with Max/Avg/Min bandwidth, optionally including the winning configuration. + +**Restrictions:** + +- **Every rank must have at least one GPU:** A rank with none is a fatal error (``[ERROR] Each rank must have at least GPU. Rank %d has no GPUs``). + +- **Cross-rank uniformity is enforced** for every sweep parameter except ``GPU_INDICES``, which may legitimately differ per rank. + +- **``SHOW_DETAILS`` is silently disabled on multi-rank runs**, since the per-sweep output would interleave across ranks. + +- **Non-temporal reads are unavailable on NVIDIA:** ``TEMPORAL_MASK`` is forced to ``1`` there regardless of what's set. + +- **Results are gathered across ranks** and printed as one table, so a multi-node run gives a single view of every GPU in the job. + +**Usage:** + +.. code-block:: shell + + ./TransferBench hbm + +Show which configuration won on each GPU: + +.. code-block:: shell + + SHOW_EXTRA=1 ./TransferBench hbm + +Test two GPUs with a narrow sweep and temporal reads only: + +.. code-block:: shell + + GPU_INDICES=0,1 BLOCKSIZES=256 UNROLLS=8 TEMPORAL_MASK=1 ./TransferBench hbm + +Environment variables +----------------------- + +To modify the behavior of the hbm preset, use the following environment variables: + +.. list-table:: + :header-rows: 1 + + * - Environment variable + - Description + - Default value + + * - ``BLOCKSIZES`` + - Threadblock sizes to sweep. Must be positive multiples of 128, up to 1024; may not be empty. + - ``256,512`` + + * - ``CRITERIA`` + - Which bandwidth decides the best configuration: 0=MAX, 1=AVG, 2=MIN. + - ``0`` + + * - ``ELEM_BYTES`` + - Element sizes in bytes to sweep. May contain only 4, 8, or 16; may not be empty. + - ``16,8`` + + * - ``GPU_INDICES`` + - GPU indices to test. Empty means every GPU on the rank. May differ per rank. + - (all) + + * - ``MEM_TYPE`` + - GPU memory type: 0=global, 1=fine-grained, 2=uncached, 3=managed. See :ref:`mem-type`. + - ``0`` + + * - ``NUM_BUFFERS`` + - Buffers rotated through, one per iteration, to defeat caching. Must be positive. A value above ``NUM_ITERATIONS`` warns that some buffers go unused. + - ``2`` + + * - ``NUM_ITERATIONS`` + - Timed iterations. Must be positive. + - ``100`` + + * - ``NUM_SUB_EXECS`` + - Sub-executor counts to sweep. Each must be positive and no greater than the available CU count. + - (all available) + + * - ``PREWARM_MSEC`` + - Prewarm duration in milliseconds before timing starts. Must be non-negative. + - ``50`` + + * - ``SHOW_DETAILS`` + - Show sweep details; ``2`` adds per-iteration output. Ignored on multi-rank runs. + - ``0`` + + * - ``SHOW_EXTRA`` + - ``1`` appends the winning ``#SE``, ``Blocksize``, ``Unroll``, and ``EBytes`` columns to the result table. + - ``0`` + + * - ``TEMPORAL_MASK`` + - Which load modes to sweep: 1=temporal, 2=non-temporal, 3=both. Forced to ``1`` on NVIDIA, which has no non-temporal reads. + - ``3`` + + * - ``UNROLLS`` + - Unroll factors to sweep. May contain only 1, 2, 4, 8, or 16. + - ``16,8,4`` + + * - ``USE_WALLCLOCK`` + - ``1`` times with the GPU wall-clock, ``0`` uses events. + - ``1`` + + * - ``OUTPUT_TO_CSV`` + - CSV formatting for the result table. + - ``0`` + + * - ``SHOW_BORDERS`` + - Draw borders on the result table. + - ``1`` + +Example output +---------------- + +.. code-block:: shell + + Rank | GPU | MaxBw (GB/s) | AvgBw (GB/s) | MinBw (GB/s) | + 0 | 0 | ... | ... | ... | + 0 | 1 | ... | ... | ... | + ... + +With ``SHOW_EXTRA=1`` the winning configuration is appended: + +.. code-block:: shell + + Rank | GPU | MaxBw (GB/s) | AvgBw (GB/s) | MinBw (GB/s) | #SE | Blocksize | Unroll | EBytes | + +.. note:: + + A capture from real hardware has not been added yet. + +.. _help-envvars: + +Utility presets (help, envvars) +================================== + +The help and envvars presets are reference commands rather than benchmarks. Each prints static documentation and exits. No transfers are run, no device is touched, and any byte count on the command line is ignored. + +Both are useful as the authoritative, version-matched answer to "what syntax does this build accept?" and "what environment variables does this build support?" They're generated from the binary you're actually running, so they can't drift from it the way external documentation can. + +**Restrictions:** + +- **No transfers are run** and no results are produced; both return success immediately after printing. + +- **Only the output rank prints.** Under multi-node, both commands check ``RankDoesOutput()`` first, so the reference text appears once rather than once per rank. + +- **No environment variables of their own.** Neither preset reads any configuration. + +.. _help: + +help +------ + +The help preset prints the configuration-file format reference: + +- The ``SRC -> Executor -> DST`` Transfer model. + +- The six executor types and what each one uses as a sub-executor (CPU, GPU/GFX, DMA, NIC, Batched-DMA, TDM). + +- Every executor character code (``C G D B T I N``) and the memory-location codes the output lists (``C P B D K H G F U N``), with how each is indexed. + +- Basic and advanced Test syntax, including how to specify bytes per Transfer and sub-executor counts per Transfer. + +- Worked examples, from a single GPU-executed copy through memsets, read-only Transfers, and broadcasts. + +**Usage:** + +.. code-block:: shell + + ./TransferBench help + +Because the output is a valid, commented config file, it can be redirected straight into one as a starting point: + +.. code-block:: shell + + ./TransferBench help > example.cfg + +.. _envvars: + +envvars +--------- + +The envvars preset prints every environment variable this build understands, grouped by area, with a one-line description of each. This is the output of ``EnvVars::DisplayEnvVarsList()``, the same list the client uses internally, so it always matches the binary. + +For the documented reference with defaults and fuller descriptions, see :ref:`environment-variables`. If the two ever disagree, the command output is correct for your build. + +**Usage:** + +.. code-block:: shell + + ./TransferBench envvars diff --git a/docs/reference/transfer-definition-syntax.rst b/docs/reference/transfer-definition-syntax.rst index ebc1ce57..4bf2a622 100644 --- a/docs/reference/transfer-definition-syntax.rst +++ b/docs/reference/transfer-definition-syntax.rst @@ -1,6 +1,6 @@ .. meta:: - :description: Reference for TransferBench transfer definition syntax, including simple and advanced modes, memory and Executor letter codes, and wildcard syntax. - :keywords: TransferBench transfer definition, TransferBench syntax, TransferBench memory types, TransferBench Executor types, TransferBench wildcards + :description: Reference for TransferBench transfer definition syntax, including simple and advanced modes, memory and Executor letter codes, storage transfers, and wildcard syntax. + :keywords: TransferBench transfer definition, TransferBench syntax, TransferBench memory types, TransferBench Executor types, TransferBench wildcards, TransferBench storage, hipFile .. _transfer-definition-syntax: @@ -10,7 +10,9 @@ Transfer definition syntax A transfer is a single operation where an Executor reads and adds values from source (SRC) memory, then writes the sum to destination (DST) memory. When a transfer has a single SRC and a single DST, it is a copy operation. -TransferBench supports two modes for defining transfers: simple mode and advanced mode. +TransferBench supports two modes for defining transfers: :ref:`simple mode ` and :ref:`advanced mode `. Within either mode, a transfer entry can also be written as a :ref:`PingPong ` to measure round-trip latency instead of bandwidth. + +.. _simple-mode: Simple mode =========== @@ -24,7 +26,7 @@ Use simple mode when all transfers in a test share the same number of SubExecuto The format uses the following fields: - ``#Transfers``: A positive integer that specifies the number of parallel transfers. -- ``#SEs``: The number of SubExecutors (CUs, threads, or queue pairs) used by all transfers. +- ``#SEs``: The number of SubExecutors (CUs, threads, queue pairs, or storage I/O threads) used by all transfers. - ``(srcMem Executor dstMem)``: A triplet that describes one transfer. The transfer size comes from the ``num_bytes`` command-line argument. @@ -37,6 +39,8 @@ The following examples show valid simple mode definitions: 2 4 (G0 G0 G1) (G1 G1 G0) # Two parallel transfers: GPU 0 to GPU 1 and GPU 1 to GPU 0 1 4 (G0->G0->G0G1G2G3) # Reads GPU 0 then writes to GPU 0, GPU 1, GPU 2, and GPU 3 +.. _advanced-mode: + Advanced mode ============= @@ -58,6 +62,42 @@ The following example runs two transfers with different sizes and SubExecutor co -2 (G0 G0 G1 4 1M) (G1 G1 G0 2 2M) # 1 MB GPU 0 to GPU 1 with 4 CUs; 2 MB GPU 1 to GPU 0 with 2 CUs +.. _pingpong-transfers: + +PingPong (latency) transfers +============================= + +Instead of a plain triplet or quintuplet, any transfer entry in :ref:`simple ` or :ref:`advanced ` mode can be written as a PingPong. A PingPong joins a Ping triplet and a Pong triplet with ``+`` and an optional lap count. On each lap, the Ping executor writes a 1-byte flag to its DST and waits for the Pong executor to write one back to the Pong DST. The result is the GPU-timed round-trip latency per lap: + +.. code-block:: shell + + (pingSrc PingExecutor pingDst)+N(pongSrc PongExecutor pongDst) + +- ``N``: Number of laps (positive integer). A bare ``+`` means 1 lap. +- ``DST``: Required for both halves. Each half writes its flag to its own DST, and the partner polls it. +- ``SRC``: Optional (``N`` for none). If given, the flag value written on each lap is first read from SRC, which adds a real memory read to every lap. +- Each SRC and DST must be a single memory device. Wildcards are allowed: every expansion of the Ping half is paired with every expansion of the Pong half. + +A PingPong counts as one transfer toward ``#Transfers``. It can be mixed with regular transfers in the same test, though doing so means aggregate CPU results are omitted for that test. It doesn't count toward executor bandwidth, and its bytes aren't reported. An executor that runs only PingPongs shows ``pingpong`` in place of a bandwidth sum. + +Each half runs as a single threadblock, so ``#SEs``/``#CU`` doesn't apply: + +- In simple mode, any ``#SEs`` value is silently discarded for PingPong transfers. +- In advanced mode, a PingPong must not include ``#SEs`` or ``Bytes``. Doing so is rejected with ``Pingpong %d must not specify #CU / #Bytes, use (SRC EXE DST)+N(SRC EXE DST)``. + +Currently supported on GFX executors (``G``) only. Ping and Pong might run on different ranks in the same pod (requires pod communication support); cross-rank flags must be in GPU memory. + +``NUM_SUBITERATIONS`` is ignored (forced to ``1``, with a warning) when every transfer in a test is a PingPong. The flag buffer and stall watchdog are controlled by ``PNP_FLAG_BUFFER``, ``PNP_STRIDE``, and ``PNP_SPIN_LIMIT``. + +The following examples show valid PingPong definitions: + +.. code-block:: shell + + 1 1 (N->G0->F1)+1000(N->G1->F0) # 1000 laps: GPU 0 writes a flag to GPU 1, GPU 1 answers into GPU 0 + -2 (G0 G0 G1 4 1M) (N G0 G0)+500(N G1 G1) # Advanced mode: a 1 MB copy running alongside a 500-lap PingPong + +In the results table, a PingPong is reported as a ``PingPong `` row showing latency per lap (in microseconds), total time across all laps (in milliseconds), the lap count, and ``pingSrc->PingExe->pingDst <+> pongSrc->PongExe->pongDst``. With ``SHOW_ITERATIONS=1``, per-iteration latency and a standard deviation follow. For ready-made latency matrices, see the :ref:`latency presets `. + Memory and Executor letter codes ================================ @@ -79,7 +119,7 @@ The following table lists the supported memory type letters: * - ``C`` - Coarse-grained pinned host - - NUMA node (0 to #NUMA - 1) + - CPU NUMA node, logical index (0 to #exposed - 1) * - ``P`` - Pinned host (closest to GPU) @@ -121,6 +161,10 @@ The following table lists the supported memory type letters: - Null (empty). Use this to denote read-only or write-only transfers. - Index ignored. + * - ``S`` + - Storage (a regular file or a raw block device). See :ref:`storage-transfers`. + - Position in the ``TB_STORAGE_PATHS`` list (0 to #paths - 1) + You can concatenate multiple memory locations for broadcast or reduce operations. For example, ``G0G1`` refers to GPU 0 and GPU 1. Executor letters @@ -141,7 +185,7 @@ The following table lists the supported Executor type letters: * - ``C`` - CPU - CPU thread - - NUMA node (0 to #NUMA - 1) + - CPU NUMA node, logical index (0 to #exposed - 1) * - ``G`` - GPU (GFX/kernel) @@ -163,12 +207,76 @@ The following table lists the supported Executor type letters: - Queue pair - GPU. Uses the closest NIC for SRC and DST. SubIndex is optional. + * - ``B`` + - Batched DMA + - Batch item + - GPU (0 to #GPUs - 1). Requires a single SRC and at least one DST. + + * - ``T`` + - TDM + - Threadblock/CU + - GPU (0 to #GPUs - 1). Requires AMD gfx1250 or NVIDIA sm_90+. + + * - ``F`` + - hipFile (``hipFileRead``/``hipFileWrite``) + - I/O thread + - GPU (0 to #GPUs - 1). See :ref:`storage-transfers`. + +.. note:: + + The memory and Executor letters are independent. ``F`` in a memory position is fine-grained device memory, while ``F`` in the Executor position is the hipFile Executor. Likewise, ``D`` and ``B`` are host memory types in a memory position and the DMA and Batched DMA Executors in the Executor position. + The optional Executor fields have the following meanings: - ``Slot`` (``A``, ``B``, ...): Selects which closest NIC to use, where ``A`` is the first and ``B`` is the second, and so on. Used for ``EXE_NIC_NEAREST``. - ``SubIndex`` (after ``.``): Specifies the queue pair or sub-index for the NIC. - ``SubSlot``: Specifies the alpha range for sub-slot selection. +.. note:: + + CPU indices are logical. Since v1.70.0, TransferBench hides CPU NUMA nodes that have no cores, so ``C0``, ``C1``, and so on number only the exposed nodes and might not match the physical node IDs reported by ``numactl --hardware``. Set ``TB_SHOW_ALL_NUMA=1`` to expose every configured node and restore the original numbering. + +.. _storage-transfers: + +Storage transfers +================= + +Storage memory (``S``) together with the hipFile (``F``) Executor benchmarks I/O between storage, such as an NVMe drive, and GPU memory: + +.. code-block:: shell + + 1 4 (S0->F0->G0) # hipFile reads storage 0 into GPU 0 memory using 4 I/O threads + 1 4 (G0->F0->S0) # hipFile writes GPU 0 memory to storage 0 using 4 I/O threads + 1 4 (S1->F0->G0) # hipFile reads storage 1 into GPU 0 memory using 4 I/O threads + +Storage index ``N`` refers to the N-th path (starting from 0) in the comma-separated ``TB_STORAGE_PATHS`` environment variable. Each path is either a regular file, typically on an NVMe-backed file system, or a raw block device such as ``/dev/nvme1n1``. A regular file is created if it doesn't exist, except under ``/dev/`` (other than ``/dev/shm/``), where a missing path is rejected as a probable mistyped device name. With multiple ranks, each rank uses its own ``TB_STORAGE_PATHS``. + +The following rules apply: + +- Storage memory can only be used with the ``F`` Executor, and this Executor can't be used without storage memory. +- A storage transfer has exactly one SRC and one DST. One of them is storage memory (``S``) and the other is global device memory (``G``) on the GPU that the Executor is indexed by. For example, ``(S0->F1->G1)`` is valid, while ``(S0->F0->G1)``, ``(S0->F0->C0)``, ``(S0->F0->S1)``, and ``(S0->G0->G0)`` are rejected. +- The storage, the Executor, and the GPU memory must be on the same rank. +- The number of SubExecutors is the number of threads that issue blocking I/O calls. The data is divided between them in multiples of 4096 bytes; ``BLOCK_BYTES`` isn't used. +- The transfer size and ``BYTE_OFFSET`` should be multiples of 4096 bytes. Other values are accepted with a warning, because hipFile then uses its compatibility path. +- A block device is written to only when ``TB_STORAGE_ALLOW_BLOCK_WRITE=1`` is set. Without it, a transfer with a block device as DST is rejected, and a transfer with a block device as SRC transfers the existing contents of the device without data validation. +- The same applies to a regular file that already holds data, with ``TB_STORAGE_ALLOW_OVERWRITE=1``. A file that TransferBench creates, or finds empty, is always writable for the rest of the run. +- Executor subindices and PingPong operations aren't supported. +- The ``F`` Executor requires TransferBench to be built with hipFile support. Without it, the transfer is still parsed and is then rejected with an error that says so. This includes transfers that a ``*`` wildcard for the Executor index expands to. See :ref:`source-build`. +- The ``F`` Executor isn't supported on NVIDIA hardware. + +Numeric wildcards work for the storage index, the Executor index, and the GPU memory index. Because the GPU memory must be on the GPU of the Executor, these two wildcards follow each other instead of expanding to every combination: + +.. code-block:: shell + + 1 4 (S0->F*->G*) # One transfer per GPU: (S0->F0->G0), (S0->F1->G1), ... + 1 4 (S*->F*->G*) # One transfer per storage path and GPU + 1 4 (S0->F1->G*) # (S0->F1->G1) only + 1 4 (G*->F*->S0) # One write per GPU + +This applies to the ``*`` wildcard only. An explicit list such as ``(S0->F[0,1]->G[0,1])`` still expands to every combination, and the transfers whose GPU memory isn't on the GPU of the Executor are rejected. + +For setup instructions and what to check before trusting the results, see :ref:`storage-benchmarking`. + Wildcards ========= diff --git a/docs/sphinx/_toc.yml.in b/docs/sphinx/_toc.yml.in index 95a9470a..d1d9e66f 100644 --- a/docs/sphinx/_toc.yml.in +++ b/docs/sphinx/_toc.yml.in @@ -12,6 +12,7 @@ subtrees: - caption: How to entries: - file: how to/running-transferbench-customized.rst + - file: how to/storage-benchmarking.rst - caption: Conceptual entries: diff --git a/docs/what-is-transferbench.rst b/docs/what-is-transferbench.rst index 84f6f3df..614597f1 100644 --- a/docs/what-is-transferbench.rst +++ b/docs/what-is-transferbench.rst @@ -1,6 +1,6 @@ .. meta:: - :description: Overview of TransferBench, a utility for benchmarking simultaneous memory transfers between CPUs, GPUs, and NICs. - :keywords: TransferBench, benchmarking utility, memory transfers, GPU transfers, NIC transfers, memory device, Executor + :description: Overview of TransferBench, a utility for benchmarking simultaneous memory transfers between CPUs, GPUs, NICs, and storage. + :keywords: TransferBench, benchmarking utility, memory transfers, GPU transfers, NIC transfers, storage transfers, NVMe, memory device, Executor .. _what-is-transferbench: @@ -8,14 +8,14 @@ What is TransferBench? ======================= -TransferBench is a utility for benchmarking simultaneous memory transfers between user-specified devices (CPUs, GPUs, and NICs). +TransferBench is a utility for benchmarking simultaneous memory transfers between user-specified devices (CPUs, GPUs, NICs, and storage). Memory transfers ================ A memory transfer is a single operation where an Executor (EXE) reads and adds values from source (SRC) memory devices, then writes the sum to destination (DST) memory devices. With a single SRC or DST, a memory transfer reduces to a simple copy operation. The memory transfer is commonly denoted by the ``(SRC->EXE->DST)`` triplet. -A memory device consists of a location (a specific device that owns the memory) and a memory type (usually some attribute about the memory). For example, fine-grained HBM memory (memory type) on GPU 0 (location), or pinned CPU memory on NUMA node 1 (location). +A memory device consists of a location (a specific device that owns the memory) and a memory type (usually some attribute about the memory). For example, fine-grained HBM memory (memory type) on GPU 0 (location), or pinned CPU memory on NUMA node 1 (location). A file or a block device on storage, such as an NVMe drive, can also act as a memory device. A set of transfers to be run simultaneously is called a Test. @@ -27,7 +27,10 @@ An Executor (EXE) is the specific device that performs a transfer — reading fr - **CPU threads** - **GPU compute kernels** (GFX) - **GPU DMA engines** (SDMA) +- **GPU batched DMA** (must have a single SRC and at least one DST) +- **GPU TDM** (Tensor Data Mover; requires hardware support: AMD gfx1250 or NVIDIA sm_90+) - **NIC RDMA** (via Remote Direct Memory Access network interface cards) +- **Storage I/O** between a file or block device and GPU memory, through the hipFile library Some Executors support **SubExecutors**, which allow further partitioning of the data to be transferred across multiple execution units within the same device. @@ -36,7 +39,9 @@ Features TransferBench supports the following features: -- **Multiple Executors:** CPU threads, GPU compute kernels (GFX), GPU DMA engines (SDMA), and NIC RDMA. +- **Multiple Executors:** CPU threads, GPU compute kernels (GFX), GPU DMA engines (SDMA), GPU batched DMA, GPU TDM, NIC RDMA, and storage I/O (hipFile). + +- **Storage benchmarking:** Reads and writes between NVMe-backed files or block devices and GPU memory. See :ref:`storage-benchmarking`. - **Multi-input or multi-output (MIMO) transfers:** Element-wise sum from multiple SRCs to multiple DSTs. diff --git a/examples/example.cfg b/examples/example.cfg index 14df7e3a..1655d86f 100644 --- a/examples/example.cfg +++ b/examples/example.cfg @@ -8,13 +8,16 @@ # SRC 1 -> Executor -> DST 1 # SRC X DST Y -# Five Executors are supported by TransferBench +# Eight Executors are supported by TransferBench # Executor: SubExecutor: # 1) CPU CPU thread # 2) GPU GPU threadblock/Compute Unit (CU) # 3) DMA N/A. (Must have single SRC, at least one DST) # 4) NIC Queue Pair -# 5) Batched-DMA Batch item (Must have single SRC, at least one DST) +# 5) Nearest NIC Queue Pair (Uses NICs closest to SRC and DST) +# 6) Batched-DMA Batch item (Must have single SRC, at least one DST) +# 7) TDM GPU threadblock/Compute Unit (CU) (Requires hardware support: AMD gfx1250 or NVIDIA sm_90+) +# 8) hipFile I/O thread (Storage <-> GPU device memory via hipFileRead/hipFileWrite) # Each single line in the configuration file defines a set of Transfers (a Test) to run in parallel @@ -33,7 +36,7 @@ # Argument Details: # #Transfers: Number of Transfers to be run in parallel -# #SEs : Number of SubExectors to use (CPU threads/ GPU threadblocks) +# #SEs : Number of SubExecutors to use (CPU threads/ GPU threadblocks/ NIC queue pairs/ storage I/O threads) # srcMemL : Source memory locations (Where the data is to be read from) # Executor : Executor is specified by a character indicating type, followed by device index (0-indexed) # - C: CPU-executed (Indexed from 0 to # NUMA nodes - 1) @@ -42,6 +45,8 @@ # - B: Batched-DMA-executor (Indexed from 0 to # GPUs - 1) # - I#.#: NIC executor (Indexed from 0 to # NICs - 1) # - N#.#: Nearest NIC executor (Indexed from 0 to # GPUs - 1) +# - T: TDM-executor (Indexed from 0 to # GPUs - 1) +# - F: hipFile-executor (Indexed from 0 to # GPUs - 1) # dstMemL : Destination memory locations (Where the data is to be written to) # bytesL : Number of bytes to copy (0 means use command-line specified size) # Must be a multiple of 4 and may be suffixed with ('K','M', or 'G') @@ -58,7 +63,18 @@ # - G: Global device memory (on GPU device indexed from 0 to [# GPUs - 1]) # - F: Fine-grain device memory (on GPU device indexed from 0 to [# GPUs - 1]) # - U: Uncached device memory (on GPU device indexed from 0 to [# GPUs - 1]) +# - M: Managed memory (on GPU device indexed from 0 to [# GPUs - 1]) # - N: Null memory (index ignored) +# - S: Storage (file or block device) (indexed from 0 to [# paths in TB_STORAGE_PATHS - 1]) +# +# Storage memory (S) can only be used with the hipFile (F) executor +# - Such a Transfer has exactly one SRC and one DST: one is storage memory (S) and the other is +# global device memory (G) on the GPU of the executor (S0->F0->G0 reads, G0->F0->S0 writes) +# - TB_STORAGE_PATHS is a comma-separated list of files and/or block devices. S0 is its first path +# - Block devices are only written to if TB_STORAGE_ALLOW_BLOCK_WRITE=1 (this destroys their contents) +# - Files that already hold data are only written to if TB_STORAGE_ALLOW_OVERWRITE=1 +# - Bytes and BYTE_OFFSET should be multiples of 4096 (hipFile otherwise falls back to non-direct I/O) +# - The hipFile executor (F) requires TransferBench to be built with hipFile support # Examples: @@ -70,6 +86,8 @@ # 1 1 (F0->N0.1->F1) Uses 1 QP to transfer data from GPU0 via GPU0's closest NIC to GPU1 via GPU1's closest NIC # -2 (G0->N0.1->G1 2 128M) (G1->N1.0->G0 1 256M) Uses Nearest NIC executor to copy 128Mb from GPU0 to GPU1 with 2 QPs, # and 256Mb from GPU1 to GPU0 with 1 QP +# 1 4 (S0->F0->G0) Uses 4 I/O threads to read from storage 0 into GPU0 via hipFile +# 1 4 (G0->F0->S0) Uses 4 I/O threads to write from GPU0 to storage 0 via hipFile # Round brackets and arrows' ->' may be included for human clarity, but will be ignored and are unnecessary # Lines starting with # will be ignored. Lines starting with ## will be echoed to output diff --git a/src/client/Client.cpp b/src/client/Client.cpp index 2a653330..4e1d5db9 100644 --- a/src/client/Client.cpp +++ b/src/client/Client.cpp @@ -235,6 +235,7 @@ void DisplayVersion() { bool nicSupport = false, mpiSupport = false, podSupport = false; nicSupport = IsIbvSymbolsReady(); + bool hipFileSupport = IsHipFileAvailable(); #if MPI_COMM_ENABLED mpiSupport = true; #endif @@ -250,6 +251,8 @@ void DisplayVersion() isFound |= nicSupport; support += podSupport ? (isFound ? "+POD" : " (with POD") : ""; isFound |= podSupport; + support += hipFileSupport ? (isFound ? "+hipFile" : " (with hipFile") : ""; + isFound |= hipFileSupport; support += isFound ? " support)" : " (No extra feature support)"; std::string multiNodeMode = ""; diff --git a/src/client/EnvVars.hpp b/src/client/EnvVars.hpp index a1deafe4..7b0e49fb 100644 --- a/src/client/EnvVars.hpp +++ b/src/client/EnvVars.hpp @@ -443,6 +443,7 @@ class EnvVars printf(" TB_DUMP_CFG_FILE - Writes executed transfers to a config file\n"); printf(" TB_DUMP_LINES - Dumps randomized input-line statistics for FILL_COMPRESS setup\n"); printf(" TB_FORCE_SINGLE_POD - Forces all ranks into one pod (skips pod query)\n"); + printf(" TB_HIPFILE_SKIP_BUF_REGISTER - Set to 1 to skip registering GPU buffers with hipFile (hipFileBufRegister)\n"); printf(" TB_MASTER_ADDR - Rank 0 hostname or IPv4 for workers; optional on rank 0 (auto-detected if unset)\n"); printf(" TB_MASTER_IFACE - When TB_MASTER_ADDR unset on rank 0, optional interface for IPv4 detection (e.g. eth0)\n"); printf(" TB_MASTER_PORT - Used to set Rank 0 port for socket communicator (default: 29500)\n"); @@ -453,8 +454,21 @@ class EnvVars printf(" TB_SEND_USLEEP - Microseconds to sleep after each socket SendData call (default: 0)\n"); printf(" TB_SHOW_ALL_NUMA - Shows all CPU NUMA nodes incl. those with no cores (default: skip core-less)\n"); printf(" TB_SINGLE_LOG - In socket mode, only rank 0 logs when set\n"); + printf(" TB_STORAGE_ALLOW_BLOCK_WRITE - Set to 1 to allow writing to block devices listed in TB_STORAGE_PATHS (destroys their contents)\n"); + printf(" TB_STORAGE_ALLOW_OVERWRITE - Set to 1 to allow overwriting files listed in TB_STORAGE_PATHS that already hold data\n"); + printf(" TB_STORAGE_PATHS - Comma-separated list of files / block devices used as storage memory (S). SN refers to the N-th path\n"); printf(" TB_VERBOSE - Enables additional internal logging\n"); printf(" TB_WALLCLOCK_RATE - Overrides queried GPU wallclock rate if needed\n"); + if (TransferBench::IsHipFileAvailable()) { + printf("\n"); + printf("Environment variables (hipFile library):\n"); + printf("====================================\n"); + printf(" These are read by hipFile itself (once, when the hipFile executor is first used) and are never set by TransferBench\n"); + printf(" HIPFILE_ALLOW_COMPAT_MODE - false = fail instead of falling back to POSIX I/O via host memory (default: true)\n"); + printf(" HIPFILE_FORCE_COMPAT_MODE - true = never use direct (fastpath) I/O between storage and GPU memory (default: false)\n"); + printf(" HIPFILE_STATS_LEVEL - 0 = disable hipFile statistics, which makes the I/O path report as unknown (default: 1)\n"); + printf(" HIPFILE_UNSUPPORTED_FILE_SYSTEMS - true = attempt direct I/O on file systems other than ext4 (data=ordered) / xfs (default: false)\n"); + } } void Print(std::string const& name, int32_t const value, const char* format, ...) const diff --git a/src/client/Presets/Help.hpp b/src/client/Presets/Help.hpp index 052b707d..48737de6 100644 --- a/src/client/Presets/Help.hpp +++ b/src/client/Presets/Help.hpp @@ -37,14 +37,16 @@ int HelpPreset([[maybe_unused]] EnvVars& ev, printf("# SRC 1 -> Executor -> DST 1\n"); printf("# SRC X DST Y\n"); printf("\n"); - printf("# Six Executors are supported by TransferBench\n"); + printf("# Eight Executors are supported by TransferBench\n"); printf("# Executor: SubExecutor:\n"); printf("# 1) CPU CPU thread\n"); printf("# 2) GPU GPU threadblock/Compute Unit (CU)\n"); printf("# 3) DMA N/A. (Must have single SRC, at least one DST)\n"); printf("# 4) NIC Queue Pair\n"); - printf("# 5) Batched-DMA Batch item (Must have single SRC, at least one DST)\n"); - printf("# 6) TDM GPU threadblock/Compute Unit (CU) (Requires hardware support: AMD gfx1250 or NVIDIA sm_90+)\n"); + printf("# 5) Nearest NIC Queue Pair (Uses NICs closest to SRC and DST)\n"); + printf("# 6) Batched-DMA Batch item (Must have single SRC, at least one DST)\n"); + printf("# 7) TDM GPU threadblock/Compute Unit (CU) (Requires hardware support: AMD gfx1250 or NVIDIA sm_90+)\n"); + printf("# 8) hipFile I/O thread (Storage <-> GPU device memory via hipFileRead/hipFileWrite)\n"); printf("\n"); printf("# Each single line in the configuration file defines a set of Transfers (a Test) to run in parallel\n"); @@ -64,7 +66,7 @@ int HelpPreset([[maybe_unused]] EnvVars& ev, printf("\n"); printf("# Argument Details:\n"); printf("# #Transfers: Number of Transfers to be run in parallel\n"); - printf("# #SEs : Number of SubExecutors to use (CPU threads/ GPU threadblocks)\n"); + printf("# #SEs : Number of SubExecutors to use (CPU threads/ GPU threadblocks/ NIC queue pairs/ storage I/O threads)\n"); printf("# srcMemL : Source memory locations (Where the data is to be read from)\n"); printf("# Executor : Executor is specified by a character indicating type, followed by device index (0-indexed)\n"); printf("# - C: CPU-executed (Indexed from 0 to # NUMA nodes - 1)\n"); @@ -74,6 +76,7 @@ int HelpPreset([[maybe_unused]] EnvVars& ev, printf("# - I#.#: NIC executor (Indexed from 0 to # NICs - 1)\n"); printf("# - N#.#: Nearest NIC executor (Indexed from 0 to # GPUs - 1)\n"); printf("# - T: TDM-executor (Indexed from 0 to # GPUs - 1)\n"); + printf("# - F: hipFile-executor (Indexed from 0 to # GPUs - 1)\n"); printf("# dstMemL : Destination memory locations (Where the data is to be written to)\n"); printf("# bytesL : Number of bytes to copy (0 means use command-line specified size)\n"); printf("# Must be a multiple of 4 and may be suffixed with ('K','M', or 'G')\n"); @@ -90,7 +93,18 @@ int HelpPreset([[maybe_unused]] EnvVars& ev, printf("# - G: Global device memory (on GPU device indexed from 0 to [# GPUs - 1])\n"); printf("# - F: Fine-grain device memory (on GPU device indexed from 0 to [# GPUs - 1])\n"); printf("# - U: Uncached device memory (on GPU device indexed from 0 to [# GPUs - 1])\n"); + printf("# - M: Managed memory (on GPU device indexed from 0 to [# GPUs - 1])\n"); printf("# - N: Null memory (index ignored)\n"); + printf("# - S: Storage (file or block device) (indexed from 0 to [# paths in TB_STORAGE_PATHS - 1])\n"); + printf("#\n"); + printf("# Storage memory (S) can only be used with the hipFile (F) executor\n"); + printf("# - Such a Transfer has exactly one SRC and one DST: one is storage memory (S) and the other is\n"); + printf("# global device memory (G) on the GPU of the executor (S0->F0->G0 reads, G0->F0->S0 writes)\n"); + printf("# - TB_STORAGE_PATHS is a comma-separated list of files and/or block devices. S0 is its first path\n"); + printf("# - Block devices are only written to if TB_STORAGE_ALLOW_BLOCK_WRITE=1 (this destroys their contents)\n"); + printf("# - Files that already hold data are only written to if TB_STORAGE_ALLOW_OVERWRITE=1\n"); + printf("# - Bytes and BYTE_OFFSET should be multiples of 4096 (hipFile otherwise falls back to non-direct I/O)\n"); + printf("# - The hipFile executor (F) requires TransferBench to be built with hipFile support\n"); printf("\n"); printf("\n"); printf("# Examples:\n"); @@ -102,6 +116,8 @@ int HelpPreset([[maybe_unused]] EnvVars& ev, printf("# 1 1 (F0->N0.1->F1) Uses 1 QP to transfer data from GPU0 via GPU0's closest NIC to GPU1 via GPU1's closest NIC\n"); printf("# -2 (G0->N0.1->G1 2 128M) (G1->N1.0->G0 1 256M) Uses Nearest NIC executor to copy 128Mb from GPU0 to GPU1 with 2 QPs,\n"); printf("# and 256Mb from GPU1 to GPU0 with 1 QP\n"); + printf("# 1 4 (S0->F0->G0) Uses 4 I/O threads to read from storage 0 into GPU0 via hipFile\n"); + printf("# 1 4 (G0->F0->S0) Uses 4 I/O threads to write from GPU0 to storage 0 via hipFile\n"); printf("# Round brackets and arrows' ->' may be included for human clarity, but will be ignored and are unnecessary\n"); printf("# Lines starting with # will be ignored. Lines starting with ## will be echoed to output\n"); printf("\n"); diff --git a/src/client/Presets/Nvme.hpp b/src/client/Presets/Nvme.hpp new file mode 100644 index 00000000..66667fa8 --- /dev/null +++ b/src/client/Presets/Nvme.hpp @@ -0,0 +1,248 @@ +/* +Copyright (c) Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +#include +#include + +int NvmePreset(EnvVars& ev, + size_t const numBytesPerTransfer, + std::string const presetName, + bool const bytesSpecified) +{ + if (TransferBench::GetNumRanks() > 1) { + Utils::Print("[ERROR] nvme preset currently not supported for multi-node\n"); + return ERR_FATAL; + } + +#if defined(__NVCC__) + Utils::Print("[ERROR] nvme preset requires the hipFile executor, which is not supported on NVIDIA hardware\n"); + return ERR_FATAL; +#endif + + int numDetectedGpus = TransferBench::GetNumExecutors(EXE_GPU_GFX); + if (numDetectedGpus == 0) { + Utils::Print("[ERROR] No GPU detected, GPUs are required to run this preset\n"); + return ERR_FATAL; + } + + int numStoragePaths = TransferBench::GetNumStoragePaths(); + if (numStoragePaths == 0) { + Utils::Print("[ERROR] nvme preset requires at least one storage path, but TB_STORAGE_PATHS is not set\n"); + Utils::Print(" Set TB_STORAGE_PATHS to a comma-separated list of files (typically on an NVMe-backed filesystem)\n"); + Utils::Print(" and/or raw block devices. Storage memory SN refers to the N-th entry (starting from 0). For example:\n"); + Utils::Print(" TB_STORAGE_PATHS=/mnt/nvme0/tb.dat,/mnt/nvme1/tb.dat ./TransferBench nvme 1G\n"); + Utils::Print(" Regular files are created/grown as needed and are left in place afterwards\n"); + Utils::Print(" Files that already hold data are only read from, unless TB_STORAGE_ALLOW_OVERWRITE=1 is set\n"); + Utils::Print(" Block devices (e.g. /dev/nvme1n1) are only read from, unless TB_STORAGE_ALLOW_BLOCK_WRITE=1 is set\n"); + return ERR_FATAL; + } + if (!TransferBench::IsStoragePathListValid()) { + Utils::Print("[ERROR] TB_STORAGE_PATHS has an empty entry ahead of a path, which would renumber the storage indices\n"); + Utils::Print(" that follow it. Remove the empty entry\n"); + return ERR_FATAL; + } + + if (numBytesPerTransfer == 0) { + Utils::Print("[ERROR] nvme preset requires a non-zero number of bytes per Transfer\n"); + return ERR_FATAL; + } + + // Collect env vars for this preset + int numFileSubExecs = EnvVars::GetEnvVar("NUM_FILE_SE", 4); + int numGpuDevices = EnvVars::GetEnvVar("NUM_GPU_DEVICES", numDetectedGpus); + int nvmeMode = EnvVars::GetEnvVar("NVME_MODE", 0); + int nvmePaired = EnvVars::GetEnvVar("NVME_PAIRED", 0); + + if (numGpuDevices < 1 || numGpuDevices > numDetectedGpus) { + Utils::Print("[ERROR] NUM_GPU_DEVICES must be between 1 and %d (instead of %d)\n", numDetectedGpus, numGpuDevices); + return ERR_FATAL; + } + if (numFileSubExecs < 1) { + Utils::Print("[ERROR] NUM_FILE_SE must be positive (instead of %d)\n", numFileSubExecs); + return ERR_FATAL; + } + if (nvmeMode < 0 || nvmeMode > 2) { + Utils::Print("[ERROR] NVME_MODE must be 0 (write + read), 1 (write only) or 2 (read only) (instead of %d)\n", nvmeMode); + return ERR_FATAL; + } + + // Display environment variables + if (Utils::RankDoesOutput()) { + ev.DisplayEnvVars(); + if (!ev.hideEnv) { + if (!ev.outputToCsv) printf("[NVMe Related]\n"); + ev.Print("NUM_FILE_SE", numFileSubExecs, "Using %d I/O thread(s) per Transfer", numFileSubExecs); + ev.Print("NUM_GPU_DEVICES", numGpuDevices, "Using %d GPUs", numGpuDevices); + ev.Print("NVME_MODE", nvmeMode, "Running %s transfers", nvmeMode == 0 ? "write + read" : + nvmeMode == 1 ? "write-only" + : "read-only"); + ev.Print("NVME_PAIRED", nvmePaired, "%s", nvmePaired ? "Each GPU uses one storage path (GPU index modulo # paths)" + : "Each GPU uses every storage path"); + printf("\n"); + } + } + + if (!TransferBench::IsHipFileAvailable()) { + Utils::Print("[ERROR] hipFile executor is not available (TransferBench was built without hipFile support)\n"); + Utils::Print(" Rebuild with the hipFile development package (amdrocm-hipfile-dev) installed\n"); + return ERR_FATAL; + } + + // Raw block devices and files that already hold data are only written to if explicitly allowed + // (same rule as enforced by backend) + char const* allowBlockWriteStr = getenv("TB_STORAGE_ALLOW_BLOCK_WRITE"); + char const* allowOverwriteStr = getenv("TB_STORAGE_ALLOW_OVERWRITE"); + bool const allowBlockWrite = (allowBlockWriteStr && !strcmp(allowBlockWriteStr, "1")); + bool const allowOverwrite = (allowOverwriteStr && !strcmp(allowOverwriteStr, "1")); + std::vector isReadOnlyStorage(numStoragePaths); + for (int i = 0; i < numStoragePaths; i++) { + std::string const path = TransferBench::GetStoragePath(i); + struct stat st; + bool const exists = (stat(path.c_str(), &st) == 0); + bool const isBlockDevice = (exists && S_ISBLK(st.st_mode)); + bool const holdsData = (exists && S_ISREG(st.st_mode) && st.st_size > 0); + isReadOnlyStorage[i] = isBlockDevice ? !allowBlockWrite : (holdsData && !allowOverwrite); + Utils::Print("Storage %d (S%d): %s (%s)\n", i, i, path.c_str(), + isBlockDevice ? (allowBlockWrite ? "block device, contents will be overwritten" + : "block device, read-only unless TB_STORAGE_ALLOW_BLOCK_WRITE=1") : + holdsData ? (allowOverwrite ? "existing file, contents will be overwritten" + : "existing file, read-only unless TB_STORAGE_ALLOW_OVERWRITE=1") + : "file"); + } + if (ev.alwaysValidate < 0) + Utils::Print("[WARN] Data validation is disabled (ALWAYS_VALIDATE < 0)\n"); + + char const separator = ev.outputToCsv ? ',' : ' '; + Utils::Print("Bytes Per Transfer%c%lu\n", separator, numBytesPerTransfer); + + TransferBench::ConfigOptions cfg = ev.ToConfigOptions(); + TransferBench::TestResults results; + + // Each row is one (GPU, storage) combination + int const numStoragePerGpu = nvmePaired ? 1 : numStoragePaths; + int const numRows = 1 + numGpuDevices * numStoragePerGpu; + int const numCols = 7; + Utils::TableHelper table(numRows, numCols); + + table.Set(0, 0, " GPU "); + table.Set(0, 1, " Storage "); + table.Set(0, 2, " Write (GB/s) "); + table.Set(0, 3, " Write path "); + table.Set(0, 4, " Read (GB/s) "); + table.Set(0, 5, " Read path "); + table.Set(0, 6, " Result "); + table.DrawRowBorder(0); + table.DrawRowBorder(1); + table.DrawRowBorder(numRows); + for (int col = 0; col <= numCols; col++) + table.DrawColBorder(col); + + int numRun = 0, numFailed = 0, numUnvalidated = 0; + std::set shownWarnings; + + int rowIdx = 1; + for (int gpuIdx = 0; gpuIdx < numGpuDevices; gpuIdx++) { + for (int i = 0; i < numStoragePerGpu; i++) { + int const storageIdx = nvmePaired ? (gpuIdx % numStoragePaths) : i; + bool const isReadOnly = isReadOnlyStorage[storageIdx]; + + table.Set(rowIdx, 0, " GPU %02d ", gpuIdx); + table.Set(rowIdx, 1, " S%d ", storageIdx); + + bool rowFailed = false, rowValidated = true, rowRan = false; + + // Write (GPU -> storage), then read (storage -> GPU) + for (int isRead = 0; isRead <= 1; isRead++) { + int const bwCol = isRead ? 4 : 2; + if ((nvmeMode == 1 && isRead) || (nvmeMode == 2 && !isRead) || (!isRead && isReadOnly)) { + table.Set(rowIdx, bwCol, " N/A "); + table.Set(rowIdx, bwCol + 1, " N/A "); + continue; + } + + MemDevice const gpuMem = {MEM_GPU, gpuIdx}; + MemDevice const storageMem = {MEM_STORAGE, storageIdx}; + + std::vector transfers(1); + transfers[0].numBytes = numBytesPerTransfer; + transfers[0].srcs.push_back(isRead ? storageMem : gpuMem); + transfers[0].dsts.push_back(isRead ? gpuMem : storageMem); + transfers[0].exeDevice = {EXE_GPU_HIPFILE, gpuIdx}; + transfers[0].exeSubIndex = -1; + transfers[0].numSubExecs = numFileSubExecs; + + numRun++; + rowRan = true; + bool const success = TransferBench::RunTransfers(cfg, transfers, results); + for (auto const& err : results.errResults) { + if (err.errType == ERR_FATAL) { + Utils::Print("[ERROR] (%s->%s->%s) %s\n", + Utils::MemDevicesToStr(transfers[0].srcs).c_str(), + Utils::ExeDeviceToStr(transfers[0].exeDevice).c_str(), + Utils::MemDevicesToStr(transfers[0].dsts).c_str(), err.errMsg.c_str()); + } else if (shownWarnings.insert(err.errMsg).second) { + Utils::Print("[WARN] %s\n", err.errMsg.c_str()); + } + } + + if (!success) { + numFailed++; + rowFailed = true; + table.Set(rowIdx, bwCol, " FAIL "); + table.Set(rowIdx, bwCol + 1, " N/A "); + continue; + } + + // Existing contents of read-only storage cannot be validated + if (ev.alwaysValidate < 0 || (isRead && isReadOnly)) { + numUnvalidated++; + rowValidated = false; + } + table.Set(rowIdx, bwCol, " %.3f ", results.tfrResults[0].avgBandwidthGbPerSec); + table.Set(rowIdx, bwCol + 1, " %s ", TransferBench::IoPathTypeStr[results.tfrResults[0].ioPath]); + } + + table.Set(rowIdx, 6, " %s ", !rowRan ? "N/A" : + rowFailed ? "FAIL" : + !rowValidated ? "UNVALIDATED" : "PASS"); + rowIdx++; + } + } + + Utils::Print("GPU <-> storage bandwidth GB/s (hipFile %s, %d I/O thread(s) per Transfer)\n", + TransferBench::GetHipFileVersion().c_str(), numFileSubExecs); + table.PrintTable(ev.outputToCsv, ev.showBorders); + + if (numRun == 0) { + Utils::Print("[ERROR] No Transfers were run (see NVME_MODE, TB_STORAGE_ALLOW_OVERWRITE and TB_STORAGE_ALLOW_BLOCK_WRITE)\n"); + return ERR_FATAL; + } + if (numFailed) { + Utils::Print("[ERROR] %d of %d Transfers FAILED\n", numFailed, numRun); + return ERR_FATAL; + } + if (numUnvalidated) + Utils::Print("%d Transfers completed (%d without data validation)\n", numRun, numUnvalidated); + else + Utils::Print("All %d Transfers passed\n", numRun); + return ERR_NONE; +} diff --git a/src/client/Presets/PerfReport.hpp b/src/client/Presets/PerfReport.hpp index 724101be..8a0d46a2 100644 --- a/src/client/Presets/PerfReport.hpp +++ b/src/client/Presets/PerfReport.hpp @@ -1348,6 +1348,7 @@ namespace PerfReport case EXE_NIC_NEAREST: return "NIC_NEAREST"; case EXE_GPU_BDMA: return "BDMA"; case EXE_GPU_TDM: return "TDM"; + case EXE_GPU_HIPFILE: return "HIPFILE"; default: return "?"; } } diff --git a/src/client/Presets/Presets.hpp b/src/client/Presets/Presets.hpp index 86410a94..42a0dfb5 100644 --- a/src/client/Presets/Presets.hpp +++ b/src/client/Presets/Presets.hpp @@ -42,6 +42,7 @@ THE SOFTWARE. #include "NicAllToAll.hpp" #include "NicRings.hpp" #include "NicPeerToPeer.hpp" +#include "Nvme.hpp" #include "OneToAll.hpp" #include "PeerToPeer.hpp" #include "PodAllToAll.hpp" @@ -81,6 +82,7 @@ std::map presetFuncMap = {"nica2a", {NicAllToAllPreset, "All-to-all GPU traffic over NIC transfers using each NIC's closest GPU/CPU endpoint"}}, {"nicp2p", {NicPeerToPeerPreset, "Multi-node peer-to-peer RDMA transfer test between all NICs"}}, {"nicrings", {NicRingsPreset, "Tests NIC rings created across identical NIC indices across ranks"}}, + {"nvme", {NvmePreset, "GPU <-> storage (NVMe) write/read bandwidth test using the hipFile executor"}}, {"one2all", {OneToAllPreset, "Test all subsets of parallel transfers from one GPU to all others"}}, {"one2all_latency", {LatencyPreset, "Latency values from one Executor to many, run in parallel"}}, {"p2p", {PeerToPeerPreset, "Peer-to-peer device memory bandwidth test"}}, diff --git a/src/client/Topology.hpp b/src/client/Topology.hpp index e9eca347..1b5d6caa 100644 --- a/src/client/Topology.hpp +++ b/src/client/Topology.hpp @@ -70,6 +70,26 @@ static void PrintNicToGPUTopo(bool outputToCsv) printf("\n"); } +static void PrintStorageTopo(bool outputToCsv) +{ + char sep = (outputToCsv ? ',' : '|'); + int numStoragePaths = TransferBench::GetNumStoragePaths(); + + printf(" Storage %c Path (TB_STORAGE_PATHS)\n", sep); + if (!outputToCsv) + printf("---------+-------------------------\n"); + for (int i = 0; i < numStoragePaths; i++) + printf(" S%-6d %c %s\n", i, sep, TransferBench::GetStoragePath(i).c_str()); + if (numStoragePaths == 0) + printf(" N/A %c Not set\n", sep); + + std::string hipFileDesc = "Not available (built without hipFile support)"; + if (TransferBench::IsHipFileAvailable()) + hipFileDesc = "Available (hipFile " + TransferBench::GetHipFileVersion() + ")"; + printf(" hipFile %c %s\n", sep, hipFileDesc.c_str()); + printf("\n"); +} + void DisplaySingleRankTopology(bool outputToCsv) { int numCpus = TransferBench::GetNumExecutors(EXE_CPU); @@ -135,6 +155,9 @@ void DisplaySingleRankTopology(bool outputToCsv) // Print out detected NIC topology PrintNicToGPUTopo(outputToCsv); + // Print out storage paths and hipFile executor availability + PrintStorageTopo(outputToCsv); + // Print out detected GPU topology #if defined(__NVCC__) for (int i = 0; i < numGpus; i++) { diff --git a/src/client/Utilities.hpp b/src/client/Utilities.hpp index 943f23b2..b73cb384 100644 --- a/src/client/Utilities.hpp +++ b/src/client/Utilities.hpp @@ -462,6 +462,7 @@ namespace TransferBench::Utils case EXE_NIC_NEAREST: return "NIC"; case EXE_GPU_BDMA: return "BMA"; case EXE_GPU_TDM: return "TDM"; + case EXE_GPU_HIPFILE: return "HPF"; default: return "N/A"; } } diff --git a/src/header/TransferBench.hpp b/src/header/TransferBench.hpp index 6884427b..acc4b458 100644 --- a/src/header/TransferBench.hpp +++ b/src/header/TransferBench.hpp @@ -55,6 +55,8 @@ THE SOFTWARE. #include #include #include +#include +#include #include #include #include @@ -85,7 +87,11 @@ THE SOFTWARE. #ifdef AMD_SMI_ENABLED #include "amd_smi/amdsmi.h" #endif - +// hipFile executor is only supported when built with hipFile (HIPFILE_ENABLED) +#ifdef HIPFILE_ENABLED +#include +#define HIPFILE_EXEC_ENABLED +#endif #endif #include "tdmCopy.h" @@ -119,11 +125,13 @@ namespace TransferBench EXE_NIC_NEAREST = 4, ///< NIC RDMA nearest executor (subExecutor = queue pair) EXE_GPU_BDMA = 5, ///< GPU Batched SDMA executor (subExecutor = batch item) EXE_GPU_TDM = 6, ///< GPU TDM executor (subExecutor = threadblock/CU) + EXE_GPU_HIPFILE = 7, ///< GPU hipFile executor (subExecutor = I/O thread) }; - char const ExeTypeStr[8] = "CGDINBT"; + char const ExeTypeStr[9] = "CGDINBTF"; inline bool IsCpuExeType(ExeType e){ return e == EXE_CPU; } inline bool IsGpuExeType(ExeType e){ return e == EXE_GPU_GFX || e == EXE_GPU_DMA || e == EXE_GPU_BDMA || e == EXE_GPU_TDM; } inline bool IsNicExeType(ExeType e){ return e == EXE_NIC || e == EXE_NIC_NEAREST; } + inline bool IsFileExeType(ExeType e){ return e == EXE_GPU_HIPFILE; } /** * A ExeDevice defines a specific Executor @@ -161,10 +169,12 @@ namespace TransferBench MEM_GPU_UNCACHED = 8, ///< Uncached GPU memory (via hipDeviceMallocUncached flag) MEM_MANAGED = 9, ///< Managed memory MEM_NULL = 10, ///< NULL memory - used for empty + MEM_STORAGE = 11, ///< Storage (file or block device, indexed into TB_STORAGE_PATHS) }; - char const MemTypeStr[12] = "CPBDKHGFUMN"; + char const MemTypeStr[13] = "CPBDKHGFUMNS"; inline bool IsCpuMemType(MemType m) { return (MEM_CPU <= m && m <= MEM_CPU_UNPINNED);} inline bool IsGpuMemType(MemType m) { return (MEM_GPU <= m && m <= MEM_MANAGED);} + inline bool IsStorageMemType(MemType m) { return m == MEM_STORAGE;} /** * Enumeration of supported GFX kernels @@ -400,6 +410,27 @@ namespace TransferBench ErrResult(ErrType errType, const char* format, ...); }; + /** + * Enumeration of storage I/O paths + * + * @note Reports how data was moved between storage memory (MEM_STORAGE) and GPU memory + */ + enum IoPathType + { + IO_PATH_NONE = 0, ///< Transfer does not involve storage memory + IO_PATH_UNKNOWN = 1, ///< Storage Transfer, but the I/O path could not be determined + IO_PATH_FASTPATH = 2, ///< hipFile fastpath (direct I/O between storage and GPU memory) + IO_PATH_COMPAT = 3, ///< hipFile compatibility path (POSIX I/O via host bounce buffer) + IO_PATH_MIXED = 4, ///< Both direct and compatibility path I/O were performed + }; + char const* const IoPathTypeStr[] = { + "none", + "unknown", + "fastpath", + "compat", + "mixed" + }; + /** * Results for a single Executor */ @@ -427,6 +458,8 @@ namespace TransferBench ExeDevice exeDevice; ///< Tracks which executor performed this Transfer (e.g. for EXE_NIC_NEAREST) ExeDevice exeDstDevice; ///< Tracks actual destination executor (only valid for EXE_NIC/EXE_NIC_NEAREST) + + IoPathType ioPath = IO_PATH_NONE; ///< Storage I/O path used (only valid for EXE_GPU_HIPFILE) }; /** @@ -485,6 +518,8 @@ namespace TransferBench /** * Returns information about number of available Executors given a memory type * + * @note For storage memory (MEM_STORAGE), this is the number of storage paths + * * @param[in] memType Memory type to query * @param[in] targetRank Rank to query (-1 for local rank) * @returns Number of detected Executors for memType @@ -497,6 +532,7 @@ namespace TransferBench * @note For CPU, this is 0 * @note For GFX, this refers to the number of XCDs * @note For DMA, this refers to the number of DMA engines + * @note For hipFile, this is 0 * * @param[in] exeDevice The specific Executor to query * @returns Number of detected executor subindices @@ -646,6 +682,56 @@ namespace TransferBench */ uint32_t GetNicMaxMsgSize(int nicIndex, int targetRank = -1); + /** + * Returns the number of storage paths available as storage memory (MEM_STORAGE) + * + * @note Storage paths are provided as a comma-separated list via the TB_STORAGE_PATHS + * environment variable. Storage memory index N refers to the N-th path in that list + * @note This is equivalent to GetNumExecutors(MEM_STORAGE, targetRank) + * + * @param[in] targetRank Rank to query (-1 for local rank) + * @returns Number of storage paths defined on the target rank + */ + int GetNumStoragePaths(int targetRank = -1); + + /** + * Returns the path backing a storage memory index + * + * @param[in] storageIndex Storage memory index to query + * @param[in] targetRank Rank to query (-1 for local rank) + * @returns Path of the file or block device, or an empty string if storageIndex is out of range + */ + std::string GetStoragePath(int storageIndex, int targetRank = -1); + + /** + * Returns whether the list of storage paths of the local rank is well-formed + * + * @note An empty entry ahead of a path (e.g. TB_STORAGE_PATHS=",/mnt/nvme1/tb.dat") makes the + * list invalid, as it would renumber the storage memory indices that follow it. Transfers + * using storage memory are rejected while the list is invalid + * + * @returns true if and only if storage memory indices can be relied upon + */ + bool IsStoragePathListValid(); + + /** + * Returns whether the hipFile executor (EXE_GPU_HIPFILE) is usable + * + * @note hipFile is a build-time dependency: the executor is only available if TransferBench + * was compiled with HIPFILE_ENABLED defined (which requires hipfile.h and linking + * against libhipfile) + * + * @param[in] targetRank Rank to query (-1 for local rank) + * @returns true if and only if TransferBench was built with hipFile support on the target rank + */ + bool IsHipFileAvailable(int targetRank = -1); + + /** + * @returns Version of the hipFile library in use on the local rank ("major.minor.patch"), + * or an empty string if hipFile is not available + */ + std::string GetHipFileVersion(); + /** * Helper function to parse a line containing Transfers into a vector of Transfers * @@ -1181,6 +1267,9 @@ const auto& AmdSmiFabricInfoV1(const T& info) std::string GetExecutorName(ExeDevice exeDevice) const; int NicIsActive(int nicIndex, int targetRank) const; uint32_t GetNicMaxMsgSize(int nicIndex, int targetRank) const; + int GetNumStoragePaths(int targetRank) const; + std::string GetStoragePath(int storageIndex, int targetRank) const; + bool IsFileExeAvailable(ExeType exeType, int targetRank) const; // Translate a logical CPU NUMA index (as exposed to users) into the physical // NUMA node id used by libnuma / HSA. Returns the index unchanged if out of range. @@ -1258,6 +1347,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) std::map> closestNicsToGpu; std::map> closestGpusToNic; std::map, std::string> executorName; + std::map storagePath; + std::map fileExeAvailable; }; std::vector rankInfo; ///< Topology of each rank @@ -1633,6 +1724,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) case MEM_GPU_UNCACHED: return "GPU_UNCACHED"; case MEM_MANAGED: return "GPU_MANAGED"; case MEM_NULL: return "NULL"; + case MEM_STORAGE: return "STORAGE"; default: return "UNKNOWN"; } } @@ -1688,6 +1780,11 @@ const auto& AmdSmiFabricInfoV1(const T& info) } *memPtr = nullptr; + // Storage memory has no memory pointer. It is opened via OpenStorage instead + if (IsStorageMemType(memDevice.memType)) { + return {ERR_FATAL, "Storage memory cannot be allocated as a memory buffer"}; + } + MemType const& memType = memDevice.memType; int deviceIdx = memDevice.memIndex; if (memType == MEM_CPU_CLOSEST) { @@ -1834,6 +1931,10 @@ const auto& AmdSmiFabricInfoV1(const T& info) static ErrResult DeallocateMemory(MemType memType, void *memPtr, size_t const bytes, hipMemGenericAllocationHandle_t* memHandle = nullptr) { + // Storage memory has no memory pointer. It is released via CloseStorage instead + if (IsStorageMemType(memType)) + return {ERR_FATAL, "Storage memory cannot be deallocated as a memory buffer"}; + // Avoid deallocating nullptr if (memPtr == nullptr) return {ERR_FATAL, "Attempted to free null pointer for %lu bytes", bytes}; @@ -2037,6 +2138,395 @@ const auto& AmdSmiFabricInfoV1(const T& info) } #endif +// Storage-related functions +//======================================================================================== + size_t constexpr STORAGE_ALIGN_BYTES = 4096; // Alignment of storage I/O (file offset, size, buffer) + size_t constexpr STORAGE_BOUNCE_BYTES = 16 << 20; // Max size of host bounce buffer for storage prep/validation + size_t constexpr STORAGE_MAX_IO_BYTES = 0x7ffff000; // Max bytes hipFile moves in a single call + + // A path used as storage memory (MEM_STORAGE) + struct StorageDevice + { + std::string path; ///< Path to a regular file or a block device + bool isBlockDevice = false; ///< Path refers to a block device + bool isWritable = true; ///< Whether TransferBench is allowed to write to this path + int fd = -1; ///< File descriptor shared by all Transfers (-1 if closed) + int useCount = 0; ///< Number of Transfer endpoints currently using this path + void* fileHandle = nullptr; ///< hipFile handle shared by all Transfers (if registered) + bool isScratch = false; ///< File did not exist or was empty when first seen (holds no other data) + bool wasCreated = false; ///< File was created by TransferBench + dev_t idDevice = 0; ///< While open: the block device, or the device holding the file + ino_t idInode = 0; ///< While open: inode of the file (0 for block devices) + }; + + static size_t AlignUp(size_t const value, size_t const alignment) + { + return (value + alignment - 1) / alignment * alignment; + } + + static std::mutex& GetStorageMutex() + { + static std::mutex storageMutex; + return storageMutex; + } + + // Storage paths are given as a comma-separated list in TB_STORAGE_PATHS. A MemDevice is + // broadcast between ranks as raw bytes and cannot carry a path, so storage memory index N + // refers to the N-th entry of this (per-rank) list + struct StorageConfig + { + std::vector list; ///< Storage paths in the order they were given + bool hasEmptyEntry = false; ///< An empty entry was given ahead of a path + }; + + static StorageConfig& GetStorageConfig() + { + static StorageConfig storageConfig = [] { + StorageConfig config; + char const* env = getenv("TB_STORAGE_PATHS"); + if (env) { + std::stringstream ss(env); + std::string path; + bool emptyPending = false; + while (std::getline(ss, path, ',')) { + size_t const first = path.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) { + emptyPending = true; + continue; + } + // Trailing commas are harmless, but an empty entry ahead of a path (e.g. from an unset + // variable in a script) would silently renumber the storage indices that follow it + config.hasEmptyEntry |= emptyPending; + size_t const last = path.find_last_not_of(" \t\r\n"); + StorageDevice dev; + dev.path = path.substr(first, last - first + 1); + config.list.push_back(dev); + } + } + return config; + }(); + return storageConfig; + } + + static std::vector& GetStorageDeviceList() + { + return GetStorageConfig().list; + } + + // Storage indices cannot be trusted if TB_STORAGE_PATHS has an empty entry ahead of a path + static ErrResult CheckStoragePathList() + { + if (GetStorageConfig().hasEmptyEntry) { + return {ERR_FATAL, "TB_STORAGE_PATHS has an empty entry ahead of a path on rank %d, which would renumber " + "the storage indices that follow it. Remove the empty entry", GetRank()}; + } + return ERR_NONE; + } + + // Returns whether a path lies under /dev/, where device nodes live (/dev/shm/ is a tmpfs for files) + static bool IsDeviceNodePath(std::string const& path) + { + std::error_code ec; + std::filesystem::path absPath = std::filesystem::absolute(path, ec); + if (ec) absPath = path; + std::filesystem::path resolvedPath = std::filesystem::weakly_canonical(absPath, ec); + if (ec) resolvedPath = absPath.lexically_normal(); + std::string const resolved = resolvedPath.string(); + return resolved.rfind("/dev/", 0) == 0 && resolved.rfind("/dev/shm/", 0) != 0; + } + + // Determines if a storage path is a block device, and whether it may be written to. + // Writing destroys whatever is stored there, so it is only permitted + // - for a block device, when TB_STORAGE_ALLOW_BLOCK_WRITE=1 is set + // - for a regular file that already holds data, when TB_STORAGE_ALLOW_OVERWRITE=1 is set + // A file that did not exist or was empty when first seen has nothing to lose, and stays + // writable for the rest of the run (so that Tests can reuse the file an earlier Test created) + static void ProbeStorageDevice(StorageDevice& dev) + { + struct stat st; + bool const exists = (stat(dev.path.c_str(), &st) == 0); + dev.isBlockDevice = (exists && S_ISBLK(st.st_mode)); + if (!dev.isBlockDevice && !(exists && S_ISREG(st.st_mode) && st.st_size > 0)) dev.isScratch = true; + char const* allowWrite = getenv(dev.isBlockDevice ? "TB_STORAGE_ALLOW_BLOCK_WRITE" : "TB_STORAGE_ALLOW_OVERWRITE"); + dev.isWritable = (!dev.isBlockDevice && dev.isScratch) || (allowWrite && !strcmp(allowWrite, "1")); + } + + // Returns whether TransferBench is allowed to write to a (local) storage index + static bool IsStorageWritable(int const storageIndex, bool* isBlockDevice = nullptr) + { + std::lock_guard lock(GetStorageMutex()); + std::vector& storageList = GetStorageDeviceList(); + if (storageIndex < 0 || storageIndex >= (int)storageList.size()) return false; + StorageDevice& dev = storageList[storageIndex]; + if (dev.fd < 0) ProbeStorageDevice(dev); + if (isBlockDevice) *isBlockDevice = dev.isBlockDevice; + return dev.isWritable; + } + + // Returns true if any of the given (local) memory devices is storage that may not be written to + static bool HasReadOnlyStorage(vector const& memDevices) + { + for (auto const& memDevice : memDevices) { + if (IsStorageMemType(memDevice.memType) && memDevice.memRank == GetRank() && + !IsStorageWritable(memDevice.memIndex)) + return true; + } + return false; + } + + // Storage equivalent of AllocateMemory: opens the path backing a storage index and makes + // sure it holds at least numBytes. There is no memory pointer for storage memory, the file + // descriptor is provided instead. All Transfers using a storage index share one descriptor. + // Regular files are created and grown as needed. Block devices are never created, truncated + // or resized. Block devices and files that already hold data are opened read-only (and are + // not resized) unless writing to them has been explicitly allowed + static ErrResult OpenStorage(int const storageIndex, size_t const numBytes, int& fd) + { + fd = -1; + ERR_CHECK(CheckStoragePathList()); + + std::lock_guard lock(GetStorageMutex()); + std::vector& storageList = GetStorageDeviceList(); + if (storageIndex < 0 || storageIndex >= (int)storageList.size()) { + return {ERR_FATAL, "Storage index %d is out of range (%lu storage paths defined via TB_STORAGE_PATHS)", + storageIndex, storageList.size()}; + } + StorageDevice& dev = storageList[storageIndex]; + char const* path = dev.path.c_str(); + + bool const wasOpen = (dev.fd >= 0); + if (!wasOpen) { + struct stat st; + bool const exists = (stat(path, &st) == 0); + if (exists && !S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode)) { + return {ERR_FATAL, "Storage %d (%s) must be a regular file or a block device", storageIndex, path}; + } + // A device name that does not exist is most likely mistyped. Creating it would leave a + // regular file in devtmpfs (i.e. in host memory) standing in for the intended block device + if (!exists && IsDeviceNodePath(dev.path)) { + return {ERR_FATAL, "Storage %d (%s) does not exist. Paths under /dev/ (other than /dev/shm/) are " + "not created, as they are expected to be existing block devices", storageIndex, path}; + } + // Creating through a dangling symbolic link would bypass the check above + if (!exists && lstat(path, &st) == 0 && S_ISLNK(st.st_mode)) { + return {ERR_FATAL, "Storage %d (%s) is a symbolic link to a path that does not exist", + storageIndex, path}; + } + ProbeStorageDevice(dev); + + int flags = (dev.isWritable ? O_RDWR : O_RDONLY) | O_CLOEXEC; + if (dev.isWritable) { + // An exclusive open of a block device fails if the device, or one of its partitions, is + // mounted or otherwise claimed, which catches a device name that now refers to a disk in use + flags |= dev.isBlockDevice ? O_EXCL : O_CREAT; + } + + dev.fd = open(path, flags | O_DIRECT, 0644); + if (dev.fd < 0 && errno == EBUSY && (flags & O_EXCL)) { + return {ERR_FATAL, "Unable to open storage %d (%s) for writing: the device, or one of its partitions, is " + "mounted or in use (possibly by another TransferBench rank, or by another TB_STORAGE_PATHS entry " + "that refers to the same device)", storageIndex, path}; + } + if (dev.fd < 0) { + return {ERR_FATAL, "Unable to open storage %d (%s): %s", storageIndex, path, strerror(errno)}; + } + + // The write permission above was decided from the path, so make sure the opened file agrees + if (fstat(dev.fd, &st) != 0 || (bool)S_ISBLK(st.st_mode) != dev.isBlockDevice) { + close(dev.fd); + dev.fd = -1; + return {ERR_FATAL, "Storage %d (%s) changed type while being opened", storageIndex, path}; + } + + // Regions are assigned per storage index, so two indices that refer to the same file or + // device would be handed overlapping regions + dev.idDevice = dev.isBlockDevice ? st.st_rdev : st.st_dev; + dev.idInode = dev.isBlockDevice ? 0 : st.st_ino; + for (int i = 0; i < (int)storageList.size(); i++) { + StorageDevice const& other = storageList[i]; + if (i == storageIndex || other.fd < 0 || other.isBlockDevice != dev.isBlockDevice || + other.idDevice != dev.idDevice || other.idInode != dev.idInode) continue; + close(dev.fd); + dev.fd = -1; + return {ERR_FATAL, "Storage %d (%s) and storage %d (%s) refer to the same %s. Each TB_STORAGE_PATHS " + "entry must be a distinct file or block device", storageIndex, path, i, other.path.c_str(), + dev.isBlockDevice ? "block device" : "file"}; + } + + // Regions are also assigned per process, so a file shared with another rank or process on + // this host would be overwritten by both. Block devices are left alone, as udev briefly + // locks them itself (writers are kept apart by the exclusive open instead) + if (!dev.isBlockDevice && flock(dev.fd, (dev.isWritable ? LOCK_EX : LOCK_SH) | LOCK_NB) != 0 && + errno == EWOULDBLOCK) { + close(dev.fd); + dev.fd = -1; + return {ERR_FATAL, "Storage %d (%s) is locked by another process, most likely another TransferBench rank " + "or run. Ranks running on the same host need distinct storage paths", storageIndex, path}; + } + dev.wasCreated |= !exists; + } + + // Storage I/O is performed in multiples of STORAGE_ALIGN_BYTES + size_t const neededBytes = AlignUp(numBytes, STORAGE_ALIGN_BYTES); + ErrResult err = ERR_NONE; + if (dev.isBlockDevice) { + // All storage I/O uses explicit offsets, so moving the file position here is harmless + off_t const deviceBytes = lseek(dev.fd, 0, SEEK_END); + if (deviceBytes < 0) { + err = {ERR_FATAL, "Unable to query size of storage %d (%s): %s", storageIndex, path, strerror(errno)}; + } else if ((size_t)deviceBytes < neededBytes) { + err = {ERR_FATAL, "Storage %d (%s) is too small: %lu bytes are required but only %lu are available", + storageIndex, path, neededBytes, (size_t)deviceBytes}; + } + } else { + struct stat st; + if (fstat(dev.fd, &st) != 0) { + err = {ERR_FATAL, "Unable to query size of storage %d (%s): %s", storageIndex, path, strerror(errno)}; + } else if ((size_t)st.st_size < neededBytes && !dev.isWritable) { + err = {ERR_FATAL, "Storage %d (%s) is too small: %lu bytes are required but only %lu are available. " + "An existing file is not grown unless TB_STORAGE_ALLOW_OVERWRITE=1 is set", + storageIndex, path, neededBytes, (size_t)st.st_size}; + } else if ((size_t)st.st_size < neededBytes) { + // Allocate the blocks up front so that direct I/O never has to extend the file + int rc; + do { + rc = posix_fallocate(dev.fd, 0, neededBytes); + } while (rc == EINTR); + + // Only a filesystem that cannot preallocate gets a sparse file instead. Any other failure + // (e.g. out of space) would otherwise only surface once the filesystem has been filled up + if (rc == EOPNOTSUPP || rc == EINVAL || rc == ENOSYS) { + rc = (ftruncate(dev.fd, neededBytes) == 0) ? 0 : errno; + } + if (rc != 0) { + err = {ERR_FATAL, "Unable to resize storage %d (%s) to %lu bytes: %s", + storageIndex, path, neededBytes, strerror(rc)}; + + // A failed allocation can leave the file partially extended + bool const restored = (ftruncate(dev.fd, st.st_size) == 0); + if (dev.wasCreated) { + unlink(path); + dev.wasCreated = false; + } else if (!restored) { + err.errMsg += " (and unable to restore its previous size)"; + } + } + } + } + + if (err.errType != ERR_NONE) { + if (!wasOpen) { + close(dev.fd); + dev.fd = -1; + } + return err; + } + + dev.useCount++; + fd = dev.fd; + return ERR_NONE; + } + + // Storage equivalent of DeallocateMemory. The path is closed once its last user is gone + static ErrResult CloseStorage(int const storageIndex) + { + std::lock_guard lock(GetStorageMutex()); + std::vector& storageList = GetStorageDeviceList(); + if (storageIndex < 0 || storageIndex >= (int)storageList.size() || + storageList[storageIndex].fd < 0 || storageList[storageIndex].useCount <= 0) { + return {ERR_FATAL, "Attempted to close storage %d which is not open", storageIndex}; + } + + StorageDevice& dev = storageList[storageIndex]; + if (--dev.useCount > 0) return ERR_NONE; + +#ifdef HIPFILE_EXEC_ENABLED + if (dev.fileHandle != nullptr) { + hipFileHandleDeregister(dev.fileHandle); + dev.fileHandle = nullptr; + } +#endif + if (dev.isWritable) fdatasync(dev.fd); + close(dev.fd); + dev.fd = -1; + return ERR_NONE; + } + +// Reads or writes exactly numBytes at fileOffset (all must be multiples of STORAGE_ALIGN_BYTES) + static ErrResult StorageBlockIo(int const fd, bool const isWrite, char* buffer, + size_t const numBytes, size_t const fileOffset) + { + size_t done = 0; + while (done < numBytes) { + ssize_t const ret = isWrite ? pwrite(fd, buffer + done, numBytes - done, fileOffset + done) + : pread (fd, buffer + done, numBytes - done, fileOffset + done); + if (ret < 0) { + if (errno == EINTR) continue; + return {ERR_FATAL, "Unable to %s %lu bytes at offset %lu of storage: %s", + isWrite ? "write" : "read", numBytes - done, fileOffset + done, strerror(errno)}; + } + if (ret == 0) { + return {ERR_FATAL, "Unexpected end of storage when %s at offset %lu", + isWrite ? "writing" : "reading", fileOffset + done}; + } + done += ret; + } + return ERR_NONE; + } + + // Copies data between host memory and storage. Storage memory has no memory pointer, so + // this replaces the hipMemcpy / memset calls used for regular memory when preparing, + // clearing and validating it. If isWrite is set and data is NULL, storage is zero-filled. + // The storage descriptor is typically opened with O_DIRECT, so data moves through an aligned + // host bounce buffer and every I/O is issued on STORAGE_ALIGN_BYTES boundaries (reading back + // the partial first / last block before writing an unaligned range) + static ErrResult StorageCopy(int const fd, bool const isWrite, size_t const fileOffset, + void* data, size_t const numBytes) + { + if (fd < 0) return {ERR_FATAL, "Storage is not open"}; + if (numBytes == 0) return ERR_NONE; + + size_t const rangeEnd = fileOffset + numBytes; + size_t const alignedStart = fileOffset / STORAGE_ALIGN_BYTES * STORAGE_ALIGN_BYTES; + size_t const alignedEnd = AlignUp(rangeEnd, STORAGE_ALIGN_BYTES); + size_t const bounceBytes = std::min(alignedEnd - alignedStart, STORAGE_BOUNCE_BYTES); + + void* bounceMem = nullptr; + if (posix_memalign(&bounceMem, STORAGE_ALIGN_BYTES, bounceBytes) != 0) { + return {ERR_FATAL, "Unable to allocate %lu byte bounce buffer for storage", bounceBytes}; + } + char* const bounce = (char*)bounceMem; + + ErrResult err = ERR_NONE; + for (size_t pos = alignedStart; pos < alignedEnd && err.errType == ERR_NONE; pos += bounceBytes) { + size_t const chunkBytes = std::min(bounceBytes, alignedEnd - pos); + + // Portion of this chunk that lies within the requested range + size_t const lo = std::max(pos, fileOffset); + size_t const hi = std::min(pos + chunkBytes, rangeEnd); + + if (!isWrite || lo != pos || hi != pos + chunkBytes) { + err = StorageBlockIo(fd, false, bounce, chunkBytes, pos); + if (err.errType != ERR_NONE) break; + } + if (isWrite) { + if (data) memcpy(bounce + (lo - pos), (char*)data + (lo - fileOffset), hi - lo); + else memset(bounce + (lo - pos), 0, hi - lo); + err = StorageBlockIo(fd, true, bounce, chunkBytes, pos); + } else { + memcpy((char*)data + (lo - fileOffset), bounce + (lo - pos), hi - lo); + } + } + free(bounceMem); + return err; + } + + // Zero-fills a region of storage (storage equivalent of clearing a memory buffer) + static ErrResult ClearStorage(int const fd, size_t const fileOffset, size_t const numBytes) + { + return StorageCopy(fd, true, fileOffset, nullptr, numBytes); + } + // Setup validation-related functions //======================================================================================== // This function resolves executors that may be indexed by "nearest" @@ -2112,6 +2602,19 @@ const auto& AmdSmiFabricInfoV1(const T& info) } return ERR_NONE; } + + if (IsStorageMemType(memDevice.memType)) { + if (GetRank() == memDevice.memRank) ERR_CHECK(CheckStoragePathList()); + int numStorage = GetNumStoragePaths(memDevice.memRank); + if (numStorage == 0) + return {ERR_FATAL, + "No storage paths are defined on rank %d. Set TB_STORAGE_PATHS to a comma-separated list of " + "files or block devices", memDevice.memRank}; + if (memDevice.memIndex < 0 || memDevice.memIndex >= numStorage) + return {ERR_FATAL, + "Storage index must be between 0 and %d (instead of %d) on rank %d", numStorage - 1, memDevice.memIndex, memDevice.memRank}; + return ERR_NONE; + } return {ERR_FATAL, "Unsupported memory type (%d)", memDevice.memType}; } @@ -2540,15 +3043,18 @@ const auto& AmdSmiFabricInfoV1(const T& info) // transfer is small if (t.exeDevice.exeType != EXE_GPU_DMA) { // GPU DMA-Executor ignores subexecutors + // The hipFile executor splits work in multiples of the storage I/O alignment instead + int const blockBytes = IsFileExeType(t.exeDevice.exeType) ? (int)STORAGE_ALIGN_BYTES + : cfg.data.blockBytes; size_t const N = t.numBytes / sizeof(float); - int const targetMultiple = cfg.data.blockBytes / sizeof(float); + int const targetMultiple = blockBytes / sizeof(float); int const maxSubExecToUse = std::min((size_t)(N + targetMultiple - 1) / targetMultiple, (size_t)t.numSubExecs); if (maxSubExecToUse < t.numSubExecs) errors.push_back({ERR_WARN, "Transfer %d data size is too small - will only use %d of %d subexecutors due to blockBytes of %d", - i, maxSubExecToUse, t.numSubExecs, cfg.data.blockBytes}); + i, maxSubExecToUse, t.numSubExecs, blockBytes}); } bool const isPingpong = t.numLaps > 0; @@ -2598,6 +3104,23 @@ const auto& AmdSmiFabricInfoV1(const T& info) } if (hasFatalError) break; + // Storage memory has no memory pointer, so only the hipFile executor is able to access it + { + bool hasStorage = false; + for (auto const* memList : {&t.srcs, &t.dsts}) + for (auto const& mem : *memList) + hasStorage |= IsStorageMemType(mem.memType); + + if (hasStorage && (isPingpong || !IsFileExeType(t.exeDevice.exeType))) { + errors.push_back({ERR_FATAL, + "Transfer %zu: Storage memory (%c) can only be accessed by the hipFile (%c) executor%s", + i, MemTypeStr[MEM_STORAGE], ExeTypeStr[EXE_GPU_HIPFILE], + isPingpong ? ", and is not supported for pingpong transfers" : ""}); + hasFatalError = true; + break; + } + } + if (isPingpong) { if (t.exeDevice.exeType != EXE_GPU_GFX || t.exeDevicePong.exeType != EXE_GPU_GFX) { errors.push_back({ERR_FATAL, @@ -2991,6 +3514,108 @@ const auto& AmdSmiFabricInfoV1(const T& info) hasFatalError = true; } break; + case EXE_GPU_HIPFILE: + { +#if defined(__NVCC__) + errors.push_back({ERR_FATAL, "Transfer %d: hipFile executor is not supported on NVIDIA hardware", i}); + hasFatalError = true; + break; +#else + if (!System::Get().IsFileExeAvailable(t.exeDevice.exeType, t.exeDevice.exeRank)) { + errors.push_back({ERR_FATAL, "Transfer %d: hipFile executor is requested but is not available on rank %d " + "(TransferBench was built without hipFile support. Rebuild it with the hipFile development " + "package (amdrocm-hipfile-dev, which provides hipfile.h) installed)", + i, t.exeDevice.exeRank}); + hasFatalError = true; + break; + } + + // The hipFile executor can only move data between one storage location and one GPU buffer + if (t.srcs.size() != 1 || t.dsts.size() != 1) { + errors.push_back({ERR_FATAL, "Transfer %d: hipFile executor requires exactly 1 SRC and 1 DST", i}); + hasFatalError = true; + break; + } + + bool const srcIsStorage = IsStorageMemType(t.srcs[0].memType); + bool const dstIsStorage = IsStorageMemType(t.dsts[0].memType); + if (srcIsStorage == dstIsStorage) { + errors.push_back({ERR_FATAL, + "Transfer %d: hipFile executor requires exactly one of SRC and DST to be storage memory (%c)", + i, MemTypeStr[MEM_STORAGE]}); + hasFatalError = true; + break; + } + + MemDevice const& gpuMem = srcIsStorage ? t.dsts[0] : t.srcs[0]; + MemDevice const& storageMem = srcIsStorage ? t.srcs[0] : t.dsts[0]; + if (gpuMem.memType != MEM_GPU) { + errors.push_back({ERR_FATAL, + "Transfer %d: hipFile executor requires %s to be GPU device memory (%c) instead of (%c)", + i, srcIsStorage ? "DST" : "SRC", MemTypeStr[MEM_GPU], MemTypeStr[gpuMem.memType]}); + hasFatalError = true; + break; + } + + if (t.exeDevice.exeIndex < 0 || t.exeDevice.exeIndex >= numExecutors) { + errors.push_back({ERR_FATAL, + "Transfer %d: hipFile index must be between 0 and %d (instead of %d) for rank %d", + i, numExecutors - 1, t.exeDevice.exeIndex, t.exeDevice.exeRank}); + hasFatalError = true; + break; + } + + if (t.srcs[0].memRank != t.exeDevice.exeRank || t.dsts[0].memRank != t.exeDevice.exeRank) { + errors.push_back({ERR_FATAL, + "Transfer %d: hipFile executor rank (%d) must be same as SRC memory rank (%d) and DST memory rank (%d)", + i, t.exeDevice.exeRank, t.srcs[0].memRank, t.dsts[0].memRank}); + hasFatalError = true; + break; + } + + if (gpuMem.memIndex != t.exeDevice.exeIndex) { + errors.push_back({ERR_FATAL, + "Transfer %d: hipFile executor %d requires GPU memory to be on GPU %d (instead of GPU %d)", + i, t.exeDevice.exeIndex, t.exeDevice.exeIndex, gpuMem.memIndex}); + hasFatalError = true; + break; + } + + if (t.exeSubIndex != -1) { + errors.push_back({ERR_FATAL, "Transfer %d: hipFile executor does not support subindices", i}); + hasFatalError = true; + break; + } + + // Direct I/O between storage and GPU memory requires aligned sizes and offsets + if (t.numBytes % STORAGE_ALIGN_BYTES || cfg.data.byteOffset % STORAGE_ALIGN_BYTES) { + errors.push_back({ERR_WARN, + "Transfer %d: numBytes (%lu) and [data.byteOffset] (%d) are not both multiples of %lu. " + "hipFile will use its compatibility path for unaligned I/O", + i, t.numBytes, cfg.data.byteOffset, STORAGE_ALIGN_BYTES}); + } + + // Raw block devices and files that already hold data are only written to on explicit request + bool isBlockDevice = false; + if (storageMem.memRank == GetRank() && !IsStorageWritable(storageMem.memIndex, &isBlockDevice)) { + std::string const path = GetStoragePath(storageMem.memIndex, storageMem.memRank); + char const* const kind = isBlockDevice ? "a block device" : "an existing file that holds data"; + char const* const allow = isBlockDevice ? "TB_STORAGE_ALLOW_BLOCK_WRITE=1" : "TB_STORAGE_ALLOW_OVERWRITE=1"; + if (dstIsStorage) { + errors.push_back({ERR_FATAL, + "Transfer %d: Storage %d (%s) is %s. Writing to it destroys its contents and " + "requires %s", i, storageMem.memIndex, path.c_str(), kind, allow}); + hasFatalError = true; + break; + } + errors.push_back({ERR_WARN, + "Transfer %d: Storage %d (%s) is %s and is used read-only. Its existing contents are " + "transferred and data validation is skipped. Set %s to allow it " + "to be overwritten with source data", i, storageMem.memIndex, path.c_str(), kind, allow}); + } + break; +#endif + } } } // !isPingpong @@ -3385,6 +4010,16 @@ const auto& AmdSmiFabricInfoV1(const T& info) vector batchBytes; ///< Bytes to copy (per batch item) #endif + // For storage memory (no memory pointer: srcMem / dstMem stay NULL) and the hipFile executor + vector srcStorageFd; ///< File descriptor per SRC (-1 if not local storage memory) + vector dstStorageFd; ///< File descriptor per DST (-1 if not local storage memory) + size_t storageOffset; ///< Offset of this Transfer's region within its storage path + bool fileIsRead; ///< Storage is the SRC (read into GPU memory) instead of the DST + int fileFd; ///< File descriptor of the storage side of the Transfer + char* fileGpuMem; ///< GPU buffer on the other side of the Transfer + void* fileHandle; ///< hipFile handle for the storage side (hipFile executor only) + void* fileRegisteredBuf; ///< GPU buffer registered with hipFile (NULL if none) + // Pingpong role/lap count on this resource half (0 = normal, >0 = ping, <0 = pong) int numLaps = 0; float* partnerFlagMem = nullptr; ///< Partner dst imported onto this executor (cross-rank/pod) @@ -3496,6 +4131,14 @@ const auto& AmdSmiFabricInfoV1(const T& info) bool stop = false; ///< Set at destruction }; + // Unit of work for a hipFile executor I/O thread + struct FileIoTask + { + int rssIdx; ///< Index into resources of the Transfer this task belongs to + size_t byteOffset; ///< Offset of this task within the Transfer + size_t numBytes; ///< Number of bytes this task moves + }; + // Internal resources allocated per Executor struct ExeInfo { @@ -3524,6 +4167,9 @@ const auto& AmdSmiFabricInfoV1(const T& info) // For TDM-Executors uint32_t ldsBytesActual; ///< Actual number of LDS bytes to use as buffer + // For hipFile executors + vector fileTasks; ///< Storage I/O tasks (one per subexecutor with work to do) + // Persistent worker pool servicing this executor's Transfers/subexecutors across all // iterations. Created in PrepareExecutor (NUMA-pinned), destroyed in TeardownExecutor. std::unique_ptr pool; @@ -4822,6 +5468,10 @@ const auto& AmdSmiFabricInfoV1(const T& info) // hold lap flags that no dstReference entry describes if (t.numLaps != 0) continue; + // Read-only storage sources hold whatever was already stored there instead of reference + // data, so there are no expected values to compare against + if (HasReadOnlyStorage(t.srcs)) continue; + float const* expected = dstReference[t.srcs.size()].data(); for (int dstIdx = 0; dstIdx < (int)rss->dstMem.size(); dstIdx++) { // Validation is only done on the rank the destination memory is on @@ -4846,7 +5496,18 @@ const auto& AmdSmiFabricInfoV1(const T& info) transferIdx, dstIdx, t.dsts[dstIdx].memRank, count, firstOff}; } } else { - if (IsCpuMemType(t.dsts[dstIdx].memType) || cfg.data.validateDirect) { + if (IsStorageMemType(t.dsts[dstIdx].memType)) { + // Storage memory has no memory pointer: read the data back from the file instead + size_t const fileOffset = rss->storageOffset + cfg.data.byteOffset; + if (verbose) { + System::Get().Log("[INFO] Validation read: transfer %d DST[%d] %s%d->host %zu bytes offset=%zu dst=%p\n", + transferIdx, dstIdx, + GetMemTypeName(t.dsts[dstIdx].memType), t.dsts[dstIdx].memIndex, + t.numBytes, fileOffset, outputBuffer.data()); + } + ERR_CHECK(StorageCopy(rss->dstStorageFd[dstIdx], false, fileOffset, outputBuffer.data(), t.numBytes)); + output = outputBuffer.data(); + } else if (IsCpuMemType(t.dsts[dstIdx].memType) || cfg.data.validateDirect) { output = (rss->dstMem[dstIdx]) + initOffset; if (verbose) { System::Get().Log("[INFO] Validation: transfer %d DST[%d] direct read from %s%d %zu bytes ptr=%p\n", @@ -4979,14 +5640,22 @@ const auto& AmdSmiFabricInfoV1(const T& info) // Figure out the sub-array each subExecutor works on for this Transfer // - Partition N as evenly as possible, but try to keep subarray sizes as multiples of data.blockBytes // except the very last one, for alignment reasons + // - The hipFile executor instead uses multiples of the storage I/O alignment, as direct + // I/O between storage and GPU memory requires aligned sizes and offsets size_t const N = transfer.numBytes / sizeof(float); int const initOffset = cfg.data.byteOffset / sizeof(float); - int const targetMultiple = cfg.data.blockBytes / sizeof(float); + int const targetMultiple = (IsFileExeType(transfer.exeDevice.exeType) ? (int)STORAGE_ALIGN_BYTES + : cfg.data.blockBytes) / sizeof(float); // In some cases, there may not be enough data for all subExecutors int const maxSubExecToUse = std::min((size_t)(N + targetMultiple - 1) / targetMultiple, (size_t)transfer.numSubExecs); + // Storage memory has no memory pointer, which is kept as NULL instead of being offset + auto offsetPtr = [](float* const base, size_t const offset) -> float* { + return base ? base + offset : nullptr; + }; + vector& subExecParam = rss.subExecParamCpu; subExecParam.clear(); subExecParam.resize(transfer.numSubExecs); @@ -5006,8 +5675,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) p.N = N; p.teamSize = transfer.numSubExecs; p.teamIdx = i; - for (int iSrc = 0; iSrc < p.numSrcs; ++iSrc) p.src[iSrc] = rss.srcMem[iSrc] + initOffset; - for (int iDst = 0; iDst < p.numDsts; ++iDst) p.dst[iDst] = rss.dstMem[iDst] + initOffset; + for (int iSrc = 0; iSrc < p.numSrcs; ++iSrc) p.src[iSrc] = offsetPtr(rss.srcMem[iSrc], initOffset); + for (int iDst = 0; iDst < p.numDsts; ++iDst) p.dst[iDst] = offsetPtr(rss.dstMem[iDst], initOffset); } else { // Otherwise, each subexecutor works on separate subarrays int const subExecLeft = std::max(0, maxSubExecToUse - i); @@ -5017,8 +5686,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) p.N = subExecLeft ? std::min(leftover, ((roundedN / subExecLeft) * targetMultiple)) : 0; p.teamSize = 1; p.teamIdx = 0; - for (int iSrc = 0; iSrc < p.numSrcs; ++iSrc) p.src[iSrc] = rss.srcMem[iSrc] + initOffset + assigned; - for (int iDst = 0; iDst < p.numDsts; ++iDst) p.dst[iDst] = rss.dstMem[iDst] + initOffset + assigned; + for (int iSrc = 0; iSrc < p.numSrcs; ++iSrc) p.src[iSrc] = offsetPtr(rss.srcMem[iSrc], initOffset + assigned); + for (int iDst = 0; iDst < p.numDsts; ++iDst) p.dst[iDst] = offsetPtr(rss.dstMem[iDst], initOffset + assigned); assigned += p.N; } @@ -5140,6 +5809,14 @@ const auto& AmdSmiFabricInfoV1(const T& info) static ErrResult ExchangeMemory(MemDevice const& memDevice, ExeDevice const& exeDevice, size_t* pActualBytes, float** memPtr, hipMemGenericAllocationHandle_t* memHandle) { + // Storage memory has no memory pointer to exchange (it stays NULL on every rank), and its + // file descriptor is only meaningful on the rank that opened it. Only the size is shared + if (IsStorageMemType(memDevice.memType)) { + *memPtr = nullptr; + System::Get().Broadcast(memDevice.memRank, sizeof(*pActualBytes), pActualBytes); + return ERR_NONE; + } + // Pass this pointer to all ranks (Used for pointer arithmetic, not defererenced on non-local ranks) // NOTE: This will be overwritten on executor rank if pod communication is required System::Get().Broadcast(memDevice.memRank, sizeof(*memPtr), memPtr); @@ -5205,6 +5882,132 @@ const auto& AmdSmiFabricInfoV1(const T& info) return ERR_NONE; } +#ifdef HIPFILE_EXEC_ENABLED + // Describes an error returned by hipFile + static std::string HipFileErrorString(hipFileError_t const& err) + { + std::string errMsg = hipFileGetOpErrorString(err.err); + if (err.err == hipFileHipDriverError) + errMsg += std::string(" (") + hipGetErrorString(err.hip_drv_err) + ")"; + return errMsg; + } + + // Opens the hipFile driver on first use. hipFile reads its configuration (HIPFILE_* environment + // variables) at this point, and it applies to the whole process. The driver is never closed, + // as doing so drops every registered file and it may still be needed by subsequent tests + static ErrResult OpenHipFileDriver() + { + static std::mutex driverMutex; + static bool driverIsOpen = false; + + std::lock_guard lock(driverMutex); + if (driverIsOpen) return ERR_NONE; + + hipFileError_t err = hipFileDriverOpen(); + if (err.err != hipFileSuccess) { + return {ERR_FATAL, "Unable to open hipFile driver: %s", HipFileErrorString(err).c_str()}; + } + driverIsOpen = true; + return ERR_NONE; + } + + // Returns the hipFile handle for an open storage index, registering it on first use. + // hipFile refuses to register a file descriptor twice, so all Transfers using a storage index + // share one handle (deregistered by CloseStorage once the last of them is done) + static ErrResult GetStorageFileHandle(int const storageIndex, void*& fileHandle) + { + std::lock_guard lock(GetStorageMutex()); + std::vector& storageList = GetStorageDeviceList(); + if (storageIndex < 0 || storageIndex >= (int)storageList.size() || storageList[storageIndex].fd < 0) { + return {ERR_FATAL, "Unable to register storage %d with hipFile as it is not open", storageIndex}; + } + + StorageDevice& dev = storageList[storageIndex]; + if (dev.fileHandle == nullptr) { + hipFileDescr_t descr = {}; + descr.type = hipFileHandleTypeOpaqueFD; + descr.handle.fd = dev.fd; + hipFileError_t err = hipFileHandleRegister(&dev.fileHandle, &descr); + if (err.err != hipFileSuccess) { + dev.fileHandle = nullptr; + return {ERR_FATAL, "Unable to register storage %d (%s) with hipFile: %s", + storageIndex, dev.path.c_str(), HipFileErrorString(err).c_str()}; + } + } + fileHandle = dev.fileHandle; + return ERR_NONE; + } + + // Returns the version of the hipFile library in use as "major.minor.patch" + static std::string HipFileVersionString() + { + unsigned major = 0, minor = 0, patch = 0; + if (hipFileGetVersion(&major, &minor, &patch).err != hipFileSuccess) return ""; + return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); + } +#endif + +#if !defined(__NVCC__) + // Prepares hipFile specific resources for a Transfer (after its memory has been set up) + static ErrResult PrepareFileTransferResources(ExeDevice const& exeDevice, + Transfer const& t, + TransferResources& rss) + { + // Validation guarantees exactly one SRC and one DST, one of which is storage memory + rss.fileIsRead = IsStorageMemType(t.srcs[0].memType); + rss.fileFd = rss.fileIsRead ? rss.srcStorageFd[0] : rss.dstStorageFd[0]; + rss.fileGpuMem = (char*)(rss.fileIsRead ? rss.dstMem[0] : rss.srcMem[0]); + rss.fileHandle = nullptr; + rss.fileRegisteredBuf = nullptr; + + [[maybe_unused]] int const storageIndex = rss.fileIsRead ? t.srcs[0].memIndex : t.dsts[0].memIndex; + [[maybe_unused]] size_t const gpuBytes = rss.fileIsRead ? rss.dstActualBytes[0] : rss.srcActualBytes[0]; + [[maybe_unused]] bool const verbose = System::Get().IsVerbose(); + +#ifdef HIPFILE_EXEC_ENABLED + ERR_CHECK(OpenHipFileDriver()); + ERR_CHECK(GetStorageFileHandle(storageIndex, rss.fileHandle)); + + // Registering the GPU buffer is optional: it saves hipFile from looking the buffer up on + // every I/O. TB_HIPFILE_SKIP_BUF_REGISTER=1 leaves the buffer unregistered + char const* skipRegister = getenv("TB_HIPFILE_SKIP_BUF_REGISTER"); + if (!(skipRegister && !strcmp(skipRegister, "1"))) { + ERR_CHECK(hipSetDevice(exeDevice.exeIndex)); + hipFileError_t err = hipFileBufRegister(rss.fileGpuMem, gpuBytes, 0); + if (err.err == hipFileSuccess) { + rss.fileRegisteredBuf = rss.fileGpuMem; + } else if (verbose) { + System::Get().Log("[INFO] GPU buffer %p not registered with hipFile: %s\n", + rss.fileGpuMem, HipFileErrorString(err).c_str()); + } + } + if (verbose) { + System::Get().Log("[INFO] hipFile %s: storage %d handle=%p GPU buffer %p (%zu bytes, %s)\n", + rss.fileIsRead ? "read" : "write", storageIndex, rss.fileHandle, rss.fileGpuMem, + gpuBytes, rss.fileRegisteredBuf ? "registered" : "not registered"); + } + return ERR_NONE; +#else + return {ERR_FATAL, "hipFile executor is not supported as TransferBench was built without hipFile support"}; +#endif + } + + // Releases hipFile specific resources for a Transfer (before its memory is freed) + static void TeardownFileTransferResources(TransferResources& rss) + { +#ifdef HIPFILE_EXEC_ENABLED + if (rss.fileRegisteredBuf) { + hipFileError_t err = hipFileBufDeregister(rss.fileRegisteredBuf); + if (err.err != hipFileSuccess && System::Get().IsVerbose()) { + System::Get().Log("[INFO] Unable to deregister GPU buffer %p from hipFile: %s\n", + rss.fileRegisteredBuf, HipFileErrorString(err).c_str()); + } + } +#endif + rss.fileRegisteredBuf = nullptr; + } +#endif + // Prepare each executor // Allocates memory for src/dst, prepares subexecutors, executor-specific data structures static ErrResult PrepareExecutor(ConfigOptions const& cfg, @@ -5223,8 +6026,10 @@ const auto& AmdSmiFabricInfoV1(const T& info) exeInfo.transferRssIdx.push_back(r); // Executor BDF and NUMA are constant across all transfers — compute once - std::string exeBdf = IsGpuExeType(exeDevice.exeType) ? GetGpuBdf(exeDevice.exeIndex) : ""; - int exeNuma = IsGpuExeType(exeDevice.exeType) + // (The hipFile executor is indexed by the GPU whose memory it reads into / writes from) + bool const exeIsOnGpu = IsGpuExeType(exeDevice.exeType) || IsFileExeType(exeDevice.exeType); + std::string exeBdf = exeIsOnGpu ? GetGpuBdf(exeDevice.exeIndex) : ""; + int exeNuma = exeIsOnGpu ? GetClosestCpuNumaToGpu(exeDevice.exeIndex, exeDevice.exeRank) : IsNicExeType(exeDevice.exeType) ? GetClosestCpuNumaToNic(exeDevice.exeIndex, exeDevice.exeRank) @@ -5257,6 +6062,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) rss.srcMem.resize(srcs.size()); rss.srcActualBytes.resize(srcs.size()); rss.srcMemHandle.resize(srcs.size(), NULL); + rss.srcStorageFd.assign(srcs.size(), -1); for (int iSrc = 0; iSrc < srcs.size(); ++iSrc) { MemDevice const& srcMemDevice = srcs[iSrc]; size_t srcAllocBytes = t.numBytes + cfg.data.byteOffset; @@ -5279,7 +6085,20 @@ const auto& AmdSmiFabricInfoV1(const T& info) // Allocate source memory (on the correct rank) bool requiresFabricHandle = (srcMemDevice.memRank != exeDevice.exeRank) && IsGpuExeType(exeDevice.exeType); - if (srcMemDevice.memRank == localRank) { + if (IsStorageMemType(srcMemDevice.memType)) { + // Storage memory is opened instead of allocated, and has no memory pointer + if (srcMemDevice.memRank == localRank) { + if (verbose) { + System::Get().Log("[INFO] SRC[%d]: %s idx=%d (Rank %d) %s %zu bytes at offset %zu\n", + iSrc, GetMemTypeName(srcMemDevice.memType), srcMemDevice.memIndex, + srcMemDevice.memRank, + GetStoragePath(srcMemDevice.memIndex, srcMemDevice.memRank).c_str(), + srcAllocBytes, rss.storageOffset); + } + ERR_CHECK(OpenStorage(srcMemDevice.memIndex, rss.storageOffset + srcAllocBytes, rss.srcStorageFd[iSrc])); + rss.srcActualBytes[iSrc] = srcAllocBytes; + } + } else if (srcMemDevice.memRank == localRank) { if (verbose) { std::string bdf = IsGpuMemType(srcMemDevice.memType) ? GetGpuBdf(srcMemDevice.memIndex) : ""; System::Get().Log("[INFO] SRC[%d]: %s idx=%d NUMA=%s%s%s (Rank %d) %zu bytes%s\n", @@ -5318,6 +6137,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) rss.dstMem.resize(dsts.size()); rss.dstActualBytes.resize(dsts.size()); rss.dstMemHandle.resize(dsts.size(), NULL); + rss.dstStorageFd.assign(dsts.size(), -1); for (int iDst = 0; iDst < dsts.size(); ++iDst) { MemDevice const& dstMemDevice = dsts[iDst]; @@ -5346,7 +6166,20 @@ const auto& AmdSmiFabricInfoV1(const T& info) if (IsGpuExeType(partnerExe.exeType) && partnerExe.exeRank != dstMemDevice.memRank) requiresFabricHandle = true; } - if (dstMemDevice.memRank == localRank) { + if (IsStorageMemType(dstMemDevice.memType)) { + // Storage memory is opened instead of allocated, and has no memory pointer + if (dstMemDevice.memRank == localRank) { + if (verbose) { + System::Get().Log("[INFO] DST[%d]: %s idx=%d (Rank %d) %s %zu bytes at offset %zu\n", + iDst, GetMemTypeName(dstMemDevice.memType), dstMemDevice.memIndex, + dstMemDevice.memRank, + GetStoragePath(dstMemDevice.memIndex, dstMemDevice.memRank).c_str(), + dstAllocBytes, rss.storageOffset); + } + ERR_CHECK(OpenStorage(dstMemDevice.memIndex, rss.storageOffset + dstAllocBytes, rss.dstStorageFd[iDst])); + rss.dstActualBytes[iDst] = dstAllocBytes; + } + } else if (dstMemDevice.memRank == localRank) { if (verbose) { std::string bdf = IsGpuMemType(dstMemDevice.memType) ? GetGpuBdf(dstMemDevice.memIndex) : ""; System::Get().Log("[INFO] DST[%d]: %s idx=%d NUMA=%s%s%s (Rank %d) %zu bytes%s\n", @@ -5574,6 +6407,28 @@ const auto& AmdSmiFabricInfoV1(const T& info) } } + // Prepare for the hipFile executor + if (IsFileExeType(exeDevice.exeType) && exeDevice.exeRank == localRank) { +#if defined(__NVCC__) + return {ERR_FATAL, "hipFile executor is not supported on NVIDIA hardware"}; +#else + exeInfo.fileTasks.clear(); + for (int rssIdx = 0; rssIdx < (int)exeInfo.resources.size(); rssIdx++) { + TransferResources& rss = exeInfo.resources[rssIdx]; + Transfer const& t = transfers[rss.transferIdx]; + ERR_CHECK(PrepareFileTransferResources(exeDevice, t, rss)); + + // Each subexecutor is an I/O thread that works on its own part of the Transfer + size_t byteOffset = 0; + for (auto const& p : rss.subExecParamCpu) { + size_t const numBytes = p.N * sizeof(float); + if (numBytes) exeInfo.fileTasks.push_back({rssIdx, byteOffset, numBytes}); + byteOffset += numBytes; + } + } +#endif + } + // Check that GPU wallclock rate is non-zero (GFX and TDM both use it for in-kernel cycle timing) if ((exeDevice.exeType == EXE_GPU_GFX || exeDevice.exeType == EXE_GPU_TDM) && exeInfo.wallClockRate == 0 && exeDevice.exeRank == localRank) { @@ -5608,6 +6463,16 @@ const auto& AmdSmiFabricInfoV1(const T& info) if (physNode >= 0) numa_run_on_node(physNode); (void)hipSetDevice(exeIndex); })); + } else if (IsFileExeType(exeDevice.exeType)) { + // One thread per subexecutor, as each issues blocking I/O calls. hipFile acts on + // the calling thread's current device, so every thread is bound to the executor's GPU + int const numThreads = std::max(1, (int)exeInfo.fileTasks.size()); + int const exeIndex = exeDevice.exeIndex; + int const physNode = (exeNuma >= 0) ? System::Get().GetCpuPhysicalNode(exeNuma) : -1; + exeInfo.pool.reset(new ThreadPool(numThreads, [physNode, exeIndex] { + if (physNode >= 0) numa_run_on_node(physNode); + (void)hipSetDevice(exeIndex); + })); } } @@ -5736,9 +6601,26 @@ const auto& AmdSmiFabricInfoV1(const T& info) rss.numLaps > 0 ? " (ping)" : rss.numLaps < 0 ? " (pong)" : ""); } +#if !defined(__NVCC__) + // Release hipFile related resources (before the GPU buffers they refer to are freed) + if (IsFileExeType(exeDevice.exeType) && exeDevice.exeRank == localRank) { + TeardownFileTransferResources(rss); + } +#endif + // Deallocate source memory for (int iSrc = 0; iSrc < (int)srcs.size(); ++iSrc) { - if (srcs[iSrc].memRank == localRank) { + if (IsStorageMemType(srcs[iSrc].memType)) { + // Storage memory is closed instead of deallocated (only if this rank managed to open it) + if (iSrc < (int)rss.srcStorageFd.size() && rss.srcStorageFd[iSrc] >= 0) { + if (verbose) { + System::Get().Log("[INFO] Close SRC[%d]: %s idx=%d\n", + iSrc, GetMemTypeName(srcs[iSrc].memType), srcs[iSrc].memIndex); + } + ERR_CHECK(CloseStorage(srcs[iSrc].memIndex)); + rss.srcStorageFd[iSrc] = -1; + } + } else if (srcs[iSrc].memRank == localRank) { if (verbose) { System::Get().Log("[INFO] Free SRC[%d]: %s idx=%d %p (%zu bytes)\n", iSrc, GetMemTypeName(srcs[iSrc].memType), @@ -5762,7 +6644,17 @@ const auto& AmdSmiFabricInfoV1(const T& info) // Deallocate destination memory for (int iDst = 0; iDst < (int)dsts.size(); ++iDst) { - if (dsts[iDst].memRank == localRank) { + if (IsStorageMemType(dsts[iDst].memType)) { + // Storage memory is closed instead of deallocated (only if this rank managed to open it) + if (iDst < (int)rss.dstStorageFd.size() && rss.dstStorageFd[iDst] >= 0) { + if (verbose) { + System::Get().Log("[INFO] Close DST[%d]: %s idx=%d\n", + iDst, GetMemTypeName(dsts[iDst].memType), dsts[iDst].memIndex); + } + ERR_CHECK(CloseStorage(dsts[iDst].memIndex)); + rss.dstStorageFd[iDst] = -1; + } + } else if (dsts[iDst].memRank == localRank) { if (verbose) { System::Get().Log("[INFO] Free DST[%d]: %s idx=%d %p (%zu bytes)\n", iDst, GetMemTypeName(dsts[iDst].memType), @@ -5854,6 +6746,61 @@ const auto& AmdSmiFabricInfoV1(const T& info) return ERR_NONE; } + // Best-effort release of what a local hipFile executor holds, for a Test that is + // abandoned after a failure and so never reaches TeardownExecutor. Open storage paths and + // hipFile registrations outlive a Test, so they (and the GPU buffers) would otherwise stay held + // for the rest of the process. Tolerates an executor that was only partially prepared + static void AbandonFileExecutor(ExeDevice const& exeDevice, + vector const& transfers, + ExeInfo& exeInfo) + { +#if !defined(__NVCC__) + if (!IsFileExeType(exeDevice.exeType) || exeDevice.exeRank != GetRank()) return; + + exeInfo.pool.reset(); + for (auto& rss : exeInfo.resources) { + Transfer const& t = transfers[rss.transferIdx]; + if (System::Get().IsVerbose()) { + System::Get().Log("[INFO] Rank %d releasing resources of failed transfer %d\n", GetRank(), rss.transferIdx); + } + TeardownFileTransferResources(rss); + + for (int isDst = 0; isDst <= 1; isDst++) { + vector const& mems = isDst ? t.dsts : t.srcs; + vector& storageFds = isDst ? rss.dstStorageFd : rss.srcStorageFd; + vector& memPtrs = isDst ? rss.dstMem : rss.srcMem; + vector& memBytes = isDst ? rss.dstActualBytes : rss.srcActualBytes; + vector& expected = isDst ? rss.dstExpectedMem : rss.srcExpectedMem; + vector& expBytes = isDst ? rss.dstExpectedBytes : rss.srcExpectedBytes; + auto& scratch = isDst ? rss.dstValidateScratch : rss.srcValidateScratch; + + for (size_t i = 0; i < mems.size(); i++) { + if (IsStorageMemType(mems[i].memType)) { + if (i < storageFds.size() && storageFds[i] >= 0) { + (void)CloseStorage(mems[i].memIndex); + storageFds[i] = -1; + } + continue; + } + MemType const memType = mems[i].memType; + if (i < memPtrs.size() && i < memBytes.size() && memPtrs[i]) { + (void)DeallocateMemory(memType, memPtrs[i], memBytes[i]); + memPtrs[i] = nullptr; + } + if (i < expected.size() && i < expBytes.size() && expected[i]) { + (void)DeallocateMemory(memType, expected[i], expBytes[i]); + expected[i] = nullptr; + } + if (i < scratch.size() && scratch[i]) { + (void)DeallocateMemory(memType, scratch[i], 2 * sizeof(unsigned long long)); + scratch[i] = nullptr; + } + } + } + } +#endif + } + // PingPong Wait primitives //======================================================================================== @@ -7248,6 +8195,179 @@ const auto& AmdSmiFabricInfoV1(const T& info) } #endif // BMA_EXEC_ENABLED +// hipFile Executor-related functions +//======================================================================================== +#if !defined(__NVCC__) + // Moves one subexecutor's share of a Transfer between storage and GPU memory + static ErrResult ExecuteFileTask(ConfigOptions const& cfg, + TransferResources const& rss, + FileIoTask const& task) + { + char const* const opName = rss.fileIsRead ? "read" : "write"; + + // Data is laid out identically in the GPU buffer and in this Transfer's region of storage + size_t const gpuOffset = cfg.data.byteOffset + task.byteOffset; + size_t const fileOffset = rss.storageOffset + gpuOffset; + + // A single call moves a limited number of bytes and may move fewer than requested + size_t done = 0; + while (done < task.numBytes) { + [[maybe_unused]] size_t const numBytes = std::min(task.numBytes - done, STORAGE_MAX_IO_BYTES); + size_t moved = 0; + +#ifdef HIPFILE_EXEC_ENABLED + ssize_t const ret = rss.fileIsRead + ? hipFileRead (rss.fileHandle, rss.fileGpuMem, numBytes, fileOffset + done, gpuOffset + done) + : hipFileWrite(rss.fileHandle, rss.fileGpuMem, numBytes, fileOffset + done, gpuOffset + done); + if (ret == -1) { + return {ERR_FATAL, "Transfer %d: hipFile %s of %lu bytes at offset %lu failed: %s", + rss.transferIdx, opName, numBytes, fileOffset + done, strerror(errno)}; + } else if (ret < 0) { + // Other negative values are either a negated hipFile error or a negated HIP error + std::string errMsg; + if (-ret > HIPFILE_BASE_ERR) { + errMsg = hipFileGetOpErrorString((hipFileOpError_t)(-ret)); + if (-ret == hipFileHipDriverError) + errMsg += std::string(" (") + hipGetErrorString(hipGetLastError()) + ")"; + } else { + // The HIP runtime rejected direct I/O, which hipFile does not retry on its compatibility path + errMsg = std::string("HIP Error: ") + hipGetErrorString((hipError_t)(-ret)) + + ". hipFile's fastpath may not be usable here (HIPFILE_FORCE_COMPAT_MODE=true selects" + " its compatibility path instead)"; + } + return {ERR_FATAL, "Transfer %d: hipFile %s of %lu bytes at offset %lu failed (%ld): %s", + rss.transferIdx, opName, numBytes, fileOffset + done, (long)ret, errMsg.c_str()}; + } + moved = ret; +#else + return {ERR_FATAL, "hipFile executor is not supported as TransferBench was built without hipFile support"}; +#endif + + if (moved == 0) { + return {ERR_FATAL, "Transfer %d: hipFile %s unexpectedly moved no data at offset %lu", + rss.transferIdx, opName, fileOffset + done}; + } + done += moved; + } + return ERR_NONE; + } + + // Execution of a single hipFile executor + static ErrResult RunFileExecutor(int const iteration, + ConfigOptions const& cfg, + int const exeIndex, + ExeInfo& exeInfo) + { + using Clock = std::chrono::high_resolution_clock; + + int const numTasks = (int)exeInfo.fileTasks.size(); + int const numRss = (int)exeInfo.resources.size(); + + std::vector taskErr(numTasks); + std::vector taskStop(numTasks); + std::vector rssMsec(numRss, 0.0); + double exeMsec = 0.0; + + int subIterations = 0; + do { + // Only the I/O itself is timed + auto const cpuStart = Clock::now(); + + exeInfo.pool->ParallelFor(numTasks, [&](int i) { + FileIoTask const& task = exeInfo.fileTasks[i]; + taskErr[i] = ExecuteFileTask(cfg, exeInfo.resources[task.rssIdx], task); + taskStop[i] = Clock::now(); + }); + for (auto& e : taskErr) ERR_CHECK(e); + + // A Transfer is complete once the last of its subexecutors is + std::vector rssStop(numRss, cpuStart); + for (int i = 0; i < numTasks; i++) { + int const rssIdx = exeInfo.fileTasks[i].rssIdx; + rssStop[rssIdx] = std::max(rssStop[rssIdx], taskStop[i]); + } + for (int rssIdx = 0; rssIdx < numRss; rssIdx++) + rssMsec[rssIdx] += std::chrono::duration_cast>(rssStop[rssIdx] - cpuStart).count() * 1000.0; + + auto const cpuDelta = Clock::now() - cpuStart; + exeMsec += std::chrono::duration_cast>(cpuDelta).count() * 1000.0; + } while (++subIterations != cfg.general.numSubIterations); + + if (iteration >= 0) { + exeInfo.totalDurationMsec += exeMsec / cfg.general.numSubIterations; + for (int rssIdx = 0; rssIdx < numRss; rssIdx++) { + TransferResources& rss = exeInfo.resources[rssIdx]; + double const deltaMsec = rssMsec[rssIdx] / cfg.general.numSubIterations; + rss.totalDurationMsec += deltaMsec; + if (cfg.general.recordPerIteration) + rss.perIterMsec.push_back(deltaMsec); + } + } + return ERR_NONE; + } +#endif + +#ifdef HIPFILE_EXEC_ENABLED + // Number of hipFile I/Os performed per GPU on each I/O path (since the driver was opened) + struct HipFileIoCounts + { + std::vector fastpath; + std::vector compat; + }; + + // Collects per-GPU hipFile I/O counts. Returns false if hipFile cannot provide them + static bool GetHipFileIoCounts(HipFileIoCounts& counts) + { + counts = {}; + + // hipFile provides I/O statistics since version 0.5.0 +#if HIPFILE_VERSION_MAJOR > 0 || HIPFILE_VERSION_MINOR >= 5 + // Leave slack after the structure in case a newer hipFile fills in more than the layout + // TransferBench was built against + std::vector buffer((sizeof(hipFileStatsLevel3_t) + 65536) / sizeof(uint64_t), 0); + hipFileStatsLevel3_t* stats = (hipFileStatsLevel3_t*)buffer.data(); + hipFileError_t err = hipFileGetStatsL3(stats); + if (err.err != hipFileSuccess || stats->num_gpus > HIPFILE_MAX_GPUS) return false; + + for (int i = 0; i < HIPFILE_MAX_GPUS; i++) { + hipFilePerGpuStats_t const& gpuStats = stats->per_gpu_stats[i]; + counts.fastpath.push_back(gpuStats.n_nvfs_reads + gpuStats.n_nvfs_writes); + counts.compat.push_back (gpuStats.n_posix_reads + gpuStats.n_posix_writes); + } + return true; +#else + return false; +#endif + } + + // Determines which I/O path hipFile used on a GPU between two sets of I/O counts + static IoPathType GetHipFileIoPath(HipFileIoCounts const& before, + HipFileIoCounts const& after, + int const gpuIndex) + { + int const numGpus = (int)std::min(before.fastpath.size(), after.fastpath.size()); + + uint64_t fastpath = 0, compat = 0; + if (gpuIndex >= 0 && gpuIndex < numGpus) { + fastpath = after.fastpath[gpuIndex] - before.fastpath[gpuIndex]; + compat = after.compat[gpuIndex] - before.compat[gpuIndex]; + } + + // hipFile may number GPUs differently. If nothing was counted for this GPU, go by the totals + if (fastpath == 0 && compat == 0) { + for (int i = 0; i < numGpus; i++) { + fastpath += after.fastpath[i] - before.fastpath[i]; + compat += after.compat[i] - before.compat[i]; + } + } + + if (fastpath && compat) return IO_PATH_MIXED; + if (fastpath) return IO_PATH_FASTPATH; + if (compat) return IO_PATH_COMPAT; + return IO_PATH_UNKNOWN; + } +#endif + // TDM Executor-related functions //======================================================================================== #if TDM_SUPPORTED @@ -7466,6 +8586,9 @@ const auto& AmdSmiFabricInfoV1(const T& info) case EXE_NIC: return RunNicExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo); #ifdef BMA_EXEC_ENABLED case EXE_GPU_BDMA: return RunBmaExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo); +#endif +#if !defined(__NVCC__) + case EXE_GPU_HIPFILE: return RunFileExecutor(iteration, cfg, exeDevice.exeIndex, exeInfo); #endif default: return {ERR_FATAL, "Unsupported executor (%d)", exeDevice.exeType}; } @@ -7595,6 +8718,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) int maxNumSrcs = 0; size_t maxNumBytes = 0; std::map executorMap; + std::map, size_t> storageBytesUsed; for (int i = 0; i < transfers.size(); i++) { Transfer const& t = transfers[i]; ExeDevice exeDevice; @@ -7604,6 +8728,17 @@ const auto& AmdSmiFabricInfoV1(const T& info) resource.transferIdx = i; resource.numLaps = t.numLaps; + // Each Transfer gets its own (aligned) region of the storage path it uses, so that + // Transfers sharing a storage path do not overwrite each other's data + for (auto const* memList : {&t.srcs, &t.dsts}) { + for (auto const& mem : *memList) { + if (!IsStorageMemType(mem.memType)) continue; + size_t& bytesUsed = storageBytesUsed[{mem.memRank, mem.memIndex}]; + resource.storageOffset = bytesUsed; + bytesUsed += AlignUp(t.numBytes + cfg.data.byteOffset, STORAGE_ALIGN_BYTES); + } + } + bool isPingpong = t.numLaps != 0; ExeInfo& exeInfo = executorMap[exeDevice]; @@ -7647,6 +8782,21 @@ const auto& AmdSmiFabricInfoV1(const T& info) int const localRank = GetRank(); vector localExecutors; vector transferResources; + + // The failure exits from here on return before the executors are torn down + struct FileExecutorCleanup + { + std::map& executorMap; + vector const& transfers; + bool isNeeded; + ~FileExecutorCleanup() + { + if (!isNeeded) return; + for (auto& exeInfoPair : executorMap) + AbandonFileExecutor(exeInfoPair.first, transfers, exeInfoPair.second); + } + } fileExecutorCleanup{executorMap, transfers, true}; + for (auto& exeInfoPair : executorMap) { ExeDevice const& exeDevice = exeInfoPair.first; ExeInfo& exeInfo = exeInfoPair.second; @@ -7694,14 +8844,63 @@ const auto& AmdSmiFabricInfoV1(const T& info) for (int numSrcs = 0; numSrcs < minNumSrcs; numSrcs++) dstReference[numSrcs].clear(); - // Initialize all src memory buffers (if on local rank) bool const verbose = System::Get().IsVerbose(); + + // Storage keeps its contents between runs (memory destinations are zeroed when allocated), + // so clear storage destinations to make sure validation only passes on data this run delivered + if (validateEnabled) { + for (auto resource : transferResources) { + Transfer const& t = transfers[resource->transferIdx]; + if (t.numLaps != 0) continue; + for (int dstIdx = 0; dstIdx < (int)resource->dstStorageFd.size(); dstIdx++) { + MemDevice const& md = t.dsts[dstIdx]; + if (md.memRank != localRank || !IsStorageMemType(md.memType)) continue; + size_t const fileOffset = resource->storageOffset + cfg.data.byteOffset; + if (verbose) { + System::Get().Log("[INFO] Data prep clear: transfer %d DST[%d] %s%d %zu bytes offset=%zu\n", + resource->transferIdx, dstIdx, GetMemTypeName(md.memType), md.memIndex, + resource->numBytes, fileOffset); + } + ERR_APPEND(ClearStorage(resource->dstStorageFd[dstIdx], fileOffset, resource->numBytes), errResults); + } + } + } + + // Initialize all src memory buffers (if on local rank) for (auto resource : transferResources) { Transfer const& t = transfers[resource->transferIdx]; // Ping and Pong will start with src value of 0 if (t.numLaps != 0) continue; for (int srcIdx = 0; srcIdx < resource->srcMem.size(); srcIdx++) { if (t.srcs[srcIdx].memRank == localRank) { + // Storage memory has no memory pointer: source data is written to the file instead + if (IsStorageMemType(t.srcs[srcIdx].memType)) { + MemDevice const& md = t.srcs[srcIdx]; + + // Read-only storage (e.g. block devices by default) keeps its existing contents + if (!IsStorageWritable(md.memIndex)) continue; + + int const fd = resource->srcStorageFd[srcIdx]; + size_t const fileOffset = resource->storageOffset + cfg.data.byteOffset; + if (verbose) { + System::Get().Log("[INFO] Data prep write: transfer %d SRC[%d] host->%s%d %zu bytes offset=%zu src=%p\n", + resource->transferIdx, srcIdx, + GetMemTypeName(md.memType), md.memIndex, + resource->numBytes, fileOffset, srcReference[srcIdx].data()); + } + ERR_APPEND(StorageCopy(fd, true, fileOffset, srcReference[srcIdx].data(), resource->numBytes), errResults); + + // Optionally validate source storage right after preparation + if (cfg.data.validateSource) { + vector tmp(resource->numBytes / sizeof(float)); + ERR_APPEND(StorageCopy(fd, false, fileOffset, tmp.data(), resource->numBytes), errResults); + if (memcmp(tmp.data(), srcReference[srcIdx].data(), resource->numBytes)) + ERR_APPEND((ErrResult{ERR_FATAL, "Transfer %d: Source %d mismatch after prep", + resource->transferIdx, srcIdx}), errResults); + } + continue; + } + if (IsGpuMemType(t.srcs[srcIdx].memType)) { ERR_APPEND(hipSetDevice(t.srcs[srcIdx].memIndex), errResults); } @@ -7801,8 +9000,9 @@ const auto& AmdSmiFabricInfoV1(const T& info) char const* halfStr = rss->numLaps == 0 ? "" : isPong ? " (pong)" : " (ping)"; // Executor info - std::string exeBdf = IsGpuExeType(exe.exeType) ? GetGpuBdf(exe.exeIndex) : ""; - int exeNuma = IsGpuExeType(exe.exeType) + bool const exeIsOnGpu = IsGpuExeType(exe.exeType) || IsFileExeType(exe.exeType); + std::string exeBdf = exeIsOnGpu ? GetGpuBdf(exe.exeIndex) : ""; + int exeNuma = exeIsOnGpu ? System::Get().GetClosestCpuNumaToGpu(exe.exeIndex, exe.exeRank) : IsNicExeType(exe.exeType) ? System::Get().GetClosestCpuNumaToNic(exe.exeIndex, exe.exeRank) @@ -7855,6 +9055,17 @@ const auto& AmdSmiFabricInfoV1(const T& info) ThreadPool executorPool((int)localExecutors.size()); std::vector exeErrors(localExecutors.size()); +#ifdef HIPFILE_EXEC_ENABLED + // hipFile decides per I/O whether to use its fastpath or its compatibility path. Compare its + // I/O counters before and after the Transfers to report which one was actually taken + bool hasHipFileExecutor = false; + for (auto const& exeDevice : localExecutors) + hasHipFileExecutor |= (exeDevice.exeType == EXE_GPU_HIPFILE); + bool hasIoCounts = false; + HipFileIoCounts ioCountsBefore, ioCountsAfter; + if (hasHipFileExecutor) hasIoCounts = GetHipFileIoCounts(ioCountsBefore); +#endif + size_t numTimedIterations = 0; double totalCpuTimeSec = 0.0; for (int iteration = -cfg.general.numWarmups; ; iteration++) { @@ -7935,6 +9146,12 @@ const auto& AmdSmiFabricInfoV1(const T& info) Transfer const& t = transfers[rss->transferIdx]; for (int dstIdx = 0; dstIdx < (int)rss->dstMem.size(); dstIdx++) { if (t.dsts[dstIdx].memRank != localRank) continue; + if (IsStorageMemType(t.dsts[dstIdx].memType)) { + // Storage memory has no memory pointer: zero this Transfer's region of the file instead + ERR_APPEND(ClearStorage(rss->dstStorageFd[dstIdx], rss->storageOffset + cfg.data.byteOffset, + rss->numBytes), errResults); + continue; + } float* dstPtr = rss->dstMem[dstIdx] + initOffset; if (IsCpuMemType(t.dsts[dstIdx].memType)) { memset(dstPtr, 0, rss->numBytes); @@ -7953,6 +9170,10 @@ const auto& AmdSmiFabricInfoV1(const T& info) } } +#ifdef HIPFILE_EXEC_ENABLED + if (hasIoCounts) hasIoCounts = GetHipFileIoCounts(ioCountsAfter); +#endif + // Interactive per-transfer PASS/FAIL display (skipped when validation disabled). This does its // own comparison pass to show results; authoritative error reporting still comes from // ValidateAllTransfers (mode 0) or the inline per-iteration validation (mode >0). @@ -7992,6 +9213,12 @@ const auto& AmdSmiFabricInfoV1(const T& info) continue; } + // Read-only storage sources were not filled with reference data + if (HasReadOnlyStorage(t.srcs)) { + System::Get().Log(" Transfer %03d: SKIP(read-only storage source)\n", transferIdx); + continue; + } + float const* expected = dstReference[t.srcs.size()].data(); bool transferOk = true; bool anyLocalDst = false; @@ -8017,7 +9244,12 @@ const auto& AmdSmiFabricInfoV1(const T& info) continue; } float* output; - if (IsCpuMemType(t.dsts[dstIdx].memType) || cfg.data.validateDirect) { + if (IsStorageMemType(t.dsts[dstIdx].memType)) { + // Storage memory has no memory pointer: read the data back from the file instead + (void)StorageCopy(rss->dstStorageFd[dstIdx], false, rss->storageOffset + cfg.data.byteOffset, + outputBuffer.data(), t.numBytes); + output = outputBuffer.data(); + } else if (IsCpuMemType(t.dsts[dstIdx].memType) || cfg.data.validateDirect) { output = rss->dstMem[dstIdx] + initOffset; } else { (void)hipSetDevice(t.dsts[dstIdx].memIndex); @@ -8078,6 +9310,20 @@ const auto& AmdSmiFabricInfoV1(const T& info) exeResult.sumBandwidthGbPerSec = 0.0; exeResult.transferIdx.clear(); + // Determine how this executor moved data to / from storage + IoPathType ioPath = IO_PATH_NONE; + if (exeDevice.exeType == EXE_GPU_HIPFILE) { + ioPath = IO_PATH_UNKNOWN; +#ifdef HIPFILE_EXEC_ENABLED + if (hasIoCounts) ioPath = GetHipFileIoPath(ioCountsBefore, ioCountsAfter, exeDevice.exeIndex); +#endif + } + if (ioPath != IO_PATH_NONE && System::Get().IsVerbose()) { + System::Get().Log("[INFO] Executor (R%d%c%d) storage I/O path: %s\n", + exeDevice.exeRank, ExeTypeStr[exeDevice.exeType], exeDevice.exeIndex, + IoPathTypeStr[ioPath]); + } + // Copy over transfer results (ping half owns pingpong latency) for (auto const& rss : exeInfo.resources) { if (rss.numLaps < 0) continue; // skip pong half — ping owns the result row @@ -8091,6 +9337,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) TransferResult& tfrResult = results.tfrResults[transferIdx]; tfrResult.exeDevice = exeDevice; tfrResult.exeDstDevice = {exeDevice.exeType, rss.dstNicIndex}; + tfrResult.ioPath = ioPath; tfrResult.numBytes = reportedBytes; tfrResult.avgDurationMsec = rss.totalDurationMsec / numTimedIterations; tfrResult.avgBandwidthGbPerSec = reportedBytes ? (reportedBytes / 1.0e6) / tfrResult.avgDurationMsec @@ -8118,6 +9365,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) : 0.0; // Teardown executors + fileExecutorCleanup.isNeeded = false; for (auto& exeInfoPair : executorMap) { ExeDevice const& exeDevice = exeInfoPair.first; ExeInfo& exeInfo = exeInfoPair.second; @@ -8203,7 +9451,16 @@ const auto& AmdSmiFabricInfoV1(const T& info) } else if (wc.mem[isDst][iMem].memIndices.size() == 1 && wc.mem[isDst][iMem].memIndices[0] == -1) { // Wildcard - loop over all possible device indices for this memory type int numExecutors = GetNumExecutors(wc.mem[isDst][iMem].memType, wc.mem[isDst][iMem].memRanks[0]); + + // The hipFile executor only accesses the memory of its own GPU, so GPU memory follows the executor + int fileGpuIndex = -1; + if (IsFileExeType(wc.exe.exeType) && IsGpuMemType(wc.mem[isDst][iMem].memType) && + wc.exe.exeIndices.size() == 1 && wc.exe.exeIndices[0] < numExecutors) { + fileGpuIndex = wc.exe.exeIndices[0]; + } + for (int x = 0; x < numExecutors; x++) { + if (fileGpuIndex >= 0 && x != fileGpuIndex) continue; wc.mem[isDst][iMem].memIndices[0] = x; result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers); } @@ -8295,8 +9552,25 @@ const auto& AmdSmiFabricInfoV1(const T& info) return result; } else if (wc.exe.exeIndices[0] == -1) { // Wildcard - loop over all possible executor indices - int numExecutors = GetNumExecutors(wc.exe.exeType, wc.exe.exeRanks[0]); + // (The hipFile executor is expanded over every GPU even if unavailable, so that the Transfers + // are rejected with an explanation instead of silently expanding to nothing) + int numExecutors = GetNumExecutors(IsFileExeType(wc.exe.exeType) ? EXE_GPU_GFX : wc.exe.exeType, + wc.exe.exeRanks[0]); + + // The hipFile executor only accesses the memory of its own GPU, so the executor follows GPU memory + // (which has been resolved by this point) + int fileGpuIndex = -1; + if (IsFileExeType(wc.exe.exeType)) { + for (int isDst = 0; isDst <= 1; isDst++) { + for (auto const& mem : wc.mem[isDst]) { + if (IsGpuMemType(mem.memType) && mem.memIndices[0] < numExecutors) + fileGpuIndex = mem.memIndices[0]; + } + } + } + for (int x = 0; x < numExecutors; x++) { + if (fileGpuIndex >= 0 && x != fileGpuIndex) continue; wc.exe.exeIndices[0] = x; result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers); } @@ -8339,7 +9613,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) // Resolve EXE subindex if (wc.exe.exeSubIndices.size() == 0) { - if (IsCpuExeType(wc.exe.exeType) || IsGpuExeType(wc.exe.exeType)) { + if (IsCpuExeType(wc.exe.exeType) || IsGpuExeType(wc.exe.exeType) || IsFileExeType(wc.exe.exeType)) { wc.exe.exeSubIndices = {-1}; result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers); wc.exe.exeSubIndices.clear(); @@ -8374,7 +9648,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) return result; } else if (wc.exe.exeSubIndices[0] == -2) { switch (wc.exe.exeType) { - case EXE_CPU: case EXE_GPU_TDM: + case EXE_CPU: case EXE_GPU_TDM: case EXE_GPU_HIPFILE: // These Executors do not support subindices wc.exe.exeSubIndices[0] = -1; result |= RecursiveWildcardTransferExpansion(wc, baseRankIndex, numBytes, numSubExecs, transfers); @@ -8492,6 +9766,25 @@ const auto& AmdSmiFabricInfoV1(const T& info) int numSubExecs; std::string srcStr, exeStr, dstStr, numBytesToken; + // Storage memory can only be accessed by the hipFile executor. Anything else is rejected while + // parsing, as wildcard expansion for the other executors assumes that memory is indexed by + // CPU NUMA node or by GPU + auto checkStorageUse = [](WildcardTransfer const& w, int const transferNum) -> ErrResult { + if (IsFileExeType(w.exe.exeType)) return ERR_NONE; + for (int isDst = 0; isDst <= 1; isDst++) { + for (auto const& mem : w.mem[isDst]) { + if (IsStorageMemType(mem.memType)) { + return {ERR_FATAL, + "Parsing error: Transfer %d: Storage memory (%c) can only be accessed by the hipFile (%c) " + "executor (instead of %c)", + transferNum, MemTypeStr[MEM_STORAGE], ExeTypeStr[EXE_GPU_HIPFILE], + ExeTypeStr[w.exe.exeType]}; + } + } + } + return ERR_NONE; + }; + if (!advancedMode) { iss >> numSubExecs; if (numSubExecs < 0 || iss.fail()) { @@ -8561,6 +9854,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) ERR_CHECK(ParseMemType(dstStr, wct.mem[1])); ERR_CHECK(ParseExeType(exeStr, wct.exe)); + ERR_CHECK(checkStorageUse(wct, i+1)); + if (isPingpong) { // Parse the pong triplet std::string pongSrcStr, pongExeStr, pongDstStr; @@ -8573,6 +9868,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) ERR_CHECK(ParseMemType(pongSrcStr, pongWct.mem[0])); ERR_CHECK(ParseMemType(pongDstStr, pongWct.mem[1])); ERR_CHECK(ParseExeType(pongExeStr, pongWct.exe)); + ERR_CHECK(checkStorageUse(pongWct, i+1)); // Each half exchanges one flag, so it takes at most one SRC and one DST std::pair const&, char const*> const halfMems[] = { @@ -9478,6 +10774,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) topo.closestCpuNumaToNic.clear(); topo.closestNicsToGpu.clear(); topo.closestGpusToNic.clear(); + topo.storagePath.clear(); + topo.fileExeAvailable.clear(); memset(topo.hostname, 0, sizeof(topo.hostname)); gethostname(topo.hostname, 32); @@ -9599,6 +10897,40 @@ const auto& AmdSmiFabricInfoV1(const T& info) topo.closestNicsToGpu[exeIndex] = {}; } + // hipFile Executor, indexed by the GPU whose memory is read into / written from + // hipFile is a build-time dependency +#ifdef HIPFILE_EXEC_ENABLED + bool const hipFileAvailable = true; +#else + bool const hipFileAvailable = false; +#endif + topo.fileExeAvailable[EXE_GPU_HIPFILE] = hipFileAvailable; + topo.numExecutors[EXE_GPU_HIPFILE] = hipFileAvailable ? numGpus : 0; + if (hipFileAvailable) { + for (int exeIndex = 0; exeIndex < numGpus; exeIndex++) { + topo.executorName[{EXE_GPU_HIPFILE, exeIndex}] = topo.executorName[{EXE_GPU_GFX, exeIndex}]; + topo.numExecutorSubIndices[{EXE_GPU_HIPFILE, exeIndex}] = 0; + topo.numSubExecutors[{EXE_GPU_HIPFILE, exeIndex}] = numa_num_configured_cpus(); + } + } + + // Storage memory (indexed by position in TB_STORAGE_PATHS) + { + std::lock_guard lock(GetStorageMutex()); + std::vector const& storageList = GetStorageDeviceList(); + for (int i = 0; i < (int)storageList.size(); i++) + topo.storagePath[i] = storageList[i].path; + } + + if (verbose) { + Log("[INFO] Rank %03d: hipFile executor %s\n", rank, + hipFileAvailable ? ("available v" + GetHipFileVersion()).c_str() : "not available (built without hipFile)"); + for (auto const& storage : topo.storagePath) { + Log("[INFO] Rank %03d: Storage [%02d/%02d] %s\n", rank, storage.first, (int)topo.storagePath.size(), + storage.second.c_str()); + } + } + // NIC Executor int numNics = 0; if (IsIbvSymbolsReady()) @@ -9865,6 +11197,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) SendMap(peerRank, topo.closestNicsToGpu); SendMap(peerRank, topo.closestGpusToNic); SendMap(peerRank, topo.executorName); + SendMap(peerRank, topo.storagePath); + SendMap(peerRank, topo.fileExeAvailable); }; void System::RecvRankTopo(int peerRank, RankTopology& topo) const @@ -9882,6 +11216,8 @@ const auto& AmdSmiFabricInfoV1(const T& info) RecvMap(peerRank, topo.closestNicsToGpu); RecvMap(peerRank, topo.closestGpusToNic); RecvMap(peerRank, topo.executorName); + RecvMap(peerRank, topo.storagePath); + RecvMap(peerRank, topo.fileExeAvailable); } template @@ -9928,6 +11264,7 @@ const auto& AmdSmiFabricInfoV1(const T& info) BroadcastVector(root, tfrResult.perIterMsec); BROADCAST(tfrResult.exeDevice); BROADCAST(tfrResult.exeDstDevice); + BROADCAST(tfrResult.ioPath); // Per-Iteration CU results need to be handled in a custom manner size_t perIterCuSize = tfrResult.perIterCUs.size(); @@ -10255,6 +11592,26 @@ const auto& AmdSmiFabricInfoV1(const T& info) return rankInfo[targetRank].nicMaxMsgSize.at(nicIndex); } + int System::GetNumStoragePaths(int targetRank) const + { + if (targetRank < 0 || targetRank >= numRanks) targetRank = rank; + return (int)rankInfo[targetRank].storagePath.size(); + } + + std::string System::GetStoragePath(int storageIndex, int targetRank) const + { + if (targetRank < 0 || targetRank >= numRanks) targetRank = rank; + if (rankInfo[targetRank].storagePath.count(storageIndex) == 0) return ""; + return rankInfo[targetRank].storagePath.at(storageIndex); + } + + bool System::IsFileExeAvailable(ExeType exeType, int targetRank) const + { + if (targetRank < 0 || targetRank >= numRanks) targetRank = rank; + if (rankInfo[targetRank].fileExeAvailable.count(exeType) == 0) return false; + return rankInfo[targetRank].fileExeAvailable.at(exeType) != 0; + } + int GetNumExecutors(ExeType exeType, int targetRank) { return System::Get().GetNumExecutors(exeType, targetRank); @@ -10262,8 +11619,9 @@ const auto& AmdSmiFabricInfoV1(const T& info) int GetNumExecutors(MemType memType, int targetRank) { - if (IsCpuMemType(memType)) return GetNumExecutors(EXE_CPU, targetRank); - if (IsGpuMemType(memType)) return GetNumExecutors(EXE_GPU_GFX, targetRank); + if (IsCpuMemType(memType)) return GetNumExecutors(EXE_CPU, targetRank); + if (IsGpuMemType(memType)) return GetNumExecutors(EXE_GPU_GFX, targetRank); + if (IsStorageMemType(memType)) return GetNumStoragePaths(targetRank); return 0; } @@ -10374,6 +11732,35 @@ const auto& AmdSmiFabricInfoV1(const T& info) return System::Get().GetNicMaxMsgSize(nicIndex, targetRank); } + int GetNumStoragePaths(int targetRank) + { + return System::Get().GetNumStoragePaths(targetRank); + } + + std::string GetStoragePath(int storageIndex, int targetRank) + { + return System::Get().GetStoragePath(storageIndex, targetRank); + } + + bool IsStoragePathListValid() + { + return !GetStorageConfig().hasEmptyEntry; + } + + bool IsHipFileAvailable(int targetRank) + { + return System::Get().IsFileExeAvailable(EXE_GPU_HIPFILE, targetRank); + } + + std::string GetHipFileVersion() + { +#ifdef HIPFILE_EXEC_ENABLED + return HipFileVersionString(); +#else + return ""; +#endif + } + // Undefine CUDA compatibility macros #if defined(__NVCC__)