From f30b558a65a18d70579b1c6d3343e32d16112792 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 29 Sep 2026 21:31:44 +0000 Subject: [PATCH 1/8] Document ROCm image validation and ROCm 10 migration requirements Record TheRock packaging, RVS/TransferBench coverage, and the public MI455X gfx1250 mapping without enabling unqualified targets. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/getting-started/installation.mdx | 110 ++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index a3f2f7c47..2f22b27c1 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -110,3 +110,113 @@ Here're the system requirements for all managed GPU nodes. + +### Building the ROCm 7 images + +The ROCm 7.0 and 7.2 Dockerfiles use ROCm 7.0.2 and 7.2.4 respectively, +with Ubuntu 24.04, Python 3.12, and PyTorch 2.9.1. Both default to +`AMDGPU_TARGETS="gfx942 gfx950"` (MI300X and MI355X). +Initialize the submodules before building; otherwise some third-party benchmark +binaries can be silently omitted by the Makefile. + +```bash +git submodule update --init --recursive +docker build --build-arg NUM_MAKE_JOBS=8 \ + -f dockerfile/rocm7.0.x.dockerfile -t superbench:rocm70 . +docker build --build-arg NUM_MAKE_JOBS=8 \ + -f dockerfile/rocm7.2.x.dockerfile -t superbench:rocm72 . + +# CPU-only architecture-routing regression tests: +python3 -m unittest discover -s tests -p 'test_rocm*dockerfile.py' -v +``` + +Use `--build-arg AMDGPU_TARGETS="gfx942"` for an MI300X-only benchmark build. +This does not prune the base image's libraries or the source-built RCCL library. +An image build alone does not qualify either GPU architecture. On an otherwise +idle GPU node, expose `/dev/kfd` and `/dev/dri` to the container and check: + +* Device enumeration, architecture names, and loaded ROCm/RCCL library paths. +* PyTorch GEMM and attention correctness, including backward passes, and + TransformerEngine execution (not just its import). +* SuperBench `gemm-flops`, `hipblaslt-gemm`, `mem-bw`, and `gpu-copy-bw`, including + successful result parsing and finite, positive metrics. +* RCCL collectives with data checking on all local GPUs. Multi-node RCCL and + RDMA require separate network validation. + +### ROCm 10 migration considerations + +The following is a scouting snapshot from **2026-09-29**, not a claim that the +ROCm 7 images support ROCm 10 or a new GPU. Keep the ROCm 7 baseline while +qualifying a separately pinned ROCm 10 image. + +#### Confirm the new GPU target first + +TheRock's public +[target definitions](https://github.com/ROCm/TheRock/blob/68ac349433a9a1f8434010c2751404d0f6192916/cmake/therock_amdgpu_targets.cmake) +identify **MI450/MI450X/MI455X as `gfx1250`**, not `gfx1251`. +Its [development support table](https://github.com/ROCm/TheRock/blob/68ac349433a9a1f8434010c2751404d0f6192916/SUPPORTED_GPUS.md) +marks `gfx1250` build-passing and sanity-tested but not release-ready. +The public [ROCm 10 compatibility matrix](https://rocm.docs.amd.com/en/latest/compatibility/compatibility-matrix.html) +lists MI300X and MI355X, but does not yet list MI455X. + +Treat `gfx1251` as a separate, unqualified target until the actual device's +`rocminfo` output and its vendor support matrix establish the mapping. +Compiler recognition is not proof of runtime, library kernel, or framework +support. Do not simply add either target to the ROCm 7 Dockerfiles or their +TransformerEngine AOTriton allowlists. + +#### Installation and dependency changes + +[ROCm 10 is a production Core SDK release built through TheRock](https://rocm.docs.amd.com/en/latest/about/transition-guide-TheRock.html). +It changes more than the base-image tag: + +| Area | ROCm 7 baseline | ROCm 10 work to qualify | +| --- | --- | --- | +| SDK packaging | Legacy packages such as `amd-smi-lib`, `rocm-cmake`, and `hipify-clang`; `/opt/rocm` paths | Core SDK under `/opt/rocm/core-10.0`; packages such as `amdrocm-amdsmi`, `amdrocm-base`, `amdrocm-hipify`, `amdrocm-blas`, and `amdrocm-rccl`. Package-manager installs provide compatibility symlinks; tarballs/wheels need explicit path discovery. | +| Source builds | Separate RCCL, rocBLAS, hipBLASLt and HIP clones | Pin a coherent TheRock release and its dependencies. Math libraries now live in [rocm-libraries](https://github.com/ROCm/rocm-libraries); runtime, HIP and management/profiling components in [rocm-systems](https://github.com/ROCm/rocm-systems). Do not assume old branches, `install.sh` options, or the 7.2 standalone hipBLASLt client shim remain applicable. | +| Device libraries | Prebuilt gfx942/gfx950 kernels plus locally compiled benchmarks | Install the matching device kernel packs as well as host libraries, compiler, headers and benchmark clients. Confirm each requested target is actually in the shipped artifacts. Keep MI300X as a regression target. | +| Frameworks | PyTorch 2.9.1; TE `v2.4_rocm` / `v2.10_rocm`; CK attention disabled | Select matched PyTorch, Triton, TE and attention-library releases. Current [TE development](https://github.com/ROCm/TransformerEngine/blob/03afd8f813300417ee1a41a4471d89be71c88f2d/README.rst) uses hipBLASLt for GEMM and AITER/CK JIT for attention; warm and record JIT caches before timing. AOTriton remains version/ABI-sensitive and its development builds add FlyDSL dependencies. | +| Monitoring | Python device manager already uses AMD SMI, but system-info collection invokes `rocm-smi` | ROCm SMI is removed from Core SDK. Port system-info commands and parsers to AMD SMI; retest enumeration, power units, ECC, topology and partition identifiers. | +| Profiling | Runner builds `rocprofv2` commands | Qualify ROCprofiler-SDK / `rocprofv3`, its CLI arguments and output formats; update runner tests and trace collection rather than only renaming the executable. | +| Host integration | Container uses the host's kernel driver and network devices | Qualify the OS, AMDGPU driver/firmware and user-space compatibility together. Preserve matched OFED/RDMA libraries and test single-node then multi-node RCCL; installing a newer SDK inside a container does not update the host driver. | + +For Python-distributed SDKs, TheRock now separates `rocm-sdk-core`, +`rocm-sdk-libraries`, `rocm-sdk-devel`, and `rocm-sdk-device-*`. +[TheRock's release instructions](https://github.com/ROCm/TheRock/blob/68ac349433a9a1f8434010c2751404d0f6192916/RELEASES.md) +describe `rocm[libraries,devel,device-gfx942,device-gfx950]`, `rocm-sdk init`, +`rocm-sdk test`, and `rocm-sdk path` for discovery. Pin the release/index; +nightly package availability does not establish hardware qualification. +Do not mix a wheel SDK with unrelated `/opt/rocm` libraries through +`LD_LIBRARY_PATH`. + +#### RVS and the validation matrix + +[RVS and TransferBench are ROCm Extras](https://rocm.docs.amd.com/en/latest/components/extras.html), +not part of the Core SDK install. The current +[RVS installation guide](https://rocm.docs.amd.com/projects/ROCmValidationSuite/en/latest/install/installation.html) +uses the separate Extras repository, package `amdrocm10-rvs`, and +`/opt/rocm/extras-10`. RVS includes TransferBench; source builds make its +standalone CLI optional. + +ROCm Bandwidth Test is end-of-life, with RVS/TransferBench the recommended +replacements. SuperBench's current `mem-bw` is a **different legacy path**: +it builds `hipBusBandwidth` from the HIP 5.5 samples. Replace that dependency +with an explicit RVS-backed benchmark/parser rather than assuming the old +command and metric format work unchanged. + +| Coverage | Candidate RVS module / retained test | +| --- | --- | +| Inventory, configuration and PCIe qualification | GPUP, RCQT, PEQT; AMD SMI inventory and telemetry | +| Host/device and peer transfers | PEBB and PBQT, now using TransferBench; retain SuperBench SM/DMA copy correctness checks | +| HBM bandwidth and integrity | BABEL (BabelStream) and MEM; qualify duration, allocation size and fault reporting | +| Sustained compute, power and thermal behavior | GST, IET and TST with per-SKU limits and opt-in durations | +| Communication and application regressions | Retain RCCL correctness/scaling, RDMA tests, rocBLAS/hipBLASLt precision checks, and PyTorch/TE forward/backward/attention tests | + +See the [RVS module descriptions](https://rocm.docs.amd.com/projects/ROCmValidationSuite/en/latest/features.html) +and [TransferBench integration notes](https://rocm.docs.amd.com/projects/ROCmValidationSuite/en/latest/transferbench.html). +The documented TransferBench default offload targets do not include gfx1250 +or gfx1251; verify actual package contents or build with explicitly supported +targets before claiming new-GPU coverage. RVS is not a replacement for all +SuperBench application/network tests. Keep stress tests opt-in on shared nodes, +preserve units and GPU identifiers in new parsers, and establish new per-SKU +thresholds rather than reusing MI300X baselines. From 3e60284011f47aa7203bc6f47ad2fb09c3c142cb Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Wed, 30 Sep 2026 00:57:04 +0000 Subject: [PATCH 2/8] Scaffold ROCm 10 on AMD Ubuntu 26.04 with packaged RCCL Keep the all-device wheel SDK and legacy MPI prefix, add release-matched RCCL clients and pinned relocatable RVS/TransferBench, and preserve AMD framework versions. Canonicalize AMD SMI loading to prevent import-order-dependent zero-GPU discovery. Document scaffold boundaries, tested transfer replacements, and remaining qualification choices. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dockerfile/rocm10.0.x.dockerfile | 149 ++++++++++++++++++++++++++ docs/getting-started/installation.mdx | 122 +++++++++++++++++---- tests/test_rocm10_dockerfile.py | 108 +++++++++++++++++++ 3 files changed, 356 insertions(+), 23 deletions(-) create mode 100644 dockerfile/rocm10.0.x.dockerfile create mode 100644 tests/test_rocm10_dockerfile.py diff --git a/dockerfile/rocm10.0.x.dockerfile b/dockerfile/rocm10.0.x.dockerfile new file mode 100644 index 000000000..1595a673e --- /dev/null +++ b/dockerfile/rocm10.0.x.dockerfile @@ -0,0 +1,149 @@ +ARG BASE_IMAGE=rocm/pytorch:rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:3174cb7061d94c427da96c0edef4adea28046fa3f3b2ff3948dc4e995665ff8c +FROM ${BASE_IMAGE} + +LABEL maintainer="SuperBench" +SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"] + +# Experimental scaffold: preserve AMD's matched Python 3.14 / PyTorch 2.13 stack. +# SDK packages include all devices; this argument only selects locally built kernels. +ARG AMDGPU_TARGETS="gfx942 gfx950" +ARG NUM_MAKE_JOBS=8 +ARG ROCM_VERSION=10.0.0 +ARG OPENMPI_VERSION=4.1.8 +# rocm-systems revision selected by TheRock's therock-10.0 release. +ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9 + +ENV DEBIAN_FRONTEND=noninteractive \ + AMDGPU_TARGETS="${AMDGPU_TARGETS}" \ + CMAKE_BUILD_PARALLEL_LEVEL="${NUM_MAKE_JOBS}" \ + CMAKE_POLICY_VERSION_MINIMUM=3.5 \ + MPI_HOME=/usr/local/mpi \ + ROCM_PATH=/opt/rocm \ + HIP_PATH=/opt/rocm \ + RCCL_HOME=/opt/rocm \ + SB_HOME=/opt/superbench \ + SB_MICRO_PATH=/opt/superbench \ + ANSIBLE_DEPRECATION_WARNINGS=FALSE \ + ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + autoconf automake bc build-essential ca-certificates cmake curl \ + dmidecode flex gfortran git iproute2 jq libaio-dev \ + libatomic1 libboost-program-options-dev libcap2 libcurl4-openssl-dev \ + libibumad-dev libibverbs-dev libnuma-dev libpci-dev libquadmath0 librdmacm-dev \ + libssl-dev libtinfo6 libtool lshw net-tools ninja-build numactl \ + openssh-client openssh-server pciutils pkg-config rsync sudo \ + util-linux wget && \ + apt-get clean + +# The base uses ROCm wheels, not DEBs. Add development files to that same SDK; +# installing amdrocm-core-sdk as well would introduce a second runtime. +# RCCL is AMD's prebuilt library in rocm-sdk-libraries, never built from source. +RUN python3 -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ \ + "rocm[devel,libraries,device-all]==${ROCM_VERSION}" && \ + rocm-sdk init && \ + ln -s "$(rocm-sdk path --root)" "${ROCM_PATH}" && \ + test -r "${ROCM_PATH}/.info/version" && \ + test -r "${ROCM_PATH}/lib/librccl.so" && \ + printf '%s\n' "${ROCM_PATH}/lib" "${ROCM_PATH}/lib/llvm/lib" > /etc/ld.so.conf.d/rocm.conf && \ + ldconfig && \ + python3 -m pip install "${ROCM_PATH}/share/amd_smi" + +# MPI in the built-in benchmarks exchanges host metadata/results; RCCL exchanges +# GPU buffers. Keep the existing MPI prefix without claiming HIP-aware MPI support. +RUN git clone --depth 1 --recursive -b "v${OPENMPI_VERSION}" https://github.com/open-mpi/ompi.git /tmp/ompi && \ + cd /tmp/ompi && \ + ./autogen.pl && \ + mkdir build && cd build && \ + ../configure --prefix="${MPI_HOME}" \ + --enable-orterun-prefix-by-default --enable-mpirun-prefix-by-default && \ + make -j"${NUM_MAKE_JOBS}" && \ + make install && \ + printf '%s\n' "${MPI_HOME}/lib" > /etc/ld.so.conf.d/superbench-mpi.conf && \ + ldconfig && \ + cd / && rm -rf /tmp/ompi + +ENV PATH="/usr/local/mpi/bin:/opt/superbench/bin:/opt/rocm/bin:${PATH}" \ + LD_LIBRARY_PATH="/usr/local/mpi/lib:/opt/rocm/lib:/opt/rocm/lib/llvm/lib" \ + USE_HIP_DATATYPE=1 \ + USE_HIPBLAS_COMPUTETYPE=1 + +ARG DOCKER_VERSION=29.6.2 +RUN curl -fsSL "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz" -o /tmp/docker.tgz && \ + tar --extract --file /tmp/docker.tgz --strip-components 1 --directory /usr/local/bin/ docker/docker && \ + rm /tmp/docker.tgz + +RUN mkdir -p /root/.ssh /var/run/sshd && \ + touch /root/.ssh/authorized_keys && \ + sed -i 's/[# ]*PermitRootLogin prohibit-password/PermitRootLogin yes/; s/[# ]*PermitUserEnvironment no/PermitUserEnvironment yes/' /etc/ssh/sshd_config && \ + printf '%s\n' '* soft nofile 1048576' '* hard nofile 1048576' >> /etc/security/limits.conf && \ + printf 'PATH=%s\nLD_LIBRARY_PATH=%s\nSB_MICRO_PATH=%s\n' \ + "${PATH}" "${LD_LIBRARY_PATH}" "${SB_MICRO_PATH}" > /etc/environment + +# Build only the release-matched RCCL test clients against the packaged library. +RUN git init /tmp/rocm-systems && \ + git -C /tmp/rocm-systems remote add origin https://github.com/ROCm/rocm-systems.git && \ + git -C /tmp/rocm-systems sparse-checkout set projects/rccl-tests && \ + git -C /tmp/rocm-systems fetch --depth 1 --filter=blob:none origin "${ROCM_SYSTEMS_COMMIT}" && \ + git -C /tmp/rocm-systems checkout --detach FETCH_HEAD && \ + rccl_architectures=$(printf '%s' "${AMDGPU_TARGETS}" | tr -s '[:space:]' ';' | sed 's/^;//; s/;$//') && \ + if [ -z "${rccl_architectures}" ]; then \ + echo 'AMDGPU_TARGETS must contain at least one GPU architecture.' >&2; exit 1; \ + fi && \ + cmake -S /tmp/rocm-systems/projects/rccl-tests -B /tmp/rccl-tests-build \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_PREFIX_PATH="${ROCM_PATH};${MPI_HOME}" \ + -DROCM_PATH="${ROCM_PATH}" \ + -DGPU_TARGETS="${rccl_architectures}" \ + -DUSE_MPI=ON \ + -DCMAKE_INSTALL_PREFIX="${SB_HOME}" \ + -DCMAKE_INSTALL_RPATH="${ROCM_PATH}/lib;${MPI_HOME}/lib" \ + -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON && \ + cmake --build /tmp/rccl-tests-build -j"${NUM_MAKE_JOBS}" && \ + cmake --install /tmp/rccl-tests-build && \ + rm -rf /tmp/rocm-systems /tmp/rccl-tests-build + +WORKDIR ${SB_HOME} +COPY third_party third_party +# Do not invoke the legacy ROCm aggregate target: it clones HIP 5.5 samples, +# rebuilds math libraries, and installs unqualified Megatron/DeepSpeed dependencies. +RUN test -f third_party/fio/Makefile && \ + test -f third_party/perftest/autogen.sh && \ + make -C third_party fio rocm_perftest + +COPY . . +# Keep AMD's framework and all-device SDK packages when resolving SuperBench deps. +RUN python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|rocm|rocm-sdk-[^=]+)==' > /tmp/rocm10-constraints.txt && \ + python3 -m pip install -c /tmp/rocm10-constraints.txt '.[amdworker]' && \ + CXX="${ROCM_PATH}/bin/hipcc" make cppbuild && \ + make postinstall && \ + python3 -m pip install pytest pytest-timeout vcrpy && \ + python3 -m pip check && \ + sb --help && \ + rm /tmp/rocm10-constraints.txt && \ + rm -rf .git + +# The official relocatable Extras archive works with the wheel SDK without +# pulling a second ROCm installation through native-package dependencies. +ARG RVS_VERSION=1.6.122-708 +ARG RVS_SHA256=4ea57ddd8442f0e271e4d7cc8806019f7b0b008e258b883a38dd951c0097516a +ENV EXTRAS_PATH=/opt/rocm-extras-10 +ENV PATH="${EXTRAS_PATH}/bin:${PATH}" \ + LD_LIBRARY_PATH="${EXTRAS_PATH}/lib:${LD_LIBRARY_PATH}" +RUN curl -fsSL "https://stable.repo.amd.com/rocm/extras/rvs/tarball/amdrocm10-rvs-${RVS_VERSION}-Linux.tar.gz" -o /tmp/rvs.tar.gz && \ + printf '%s %s\n' "${RVS_SHA256}" /tmp/rvs.tar.gz | sha256sum --check --strict && \ + mkdir -p "${EXTRAS_PATH}" && \ + tar -xzf /tmp/rvs.tar.gz -C "${EXTRAS_PATH}" && \ + rm /tmp/rvs.tar.gz && \ + test -x "${EXTRAS_PATH}/bin/rvs" && \ + test -x "${EXTRAS_PATH}/bin/TransferBench" && \ + printf 'PATH=%s\nLD_LIBRARY_PATH=%s\nSB_MICRO_PATH=%s\n' \ + "${PATH}" "${LD_LIBRARY_PATH}" "${SB_MICRO_PATH}" > /etc/environment + +# Loading the devel overlay's AMD SMI copy after PyTorch's core copy creates two +# initialization states and reports zero GPUs. Both bindings must load one file. +RUN smi_library=$(python3 -c 'from importlib.metadata import distribution; print(distribution("rocm-sdk-core").locate_file("_rocm_sdk_core/lib/libamd_smi.so.27"))') && \ + cmp "${ROCM_PATH}/lib/libamd_smi.so" "${smi_library}" && \ + ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so" && \ + ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so.27" diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 2f22b27c1..e41cd7edd 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -111,37 +111,113 @@ Here're the system requirements for all managed GPU nodes. -### Building the ROCm 7 images +### Experimental ROCm 10 image scaffold -The ROCm 7.0 and 7.2 Dockerfiles use ROCm 7.0.2 and 7.2.4 respectively, -with Ubuntu 24.04, Python 3.12, and PyTorch 2.9.1. Both default to -`AMDGPU_TARGETS="gfx942 gfx950"` (MI300X and MI355X). -Initialize the submodules before building; otherwise some third-party benchmark -binaries can be silently omitted by the Makefile. +`dockerfile/rocm10.0.x.dockerfile` starts from AMD's digest-pinned +`rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0` image. +It is a scaffold, not a feature-equivalent replacement for the ROCm 7 images, +and is intentionally not yet in the release-image workflow matrix. ```bash git submodule update --init --recursive docker build --build-arg NUM_MAKE_JOBS=8 \ - -f dockerfile/rocm7.0.x.dockerfile -t superbench:rocm70 . -docker build --build-arg NUM_MAKE_JOBS=8 \ - -f dockerfile/rocm7.2.x.dockerfile -t superbench:rocm72 . + -f dockerfile/rocm10.0.x.dockerfile -t superbench:rocm10-scaffold . +``` + +The base contains a wheel-distributed SDK. The scaffold installs +`rocm[devel,libraries,device-all]==10.0.0` and preserves the base's framework +and SDK versions with pip constraints. **All-device GPU packages are the +default**; this is not a multi-platform CPU image (the base is Linux x86_64). +`rocm-sdk init` expands the development tree, and `/opt/rocm` points to the +discovered SDK root. No second native-package ROCm SDK is installed. +The development overlay's AMD SMI library aliases point to the core wheel's +canonical library. Otherwise, importing PyTorch before the AMD SMI bindings +can load two initialization states and report zero GPUs even when HIP sees +all devices. + +* RCCL is AMD's **prebuilt SDK library**, not rebuilt from source. + Only RCCL-tests is compiled, from the `rocm-systems` revision selected by + TheRock's `therock-10.0` release. +* Open MPI from the `v4.1.8` source tag retains `/usr/local/mpi` (this source + build reports `4.1.8rc1`). Current built-in MPI calls exchange + host metadata, timing/error values, and NumPy arrays; GPU collectives use + RCCL. This scaffold does not claim ROCm-aware MPI support for applications + that pass device pointers directly to MPI. +* Locally compiled benchmark kernels default to `gfx942 gfx950`, independently + of the all-device SDK packages. Other kernel targets require an explicit + `AMDGPU_TARGETS` build argument and hardware qualification. +* RVS `1.6.122-708` and its bundled TransferBench are installed from AMD's + SHA-256-pinned relocatable Extras archive. Their prefix is + `/opt/rocm-extras-10`, separate from the wheel SDK. Native RVS packages are + not installed because their dependencies would bring in another SDK. +* The image includes SuperBench, its native microbenchmarks, RCCL-tests, fio, + and ROCm-enabled perftest. It uses Ubuntu's RDMA development packages; + no DOCA/OFED userspace version or host driver is selected by this scaffold. + +The following remain deliberately unqualified or absent: TransformerEngine, +Megatron/DeepSpeed setup, `rocblas-bench`, `hipblaslt-bench`, Intel MLC, and the +old HIP 5.5 `hipBusBandwidth` sample. Consequently, the existing `gemm-flops`, +`hipblaslt-gemm`, `cpu-memory-bw-latency`, and ROCm `mem-bw` wrappers are not +ready to run in this scaffold. No executable aliases or silently substituted +metrics are provided. Existing `rocm-smi` system-info collection and +`rocprofv2` tracing still need their separate ROCm 10 migrations. + +Validation on 2026-09-30: the scaffold built successfully and passed `pip check`, +34 targeted regression tests (three NVIDIA-only tests skipped), GEMM correctness +on all eight MI300X GPUs, FP16/BF16 PyTorch flash SDPA forward/backward, and the +SuperBench GPU-copy wrapper with data checking and 304 positive parsed metrics. +An eight-rank Open MPI / packaged-RCCL all-reduce passed data checking +(`NCCL_IB_DISABLE=1`, single node). RVS module/GPU discovery also worked. +These checks do not qualify multi-node networking, additional GPU architectures, +the omitted benchmarks, or sustained RVS stress workloads. + +#### TransferBench versus the legacy memory-bandwidth test + +The bundled CLI reports version 1.69.00, commit `5fbfa95`; do not assume that it includes every +feature of upstream development. Inspect its actual presets with +`TransferBench presets`. +The [v1.69 preset definitions](https://github.com/ROCm/TransferBench/blob/5fbfa95a1111a7f33f20b9780e5f22bf739f82fa/src/client/Presets/Presets.hpp) +and [transfer syntax](https://github.com/ROCm/TransferBench/blob/5fbfa95a1111a7f33f20b9780e5f22bf739f82fa/src/client/Presets/Help.hpp) +provide these candidate replacements: + +| Interface | Fit for SuperBench | +| --- | --- | +| `p2p` preset | Closest ready-made CPU/NUMA/GPU bandwidth matrix, but it runs more than H2D/D2H and defaults to compute execution. Setting `USE_GPU_DMA=1` alone does not make the CPU-to-GPU rows GPU-executed. | +| Explicit `cmdline` transfers | Best candidate for a new backend: `C0 D0 G0` selects pinned CPU-node-0 memory to GPU 0 via GPU-0 DMA; `G0 D0 C0` reverses the transfer. | +| `hbm`, `a2a`, `one2all`, sweep presets | Useful additional coverage, not drop-in replacements for the two existing host/device metrics. | +| RVS PEBB/PBQT with TransferBench | Suitable qualification workloads. The inspected PEBB adapter supports pinned CPU memory, not pageable memory, and uses only the first configured block size. | + +There is no `hipBusBandwidth`, `--h2d`/`--d2h`, or `rocm-bandwidth-test` +compatibility preset. For a bounded manual smoke test on an idle node, select +accessible NUMA/GPU indices and permit the required NUMA syscalls: -# CPU-only architecture-routing regression tests: -python3 -m unittest discover -s tests -p 'test_rocm*dockerfile.py' -v +```bash +TransferBench dryrun 4M '1 1 C0 D0 G0' +timeout 20s env TB_NUM_RANKS=1 NUM_ITERATIONS=3 NUM_WARMUPS=1 \ + NUM_SUBITERATIONS=1 ALWAYS_VALIDATE=0 USE_HSA_DMA=0 \ + USE_HIP_EVENTS=1 USE_INTERACTIVE=0 HIDE_ENV=1 \ + TransferBench cmdline 4M '1 1 C0 D0 G0' +# D2H: use '1 1 G0 D0 C0' instead. ``` -Use `--build-arg AMDGPU_TARGETS="gfx942"` for an MI300X-only benchmark build. -This does not prune the base image's libraries or the source-built RCCL library. -An image build alone does not qualify either GPU architecture. On an otherwise -idle GPU node, expose `/dev/kfd` and `/dev/dri` to the container and check: - -* Device enumeration, architecture names, and loaded ROCm/RCCL library paths. -* PyTorch GEMM and attention correctness, including backward passes, and - TransformerEngine execution (not just its import). -* SuperBench `gemm-flops`, `hipblaslt-gemm`, `mem-bw`, and `gpu-copy-bw`, including - successful result parsing and finite, positive metrics. -* RCCL collectives with data checking on all local GPUs. Multi-node RCCL and - RDMA require separate network validation. +`ALWAYS_VALIDATE=0` retains the final correctness check; negative values disable +it. `P0` selects pinned host memory near GPU 0, while `H0` selects pageable +memory on NUMA node 0. Both pinned and pageable 4-MiB transfers passed bounded +H2D/D2H smoke tests on MI300X; other sizes, devices and placements still need +qualification. +Container policies must permit NUMA allocation/placement queries; failed +placement checks are errors, not valid bandwidth results. +The tested `OUTPUT_TO_CSV=1` output still includes banners and executor/aggregate +rows; do not treat the complete stdout stream as a flat table of transfer results. + +Before replacing `mem-bw`, choose whether to introduce a separate benchmark/new +baseline or retain strict compatibility. TransferBench's HIP asynchronous DMA +path differs from the old sample's default synchronous `hipMemcpy`. +It reports bytes divided by mean duration, whereas the old sample averages +per-trial bandwidth. Its generic size sweep also omits the old sub-1-KiB +sizes. A new parser must select individual transfer rows, retain device/NUMA +identity, and define the size sweep, aggregation, and pageable-memory policy; +simply renaming the executable would silently change the measurement. ### ROCm 10 migration considerations diff --git a/tests/test_rocm10_dockerfile.py b/tests/test_rocm10_dockerfile.py new file mode 100644 index 000000000..48f3994f5 --- /dev/null +++ b/tests/test_rocm10_dockerfile.py @@ -0,0 +1,108 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Tests for the experimental ROCm 10 image scaffold.""" + +import os +import subprocess +import unittest +from pathlib import Path + + +class Rocm10DockerfileTestCase(unittest.TestCase): + """Check package selection and executable architecture routing without Docker.""" + + @classmethod + def setUpClass(cls): + """Load the Dockerfile and extract RCCL test architecture handling.""" + root = Path(__file__).resolve().parents[1] + cls.dockerfile = (root / 'dockerfile' / 'rocm10.0.x.dockerfile').read_text(encoding='utf-8') + start = cls.dockerfile.index('rccl_architectures=$(printf') + end = cls.dockerfile.index(' cmake -S /tmp/rocm-systems', start) + cls.routing = cls.dockerfile[start:end] + 'printf \'%s\\n\' "$rccl_architectures"\n' + + def run_routing(self, targets): + """Execute the real Dockerfile routing block with a supplied target list.""" + env = os.environ.copy() + env['AMDGPU_TARGETS'] = targets + return subprocess.run( + ['/bin/bash', '-e', '-o', 'pipefail', '-c', self.routing], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + check=False, + ) + + def test_architecture_routing(self): + """Normalize single, multiple, and whitespace-separated architectures.""" + for targets, expected in ( + ('gfx942 gfx950', 'gfx942;gfx950'), + ('gfx942', 'gfx942'), + ('gfx90a gfx942 gfx950 gfx1250', 'gfx90a;gfx942;gfx950;gfx1250'), + (' gfx942\t gfx950\n', 'gfx942;gfx950'), + ): + with self.subTest(targets=targets): + result = self.run_routing(targets) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), expected) + + def test_empty_architectures_fail_explicitly(self): + """Do not fall back to the build host's detected GPU architecture.""" + for targets in ('', ' \t\n'): + with self.subTest(targets=targets): + result = self.run_routing(targets) + self.assertNotEqual(result.returncode, 0) + self.assertIn('AMDGPU_TARGETS must contain at least one GPU architecture.', result.stderr) + + def test_all_device_sdk_uses_base_package_ecosystem(self): + """Keep all-device wheels rather than installing a second native SDK.""" + self.assertIn('rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:', self.dockerfile) + self.assertIn('"rocm[devel,libraries,device-all]==${ROCM_VERSION}"', self.dockerfile) + self.assertIn('rocm-sdk init', self.dockerfile) + self.assertIn('ln -s "$(rocm-sdk path --root)" "${ROCM_PATH}"', self.dockerfile) + self.assertNotIn('apt install -y amdrocm', self.dockerfile) + + def test_rccl_uses_packaged_library_and_matched_test_sources(self): + """Build only test clients and retain runtime library search paths.""" + self.assertIn('test -r "${ROCM_PATH}/lib/librccl.so"', self.dockerfile) + self.assertIn('ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9', self.dockerfile) + self.assertIn('-DGPU_TARGETS="${rccl_architectures}"', self.dockerfile) + self.assertIn('-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON', self.dockerfile) + self.assertNotIn('https://github.com/ROCm/rccl.git', self.dockerfile) + self.assertNotIn('https://github.com/ROCmSoftwarePlatform/rccl.git', self.dockerfile) + self.assertNotIn('LD_PRELOAD=', self.dockerfile) + + def test_legacy_mpi_and_scaffold_boundaries(self): + """Keep the MPI prefix while avoiding unqualified legacy dependencies.""" + self.assertIn('MPI_HOME=/usr/local/mpi', self.dockerfile) + self.assertIn('ARG OPENMPI_VERSION=4.1.8', self.dockerfile) + self.assertNotIn('--with-rocm=', self.dockerfile) + self.assertIn('make -C third_party fio rocm_perftest', self.dockerfile) + self.assertNotIn('ROCM_VER=rocm-5.5.0', self.dockerfile) + self.assertNotIn('https://github.com/ROCm/TransformerEngine.git', self.dockerfile) + self.assertIn("pip install -c /tmp/rocm10-constraints.txt '.[amdworker]'", self.dockerfile) + self.assertIn('python3 -m pip check', self.dockerfile) + + def test_extras_do_not_install_another_sdk(self): + """Pin the relocatable RVS archive and expose its bundled TransferBench.""" + self.assertIn('ARG RVS_VERSION=1.6.122-708', self.dockerfile) + self.assertIn('sha256sum --check --strict', self.dockerfile) + self.assertIn('tar -xzf /tmp/rvs.tar.gz -C "${EXTRAS_PATH}"', self.dockerfile) + self.assertIn('test -x "${EXTRAS_PATH}/bin/TransferBench"', self.dockerfile) + self.assertIn('LD_LIBRARY_PATH="${EXTRAS_PATH}/lib:${LD_LIBRARY_PATH}"', self.dockerfile) + self.assertNotIn('apt install -y amdrocm10-rvs', self.dockerfile) + + def test_amdsmi_bindings_share_the_core_library(self): + """Avoid independent AMD SMI initialization states in PyTorch and SuperBench.""" + self.assertIn( + 'distribution("rocm-sdk-core").locate_file("_rocm_sdk_core/lib/libamd_smi.so.27")', + self.dockerfile, + ) + self.assertIn('cmp "${ROCM_PATH}/lib/libamd_smi.so" "${smi_library}"', self.dockerfile) + self.assertIn('ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so"', self.dockerfile) + self.assertIn('ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so.27"', self.dockerfile) + + +if __name__ == '__main__': + unittest.main() From 8f1de72ac3738770ef6060b046cadabd2cc0b75f Mon Sep 17 00:00:00 2001 From: Zheyu Shen Date: Wed, 7 Oct 2026 23:21:07 +0000 Subject: [PATCH 3/8] experimental rocm10 support --- dockerfile/etc/install-rocm10-frameworks.sh | 136 +++++++ dockerfile/rocm10.0.x.dockerfile | 221 +++++++---- .../rocm_memory_bw_performance.py | 183 +++++++++- .../model_benchmarks/megatron_gpt3.py | 17 +- .../model_benchmarks/pytorch_base.py | 18 +- .../model_benchmarks/pytorch_bert.py | 1 + .../model_benchmarks/pytorch_gpt2.py | 1 + .../model_benchmarks/pytorch_llama.py | 1 + .../test_rocm_memory_bw_performance.py | 343 +++++++++++++++++- .../model_benchmarks/test_megatron_launch.py | 85 +++++ .../test_transformer_precisions.py | 38 ++ tests/test_rocm10_dockerfile.py | 271 ++++++++++++-- tests/test_rocm10_framework_install.py | 42 +++ third_party/Makefile | 2 +- .../megatron_core_0.19.2_rocm10.patch | 58 +++ 15 files changed, 1314 insertions(+), 103 deletions(-) create mode 100755 dockerfile/etc/install-rocm10-frameworks.sh create mode 100644 tests/benchmarks/model_benchmarks/test_megatron_launch.py create mode 100644 tests/benchmarks/model_benchmarks/test_transformer_precisions.py create mode 100644 tests/test_rocm10_framework_install.py create mode 100644 third_party/Megatron/megatron_core_0.19.2_rocm10.patch diff --git a/dockerfile/etc/install-rocm10-frameworks.sh b/dockerfile/etc/install-rocm10-frameworks.sh new file mode 100755 index 000000000..3ff2e24c6 --- /dev/null +++ b/dockerfile/etc/install-rocm10-frameworks.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# Build ROCm Transformer Engine and AITER without replacing the wheel SDK, +# PyTorch, or Triton. Invoke from a writable build directory inside the ROCm10 +# image, not on the host. ROCM_PATH must select the wheel-SDK development root; +# CMake, Ninja, a C++ compiler, Git and Python development headers are required. +# Validated on Ubuntu 26.04 / Python 3.14.4 / MI300X (gfx942). The other two +# targets are compile-only coverage, not a runtime certification. +# For native-FP16 SB BERT/GPT2/Llama training (including FP8 linear layers), +# pass --optimizer_eps 1e-4: the legacy 1e-8 default underflows in FP16 Adam. +# BERT's pooler also requires an FP8-aligned batch size (use 16 or a multiple). +# GPT2's Hugging Face Conv1D layers are not converted to TE by SuperBench; +# use Llama/BERT or Megatron to exercise FP8 attention/MLP projection GEMMs. +# FP8 projection GEMMs do not imply FP8 dot-product attention support. +# For full-precision FP32 AITER Triton attention, set TRITON_F32_DEFAULT=ieee; +# its default TF32 dot products are independent of PyTorch's TF32 switches. +# Standalone aiter.flash_attn_func training requires return_lse=True; unpack +# (output, lse). Its CK JIT cold build can take many minutes, unlike TE's CK JIT. +# The separate Megatron checkout is selected with --code_base; the repository's +# older Megatron-LM and Megatron-DeepSpeed submodule pointers remain unchanged. +# An image can set SB_MEGATRON_PATH to that checkout as its non-DeepSpeed default. +set -euo pipefail + +readonly TE_COMMIT=e7835ed1b134f56e58c575fba2455471064cab9b +readonly AITER_COMMIT=89a47b84ac4b576339a50047e290c383c2377389 +readonly MEGATRON_COMMIT=4b4acac9a1d28ea6829c8d4f566d75698a21249d +# TE v2.15_rocm, AITER HEAD snapshot 2026-09-30, and Megatron Core v0.19.2. +# The tested TE 2.18-dev alternative cannot compile its BF16 small-sequence +# attention for gfx1250; do not silently replace this pin with moving dev. +readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +readonly SOURCE_ROOT="${SB_ROCM10_FRAMEWORK_ROOT:-${PWD}/rocm10-frameworks}" +readonly WHEELHOUSE="${SOURCE_ROOT}/wheels/${TE_COMMIT}-${AITER_COMMIT}-${MEGATRON_COMMIT}" +mkdir -p "${SOURCE_ROOT}/scratch" "${WHEELHOUSE}" +export TMPDIR="${SOURCE_ROOT}/scratch" +export MAX_JOBS="${MAX_JOBS:-16}" +if ! [[ "${MAX_JOBS}" =~ ^[0-9]+$ ]] || ((MAX_JOBS < 1 || MAX_JOBS > 16)); then + echo 'MAX_JOBS must be between 1 and 16.' >&2 + exit 1 +fi +export CMAKE_BUILD_PARALLEL_LEVEL="${MAX_JOBS}" NVTE_BUILD_MAX_JOBS="${MAX_JOBS}" +ROCM_PATH="$(rocm-sdk path --root)" +export ROCM_PATH ROCM_HOME="${ROCM_PATH}" HIP_PATH="${ROCM_PATH}" RCCL_HOME="${ROCM_PATH}" +export NVTE_USE_ROCM=1 NVTE_FRAMEWORK=pytorch NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250' +export NVTE_NO_LOCAL_VERSION=1 +export NVTE_CK_JIT=1 NVTE_FUSED_ATTN=1 NVTE_FUSED_ATTN_CK=1 NVTE_FUSED_ATTN_AOTRITON=1 +export AITER_USE_SYSTEM_TRITON=1 PREBUILD_KERNELS=0 BUILD_TARGET=rocm + +# An explicit constraints file also protects transitive dependency resolution. +# --no-build-isolation prevents pip from fetching a different build-time torch. +python - "${SOURCE_ROOT}/sdk-constraints.txt" <<'PY' +import importlib.metadata as metadata +import sys + +expected = { + "torch": "2.13.0+rocm10.0.0", + "triton": "3.8.0+git4cff872c.rocm10.0.0", + "rocm-sdk-core": "10.0.0", + "rocm-sdk-devel": "10.0.0", +} +for name, version in expected.items(): + actual = metadata.version(name) + if actual != version: + raise SystemExit(f"Expected {name}=={version}, found {actual}") +protected = [] +for distribution in metadata.distributions(): + name = distribution.metadata["Name"].lower().replace("_", "-") + if name.startswith("rocm-") or name in {"rocm", "torch", "torchvision", "torchaudio", "triton", "apex"}: + protected.append(f"{name}=={distribution.version}") +with open(sys.argv[1], "w") as file: + file.write("\n".join(sorted(protected)) + "\n") +PY +export PIP_CONSTRAINT="${SOURCE_ROOT}/sdk-constraints.txt" + +checkout() { + local repository="$1" commit="$2" destination="$3" + if [[ ! -d "${destination}/.git" ]]; then + git init --quiet "${destination}" + git -C "${destination}" remote add origin "${repository}" + fi + git -C "${destination}" fetch --quiet --depth 1 origin "${commit}" + git -C "${destination}" checkout --quiet --detach "${commit}" + git -C "${destination}" submodule update --init --recursive --depth 1 +} + +python -m pip install \ + pybind11==3.0.1 pydantic==2.13.5 einops==0.8.2 psutil==7.2.2 mpi4py==4.1.1 \ + flydsl==0.3.4.1 pandas==3.0.5 nvdlfw-inspect==0.2.2 \ + onnxscript==0.7.2 onnx-ir==1.0.0 onnx==1.23.1 ml_dtypes==0.6.0 +checkout https://github.com/ROCm/TransformerEngine.git "${TE_COMMIT}" "${SOURCE_ROOT}/TransformerEngine" +checkout https://github.com/ROCm/aiter.git "${AITER_COMMIT}" "${SOURCE_ROOT}/aiter" +checkout https://github.com/NVIDIA/Megatron-LM.git "${MEGATRON_COMMIT}" "${SOURCE_ROOT}/Megatron-LM" +MEGATRON_PATCH="${SB_ROCM10_MEGATRON_PATCH:-${SCRIPT_DIR}/../../third_party/Megatron/megatron_core_0.19.2_rocm10.patch}" +if ! git -C "${SOURCE_ROOT}/Megatron-LM" apply --reverse --check "${MEGATRON_PATCH}" 2>/dev/null; then + git -C "${SOURCE_ROOT}/Megatron-LM" apply --check "${MEGATRON_PATCH}" + git -C "${SOURCE_ROOT}/Megatron-LM" apply "${MEGATRON_PATCH}" +fi + +# TE pins its own private AITER/CK implementation in qola_manifest.toml. +# Do not override it with the separately installed Python AITER package. +# CK excludes gfx1250 upstream; common TE kernels still compile for all three +# requested targets. AOTriton ships images for gfx942/gfx950, not gfx1250. +python -m pip wheel --no-build-isolation --no-deps \ + "${SOURCE_ROOT}/TransformerEngine" "${SOURCE_ROOT}/aiter" "${SOURCE_ROOT}/Megatron-LM" \ + -w "${WHEELHOUSE}" +python -m pip install --no-deps "${WHEELHOUSE}"/*.whl + +python -m pip check +python - "${SOURCE_ROOT}/sdk-constraints.txt" <<'PY' +import importlib.metadata as metadata +import sys + +for line in open(sys.argv[1]): + name, expected = line.strip().split("==") + actual = metadata.version(name) + if actual != expected: + raise SystemExit(f"Protected dependency changed: {name}: {expected} -> {actual}") +PY +python - "${SOURCE_ROOT}" "${TE_COMMIT}" "${AITER_COMMIT}" "${MEGATRON_COMMIT}" <<'PY' +import importlib.metadata as metadata +import json +from pathlib import Path +import sys + +root, te, aiter, megatron = sys.argv[1:] +manifest = { + "sources": {"transformer_engine": te, "aiter": aiter, "megatron": megatron}, + "packages": {name: metadata.version(name) for name in + ["torch", "triton", "transformer_engine", "amd-aiter", "megatron-core", "flydsl"]}, + "compiled_te_targets": ["gfx942", "gfx950", "gfx1250"], + "ck_attention_targets": ["gfx942", "gfx950"], + "aotriton_image_targets": ["gfx942", "gfx950"], +} +(Path(root) / "framework-pins.json").write_text(json.dumps(manifest, indent=2) + "\n") +PY +echo "Framework sources: ${SOURCE_ROOT}" +echo "Megatron --code_base: ${SOURCE_ROOT}/Megatron-LM" +echo "Optional image ENV: SB_MEGATRON_PATH=${SOURCE_ROOT}/Megatron-LM" diff --git a/dockerfile/rocm10.0.x.dockerfile b/dockerfile/rocm10.0.x.dockerfile index 1595a673e..66bda8a20 100644 --- a/dockerfile/rocm10.0.x.dockerfile +++ b/dockerfile/rocm10.0.x.dockerfile @@ -6,10 +6,9 @@ SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"] # Experimental scaffold: preserve AMD's matched Python 3.14 / PyTorch 2.13 stack. # SDK packages include all devices; this argument only selects locally built kernels. -ARG AMDGPU_TARGETS="gfx942 gfx950" -ARG NUM_MAKE_JOBS=8 +ARG AMDGPU_TARGETS="gfx942 gfx950 gfx1250" +ARG NUM_MAKE_JOBS=64 ARG ROCM_VERSION=10.0.0 -ARG OPENMPI_VERSION=4.1.8 # rocm-systems revision selected by TheRock's therock-10.0 release. ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9 @@ -18,9 +17,7 @@ ENV DEBIAN_FRONTEND=noninteractive \ CMAKE_BUILD_PARALLEL_LEVEL="${NUM_MAKE_JOBS}" \ CMAKE_POLICY_VERSION_MINIMUM=3.5 \ MPI_HOME=/usr/local/mpi \ - ROCM_PATH=/opt/rocm \ - HIP_PATH=/opt/rocm \ - RCCL_HOME=/opt/rocm \ + EXTRAS_PATH=/opt/rocm/extras-10 \ SB_HOME=/opt/superbench \ SB_MICRO_PATH=/opt/superbench \ ANSIBLE_DEPRECATION_WARNINGS=FALSE \ @@ -29,57 +26,110 @@ ENV DEBIAN_FRONTEND=noninteractive \ RUN apt-get update && \ apt-get install -y --no-install-recommends \ autoconf automake bc build-essential ca-certificates cmake curl \ - dmidecode flex gfortran git iproute2 jq libaio-dev \ + dmidecode flex gfortran git gnupg iproute2 jq libaio-dev \ libatomic1 libboost-program-options-dev libcap2 libcurl4-openssl-dev \ libibumad-dev libibverbs-dev libnuma-dev libpci-dev libquadmath0 librdmacm-dev \ libssl-dev libtinfo6 libtool lshw net-tools ninja-build numactl \ - openssh-client openssh-server pciutils pkg-config rsync sudo \ + openssh-client openssh-server pciutils pkg-config python3-dev rsync sudo \ util-linux wget && \ apt-get clean -# The base uses ROCm wheels, not DEBs. Add development files to that same SDK; -# installing amdrocm-core-sdk as well would introduce a second runtime. +# Install the Docker CLI client only. +ARG DOCKER_VERSION=29.6.2 +RUN curl -fsSL "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz" -o /tmp/docker.tgz && \ + tar --extract --file /tmp/docker.tgz --strip-components 1 --directory /usr/local/bin/ docker/docker && \ + rm /tmp/docker.tgz + +# Update system config. +RUN mkdir -p /root/.ssh /var/run/sshd && \ + touch /root/.ssh/authorized_keys && \ + sed -i 's/[# ]*PermitRootLogin prohibit-password/PermitRootLogin yes/; s/[# ]*PermitUserEnvironment no/PermitUserEnvironment yes/' /etc/ssh/sshd_config && \ + printf '%s\n' '* soft nofile 1048576' '* hard nofile 1048576' >> /etc/security/limits.conf + +# Match the Ubuntu 26.04 Azure HPC userspace stack; never install host drivers here. +# TODO: Add a selectable alternative networking stack after its qualification. +ARG DOCA_VERSION=3.4.0 +ARG DOCA_PACKAGE_VERSION=3.4.0-085000 +ARG DOCA_OPENMPI_VERSION=5.0.10rc2.2605121430-1.b99be7132e +ARG DOCA_BUNDLE_SHA256=60789bbbfc9b283a87a64589a0d4bd5d08d1b746494c24ce05e10bbd694de6bb +# Use NVIDIA's signed local repository bundle: the online repository's TLS EOF +# handling fails with Ubuntu 26.04 APT. Do not disable certificate/signature checks. +RUN curl -fsSL "https://content.mellanox.com/DOCA/DOCA_v${DOCA_VERSION}/host/doca-host_${DOCA_PACKAGE_VERSION}-26.04-ubuntu2604_amd64.deb" -o /tmp/doca-host.deb && \ + printf '%s %s\n' "${DOCA_BUNDLE_SHA256}" /tmp/doca-host.deb | sha256sum --check --strict && \ + dpkg -i /tmp/doca-host.deb && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + "doca-ofed-userspace=${DOCA_PACKAGE_VERSION}" "openmpi=${DOCA_OPENMPI_VERSION}" && \ + mpi_prefix=$(dpkg-query -L openmpi | sed -n 's#/bin/mpirun$##p') && \ + test -n "${mpi_prefix}" && \ + test -x "${mpi_prefix}/bin/mpicc" && \ + ln -s "${mpi_prefix}" "${MPI_HOME}" && \ + printf '%s\n' "${MPI_HOME}/lib" > /etc/ld.so.conf.d/superbench-mpi.conf && \ + ldconfig && \ + "${MPI_HOME}/bin/mpirun" --version && \ + apt-get purge -y doca-host && \ + rm /tmp/doca-host.deb && \ + apt-get update && apt-get clean + +# Add development files to the base's SDK and use AMD's path discovery directly. # RCCL is AMD's prebuilt library in rocm-sdk-libraries, never built from source. RUN python3 -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ \ "rocm[devel,libraries,device-all]==${ROCM_VERSION}" && \ rocm-sdk init && \ - ln -s "$(rocm-sdk path --root)" "${ROCM_PATH}" && \ + ROCM_PATH="$(rocm-sdk path --root)" && \ test -r "${ROCM_PATH}/.info/version" && \ test -r "${ROCM_PATH}/lib/librccl.so" && \ - printf '%s\n' "${ROCM_PATH}/lib" "${ROCM_PATH}/lib/llvm/lib" > /etc/ld.so.conf.d/rocm.conf && \ - ldconfig && \ - python3 -m pip install "${ROCM_PATH}/share/amd_smi" - -# MPI in the built-in benchmarks exchanges host metadata/results; RCCL exchanges -# GPU buffers. Keep the existing MPI prefix without claiming HIP-aware MPI support. -RUN git clone --depth 1 --recursive -b "v${OPENMPI_VERSION}" https://github.com/open-mpi/ompi.git /tmp/ompi && \ - cd /tmp/ompi && \ - ./autogen.pl && \ - mkdir build && cd build && \ - ../configure --prefix="${MPI_HOME}" \ - --enable-orterun-prefix-by-default --enable-mpirun-prefix-by-default && \ - make -j"${NUM_MAKE_JOBS}" && \ - make install && \ - printf '%s\n' "${MPI_HOME}/lib" > /etc/ld.so.conf.d/superbench-mpi.conf && \ - ldconfig && \ - cd / && rm -rf /tmp/ompi + printf 'export ROCM_PATH=%q\n' "${ROCM_PATH}" > /etc/profile.d/rocm10-env.sh && \ + printf '%s\n' \ + 'export ROCM_HOME="${ROCM_PATH}" HIP_PATH="${ROCM_PATH}" RCCL_HOME="${ROCM_PATH}"' \ + 'export PATH="${EXTRAS_PATH}/bin:${MPI_HOME}/bin:${SB_MICRO_PATH}/bin:${ROCM_PATH}/bin:${PATH}"' \ + 'export LD_LIBRARY_PATH="${EXTRAS_PATH}/lib:${MPI_HOME}/lib:${ROCM_PATH}/lib:${ROCM_PATH}/lib/llvm/lib:${ROCM_PATH}/lib/host-math/lib:${ROCM_PATH}/lib/rocm_sysdeps/lib"' \ + >> /etc/profile.d/rocm10-env.sh + +# Resolve the SDK once at build time; shell startup must not reinitialize it. +ENV BASH_ENV=/etc/profile.d/rocm10-env.sh +ENTRYPOINT ["/bin/bash", "-e", "-c", "exec \"$@\"", "--"] +CMD ["/bin/bash"] + +# Register the bundled module until https://github.com/ROCm/TheRock/issues/3054 +# is fixed (upstream registration: https://github.com/ROCm/TheRock/pull/8424). +# A relative .pth entry preserves the wrapper's lookup of its matching library. +RUN python3 -c 'import sysconfig; from pathlib import Path; Path(sysconfig.get_path("purelib"), "amdsmi.pth").write_text("_rocm_sdk_core/share/amd_smi\n")' && \ + python3 -c 'import amdsmi' -ENV PATH="/usr/local/mpi/bin:/opt/superbench/bin:/opt/rocm/bin:${PATH}" \ - LD_LIBRARY_PATH="/usr/local/mpi/lib:/opt/rocm/lib:/opt/rocm/lib/llvm/lib" \ +# Built-in MPI calls exchange host data; RCCL exchanges GPU buffers. The DOCA +# Open MPI package needs neither a ROCm-aware rebuild nor unused OpenSHMEM. +ENV SB_ROCM_MEM_BW_BACKEND=transferbench \ USE_HIP_DATATYPE=1 \ USE_HIPBLAS_COMPUTETYPE=1 -ARG DOCKER_VERSION=29.6.2 -RUN curl -fsSL "https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz" -o /tmp/docker.tgz && \ - tar --extract --file /tmp/docker.tgz --strip-components 1 --directory /usr/local/bin/ docker/docker && \ - rm /tmp/docker.tgz +# Install RVS through AMD's signed Ubuntu 26.04 repositories. Explicitly select +# matching native dependencies instead of legacy distro packages or ROCm 10.1. +ARG RVS_VERSION=1.6.122-708 +ARG ROCM_APT_VERSION=10.0.0-4 +RUN install -d -m 0755 /etc/apt/keyrings && \ + curl -fsSL https://stable.repo.amd.com/rocm/gpg/packages.gpg | \ + gpg --batch --yes --dearmor -o /etc/apt/keyrings/amdrocm.gpg && \ + printf '%s\n' 'Types: deb' \ + 'URIs: https://stable.repo.amd.com/rocm/core/packages/ubuntu2604/' \ + 'Suites: stable' 'Components: main' 'Architectures: amd64' \ + 'Signed-By: /etc/apt/keyrings/amdrocm.gpg' > /etc/apt/sources.list.d/amdrocm-core.sources && \ + printf '%s\n' 'Types: deb' \ + 'URIs: https://stable.repo.amd.com/rocm/extras/rvs/packages/ubuntu2604/' \ + 'Suites: stable' 'Components: main' 'Architectures: amd64' \ + 'Signed-By: /etc/apt/keyrings/amdrocm.gpg' > /etc/apt/sources.list.d/amdrocm-rvs.sources && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + "amdrocm-runtime=${ROCM_APT_VERSION}" "amdrocm-base=${ROCM_APT_VERSION}" \ + "amdrocm-amdsmi=${ROCM_APT_VERSION}" "amdrocm-blas=${ROCM_APT_VERSION}" \ + "amdrocm-rand=${ROCM_APT_VERSION}" "amdrocm-llvm=${ROCM_APT_VERSION}" \ + "amdrocm10-rvs=${RVS_VERSION}" && \ + apt-get clean && \ + test -x "${EXTRAS_PATH}/bin/rvs" && \ + test -x "${EXTRAS_PATH}/bin/TransferBench" -RUN mkdir -p /root/.ssh /var/run/sshd && \ - touch /root/.ssh/authorized_keys && \ - sed -i 's/[# ]*PermitRootLogin prohibit-password/PermitRootLogin yes/; s/[# ]*PermitUserEnvironment no/PermitUserEnvironment yes/' /etc/ssh/sshd_config && \ - printf '%s\n' '* soft nofile 1048576' '* hard nofile 1048576' >> /etc/security/limits.conf && \ - printf 'PATH=%s\nLD_LIBRARY_PATH=%s\nSB_MICRO_PATH=%s\n' \ - "${PATH}" "${LD_LIBRARY_PATH}" "${SB_MICRO_PATH}" > /etc/environment +WORKDIR ${SB_HOME} +COPY third_party third_party # Build only the release-matched RCCL test clients against the packaged library. RUN git init /tmp/rocm-systems && \ @@ -104,46 +154,75 @@ RUN git init /tmp/rocm-systems && \ cmake --install /tmp/rccl-tests-build && \ rm -rf /tmp/rocm-systems /tmp/rccl-tests-build -WORKDIR ${SB_HOME} -COPY third_party third_party # Do not invoke the legacy ROCm aggregate target: it clones HIP 5.5 samples, # rebuilds math libraries, and installs unqualified Megatron/DeepSpeed dependencies. RUN test -f third_party/fio/Makefile && \ test -f third_party/perftest/autogen.sh && \ make -C third_party fio rocm_perftest +# Extract only matching prebuilt clients and their external GPU kernel packs. +# The ELFs alone cannot initialize matrices without the blas_test_*.kpack files. +ARG ROCM_TESTS_SHA256=47468ff71b8027eed4784de5052aa18684cb2ec0bfe0409ad7e62b9a6cf88f1f +RUN curl -fsSL "https://stable.repo.amd.com/rocm/core/tarball/therock-dist-linux-multiarch-tests-${ROCM_VERSION}.tar.gz" -o /tmp/rocm-tests.tar.gz && \ + printf '%s %s\n' "${ROCM_TESTS_SHA256}" /tmp/rocm-tests.tar.gz | sha256sum --check --strict && \ + tar -xzf /tmp/rocm-tests.tar.gz -C "${SB_HOME}" --wildcards --no-wildcards-match-slash \ + './bin/rocblas-bench' './bin/hipblaslt-bench' './.kpack/blas_test_*.kpack' && \ + rm /tmp/rocm-tests.tar.gz && \ + test -x "${SB_HOME}/bin/rocblas-bench" && \ + test -x "${SB_HOME}/bin/hipblaslt-bench" && \ + test -s "${SB_HOME}/.kpack/blas_test_gfx942.kpack" && \ + test -s "${SB_HOME}/.kpack/blas_test_gfx950.kpack" && \ + test -s "${SB_HOME}/.kpack/blas_test_gfx1250.kpack" + COPY . . # Keep AMD's framework and all-device SDK packages when resolving SuperBench deps. +# Resolve these before the framework installer applies its tested dependency pins. +# The SDK supplies amdsmi via .pth, not a separate distribution; use the torch +# extra so amdworker does not install a PyPI wrapper that shadows the SDK module. RUN python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|rocm|rocm-sdk-[^=]+)==' > /tmp/rocm10-constraints.txt && \ - python3 -m pip install -c /tmp/rocm10-constraints.txt '.[amdworker]' && \ - CXX="${ROCM_PATH}/bin/hipcc" make cppbuild && \ - make postinstall && \ - python3 -m pip install pytest pytest-timeout vcrpy && \ - python3 -m pip check && \ + python3 -m pip install -c /tmp/rocm10-constraints.txt '.[torch]' && \ + python3 -m pip install pytest pytest-timeout vcrpy + +# Install TransformerEngine, AITER and Megatron before the final native build. +ENV SB_ROCM10_FRAMEWORK_ROOT=/opt/rocm10-frameworks \ + SB_MEGATRON_PATH=/opt/rocm10-frameworks/Megatron-LM \ + AITER_USE_SYSTEM_TRITON=1 \ + TRITON_F32_DEFAULT=ieee \ + MAX_JOBS=16 \ + CUDA_DEVICE_MAX_CONNECTIONS=1 \ + NVTE_FLASH_ATTN=0 \ + NVTE_FUSED_ATTN=1 \ + NVTE_FUSED_ATTN_CK=1 \ + NVTE_FUSED_ATTN_AOTRITON=0 +RUN framework_jobs="${NUM_MAKE_JOBS}" && \ + if [ "${framework_jobs}" -gt 16 ]; then framework_jobs=16; fi && \ + MAX_JOBS="${framework_jobs}" bash dockerfile/etc/install-rocm10-frameworks.sh && \ + printf '%s\n' \ + "PATH=${PATH}" \ + "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}" \ + "SB_MICRO_PATH=${SB_MICRO_PATH}" \ + "SB_ROCM_MEM_BW_BACKEND=${SB_ROCM_MEM_BW_BACKEND}" \ + "ROCM_PATH=${ROCM_PATH}" \ + "ROCM_HOME=${ROCM_HOME}" \ + "HIP_PATH=${HIP_PATH}" \ + "RCCL_HOME=${RCCL_HOME}" \ + "SB_ROCM10_FRAMEWORK_ROOT=${SB_ROCM10_FRAMEWORK_ROOT}" \ + "SB_MEGATRON_PATH=${SB_MEGATRON_PATH}" \ + "AITER_USE_SYSTEM_TRITON=${AITER_USE_SYSTEM_TRITON}" \ + "TRITON_F32_DEFAULT=${TRITON_F32_DEFAULT}" \ + "MAX_JOBS=${MAX_JOBS}" \ + "CUDA_DEVICE_MAX_CONNECTIONS=${CUDA_DEVICE_MAX_CONNECTIONS}" \ + "NVTE_FLASH_ATTN=${NVTE_FLASH_ATTN}" \ + "NVTE_FUSED_ATTN=${NVTE_FUSED_ATTN}" \ + "NVTE_FUSED_ATTN_CK=${NVTE_FUSED_ATTN_CK}" \ + "NVTE_FUSED_ATTN_AOTRITON=${NVTE_FUSED_ATTN_AOTRITON}" \ + > /etc/environment + +# Build SuperBench and finish installation. +RUN CXX="${ROCM_PATH}/bin/hipcc" make cppbuild && \ + make postinstall + +RUN python3 -m pip check && \ sb --help && \ rm /tmp/rocm10-constraints.txt && \ rm -rf .git - -# The official relocatable Extras archive works with the wheel SDK without -# pulling a second ROCm installation through native-package dependencies. -ARG RVS_VERSION=1.6.122-708 -ARG RVS_SHA256=4ea57ddd8442f0e271e4d7cc8806019f7b0b008e258b883a38dd951c0097516a -ENV EXTRAS_PATH=/opt/rocm-extras-10 -ENV PATH="${EXTRAS_PATH}/bin:${PATH}" \ - LD_LIBRARY_PATH="${EXTRAS_PATH}/lib:${LD_LIBRARY_PATH}" -RUN curl -fsSL "https://stable.repo.amd.com/rocm/extras/rvs/tarball/amdrocm10-rvs-${RVS_VERSION}-Linux.tar.gz" -o /tmp/rvs.tar.gz && \ - printf '%s %s\n' "${RVS_SHA256}" /tmp/rvs.tar.gz | sha256sum --check --strict && \ - mkdir -p "${EXTRAS_PATH}" && \ - tar -xzf /tmp/rvs.tar.gz -C "${EXTRAS_PATH}" && \ - rm /tmp/rvs.tar.gz && \ - test -x "${EXTRAS_PATH}/bin/rvs" && \ - test -x "${EXTRAS_PATH}/bin/TransferBench" && \ - printf 'PATH=%s\nLD_LIBRARY_PATH=%s\nSB_MICRO_PATH=%s\n' \ - "${PATH}" "${LD_LIBRARY_PATH}" "${SB_MICRO_PATH}" > /etc/environment - -# Loading the devel overlay's AMD SMI copy after PyTorch's core copy creates two -# initialization states and reports zero GPUs. Both bindings must load one file. -RUN smi_library=$(python3 -c 'from importlib.metadata import distribution; print(distribution("rocm-sdk-core").locate_file("_rocm_sdk_core/lib/libamd_smi.so.27"))') && \ - cmp "${ROCM_PATH}/lib/libamd_smi.so" "${smi_library}" && \ - ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so" && \ - ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so.27" diff --git a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py index e7f25da86..347d82171 100644 --- a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py +++ b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py @@ -3,15 +3,43 @@ """Module of the ROCm memory performance benchmarks.""" +import csv +import ctypes +import math import os +from pathlib import Path +import re +import shlex +import statistics from superbench.common.utils import logger -from superbench.benchmarks import BenchmarkRegistry, Platform +from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode from superbench.benchmarks.micro_benchmarks import MemBwBenchmark class RocmMemBwBenchmark(MemBwBenchmark): """The ROCm memory performance benchmark class.""" + + # HIP rocm-5.5.0 samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp. + _TRANSFERBENCH_SIZES = (64, 256, 512) + tuple(2**power for power in range(10, 30)) + _TRANSFERBENCH_ITERATIONS = ( + 1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, + 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20 + ) + _TRANSFERBENCH_ENV = { + 'NUM_WARMUPS': 0, + 'NUM_SUBITERATIONS': 1, + 'SHOW_ITERATIONS': 1, + 'USE_HIP_EVENTS': 1, + 'USE_HSA_DMA': 0, + 'USE_SINGLE_STREAM': 1, + 'USE_INTERACTIVE': 0, + 'ALWAYS_VALIDATE': 0, + 'VALIDATE_DIRECT': 0, + 'VALIDATE_SOURCE': 0, + 'BYTE_OFFSET': 0, + } + def __init__(self, name, parameters=''): """Constructor. @@ -21,14 +49,24 @@ def __init__(self, name, parameters=''): """ super().__init__(name, parameters) - self._bin_name = 'hipBusBandwidth' + self._backend = os.getenv('SB_ROCM_MEM_BW_BACKEND', 'hipbusbandwidth').lower() + self._bin_name = 'TransferBench' if self._backend == 'transferbench' else 'hipBusBandwidth' self._mem_types = ['htod', 'dtoh'] self._parse_logline_map = {'htod': 'H2D_Bandwidth', 'dtoh': 'D2H_Bandwidth'} + self._worker_numa_node = None def add_parser_arguments(self): """Add the specified arguments.""" super().add_parser_arguments() + def _set_binary_path(self): + """Validate explicit backend selection before looking up an executable.""" + if self._backend not in ('hipbusbandwidth', 'transferbench'): + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + logger.error('Unsupported ROCm mem-bw backend: {}.'.format(self._backend)) + return False + return super()._set_binary_path() + def _preprocess(self): """Preprocess/preparation operations before the benchmarking. @@ -38,8 +76,15 @@ def _preprocess(self): if not super()._preprocess(): return False + if self._backend == 'transferbench' and self._args.memory == 'unpinned': + if not self._set_worker_numa_node(): + return False + # Check the arguments and generate the commands for mem_type in self._args.mem_type: + if self._backend == 'transferbench': + self._commands.append(self._transferbench_command(mem_type)) + continue command = os.path.join(self._args.bin_dir, self._bin_name) command += ' --' + mem_type.replace('to', '2') if self._args.memory == 'unpinned': @@ -48,6 +93,137 @@ def _preprocess(self): return True + def _set_worker_numa_node(self): + """Resolve the executing worker CPU's NUMA node once for this sweep.""" + try: + getcpu = ctypes.CDLL(None, use_errno=True).sched_getcpu + getcpu.argtypes = [] + getcpu.restype = ctypes.c_int + cpu = getcpu() + if cpu < 0: + raise OSError(ctypes.get_errno(), 'sched_getcpu failed') + cpu_path = Path('/sys/devices/system/cpu/cpu{}'.format(cpu)) + nodes = [entry for entry in cpu_path.iterdir() if re.fullmatch(r'node[0-9]+', entry.name)] + if len(nodes) != 1: + raise ValueError('Expected one NUMA node for CPU {}, found {}'.format(cpu, len(nodes))) + self._worker_numa_node = int(nodes[0].name[4:]) + except (AttributeError, OSError, ValueError) as error: + self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + logger.error( + 'Cannot determine worker-local NUMA placement - benchmark: {}, error: {}.'.format(self._name, error) + ) + return False + logger.info( + 'TransferBench pageable placement - benchmark: {}, worker CPU: {}, NUMA node: {}, endpoint: H{}.'.format( + self._name, cpu, self._worker_numa_node, self._worker_numa_node + ) + ) + return True + + def _transferbench_route(self, mem_type): + """Return the single-device DMA route, using HIP's logical device zero.""" + host = 'P0' if self._args.memory == 'pinned' else 'H{}'.format(self._worker_numa_node) + return (host, 'G0') if mem_type == 'htod' else ('G0', host) + + def _transferbench_command(self, mem_type): + """Build one fail-fast sweep per direction, retaining one raw log per direction.""" + source, destination = self._transferbench_route(mem_type) + binary = shlex.quote(os.path.join(self._args.bin_dir, self._bin_name)) + environment = dict(self._TRANSFERBENCH_ENV, OUTPUT_TO_CSV=1, HIDE_ENV=0, SHOW_PERCENTILES='') + options = ' '.join('{}={}'.format(key, value) for key, value in environment.items()) + commands = [] + for size, iterations in zip(self._TRANSFERBENCH_SIZES, self._TRANSFERBENCH_ITERATIONS): + commands.append( + "env {} NUM_ITERATIONS={} {} cmdline {} '1 1 {} D0 {}'".format( + options, iterations, binary, size, source, destination + ) + ) + return ' && '.join(commands) + + @staticmethod + def _transferbench_quantity(value, unit, allow_zero=False): + """Parse a finite numeric field with its explicit unit.""" + fields = value.split() + if len(fields) != 2 or fields[1] != unit: + raise ValueError('Invalid TransferBench quantity: {}'.format(value)) + number = float(fields[0]) + if not math.isfinite(number) or number < 0 or (number == 0 and not allow_zero): + raise ValueError('Invalid TransferBench quantity: {}'.format(value)) + return number + + def _transferbench_samples(self, rows, size, iterations): + """Extract every timed iteration, not the reciprocal-mean-time summary.""" + samples = {} + for row in rows: + if not row[0].startswith('Iter '): + continue + index = int(row[0].split()[1]) + if index in samples or not 1 <= index <= iterations: + raise ValueError('Duplicate or unexpected TransferBench iteration') + bandwidth = self._transferbench_quantity(row[1], 'GB/s', allow_zero=True) + duration = self._transferbench_quantity(row[2], 'ms') + # Three-decimal CLI output can round a genuine small-copy bandwidth to zero. + if bandwidth == 0 and size / (duration + 0.0005) / 1e6 >= 0.0005: + raise ValueError('Nonpositive TransferBench bandwidth') + # Preserve HIP5.5's integer nbytes/1000 division, including sub-KB zeros. + samples[index] = (size // 1000) / 1000 / duration + if len(samples) != iterations: + raise ValueError('Incomplete TransferBench iterations') + return statistics.mean(samples.values()) + + def _transferbench_report(self, report, size, iterations, mem_type): + """Validate one CSV-mode report, which also contains banners and typed table rows.""" + rows = [[field.strip() for field in row] for row in csv.reader(report.splitlines()) if row] + settings = dict(self._TRANSFERBENCH_ENV, NUM_ITERATIONS=iterations) + for key, value in settings.items(): + matches = [row for row in rows if row[0] == key] + if len(matches) != 1 or int(matches[0][1]) != value: + raise ValueError('Unexpected TransferBench setting: {}'.format(key)) + + executors = [row for row in rows if row[0].startswith('Executor:')] + transfers = [row for row in rows if row[0].startswith('Transfer ')] + aggregates = [row for row in rows if row[0] == 'Aggregate (CPU)'] + deviations = [row for row in rows if row[0] == 'StandardDev'] + if len(executors) != 1 or len(transfers) != 1 or len(aggregates) != 1 or len(deviations) != 1: + raise ValueError('Incomplete or multi-device TransferBench report') + if executors[0][0] != 'Executor: DMA 00' or transfers[0][0] != 'Transfer 0': + raise ValueError('Unexpected TransferBench executor') + source, destination = self._transferbench_route(mem_type) + if transfers[0][4].split() != [source, '->', 'D0:1', '->', destination]: + raise ValueError('Unexpected TransferBench route') + for row in (executors[0], transfers[0], aggregates[0]): + if row[3].split() != [str(size), 'bytes']: + raise ValueError('Unexpected TransferBench byte count') + return self._transferbench_samples(rows, size, iterations) + + def _process_transferbench_result(self, cmd_idx, raw_output): + """Reduce a complete size sweep to the maximum arithmetic mean bandwidth.""" + try: + if '[ERROR]' in raw_output: + raise ValueError('TransferBench reported an error') + reports = re.split(r'(?m)^TransferBench v[^\n]*\n', raw_output) + if len(reports) != len(self._TRANSFERBENCH_SIZES) + 1: + raise ValueError('Incomplete TransferBench size sweep') + means = [ + self._transferbench_report(report, size, iterations, self._args.mem_type[cmd_idx]) + for report, size, iterations in zip( + reports[1:], self._TRANSFERBENCH_SIZES, self._TRANSFERBENCH_ITERATIONS + ) + ] + bandwidth = max(means) + if not math.isfinite(bandwidth) or bandwidth <= 0: + raise ValueError('Nonpositive TransferBench result') + except (ValueError, IndexError, OverflowError) as error: + logger.error( + 'The result format is invalid - round: {}, benchmark: {}, error: {}, raw output: {}.'.format( + self._curr_run_index, self._name, error, raw_output + ) + ) + return False + metric = self._metrics[self._mem_types.index(self._args.mem_type[cmd_idx])] + self._result.add_result(metric, bandwidth) + return True + def _process_raw_result(self, cmd_idx, raw_output): """Function to parse raw results and save the summarized results. @@ -62,6 +238,9 @@ def _process_raw_result(self, cmd_idx, raw_output): """ self._result.add_raw_data('raw_output_' + self._args.mem_type[cmd_idx], raw_output, self._args.log_raw_data) + if self._backend == 'transferbench': + return self._process_transferbench_result(cmd_idx, raw_output) + mem_bw = -1 value_index = -1 valid = True diff --git a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py index 86612f053..50a439194 100644 --- a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py +++ b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py @@ -240,7 +240,9 @@ def _preprocess(self): os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-DeepSpeed/' ) else: - self._args.code_base = os.path.join(os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-LM') + self._args.code_base = os.getenv('SB_MEGATRON_PATH') or os.path.join( + os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-LM' + ) if not os.path.exists(self._args.code_base) or not os.path.exists( os.path.join(self._args.code_base, f'pretrain_{self._args.model}.py') @@ -540,6 +542,8 @@ def _megatron_command(self, precision): # noqa: C901 else: command = f'torchrun {self._distributed_args} {script_path} {megatron_options} {self._data_options}' + if self._args.extra: + command += f' {self._args.extra}' return command def _train_step(self, precision): # noqa: E501 @@ -547,8 +551,13 @@ def _train_step(self, precision): # noqa: E501 command = self._megatron_command(precision) local_rank = os.environ.pop('OMPI_COMM_WORLD_LOCAL_RANK', None) logger.info('Running command: {}.'.format(command)) - output = run_command(command, flush_output=True) - os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank + try: + output = run_command(command, flush_output=True) + finally: + if local_rank is not None: + os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank + if output.returncode != 0: + raise RuntimeError('Megatron training failed with exit code {}.'.format(output.returncode)) iteration_times = [] info = {} @@ -644,6 +653,8 @@ def _generate_dataset(self): # noqa: C901 Return: True if dataset is created successfully. """ + if not self._args.code_base and not self._args.deepspeed: + self._args.code_base = os.getenv('SB_MEGATRON_PATH') or self._args.code_base # Validate num_workers unconditionally so a negative value is rejected even when # dataset files already exist (it would otherwise be emitted as `--num-workers -1` # into the Megatron training command). diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index 7810b982d..dd21db20e 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -131,6 +131,12 @@ def _finalize_periodic_logging(self, periodic, info_key='loss'): def add_parser_arguments(self): """Add PyTorch model benchmark-specific arguments to the argument parser.""" super().add_parser_arguments() + self._parser.add_argument( + '--optimizer_eps', + type=float, + default=1e-8, + help='Adam/AdamW epsilon. Use a representable value (for example 1e-4) for native FP16 training.', + ) self._parser.add_argument( '--deterministic_seed', type=int, @@ -446,12 +452,18 @@ def _create_optimizer(self): self._model.parameters(), lr=1e-5, momentum=0.9, weight_decay=1e-4, nesterov=True ) elif self._optimizer_type == Optimizer.ADAM: - self._optimizer = torch.optim.Adam(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) + self._optimizer = torch.optim.Adam( + self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps + ) elif self._optimizer_type == Optimizer.ADAMW: if hasattr(torch.optim, 'AdamW'): - self._optimizer = torch.optim.AdamW(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) + self._optimizer = torch.optim.AdamW( + self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps + ) else: - self._optimizer = transformers.AdamW(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) + self._optimizer = transformers.AdamW( + self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps + ) else: self._optimizer = None diff --git a/superbench/benchmarks/model_benchmarks/pytorch_bert.py b/superbench/benchmarks/model_benchmarks/pytorch_bert.py index 94c0d9c45..f052c1b3a 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_bert.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_bert.py @@ -62,6 +62,7 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, + Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py b/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py index 67f781d0a..aaee40cc6 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py @@ -62,6 +62,7 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, + Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/benchmarks/model_benchmarks/pytorch_llama.py b/superbench/benchmarks/model_benchmarks/pytorch_llama.py index d57b60821..c418932b2 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_llama.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_llama.py @@ -62,6 +62,7 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, + Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py index 139716cdc..16db79b73 100644 --- a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py +++ b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py @@ -4,11 +4,18 @@ """Tests for mem-bw benchmark.""" import numbers +import os +from pathlib import Path +import re +import shlex +import subprocess import unittest +from unittest import mock from tests.helper import decorator from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform +from superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance import RocmMemBwBenchmark class RocmMemBwTest(BenchmarkTestCase, unittest.TestCase): @@ -18,7 +25,52 @@ def setUpClass(cls): """Hook method for setting up class fixture before running tests in the class.""" super().setUpClass() cls.createMockEnvs(cls) - cls.createMockFiles(cls, ['bin/hipBusBandwidth']) + cls.createMockFiles(cls, ['bin/hipBusBandwidth', 'bin/TransferBench']) + + def setUp(self): + """Keep the legacy default independent of the image's backend selection.""" + self.environment = mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'hipbusbandwidth'}) + self.environment.start() + self.addCleanup(self.environment.stop) + module = 'superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance' + libc_patch = mock.patch(module + '.ctypes.CDLL') + self.libc = libc_patch.start() + self.addCleanup(libc_patch.stop) + self.libc.return_value.sched_getcpu.return_value = 0 + nodes_patch = mock.patch(module + '.Path.iterdir', autospec=True) + self.cpu_nodes = nodes_patch.start() + self.addCleanup(nodes_patch.stop) + self.cpu_nodes.return_value = [Path('/sys/devices/system/cpu/cpu0/node0')] + + def _transferbench(self, parameters=''): + """Prepare the explicitly selected backend with mock executables.""" + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw', parameters) + self.assertTrue(benchmark._preprocess()) + return benchmark + + @staticmethod + def _fixture(memory='pinned', direction='htod'): + """Read captured TransferBench v1.69.00 GPU2 output, logical device zero.""" + return Path('tests/data/rocm_transferbench_{}_{}.log'.format(memory, direction)).read_text() + + def _report(self, size, durations, direction='htod', memory='pinned'): + """Build variable-size reports using the measured CLI format, including misleading summaries.""" + header = self._fixture(memory, direction).split(' Executor:')[0] + header = re.sub(r'(NUM_ITERATIONS\s*,\s*)3,', r'\g<1>{},'.format(len(durations)), header) + host = 'P0' if memory == 'pinned' else 'H0' + route = '{} -> D0:1 -> G0'.format(host) if direction == 'htod' else 'G0 -> D0:1 -> {}'.format(host) + rows = [ + 'Executor: DMA 00, 999.000 GB/s, 1.000 ms, {} bytes, 999.000 GB/s (sum),'.format(size), + 'Transfer 0, 888.000 GB/s, 1.000 ms, {} bytes, {},'.format(size, route), + ] + for index, duration in reversed(list(enumerate(durations, 1))): + rows.append('Iter {:03d}, {:.3f} GB/s, {:.3f} ms, , ,'.format(index, size / duration / 1e6, duration)) + rows.extend([ + 'StandardDev, 0.000 GB/s, 0.000 ms, , ,', + 'Aggregate (CPU), 777.000 GB/s, 1.000 ms, {} bytes, Overhead 0.000 ms,'.format(size), + ]) + return header + '\n'.join(rows) + '\n' @decorator.load_data('tests/data/rocm_memory_h2d_bw.log') @decorator.load_data('tests/data/rocm_memory_d2h_bw.log') @@ -56,3 +108,292 @@ def test_rocm_memory_bw_performance(self, raw_output_h2d, raw_output_d2h): assert (benchmark.result['h2d_bw'][0] == 25.2351) assert (benchmark.result['d2h_bw'][0] == 27.9348) + + def test_legacy_default_and_arguments(self): + """Retain the old executable, flags, normalization and ignored NUMA argument.""" + with mock.patch.dict(os.environ): + os.environ.pop('SB_ROCM_MEM_BW_BACKEND', None) + benchmark = RocmMemBwBenchmark('mem-bw', '--mem_type DTOH --memory unpinned --numa 3') + self.assertTrue(benchmark._preprocess()) + self.assertEqual(benchmark._bin_name, 'hipBusBandwidth') + self.assertEqual(len(benchmark._commands), 1) + self.assertTrue(benchmark._commands[0].endswith('hipBusBandwidth --d2h --unpinned')) + self.assertEqual(benchmark._args.numa, 3) + self.assertNotIn('numactl', benchmark._commands[0]) + + def test_transferbench_exact_legacy_policy(self): + """Cover the complete HIP5.5 size/trial arrays and all controllable timing settings.""" + benchmark = self._transferbench('--numa 3') + sizes = ( + 64, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, + 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, + 134217728, 268435456, 536870912 + ) + iterations = ( + 1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, + 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20 + ) + self.assertEqual(benchmark._TRANSFERBENCH_SIZES, sizes) + self.assertEqual(benchmark._TRANSFERBENCH_ITERATIONS, iterations) + self.assertEqual(len(benchmark._commands), 2) + for direction, command in enumerate(benchmark._commands): + commands = command.split(' && ') + self.assertEqual(len(commands), 23) + for subcommand, size, count in zip(commands, sizes, iterations): + tokens = shlex.split(subcommand) + self.assertEqual(tokens[-3:], [ + 'cmdline', str(size), '1 1 P0 D0 G0' if direction == 0 else '1 1 G0 D0 P0' + ]) + for setting in ( + 'NUM_ITERATIONS={}'.format(count), 'NUM_WARMUPS=0', 'NUM_SUBITERATIONS=1', + 'SHOW_ITERATIONS=1', 'OUTPUT_TO_CSV=1', 'USE_HIP_EVENTS=1', 'USE_HSA_DMA=0', + 'USE_INTERACTIVE=0', 'ALWAYS_VALIDATE=0' + ): + self.assertIn(setting, tokens) + self.assertNotIn('numactl', command) + self.assertNotIn('G1', command) + self.assertEqual(benchmark._args.numa, 3) + + def test_transferbench_pageable_subset(self): + """Preserve memory and direction selection without introducing new CLI arguments.""" + benchmark = self._transferbench('--memory unpinned --mem_type DTOH') + self.assertEqual(len(benchmark._commands), 1) + self.assertIn("'1 1 G0 D0 H0'", benchmark._commands[0]) + self.assertNotIn('P0', benchmark._commands[0]) + + def test_transferbench_numa_does_not_override_logical_gpu_locality(self): + """P0 means the visible GPU's nearest node, not physical GPU zero or NUMA zero.""" + with mock.patch.dict(os.environ, {'HIP_VISIBLE_DEVICES': '5'}): + for memory, host in (('pinned', 'P0'), ('unpinned', 'H0')): + with self.subTest(memory=memory): + baseline = self._transferbench('--memory {}'.format(memory)) + explicit = self._transferbench('--memory {} --numa 1'.format(memory)) + self.assertEqual(baseline._commands, explicit._commands) + self.assertIn("'1 1 {} D0 G0'".format(host), explicit._commands[0]) + self.assertIn("'1 1 G0 D0 {}'".format(host), explicit._commands[1]) + self.assertNotIn('C0', explicit._commands[0]) + self.assertNotIn('G5', explicit._commands[0]) + self.assertEqual(explicit._args.numa, 1) + + def test_transferbench_pageable_worker_nodes(self): + """Resolve node0/node1 from the worker CPU, not --numa or the GPU index.""" + for cpu, node in ((0, 0), (48, 1)): + with self.subTest(cpu=cpu, node=node): + self.libc.return_value.sched_getcpu.return_value = cpu + self.cpu_nodes.return_value = [Path('/sys/devices/system/cpu/cpu{}/node{}'.format(cpu, node))] + benchmark = self._transferbench('--memory unpinned --numa 3') + self.cpu_nodes.assert_called_with(Path('/sys/devices/system/cpu/cpu{}'.format(cpu))) + self.assertEqual(benchmark._worker_numa_node, node) + self.assertIn("'1 1 H{} D0 G0'".format(node), benchmark._commands[0]) + self.assertIn("'1 1 G0 D0 H{}'".format(node), benchmark._commands[1]) + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + raw = self._fixture('unpinned').replace('H0', 'H{}'.format(node)) + self.assertTrue(benchmark._process_raw_result(0, raw)) + wrong_node = self._fixture('unpinned').replace('H0', 'H{}'.format(1 - node)) + self.assertFalse(benchmark._process_raw_result(0, wrong_node)) + self.assertEqual(len(benchmark.result['h2d_bw']), 1) + self.assertEqual(benchmark._args.numa, 3) + + def test_transferbench_pageable_detection_errors(self): + """Fail explicitly on unavailable CPU detection or missing/ambiguous/inaccessible topology.""" + module = 'superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance' + for error in ('library', 'symbol', 'cpu', 'missing', 'ambiguous', 'permission'): + with self.subTest(error=error): + self.libc.side_effect = None + self.libc.return_value.sched_getcpu.side_effect = None + self.libc.return_value.sched_getcpu.return_value = 0 + self.cpu_nodes.side_effect = None + self.cpu_nodes.return_value = [Path('node0')] + if error == 'library': + self.libc.side_effect = OSError('libc unavailable') + elif error == 'symbol': + self.libc.return_value.sched_getcpu.side_effect = AttributeError('sched_getcpu unavailable') + elif error == 'cpu': + self.libc.return_value.sched_getcpu.return_value = -1 + elif error == 'missing': + self.cpu_nodes.return_value = [Path('topology'), Path('node-invalid')] + elif error == 'ambiguous': + self.cpu_nodes.return_value = [Path('node0'), Path('node1')] + else: + self.cpu_nodes.side_effect = PermissionError('sysfs denied') + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw', '--memory unpinned') + with mock.patch(module + '.logger.error') as log: + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) + self.assertEqual(benchmark._commands, []) + self.assertIsNone(benchmark._worker_numa_node) + self.assertIn('Cannot determine worker-local NUMA placement', log.call_args[0][0]) + + def test_pinned_and_legacy_do_not_detect_worker_numa(self): + """Keep pinned P0 GPU-local and leave both legacy allocation modes unchanged.""" + self.libc.side_effect = OSError('CPU detection unavailable') + benchmark = self._transferbench('--memory pinned --numa 1') + self.assertIn("'1 1 P0 D0 G0'", benchmark._commands[0]) + for memory in ('pinned', 'unpinned'): + with self.subTest(memory=memory): + benchmark = RocmMemBwBenchmark('mem-bw', '--memory {} --numa 1'.format(memory)) + self.assertTrue(benchmark._preprocess()) + self.assertNotIn('numactl', benchmark._commands[0]) + self.libc.assert_not_called() + + def test_transferbench_measured_fixtures(self): + """Use real pinned/pageable output, not flat CSV or aggregate executor bandwidth.""" + expected_times = { + ('pinned', 'htod'): (0.100, 0.104, 23.315), + ('pinned', 'dtoh'): (0.093, 0.094, 23.555), + ('unpinned', 'htod'): (0.131, 0.139, 23.634), + ('unpinned', 'dtoh'): (0.133, 0.135, 23.265), + } + for (memory, direction), times in expected_times.items(): + with self.subTest(memory=memory, direction=direction): + benchmark = self._transferbench('--memory {} --mem_type {}'.format(memory, direction)) + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + raw = self._fixture(memory, direction) + self.assertTrue(benchmark._process_raw_result(0, raw)) + metric = 'h2d_bw' if direction == 'htod' else 'd2h_bw' + self.assertEqual(len(benchmark.result[metric]), 1) + self.assertAlmostEqual(benchmark.result[metric][0], sum(4.194 / time for time in times) / 3) + self.assertEqual(benchmark.raw_data['raw_output_' + direction], [raw]) + + def test_transferbench_arithmetic_mean_then_max(self): + """Neither fastest sample, inverse mean duration nor aggregate rows are the metric.""" + benchmark = self._transferbench() + benchmark._TRANSFERBENCH_SIZES = (1000000, 2000000) + benchmark._TRANSFERBENCH_ITERATIONS = (2, 2) + raw = self._report(1000000, (1, 0.125)) + self._report(2000000, (0.5, 0.5)) + self.assertTrue(benchmark._process_raw_result(0, raw)) + self.assertEqual(benchmark.result['h2d_bw'], [4.5]) + + def test_transferbench_full_sweep_and_integer_conversion(self): + """Include all trial IDs, sub-KB zero contributions and old integer-byte truncation.""" + benchmark = self._transferbench() + raw = ''.join( + self._report(size, [1] * count) + for size, count in zip(benchmark._TRANSFERBENCH_SIZES, benchmark._TRANSFERBENCH_ITERATIONS) + ) + self.assertTrue(benchmark._process_raw_result(0, raw)) + self.assertEqual(benchmark.result['h2d_bw'], [536.870]) + benchmark._TRANSFERBENCH_SIZES = (64, 1024) + benchmark._TRANSFERBENCH_ITERATIONS = (2, 2) + raw = self._report(64, (16, 1)) + self._report(1024, (1, 1)) + self.assertTrue(benchmark._process_raw_result(0, raw)) + self.assertEqual(benchmark.result['h2d_bw'][-1], 0.001) + + def test_transferbench_rejects_incomplete_and_wrong_reports(self): + """Reject missing/extra sizes, samples, executors, settings and incorrect routes.""" + raw = self._fixture() + corruptions = [ + '', raw + raw, raw[:raw.index('Aggregate (CPU)')], + re.sub(r'^.*Iter 001.*\n', '', raw, flags=re.MULTILINE), + raw.replace('Iter 001', 'Iter 002'), raw.replace('Iter 001', 'Iter 004'), + raw.replace('DMA 00', 'DMA 01'), raw.replace('DMA 00', 'GFX 00'), + raw.replace('Transfer 0', 'Transfer 1'), raw.replace('G0', 'G1'), + raw.replace('D0:1', 'D1:1'), raw.replace('P0', 'H0'), + raw.replace('P0 -> D0:1 -> G0', 'G0 -> D0:1 -> P0'), + raw.replace('4194304 bytes', '4194305 bytes'), + raw.replace('NUM_WARMUPS , 0', 'NUM_WARMUPS , 3'), + raw.replace('NUM_ITERATIONS , 3', 'NUM_ITERATIONS , 2'), + raw + '[ERROR] validation failed\n', + raw.replace('Transfer 0', 'Transfer 0, bad'), + raw.replace('StandardDev', 'missing'), + raw.replace(' Iter 001', 'Transfer 1, 1 GB/s, 1 ms, 4194304 bytes, P0 -> D0:1 -> G0\nIter 001'), + ] + for index, corrupted in enumerate(corruptions): + with self.subTest(case=index): + benchmark = self._transferbench() + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + self.assertFalse(benchmark._process_raw_result(0, corrupted)) + self.assertNotIn('h2d_bw', benchmark.result) + self.assertEqual(benchmark.raw_data['raw_output_htod'], [corrupted]) + + def test_transferbench_rejects_invalid_numeric_samples(self): + """Reject nonfinite/nonpositive timings and nonphysical bandwidths before reduction.""" + raw = self._fixture() + for field in ('42.133 GB/s', '0.100 ms'): + for invalid in ('nan', 'inf', '-inf', '-1', '0', 'bogus'): + with self.subTest(field=field, invalid=invalid): + benchmark = self._transferbench() + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + corrupted = raw.replace(field, invalid + ' ' + field.split()[1]) + self.assertFalse(benchmark._process_raw_result(0, corrupted)) + self.assertNotIn('h2d_bw', benchmark.result) + + def test_transferbench_rejects_partial_size_sweep(self): + """Do not accept a valid single-size run as a full legacy-policy sweep.""" + benchmark = self._transferbench() + self.assertFalse(benchmark._process_raw_result(0, self._fixture())) + + def test_transferbench_failure_does_not_fall_back(self): + """Execution and parse errors use framework return codes without invoking hipBusBandwidth.""" + for code, raw, expected in ( + (1, '[ERROR] allocation failed', ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE), + (0, 'malformed', ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE), + ): + with self.subTest(code=code): + benchmark = self._transferbench() + with mock.patch( + 'superbench.benchmarks.micro_benchmarks.micro_base.run_command', + return_value=subprocess.CompletedProcess([], code, raw) + ) as invoke: + self.assertFalse(benchmark._benchmark()) + self.assertEqual(benchmark.return_code, expected) + self.assertEqual(invoke.call_count, 1) + self.assertNotIn('hipBusBandwidth', invoke.call_args[0][0]) + + def test_transferbench_missing_binary_and_unknown_backend(self): + """Explicit selection is never replaced by an available legacy binary.""" + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw') + with mock.patch('shutil.which', return_value=None): + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_BINARY_NOT_EXIST) + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'invalid'}): + benchmark = RocmMemBwBenchmark('mem-bw') + with mock.patch('shutil.which', return_value=None) as lookup: + self.assertFalse(benchmark._preprocess()) + lookup.assert_not_called() + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + + def test_transferbench_tolerant_failure_keeps_direction_mapping(self): + """An invalid H2D result must not mislabel a subsequent successful D2H result.""" + benchmark = self._transferbench('--tolerant_fail') + benchmark._TRANSFERBENCH_SIZES = (4194304,) + benchmark._TRANSFERBENCH_ITERATIONS = (3,) + results = [ + subprocess.CompletedProcess([], 0, 'invalid'), + subprocess.CompletedProcess([], 0, self._fixture(direction='dtoh')), + ] + with mock.patch( + 'superbench.benchmarks.micro_benchmarks.micro_base.run_command', side_effect=results + ) as invoke: + self.assertFalse(benchmark._benchmark()) + self.assertEqual(invoke.call_count, 2) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertNotIn('h2d_bw', benchmark.result) + self.assertEqual(len(benchmark.result['d2h_bw']), 1) + + def test_transferbench_shell_quoting_and_failure_chain(self): + """Quote explicit binary paths and stop a failed sweep before subsequent sizes.""" + binary_dir = Path(self._tmp_dir) / 'bin with spaces' + binary_dir.mkdir(exist_ok=True) + binary = binary_dir / 'TransferBench' + binary.write_text('#!/bin/sh\necho "[ERROR] synthetic failure"\nexit 3\n') + binary.chmod(0o755) + benchmark = self._transferbench('--bin_dir {}'.format(shlex.quote(str(binary_dir)))) + result = subprocess.run(benchmark._commands[0], shell=True, text=True, stdout=subprocess.PIPE, timeout=5) + self.assertEqual(result.returncode, 3) + self.assertEqual(result.stdout.count('[ERROR] synthetic failure'), 1) + + def test_transferbench_invalid_memory_and_direction(self): + """Retain existing validation for unsupported YAML/CLI options.""" + for parameters in ('--memory registered', '--mem_type dtod', '--memory PINNED'): + with self.subTest(parameters=parameters): + with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): + benchmark = RocmMemBwBenchmark('mem-bw', parameters) + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) diff --git a/tests/benchmarks/model_benchmarks/test_megatron_launch.py b/tests/benchmarks/model_benchmarks/test_megatron_launch.py new file mode 100644 index 000000000..81677341a --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_megatron_launch.py @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Regression tests for Megatron command forwarding and failure reporting.""" + +import os +from subprocess import CompletedProcess +from unittest import mock + +import pytest + +from superbench.benchmarks import Precision +from superbench.benchmarks.model_benchmarks.megatron_gpt3 import MegatronGPT +from superbench.benchmarks.model_benchmarks.model_base import ModelBenchmark + + +def make_benchmark(parameters=''): + """Build a command-only benchmark without initializing MPI or downloading data.""" + benchmark = MegatronGPT('megatron-gpt', parameters) + benchmark.add_parser_arguments() + valid, benchmark._args, _ = benchmark.parse_args() + assert valid + benchmark._distributed_args = '--nproc_per_node 2' + benchmark._data_options = '--mock-data' + return benchmark + + +def test_extra_arguments_forwarded(): + """Version-specific options must reach the selected Megatron checkout.""" + benchmark = make_benchmark('--extra "--vocab-size 128 --attention-backend unfused"') + command = benchmark._megatron_command(Precision.BFLOAT16) + assert command.endswith('--mock-data --vocab-size 128 --attention-backend unfused') + + +@pytest.mark.parametrize( + 'explicit,deepspeed,override,expected', + [ + ('', False, '/rocm10/Megatron-LM', '/rocm10/Megatron-LM'), + ('', False, '', '/legacy/third_party/Megatron/Megatron-LM'), + ('', True, '/rocm10/Megatron-LM', '/legacy/third_party/Megatron/Megatron-DeepSpeed/'), + ('/explicit', False, '/rocm10/Megatron-LM', '/explicit'), + ] +) +def test_code_base_selection(explicit, deepspeed, override, expected): + """The image override must preserve explicit paths and legacy/DeepSpeed defaults.""" + benchmark = make_benchmark('--batch_size 32 --num_gpus 2') + benchmark._args.code_base = explicit + benchmark._args.deepspeed = deepspeed + benchmark._num_nodes = 1 + with mock.patch.dict(os.environ, {'SB_MICRO_PATH': '/legacy', 'SB_MEGATRON_PATH': override}): + with mock.patch.object(ModelBenchmark, '_preprocess', return_value=True): + with mock.patch('superbench.benchmarks.model_benchmarks.megatron_gpt3.os.path.exists', return_value=True): + assert benchmark._preprocess() + assert benchmark._args.code_base == expected + + +@pytest.mark.parametrize( + 'explicit,deepspeed,expected', + [('', False, '/rocm10/Megatron-LM'), ('/explicit', False, '/explicit'), ('', True, '')] +) +def test_environment_path_available_during_dataset_generation(explicit, deepspeed, expected): + """Apply the environment path before dataset generation and final path validation.""" + benchmark = make_benchmark('--mock_data --num_workers 0') + benchmark._args.code_base = explicit + benchmark._args.deepspeed = deepspeed + with mock.patch.dict(os.environ, {'SB_MEGATRON_PATH': '/rocm10/Megatron-LM'}): + assert benchmark._generate_dataset() + assert benchmark._args.code_base == expected + + +@pytest.mark.parametrize('local_rank', [None, '0']) +def test_training_failure_restores_environment(local_rank): + """Do not report failed subprocesses as successful timings or assign None to environ.""" + benchmark = make_benchmark() + with mock.patch.dict(os.environ): + os.environ.pop('OMPI_COMM_WORLD_LOCAL_RANK', None) + if local_rank is not None: + os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank + with mock.patch( + 'superbench.benchmarks.model_benchmarks.megatron_gpt3.run_command', + return_value=CompletedProcess('torchrun', 2, 'training failed') + ): + with pytest.raises(RuntimeError, match='exit code 2'): + benchmark._train_step(Precision.FLOAT32) + assert os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') == local_rank diff --git a/tests/benchmarks/model_benchmarks/test_transformer_precisions.py b/tests/benchmarks/model_benchmarks/test_transformer_precisions.py new file mode 100644 index 000000000..b1c6ca585 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_transformer_precisions.py @@ -0,0 +1,38 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Precision coverage for Transformer Engine consumers.""" + +import pytest +import torch + +from superbench.benchmarks import Precision +from superbench.benchmarks.model_benchmarks.model_base import Optimizer +from superbench.benchmarks.model_benchmarks.pytorch_bert import PytorchBERT +from superbench.benchmarks.model_benchmarks.pytorch_gpt2 import PytorchGPT2 +from superbench.benchmarks.model_benchmarks.pytorch_llama import PytorchLlama + + +@pytest.mark.parametrize('benchmark', [PytorchBERT, PytorchGPT2, PytorchLlama]) +def test_transformer_bfloat16_supported(benchmark): + """BF16 must not be silently skipped by the generic precision filter.""" + instance = benchmark('precision-test') + assert Precision.BFLOAT16 in instance._supported_precision + instance.add_parser_arguments() + valid, arguments, _ = instance.parse_args() + assert valid + assert Precision.BFLOAT16 not in arguments.precision + + +@pytest.mark.parametrize('optimizer', [Optimizer.ADAM, Optimizer.ADAMW]) +@pytest.mark.parametrize('parameters,epsilon', [('', 1e-8), ('--optimizer_eps 1e-4', 1e-4)]) +def test_optimizer_epsilon(optimizer, parameters, epsilon): + """Preserve the default and permit an explicitly FP16-representable epsilon.""" + benchmark = PytorchGPT2('precision-test', parameters) + benchmark.add_parser_arguments() + valid, benchmark._args, _ = benchmark.parse_args() + assert valid + benchmark._model = torch.nn.Linear(16, 16) + benchmark._optimizer_type = optimizer + assert benchmark._create_optimizer() + assert benchmark._optimizer.param_groups[0]['eps'] == epsilon diff --git a/tests/test_rocm10_dockerfile.py b/tests/test_rocm10_dockerfile.py index 48f3994f5..41dc957c7 100644 --- a/tests/test_rocm10_dockerfile.py +++ b/tests/test_rocm10_dockerfile.py @@ -5,7 +5,9 @@ import os import subprocess +import tempfile import unittest +import venv from pathlib import Path @@ -17,6 +19,12 @@ def setUpClass(cls): """Load the Dockerfile and extract RCCL test architecture handling.""" root = Path(__file__).resolve().parents[1] cls.dockerfile = (root / 'dockerfile' / 'rocm10.0.x.dockerfile').read_text(encoding='utf-8') + env_start = cls.dockerfile.index("printf 'export ROCM_PATH=%q") + env_end = cls.dockerfile.index('\n\n', env_start) + cls.environment_script = cls.dockerfile[env_start:env_end] + registration_start = cls.dockerfile.index("RUN python3 -c 'import sysconfig;") + registration_end = cls.dockerfile.index('\n\n', registration_start) + cls.registration_script = cls.dockerfile[registration_start + len('RUN '):registration_end] start = cls.dockerfile.index('rccl_architectures=$(printf') end = cls.dockerfile.index(' cmake -S /tmp/rocm-systems', start) cls.routing = cls.dockerfile[start:end] + 'printf \'%s\\n\' "$rccl_architectures"\n' @@ -37,7 +45,7 @@ def run_routing(self, targets): def test_architecture_routing(self): """Normalize single, multiple, and whitespace-separated architectures.""" for targets, expected in ( - ('gfx942 gfx950', 'gfx942;gfx950'), + ('gfx942 gfx950 gfx1250', 'gfx942;gfx950;gfx1250'), ('gfx942', 'gfx942'), ('gfx90a gfx942 gfx950 gfx1250', 'gfx90a;gfx942;gfx950;gfx1250'), (' gfx942\t gfx950\n', 'gfx942;gfx950'), @@ -55,16 +63,101 @@ def test_empty_architectures_fail_explicitly(self): self.assertNotEqual(result.returncode, 0) self.assertIn('AMDGPU_TARGETS must contain at least one GPU architecture.', result.stderr) + def test_default_build_parallelism(self): + """Default native builds to 64 jobs while retaining the framework build cap.""" + self.assertIn('ARG NUM_MAKE_JOBS=64', self.dockerfile) + self.assertIn('CMAKE_BUILD_PARALLEL_LEVEL="${NUM_MAKE_JOBS}"', self.dockerfile) + self.assertIn('if [ "${framework_jobs}" -gt 16 ]; then framework_jobs=16; fi', self.dockerfile) + def test_all_device_sdk_uses_base_package_ecosystem(self): - """Keep all-device wheels rather than installing a second native SDK.""" + """Discover the installed wheel SDK without an alias or global loader override.""" self.assertIn('rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:', self.dockerfile) self.assertIn('"rocm[devel,libraries,device-all]==${ROCM_VERSION}"', self.dockerfile) self.assertIn('rocm-sdk init', self.dockerfile) - self.assertIn('ln -s "$(rocm-sdk path --root)" "${ROCM_PATH}"', self.dockerfile) - self.assertNotIn('apt install -y amdrocm', self.dockerfile) + self.assertIn('ROCM_PATH="$(rocm-sdk path --root)"', self.dockerfile) + self.assertNotIn('/opt/rocm/wheel', self.dockerfile) + self.assertNotIn('ln -s "$(rocm-sdk path --root)"', self.dockerfile) + self.assertNotIn('/etc/ld.so.conf.d/rocm.conf', self.dockerfile) + self.assertIn('ENV BASH_ENV=/etc/profile.d/rocm10-env.sh', self.dockerfile) + self.assertIn('ENTRYPOINT ["/bin/bash", "-e", "-c", "exec \\"$@\\"", "--"]', self.dockerfile) + self.assertIn('CMD ["/bin/bash"]', self.dockerfile) + + def test_sdk_environment_uses_discovered_paths(self): + """Activate the SDK for shell builds and arbitrary container commands.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + sdk_root = str(root / 'sdk with spaces') + bin_dir = root / 'venv' / 'bin' + bin_dir.mkdir(parents=True) + sdk = bin_dir / 'rocm-sdk' + sdk.write_text('#!/bin/sh\n[ "$1" = path ] && [ "$2" = --root ] || exit 2\n' + 'printf "%s\\n" "$TEST_SDK_ROOT"\n') + sdk.chmod(0o755) + env = os.environ.copy() + env.pop('BASH_ENV', None) + env.update({ + 'VIRTUAL_ENV': str(root / 'venv'), + 'TEST_SDK_ROOT': sdk_root, + 'MPI_HOME': '/vendor/mpi', + 'SB_MICRO_PATH': '/superbench', + 'EXTRAS_PATH': '/vendor/extras', + 'ROCM_PATH': '/stale/sdk', + 'ROCM_HOME': '/stale/sdk', + 'HIP_PATH': '/stale/sdk', + 'RCCL_HOME': '/stale/sdk', + 'LD_LIBRARY_PATH': '/stale/sdk/lib', + 'PATH': f'{bin_dir}:/usr/bin:/bin', + }) + activation = root / 'rocm10-env.sh' + script = 'ROCM_PATH="$(rocm-sdk path --root)" && ' + self.environment_script.replace( + '/etc/profile.d/rocm10-env.sh', str(activation) + ) + subprocess.run(['/bin/bash', '-e', '-c', script], env=env, check=True) + sdk.unlink() + env.update({'BASH_ENV': str(activation), 'PATH': '/usr/bin:/bin'}) + result = subprocess.run( + ['/bin/bash', '-e', '-c', 'exec "$@"', '--', '/usr/bin/env'], + env=env, check=True, capture_output=True, text=True, + ) + actual = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line) + for name in ('ROCM_PATH', 'ROCM_HOME', 'HIP_PATH', 'RCCL_HOME'): + self.assertEqual(actual[name], sdk_root) + self.assertEqual( + actual['PATH'], f'/vendor/extras/bin:/vendor/mpi/bin:/superbench/bin:{sdk_root}/bin:/usr/bin:/bin' + ) + self.assertEqual( + actual['LD_LIBRARY_PATH'], + f'/vendor/extras/lib:/vendor/mpi/lib:{sdk_root}/lib:{sdk_root}/lib/llvm/lib:' + f'{sdk_root}/lib/host-math/lib:{sdk_root}/lib/rocm_sysdeps/lib', + ) + + def test_sdk_discovery_failure_stops_environment_generation(self): + """Never publish stale SDK paths if build-time discovery fails.""" + with tempfile.TemporaryDirectory() as directory: + bin_dir = Path(directory) / 'bin' + bin_dir.mkdir() + sdk = bin_dir / 'rocm-sdk' + sdk.write_text('#!/bin/sh\necho "SDK unavailable" >&2\nexit 7\n') + sdk.chmod(0o755) + env = os.environ.copy() + env.update({'PATH': f'{bin_dir}:/usr/bin:/bin'}) + env.pop('BASH_ENV', None) + activation = Path(directory) / 'rocm10-env.sh' + script = 'ROCM_PATH="$(rocm-sdk path --root)" && ' + self.environment_script.replace( + '/etc/profile.d/rocm10-env.sh', str(activation) + ) + result = subprocess.run( + ['/bin/bash', '-e', '-c', script], + env=env, check=False, capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 7) + self.assertIn('SDK unavailable', result.stderr) + self.assertEqual(result.stdout, '') + self.assertFalse(activation.exists()) def test_rccl_uses_packaged_library_and_matched_test_sources(self): """Build only test clients and retain runtime library search paths.""" + self.assertIn('ARG AMDGPU_TARGETS="gfx942 gfx950 gfx1250"', self.dockerfile) self.assertIn('test -r "${ROCM_PATH}/lib/librccl.so"', self.dockerfile) self.assertIn('ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9', self.dockerfile) self.assertIn('-DGPU_TARGETS="${rccl_architectures}"', self.dockerfile) @@ -73,35 +166,169 @@ def test_rccl_uses_packaged_library_and_matched_test_sources(self): self.assertNotIn('https://github.com/ROCmSoftwarePlatform/rccl.git', self.dockerfile) self.assertNotIn('LD_PRELOAD=', self.dockerfile) - def test_legacy_mpi_and_scaffold_boundaries(self): + def test_doca_uses_only_the_userspace_profile(self): + """Use the matching Ubuntu release without installing host kernel drivers.""" + self.assertIn('ARG DOCA_VERSION=3.4.0', self.dockerfile) + self.assertIn('ARG DOCA_PACKAGE_VERSION=3.4.0-085000', self.dockerfile) + self.assertIn('-26.04-ubuntu2604_amd64.deb', self.dockerfile) + self.assertIn('"doca-ofed-userspace=${DOCA_PACKAGE_VERSION}"', self.dockerfile) + self.assertIn('"${DOCA_BUNDLE_SHA256}" /tmp/doca-host.deb | sha256sum --check --strict', self.dockerfile) + self.assertIn('apt-get purge -y doca-host', self.dockerfile) + self.assertNotIn('apt-get install -y doca-ofed ', self.dockerfile) + self.assertNotIn('amdgpu-dkms', self.dockerfile) + + def test_mpi_reuses_the_doca_package(self): + """Install vendor MPI before removing its repository, without a source build.""" + self.assertIn('ARG DOCA_OPENMPI_VERSION=5.0.10rc2.2605121430-1.b99be7132e', self.dockerfile) + self.assertIn('"openmpi=${DOCA_OPENMPI_VERSION}"', self.dockerfile) + self.assertIn("dpkg-query -L openmpi | sed -n 's#/bin/mpirun$##p'", self.dockerfile) + self.assertIn('test -x "${mpi_prefix}/bin/mpicc"', self.dockerfile) + self.assertIn('ln -s "${mpi_prefix}" "${MPI_HOME}"', self.dockerfile) + self.assertLess( + self.dockerfile.index('"openmpi=${DOCA_OPENMPI_VERSION}"'), + self.dockerfile.index('apt-get purge -y doca-host'), + ) + self.assertNotIn('ARG OPENMPI_VERSION=', self.dockerfile) + self.assertNotIn('https://github.com/open-mpi/ompi.git', self.dockerfile) + self.assertNotIn('--disable-oshmem', self.dockerfile) + + def test_prebuilt_blas_clients_keep_their_kernel_packs(self): + """Keep helper kernels and SDK dependency paths without extracting another runtime.""" + self.assertIn('therock-dist-linux-multiarch-tests-${ROCM_VERSION}.tar.gz', self.dockerfile) + self.assertIn("'./bin/rocblas-bench' './bin/hipblaslt-bench' './.kpack/blas_test_*.kpack'", self.dockerfile) + for arch in ('gfx942', 'gfx950', 'gfx1250'): + self.assertIn(f'test -s "${{SB_HOME}}/.kpack/blas_test_{arch}.kpack"', self.dockerfile) + self.assertIn( + '${ROCM_PATH}/lib/host-math/lib:${ROCM_PATH}/lib/rocm_sysdeps/lib', + self.environment_script, + ) + + def test_transferbench_backend_is_inherited_by_ssh(self): + """Preserve existing YAML while making the image's backend choice explicit.""" + self.assertIn('SB_ROCM_MEM_BW_BACKEND=transferbench', self.dockerfile) + self.assertEqual(self.dockerfile.count('> /etc/environment'), 1) + self.assertIn('"SB_ROCM_MEM_BW_BACKEND=${SB_ROCM_MEM_BW_BACKEND}"', self.dockerfile) + + def test_installation_order_and_prerequisites(self): + """Follow the older images' layout while retaining ROCm 10 prerequisites.""" + steps = ( + 'RUN apt-get update', + 'ARG DOCKER_VERSION=', + 'RUN mkdir -p /root/.ssh', + 'ARG DOCA_VERSION=', + '"rocm[devel,libraries,device-all]==${ROCM_VERSION}"', + "RUN python3 -c 'import sysconfig;", + '"amdrocm10-rvs=${RVS_VERSION}"', + 'WORKDIR ${SB_HOME}', + 'COPY third_party third_party', + 'RUN git init /tmp/rocm-systems', + 'make -C third_party fio rocm_perftest', + 'ARG ROCM_TESTS_SHA256=', + 'COPY . .', + "pip install -c /tmp/rocm10-constraints.txt '.[torch]'", + 'python3 -m pip install pytest pytest-timeout vcrpy', + 'bash dockerfile/etc/install-rocm10-frameworks.sh', + '> /etc/environment', + 'CXX="${ROCM_PATH}/bin/hipcc" make cppbuild', + 'make postinstall', + 'RUN python3 -m pip check', + 'sb --help', + 'rm -rf .git', + ) + positions = [self.dockerfile.index(step) for step in steps] + self.assertEqual(positions, sorted(positions)) + + def test_framework_runtime_configuration_survives_build_layers(self): + """Keep the selected Megatron path and precise Triton FP32 mode at runtime.""" + self.assertIn('SB_MEGATRON_PATH=/opt/rocm10-frameworks/Megatron-LM', self.dockerfile) + self.assertIn('AITER_USE_SYSTEM_TRITON=1', self.dockerfile) + self.assertIn('TRITON_F32_DEFAULT=ieee', self.dockerfile) + self.assertIn('bash dockerfile/etc/install-rocm10-frameworks.sh', self.dockerfile) + for name in ( + 'ROCM_PATH', 'ROCM_HOME', 'HIP_PATH', 'RCCL_HOME', + 'SB_MEGATRON_PATH', 'AITER_USE_SYSTEM_TRITON', 'TRITON_F32_DEFAULT', 'MAX_JOBS', + 'CUDA_DEVICE_MAX_CONNECTIONS', 'NVTE_FLASH_ATTN', 'NVTE_FUSED_ATTN', + 'NVTE_FUSED_ATTN_CK', 'NVTE_FUSED_ATTN_AOTRITON' + ): + self.assertIn(f'"{name}=${{{name}}}"', self.dockerfile) + self.assertIn('CUDA_DEVICE_MAX_CONNECTIONS=1', self.dockerfile) + self.assertIn('NVTE_FUSED_ATTN_CK=1', self.dockerfile) + self.assertIn('NVTE_FUSED_ATTN_AOTRITON=0', self.dockerfile) + self.assertLess( + self.dockerfile.index("RUN python3 -c 'import sysconfig;"), + self.dockerfile.index('bash dockerfile/etc/install-rocm10-frameworks.sh'), + ) + + def test_mpi_prefix_and_scaffold_boundaries(self): """Keep the MPI prefix while avoiding unqualified legacy dependencies.""" self.assertIn('MPI_HOME=/usr/local/mpi', self.dockerfile) - self.assertIn('ARG OPENMPI_VERSION=4.1.8', self.dockerfile) self.assertNotIn('--with-rocm=', self.dockerfile) self.assertIn('make -C third_party fio rocm_perftest', self.dockerfile) self.assertNotIn('ROCM_VER=rocm-5.5.0', self.dockerfile) self.assertNotIn('https://github.com/ROCm/TransformerEngine.git', self.dockerfile) - self.assertIn("pip install -c /tmp/rocm10-constraints.txt '.[amdworker]'", self.dockerfile) + self.assertIn("pip install -c /tmp/rocm10-constraints.txt '.[torch]'", self.dockerfile) self.assertIn('python3 -m pip check', self.dockerfile) - def test_extras_do_not_install_another_sdk(self): - """Pin the relocatable RVS archive and expose its bundled TransferBench.""" + def test_rvs_uses_signed_apt_repositories(self): + """Install RVS and matching dependencies with APT, not a tarball or forced extraction.""" self.assertIn('ARG RVS_VERSION=1.6.122-708', self.dockerfile) - self.assertIn('sha256sum --check --strict', self.dockerfile) - self.assertIn('tar -xzf /tmp/rvs.tar.gz -C "${EXTRAS_PATH}"', self.dockerfile) + self.assertIn('ARG ROCM_APT_VERSION=10.0.0-4', self.dockerfile) + self.assertIn('https://stable.repo.amd.com/rocm/extras/rvs/packages/ubuntu2604/', self.dockerfile) + self.assertIn('https://stable.repo.amd.com/rocm/core/packages/ubuntu2604/', self.dockerfile) + self.assertIn('Signed-By: /etc/apt/keyrings/amdrocm.gpg', self.dockerfile) + self.assertIn('"amdrocm10-rvs=${RVS_VERSION}"', self.dockerfile) + for component in ('runtime', 'base', 'amdsmi', 'blas', 'rand', 'llvm'): + self.assertIn(f'"amdrocm-{component}=${{ROCM_APT_VERSION}}"', self.dockerfile) + self.assertIn('EXTRAS_PATH=/opt/rocm/extras-10', self.dockerfile) self.assertIn('test -x "${EXTRAS_PATH}/bin/TransferBench"', self.dockerfile) - self.assertIn('LD_LIBRARY_PATH="${EXTRAS_PATH}/lib:${LD_LIBRARY_PATH}"', self.dockerfile) - self.assertNotIn('apt install -y amdrocm10-rvs', self.dockerfile) + self.assertIn('LD_LIBRARY_PATH="${EXTRAS_PATH}/lib:', self.environment_script) + self.assertNotIn('/rvs/tarball/', self.dockerfile) + self.assertNotIn('RVS_SHA256', self.dockerfile) + self.assertNotIn('/tmp/rvs.tar.gz', self.dockerfile) - def test_amdsmi_bindings_share_the_core_library(self): - """Avoid independent AMD SMI initialization states in PyTorch and SuperBench.""" - self.assertIn( - 'distribution("rocm-sdk-core").locate_file("_rocm_sdk_core/lib/libamd_smi.so.27")', - self.dockerfile, - ) - self.assertIn('cmp "${ROCM_PATH}/lib/libamd_smi.so" "${smi_library}"', self.dockerfile) - self.assertIn('ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so"', self.dockerfile) - self.assertIn('ln -sf "${smi_library}" "${ROCM_PATH}/lib/libamd_smi.so.27"', self.dockerfile) + def test_perftest_uses_the_configured_sdk(self): + """Honor the wheel SDK prefix while preserving other images' /opt/rocm default.""" + root = Path(__file__).resolve().parents[1] + makefile = (root / 'third_party' / 'Makefile').read_text(encoding='utf-8') + self.assertIn('--enable-rocm --with-rocm="$(ROCM_PATH)"', makefile) + self.assertIn('ROCM_PATH ?= /opt/rocm', makefile) + + def test_amdsmi_uses_the_core_bindings_in_place(self): + """Preserve the SDK's binding/library layout without copying or patching either.""" + self.assertIn('https://github.com/ROCm/TheRock/issues/3054', self.dockerfile) + self.assertIn('https://github.com/ROCm/TheRock/pull/8424', self.dockerfile) + self.assertIn('Path(sysconfig.get_path("purelib"), "amdsmi.pth")', self.registration_script) + self.assertIn('.write_text("_rocm_sdk_core/share/amd_smi\\n")', self.registration_script) + self.assertNotIn('--editable', self.dockerfile) + self.assertNotIn("'.[amdworker]'", self.dockerfile) + self.assertNotIn('version("amdsmi")', self.dockerfile) + self.assertNotIn('pip install "${ROCM_PATH}/share/amd_smi"', self.dockerfile) + self.assertNotIn('smi_library=', self.dockerfile) + self.assertNotIn('ln -sf', self.dockerfile) + + def test_amdsmi_registration_makes_bundled_module_importable(self): + """Execute the real build step in an isolated interpreter with an SDK payload.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + venv.EnvBuilder(with_pip=False).create(root) + python = root / 'bin' / 'python3' + env = os.environ.copy() + for name in ('PYTHONPATH', 'PYTHONHOME', 'BASH_ENV'): + env.pop(name, None) + env['PATH'] = f'{python.parent}:/usr/bin:/bin' + purelib = Path(subprocess.check_output( + [str(python), '-c', 'import sysconfig; print(sysconfig.get_path("purelib"))'], + env=env, text=True, + ).strip()) + module = purelib / '_rocm_sdk_core' / 'share' / 'amd_smi' / 'amdsmi' + module.mkdir(parents=True) + (module / '__init__.py').write_text('VERSION = "sdk-bundled"\n') + subprocess.run(['/bin/bash', '-e', '-c', self.registration_script], env=env, check=True) + self.assertEqual((purelib / 'amdsmi.pth').read_text(), '_rocm_sdk_core/share/amd_smi\n') + imported = subprocess.check_output( + [str(python), '-c', 'import amdsmi; print(amdsmi.__file__)'], env=env, text=True, + ).strip() + self.assertEqual(Path(imported), module / '__init__.py') if __name__ == '__main__': diff --git a/tests/test_rocm10_framework_install.py b/tests/test_rocm10_framework_install.py new file mode 100644 index 000000000..f54b1834a --- /dev/null +++ b/tests/test_rocm10_framework_install.py @@ -0,0 +1,42 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Guard the ROCm10-only source installer against unpinned or CUDA wheel substitutions.""" + +from pathlib import Path +import re +import subprocess + + +INSTALLER = Path(__file__).resolve().parents[1] / 'dockerfile/etc/install-rocm10-frameworks.sh' + + +def test_framework_source_pins(): + """Every framework checkout must use an immutable source revision.""" + source = INSTALLER.read_text() + for name in ['TE_COMMIT', 'AITER_COMMIT', 'MEGATRON_COMMIT']: + assert re.search(r'^readonly {}=[0-9a-f]{{40}}$'.format(name), source, re.MULTILINE) + assert 'https://github.com/ROCm/TransformerEngine.git' in source + assert 'https://github.com/ROCm/aiter.git' in source + assert '--no-build-isolation --no-deps' in source + assert 'pip install transformer_engine' not in source + + +def test_framework_sdk_and_architecture_guards(): + """Preserve the installed SDK/Triton and compile the requested local targets.""" + source = INSTALLER.read_text() + assert 'AITER_USE_SYSTEM_TRITON=1' in source + assert 'PIP_CONSTRAINT=' in source + assert '"torch": "2.13.0+rocm10.0.0"' in source + assert '"triton": "3.8.0+git4cff872c.rocm10.0.0"' in source + assert '"rocm-sdk-core": "10.0.0"' in source + assert '"rocm-sdk-devel": "10.0.0"' in source + assert 'ROCM_PATH="$(rocm-sdk path --root)"' in source + assert "NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250'" in source + assert 'MAX_JOBS > 16' in source + assert 'megatron_core_0.19.2_rocm10.patch' in source + + +def test_framework_installer_shell_syntax(): + """Check shell syntax without installing packages or requiring a GPU.""" + subprocess.run(['bash', '-n', str(INSTALLER)], check=True) diff --git a/third_party/Makefile b/third_party/Makefile index 5dd73372c..d88feba8e 100755 --- a/third_party/Makefile +++ b/third_party/Makefile @@ -136,7 +136,7 @@ ifneq (,$(wildcard perftest/autogen.sh)) endif rocm_perftest: ifneq (,$(wildcard perftest/autogen.sh)) - cd perftest && ./autogen.sh && ./configure --enable-rocm --with-rocm=/opt/rocm --prefix=$(SB_MICRO_PATH) && make -j && make install + cd perftest && ./autogen.sh && ./configure --enable-rocm --with-rocm="$(ROCM_PATH)" --prefix=$(SB_MICRO_PATH) && make -j && make install endif cpu_perftest: ifneq (,$(wildcard perftest/autogen.sh)) diff --git a/third_party/Megatron/megatron_core_0.19.2_rocm10.patch b/third_party/Megatron/megatron_core_0.19.2_rocm10.patch new file mode 100644 index 000000000..10239576f --- /dev/null +++ b/third_party/Megatron/megatron_core_0.19.2_rocm10.patch @@ -0,0 +1,58 @@ +diff --git a/megatron/training/argument_utils.py b/megatron/training/argument_utils.py +index 70f26c6..6b35b88 100644 +--- a/megatron/training/argument_utils.py ++++ b/megatron/training/argument_utils.py +@@ -166,7 +166,7 @@ class ArgumentGroupFactory: + argparse_kwargs = {} + argparse_kwargs["arg_names"] = [self._format_arg_name(attribute.name)] + argparse_kwargs["dest"] = attribute.name +- argparse_kwargs["help"] = self.field_docstrings[attribute.name] if attribute.name in self.field_docstrings else "" ++ argparse_kwargs["help"] = self.field_docstrings.get(attribute.name, "").replace("%", "%%") + + # dataclasses specifies that both should not be set + if isinstance(attribute.default, type(dataclasses.MISSING)): +diff --git a/megatron/training/arguments.py b/megatron/training/arguments.py +index fd30984..a32caf8 100644 +--- a/megatron/training/arguments.py ++++ b/megatron/training/arguments.py +@@ -2625,7 +2625,7 @@ def _add_rl_args(parser): + 'persist: leave KV cache in GPU memory (default), ' + 'offload: offload KV cache to CPU during training, ' + 'recompute: deallocate KV cache and recompute from scratch each cycle') +- group.add_argument('--rl-persist-cuda-graphs', action=argparse.BooleanOptionalAction, type=bool, default=False, ++ group.add_argument('--rl-persist-cuda-graphs', action=argparse.BooleanOptionalAction, default=False, + help='Persist CUDA graphs when the inference engine is suspended. ' + 'If False, CUDA graphs are deleted on suspend and re-captured on resume.') + group.add_argument('--rl-partial-rollouts', action=argparse.BooleanOptionalAction, default=False, +@@ -2633,11 +2633,11 @@ def _add_rl_args(parser): + 'the policy weights. This enables off-policy training where rollouts may ' + 'be generated with a stale version of the policy. Use ' + '--rl-generation-lag to control the degree of staleness.') +- group.add_argument('--rl-inference-logprobs-is-correction', action=argparse.BooleanOptionalAction, type=bool, default=False, ++ group.add_argument('--rl-inference-logprobs-is-correction', action=argparse.BooleanOptionalAction, default=False, + help='If set, use inference logprobs in importance sampling correction of the loss.') + group.add_argument('--rl-importance-sampling-truncation-coef', type=float, default=None, + help="If --inference-logprobs-is-correction is on and this coefficient is set, apply truncation for the IS correction at GRPO loss.") +- group.add_argument('--rl-use-sequence-packing', action=argparse.BooleanOptionalAction, type=bool, default=False, ++ group.add_argument('--rl-use-sequence-packing', action=argparse.BooleanOptionalAction, default=False, + help='Enable sequence packing') + group.add_argument('--rl-sequence-packing-max-sequences-per-bin', type=int, default=50, + help='Maximum number of sequences that can be packed into a single bin. ') +@@ -2646,7 +2646,7 @@ def _add_rl_args(parser): + help='Algorithm for distributing packed bins across ranks. ' + 'fifo: first-in-first-out sequential distribution, ' + 'round-robin: distribute bins cyclically across ranks for better load balancing') +- group.add_argument('--rl-training-cuda-graphs', action=argparse.BooleanOptionalAction, type=bool, ++ group.add_argument('--rl-training-cuda-graphs', action=argparse.BooleanOptionalAction, + default=False, + help='If set, do not toggle CUDA graphs on/off between inference and training phases.') + group.add_argument('--rl-inference-tensor-model-parallel-size', type=int, default=None, +@@ -2705,7 +2705,7 @@ def _add_rl_args(parser): + help='If set, verify that the model weights were correctly transferred by comparing forward pass outputs on' + 'the first swap of model weights.') + +- group.add_argument('--rl-skip-bos-token', action=argparse.BooleanOptionalAction, type=bool, default=False, ++ group.add_argument('--rl-skip-bos-token', action=argparse.BooleanOptionalAction, default=False, + help='Skip BOS token at the beginning of the sequences. Default is False.') + group.add_argument('--rl-profile', action='store_true', default=False, + help='Enable RL profiling to collect detailed timer data (JSONL + CSV).') From a7ef18c6ea049cfddce3b1f35f8bfe2c1ebfcf67 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 12:28:14 -0700 Subject: [PATCH 4/8] Add rocm10 + mi455x sb config --- dockerfile/rocm10.0.x.dockerfile | 57 ++++++++-- docs/getting-started/installation.mdx | 64 ++++++++---- superbench/config/amd_mi455x.yaml | 145 ++++++++++++++++++++++++++ tests/test_rocm10_dockerfile.py | 48 ++++++++- 4 files changed, 277 insertions(+), 37 deletions(-) create mode 100644 superbench/config/amd_mi455x.yaml diff --git a/dockerfile/rocm10.0.x.dockerfile b/dockerfile/rocm10.0.x.dockerfile index 66bda8a20..7845b7df5 100644 --- a/dockerfile/rocm10.0.x.dockerfile +++ b/dockerfile/rocm10.0.x.dockerfile @@ -11,12 +11,19 @@ ARG NUM_MAKE_JOBS=64 ARG ROCM_VERSION=10.0.0 # rocm-systems revision selected by TheRock's therock-10.0 release. ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9 +# MI455X (gfx1250) needs RCCL fixes merged to rocm-systems develop after that +# release, including ROCm/rocm-systems#12051 (GPU->NIC distance and GDR on gfx1250 +# MLOPart partitions) and the gfx1250 symmetric-memory/VMM teardown fixes. +# RCCL and RCCL-tests are built from this revision into RCCL_SOURCE_PREFIX. +# Pass an empty value to keep the packaged RCCL with release-matched RCCL-tests. +ARG RCCL_SOURCE_COMMIT=2a0c58ec63ea22487ea65458b68b92426119eb11 ENV DEBIAN_FRONTEND=noninteractive \ AMDGPU_TARGETS="${AMDGPU_TARGETS}" \ CMAKE_BUILD_PARALLEL_LEVEL="${NUM_MAKE_JOBS}" \ CMAKE_POLICY_VERSION_MINIMUM=3.5 \ MPI_HOME=/usr/local/mpi \ + RCCL_SOURCE_PREFIX=/opt/rccl \ EXTRAS_PATH=/opt/rocm/extras-10 \ SB_HOME=/opt/superbench \ SB_MICRO_PATH=/opt/superbench \ @@ -72,7 +79,7 @@ RUN curl -fsSL "https://content.mellanox.com/DOCA/DOCA_v${DOCA_VERSION}/host/doc apt-get update && apt-get clean # Add development files to the base's SDK and use AMD's path discovery directly. -# RCCL is AMD's prebuilt library in rocm-sdk-libraries, never built from source. +# The SDK's prebuilt RCCL remains installed; RCCL_SOURCE_COMMIT may add an override. RUN python3 -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ \ "rocm[devel,libraries,device-all]==${ROCM_VERSION}" && \ rocm-sdk init && \ @@ -131,28 +138,56 @@ RUN install -d -m 0755 /etc/apt/keyrings && \ WORKDIR ${SB_HOME} COPY third_party third_party -# Build only the release-matched RCCL test clients against the packaged library. -RUN git init /tmp/rocm-systems && \ - git -C /tmp/rocm-systems remote add origin https://github.com/ROCm/rocm-systems.git && \ - git -C /tmp/rocm-systems sparse-checkout set projects/rccl-tests && \ - git -C /tmp/rocm-systems fetch --depth 1 --filter=blob:none origin "${ROCM_SYSTEMS_COMMIT}" && \ - git -C /tmp/rocm-systems checkout --detach FETCH_HEAD && \ - rccl_architectures=$(printf '%s' "${AMDGPU_TARGETS}" | tr -s '[:space:]' ';' | sed 's/^;//; s/;$//') && \ +# Build RCCL-tests, and RCCL itself when RCCL_SOURCE_COMMIT is set, from one +# rocm-systems revision. The source-built library precedes the SDK library on +# LD_LIBRARY_PATH, which RUNPATH alone cannot override, so soname lookups +# (including SuperBench's mpirun -x LD_LIBRARY_PATH) resolve the fixed RCCL. +RUN rccl_architectures=$(printf '%s' "${AMDGPU_TARGETS}" | tr -s '[:space:]' ';' | sed 's/^;//; s/;$//') && \ if [ -z "${rccl_architectures}" ]; then \ echo 'AMDGPU_TARGETS must contain at least one GPU architecture.' >&2; exit 1; \ fi && \ + if [ -n "${RCCL_SOURCE_COMMIT}" ]; then \ + rocm_systems_commit="${RCCL_SOURCE_COMMIT}"; rccl_prefix="${RCCL_SOURCE_PREFIX}"; \ + rccl_projects='projects/rccl projects/rccl-tests'; \ + else \ + rocm_systems_commit="${ROCM_SYSTEMS_COMMIT}"; rccl_prefix="${ROCM_PATH}"; \ + rccl_projects='projects/rccl-tests'; \ + fi && \ + git init /tmp/rocm-systems && \ + git -C /tmp/rocm-systems remote add origin https://github.com/ROCm/rocm-systems.git && \ + git -C /tmp/rocm-systems sparse-checkout set ${rccl_projects} && \ + git -C /tmp/rocm-systems fetch --depth 1 --filter=blob:none origin "${rocm_systems_commit}" && \ + git -C /tmp/rocm-systems checkout --detach FETCH_HEAD && \ + if [ -n "${RCCL_SOURCE_COMMIT}" ]; then \ + cmake -S /tmp/rocm-systems/projects/rccl -B /tmp/rccl-build -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CXX_COMPILER="${ROCM_PATH}/bin/hipcc" \ + -DCMAKE_PREFIX_PATH="${ROCM_PATH}" \ + -DROCM_PATH="${ROCM_PATH}" \ + -DGPU_TARGETS="${rccl_architectures}" \ + -DBUILD_TESTS=OFF \ + -DCMAKE_INSTALL_PREFIX="${rccl_prefix}" \ + -DCMAKE_INSTALL_LIBDIR=lib \ + -DCMAKE_INSTALL_RPATH="${ROCM_PATH}/lib" && \ + cmake --build /tmp/rccl-build -j"${NUM_MAKE_JOBS}" && \ + cmake --install /tmp/rccl-build && \ + test -r "${rccl_prefix}/lib/librccl.so" && \ + printf 'export RCCL_HOME=%q\n' "${rccl_prefix}" >> /etc/profile.d/rocm10-env.sh && \ + printf 'export LD_LIBRARY_PATH=%q:"${LD_LIBRARY_PATH}"\n' "${rccl_prefix}/lib" >> /etc/profile.d/rocm10-env.sh; \ + fi && \ cmake -S /tmp/rocm-systems/projects/rccl-tests -B /tmp/rccl-tests-build \ -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_PREFIX_PATH="${ROCM_PATH};${MPI_HOME}" \ + -DCMAKE_PREFIX_PATH="${rccl_prefix};${ROCM_PATH};${MPI_HOME}" \ -DROCM_PATH="${ROCM_PATH}" \ -DGPU_TARGETS="${rccl_architectures}" \ -DUSE_MPI=ON \ -DCMAKE_INSTALL_PREFIX="${SB_HOME}" \ - -DCMAKE_INSTALL_RPATH="${ROCM_PATH}/lib;${MPI_HOME}/lib" \ + -DCMAKE_INSTALL_RPATH="${rccl_prefix}/lib;${ROCM_PATH}/lib;${MPI_HOME}/lib" \ -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON && \ cmake --build /tmp/rccl-tests-build -j"${NUM_MAKE_JOBS}" && \ cmake --install /tmp/rccl-tests-build && \ - rm -rf /tmp/rocm-systems /tmp/rccl-tests-build + rm -rf /tmp/rocm-systems /tmp/rccl-build /tmp/rccl-tests-build && \ + bash -c 'ldd "${SB_HOME}/bin/all_reduce_perf"' | grep -F "${rccl_prefix}/lib/librccl.so" # Do not invoke the legacy ROCm aggregate target: it clones HIP 5.5 samples, # rebuilds math libraries, and installs unqualified Megatron/DeepSpeed dependencies. diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index e41cd7edd..8a4798d12 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -135,32 +135,35 @@ canonical library. Otherwise, importing PyTorch before the AMD SMI bindings can load two initialization states and report zero GPUs even when HIP sees all devices. -* RCCL is AMD's **prebuilt SDK library**, not rebuilt from source. - Only RCCL-tests is compiled, from the `rocm-systems` revision selected by - TheRock's `therock-10.0` release. -* Open MPI from the `v4.1.8` source tag retains `/usr/local/mpi` (this source - build reports `4.1.8rc1`). Current built-in MPI calls exchange +* RCCL and RCCL-tests are built from one `rocm-systems` revision + (`RCCL_SOURCE_COMMIT`) and installed under `/opt/rccl` and + `/opt/superbench/bin`. The default revision contains the gfx1250 (MI455X) + fixes merged after TheRock's `therock-10.0` release, including + [ROCm/rocm-systems#12051](https://github.com/ROCm/rocm-systems/pull/12051). + `/opt/rccl/lib` precedes the SDK library on `LD_LIBRARY_PATH`, so RCCL-tests + and other soname lookups, including SuperBench MPI launches, resolve it. Build with + `--build-arg RCCL_SOURCE_COMMIT=` to keep AMD's prebuilt SDK RCCL and compile + only RCCL-tests from the `therock-10.0` revision. +* Open MPI 5.0.10 from the DOCA 3.4.0 userspace packages retains + `/usr/local/mpi`. Current built-in MPI calls exchange host metadata, timing/error values, and NumPy arrays; GPU collectives use RCCL. This scaffold does not claim ROCm-aware MPI support for applications that pass device pointers directly to MPI. -* Locally compiled benchmark kernels default to `gfx942 gfx950`, independently - of the all-device SDK packages. Other kernel targets require an explicit - `AMDGPU_TARGETS` build argument and hardware qualification. -* RVS `1.6.122-708` and its bundled TransferBench are installed from AMD's - SHA-256-pinned relocatable Extras archive. Their prefix is - `/opt/rocm-extras-10`, separate from the wheel SDK. Native RVS packages are - not installed because their dependencies would bring in another SDK. +* Locally compiled benchmark kernels default to `gfx942 gfx950 gfx1250`, + independently of the all-device SDK packages. Other kernel targets require an + explicit `AMDGPU_TARGETS` build argument and hardware qualification. +* RVS `1.6.122-708` and its bundled TransferBench come from AMD's signed + Ubuntu 26.04 APT repositories under `/opt/rocm/extras-10`. ROCm `mem-bw` + uses the TransferBench backend (`SB_ROCM_MEM_BW_BACKEND=transferbench`). * The image includes SuperBench, its native microbenchmarks, RCCL-tests, fio, - and ROCm-enabled perftest. It uses Ubuntu's RDMA development packages; - no DOCA/OFED userspace version or host driver is selected by this scaffold. + ROCm-enabled perftest, `rocblas-bench`/`hipblaslt-bench` from TheRock's test + archive, and TransformerEngine, AITER and Megatron-LM built by + `dockerfile/etc/install-rocm10-frameworks.sh`. No host driver is installed. -The following remain deliberately unqualified or absent: TransformerEngine, -Megatron/DeepSpeed setup, `rocblas-bench`, `hipblaslt-bench`, Intel MLC, and the -old HIP 5.5 `hipBusBandwidth` sample. Consequently, the existing `gemm-flops`, -`hipblaslt-gemm`, `cpu-memory-bw-latency`, and ROCm `mem-bw` wrappers are not -ready to run in this scaffold. No executable aliases or silently substituted -metrics are provided. Existing `rocm-smi` system-info collection and -`rocprofv2` tracing still need their separate ROCm 10 migrations. +The following remain absent: Intel MLC (`cpu-memory-bw-latency`), +Megatron-DeepSpeed, and the old HIP 5.5 `hipBusBandwidth` sample. Existing +`rocm-smi` system-info collection and `rocprofv2` tracing still need their +separate ROCm 10 migrations. Validation on 2026-09-30: the scaffold built successfully and passed `pip check`, 34 targeted regression tests (three NVIDIA-only tests skipped), GEMM correctness @@ -171,6 +174,25 @@ An eight-rank Open MPI / packaged-RCCL all-reduce passed data checking These checks do not qualify multi-node networking, additional GPU architectures, the omitted benchmarks, or sustained RVS stress workloads. +#### Running on MI455X (gfx1250) + +`superbench/config/amd_mi455x.yaml` is a small four-GPU configuration for this +image. Its RCCL modes set the environment used for MI455X all-reduce runs +(`NCCL_IGNORE_CPU_AFFINITY`, `NCCL_CUMEM_ENABLE`, `NCCL_MNNVL_ENABLE`, +`HSA_HOTSWAP_DISABLE`, and `NCCL_DEBUG=VERSION` to log the loaded RCCL), and +`rccl-bw:allreduce` runs the equivalent of +`mpirun -np 4 all_reduce_perf -b 1G -e 32G -f 2 -g 1 -c 0 -w 10 -n 50`. + +```bash +sb run --host-list localhost -i superbench:rocm10-scaffold \ + -c superbench/config/amd_mi455x.yaml \ + -C 'superbench.enable=["rccl-bw:allreduce:correctness","rccl-bw:allreduce"]' +``` + +MNNVL requires `NCCL_CUMEM_ENABLE=1`; set `NCCL_MNNVL_ENABLE=0` on hosts +without a configured scale-up fabric. RCCL-tests' `-A 1` algorithm/protocol +columns are a manual diagnostic and are not emitted by `rccl-bw`. + #### TransferBench versus the legacy memory-bandwidth test The bundled CLI reports version 1.69.00, commit `5fbfa95`; do not assume that it includes every diff --git a/superbench/config/amd_mi455x.yaml b/superbench/config/amd_mi455x.yaml new file mode 100644 index 000000000..207bab886 --- /dev/null +++ b/superbench/config/amd_mi455x.yaml @@ -0,0 +1,145 @@ +# SuperBench Config - AMD Instinct MI455X (gfx1250), 4 GPUs per node. +# Requires the dockerfile/rocm10.0.x.dockerfile image, whose RCCL and RCCL-tests +# include the gfx1250 fixes from ROCm/rocm-systems#12051. +# Run a subset with: sb run ... -C 'superbench.enable=["gpu-copy-bw:perf"]' +version: v0.12 +superbench: + enable: null + env: + HIP_FORCE_DEV_KERNARG: '1' + var: + default_local_mode: &default_local_mode + enable: true + modes: + - name: local + proc_num: 4 + prefix: HIP_VISIBLE_DEVICES={proc_rank} + parallel: yes + default_pytorch_mode: &default_pytorch_mode + enable: true + modes: + - name: torch.distributed + proc_num: 4 + node_num: 1 + frameworks: + - pytorch + # RCCL environment validated on MI455X. MNNVL uses fabric memory handles and + # needs cuMem; HSA_HOTSWAP_DISABLE turns off the gfx1250 code-object hotswap hook. + rccl_env: &rccl_env + NCCL_IGNORE_CPU_AFFINITY: '1' + NCCL_CUMEM_ENABLE: '1' + NCCL_MNNVL_ENABLE: '1' + HSA_HOTSWAP_DISABLE: '1' + NCCL_DEBUG: VERSION + rccl_mode: &rccl_mode + enable: true + timeout: 1800 + modes: + - name: mpi + proc_num: 4 + node_num: 1 + env: + <<: *rccl_env + model_ddp_parameter: &model_ddp_param + duration: 0 + num_warmup: 64 + num_steps: 512 + sample_count: 8192 + batch_size: 128 + precision: [float32, float16] + model_action: [train] + pin_memory: yes + num_workers: 0 + benchmarks: + kernel-launch: + <<: *default_local_mode + gemm-flops: + <<: *default_local_mode + parameters: + m: 7680 + n: 8192 + k: 8192 + hipblaslt-gemm: + <<: *default_local_mode + parameters: + in_types: ['fp32', 'fp16', 'bf16', 'fp8'] + tolerant_fail: yes + num_warmup: 10 + num_steps: 100 + shapes: + - 4096,4096,4096 + - 8192,8192,8192 + - 16384,16384,16384 + mem-bw: + enable: true + modes: + - name: local + proc_num: 4 + prefix: HIP_VISIBLE_DEVICES={proc_rank} + parallel: no + gpu-copy-bw:correctness: + enable: true + modes: + - name: local + parallel: no + parameters: + mem_type: [htod, dtoh, dtod, one_to_all, all_to_one, all_to_all] + copy_type: [sm, dma] + size: 4096 + num_warm_up: 0 + num_loops: 1 + check_data: true + gpu-copy-bw:perf: + enable: true + timeout: 1800 + modes: + - name: local + parallel: no + parameters: + mem_type: [dtod, all_to_all] + copy_type: [sm, dma] + size: 34359738368 + num_warm_up: 1 + num_loops: 10 + # Data check over small sizes before the large-message bandwidth sweep. + rccl-bw:allreduce:correctness: + <<: *rccl_mode + parameters: + operation: allreduce + ngpus: 1 + minbytes: 8 + maxbytes: 64M + stepfactor: 2 + check: 1 + warmup_iters: 5 + iters: 20 + # Equivalent to: mpirun -np 4 all_reduce_perf -b 1G -e 32G -f 2 -g 1 -c 0 -w 10 -n 50 + rccl-bw:allreduce: + <<: *rccl_mode + parameters: + operation: allreduce + ngpus: 1 + minbytes: 1G + maxbytes: 32G + stepfactor: 2 + check: 0 + warmup_iters: 10 + iters: 50 + model-benchmarks:bert: + <<: *default_pytorch_mode + models: + - bert-base + - bert-large + parameters: + <<: *model_ddp_param + seq_len: 224 + # The default 1e-8 underflows in FP16 Adam. + optimizer_eps: 0.0001 + model-benchmarks:resnet: + <<: *default_pytorch_mode + models: + - resnet50 + - resnet101 + parameters: + <<: *model_ddp_param + batch_size: 384 diff --git a/tests/test_rocm10_dockerfile.py b/tests/test_rocm10_dockerfile.py index 41dc957c7..bd7a08026 100644 --- a/tests/test_rocm10_dockerfile.py +++ b/tests/test_rocm10_dockerfile.py @@ -26,8 +26,11 @@ def setUpClass(cls): registration_end = cls.dockerfile.index('\n\n', registration_start) cls.registration_script = cls.dockerfile[registration_start + len('RUN '):registration_end] start = cls.dockerfile.index('rccl_architectures=$(printf') - end = cls.dockerfile.index(' cmake -S /tmp/rocm-systems', start) + end = cls.dockerfile.index(' if [ -n "${RCCL_SOURCE_COMMIT}" ]; then', start) cls.routing = cls.dockerfile[start:end] + 'printf \'%s\\n\' "$rccl_architectures"\n' + override_start = cls.dockerfile.index("printf 'export RCCL_HOME=%q") + override_end = cls.dockerfile.index('; \\\n fi', override_start) + cls.rccl_override_script = cls.dockerfile[override_start:override_end].replace('\\\n', '\n') def run_routing(self, targets): """Execute the real Dockerfile routing block with a supplied target list.""" @@ -155,17 +158,51 @@ def test_sdk_discovery_failure_stops_environment_generation(self): self.assertEqual(result.stdout, '') self.assertFalse(activation.exists()) - def test_rccl_uses_packaged_library_and_matched_test_sources(self): - """Build only test clients and retain runtime library search paths.""" + def test_rccl_source_build_includes_gfx1250_fixes(self): + """Build RCCL and its tests from one revision that contains the MI455X fixes.""" self.assertIn('ARG AMDGPU_TARGETS="gfx942 gfx950 gfx1250"', self.dockerfile) self.assertIn('test -r "${ROCM_PATH}/lib/librccl.so"', self.dockerfile) self.assertIn('ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9', self.dockerfile) - self.assertIn('-DGPU_TARGETS="${rccl_architectures}"', self.dockerfile) + # Merge commit of ROCm/rocm-systems#12051. + self.assertIn('ARG RCCL_SOURCE_COMMIT=2a0c58ec63ea22487ea65458b68b92426119eb11', self.dockerfile) + self.assertIn('RCCL_SOURCE_PREFIX=/opt/rccl', self.dockerfile) + self.assertIn("rccl_projects='projects/rccl projects/rccl-tests'", self.dockerfile) + self.assertIn("rccl_projects='projects/rccl-tests'", self.dockerfile) + self.assertIn('cmake -S /tmp/rocm-systems/projects/rccl -B /tmp/rccl-build', self.dockerfile) + self.assertEqual(self.dockerfile.count('-DGPU_TARGETS="${rccl_architectures}"'), 2) + self.assertIn('-DCMAKE_PREFIX_PATH="${rccl_prefix};${ROCM_PATH};${MPI_HOME}"', self.dockerfile) self.assertIn('-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON', self.dockerfile) + self.assertIn('grep -F "${rccl_prefix}/lib/librccl.so"', self.dockerfile) + self.assertLess( + self.dockerfile.index('cmake --install /tmp/rccl-build'), + self.dockerfile.index('cmake -S /tmp/rocm-systems/projects/rccl-tests'), + ) self.assertNotIn('https://github.com/ROCm/rccl.git', self.dockerfile) self.assertNotIn('https://github.com/ROCmSoftwarePlatform/rccl.git', self.dockerfile) self.assertNotIn('LD_PRELOAD=', self.dockerfile) + def test_source_built_rccl_precedes_the_sdk_library(self): + """Prepend the source-built RCCL once, even when the activation is sourced again.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + activation = root / 'rocm10-env.sh' + prefix = str(root / 'rccl with spaces') + activation.write_text('export ROCM_PATH=/sdk RCCL_HOME=/sdk\nexport LD_LIBRARY_PATH="/sdk/lib"\n') + env = os.environ.copy() + env.pop('BASH_ENV', None) + env['rccl_prefix'] = prefix + script = self.rccl_override_script.replace('/etc/profile.d/rocm10-env.sh', str(activation)) + subprocess.run(['/bin/bash', '-e', '-c', script], env=env, check=True) + env.update({'BASH_ENV': str(activation), 'LD_LIBRARY_PATH': '/stale'}) + result = subprocess.run( + ['/bin/bash', '-e', '-c', '. "$BASH_ENV"; printf "%s\\n%s\\n" "$RCCL_HOME" "$LD_LIBRARY_PATH"'], + env=env, + check=True, + capture_output=True, + text=True, + ) + self.assertEqual(result.stdout.splitlines(), [prefix, f'{prefix}/lib:/sdk/lib']) + def test_doca_uses_only_the_userspace_profile(self): """Use the matching Ubuntu release without installing host kernel drivers.""" self.assertIn('ARG DOCA_VERSION=3.4.0', self.dockerfile) @@ -221,7 +258,8 @@ def test_installation_order_and_prerequisites(self): '"amdrocm10-rvs=${RVS_VERSION}"', 'WORKDIR ${SB_HOME}', 'COPY third_party third_party', - 'RUN git init /tmp/rocm-systems', + 'RUN rccl_architectures=$(printf', + 'git init /tmp/rocm-systems', 'make -C third_party fio rocm_perftest', 'ARG ROCM_TESTS_SHA256=', 'COPY . .', From 8590af605a2d34a10ee50f754548357fd54e5c50 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 14:03:51 -0700 Subject: [PATCH 5/8] Address review: inline framework build, split benchmarks, drop config - Build TransformerEngine, AITER and Megatron-LM directly in rocm10.0.x.dockerfile (pinned ARGs) and remove dockerfile/etc/install-rocm10-frameworks.sh. Build-only settings run in their own layer so they do not reach /etc/environment. - Move the TransferBench mem-bw backend and model benchmark changes, with their tests, to a separate PR. - Remove superbench/config/amd_mi455x.yaml; configs are kept internally. - Docs: qualify the packaged-RCCL validation, drop the moved TransferBench and MI455X config sections. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dockerfile/etc/install-rocm10-frameworks.sh | 136 ------- dockerfile/rocm10.0.x.dockerfile | 48 ++- docs/getting-started/installation.mdx | 84 +---- .../rocm_memory_bw_performance.py | 183 +--------- .../model_benchmarks/megatron_gpt3.py | 17 +- .../model_benchmarks/pytorch_base.py | 18 +- .../model_benchmarks/pytorch_bert.py | 1 - .../model_benchmarks/pytorch_gpt2.py | 1 - .../model_benchmarks/pytorch_llama.py | 1 - superbench/config/amd_mi455x.yaml | 145 -------- .../test_rocm_memory_bw_performance.py | 343 +----------------- .../model_benchmarks/test_megatron_launch.py | 85 ----- .../test_transformer_precisions.py | 38 -- tests/test_rocm10_dockerfile.py | 63 +++- tests/test_rocm10_framework_install.py | 42 --- 15 files changed, 122 insertions(+), 1083 deletions(-) delete mode 100755 dockerfile/etc/install-rocm10-frameworks.sh delete mode 100644 superbench/config/amd_mi455x.yaml delete mode 100644 tests/benchmarks/model_benchmarks/test_megatron_launch.py delete mode 100644 tests/benchmarks/model_benchmarks/test_transformer_precisions.py delete mode 100644 tests/test_rocm10_framework_install.py diff --git a/dockerfile/etc/install-rocm10-frameworks.sh b/dockerfile/etc/install-rocm10-frameworks.sh deleted file mode 100755 index 3ff2e24c6..000000000 --- a/dockerfile/etc/install-rocm10-frameworks.sh +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env bash -# Build ROCm Transformer Engine and AITER without replacing the wheel SDK, -# PyTorch, or Triton. Invoke from a writable build directory inside the ROCm10 -# image, not on the host. ROCM_PATH must select the wheel-SDK development root; -# CMake, Ninja, a C++ compiler, Git and Python development headers are required. -# Validated on Ubuntu 26.04 / Python 3.14.4 / MI300X (gfx942). The other two -# targets are compile-only coverage, not a runtime certification. -# For native-FP16 SB BERT/GPT2/Llama training (including FP8 linear layers), -# pass --optimizer_eps 1e-4: the legacy 1e-8 default underflows in FP16 Adam. -# BERT's pooler also requires an FP8-aligned batch size (use 16 or a multiple). -# GPT2's Hugging Face Conv1D layers are not converted to TE by SuperBench; -# use Llama/BERT or Megatron to exercise FP8 attention/MLP projection GEMMs. -# FP8 projection GEMMs do not imply FP8 dot-product attention support. -# For full-precision FP32 AITER Triton attention, set TRITON_F32_DEFAULT=ieee; -# its default TF32 dot products are independent of PyTorch's TF32 switches. -# Standalone aiter.flash_attn_func training requires return_lse=True; unpack -# (output, lse). Its CK JIT cold build can take many minutes, unlike TE's CK JIT. -# The separate Megatron checkout is selected with --code_base; the repository's -# older Megatron-LM and Megatron-DeepSpeed submodule pointers remain unchanged. -# An image can set SB_MEGATRON_PATH to that checkout as its non-DeepSpeed default. -set -euo pipefail - -readonly TE_COMMIT=e7835ed1b134f56e58c575fba2455471064cab9b -readonly AITER_COMMIT=89a47b84ac4b576339a50047e290c383c2377389 -readonly MEGATRON_COMMIT=4b4acac9a1d28ea6829c8d4f566d75698a21249d -# TE v2.15_rocm, AITER HEAD snapshot 2026-09-30, and Megatron Core v0.19.2. -# The tested TE 2.18-dev alternative cannot compile its BF16 small-sequence -# attention for gfx1250; do not silently replace this pin with moving dev. -readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -readonly SOURCE_ROOT="${SB_ROCM10_FRAMEWORK_ROOT:-${PWD}/rocm10-frameworks}" -readonly WHEELHOUSE="${SOURCE_ROOT}/wheels/${TE_COMMIT}-${AITER_COMMIT}-${MEGATRON_COMMIT}" -mkdir -p "${SOURCE_ROOT}/scratch" "${WHEELHOUSE}" -export TMPDIR="${SOURCE_ROOT}/scratch" -export MAX_JOBS="${MAX_JOBS:-16}" -if ! [[ "${MAX_JOBS}" =~ ^[0-9]+$ ]] || ((MAX_JOBS < 1 || MAX_JOBS > 16)); then - echo 'MAX_JOBS must be between 1 and 16.' >&2 - exit 1 -fi -export CMAKE_BUILD_PARALLEL_LEVEL="${MAX_JOBS}" NVTE_BUILD_MAX_JOBS="${MAX_JOBS}" -ROCM_PATH="$(rocm-sdk path --root)" -export ROCM_PATH ROCM_HOME="${ROCM_PATH}" HIP_PATH="${ROCM_PATH}" RCCL_HOME="${ROCM_PATH}" -export NVTE_USE_ROCM=1 NVTE_FRAMEWORK=pytorch NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250' -export NVTE_NO_LOCAL_VERSION=1 -export NVTE_CK_JIT=1 NVTE_FUSED_ATTN=1 NVTE_FUSED_ATTN_CK=1 NVTE_FUSED_ATTN_AOTRITON=1 -export AITER_USE_SYSTEM_TRITON=1 PREBUILD_KERNELS=0 BUILD_TARGET=rocm - -# An explicit constraints file also protects transitive dependency resolution. -# --no-build-isolation prevents pip from fetching a different build-time torch. -python - "${SOURCE_ROOT}/sdk-constraints.txt" <<'PY' -import importlib.metadata as metadata -import sys - -expected = { - "torch": "2.13.0+rocm10.0.0", - "triton": "3.8.0+git4cff872c.rocm10.0.0", - "rocm-sdk-core": "10.0.0", - "rocm-sdk-devel": "10.0.0", -} -for name, version in expected.items(): - actual = metadata.version(name) - if actual != version: - raise SystemExit(f"Expected {name}=={version}, found {actual}") -protected = [] -for distribution in metadata.distributions(): - name = distribution.metadata["Name"].lower().replace("_", "-") - if name.startswith("rocm-") or name in {"rocm", "torch", "torchvision", "torchaudio", "triton", "apex"}: - protected.append(f"{name}=={distribution.version}") -with open(sys.argv[1], "w") as file: - file.write("\n".join(sorted(protected)) + "\n") -PY -export PIP_CONSTRAINT="${SOURCE_ROOT}/sdk-constraints.txt" - -checkout() { - local repository="$1" commit="$2" destination="$3" - if [[ ! -d "${destination}/.git" ]]; then - git init --quiet "${destination}" - git -C "${destination}" remote add origin "${repository}" - fi - git -C "${destination}" fetch --quiet --depth 1 origin "${commit}" - git -C "${destination}" checkout --quiet --detach "${commit}" - git -C "${destination}" submodule update --init --recursive --depth 1 -} - -python -m pip install \ - pybind11==3.0.1 pydantic==2.13.5 einops==0.8.2 psutil==7.2.2 mpi4py==4.1.1 \ - flydsl==0.3.4.1 pandas==3.0.5 nvdlfw-inspect==0.2.2 \ - onnxscript==0.7.2 onnx-ir==1.0.0 onnx==1.23.1 ml_dtypes==0.6.0 -checkout https://github.com/ROCm/TransformerEngine.git "${TE_COMMIT}" "${SOURCE_ROOT}/TransformerEngine" -checkout https://github.com/ROCm/aiter.git "${AITER_COMMIT}" "${SOURCE_ROOT}/aiter" -checkout https://github.com/NVIDIA/Megatron-LM.git "${MEGATRON_COMMIT}" "${SOURCE_ROOT}/Megatron-LM" -MEGATRON_PATCH="${SB_ROCM10_MEGATRON_PATCH:-${SCRIPT_DIR}/../../third_party/Megatron/megatron_core_0.19.2_rocm10.patch}" -if ! git -C "${SOURCE_ROOT}/Megatron-LM" apply --reverse --check "${MEGATRON_PATCH}" 2>/dev/null; then - git -C "${SOURCE_ROOT}/Megatron-LM" apply --check "${MEGATRON_PATCH}" - git -C "${SOURCE_ROOT}/Megatron-LM" apply "${MEGATRON_PATCH}" -fi - -# TE pins its own private AITER/CK implementation in qola_manifest.toml. -# Do not override it with the separately installed Python AITER package. -# CK excludes gfx1250 upstream; common TE kernels still compile for all three -# requested targets. AOTriton ships images for gfx942/gfx950, not gfx1250. -python -m pip wheel --no-build-isolation --no-deps \ - "${SOURCE_ROOT}/TransformerEngine" "${SOURCE_ROOT}/aiter" "${SOURCE_ROOT}/Megatron-LM" \ - -w "${WHEELHOUSE}" -python -m pip install --no-deps "${WHEELHOUSE}"/*.whl - -python -m pip check -python - "${SOURCE_ROOT}/sdk-constraints.txt" <<'PY' -import importlib.metadata as metadata -import sys - -for line in open(sys.argv[1]): - name, expected = line.strip().split("==") - actual = metadata.version(name) - if actual != expected: - raise SystemExit(f"Protected dependency changed: {name}: {expected} -> {actual}") -PY -python - "${SOURCE_ROOT}" "${TE_COMMIT}" "${AITER_COMMIT}" "${MEGATRON_COMMIT}" <<'PY' -import importlib.metadata as metadata -import json -from pathlib import Path -import sys - -root, te, aiter, megatron = sys.argv[1:] -manifest = { - "sources": {"transformer_engine": te, "aiter": aiter, "megatron": megatron}, - "packages": {name: metadata.version(name) for name in - ["torch", "triton", "transformer_engine", "amd-aiter", "megatron-core", "flydsl"]}, - "compiled_te_targets": ["gfx942", "gfx950", "gfx1250"], - "ck_attention_targets": ["gfx942", "gfx950"], - "aotriton_image_targets": ["gfx942", "gfx950"], -} -(Path(root) / "framework-pins.json").write_text(json.dumps(manifest, indent=2) + "\n") -PY -echo "Framework sources: ${SOURCE_ROOT}" -echo "Megatron --code_base: ${SOURCE_ROOT}/Megatron-LM" -echo "Optional image ENV: SB_MEGATRON_PATH=${SOURCE_ROOT}/Megatron-LM" diff --git a/dockerfile/rocm10.0.x.dockerfile b/dockerfile/rocm10.0.x.dockerfile index 7845b7df5..f45fd8085 100644 --- a/dockerfile/rocm10.0.x.dockerfile +++ b/dockerfile/rocm10.0.x.dockerfile @@ -211,14 +211,22 @@ RUN curl -fsSL "https://stable.repo.amd.com/rocm/core/tarball/therock-dist-linux COPY . . # Keep AMD's framework and all-device SDK packages when resolving SuperBench deps. -# Resolve these before the framework installer applies its tested dependency pins. +# The same constraints protect them while building the frameworks below. # The SDK supplies amdsmi via .pth, not a separate distribution; use the torch # extra so amdworker does not install a PyPI wrapper that shadows the SDK module. -RUN python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|rocm|rocm-sdk-[^=]+)==' > /tmp/rocm10-constraints.txt && \ +RUN python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|apex|rocm|rocm[-_][^=]+)==' > /tmp/rocm10-constraints.txt && \ python3 -m pip install -c /tmp/rocm10-constraints.txt '.[torch]' && \ python3 -m pip install pytest pytest-timeout vcrpy -# Install TransformerEngine, AITER and Megatron before the final native build. +# Build TransformerEngine, AITER and Megatron-LM from pinned sources against the +# base's PyTorch, Triton and SDK, without build isolation or dependency resolution. +# TE v2.15_rocm, AITER snapshot 2026-09-30, Megatron Core v0.19.2. The TE 2.18-dev +# alternative cannot compile its BF16 small-sequence attention for gfx1250. +# TE uses its own pinned AITER/CK. CK attention excludes gfx1250 and AOTriton ships +# only gfx942/gfx950 images, so gfx1250 gets TE's common kernels. +ARG TE_COMMIT=e7835ed1b134f56e58c575fba2455471064cab9b +ARG AITER_COMMIT=89a47b84ac4b576339a50047e290c383c2377389 +ARG MEGATRON_COMMIT=4b4acac9a1d28ea6829c8d4f566d75698a21249d ENV SB_ROCM10_FRAMEWORK_ROOT=/opt/rocm10-frameworks \ SB_MEGATRON_PATH=/opt/rocm10-frameworks/Megatron-LM \ AITER_USE_SYSTEM_TRITON=1 \ @@ -231,8 +239,38 @@ ENV SB_ROCM10_FRAMEWORK_ROOT=/opt/rocm10-frameworks \ NVTE_FUSED_ATTN_AOTRITON=0 RUN framework_jobs="${NUM_MAKE_JOBS}" && \ if [ "${framework_jobs}" -gt 16 ]; then framework_jobs=16; fi && \ - MAX_JOBS="${framework_jobs}" bash dockerfile/etc/install-rocm10-frameworks.sh && \ - printf '%s\n' \ + export MAX_JOBS="${framework_jobs}" CMAKE_BUILD_PARALLEL_LEVEL="${framework_jobs}" \ + NVTE_BUILD_MAX_JOBS="${framework_jobs}" PIP_CONSTRAINT=/tmp/rocm10-constraints.txt \ + TMPDIR=/tmp/rocm10-frameworks-scratch NVTE_USE_ROCM=1 NVTE_FRAMEWORK=pytorch \ + NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250' NVTE_NO_LOCAL_VERSION=1 NVTE_CK_JIT=1 \ + NVTE_FUSED_ATTN_AOTRITON=1 PREBUILD_KERNELS=0 BUILD_TARGET=rocm RCCL_HOME="${ROCM_PATH}" && \ + python3 -c 'import sys; from importlib.metadata import version; expected = {"torch": "2.13.0+rocm10.0.0", "triton": "3.8.0+git4cff872c.rocm10.0.0", "rocm-sdk-core": "10.0.0", "rocm-sdk-devel": "10.0.0"}; wrong = ["{}=={} (found {})".format(name, value, version(name)) for name, value in expected.items() if version(name) != value]; sys.exit("Unexpected base packages: " + ", ".join(wrong) if wrong else 0)' && \ + mkdir -p "${TMPDIR}" && \ + python3 -m pip install \ + pybind11==3.0.1 pydantic==2.13.5 einops==0.8.2 psutil==7.2.2 mpi4py==4.1.1 \ + flydsl==0.3.4.1 pandas==3.0.5 nvdlfw-inspect==0.2.2 \ + onnxscript==0.7.2 onnx-ir==1.0.0 onnx==1.23.1 ml_dtypes==0.6.0 && \ + for source in "TransformerEngine https://github.com/ROCm/TransformerEngine.git ${TE_COMMIT}" \ + "aiter https://github.com/ROCm/aiter.git ${AITER_COMMIT}" \ + "Megatron-LM https://github.com/NVIDIA/Megatron-LM.git ${MEGATRON_COMMIT}"; do \ + set -- ${source} && \ + git init -q "${SB_ROCM10_FRAMEWORK_ROOT}/$1" && \ + git -C "${SB_ROCM10_FRAMEWORK_ROOT}/$1" remote add origin "$2" && \ + git -C "${SB_ROCM10_FRAMEWORK_ROOT}/$1" fetch -q --depth 1 origin "$3" && \ + git -C "${SB_ROCM10_FRAMEWORK_ROOT}/$1" checkout -q --detach FETCH_HEAD && \ + git -C "${SB_ROCM10_FRAMEWORK_ROOT}/$1" submodule update --init --recursive --depth 1 || exit 1; \ + done && \ + git -C "${SB_MEGATRON_PATH}" apply "${SB_HOME}/third_party/Megatron/megatron_core_0.19.2_rocm10.patch" && \ + python3 -m pip wheel --no-build-isolation --no-deps -w /tmp/rocm10-wheels \ + "${SB_ROCM10_FRAMEWORK_ROOT}/TransformerEngine" "${SB_ROCM10_FRAMEWORK_ROOT}/aiter" "${SB_MEGATRON_PATH}" && \ + python3 -m pip install --no-deps /tmp/rocm10-wheels/*.whl && \ + python3 -m pip check && \ + python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|apex|rocm|rocm[-_][^=]+)==' | \ + diff -u /tmp/rocm10-constraints.txt - && \ + rm -rf /tmp/rocm10-wheels "${TMPDIR}" + +# Build-only framework settings above stay out of the runtime environment. +RUN printf '%s\n' \ "PATH=${PATH}" \ "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}" \ "SB_MICRO_PATH=${SB_MICRO_PATH}" \ diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 8a4798d12..21a66073f 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -153,94 +153,32 @@ all devices. independently of the all-device SDK packages. Other kernel targets require an explicit `AMDGPU_TARGETS` build argument and hardware qualification. * RVS `1.6.122-708` and its bundled TransferBench come from AMD's signed - Ubuntu 26.04 APT repositories under `/opt/rocm/extras-10`. ROCm `mem-bw` - uses the TransferBench backend (`SB_ROCM_MEM_BW_BACKEND=transferbench`). + Ubuntu 26.04 APT repositories under `/opt/rocm/extras-10`. The image sets + `SB_ROCM_MEM_BW_BACKEND=transferbench` for ROCm `mem-bw`; the TransferBench + backend itself is added by a separate benchmark change, and `mem-bw` is not + runnable in this image without it. * The image includes SuperBench, its native microbenchmarks, RCCL-tests, fio, ROCm-enabled perftest, `rocblas-bench`/`hipblaslt-bench` from TheRock's test - archive, and TransformerEngine, AITER and Megatron-LM built by - `dockerfile/etc/install-rocm10-frameworks.sh`. No host driver is installed. + archive, and TransformerEngine, AITER and Megatron-LM built in the Dockerfile + from pinned revisions (`TE_COMMIT`, `AITER_COMMIT`, `MEGATRON_COMMIT`) against + the base's PyTorch, Triton and SDK. No host driver is installed. The following remain absent: Intel MLC (`cpu-memory-bw-latency`), Megatron-DeepSpeed, and the old HIP 5.5 `hipBusBandwidth` sample. Existing `rocm-smi` system-info collection and `rocprofv2` tracing still need their separate ROCm 10 migrations. -Validation on 2026-09-30: the scaffold built successfully and passed `pip check`, +Validation on 2026-09-30 used the earlier variant with AMD's packaged SDK RCCL +(equivalent to `--build-arg RCCL_SOURCE_COMMIT=`): the image built successfully and passed `pip check`, 34 targeted regression tests (three NVIDIA-only tests skipped), GEMM correctness on all eight MI300X GPUs, FP16/BF16 PyTorch flash SDPA forward/backward, and the SuperBench GPU-copy wrapper with data checking and 304 positive parsed metrics. An eight-rank Open MPI / packaged-RCCL all-reduce passed data checking (`NCCL_IB_DISABLE=1`, single node). RVS module/GPU discovery also worked. -These checks do not qualify multi-node networking, additional GPU architectures, +The default source-built RCCL path has not yet been built or run. These checks +do not qualify multi-node networking, additional GPU architectures, the omitted benchmarks, or sustained RVS stress workloads. -#### Running on MI455X (gfx1250) - -`superbench/config/amd_mi455x.yaml` is a small four-GPU configuration for this -image. Its RCCL modes set the environment used for MI455X all-reduce runs -(`NCCL_IGNORE_CPU_AFFINITY`, `NCCL_CUMEM_ENABLE`, `NCCL_MNNVL_ENABLE`, -`HSA_HOTSWAP_DISABLE`, and `NCCL_DEBUG=VERSION` to log the loaded RCCL), and -`rccl-bw:allreduce` runs the equivalent of -`mpirun -np 4 all_reduce_perf -b 1G -e 32G -f 2 -g 1 -c 0 -w 10 -n 50`. - -```bash -sb run --host-list localhost -i superbench:rocm10-scaffold \ - -c superbench/config/amd_mi455x.yaml \ - -C 'superbench.enable=["rccl-bw:allreduce:correctness","rccl-bw:allreduce"]' -``` - -MNNVL requires `NCCL_CUMEM_ENABLE=1`; set `NCCL_MNNVL_ENABLE=0` on hosts -without a configured scale-up fabric. RCCL-tests' `-A 1` algorithm/protocol -columns are a manual diagnostic and are not emitted by `rccl-bw`. - -#### TransferBench versus the legacy memory-bandwidth test - -The bundled CLI reports version 1.69.00, commit `5fbfa95`; do not assume that it includes every -feature of upstream development. Inspect its actual presets with -`TransferBench presets`. -The [v1.69 preset definitions](https://github.com/ROCm/TransferBench/blob/5fbfa95a1111a7f33f20b9780e5f22bf739f82fa/src/client/Presets/Presets.hpp) -and [transfer syntax](https://github.com/ROCm/TransferBench/blob/5fbfa95a1111a7f33f20b9780e5f22bf739f82fa/src/client/Presets/Help.hpp) -provide these candidate replacements: - -| Interface | Fit for SuperBench | -| --- | --- | -| `p2p` preset | Closest ready-made CPU/NUMA/GPU bandwidth matrix, but it runs more than H2D/D2H and defaults to compute execution. Setting `USE_GPU_DMA=1` alone does not make the CPU-to-GPU rows GPU-executed. | -| Explicit `cmdline` transfers | Best candidate for a new backend: `C0 D0 G0` selects pinned CPU-node-0 memory to GPU 0 via GPU-0 DMA; `G0 D0 C0` reverses the transfer. | -| `hbm`, `a2a`, `one2all`, sweep presets | Useful additional coverage, not drop-in replacements for the two existing host/device metrics. | -| RVS PEBB/PBQT with TransferBench | Suitable qualification workloads. The inspected PEBB adapter supports pinned CPU memory, not pageable memory, and uses only the first configured block size. | - -There is no `hipBusBandwidth`, `--h2d`/`--d2h`, or `rocm-bandwidth-test` -compatibility preset. For a bounded manual smoke test on an idle node, select -accessible NUMA/GPU indices and permit the required NUMA syscalls: - -```bash -TransferBench dryrun 4M '1 1 C0 D0 G0' -timeout 20s env TB_NUM_RANKS=1 NUM_ITERATIONS=3 NUM_WARMUPS=1 \ - NUM_SUBITERATIONS=1 ALWAYS_VALIDATE=0 USE_HSA_DMA=0 \ - USE_HIP_EVENTS=1 USE_INTERACTIVE=0 HIDE_ENV=1 \ - TransferBench cmdline 4M '1 1 C0 D0 G0' -# D2H: use '1 1 G0 D0 C0' instead. -``` - -`ALWAYS_VALIDATE=0` retains the final correctness check; negative values disable -it. `P0` selects pinned host memory near GPU 0, while `H0` selects pageable -memory on NUMA node 0. Both pinned and pageable 4-MiB transfers passed bounded -H2D/D2H smoke tests on MI300X; other sizes, devices and placements still need -qualification. -Container policies must permit NUMA allocation/placement queries; failed -placement checks are errors, not valid bandwidth results. -The tested `OUTPUT_TO_CSV=1` output still includes banners and executor/aggregate -rows; do not treat the complete stdout stream as a flat table of transfer results. - -Before replacing `mem-bw`, choose whether to introduce a separate benchmark/new -baseline or retain strict compatibility. TransferBench's HIP asynchronous DMA -path differs from the old sample's default synchronous `hipMemcpy`. -It reports bytes divided by mean duration, whereas the old sample averages -per-trial bandwidth. Its generic size sweep also omits the old sub-1-KiB -sizes. A new parser must select individual transfer rows, retain device/NUMA -identity, and define the size sweep, aggregation, and pageable-memory policy; -simply renaming the executable would silently change the measurement. - ### ROCm 10 migration considerations The following is a scouting snapshot from **2026-09-29**, not a claim that the diff --git a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py index 347d82171..e7f25da86 100644 --- a/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py +++ b/superbench/benchmarks/micro_benchmarks/rocm_memory_bw_performance.py @@ -3,43 +3,15 @@ """Module of the ROCm memory performance benchmarks.""" -import csv -import ctypes -import math import os -from pathlib import Path -import re -import shlex -import statistics from superbench.common.utils import logger -from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode +from superbench.benchmarks import BenchmarkRegistry, Platform from superbench.benchmarks.micro_benchmarks import MemBwBenchmark class RocmMemBwBenchmark(MemBwBenchmark): """The ROCm memory performance benchmark class.""" - - # HIP rocm-5.5.0 samples/1_Utils/hipBusBandwidth/hipBusBandwidth.cpp. - _TRANSFERBENCH_SIZES = (64, 256, 512) + tuple(2**power for power in range(10, 30)) - _TRANSFERBENCH_ITERATIONS = ( - 1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, - 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20 - ) - _TRANSFERBENCH_ENV = { - 'NUM_WARMUPS': 0, - 'NUM_SUBITERATIONS': 1, - 'SHOW_ITERATIONS': 1, - 'USE_HIP_EVENTS': 1, - 'USE_HSA_DMA': 0, - 'USE_SINGLE_STREAM': 1, - 'USE_INTERACTIVE': 0, - 'ALWAYS_VALIDATE': 0, - 'VALIDATE_DIRECT': 0, - 'VALIDATE_SOURCE': 0, - 'BYTE_OFFSET': 0, - } - def __init__(self, name, parameters=''): """Constructor. @@ -49,24 +21,14 @@ def __init__(self, name, parameters=''): """ super().__init__(name, parameters) - self._backend = os.getenv('SB_ROCM_MEM_BW_BACKEND', 'hipbusbandwidth').lower() - self._bin_name = 'TransferBench' if self._backend == 'transferbench' else 'hipBusBandwidth' + self._bin_name = 'hipBusBandwidth' self._mem_types = ['htod', 'dtoh'] self._parse_logline_map = {'htod': 'H2D_Bandwidth', 'dtoh': 'D2H_Bandwidth'} - self._worker_numa_node = None def add_parser_arguments(self): """Add the specified arguments.""" super().add_parser_arguments() - def _set_binary_path(self): - """Validate explicit backend selection before looking up an executable.""" - if self._backend not in ('hipbusbandwidth', 'transferbench'): - self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) - logger.error('Unsupported ROCm mem-bw backend: {}.'.format(self._backend)) - return False - return super()._set_binary_path() - def _preprocess(self): """Preprocess/preparation operations before the benchmarking. @@ -76,15 +38,8 @@ def _preprocess(self): if not super()._preprocess(): return False - if self._backend == 'transferbench' and self._args.memory == 'unpinned': - if not self._set_worker_numa_node(): - return False - # Check the arguments and generate the commands for mem_type in self._args.mem_type: - if self._backend == 'transferbench': - self._commands.append(self._transferbench_command(mem_type)) - continue command = os.path.join(self._args.bin_dir, self._bin_name) command += ' --' + mem_type.replace('to', '2') if self._args.memory == 'unpinned': @@ -93,137 +48,6 @@ def _preprocess(self): return True - def _set_worker_numa_node(self): - """Resolve the executing worker CPU's NUMA node once for this sweep.""" - try: - getcpu = ctypes.CDLL(None, use_errno=True).sched_getcpu - getcpu.argtypes = [] - getcpu.restype = ctypes.c_int - cpu = getcpu() - if cpu < 0: - raise OSError(ctypes.get_errno(), 'sched_getcpu failed') - cpu_path = Path('/sys/devices/system/cpu/cpu{}'.format(cpu)) - nodes = [entry for entry in cpu_path.iterdir() if re.fullmatch(r'node[0-9]+', entry.name)] - if len(nodes) != 1: - raise ValueError('Expected one NUMA node for CPU {}, found {}'.format(cpu, len(nodes))) - self._worker_numa_node = int(nodes[0].name[4:]) - except (AttributeError, OSError, ValueError) as error: - self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) - logger.error( - 'Cannot determine worker-local NUMA placement - benchmark: {}, error: {}.'.format(self._name, error) - ) - return False - logger.info( - 'TransferBench pageable placement - benchmark: {}, worker CPU: {}, NUMA node: {}, endpoint: H{}.'.format( - self._name, cpu, self._worker_numa_node, self._worker_numa_node - ) - ) - return True - - def _transferbench_route(self, mem_type): - """Return the single-device DMA route, using HIP's logical device zero.""" - host = 'P0' if self._args.memory == 'pinned' else 'H{}'.format(self._worker_numa_node) - return (host, 'G0') if mem_type == 'htod' else ('G0', host) - - def _transferbench_command(self, mem_type): - """Build one fail-fast sweep per direction, retaining one raw log per direction.""" - source, destination = self._transferbench_route(mem_type) - binary = shlex.quote(os.path.join(self._args.bin_dir, self._bin_name)) - environment = dict(self._TRANSFERBENCH_ENV, OUTPUT_TO_CSV=1, HIDE_ENV=0, SHOW_PERCENTILES='') - options = ' '.join('{}={}'.format(key, value) for key, value in environment.items()) - commands = [] - for size, iterations in zip(self._TRANSFERBENCH_SIZES, self._TRANSFERBENCH_ITERATIONS): - commands.append( - "env {} NUM_ITERATIONS={} {} cmdline {} '1 1 {} D0 {}'".format( - options, iterations, binary, size, source, destination - ) - ) - return ' && '.join(commands) - - @staticmethod - def _transferbench_quantity(value, unit, allow_zero=False): - """Parse a finite numeric field with its explicit unit.""" - fields = value.split() - if len(fields) != 2 or fields[1] != unit: - raise ValueError('Invalid TransferBench quantity: {}'.format(value)) - number = float(fields[0]) - if not math.isfinite(number) or number < 0 or (number == 0 and not allow_zero): - raise ValueError('Invalid TransferBench quantity: {}'.format(value)) - return number - - def _transferbench_samples(self, rows, size, iterations): - """Extract every timed iteration, not the reciprocal-mean-time summary.""" - samples = {} - for row in rows: - if not row[0].startswith('Iter '): - continue - index = int(row[0].split()[1]) - if index in samples or not 1 <= index <= iterations: - raise ValueError('Duplicate or unexpected TransferBench iteration') - bandwidth = self._transferbench_quantity(row[1], 'GB/s', allow_zero=True) - duration = self._transferbench_quantity(row[2], 'ms') - # Three-decimal CLI output can round a genuine small-copy bandwidth to zero. - if bandwidth == 0 and size / (duration + 0.0005) / 1e6 >= 0.0005: - raise ValueError('Nonpositive TransferBench bandwidth') - # Preserve HIP5.5's integer nbytes/1000 division, including sub-KB zeros. - samples[index] = (size // 1000) / 1000 / duration - if len(samples) != iterations: - raise ValueError('Incomplete TransferBench iterations') - return statistics.mean(samples.values()) - - def _transferbench_report(self, report, size, iterations, mem_type): - """Validate one CSV-mode report, which also contains banners and typed table rows.""" - rows = [[field.strip() for field in row] for row in csv.reader(report.splitlines()) if row] - settings = dict(self._TRANSFERBENCH_ENV, NUM_ITERATIONS=iterations) - for key, value in settings.items(): - matches = [row for row in rows if row[0] == key] - if len(matches) != 1 or int(matches[0][1]) != value: - raise ValueError('Unexpected TransferBench setting: {}'.format(key)) - - executors = [row for row in rows if row[0].startswith('Executor:')] - transfers = [row for row in rows if row[0].startswith('Transfer ')] - aggregates = [row for row in rows if row[0] == 'Aggregate (CPU)'] - deviations = [row for row in rows if row[0] == 'StandardDev'] - if len(executors) != 1 or len(transfers) != 1 or len(aggregates) != 1 or len(deviations) != 1: - raise ValueError('Incomplete or multi-device TransferBench report') - if executors[0][0] != 'Executor: DMA 00' or transfers[0][0] != 'Transfer 0': - raise ValueError('Unexpected TransferBench executor') - source, destination = self._transferbench_route(mem_type) - if transfers[0][4].split() != [source, '->', 'D0:1', '->', destination]: - raise ValueError('Unexpected TransferBench route') - for row in (executors[0], transfers[0], aggregates[0]): - if row[3].split() != [str(size), 'bytes']: - raise ValueError('Unexpected TransferBench byte count') - return self._transferbench_samples(rows, size, iterations) - - def _process_transferbench_result(self, cmd_idx, raw_output): - """Reduce a complete size sweep to the maximum arithmetic mean bandwidth.""" - try: - if '[ERROR]' in raw_output: - raise ValueError('TransferBench reported an error') - reports = re.split(r'(?m)^TransferBench v[^\n]*\n', raw_output) - if len(reports) != len(self._TRANSFERBENCH_SIZES) + 1: - raise ValueError('Incomplete TransferBench size sweep') - means = [ - self._transferbench_report(report, size, iterations, self._args.mem_type[cmd_idx]) - for report, size, iterations in zip( - reports[1:], self._TRANSFERBENCH_SIZES, self._TRANSFERBENCH_ITERATIONS - ) - ] - bandwidth = max(means) - if not math.isfinite(bandwidth) or bandwidth <= 0: - raise ValueError('Nonpositive TransferBench result') - except (ValueError, IndexError, OverflowError) as error: - logger.error( - 'The result format is invalid - round: {}, benchmark: {}, error: {}, raw output: {}.'.format( - self._curr_run_index, self._name, error, raw_output - ) - ) - return False - metric = self._metrics[self._mem_types.index(self._args.mem_type[cmd_idx])] - self._result.add_result(metric, bandwidth) - return True - def _process_raw_result(self, cmd_idx, raw_output): """Function to parse raw results and save the summarized results. @@ -238,9 +62,6 @@ def _process_raw_result(self, cmd_idx, raw_output): """ self._result.add_raw_data('raw_output_' + self._args.mem_type[cmd_idx], raw_output, self._args.log_raw_data) - if self._backend == 'transferbench': - return self._process_transferbench_result(cmd_idx, raw_output) - mem_bw = -1 value_index = -1 valid = True diff --git a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py index 50a439194..86612f053 100644 --- a/superbench/benchmarks/model_benchmarks/megatron_gpt3.py +++ b/superbench/benchmarks/model_benchmarks/megatron_gpt3.py @@ -240,9 +240,7 @@ def _preprocess(self): os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-DeepSpeed/' ) else: - self._args.code_base = os.getenv('SB_MEGATRON_PATH') or os.path.join( - os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-LM' - ) + self._args.code_base = os.path.join(os.getenv('SB_MICRO_PATH'), 'third_party/Megatron/Megatron-LM') if not os.path.exists(self._args.code_base) or not os.path.exists( os.path.join(self._args.code_base, f'pretrain_{self._args.model}.py') @@ -542,8 +540,6 @@ def _megatron_command(self, precision): # noqa: C901 else: command = f'torchrun {self._distributed_args} {script_path} {megatron_options} {self._data_options}' - if self._args.extra: - command += f' {self._args.extra}' return command def _train_step(self, precision): # noqa: E501 @@ -551,13 +547,8 @@ def _train_step(self, precision): # noqa: E501 command = self._megatron_command(precision) local_rank = os.environ.pop('OMPI_COMM_WORLD_LOCAL_RANK', None) logger.info('Running command: {}.'.format(command)) - try: - output = run_command(command, flush_output=True) - finally: - if local_rank is not None: - os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank - if output.returncode != 0: - raise RuntimeError('Megatron training failed with exit code {}.'.format(output.returncode)) + output = run_command(command, flush_output=True) + os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank iteration_times = [] info = {} @@ -653,8 +644,6 @@ def _generate_dataset(self): # noqa: C901 Return: True if dataset is created successfully. """ - if not self._args.code_base and not self._args.deepspeed: - self._args.code_base = os.getenv('SB_MEGATRON_PATH') or self._args.code_base # Validate num_workers unconditionally so a negative value is rejected even when # dataset files already exist (it would otherwise be emitted as `--num-workers -1` # into the Megatron training command). diff --git a/superbench/benchmarks/model_benchmarks/pytorch_base.py b/superbench/benchmarks/model_benchmarks/pytorch_base.py index dd21db20e..7810b982d 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_base.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_base.py @@ -131,12 +131,6 @@ def _finalize_periodic_logging(self, periodic, info_key='loss'): def add_parser_arguments(self): """Add PyTorch model benchmark-specific arguments to the argument parser.""" super().add_parser_arguments() - self._parser.add_argument( - '--optimizer_eps', - type=float, - default=1e-8, - help='Adam/AdamW epsilon. Use a representable value (for example 1e-4) for native FP16 training.', - ) self._parser.add_argument( '--deterministic_seed', type=int, @@ -452,18 +446,12 @@ def _create_optimizer(self): self._model.parameters(), lr=1e-5, momentum=0.9, weight_decay=1e-4, nesterov=True ) elif self._optimizer_type == Optimizer.ADAM: - self._optimizer = torch.optim.Adam( - self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps - ) + self._optimizer = torch.optim.Adam(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) elif self._optimizer_type == Optimizer.ADAMW: if hasattr(torch.optim, 'AdamW'): - self._optimizer = torch.optim.AdamW( - self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps - ) + self._optimizer = torch.optim.AdamW(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) else: - self._optimizer = transformers.AdamW( - self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=self._args.optimizer_eps - ) + self._optimizer = transformers.AdamW(self._model.parameters(), lr=1e-5, betas=(0.9, 0.999), eps=1e-08) else: self._optimizer = None diff --git a/superbench/benchmarks/model_benchmarks/pytorch_bert.py b/superbench/benchmarks/model_benchmarks/pytorch_bert.py index f052c1b3a..94c0d9c45 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_bert.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_bert.py @@ -62,7 +62,6 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, - Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py b/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py index aaee40cc6..67f781d0a 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_gpt2.py @@ -62,7 +62,6 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, - Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/benchmarks/model_benchmarks/pytorch_llama.py b/superbench/benchmarks/model_benchmarks/pytorch_llama.py index c418932b2..d57b60821 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_llama.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_llama.py @@ -62,7 +62,6 @@ def __init__(self, name, parameters=''): self._supported_precision = [ Precision.FLOAT32, Precision.FLOAT16, - Precision.BFLOAT16, Precision.FP8_HYBRID, Precision.FP8_E4M3, ] diff --git a/superbench/config/amd_mi455x.yaml b/superbench/config/amd_mi455x.yaml deleted file mode 100644 index 207bab886..000000000 --- a/superbench/config/amd_mi455x.yaml +++ /dev/null @@ -1,145 +0,0 @@ -# SuperBench Config - AMD Instinct MI455X (gfx1250), 4 GPUs per node. -# Requires the dockerfile/rocm10.0.x.dockerfile image, whose RCCL and RCCL-tests -# include the gfx1250 fixes from ROCm/rocm-systems#12051. -# Run a subset with: sb run ... -C 'superbench.enable=["gpu-copy-bw:perf"]' -version: v0.12 -superbench: - enable: null - env: - HIP_FORCE_DEV_KERNARG: '1' - var: - default_local_mode: &default_local_mode - enable: true - modes: - - name: local - proc_num: 4 - prefix: HIP_VISIBLE_DEVICES={proc_rank} - parallel: yes - default_pytorch_mode: &default_pytorch_mode - enable: true - modes: - - name: torch.distributed - proc_num: 4 - node_num: 1 - frameworks: - - pytorch - # RCCL environment validated on MI455X. MNNVL uses fabric memory handles and - # needs cuMem; HSA_HOTSWAP_DISABLE turns off the gfx1250 code-object hotswap hook. - rccl_env: &rccl_env - NCCL_IGNORE_CPU_AFFINITY: '1' - NCCL_CUMEM_ENABLE: '1' - NCCL_MNNVL_ENABLE: '1' - HSA_HOTSWAP_DISABLE: '1' - NCCL_DEBUG: VERSION - rccl_mode: &rccl_mode - enable: true - timeout: 1800 - modes: - - name: mpi - proc_num: 4 - node_num: 1 - env: - <<: *rccl_env - model_ddp_parameter: &model_ddp_param - duration: 0 - num_warmup: 64 - num_steps: 512 - sample_count: 8192 - batch_size: 128 - precision: [float32, float16] - model_action: [train] - pin_memory: yes - num_workers: 0 - benchmarks: - kernel-launch: - <<: *default_local_mode - gemm-flops: - <<: *default_local_mode - parameters: - m: 7680 - n: 8192 - k: 8192 - hipblaslt-gemm: - <<: *default_local_mode - parameters: - in_types: ['fp32', 'fp16', 'bf16', 'fp8'] - tolerant_fail: yes - num_warmup: 10 - num_steps: 100 - shapes: - - 4096,4096,4096 - - 8192,8192,8192 - - 16384,16384,16384 - mem-bw: - enable: true - modes: - - name: local - proc_num: 4 - prefix: HIP_VISIBLE_DEVICES={proc_rank} - parallel: no - gpu-copy-bw:correctness: - enable: true - modes: - - name: local - parallel: no - parameters: - mem_type: [htod, dtoh, dtod, one_to_all, all_to_one, all_to_all] - copy_type: [sm, dma] - size: 4096 - num_warm_up: 0 - num_loops: 1 - check_data: true - gpu-copy-bw:perf: - enable: true - timeout: 1800 - modes: - - name: local - parallel: no - parameters: - mem_type: [dtod, all_to_all] - copy_type: [sm, dma] - size: 34359738368 - num_warm_up: 1 - num_loops: 10 - # Data check over small sizes before the large-message bandwidth sweep. - rccl-bw:allreduce:correctness: - <<: *rccl_mode - parameters: - operation: allreduce - ngpus: 1 - minbytes: 8 - maxbytes: 64M - stepfactor: 2 - check: 1 - warmup_iters: 5 - iters: 20 - # Equivalent to: mpirun -np 4 all_reduce_perf -b 1G -e 32G -f 2 -g 1 -c 0 -w 10 -n 50 - rccl-bw:allreduce: - <<: *rccl_mode - parameters: - operation: allreduce - ngpus: 1 - minbytes: 1G - maxbytes: 32G - stepfactor: 2 - check: 0 - warmup_iters: 10 - iters: 50 - model-benchmarks:bert: - <<: *default_pytorch_mode - models: - - bert-base - - bert-large - parameters: - <<: *model_ddp_param - seq_len: 224 - # The default 1e-8 underflows in FP16 Adam. - optimizer_eps: 0.0001 - model-benchmarks:resnet: - <<: *default_pytorch_mode - models: - - resnet50 - - resnet101 - parameters: - <<: *model_ddp_param - batch_size: 384 diff --git a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py index 16db79b73..139716cdc 100644 --- a/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py +++ b/tests/benchmarks/micro_benchmarks/test_rocm_memory_bw_performance.py @@ -4,18 +4,11 @@ """Tests for mem-bw benchmark.""" import numbers -import os -from pathlib import Path -import re -import shlex -import subprocess import unittest -from unittest import mock from tests.helper import decorator from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform -from superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance import RocmMemBwBenchmark class RocmMemBwTest(BenchmarkTestCase, unittest.TestCase): @@ -25,52 +18,7 @@ def setUpClass(cls): """Hook method for setting up class fixture before running tests in the class.""" super().setUpClass() cls.createMockEnvs(cls) - cls.createMockFiles(cls, ['bin/hipBusBandwidth', 'bin/TransferBench']) - - def setUp(self): - """Keep the legacy default independent of the image's backend selection.""" - self.environment = mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'hipbusbandwidth'}) - self.environment.start() - self.addCleanup(self.environment.stop) - module = 'superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance' - libc_patch = mock.patch(module + '.ctypes.CDLL') - self.libc = libc_patch.start() - self.addCleanup(libc_patch.stop) - self.libc.return_value.sched_getcpu.return_value = 0 - nodes_patch = mock.patch(module + '.Path.iterdir', autospec=True) - self.cpu_nodes = nodes_patch.start() - self.addCleanup(nodes_patch.stop) - self.cpu_nodes.return_value = [Path('/sys/devices/system/cpu/cpu0/node0')] - - def _transferbench(self, parameters=''): - """Prepare the explicitly selected backend with mock executables.""" - with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): - benchmark = RocmMemBwBenchmark('mem-bw', parameters) - self.assertTrue(benchmark._preprocess()) - return benchmark - - @staticmethod - def _fixture(memory='pinned', direction='htod'): - """Read captured TransferBench v1.69.00 GPU2 output, logical device zero.""" - return Path('tests/data/rocm_transferbench_{}_{}.log'.format(memory, direction)).read_text() - - def _report(self, size, durations, direction='htod', memory='pinned'): - """Build variable-size reports using the measured CLI format, including misleading summaries.""" - header = self._fixture(memory, direction).split(' Executor:')[0] - header = re.sub(r'(NUM_ITERATIONS\s*,\s*)3,', r'\g<1>{},'.format(len(durations)), header) - host = 'P0' if memory == 'pinned' else 'H0' - route = '{} -> D0:1 -> G0'.format(host) if direction == 'htod' else 'G0 -> D0:1 -> {}'.format(host) - rows = [ - 'Executor: DMA 00, 999.000 GB/s, 1.000 ms, {} bytes, 999.000 GB/s (sum),'.format(size), - 'Transfer 0, 888.000 GB/s, 1.000 ms, {} bytes, {},'.format(size, route), - ] - for index, duration in reversed(list(enumerate(durations, 1))): - rows.append('Iter {:03d}, {:.3f} GB/s, {:.3f} ms, , ,'.format(index, size / duration / 1e6, duration)) - rows.extend([ - 'StandardDev, 0.000 GB/s, 0.000 ms, , ,', - 'Aggregate (CPU), 777.000 GB/s, 1.000 ms, {} bytes, Overhead 0.000 ms,'.format(size), - ]) - return header + '\n'.join(rows) + '\n' + cls.createMockFiles(cls, ['bin/hipBusBandwidth']) @decorator.load_data('tests/data/rocm_memory_h2d_bw.log') @decorator.load_data('tests/data/rocm_memory_d2h_bw.log') @@ -108,292 +56,3 @@ def test_rocm_memory_bw_performance(self, raw_output_h2d, raw_output_d2h): assert (benchmark.result['h2d_bw'][0] == 25.2351) assert (benchmark.result['d2h_bw'][0] == 27.9348) - - def test_legacy_default_and_arguments(self): - """Retain the old executable, flags, normalization and ignored NUMA argument.""" - with mock.patch.dict(os.environ): - os.environ.pop('SB_ROCM_MEM_BW_BACKEND', None) - benchmark = RocmMemBwBenchmark('mem-bw', '--mem_type DTOH --memory unpinned --numa 3') - self.assertTrue(benchmark._preprocess()) - self.assertEqual(benchmark._bin_name, 'hipBusBandwidth') - self.assertEqual(len(benchmark._commands), 1) - self.assertTrue(benchmark._commands[0].endswith('hipBusBandwidth --d2h --unpinned')) - self.assertEqual(benchmark._args.numa, 3) - self.assertNotIn('numactl', benchmark._commands[0]) - - def test_transferbench_exact_legacy_policy(self): - """Cover the complete HIP5.5 size/trial arrays and all controllable timing settings.""" - benchmark = self._transferbench('--numa 3') - sizes = ( - 64, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, - 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, - 134217728, 268435456, 536870912 - ) - iterations = ( - 1000, 1000, 1000, 1000, 500, 500, 500, 500, 500, 200, 200, 200, - 200, 200, 100, 100, 100, 100, 50, 50, 50, 20, 20 - ) - self.assertEqual(benchmark._TRANSFERBENCH_SIZES, sizes) - self.assertEqual(benchmark._TRANSFERBENCH_ITERATIONS, iterations) - self.assertEqual(len(benchmark._commands), 2) - for direction, command in enumerate(benchmark._commands): - commands = command.split(' && ') - self.assertEqual(len(commands), 23) - for subcommand, size, count in zip(commands, sizes, iterations): - tokens = shlex.split(subcommand) - self.assertEqual(tokens[-3:], [ - 'cmdline', str(size), '1 1 P0 D0 G0' if direction == 0 else '1 1 G0 D0 P0' - ]) - for setting in ( - 'NUM_ITERATIONS={}'.format(count), 'NUM_WARMUPS=0', 'NUM_SUBITERATIONS=1', - 'SHOW_ITERATIONS=1', 'OUTPUT_TO_CSV=1', 'USE_HIP_EVENTS=1', 'USE_HSA_DMA=0', - 'USE_INTERACTIVE=0', 'ALWAYS_VALIDATE=0' - ): - self.assertIn(setting, tokens) - self.assertNotIn('numactl', command) - self.assertNotIn('G1', command) - self.assertEqual(benchmark._args.numa, 3) - - def test_transferbench_pageable_subset(self): - """Preserve memory and direction selection without introducing new CLI arguments.""" - benchmark = self._transferbench('--memory unpinned --mem_type DTOH') - self.assertEqual(len(benchmark._commands), 1) - self.assertIn("'1 1 G0 D0 H0'", benchmark._commands[0]) - self.assertNotIn('P0', benchmark._commands[0]) - - def test_transferbench_numa_does_not_override_logical_gpu_locality(self): - """P0 means the visible GPU's nearest node, not physical GPU zero or NUMA zero.""" - with mock.patch.dict(os.environ, {'HIP_VISIBLE_DEVICES': '5'}): - for memory, host in (('pinned', 'P0'), ('unpinned', 'H0')): - with self.subTest(memory=memory): - baseline = self._transferbench('--memory {}'.format(memory)) - explicit = self._transferbench('--memory {} --numa 1'.format(memory)) - self.assertEqual(baseline._commands, explicit._commands) - self.assertIn("'1 1 {} D0 G0'".format(host), explicit._commands[0]) - self.assertIn("'1 1 G0 D0 {}'".format(host), explicit._commands[1]) - self.assertNotIn('C0', explicit._commands[0]) - self.assertNotIn('G5', explicit._commands[0]) - self.assertEqual(explicit._args.numa, 1) - - def test_transferbench_pageable_worker_nodes(self): - """Resolve node0/node1 from the worker CPU, not --numa or the GPU index.""" - for cpu, node in ((0, 0), (48, 1)): - with self.subTest(cpu=cpu, node=node): - self.libc.return_value.sched_getcpu.return_value = cpu - self.cpu_nodes.return_value = [Path('/sys/devices/system/cpu/cpu{}/node{}'.format(cpu, node))] - benchmark = self._transferbench('--memory unpinned --numa 3') - self.cpu_nodes.assert_called_with(Path('/sys/devices/system/cpu/cpu{}'.format(cpu))) - self.assertEqual(benchmark._worker_numa_node, node) - self.assertIn("'1 1 H{} D0 G0'".format(node), benchmark._commands[0]) - self.assertIn("'1 1 G0 D0 H{}'".format(node), benchmark._commands[1]) - benchmark._TRANSFERBENCH_SIZES = (4194304,) - benchmark._TRANSFERBENCH_ITERATIONS = (3,) - raw = self._fixture('unpinned').replace('H0', 'H{}'.format(node)) - self.assertTrue(benchmark._process_raw_result(0, raw)) - wrong_node = self._fixture('unpinned').replace('H0', 'H{}'.format(1 - node)) - self.assertFalse(benchmark._process_raw_result(0, wrong_node)) - self.assertEqual(len(benchmark.result['h2d_bw']), 1) - self.assertEqual(benchmark._args.numa, 3) - - def test_transferbench_pageable_detection_errors(self): - """Fail explicitly on unavailable CPU detection or missing/ambiguous/inaccessible topology.""" - module = 'superbench.benchmarks.micro_benchmarks.rocm_memory_bw_performance' - for error in ('library', 'symbol', 'cpu', 'missing', 'ambiguous', 'permission'): - with self.subTest(error=error): - self.libc.side_effect = None - self.libc.return_value.sched_getcpu.side_effect = None - self.libc.return_value.sched_getcpu.return_value = 0 - self.cpu_nodes.side_effect = None - self.cpu_nodes.return_value = [Path('node0')] - if error == 'library': - self.libc.side_effect = OSError('libc unavailable') - elif error == 'symbol': - self.libc.return_value.sched_getcpu.side_effect = AttributeError('sched_getcpu unavailable') - elif error == 'cpu': - self.libc.return_value.sched_getcpu.return_value = -1 - elif error == 'missing': - self.cpu_nodes.return_value = [Path('topology'), Path('node-invalid')] - elif error == 'ambiguous': - self.cpu_nodes.return_value = [Path('node0'), Path('node1')] - else: - self.cpu_nodes.side_effect = PermissionError('sysfs denied') - with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): - benchmark = RocmMemBwBenchmark('mem-bw', '--memory unpinned') - with mock.patch(module + '.logger.error') as log: - self.assertFalse(benchmark._preprocess()) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE) - self.assertEqual(benchmark._commands, []) - self.assertIsNone(benchmark._worker_numa_node) - self.assertIn('Cannot determine worker-local NUMA placement', log.call_args[0][0]) - - def test_pinned_and_legacy_do_not_detect_worker_numa(self): - """Keep pinned P0 GPU-local and leave both legacy allocation modes unchanged.""" - self.libc.side_effect = OSError('CPU detection unavailable') - benchmark = self._transferbench('--memory pinned --numa 1') - self.assertIn("'1 1 P0 D0 G0'", benchmark._commands[0]) - for memory in ('pinned', 'unpinned'): - with self.subTest(memory=memory): - benchmark = RocmMemBwBenchmark('mem-bw', '--memory {} --numa 1'.format(memory)) - self.assertTrue(benchmark._preprocess()) - self.assertNotIn('numactl', benchmark._commands[0]) - self.libc.assert_not_called() - - def test_transferbench_measured_fixtures(self): - """Use real pinned/pageable output, not flat CSV or aggregate executor bandwidth.""" - expected_times = { - ('pinned', 'htod'): (0.100, 0.104, 23.315), - ('pinned', 'dtoh'): (0.093, 0.094, 23.555), - ('unpinned', 'htod'): (0.131, 0.139, 23.634), - ('unpinned', 'dtoh'): (0.133, 0.135, 23.265), - } - for (memory, direction), times in expected_times.items(): - with self.subTest(memory=memory, direction=direction): - benchmark = self._transferbench('--memory {} --mem_type {}'.format(memory, direction)) - benchmark._TRANSFERBENCH_SIZES = (4194304,) - benchmark._TRANSFERBENCH_ITERATIONS = (3,) - raw = self._fixture(memory, direction) - self.assertTrue(benchmark._process_raw_result(0, raw)) - metric = 'h2d_bw' if direction == 'htod' else 'd2h_bw' - self.assertEqual(len(benchmark.result[metric]), 1) - self.assertAlmostEqual(benchmark.result[metric][0], sum(4.194 / time for time in times) / 3) - self.assertEqual(benchmark.raw_data['raw_output_' + direction], [raw]) - - def test_transferbench_arithmetic_mean_then_max(self): - """Neither fastest sample, inverse mean duration nor aggregate rows are the metric.""" - benchmark = self._transferbench() - benchmark._TRANSFERBENCH_SIZES = (1000000, 2000000) - benchmark._TRANSFERBENCH_ITERATIONS = (2, 2) - raw = self._report(1000000, (1, 0.125)) + self._report(2000000, (0.5, 0.5)) - self.assertTrue(benchmark._process_raw_result(0, raw)) - self.assertEqual(benchmark.result['h2d_bw'], [4.5]) - - def test_transferbench_full_sweep_and_integer_conversion(self): - """Include all trial IDs, sub-KB zero contributions and old integer-byte truncation.""" - benchmark = self._transferbench() - raw = ''.join( - self._report(size, [1] * count) - for size, count in zip(benchmark._TRANSFERBENCH_SIZES, benchmark._TRANSFERBENCH_ITERATIONS) - ) - self.assertTrue(benchmark._process_raw_result(0, raw)) - self.assertEqual(benchmark.result['h2d_bw'], [536.870]) - benchmark._TRANSFERBENCH_SIZES = (64, 1024) - benchmark._TRANSFERBENCH_ITERATIONS = (2, 2) - raw = self._report(64, (16, 1)) + self._report(1024, (1, 1)) - self.assertTrue(benchmark._process_raw_result(0, raw)) - self.assertEqual(benchmark.result['h2d_bw'][-1], 0.001) - - def test_transferbench_rejects_incomplete_and_wrong_reports(self): - """Reject missing/extra sizes, samples, executors, settings and incorrect routes.""" - raw = self._fixture() - corruptions = [ - '', raw + raw, raw[:raw.index('Aggregate (CPU)')], - re.sub(r'^.*Iter 001.*\n', '', raw, flags=re.MULTILINE), - raw.replace('Iter 001', 'Iter 002'), raw.replace('Iter 001', 'Iter 004'), - raw.replace('DMA 00', 'DMA 01'), raw.replace('DMA 00', 'GFX 00'), - raw.replace('Transfer 0', 'Transfer 1'), raw.replace('G0', 'G1'), - raw.replace('D0:1', 'D1:1'), raw.replace('P0', 'H0'), - raw.replace('P0 -> D0:1 -> G0', 'G0 -> D0:1 -> P0'), - raw.replace('4194304 bytes', '4194305 bytes'), - raw.replace('NUM_WARMUPS , 0', 'NUM_WARMUPS , 3'), - raw.replace('NUM_ITERATIONS , 3', 'NUM_ITERATIONS , 2'), - raw + '[ERROR] validation failed\n', - raw.replace('Transfer 0', 'Transfer 0, bad'), - raw.replace('StandardDev', 'missing'), - raw.replace(' Iter 001', 'Transfer 1, 1 GB/s, 1 ms, 4194304 bytes, P0 -> D0:1 -> G0\nIter 001'), - ] - for index, corrupted in enumerate(corruptions): - with self.subTest(case=index): - benchmark = self._transferbench() - benchmark._TRANSFERBENCH_SIZES = (4194304,) - benchmark._TRANSFERBENCH_ITERATIONS = (3,) - self.assertFalse(benchmark._process_raw_result(0, corrupted)) - self.assertNotIn('h2d_bw', benchmark.result) - self.assertEqual(benchmark.raw_data['raw_output_htod'], [corrupted]) - - def test_transferbench_rejects_invalid_numeric_samples(self): - """Reject nonfinite/nonpositive timings and nonphysical bandwidths before reduction.""" - raw = self._fixture() - for field in ('42.133 GB/s', '0.100 ms'): - for invalid in ('nan', 'inf', '-inf', '-1', '0', 'bogus'): - with self.subTest(field=field, invalid=invalid): - benchmark = self._transferbench() - benchmark._TRANSFERBENCH_SIZES = (4194304,) - benchmark._TRANSFERBENCH_ITERATIONS = (3,) - corrupted = raw.replace(field, invalid + ' ' + field.split()[1]) - self.assertFalse(benchmark._process_raw_result(0, corrupted)) - self.assertNotIn('h2d_bw', benchmark.result) - - def test_transferbench_rejects_partial_size_sweep(self): - """Do not accept a valid single-size run as a full legacy-policy sweep.""" - benchmark = self._transferbench() - self.assertFalse(benchmark._process_raw_result(0, self._fixture())) - - def test_transferbench_failure_does_not_fall_back(self): - """Execution and parse errors use framework return codes without invoking hipBusBandwidth.""" - for code, raw, expected in ( - (1, '[ERROR] allocation failed', ReturnCode.MICROBENCHMARK_EXECUTION_FAILURE), - (0, 'malformed', ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE), - ): - with self.subTest(code=code): - benchmark = self._transferbench() - with mock.patch( - 'superbench.benchmarks.micro_benchmarks.micro_base.run_command', - return_value=subprocess.CompletedProcess([], code, raw) - ) as invoke: - self.assertFalse(benchmark._benchmark()) - self.assertEqual(benchmark.return_code, expected) - self.assertEqual(invoke.call_count, 1) - self.assertNotIn('hipBusBandwidth', invoke.call_args[0][0]) - - def test_transferbench_missing_binary_and_unknown_backend(self): - """Explicit selection is never replaced by an available legacy binary.""" - with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): - benchmark = RocmMemBwBenchmark('mem-bw') - with mock.patch('shutil.which', return_value=None): - self.assertFalse(benchmark._preprocess()) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_BINARY_NOT_EXIST) - with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'invalid'}): - benchmark = RocmMemBwBenchmark('mem-bw') - with mock.patch('shutil.which', return_value=None) as lookup: - self.assertFalse(benchmark._preprocess()) - lookup.assert_not_called() - self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) - - def test_transferbench_tolerant_failure_keeps_direction_mapping(self): - """An invalid H2D result must not mislabel a subsequent successful D2H result.""" - benchmark = self._transferbench('--tolerant_fail') - benchmark._TRANSFERBENCH_SIZES = (4194304,) - benchmark._TRANSFERBENCH_ITERATIONS = (3,) - results = [ - subprocess.CompletedProcess([], 0, 'invalid'), - subprocess.CompletedProcess([], 0, self._fixture(direction='dtoh')), - ] - with mock.patch( - 'superbench.benchmarks.micro_benchmarks.micro_base.run_command', side_effect=results - ) as invoke: - self.assertFalse(benchmark._benchmark()) - self.assertEqual(invoke.call_count, 2) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - self.assertNotIn('h2d_bw', benchmark.result) - self.assertEqual(len(benchmark.result['d2h_bw']), 1) - - def test_transferbench_shell_quoting_and_failure_chain(self): - """Quote explicit binary paths and stop a failed sweep before subsequent sizes.""" - binary_dir = Path(self._tmp_dir) / 'bin with spaces' - binary_dir.mkdir(exist_ok=True) - binary = binary_dir / 'TransferBench' - binary.write_text('#!/bin/sh\necho "[ERROR] synthetic failure"\nexit 3\n') - binary.chmod(0o755) - benchmark = self._transferbench('--bin_dir {}'.format(shlex.quote(str(binary_dir)))) - result = subprocess.run(benchmark._commands[0], shell=True, text=True, stdout=subprocess.PIPE, timeout=5) - self.assertEqual(result.returncode, 3) - self.assertEqual(result.stdout.count('[ERROR] synthetic failure'), 1) - - def test_transferbench_invalid_memory_and_direction(self): - """Retain existing validation for unsupported YAML/CLI options.""" - for parameters in ('--memory registered', '--mem_type dtod', '--memory PINNED'): - with self.subTest(parameters=parameters): - with mock.patch.dict(os.environ, {'SB_ROCM_MEM_BW_BACKEND': 'transferbench'}): - benchmark = RocmMemBwBenchmark('mem-bw', parameters) - self.assertFalse(benchmark._preprocess()) - self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) diff --git a/tests/benchmarks/model_benchmarks/test_megatron_launch.py b/tests/benchmarks/model_benchmarks/test_megatron_launch.py deleted file mode 100644 index 81677341a..000000000 --- a/tests/benchmarks/model_benchmarks/test_megatron_launch.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""Regression tests for Megatron command forwarding and failure reporting.""" - -import os -from subprocess import CompletedProcess -from unittest import mock - -import pytest - -from superbench.benchmarks import Precision -from superbench.benchmarks.model_benchmarks.megatron_gpt3 import MegatronGPT -from superbench.benchmarks.model_benchmarks.model_base import ModelBenchmark - - -def make_benchmark(parameters=''): - """Build a command-only benchmark without initializing MPI or downloading data.""" - benchmark = MegatronGPT('megatron-gpt', parameters) - benchmark.add_parser_arguments() - valid, benchmark._args, _ = benchmark.parse_args() - assert valid - benchmark._distributed_args = '--nproc_per_node 2' - benchmark._data_options = '--mock-data' - return benchmark - - -def test_extra_arguments_forwarded(): - """Version-specific options must reach the selected Megatron checkout.""" - benchmark = make_benchmark('--extra "--vocab-size 128 --attention-backend unfused"') - command = benchmark._megatron_command(Precision.BFLOAT16) - assert command.endswith('--mock-data --vocab-size 128 --attention-backend unfused') - - -@pytest.mark.parametrize( - 'explicit,deepspeed,override,expected', - [ - ('', False, '/rocm10/Megatron-LM', '/rocm10/Megatron-LM'), - ('', False, '', '/legacy/third_party/Megatron/Megatron-LM'), - ('', True, '/rocm10/Megatron-LM', '/legacy/third_party/Megatron/Megatron-DeepSpeed/'), - ('/explicit', False, '/rocm10/Megatron-LM', '/explicit'), - ] -) -def test_code_base_selection(explicit, deepspeed, override, expected): - """The image override must preserve explicit paths and legacy/DeepSpeed defaults.""" - benchmark = make_benchmark('--batch_size 32 --num_gpus 2') - benchmark._args.code_base = explicit - benchmark._args.deepspeed = deepspeed - benchmark._num_nodes = 1 - with mock.patch.dict(os.environ, {'SB_MICRO_PATH': '/legacy', 'SB_MEGATRON_PATH': override}): - with mock.patch.object(ModelBenchmark, '_preprocess', return_value=True): - with mock.patch('superbench.benchmarks.model_benchmarks.megatron_gpt3.os.path.exists', return_value=True): - assert benchmark._preprocess() - assert benchmark._args.code_base == expected - - -@pytest.mark.parametrize( - 'explicit,deepspeed,expected', - [('', False, '/rocm10/Megatron-LM'), ('/explicit', False, '/explicit'), ('', True, '')] -) -def test_environment_path_available_during_dataset_generation(explicit, deepspeed, expected): - """Apply the environment path before dataset generation and final path validation.""" - benchmark = make_benchmark('--mock_data --num_workers 0') - benchmark._args.code_base = explicit - benchmark._args.deepspeed = deepspeed - with mock.patch.dict(os.environ, {'SB_MEGATRON_PATH': '/rocm10/Megatron-LM'}): - assert benchmark._generate_dataset() - assert benchmark._args.code_base == expected - - -@pytest.mark.parametrize('local_rank', [None, '0']) -def test_training_failure_restores_environment(local_rank): - """Do not report failed subprocesses as successful timings or assign None to environ.""" - benchmark = make_benchmark() - with mock.patch.dict(os.environ): - os.environ.pop('OMPI_COMM_WORLD_LOCAL_RANK', None) - if local_rank is not None: - os.environ['OMPI_COMM_WORLD_LOCAL_RANK'] = local_rank - with mock.patch( - 'superbench.benchmarks.model_benchmarks.megatron_gpt3.run_command', - return_value=CompletedProcess('torchrun', 2, 'training failed') - ): - with pytest.raises(RuntimeError, match='exit code 2'): - benchmark._train_step(Precision.FLOAT32) - assert os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') == local_rank diff --git a/tests/benchmarks/model_benchmarks/test_transformer_precisions.py b/tests/benchmarks/model_benchmarks/test_transformer_precisions.py deleted file mode 100644 index b1c6ca585..000000000 --- a/tests/benchmarks/model_benchmarks/test_transformer_precisions.py +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""Precision coverage for Transformer Engine consumers.""" - -import pytest -import torch - -from superbench.benchmarks import Precision -from superbench.benchmarks.model_benchmarks.model_base import Optimizer -from superbench.benchmarks.model_benchmarks.pytorch_bert import PytorchBERT -from superbench.benchmarks.model_benchmarks.pytorch_gpt2 import PytorchGPT2 -from superbench.benchmarks.model_benchmarks.pytorch_llama import PytorchLlama - - -@pytest.mark.parametrize('benchmark', [PytorchBERT, PytorchGPT2, PytorchLlama]) -def test_transformer_bfloat16_supported(benchmark): - """BF16 must not be silently skipped by the generic precision filter.""" - instance = benchmark('precision-test') - assert Precision.BFLOAT16 in instance._supported_precision - instance.add_parser_arguments() - valid, arguments, _ = instance.parse_args() - assert valid - assert Precision.BFLOAT16 not in arguments.precision - - -@pytest.mark.parametrize('optimizer', [Optimizer.ADAM, Optimizer.ADAMW]) -@pytest.mark.parametrize('parameters,epsilon', [('', 1e-8), ('--optimizer_eps 1e-4', 1e-4)]) -def test_optimizer_epsilon(optimizer, parameters, epsilon): - """Preserve the default and permit an explicitly FP16-representable epsilon.""" - benchmark = PytorchGPT2('precision-test', parameters) - benchmark.add_parser_arguments() - valid, benchmark._args, _ = benchmark.parse_args() - assert valid - benchmark._model = torch.nn.Linear(16, 16) - benchmark._optimizer_type = optimizer - assert benchmark._create_optimizer() - assert benchmark._optimizer.param_groups[0]['eps'] == epsilon diff --git a/tests/test_rocm10_dockerfile.py b/tests/test_rocm10_dockerfile.py index bd7a08026..b7884ec40 100644 --- a/tests/test_rocm10_dockerfile.py +++ b/tests/test_rocm10_dockerfile.py @@ -265,7 +265,9 @@ def test_installation_order_and_prerequisites(self): 'COPY . .', "pip install -c /tmp/rocm10-constraints.txt '.[torch]'", 'python3 -m pip install pytest pytest-timeout vcrpy', - 'bash dockerfile/etc/install-rocm10-frameworks.sh', + 'ARG TE_COMMIT=', + 'python3 -m pip wheel --no-build-isolation --no-deps', + 'RUN printf \'%s\\n\' \\\n "PATH=${PATH}"', '> /etc/environment', 'CXX="${ROCM_PATH}/bin/hipcc" make cppbuild', 'make postinstall', @@ -281,7 +283,6 @@ def test_framework_runtime_configuration_survives_build_layers(self): self.assertIn('SB_MEGATRON_PATH=/opt/rocm10-frameworks/Megatron-LM', self.dockerfile) self.assertIn('AITER_USE_SYSTEM_TRITON=1', self.dockerfile) self.assertIn('TRITON_F32_DEFAULT=ieee', self.dockerfile) - self.assertIn('bash dockerfile/etc/install-rocm10-frameworks.sh', self.dockerfile) for name in ( 'ROCM_PATH', 'ROCM_HOME', 'HIP_PATH', 'RCCL_HOME', 'SB_MEGATRON_PATH', 'AITER_USE_SYSTEM_TRITON', 'TRITON_F32_DEFAULT', 'MAX_JOBS', @@ -294,16 +295,70 @@ def test_framework_runtime_configuration_survives_build_layers(self): self.assertIn('NVTE_FUSED_ATTN_AOTRITON=0', self.dockerfile) self.assertLess( self.dockerfile.index("RUN python3 -c 'import sysconfig;"), - self.dockerfile.index('bash dockerfile/etc/install-rocm10-frameworks.sh'), + self.dockerfile.index('python3 -m pip wheel --no-build-isolation --no-deps'), ) + def test_framework_build_settings_do_not_reach_runtime(self): + """Export build-only settings in a different layer from the runtime environment file.""" + start = self.dockerfile.index('RUN framework_jobs=') + end = self.dockerfile.index('\n\n', start) + build = self.dockerfile[start:end] + self.assertIn('NVTE_FUSED_ATTN_AOTRITON=1', build) + self.assertIn('RCCL_HOME="${ROCM_PATH}"', build) + self.assertNotIn('/etc/environment', build) + self.assertEqual(self.dockerfile.count('NVTE_FUSED_ATTN_AOTRITON=1'), 1) + + def test_framework_sources_are_pinned_and_built_without_resolution(self): + """Build immutable framework revisions without replacing the SDK, PyTorch or Triton.""" + for name in ('TE_COMMIT', 'AITER_COMMIT', 'MEGATRON_COMMIT'): + self.assertRegex(self.dockerfile, r'(?m)^ARG {}=[0-9a-f]{{40}}$'.format(name)) + for url in ( + 'https://github.com/ROCm/TransformerEngine.git ${TE_COMMIT}', + 'https://github.com/ROCm/aiter.git ${AITER_COMMIT}', + 'https://github.com/NVIDIA/Megatron-LM.git ${MEGATRON_COMMIT}', + ): + self.assertIn(url, self.dockerfile) + self.assertIn('third_party/Megatron/megatron_core_0.19.2_rocm10.patch', self.dockerfile) + self.assertIn("NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250'", self.dockerfile) + self.assertIn('PIP_CONSTRAINT=/tmp/rocm10-constraints.txt', self.dockerfile) + self.assertIn('python3 -m pip install --no-deps /tmp/rocm10-wheels/*.whl', self.dockerfile) + self.assertIn('diff -u /tmp/rocm10-constraints.txt -', self.dockerfile) + self.assertNotIn('pip install transformer_engine', self.dockerfile) + self.assertNotIn('git clone --recursive https://github.com/ROCm/TransformerEngine.git', self.dockerfile) + self.assertFalse((Path(__file__).resolve().parents[1] / 'dockerfile/etc/install-rocm10-frameworks.sh').exists()) + + def test_framework_base_version_check(self): + """Stop before building frameworks unless the base provides the tested packages.""" + start = self.dockerfile.index("python3 -c 'import sys; from importlib.metadata import version;") + check = self.dockerfile[start:self.dockerfile.index(' && \\\n', start)] + versions = { + 'torch': '2.13.0+rocm10.0.0', + 'triton': '3.8.0+git4cff872c.rocm10.0.0', + 'rocm-sdk-core': '10.0.0', + 'rocm-sdk-devel': '10.0.0', + } + for changed in (None, 'torch'): + with self.subTest(changed=changed), tempfile.TemporaryDirectory() as directory: + for name, version in versions.items(): + version = '0.0.0' if name == changed else version + info = Path(directory) / '{}-{}.dist-info'.format(name.replace('-', '_'), version) + info.mkdir() + (info / 'METADATA').write_text(f'Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n') + env = dict(os.environ, PYTHONPATH=directory) + result = subprocess.run(['/bin/bash', '-c', check], env=env, capture_output=True, text=True) + if changed: + self.assertNotEqual(result.returncode, 0) + self.assertIn('torch==2.13.0+rocm10.0.0 (found 0.0.0)', result.stderr) + else: + self.assertEqual(result.returncode, 0, result.stderr) + def test_mpi_prefix_and_scaffold_boundaries(self): """Keep the MPI prefix while avoiding unqualified legacy dependencies.""" self.assertIn('MPI_HOME=/usr/local/mpi', self.dockerfile) self.assertNotIn('--with-rocm=', self.dockerfile) self.assertIn('make -C third_party fio rocm_perftest', self.dockerfile) self.assertNotIn('ROCM_VER=rocm-5.5.0', self.dockerfile) - self.assertNotIn('https://github.com/ROCm/TransformerEngine.git', self.dockerfile) + self.assertNotIn('make -C third_party rocm ', self.dockerfile) self.assertIn("pip install -c /tmp/rocm10-constraints.txt '.[torch]'", self.dockerfile) self.assertIn('python3 -m pip check', self.dockerfile) diff --git a/tests/test_rocm10_framework_install.py b/tests/test_rocm10_framework_install.py deleted file mode 100644 index f54b1834a..000000000 --- a/tests/test_rocm10_framework_install.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""Guard the ROCm10-only source installer against unpinned or CUDA wheel substitutions.""" - -from pathlib import Path -import re -import subprocess - - -INSTALLER = Path(__file__).resolve().parents[1] / 'dockerfile/etc/install-rocm10-frameworks.sh' - - -def test_framework_source_pins(): - """Every framework checkout must use an immutable source revision.""" - source = INSTALLER.read_text() - for name in ['TE_COMMIT', 'AITER_COMMIT', 'MEGATRON_COMMIT']: - assert re.search(r'^readonly {}=[0-9a-f]{{40}}$'.format(name), source, re.MULTILINE) - assert 'https://github.com/ROCm/TransformerEngine.git' in source - assert 'https://github.com/ROCm/aiter.git' in source - assert '--no-build-isolation --no-deps' in source - assert 'pip install transformer_engine' not in source - - -def test_framework_sdk_and_architecture_guards(): - """Preserve the installed SDK/Triton and compile the requested local targets.""" - source = INSTALLER.read_text() - assert 'AITER_USE_SYSTEM_TRITON=1' in source - assert 'PIP_CONSTRAINT=' in source - assert '"torch": "2.13.0+rocm10.0.0"' in source - assert '"triton": "3.8.0+git4cff872c.rocm10.0.0"' in source - assert '"rocm-sdk-core": "10.0.0"' in source - assert '"rocm-sdk-devel": "10.0.0"' in source - assert 'ROCM_PATH="$(rocm-sdk path --root)"' in source - assert "NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250'" in source - assert 'MAX_JOBS > 16' in source - assert 'megatron_core_0.19.2_rocm10.patch' in source - - -def test_framework_installer_shell_syntax(): - """Check shell syntax without installing packages or requiring a GPU.""" - subprocess.run(['bash', '-n', str(INSTALLER)], check=True) From 767c91d6f49a94b338caa3e25dc2a278a9a3d9e0 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Fri, 9 Oct 2026 14:18:32 -0700 Subject: [PATCH 6/8] Address review: build TE for AMDGPU_TARGETS, correct SDK path docs - Derive NVTE_ROCM_ARCH from AMDGPU_TARGETS, normalized like RCCL. - Docs: ROCM_PATH is the wheel SDK root (no /opt/rocm alias); native amdrocm-* packages are RVS dependencies only; AMD SMI bindings use .pth. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dockerfile/rocm10.0.x.dockerfile | 6 ++++-- docs/getting-started/installation.mdx | 22 +++++++++++++--------- tests/test_rocm10_dockerfile.py | 5 ++++- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/dockerfile/rocm10.0.x.dockerfile b/dockerfile/rocm10.0.x.dockerfile index f45fd8085..31183283f 100644 --- a/dockerfile/rocm10.0.x.dockerfile +++ b/dockerfile/rocm10.0.x.dockerfile @@ -5,7 +5,8 @@ LABEL maintainer="SuperBench" SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"] # Experimental scaffold: preserve AMD's matched Python 3.14 / PyTorch 2.13 stack. -# SDK packages include all devices; this argument only selects locally built kernels. +# SDK packages include all devices; this argument selects the targets of locally +# built kernels (SuperBench benchmarks, RCCL and TransformerEngine). ARG AMDGPU_TARGETS="gfx942 gfx950 gfx1250" ARG NUM_MAKE_JOBS=64 ARG ROCM_VERSION=10.0.0 @@ -239,10 +240,11 @@ ENV SB_ROCM10_FRAMEWORK_ROOT=/opt/rocm10-frameworks \ NVTE_FUSED_ATTN_AOTRITON=0 RUN framework_jobs="${NUM_MAKE_JOBS}" && \ if [ "${framework_jobs}" -gt 16 ]; then framework_jobs=16; fi && \ + te_architectures=$(printf '%s' "${AMDGPU_TARGETS}" | tr -s '[:space:]' ';' | sed 's/^;//; s/;$//') && \ export MAX_JOBS="${framework_jobs}" CMAKE_BUILD_PARALLEL_LEVEL="${framework_jobs}" \ NVTE_BUILD_MAX_JOBS="${framework_jobs}" PIP_CONSTRAINT=/tmp/rocm10-constraints.txt \ TMPDIR=/tmp/rocm10-frameworks-scratch NVTE_USE_ROCM=1 NVTE_FRAMEWORK=pytorch \ - NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250' NVTE_NO_LOCAL_VERSION=1 NVTE_CK_JIT=1 \ + NVTE_ROCM_ARCH="${te_architectures}" NVTE_NO_LOCAL_VERSION=1 NVTE_CK_JIT=1 \ NVTE_FUSED_ATTN_AOTRITON=1 PREBUILD_KERNELS=0 BUILD_TARGET=rocm RCCL_HOME="${ROCM_PATH}" && \ python3 -c 'import sys; from importlib.metadata import version; expected = {"torch": "2.13.0+rocm10.0.0", "triton": "3.8.0+git4cff872c.rocm10.0.0", "rocm-sdk-core": "10.0.0", "rocm-sdk-devel": "10.0.0"}; wrong = ["{}=={} (found {})".format(name, value, version(name)) for name, value in expected.items() if version(name) != value]; sys.exit("Unexpected base packages: " + ", ".join(wrong) if wrong else 0)' && \ mkdir -p "${TMPDIR}" && \ diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 21a66073f..4f63643f6 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -128,12 +128,15 @@ The base contains a wheel-distributed SDK. The scaffold installs `rocm[devel,libraries,device-all]==10.0.0` and preserves the base's framework and SDK versions with pip constraints. **All-device GPU packages are the default**; this is not a multi-platform CPU image (the base is Linux x86_64). -`rocm-sdk init` expands the development tree, and `/opt/rocm` points to the -discovered SDK root. No second native-package ROCm SDK is installed. -The development overlay's AMD SMI library aliases point to the core wheel's -canonical library. Otherwise, importing PyTorch before the AMD SMI bindings -can load two initialization states and report zero GPUs even when HIP sees -all devices. +`rocm-sdk init` expands the development tree. `ROCM_PATH` (and `ROCM_HOME`, +`HIP_PATH`) is set to the discovered wheel SDK root in +`/etc/profile.d/rocm10-env.sh`; no `/opt/rocm` alias is created. The native +`amdrocm-*` 10.0.0 runtime, base, AMD SMI, BLAS, rand and LLVM packages from +AMD's APT repository are installed only as RVS dependencies; SuperBench builds +and `LD_LIBRARY_PATH` use the wheel SDK. The core wheel's bundled AMD SMI Python +bindings are registered in place with a `.pth` entry (until +[ROCm/TheRock#3054](https://github.com/ROCm/TheRock/issues/3054) is fixed), so +`import amdsmi` does not pick up a separate PyPI wrapper. * RCCL and RCCL-tests are built from one `rocm-systems` revision (`RCCL_SOURCE_COMMIT`) and installed under `/opt/rccl` and @@ -149,9 +152,10 @@ all devices. host metadata, timing/error values, and NumPy arrays; GPU collectives use RCCL. This scaffold does not claim ROCm-aware MPI support for applications that pass device pointers directly to MPI. -* Locally compiled benchmark kernels default to `gfx942 gfx950 gfx1250`, - independently of the all-device SDK packages. Other kernel targets require an - explicit `AMDGPU_TARGETS` build argument and hardware qualification. +* Locally compiled kernels (SuperBench benchmarks, RCCL and TransformerEngine) + default to `gfx942 gfx950 gfx1250`, independently of the all-device SDK + packages. Other kernel targets require an explicit `AMDGPU_TARGETS` build + argument and hardware qualification. * RVS `1.6.122-708` and its bundled TransferBench come from AMD's signed Ubuntu 26.04 APT repositories under `/opt/rocm/extras-10`. The image sets `SB_ROCM_MEM_BW_BACKEND=transferbench` for ROCm `mem-bw`; the TransferBench diff --git a/tests/test_rocm10_dockerfile.py b/tests/test_rocm10_dockerfile.py index b7884ec40..f6cfca835 100644 --- a/tests/test_rocm10_dockerfile.py +++ b/tests/test_rocm10_dockerfile.py @@ -319,7 +319,10 @@ def test_framework_sources_are_pinned_and_built_without_resolution(self): ): self.assertIn(url, self.dockerfile) self.assertIn('third_party/Megatron/megatron_core_0.19.2_rocm10.patch', self.dockerfile) - self.assertIn("NVTE_ROCM_ARCH='gfx942;gfx950;gfx1250'", self.dockerfile) + self.assertIn('NVTE_ROCM_ARCH="${te_architectures}"', self.dockerfile) + normalize = "$(printf '%s' \"${AMDGPU_TARGETS}\" | tr -s '[:space:]' ';' | sed 's/^;//; s/;$//')" + self.assertIn('rccl_architectures=' + normalize, self.dockerfile) + self.assertIn('te_architectures=' + normalize, self.dockerfile) self.assertIn('PIP_CONSTRAINT=/tmp/rocm10-constraints.txt', self.dockerfile) self.assertIn('python3 -m pip install --no-deps /tmp/rocm10-wheels/*.whl', self.dockerfile) self.assertIn('diff -u /tmp/rocm10-constraints.txt -', self.dockerfile) From 95f15590fabdb4cc1d072751d6199222a11ebed9 Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Mon, 2 Nov 2026 13:38:13 -0800 Subject: [PATCH 7/8] Dockerfile - Move experimental ROCm 10 image to ROCm 10.1 Replace rocm10.0.x.dockerfile with rocm10.1.x.dockerfile on AMD's rocm10.1.0 Ubuntu 26.04 PyTorch 2.13 base, which avoids the ResNet and BERT crashes seen on 10.0. Bump the SDK, therock-10.1 rocm-systems revision, APT dependencies and test archive checksum; keep the RCCL source override because therock-10.1 branched before ROCm/rocm-systems#12051. The 10.1 base uses the system /usr/bin/python3 instead of /opt/venv, so install python3-venv and liblzma-dev for TE's AOTriton build. Build legacy rocm-smi-lib into /usr/local for TE's ROCm SMI header, and drop stale build output from the context before installing SuperBench. Update tests and docs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...0.0.x.dockerfile => rocm10.1.x.dockerfile} | 55 ++++++++++++++----- docs/getting-started/installation.mdx | 31 +++++++---- tests/test_rocm10_dockerfile.py | 47 +++++++++++----- 3 files changed, 97 insertions(+), 36 deletions(-) rename dockerfile/{rocm10.0.x.dockerfile => rocm10.1.x.dockerfile} (85%) diff --git a/dockerfile/rocm10.0.x.dockerfile b/dockerfile/rocm10.1.x.dockerfile similarity index 85% rename from dockerfile/rocm10.0.x.dockerfile rename to dockerfile/rocm10.1.x.dockerfile index 31183283f..539125c96 100644 --- a/dockerfile/rocm10.0.x.dockerfile +++ b/dockerfile/rocm10.1.x.dockerfile @@ -1,4 +1,4 @@ -ARG BASE_IMAGE=rocm/pytorch:rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:3174cb7061d94c427da96c0edef4adea28046fa3f3b2ff3948dc4e995665ff8c +ARG BASE_IMAGE=rocm/pytorch:rocm10.1.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:1d3ebef7da1df35f0c103ed038521933ebaeaf6f8c8d710168d8c294efdc59d9 FROM ${BASE_IMAGE} LABEL maintainer="SuperBench" @@ -9,11 +9,11 @@ SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"] # built kernels (SuperBench benchmarks, RCCL and TransformerEngine). ARG AMDGPU_TARGETS="gfx942 gfx950 gfx1250" ARG NUM_MAKE_JOBS=64 -ARG ROCM_VERSION=10.0.0 -# rocm-systems revision selected by TheRock's therock-10.0 release. -ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9 -# MI455X (gfx1250) needs RCCL fixes merged to rocm-systems develop after that -# release, including ROCm/rocm-systems#12051 (GPU->NIC distance and GDR on gfx1250 +ARG ROCM_VERSION=10.1.0 +# rocm-systems revision selected by TheRock's therock-10.1 release. +ARG ROCM_SYSTEMS_COMMIT=7da43026e4f2ef7600433c38c820732f7a205d22 +# Retain the source override for MI455X (gfx1250) RCCL fixes, including +# ROCm/rocm-systems#12051 (GPU->NIC distance and GDR on gfx1250 # MLOPart partitions) and the gfx1250 symmetric-memory/VMM teardown fixes. # RCCL and RCCL-tests are built from this revision into RCCL_SOURCE_PREFIX. # Pass an empty value to keep the packaged RCCL with release-matched RCCL-tests. @@ -31,15 +31,21 @@ ENV DEBIAN_FRONTEND=noninteractive \ ANSIBLE_DEPRECATION_WARNINGS=FALSE \ ANSIBLE_COLLECTIONS_PATH=/usr/share/ansible/collections +# The 10.1 base runs the system /usr/bin/python3 (the 10.0 base used /opt/venv). +# TE's AOTriton build creates a venv from that interpreter and needs liblzma. RUN apt-get update && \ apt-get install -y --no-install-recommends \ autoconf automake bc build-essential ca-certificates cmake curl \ dmidecode flex gfortran git gnupg iproute2 jq libaio-dev \ libatomic1 libboost-program-options-dev libcap2 libcurl4-openssl-dev \ - libibumad-dev libibverbs-dev libnuma-dev libpci-dev libquadmath0 librdmacm-dev \ + libdrm-dev libibumad-dev libibverbs-dev liblzma-dev libnuma-dev libpci-dev libquadmath0 librdmacm-dev \ libssl-dev libtinfo6 libtool lshw net-tools ninja-build numactl \ - openssh-client openssh-server pciutils pkg-config python3-dev rsync sudo \ + openssh-client openssh-server pciutils pkg-config python3-dev python3-venv rsync sudo \ util-linux wget && \ + pkg-config --exists liblzma && \ + /usr/bin/python3 -m venv /tmp/sb-aotriton-venv-check && \ + /tmp/sb-aotriton-venv-check/bin/python -m pip --version && \ + rm -rf /tmp/sb-aotriton-venv-check && \ apt-get clean # Install the Docker CLI client only. @@ -112,9 +118,9 @@ ENV SB_ROCM_MEM_BW_BACKEND=transferbench \ USE_HIPBLAS_COMPUTETYPE=1 # Install RVS through AMD's signed Ubuntu 26.04 repositories. Explicitly select -# matching native dependencies instead of legacy distro packages or ROCm 10.1. +# matching ROCm 10.1 native dependencies instead of legacy distro packages. ARG RVS_VERSION=1.6.122-708 -ARG ROCM_APT_VERSION=10.0.0-4 +ARG ROCM_APT_VERSION=10.1.0-3 RUN install -d -m 0755 /etc/apt/keyrings && \ curl -fsSL https://stable.repo.amd.com/rocm/gpg/packages.gpg | \ gpg --batch --yes --dearmor -o /etc/apt/keyrings/amdrocm.gpg && \ @@ -198,7 +204,7 @@ RUN test -f third_party/fio/Makefile && \ # Extract only matching prebuilt clients and their external GPU kernel packs. # The ELFs alone cannot initialize matrices without the blas_test_*.kpack files. -ARG ROCM_TESTS_SHA256=47468ff71b8027eed4784de5052aa18684cb2ec0bfe0409ad7e62b9a6cf88f1f +ARG ROCM_TESTS_SHA256=c6d6afe27474badb88793330278616caf74c40d647ea2d26457352d7dfc0ace8 RUN curl -fsSL "https://stable.repo.amd.com/rocm/core/tarball/therock-dist-linux-multiarch-tests-${ROCM_VERSION}.tar.gz" -o /tmp/rocm-tests.tar.gz && \ printf '%s %s\n' "${ROCM_TESTS_SHA256}" /tmp/rocm-tests.tar.gz | sha256sum --check --strict && \ tar -xzf /tmp/rocm-tests.tar.gz -C "${SB_HOME}" --wildcards --no-wildcards-match-slash \ @@ -215,10 +221,33 @@ COPY . . # The same constraints protect them while building the frameworks below. # The SDK supplies amdsmi via .pth, not a separate distribution; use the torch # extra so amdworker does not install a PyPI wrapper that shadows the SDK module. -RUN python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|apex|rocm|rocm[-_][^=]+)==' > /tmp/rocm10-constraints.txt && \ +# Drop stale setuptools output from the build context before installing. +RUN rm -rf build *.egg-info && \ + python3 -m pip freeze | grep -Ei '^(torch|torchvision|torchaudio|triton|apex|rocm|rocm[-_][^=]+)==' > /tmp/rocm10-constraints.txt && \ python3 -m pip install -c /tmp/rocm10-constraints.txt '.[torch]' && \ python3 -m pip install pytest pytest-timeout vcrpy +# This TE revision still includes the legacy ROCm SMI header, which the SDK omits. +# Build that library from the release's rocm-systems revision under /usr/local, +# separate from the SDK and its AMD SMI. +RUN git init -q /tmp/rocm-smi-source && \ + git -C /tmp/rocm-smi-source remote add origin https://github.com/ROCm/rocm-systems.git && \ + git -C /tmp/rocm-smi-source sparse-checkout set projects/rocm-smi-lib && \ + git -C /tmp/rocm-smi-source fetch -q --depth 1 --filter=blob:none origin "${ROCM_SYSTEMS_COMMIT}" && \ + git -C /tmp/rocm-smi-source checkout -q --detach FETCH_HEAD && \ + cmake -S /tmp/rocm-smi-source/projects/rocm-smi-lib -B /tmp/rocm-smi-build -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local \ + -DCMAKE_INSTALL_LIBDIR=lib -DROCM_SMI_DISABLE=OFF -DBUILD_TESTS=OFF && \ + cmake --build /tmp/rocm-smi-build -j"${NUM_MAKE_JOBS}" && \ + cmake --install /tmp/rocm-smi-build && \ + printf '%s\n' /usr/local/lib > /etc/ld.so.conf.d/superbench-rocm-smi.conf && \ + ldconfig && \ + test -r /usr/local/include/rocm_smi/rocm_smi.h && \ + printf '#include \n' | \ + "${ROCM_PATH}/lib/llvm/bin/clang++" -x c++ -fsyntax-only - && \ + python3 -c 'import ctypes; ctypes.CDLL("/usr/local/lib/librocm_smi64.so").rsmi_init' && \ + rm -rf /tmp/rocm-smi-source /tmp/rocm-smi-build + # Build TransformerEngine, AITER and Megatron-LM from pinned sources against the # base's PyTorch, Triton and SDK, without build isolation or dependency resolution. # TE v2.15_rocm, AITER snapshot 2026-09-30, Megatron Core v0.19.2. The TE 2.18-dev @@ -246,7 +275,7 @@ RUN framework_jobs="${NUM_MAKE_JOBS}" && \ TMPDIR=/tmp/rocm10-frameworks-scratch NVTE_USE_ROCM=1 NVTE_FRAMEWORK=pytorch \ NVTE_ROCM_ARCH="${te_architectures}" NVTE_NO_LOCAL_VERSION=1 NVTE_CK_JIT=1 \ NVTE_FUSED_ATTN_AOTRITON=1 PREBUILD_KERNELS=0 BUILD_TARGET=rocm RCCL_HOME="${ROCM_PATH}" && \ - python3 -c 'import sys; from importlib.metadata import version; expected = {"torch": "2.13.0+rocm10.0.0", "triton": "3.8.0+git4cff872c.rocm10.0.0", "rocm-sdk-core": "10.0.0", "rocm-sdk-devel": "10.0.0"}; wrong = ["{}=={} (found {})".format(name, value, version(name)) for name, value in expected.items() if version(name) != value]; sys.exit("Unexpected base packages: " + ", ".join(wrong) if wrong else 0)' && \ + python3 -c 'import sys; from importlib.metadata import version; expected = {"torch": "2.13.0+rocm10.1.0", "triton": "3.8.0+git669b31ac.rocm10.1.0", "rocm-sdk-core": "10.1.0", "rocm-sdk-devel": "10.1.0"}; wrong = ["{}=={} (found {})".format(name, value, version(name)) for name, value in expected.items() if version(name) != value]; sys.exit("Unexpected base packages: " + ", ".join(wrong) if wrong else 0)' && \ mkdir -p "${TMPDIR}" && \ python3 -m pip install \ pybind11==3.0.1 pydantic==2.13.5 einops==0.8.2 psutil==7.2.2 mpi4py==4.1.1 \ diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 4f63643f6..35a5a4d5e 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -113,25 +113,28 @@ Here're the system requirements for all managed GPU nodes. ### Experimental ROCm 10 image scaffold -`dockerfile/rocm10.0.x.dockerfile` starts from AMD's digest-pinned -`rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0` image. +`dockerfile/rocm10.1.x.dockerfile` starts from AMD's digest-pinned +`rocm10.1.0_ubuntu26.04_py3.14_pytorch_release_2.13.0` image. It is a scaffold, not a feature-equivalent replacement for the ROCm 7 images, and is intentionally not yet in the release-image workflow matrix. ```bash git submodule update --init --recursive docker build --build-arg NUM_MAKE_JOBS=8 \ - -f dockerfile/rocm10.0.x.dockerfile -t superbench:rocm10-scaffold . + -f dockerfile/rocm10.1.x.dockerfile -t superbench:rocm10-scaffold . ``` The base contains a wheel-distributed SDK. The scaffold installs -`rocm[devel,libraries,device-all]==10.0.0` and preserves the base's framework -and SDK versions with pip constraints. **All-device GPU packages are the +`rocm[devel,libraries,device-all]==10.1.0` and preserves the base's framework +and SDK versions with pip constraints. Unlike the ROCm 10.0 base, which used a +virtualenv under `/opt/venv`, the 10.1 base runs the system `/usr/bin/python3`, +so SuperBench and the frameworks install into its site-packages and +`python3-venv` is added for TransformerEngine's AOTriton build. **All-device GPU packages are the default**; this is not a multi-platform CPU image (the base is Linux x86_64). `rocm-sdk init` expands the development tree. `ROCM_PATH` (and `ROCM_HOME`, `HIP_PATH`) is set to the discovered wheel SDK root in `/etc/profile.d/rocm10-env.sh`; no `/opt/rocm` alias is created. The native -`amdrocm-*` 10.0.0 runtime, base, AMD SMI, BLAS, rand and LLVM packages from +`amdrocm-*` 10.1.0 runtime, base, AMD SMI, BLAS, rand and LLVM packages from AMD's APT repository are installed only as RVS dependencies; SuperBench builds and `LD_LIBRARY_PATH` use the wheel SDK. The core wheel's bundled AMD SMI Python bindings are registered in place with a `.pth` entry (until @@ -141,12 +144,12 @@ bindings are registered in place with a `.pth` entry (until * RCCL and RCCL-tests are built from one `rocm-systems` revision (`RCCL_SOURCE_COMMIT`) and installed under `/opt/rccl` and `/opt/superbench/bin`. The default revision contains the gfx1250 (MI455X) - fixes merged after TheRock's `therock-10.0` release, including + fixes merged after TheRock's `therock-10.1` release branched, including [ROCm/rocm-systems#12051](https://github.com/ROCm/rocm-systems/pull/12051). `/opt/rccl/lib` precedes the SDK library on `LD_LIBRARY_PATH`, so RCCL-tests and other soname lookups, including SuperBench MPI launches, resolve it. Build with `--build-arg RCCL_SOURCE_COMMIT=` to keep AMD's prebuilt SDK RCCL and compile - only RCCL-tests from the `therock-10.0` revision. + only RCCL-tests from the `therock-10.1` revision. * Open MPI 5.0.10 from the DOCA 3.4.0 userspace packages retains `/usr/local/mpi`. Current built-in MPI calls exchange host metadata, timing/error values, and NumPy arrays; GPU collectives use @@ -166,20 +169,28 @@ bindings are registered in place with a `.pth` entry (until archive, and TransformerEngine, AITER and Megatron-LM built in the Dockerfile from pinned revisions (`TE_COMMIT`, `AITER_COMMIT`, `MEGATRON_COMMIT`) against the base's PyTorch, Triton and SDK. No host driver is installed. +* The pinned TransformerEngine revision still includes the legacy ROCm SMI + header, which the SDK no longer ships, so `rocm-smi-lib` is built from the + release's `rocm-systems` revision into `/usr/local` as a build compatibility + library, separate from the SDK and its AMD SMI. The following remain absent: Intel MLC (`cpu-memory-bw-latency`), Megatron-DeepSpeed, and the old HIP 5.5 `hipBusBandwidth` sample. Existing `rocm-smi` system-info collection and `rocprofv2` tracing still need their separate ROCm 10 migrations. -Validation on 2026-09-30 used the earlier variant with AMD's packaged SDK RCCL +The ROCm 10.1 image has been built and passed the current (26.10) SuperBench +benchmark configuration, together with the PyTorch DDP store fix in the +separate benchmark change. + +Earlier validation of the ROCm 10.0 variant on 2026-09-30 used AMD's packaged SDK RCCL (equivalent to `--build-arg RCCL_SOURCE_COMMIT=`): the image built successfully and passed `pip check`, 34 targeted regression tests (three NVIDIA-only tests skipped), GEMM correctness on all eight MI300X GPUs, FP16/BF16 PyTorch flash SDPA forward/backward, and the SuperBench GPU-copy wrapper with data checking and 304 positive parsed metrics. An eight-rank Open MPI / packaged-RCCL all-reduce passed data checking (`NCCL_IB_DISABLE=1`, single node). RVS module/GPU discovery also worked. -The default source-built RCCL path has not yet been built or run. These checks +That 10.0 validation did not build or run the default source-built RCCL path. These checks do not qualify multi-node networking, additional GPU architectures, the omitted benchmarks, or sustained RVS stress workloads. diff --git a/tests/test_rocm10_dockerfile.py b/tests/test_rocm10_dockerfile.py index f6cfca835..91c425999 100644 --- a/tests/test_rocm10_dockerfile.py +++ b/tests/test_rocm10_dockerfile.py @@ -18,7 +18,7 @@ class Rocm10DockerfileTestCase(unittest.TestCase): def setUpClass(cls): """Load the Dockerfile and extract RCCL test architecture handling.""" root = Path(__file__).resolve().parents[1] - cls.dockerfile = (root / 'dockerfile' / 'rocm10.0.x.dockerfile').read_text(encoding='utf-8') + cls.dockerfile = (root / 'dockerfile' / 'rocm10.1.x.dockerfile').read_text(encoding='utf-8') env_start = cls.dockerfile.index("printf 'export ROCM_PATH=%q") env_end = cls.dockerfile.index('\n\n', env_start) cls.environment_script = cls.dockerfile[env_start:env_end] @@ -74,7 +74,7 @@ def test_default_build_parallelism(self): def test_all_device_sdk_uses_base_package_ecosystem(self): """Discover the installed wheel SDK without an alias or global loader override.""" - self.assertIn('rocm10.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:', self.dockerfile) + self.assertIn('rocm10.1.0_ubuntu26.04_py3.14_pytorch_release_2.13.0@sha256:', self.dockerfile) self.assertIn('"rocm[devel,libraries,device-all]==${ROCM_VERSION}"', self.dockerfile) self.assertIn('rocm-sdk init', self.dockerfile) self.assertIn('ROCM_PATH="$(rocm-sdk path --root)"', self.dockerfile) @@ -90,16 +90,17 @@ def test_sdk_environment_uses_discovered_paths(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) sdk_root = str(root / 'sdk with spaces') - bin_dir = root / 'venv' / 'bin' + bin_dir = root / 'usr' / 'local' / 'bin' bin_dir.mkdir(parents=True) sdk = bin_dir / 'rocm-sdk' sdk.write_text('#!/bin/sh\n[ "$1" = path ] && [ "$2" = --root ] || exit 2\n' 'printf "%s\\n" "$TEST_SDK_ROOT"\n') sdk.chmod(0o755) env = os.environ.copy() - env.pop('BASH_ENV', None) + # The 10.1 base runs the system interpreter, so the SDK CLI is not in a virtualenv. + for name in ('BASH_ENV', 'VIRTUAL_ENV'): + env.pop(name, None) env.update({ - 'VIRTUAL_ENV': str(root / 'venv'), 'TEST_SDK_ROOT': sdk_root, 'MPI_HOME': '/vendor/mpi', 'SB_MICRO_PATH': '/superbench', @@ -162,8 +163,8 @@ def test_rccl_source_build_includes_gfx1250_fixes(self): """Build RCCL and its tests from one revision that contains the MI455X fixes.""" self.assertIn('ARG AMDGPU_TARGETS="gfx942 gfx950 gfx1250"', self.dockerfile) self.assertIn('test -r "${ROCM_PATH}/lib/librccl.so"', self.dockerfile) - self.assertIn('ARG ROCM_SYSTEMS_COMMIT=6b0e43f341195e203754e08f850e437ff2fc09f9', self.dockerfile) - # Merge commit of ROCm/rocm-systems#12051. + self.assertIn('ARG ROCM_SYSTEMS_COMMIT=7da43026e4f2ef7600433c38c820732f7a205d22', self.dockerfile) + # Merge commit of ROCm/rocm-systems#12051; therock-10.1 branched before it. self.assertIn('ARG RCCL_SOURCE_COMMIT=2a0c58ec63ea22487ea65458b68b92426119eb11', self.dockerfile) self.assertIn('RCCL_SOURCE_PREFIX=/opt/rccl', self.dockerfile) self.assertIn("rccl_projects='projects/rccl projects/rccl-tests'", self.dockerfile) @@ -278,6 +279,26 @@ def test_installation_order_and_prerequisites(self): positions = [self.dockerfile.index(step) for step in steps] self.assertEqual(positions, sorted(positions)) + def test_framework_prerequisites_for_system_python(self): + """Provide TE's AOTriton and legacy ROCm SMI needs on the base's system interpreter.""" + apt_start = self.dockerfile.index('RUN apt-get update') + apt = self.dockerfile[apt_start:self.dockerfile.index('\n\n', apt_start)] + for package in ('libdrm-dev', 'liblzma-dev', 'python3-venv'): + self.assertRegex(apt, r'\s{}\s'.format(package)) + self.assertIn('pkg-config --exists liblzma', apt) + self.assertIn('/usr/bin/python3 -m venv /tmp/sb-aotriton-venv-check', apt) + self.assertEqual(self.dockerfile.count('apt-get install'), 3) + + smi_start = self.dockerfile.index('RUN git init -q /tmp/rocm-smi-source') + smi = self.dockerfile[smi_start:self.dockerfile.index('\n\n', smi_start)] + self.assertIn('origin "${ROCM_SYSTEMS_COMMIT}"', smi) + self.assertIn('sparse-checkout set projects/rocm-smi-lib', smi) + self.assertIn('-DCMAKE_INSTALL_PREFIX=/usr/local', smi) + self.assertIn('ctypes.CDLL("/usr/local/lib/librocm_smi64.so").rsmi_init', smi) + self.assertIn('rm -rf /tmp/rocm-smi-source /tmp/rocm-smi-build', smi) + self.assertLess(smi_start, self.dockerfile.index('RUN framework_jobs=')) + self.assertNotIn('pip wheel --verbose', self.dockerfile) + def test_framework_runtime_configuration_survives_build_layers(self): """Keep the selected Megatron path and precise Triton FP32 mode at runtime.""" self.assertIn('SB_MEGATRON_PATH=/opt/rocm10-frameworks/Megatron-LM', self.dockerfile) @@ -335,10 +356,10 @@ def test_framework_base_version_check(self): start = self.dockerfile.index("python3 -c 'import sys; from importlib.metadata import version;") check = self.dockerfile[start:self.dockerfile.index(' && \\\n', start)] versions = { - 'torch': '2.13.0+rocm10.0.0', - 'triton': '3.8.0+git4cff872c.rocm10.0.0', - 'rocm-sdk-core': '10.0.0', - 'rocm-sdk-devel': '10.0.0', + 'torch': '2.13.0+rocm10.1.0', + 'triton': '3.8.0+git669b31ac.rocm10.1.0', + 'rocm-sdk-core': '10.1.0', + 'rocm-sdk-devel': '10.1.0', } for changed in (None, 'torch'): with self.subTest(changed=changed), tempfile.TemporaryDirectory() as directory: @@ -351,7 +372,7 @@ def test_framework_base_version_check(self): result = subprocess.run(['/bin/bash', '-c', check], env=env, capture_output=True, text=True) if changed: self.assertNotEqual(result.returncode, 0) - self.assertIn('torch==2.13.0+rocm10.0.0 (found 0.0.0)', result.stderr) + self.assertIn('torch==2.13.0+rocm10.1.0 (found 0.0.0)', result.stderr) else: self.assertEqual(result.returncode, 0, result.stderr) @@ -368,7 +389,7 @@ def test_mpi_prefix_and_scaffold_boundaries(self): def test_rvs_uses_signed_apt_repositories(self): """Install RVS and matching dependencies with APT, not a tarball or forced extraction.""" self.assertIn('ARG RVS_VERSION=1.6.122-708', self.dockerfile) - self.assertIn('ARG ROCM_APT_VERSION=10.0.0-4', self.dockerfile) + self.assertIn('ARG ROCM_APT_VERSION=10.1.0-3', self.dockerfile) self.assertIn('https://stable.repo.amd.com/rocm/extras/rvs/packages/ubuntu2604/', self.dockerfile) self.assertIn('https://stable.repo.amd.com/rocm/core/packages/ubuntu2604/', self.dockerfile) self.assertIn('Signed-By: /etc/apt/keyrings/amdrocm.gpg', self.dockerfile) From 69da834eabe478d47750d8f84aa87111f29cd31d Mon Sep 17 00:00:00 2001 From: "Nguyen Vuong (from Dev Box)" Date: Mon, 2 Nov 2026 13:41:05 -0800 Subject: [PATCH 8/8] Docs - Require NUMA auto-balancing disabled on AMD GPU hosts As on MI200/MI300 hosts, MI455X runs with the ROCm 10 image hang or behave unexpectedly unless kernel.numa_balancing is 0. Document the host setting, how to check it and how to disable it persistently, since the container cannot change it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/getting-started/installation.mdx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 35a5a4d5e..d3e69b0e4 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -107,6 +107,13 @@ Here're the system requirements for all managed GPU nodes. * Compatible GPU drivers should be installed correctly, and group permission should be set to access GPU resources. You should be able to run `rocm-smi` and `rocminfo` directly to check GPU usage and information. * [Docker CE](https://docs.docker.com/engine/install/) version 20.10 or later (which can be checked by running `docker --version`). +* NUMA auto-balancing should be disabled on the host, as AMD + [recommends](https://instinct.docs.amd.com/projects/amdgpu-docs/en/docs-30.20.1/system-optimization/mi300x.html#disable-numa-auto-balancing) + for MI200 and MI300 series systems. Hangs and unexpected behavior have also been seen on MI455X with the ROCm 10 + image when it is enabled. This is a host kernel setting that the container cannot change. + `cat /proc/sys/kernel/numa_balancing` should print `0`. Disable it until the next reboot with + `sudo sysctl -w kernel.numa_balancing=0`, or persistently with + `echo 'kernel.numa_balancing = 0' | sudo tee /etc/sysctl.d/99-numa-balancing.conf && sudo sysctl --system`. @@ -116,7 +123,8 @@ Here're the system requirements for all managed GPU nodes. `dockerfile/rocm10.1.x.dockerfile` starts from AMD's digest-pinned `rocm10.1.0_ubuntu26.04_py3.14_pytorch_release_2.13.0` image. It is a scaffold, not a feature-equivalent replacement for the ROCm 7 images, -and is intentionally not yet in the release-image workflow matrix. +and is intentionally not yet in the release-image workflow matrix. Hosts need +the AMD GPU prerequisites above, including NUMA auto-balancing disabled. ```bash git submodule update --init --recursive