Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
feat(docker): add an AMD ROCm image, for RDNA2 through RDNA4 and CDNA (#10820)
Leo Borcherding28299aceda6c
diff --git a/.github/workflows/docker-publish-rocm.yml b/.github/workflows/docker-publish-rocm.ymlnew file mode 100644index 00000000000..883f0600ddd--- /dev/null+++ b/.github/workflows/docker-publish-rocm.yml@@ -0,0 +1,334 @@+# Builds and publishes the AMD ROCm Unsloth Docker image (docker/Dockerfile.rocm).+#+# No GPU runner needed: the ROCm torch wheels do not probe a device at install+# time, and the build-time check reads torch.version.hip, a constant baked into+# the wheel. amd64 only: neither pytorch.org nor repo.amd.com publishes ROCm+# wheels for arm64.+#+# Required secret: DOCKER_API_KEY, the Docker Hub ORGANIZATION access token used+# by docker-publish.yml. Optional variable HAS_AMD_GPU_RUNNER='true' gates the+# smoke-test job, which needs a self-hosted runner labelled amd-gpu.++name: Publish ROCm Docker image++on:+ push:+ # Tags only, for the reason docker-publish.yml gives: publishing on every merge+ # was the bulk of the repo's Actions spend. The weekly cron is the cadence.+ tags: ['v*']+ schedule:+ # Weekly, off the hour and offset from the CUDA image's daily run.+ - cron: '23 5 * * 2'+ workflow_dispatch:+ inputs:+ unsloth_ref:+ # The stable-tag gates require this EMPTY, so a non-blank default would make+ # every UI-default dispatch publish SHA tags only.+ description: 'unsloth git ref override (blank = dispatched branch + stable tags)'+ required: false+ default: ''+ unsloth_zoo_ref:+ description: 'unsloth-zoo git ref to bake in'+ required: false+ default: 'main'+ rocm_version:+ description: 'ROCm base image version (blank = the Dockerfile default, 7.2.4)'+ required: false+ default: ''+ torch_index_url:+ description: 'PyTorch ROCm wheel index (blank = the Dockerfile default, rocm7.2)'+ required: false+ default: ''+ rocm_gfx:+ description: 'AMD per-arch wheels for one gfx (gfx1150/1151/1152/1200/1201), or gfx906 (generic index, no bitsandbytes; pair with rocm_version 6.3.4); blank = generic'+ required: false+ default: ''++env:+ REGISTRY: docker.io+ IMAGE_NAME: unsloth/unsloth-rocm+ # The org name, not a person: Docker Hub authenticates an organization access+ # token as the organization. See docker-publish.yml.+ REGISTRY_USERNAME: unsloth+ DEFAULT_ROCM_VERSION: '7.2.4'+ DEFAULT_TORCH_INDEX_URL: 'https://download.pytorch.org/whl/rocm7.2'+ # the last ROCm with gfx906 kernels: the default base for rocm_gfx=gfx906+ GFX906_ROCM_VERSION: '6.3.4'++# Serialise per-ref runs, except on main where each RUN gets its own group: a+# shared group DISCARDS a pending run when a newer one is queued (see+# tests/studio/test_main_runs_survive_merge_bursts.py), and the sha alone still+# pairs a scheduled run with a dispatch on an unchanged main, so the run id is the+# key there. Never cancel in progress: a half-pushed digest is worse than a stale+# :latest for a few minutes.+concurrency:+ group: docker-publish-rocm-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.run_id || '' }}+ cancel-in-progress: false++# Pushes use Docker Hub registry creds, not GITHUB_TOKEN, so read is enough.+permissions:+ contents: read++jobs:+ # Resolve the refs ONCE, to commits: docker matches a RUN layer on the command+ # string, so a mutable "main" build arg would reuse the pip layer of an earlier+ # build and report success with stale bits.+ prepare:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ unsloth_ref: ${{ steps.unsloth_ref.outputs.ref }}+ zoo_ref: ${{ steps.zoo_ref.outputs.ref }}+ rocm_version: ${{ steps.build_args.outputs.rocm_version }}+ torch_index_url: ${{ steps.build_args.outputs.torch_index_url }}+ rocm_gfx: ${{ steps.build_args.outputs.rocm_gfx }}+ # every input at its default: only then may the build take the stable tags+ stable: ${{ steps.build_args.outputs.stable }}+ # every input at its default except a set gfx: only then the gfx tag+ gfx_tag: ${{ steps.build_args.outputs.gfx_tag }}+ steps:+ # Precedence: dispatch input, else pushed tag, else trigger sha, else main.+ - name: Resolve unsloth ref+ id: unsloth_ref+ env:+ INPUT_REF: ${{ github.event.inputs.unsloth_ref }}+ TAG_REF: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || '' }}+ PUSH_SHA: ${{ github.sha }}+ run: |+ REF="$INPUT_REF"+ [ -n "$REF" ] || REF="$TAG_REF"+ [ -n "$REF" ] || REF="$PUSH_SHA"+ REF="${REF:-main}"+ if printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then+ SHA="$REF"+ else+ # ls-remote exits 0 whether or not a ref matched, so a non-zero exit means+ # the remote was never reached and the fallback would hand a MUTABLE name+ # to the build.+ if ! LS_OUT="$(git ls-remote https://github.com/unslothai/unsloth "$REF")"; then+ echo "::error::unslothai/unsloth unreachable; cannot freeze ref '${REF}' to a sha"+ exit 1+ fi+ SHA="$(printf '%s\n' "$LS_OUT" | awk 'NR==1{print $1}')"+ [ -n "$SHA" ] || SHA="$REF"+ fi+ echo "ref=${SHA}" >> "$GITHUB_OUTPUT"+ echo "unsloth ref: ${SHA}"++ # only when the tag exists there: unsloth's v* tags are Studio releases+ - name: Resolve unsloth-zoo ref+ id: zoo_ref+ env:+ INPUT_REF: ${{ github.event.inputs.unsloth_zoo_ref }}+ IS_TAG: ${{ startsWith(github.ref, 'refs/tags/') }}+ TAG_NAME: ${{ github.ref_name }}+ run: |+ REF="$INPUT_REF"+ if [ -z "$REF" ] && [ "$IS_TAG" = "true" ]; then+ # git documents status 2 as "reached the remote, no matching ref"; any+ # other non-zero means the lookup never happened, so swallowing both+ # lets a transport blip pair the unsloth tag with zoo main.+ _rc=0+ git ls-remote --exit-code --tags https://github.com/unslothai/unsloth-zoo \+ "refs/tags/${TAG_NAME}" >/dev/null 2>&1 || _rc=$?+ if [ "$_rc" = "0" ]; then+ REF="$TAG_NAME"+ elif [ "$_rc" != "2" ]; then+ echo "::error::unslothai/unsloth-zoo unreachable (git ls-remote exit ${_rc}); cannot tell whether it carries tag '${TAG_NAME}'"+ exit 1+ fi+ fi+ REF="${REF:-main}"+ if printf '%s' "$REF" | grep -Eq '^[0-9a-f]{40}$'; then+ SHA="$REF"+ else+ if ! LS_OUT="$(git ls-remote https://github.com/unslothai/unsloth-zoo "$REF")"; then+ echo "::error::unslothai/unsloth-zoo unreachable; cannot freeze ref '${REF}' to a sha"+ exit 1+ fi+ SHA="$(printf '%s\n' "$LS_OUT" | awk 'NR==1{print $1}')"+ [ -n "$SHA" ] || SHA="$REF"+ fi+ echo "ref=${SHA}" >> "$GITHUB_OUTPUT"+ echo "unsloth-zoo ref: ${SHA}"++ # :latest and the release tags name the DEFAULT build. A dispatch that+ # changed any input (an older ROCm, another index, a per-arch build) gets+ # SHA tags only, so it can never overwrite what `docker pull` hands out.+ - name: Resolve build args and the stable-tag gate+ id: build_args+ env:+ IN_UNSLOTH: ${{ github.event.inputs.unsloth_ref }}+ IN_ZOO: ${{ github.event.inputs.unsloth_zoo_ref }}+ IN_ROCM: ${{ github.event.inputs.rocm_version }}+ IN_INDEX: ${{ github.event.inputs.torch_index_url }}+ IN_GFX: ${{ github.event.inputs.rocm_gfx }}+ run: |+ GFX="${IN_GFX}"+ case "$GFX" in+ ""|gfx906|gfx1150|gfx1151|gfx1152|gfx1200|gfx1201) ;;+ *) echo "::error::rocm_gfx='${GFX}' has no per-arch wheel index (gfx906 = generic index without bitsandbytes)"; exit 1 ;;+ esac+ # gfx906 has no kernels after ROCm 6.3, so its defaults are the last base+ # that carries it; the public :gfx906 tag names that pair, and a 6.4++ # base with gfx906 is refused rather than tagged.+ DEF_ROCM="$DEFAULT_ROCM_VERSION"+ DEF_INDEX="$DEFAULT_TORCH_INDEX_URL"+ if [ "$GFX" = gfx906 ]; then+ DEF_ROCM="$GFX906_ROCM_VERSION"+ DEF_INDEX="https://download.pytorch.org/whl/rocm${DEF_ROCM%.*}"+ fi+ ROCM="${IN_ROCM:-$DEF_ROCM}"+ # the index follows the base unless named: a 6.3.4 base with the 7.2+ # wheels would build (torch.version.hip is set either way) and not run+ INDEX="${IN_INDEX:-https://download.pytorch.org/whl/rocm${ROCM%.*}}"+ if [ "$GFX" = gfx906 ]; then+ case "$ROCM" in+ 6.[0-3]|6.[0-3].*) ;;+ *) echo "::error::rocm_gfx=gfx906 needs a ROCm 6.3 base (AMD dropped gfx906 after 6.3), not ${ROCM}"; exit 1 ;;+ esac+ fi+ # DEFAULTS: every input other than the gfx at its default. STABLE adds a+ # blank gfx. A per-arch build gets its gfx tag only under DEFAULTS, so a+ # feature-branch ref plus gfx1151 cannot replace the public gfx1151 image.+ DEFAULTS=true+ [ -z "$IN_UNSLOTH" ] || DEFAULTS=false+ case "$IN_ZOO" in ""|main) ;; *) DEFAULTS=false ;; esac+ [ "$ROCM" = "$DEF_ROCM" ] || DEFAULTS=false+ [ "$INDEX" = "$DEF_INDEX" ] || DEFAULTS=false+ STABLE=$DEFAULTS+ [ -z "$GFX" ] || STABLE=false+ GFX_TAG=false+ [ "$DEFAULTS" = "true" ] && [ -n "$GFX" ] && GFX_TAG=true+ {+ echo "rocm_version=${ROCM}"+ echo "torch_index_url=${INDEX}"+ echo "rocm_gfx=${GFX}"+ echo "stable=${STABLE}"+ echo "gfx_tag=${GFX_TAG}"+ } >> "$GITHUB_OUTPUT"+ echo "ROCm ${ROCM}, index ${INDEX}, gfx '${GFX}', stable tags: ${STABLE}, gfx tag: ${GFX_TAG}"++ build:+ needs: prepare+ runs-on: ubuntu-latest+ timeout-minutes: 120+ outputs:+ digest: ${{ steps.build.outputs.digest }}+ steps:+ - uses: actions/checkout@v4++ # The ROCm base image plus the wheel cache do not fit the default runner disk.+ - name: Reclaim disk+ run: |+ sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \+ /opt/hostedtoolcache/CodeQL "$AGENT_TOOLSDIRECTORY" || true+ df -h /++ - uses: docker/setup-buildx-action@v3++ - name: Log in to Docker Hub+ uses: docker/login-action@v3+ with:+ username: ${{ env.REGISTRY_USERNAME }}+ password: ${{ secrets.DOCKER_API_KEY }}++ - name: Resolve labels+ id: meta+ uses: docker/metadata-action@v5+ with:+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}+ # The action copies the repo's Apache-2.0; the image ships AGPL-3.0 files too+ # (docker/smoke_test_rocm.py), as docker-publish.yml records for its images.+ labels: |+ org.opencontainers.image.licenses=Apache-2.0 AND AGPL-3.0-only++ - name: Build and push (by digest)+ id: build+ uses: docker/build-push-action@v6+ with:+ context: ./docker+ file: ./docker/Dockerfile.rocm+ platforms: linux/amd64+ labels: ${{ steps.meta.outputs.labels }}+ cache-from: type=gha,scope=build-rocm-amd64+ cache-to: type=gha,scope=build-rocm-amd64,mode=max+ outputs: type=image,name=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true+ build-args: |+ ROCM_VERSION=${{ needs.prepare.outputs.rocm_version }}+ PYTHON_VERSION=3.12+ TORCH_INDEX_URL=${{ needs.prepare.outputs.torch_index_url }}+ ROCM_GFX=${{ needs.prepare.outputs.rocm_gfx }}+ UNSLOTH_REF=${{ needs.prepare.outputs.unsloth_ref }}+ UNSLOTH_ZOO_REF=${{ needs.prepare.outputs.zoo_ref }}++ # Attach human-readable tags to the digest pushed above.+ tag:+ runs-on: ubuntu-latest+ needs: [prepare, build]+ timeout-minutes: 15+ outputs:+ tags: ${{ steps.meta.outputs.tags }}+ steps:+ - uses: docker/setup-buildx-action@v3++ - name: Log in to Docker Hub+ uses: docker/login-action@v3+ with:+ username: ${{ env.REGISTRY_USERNAME }}+ password: ${{ secrets.DOCKER_API_KEY }}++ - name: Resolve tags+ id: meta+ uses: docker/metadata-action@v5+ with:+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}+ # latest: a default-input build of the default branch (schedule or dispatch).+ # A per-arch build gets its gfx in the tag so it is findable, never latest.+ # An override build's sha tag carries the run id: two experiments at the same+ # commit would otherwise overwrite each other's only name.+ tags: |+ type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.prepare.outputs.stable == 'true' }}+ type=ref,event=tag,enable=${{ needs.prepare.outputs.stable == 'true' }}+ type=schedule,pattern=nightly,enable=${{ needs.prepare.outputs.stable == 'true' }}+ type=raw,value=${{ needs.prepare.outputs.rocm_gfx }},enable=${{ needs.prepare.outputs.gfx_tag == 'true' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}+ type=sha,prefix=sha-,format=short,suffix=${{ needs.prepare.outputs.rocm_gfx != '' && format('-{0}', needs.prepare.outputs.rocm_gfx) || '' }}${{ needs.prepare.outputs.stable != 'true' && format('-r{0}', github.run_id) || '' }}++ - name: Create manifest+ env:+ DIGEST: ${{ needs.build.outputs.digest }}+ run: |+ TAG_FLAGS=()+ while IFS= read -r t; do TAG_FLAGS+=(-t "$t"); done < <(jq -r '.tags[]' <<<"$DOCKER_METADATA_OUTPUT_JSON")+ docker buildx imagetools create "${TAG_FLAGS[@]}" "${REGISTRY}/${IMAGE_NAME}@${DIGEST}"++ - name: Inspect the result+ run: |+ for tag in $(jq -r '.tags[]' <<<"$DOCKER_METADATA_OUTPUT_JSON"); do+ echo "=== $tag ==="+ docker buildx imagetools inspect "$tag"+ done++ # Optional: pull THIS run's digest onto a self-hosted AMD GPU runner and train+ # for five steps. The digest, not a tag: a tag can already point at a newer+ # run by the time this job starts.+ smoke-test:+ needs: [build, tag]+ if: ${{ vars.HAS_AMD_GPU_RUNNER == 'true' }}+ runs-on: [self-hosted, amd-gpu]+ timeout-minutes: 45+ steps:+ - name: Pull and smoke-test+ env:+ DIGEST: ${{ needs.build.outputs.digest }}+ run: |+ IMG="${REGISTRY}/${IMAGE_NAME}@${DIGEST}"+ echo "smoke-testing $IMG"+ docker pull "$IMG"+ # numeric gids: the names do not exist inside the image+ FLAGS=(--device /dev/kfd --device /dev/dri)+ for g in video render; do+ gid="$(getent group "$g" | cut -d: -f3)" || gid=""+ [ -n "$gid" ] && FLAGS+=(--group-add "$gid")+ done+ docker run --rm "${FLAGS[@]}" --ipc=host "$IMG" python /workspace/smoke_test_rocm.pydiff --git a/docker/.dockerignore b/docker/.dockerignoreindex 05d7e23c198..89e60acc4c6 100644--- a/docker/.dockerignore+++ b/docker/.dockerignore@@ -1,7 +1,11 @@**!Dockerfile+!Dockerfile.rocm+!Dockerfile.studio-rocm!entrypoint.sh+!entrypoint-rocm.sh!smoke_test.py+!smoke_test_rocm.py!fetch_llama_prebuilt.py!supervisord.conf!studio_launch.shdiff --git a/docker/Dockerfile.rocm b/docker/Dockerfile.rocmnew file mode 100644index 00000000000..0b98a76055a--- /dev/null+++ b/docker/Dockerfile.rocm@@ -0,0 +1,263 @@+# syntax=docker/dockerfile:1.7+# ---------------------------------------------------------------------------+# Unsloth for AMD GPUs (ROCm).+#+# Default build: ROCm 7.2.4 base + the pytorch.org rocm7.2 wheels, which carry+# RDNA2 (gfx1030), RDNA3 (gfx1100-1102), RDNA4 (gfx1200/1201) and CDNA+# (gfx908/90a/942). gfx906 (Radeon VII, MI50) ended with ROCm 6.3 and has no+# prebuilt bitsandbytes kernels, so it gets the 6.3 base without bitsandbytes:+# ROCM_GFX=gfx906 ROCM_VERSION=6.3.4 TORCH_INDEX_URL=https://download.pytorch.org/whl/rocm6.3 \+# bash docker/build.sh --rocm+# Strix APUs (gfx1150/1151/1152) and RDNA4 get AMD's per-arch wheels, which fix+# what the generic index below rocm7.13 lacks (the _grouped_mm segfault on+# gfx1151 among them); the index becomes repo.amd.com/rocm/whl/<family>/ and+# torch is pinned to 2.11, as install.sh routes them on a bare host:+# ROCM_GFX=gfx1151 bash docker/build.sh --rocm # or --gfx gfx1151+#+# Single-stage: ROCm publishes no runtime-only base, so a split saves nothing.+# Build host: Docker with buildkit, no GPU, amd64 only (no arm64 ROCm wheels).+#+# Build:+# bash docker/build.sh --rocm+# build.sh freezes UNSLOTH_REF / UNSLOTH_ZOO_REF to commits; a bare `docker build`+# with the default "main" reuses the cached git-install layer after upstream+# moves, so pass resolved shas when calling docker directly:+# docker build -f docker/Dockerfile.rocm --build-arg UNSLOTH_REF=<sha> \+# --build-arg UNSLOTH_ZOO_REF=<sha> -t unsloth-rocm:latest docker/+# Run:+# bash docker/run.sh --rocm+# docker run --device /dev/kfd --device /dev/dri --group-add <video gid> \+# --group-add <render gid> --ipc=host \+# unsloth-rocm:latest python /workspace/smoke_test_rocm.py+# ---------------------------------------------------------------------------++ARG ROCM_VERSION=7.2.4+ARG PYTHON_VERSION=3.12++FROM rocm/dev-ubuntu-24.04:${ROCM_VERSION}++ARG ROCM_VERSION+ARG PYTHON_VERSION+ARG UNSLOTH_REF=main+ARG UNSLOTH_ZOO_REF=main+# Matched to the base image: the rocmX.Y index has to be the ROCm the base ships.+ARG TORCH_INDEX_URL=https://download.pytorch.org/whl/rocm7.2+# Set to a gfx arch (gfx1150, gfx1151, gfx1152, gfx1200, gfx1201) for the+# per-arch AMD wheels; TORCH_INDEX_URL is then ignored.+ARG ROCM_GFX=++LABEL org.opencontainers.image.title="Unsloth (AMD ROCm)" \+ org.opencontainers.image.description="Unsloth fine-tuning for AMD RDNA2/RDNA3/RDNA4 and CDNA GPUs"++ENV DEBIAN_FRONTEND=noninteractive \+ PIP_NO_CACHE_DIR=1 \+ PIP_DISABLE_PIP_VERSION_CHECK=1 \+ PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ ROCBLAS_USE_HIPBLASLT=1++# Ubuntu 24.04's own python3.12 (the rocm/dev-ubuntu-22.04 image only has 3.10,+# which is why PYTHON_VERSION was silently ignored there).+RUN apt-get update && apt-get install -y --no-install-recommends \+ python${PYTHON_VERSION} python${PYTHON_VERSION}-venv python${PYTHON_VERSION}-dev \+ python3-pip curl wget git \+ cmake build-essential libcurl4-openssl-dev \+ && rm -rf /var/lib/apt/lists/*++ENV VENV=/opt/unsloth-venv+RUN --mount=type=cache,target=/root/.cache/pip \+ python${PYTHON_VERSION} -m venv ${VENV} \+ && ${VENV}/bin/pip install -U pip wheel setuptools uv \+ && ${VENV}/bin/python -c "import sys; assert sys.version_info[:2] == tuple(int(x) for x in '${PYTHON_VERSION}'.split('.')), sys.version"++# Where torch comes from, resolved once and read by the later layers:+# generic: TORCH_INDEX_URL as given, unpinned torch (the index is the pin)+# ROCM_GFX: AMD's per-arch index and the torch 2.11 line, as install.sh's+# Strix/RDNA4 reroute does (gfx1200/1201 share the gfx120X-all family)+RUN set -eu; \+ IDX="${TORCH_INDEX_URL}"; SPEC="torch torchvision torchaudio"; FAM=""; \+ case "${ROCM_GFX}" in \+ "") ;; \+ gfx906) ;; \+ gfx1200|gfx1201) FAM=gfx120X-all ;; \+ gfx1150|gfx1151|gfx1152) FAM="${ROCM_GFX}" ;; \+ *) echo "ROCM_GFX=${ROCM_GFX}: no per-arch wheel index (known: gfx1150 gfx1151 gfx1152 gfx1200 gfx1201; gfx906 = generic index without bitsandbytes)" >&2; exit 1 ;; \+ esac; \+ if [ -n "${FAM}" ]; then \+ IDX="https://repo.amd.com/rocm/whl/${FAM}/"; \+ SPEC="torch>=2.11.0,<2.12.0 torchvision>=0.26.0,<0.27.0 torchaudio>=2.11.0,<2.12.0"; \+ fi; \+ printf 'TORCH_INDEX_URL=%s\nTORCH_SPEC="%s"\nROCM_GFX=%s\nROCM_VERSION=%s\n' \+ "$IDX" "$SPEC" "${ROCM_GFX}" "${ROCM_VERSION}" > /etc/unsloth-rocm-build; \+ cat /etc/unsloth-rocm-build++# The whole Python stack in ONE layer, resolved once. The obvious two-step+# (torch from the ROCm index, then the rest) fails twice: unsloth-zoo bounds+# torch (<2.13 now), so the second step swaps the 14 GB torch and the old one+# stays as a dead layer (measured: 70 GB image, 16 GB live); and under+# unsafe-best-match uv takes the highest version across indexes, so a newer+# pypi torch wins as a CUDA build and drags in nvidia-* wheels.+# So: resolve the stack, read its torch version, ask the ROCm index alone for+# the torch family at or below it, resolve again under those constraints, and+# install the lock. The build check below asserts torch.version.hip anyway.+RUN --mount=type=cache,target=/root/.cache/uv \+ set -eu; . /etc/unsloth-rocm-build; \+ UV="${VENV}/bin/uv"; PY="${VENV}/bin/python"; \+ printf '%s\n' ${TORCH_SPEC} \+ "unsloth_zoo @ git+https://github.com/unslothai/unsloth-zoo@${UNSLOTH_ZOO_REF}" \+ "unsloth[huggingface] @ git+https://github.com/unslothai/unsloth@${UNSLOTH_REF}" \+ "timm>=1.0.11" "addict" > /tmp/stack.in; \+ $UV pip compile -q --python "$PY" --index-strategy unsafe-best-match \+ --extra-index-url "${TORCH_INDEX_URL}" -o /tmp/stack.lock /tmp/stack.in; \+ X="$(sed -nE 's/^torch==([0-9][^+ ]*).*/\1/p' /tmp/stack.lock)"; \+ [ -n "$X" ] || { echo "the stack resolved without torch?" >&2; exit 1; }; \+ echo "the stack wants torch ${X}"; \+ { printf '%s\n' ${TORCH_SPEC}; echo "torch<=${X}"; } > /tmp/family.in; \+ $UV pip compile -q --python "$PY" --index-url "${TORCH_INDEX_URL}" \+ -o /tmp/family.lock /tmp/family.in; \+ grep -E '^(torch|torchvision|torchaudio)==' /tmp/family.lock > /tmp/family.txt; \+ echo "ROCm index torch family:"; cat /tmp/family.txt; \+ grep -q '^torch==.*+rocm' /tmp/family.txt || { echo "no +rocm torch on ${TORCH_INDEX_URL} for torch<=${X}" >&2; exit 1; }; \+ $UV pip compile -q --python "$PY" --index-strategy unsafe-best-match \+ --extra-index-url "${TORCH_INDEX_URL}" -c /tmp/family.txt -o /tmp/stack.lock /tmp/stack.in; \+ echo "resolved:"; grep -E '^(torch|torchvision|torchaudio|torchao|triton|unsloth|transformers|trl|peft)' /tmp/stack.lock; \+ $UV pip install --python "$PY" --index-strategy unsafe-best-match \+ --extra-index-url "${TORCH_INDEX_URL}" -r /tmp/stack.lock; \+ cp /tmp/stack.lock ${VENV}/stack.lock.txt; rm -f /tmp/stack.in /tmp/stack.lock /tmp/family.in /tmp/family.lock /tmp/family.txt++# Repair the triton tree. unsloth-zoo and cut-cross-entropy declare a bare+# `triton` (pypi's NVIDIA wheel) while the ROCm torch pins its own build+# (`triton-rocm` on pytorch.org, `triton` +rocm on repo.amd.com); both unpack+# into site-packages/triton/, so the layer above leaves a spliced tree. Remove+# every triton-named dist, then reinstall torch's pin from its own index.+RUN --mount=type=cache,target=/root/.cache/uv \+ set -eu; . /etc/unsloth-rocm-build; \+ PIN="$(${VENV}/bin/python -c "import re;from importlib.metadata import requires;print(next(re.split(r'[;]', r)[0].strip() for r in requires('torch') if re.match(r'(pytorch-)?triton', r)))")"; \+ echo "torch pins ${PIN}"; \+ for d in triton triton-rocm pytorch-triton-rocm; do \+ ${VENV}/bin/uv pip uninstall --python ${VENV}/bin/python "$d" >/dev/null 2>&1 || true; \+ done; \+ rm -rf ${VENV}/lib/python${PYTHON_VERSION}/site-packages/triton; \+ ${VENV}/bin/uv pip install --python ${VENV}/bin/python \+ --index-url "${TORCH_INDEX_URL}" --reinstall "${PIN}"++# bitsandbytes via pip (uv refuses the pre-release wheel's filename/metadata+# version mismatch) from the build with the ROCm 4-bit GEMV fix (bitsandbytes+# PR #1887); the fallback is the first PyPI release with it, since 0.49.x and+# below produce NaNs at decode shape on every AMD GPU. Same URL and fallback+# as install.sh's _install_bnb_rocm(). No wheel carries gfx906 kernels, so a+# gfx906 build ships without bitsandbytes (as install.sh does).+RUN if grep -q '^ROCM_GFX=gfx906$' /etc/unsloth-rocm-build; then \+ echo "gfx906: no prebuilt bitsandbytes kernels; removing bitsandbytes from the stack"; \+ ${VENV}/bin/python -m pip uninstall -y bitsandbytes || true; \+ else \+ _BNB_WHL="https://github.com/bitsandbytes-foundation/bitsandbytes/releases/download/continuous-release_main/bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_x86_64.whl" \+ && (${VENV}/bin/python -m pip install \+ --force-reinstall --no-cache-dir --no-deps "${_BNB_WHL}" \+ || (echo "[WARN] bnb pre-release install failed; falling back to PyPI bitsandbytes>=0.50.0" >&2 \+ && ${VENV}/bin/python -m pip install \+ --force-reinstall --no-cache-dir --no-deps "bitsandbytes>=0.50.0")); \+ fi++# Pin record (informational; the resolver's own lock is stack.lock.txt beside it).+# Read with: docker run --rm <image> cat /opt/unsloth-venv/requirements.lock.txt+RUN ${VENV}/bin/pip freeze --exclude-editable > ${VENV}/requirements.lock.txt \+ && head -30 ${VENV}/requirements.lock.txt++# Build-time verification (no GPU required). torch.version.hip is a string+# constant baked into the ROCm wheel (None in CUDA builds), so it needs no device.+RUN ${VENV}/bin/python - <<'PY'+import re+from importlib.metadata import PackageNotFoundError, distributions, requires, version++import torch++assert torch.version.hip is not None, (+ f"Expected a ROCm torch wheel but got: {torch.__version__}. "+ "Check that TORCH_INDEX_URL points to the ROCm index."+)+print(f"OK: torch {torch.__version__} HIP {torch.version.hip}")++BUILD_GFX = re.search(r"^ROCM_GFX=(.*)$", open("/etc/unsloth-rocm-build").read(), re.M).group(1)+WANT_BNB = BUILD_GFX != "gfx906"+REQUIRED = [+ "torch", "unsloth", "unsloth-zoo",+ "transformers", "trl", "peft", "accelerate",+] + (["bitsandbytes"] if WANT_BNB else [])+missing = []+for pkg in REQUIRED:+ try:+ print(f" {pkg:14s} {version(pkg)}")+ except PackageNotFoundError:+ missing.append(pkg)+if missing:+ raise SystemExit(f"FAIL: missing packages: {missing}")+print("OK: all required packages present")++# No CUDA runtime wheels: their presence means a pypi torch family member won.+nvidia = sorted(d.metadata["Name"] for d in distributions() if (d.metadata["Name"] or "").startswith("nvidia-"))+assert not nvidia, f"FAIL: CUDA wheels in a ROCm image: {nvidia}"++# Exactly one triton-named dist, the one torch pins, and its files are what+# `import triton` finds (the repair layer above is what this checks).+import triton # noqa: E402++pin = next(r for r in requires("torch") if re.match(r"(pytorch-)?triton", r))+pin_name = re.split(r"[=<>!~;\s]", pin, 1)[0]+present = sorted(+ d.metadata["Name"] for d in distributions()+ if re.match(r"(pytorch-)?triton", d.metadata["Name"] or "")+)+assert present == [pin_name], f"FAIL: triton dists {present}, torch pins {pin_name}"+# Base versions only: AMD's per-arch triton is 3.6.0+rocm7.13.0 by metadata but+# reports 3.6.0 (measured on gfx1151); a pypi triton still differs in the base.+assert version(pin_name).split("+")[0] == triton.__version__.split("+")[0], (+ f"FAIL: {pin_name} {version(pin_name)} by metadata but triton.__version__ is {triton.__version__}"+)+import triton.backends # noqa: E402++backends = sorted(triton.backends.backends)+assert "amd" in backends, f"FAIL: triton has no amd backend (has {backends})"+print(f"OK: triton {triton.__version__} ({pin_name}) with backends {backends}")++# Importing bitsandbytes here catches a broken or ABI-mismatched wheel at build+# time instead of at the first training step on a real GPU.+if WANT_BNB:+ import bitsandbytes # noqa: E402, F401++ print(f"OK: bitsandbytes {bitsandbytes.__version__} imports on a no-GPU host")+else:+ try:+ version("bitsandbytes")+ except PackageNotFoundError:+ print("OK: gfx906 build carries no bitsandbytes")+ else:+ raise SystemExit("FAIL: a gfx906 build must not carry bitsandbytes")+PY++# Strip __pycache__ and bundled test suites to shrink the layer.+RUN find ${VENV} -depth -type d -name __pycache__ -exec rm -rf {} + \+ && find ${VENV} -depth -type d -name tests \+ ! -path "*numpy/_core/tests*" \+ ! -path "*numpy/tests*" \+ ! -path "*numpy/ma/tests*" \+ -exec rm -rf {} + \+ && rm -rf /root/.cache/pip /root/.cache/uv++ENV PATH=/opt/unsloth-venv/bin:${PATH} \+ HF_HOME=/workspace/.cache/huggingface \+ TRITON_CACHE_DIR=/workspace/.cache/triton \+ # so an extension that source-builds at runtime can find the toolkit+ ROCM_HOME=/opt/rocm++WORKDIR /workspace+RUN mkdir -p ${HF_HOME} ${TRITON_CACHE_DIR}++COPY smoke_test_rocm.py /workspace/smoke_test_rocm.py+COPY entrypoint-rocm.sh /usr/local/bin/unsloth-entrypoint-rocm+RUN chmod +x /usr/local/bin/unsloth-entrypoint-rocm++# The entrypoint checks /dev/kfd, rocm-smi and torch.cuda before user code, and+# names the fix for each. Bypass: docker run -e UNSLOTH_SKIP_GPU_CHECK=1 ...+ENTRYPOINT ["/usr/local/bin/unsloth-entrypoint-rocm"]+CMD ["python"]diff --git a/docker/build.sh b/docker/build.shindex 6a90428f04a..7627e86e626 100755--- a/docker/build.sh+++ b/docker/build.sh@@ -4,20 +4,57 @@## Usage:# ./build.sh # builds unsloth-blackwell:latest pinned to unsloth main+# ./build.sh --rocm # builds unsloth-rocm:latest for AMD GPUs# TAG=2026.05.1 ./build.sh # custom tag# UNSLOTH_REF=v2026.5.6 UNSLOTH_ZOO_REF=v2026.5.4 ./build.sh # pin git refs+#+# ROCm: the default is the ROCm 7.2.4 base with the pytorch.org rocm7.2 wheels+# (RDNA2, RDNA3, RDNA4, CDNA). Strix APUs and RDNA4 cards get AMD's per-arch+# wheels with --gfx (or ROCM_GFX=...), which switches the index to+# repo.amd.com/rocm/whl/<family>/ and the torch 2.11 line, as install.sh does:+# ./build.sh --rocm --gfx gfx1151 # Strix Halo+# ROCM_GFX=gfx1201 ./build.sh --rocm # RX 9070 XT+# gfx906 (Radeon VII / MI50) needs the last base that carries it, and --gfx gfx906+# leaves out bitsandbytes (no prebuilt gfx906 kernels):+# ROCM_VERSION=6.3.4 ./build.sh --rocm --gfx gfx906set -euo pipefailcd "$(dirname "$0")"-IMAGE_NAME="${IMAGE_NAME:-unsloth-blackwell}"+ROCM=0+ROCM_GFX="${ROCM_GFX:-}"+while [[ $# -gt 0 ]]; do+ case "$1" in+ --rocm) ROCM=1 ;;+ --gfx) [[ $# -ge 2 ]] || { echo "--gfx needs an arch (e.g. gfx1151)" >&2; exit 2; }+ ROCM_GFX="$2"; shift ;;+ --gfx=*) ROCM_GFX="${1#--gfx=}" ;;+ *) echo "unknown option: $1 (build.sh takes --rocm [--gfx <arch>])" >&2; exit 2 ;;+ esac+ shift+done+if [[ -n "$ROCM_GFX" && $ROCM -eq 0 ]]; then+ echo "--gfx / ROCM_GFX only applies to --rocm builds" >&2+ exit 2+fi+TAG="${TAG:-latest}"-CUDA_VERSION="${CUDA_VERSION:-12.8.1}"-UBUNTU_VERSION="${UBUNTU_VERSION:-24.04}"PYTHON_VERSION="${PYTHON_VERSION:-3.12}"UNSLOTH_REF="${UNSLOTH_REF:-main}"UNSLOTH_ZOO_REF="${UNSLOTH_ZOO_REF:-main}"UNSLOTH_NOTEBOOKS_REF="${UNSLOTH_NOTEBOOKS_REF:-main}"+if [[ $ROCM -eq 1 ]]; then+ IMAGE_NAME="${IMAGE_NAME:-unsloth-rocm}"+ # 7.2 is the floor: rocm6.4 tops out at torch 2.9.1, below what unsloth-zoo+ # wants, and RDNA4 (gfx1200/1201) has no kernels before 7.x.+ ROCM_VERSION="${ROCM_VERSION:-7.2.4}"+ # the index follows the base unless named (7.2.4 -> rocm7.2)+ TORCH_INDEX_URL="${TORCH_INDEX_URL:-https://download.pytorch.org/whl/rocm${ROCM_VERSION%.*}}"+else+ IMAGE_NAME="${IMAGE_NAME:-unsloth-blackwell}"+ CUDA_VERSION="${CUDA_VERSION:-12.8.1}"+ UBUNTU_VERSION="${UBUNTU_VERSION:-24.04}"+fi# Frozen to a commit here, for the same reason LLAMA_PREBUILT_TAG is resolved below and# the publish workflow freezes both refs with git ls-remote: docker matches a RUN layer@@ -46,6 +83,9 @@ UNSLOTH_ZOO_REF="$(resolve_git_ref https://github.com/unslothai/unsloth-zoo "$UN# workflow already freezes this one; leaving it out here meant a rebuild after# unslothai/notebooks moved silently kept the old set, and stamped the old commit# into .unsloth_template_commit so the image misreported which set it carried.+# Dockerfile.rocm carries neither the notebooks nor the llama.cpp prebuilt, so the+# ROCm build skips both lookups rather than printing a tag it never passes.+if [[ $ROCM -eq 0 ]]; thenUNSLOTH_NOTEBOOKS_REF="$(resolve_git_ref https://github.com/unslothai/notebooks "$UNSLOTH_NOTEBOOKS_REF")"# Resolved to a concrete tag here, so the build-arg changes only on a new release and@@ -64,6 +104,41 @@ if [ -z "${LLAMA_PREBUILT_TAG:-}" ]; thenecho "Could not resolve latest llama.cpp tag here; passing 'latest' (resolved inside the build)"fifi+fi++if [[ $ROCM -eq 1 ]]; then+ echo "Building ${IMAGE_NAME}:${TAG} [AMD ROCm]"+ echo " ROCm ${ROCM_VERSION} Python ${PYTHON_VERSION}"+ if [[ "$ROCM_GFX" == gfx906 ]]; then+ echo " torch index ${TORCH_INDEX_URL} (gfx906: no bitsandbytes)"+ elif [[ -n "$ROCM_GFX" ]]; then+ echo " torch index AMD per-arch wheels for ${ROCM_GFX} (repo.amd.com/rocm/whl)"+ else+ echo " torch index ${TORCH_INDEX_URL}"+ fi+ echo " unsloth @${UNSLOTH_REF}"+ echo " unsloth-zoo @${UNSLOTH_ZOO_REF}"+ echo++ DOCKER_BUILDKIT=1 docker build \+ --progress=plain \+ -f Dockerfile.rocm \+ --build-arg ROCM_VERSION="${ROCM_VERSION}" \+ --build-arg PYTHON_VERSION="${PYTHON_VERSION}" \+ --build-arg TORCH_INDEX_URL="${TORCH_INDEX_URL}" \+ --build-arg ROCM_GFX="${ROCM_GFX}" \+ --build-arg UNSLOTH_REF="${UNSLOTH_REF}" \+ --build-arg UNSLOTH_ZOO_REF="${UNSLOTH_ZOO_REF}" \+ -t "${IMAGE_NAME}:${TAG}" \+ .++ echo+ echo "Built ${IMAGE_NAME}:${TAG}"+ echo+ echo "Smoke test on an AMD host (run.sh defaults to the published image, so name this one):"+ echo " UNSLOTH_IMAGE=${IMAGE_NAME}:${TAG} bash run.sh --rocm python /workspace/smoke_test_rocm.py"+ exit 0+fiecho "Building ${IMAGE_NAME}:${TAG}"echo " CUDA ${CUDA_VERSION} Ubuntu ${UBUNTU_VERSION} Python ${PYTHON_VERSION}"diff --git a/docker/entrypoint-rocm.sh b/docker/entrypoint-rocm.shnew file mode 100644index 00000000000..bcdfd5432fe--- /dev/null+++ b/docker/entrypoint-rocm.sh@@ -0,0 +1,276 @@+#!/usr/bin/env bash+# Container startup checks for Unsloth (AMD ROCm build).+#+# Fails fast with actionable messages when the host GPU is not reachable, in+# the order the failures tend to bite:+# 1. /dev/kfd missing or unreadable (no --device flags, no --group-add,+# Docker Desktop, amdgpu not loaded)+# 2. what rocm-smi sees, as a note (it does not list every APU)+# 3. torch is a HIP build and torch.cuda.is_available() is True: the gate+# 4. the card's gfx arch against what this image's wheels carry+#+# Bypass for offline tooling / CI:+# docker run -e UNSLOTH_SKIP_GPU_CHECK=1 ...+set -euo pipefail++err() { printf "\033[1;31mERROR:\033[0m %s\n" "$*" >&2; }+warn() { printf "\033[1;33mWARN:\033[0m %s\n" "$*" >&2; }++# UNSLOTH_DEV_ROOT prefixes the /dev probes (DESTDIR idiom) so the regression+# tests can stage a device tree; leave it unset in normal use.+DEV_ROOT="${UNSLOTH_DEV_ROOT:-}"+# What the image was built with; written by Dockerfile.rocm.+BUILD_INFO="${UNSLOTH_ROCM_BUILD_INFO:-/etc/unsloth-rocm-build}"+IMAGE_ROCM=""+IMAGE_GFX=""+if [[ -r "$BUILD_INFO" ]]; then+ IMAGE_ROCM="$(sed -n 's/^ROCM_VERSION=//p' "$BUILD_INFO")"+ IMAGE_GFX="$(sed -n 's/^ROCM_GFX=//p' "$BUILD_INFO")"+fi+# A per-arch image has native kernels for its gfx; a leftover+# HSA_OVERRIDE_GFX_VERSION (the generic-wheel workaround) would make ROCr present+# an arch this image has no kernels for. install.sh clears it the same way.+case "$IMAGE_GFX" in+ gfx1150|gfx1151|gfx1152|gfx1200|gfx1201)+ if [[ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ]]; then+ warn "ignoring HSA_OVERRIDE_GFX_VERSION=${HSA_OVERRIDE_GFX_VERSION}: this image carries native ${IMAGE_GFX} kernels"+ unset HSA_OVERRIDE_GFX_VERSION+ fi ;;+esac++# The skip flag bypasses the diagnostics only; the override cleanup above+# still applies, since it changes what the command sees.+if [[ "${UNSLOTH_SKIP_GPU_CHECK:-0}" == "1" ]]; then+ exec "$@"+fi++# --- Check 1: /dev/kfd is accessible ----------------------------------------+# /dev/kfd is the AMD Kernel Fusion Driver node. It must exist AND be readable+# by the container user before any HIP / torch.cuda call can succeed.+if [[ ! -e "$DEV_ROOT/dev/kfd" ]]; then+ err "/dev/kfd not found inside the container."+ cat >&2 <<'MSG'++The AMD GPU device node is missing. Likely causes:++ 1. The container was started without --device /dev/kfd --device /dev/dri.+ Re-launch with the bundled wrapper, which adds them and the group ids:+ bash docker/run.sh --rocm <cmd>+ Or by hand:+ docker run --device /dev/kfd --device /dev/dri \+ --group-add $(getent group video | cut -d: -f3) \+ --group-add $(getent group render | cut -d: -f3) \+ <other-flags> unsloth/unsloth-rocm:latest <cmd>++ 2. The host has no /dev/kfd to pass through. Docker Desktop on Windows and+ macOS never has one (ROCm needs the Linux amdgpu driver; WSL exposes+ /dev/dxg instead), so this image cannot reach a GPU there. On Linux, check+ the driver: lsmod | grep amdgpu++To bypass this check (e.g. offline tooling), set UNSLOTH_SKIP_GPU_CHECK=1.+MSG+ exit 1+fi++if [[ ! -r "$DEV_ROOT/dev/kfd" ]]; then+ err "/dev/kfd exists but is not readable by the container user."+ cat >&2 <<'MSG'+Add the host's video and render group ids to the container (NUMERIC: the+names do not exist inside the image):+ --group-add $(getent group video | cut -d: -f3) --group-add $(getent group render | cut -d: -f3)+bash docker/run.sh --rocm does this for you.+MSG+ exit 1+fi++# --- Check 2: what rocm-smi sees (advisory) --------------------------------+# rocm-smi does not list every APU (measured on gfx1151: no GPU[..] line inside+# the container), so it cannot be the gate; check 3 asks torch itself.+if ! command -v rocm-smi >/dev/null 2>&1; then+ warn "rocm-smi not found inside the container; skipping its listing."+elif ! rocm-smi --showid 2>/dev/null | grep -q 'GPU\['; then+ warn "rocm-smi lists no GPU from inside the container. That is normal for some APUs;"+ warn "if the torch check below fails too, the usual causes are a missing --device /dev/dri,"+ warn "the host's video/render group ids not passed with --group-add (run.sh --rocm does"+ warn "both), or a host amdgpu driver older than the ROCm in this image (rocm-smi --version)."+else+ rocm-smi --showid 2>/dev/null | grep 'GPU\[' | head -4 >&2+fi++# --- Check 3: a HIP torch that can see the device ---------------------------+# ROCm maps the CUDA Python API, so torch.cuda.is_available() is the test;+# torch.version.hip first, so a CUDA or CPU torch is named, not the host driver.+IMAGE_ROCM="$IMAGE_ROCM" python - >&2 <<'PY' || exit 1+import os+import sys++import torch++hip_ver = getattr(torch.version, "hip", None)+print(f"torch {torch.__version__} HIP={hip_ver}")+if hip_ver is None:+ print("ERROR: this torch is not a ROCm build (torch.version.hip is None), so no")+ print("AMD GPU can be used. The image is broken: re-pull unsloth/unsloth-rocm, or")+ print("rebuild it with bash docker/build.sh --rocm.")+ sys.exit(1)++if torch.cuda.is_available():+ sys.exit(0)+image_rocm = os.environ.get("IMAGE_ROCM") or ".".join(hip_ver.split(".")[:2])+print("ERROR: torch is a ROCm build but torch.cuda.is_available() is False: HIP could")+print("not open the device the container was given.")+print()+print(f"This image was built against ROCm {image_rocm} (HIP {hip_ver}). The host's")+print("amdgpu driver has to be at least as new. Check the host (NOT the container):")+print(" rocm-smi --version or cat /opt/rocm/.info/version or dkms status")+print()+print("If the host is older, upgrade its driver, or rebuild with the matching base:")+print(" ROCM_VERSION=<host version> TORCH_INDEX_URL=https://download.pytorch.org/whl/rocm<X.Y> \\")+print(" bash docker/build.sh --rocm")+print("If HSA_OVERRIDE_GFX_VERSION is set, a wrong value also produces this.")+sys.exit(1)+PY++# --- Check 4: the card's gfx arch against this image's wheels ---------------+# gcnArchName carries the gfx code (e.g. "gfx1100:sramecc+"). Not a gate (ROCm+# often runs unlisted arches), but where the user learns which build to use.+IMAGE_ROCM="$IMAGE_ROCM" IMAGE_GFX="$IMAGE_GFX" python - >&2 <<'PY' || exit 1+import os+import sys++import torch++image_gfx = os.environ.get("IMAGE_GFX", "")+image_rocm = os.environ.get("IMAGE_ROCM") or ".".join(torch.version.hip.split(".")[:2])+++def rocm_tuple(v):+ try:+ return tuple(int(x) for x in v.split(".")[:2])+ except ValueError:+ return (0, 0)+++here = rocm_tuple(image_rocm)++# gfx -> (family, note). Families only: the marketing-name tables live in+# install.sh and studio/, and are kept in parity by their own test.+STRIX = {"gfx1150", "gfx1151", "gfx1152"}+RDNA4 = {"gfx1200", "gfx1201"}+FAMILY = {+ "gfx906": "GCN 5.1 / Vega 20",+ "gfx908": "CDNA 1",+ "gfx90a": "CDNA 2",+ "gfx940": "CDNA 3",+ "gfx941": "CDNA 3",+ "gfx942": "CDNA 3",+ "gfx1030": "RDNA 2",+ "gfx1031": "RDNA 2",+ "gfx1100": "RDNA 3",+ "gfx1101": "RDNA 3",+ "gfx1102": "RDNA 3",+ "gfx1150": "RDNA 3.5 APU",+ "gfx1151": "RDNA 3.5 APU",+ "gfx1152": "RDNA 3.5 APU",+ "gfx1200": "RDNA 4",+ "gfx1201": "RDNA 4",+}+++def kfd_physical_archs():+ """gfx arches the KERNEL sees, from KFD topology sysfs. amdkfd writes+ gfx_target_version itself, so HSA_OVERRIDE_GFX_VERSION (a ROCr userland+ spoof, which run.sh forwards) cannot hide the silicon here. Encoding is+ major*10000 + minor*100 + stepping: 100303 is gfx1033, 110501 is gfx1151.+ Same reader as install.sh's _kfd_gfx_targets; empty when sysfs is not there."""+ out = []+ # UNSLOTH_KFD_TOPOLOGY: the regression tests stage a topology; unset in normal use+ root = os.environ.get("UNSLOTH_KFD_TOPOLOGY") or "/sys/class/kfd/kfd/topology/nodes"+ if not os.path.isdir(root):+ return out+ for node in sorted(os.listdir(root)):+ try:+ with open(os.path.join(root, node, "properties"), encoding = "utf-8") as fh:+ props = dict(ln.split(None, 1) for ln in fh if len(ln.split(None, 1)) == 2)+ except OSError:+ continue+ gtv = int(props.get("gfx_target_version", "0").strip() or 0)+ if props.get("vendor_id", "").strip() != "4098" or gtv <= 0:+ continue+ maj, mn, step = gtv // 10000 % 100, gtv // 100 % 100, gtv % 100+ if maj <= 0 or mn > 9 or step > 15:+ continue+ out.append(f"gfx{maj}{mn}{step:x}")+ return out+++physical = kfd_physical_archs()+if physical:+ print(f"KFD reports: {' '.join(physical)}")+if "gfx1033" in physical and os.environ.get("HSA_OVERRIDE_GFX_VERSION"):+ print("ERROR: the kernel reports a gfx1033 (Van Gogh, Steam Deck) and HSA_OVERRIDE_GFX_VERSION is")+ print(f" set ({os.environ['HSA_OVERRIDE_GFX_VERSION']}), which makes ROCm present it as another arch.")+ print(" gfx1033 computes incorrect results under ROCm whatever it is called (training")+ print(" diverges to NaN, studio/ROCM_RDNA2_APU.md), so this image refuses to train on it.")+ print(" UNSLOTH_SKIP_GPU_CHECK=1 bypasses this check; the results stay wrong.")+ sys.exit(1)++for i in range(torch.cuda.device_count()):+ props = torch.cuda.get_device_properties(i)+ arch = getattr(props, "gcnArchName", "").split(":")[0] # strip e.g. :sramecc++ print(f"GPU {i}: {torch.cuda.get_device_name(i)} arch={arch} bf16={torch.cuda.is_bf16_supported()}")+ if not arch:+ continue+ fam = FAMILY.get(arch)+ if arch == "gfx1033":+ # Van Gogh (Steam Deck): forward math looks fine but training diverges to+ # NaN and fails gradcheck (studio/ROCM_RDNA2_APU.md); install.sh routes it+ # to CPU torch, a HIP-only image can only refuse. Spoofing gfx1030 hides+ # the silicon from this check, not the arithmetic.+ print(f"ERROR: {arch} (Van Gogh, Steam Deck) computes incorrect results under ROCm:")+ print(" training diverges to NaN even though forward passes look valid, so this")+ print(" image refuses to train on it. Use the CPU image path (unsloth/unsloth")+ print(" with UNSLOTH_ALLOW_CPU=1) or llama.cpp over Vulkan for inference.")+ print(" UNSLOTH_SKIP_GPU_CHECK=1 bypasses this check; the results stay wrong.")+ sys.exit(1)+ if image_gfx:+ if arch == image_gfx or (arch in RDNA4 and image_gfx in RDNA4):+ print(f" -> {fam}: this image was built for {image_gfx}")+ if image_gfx == "gfx906":+ print(" (no bitsandbytes: no prebuilt gfx906 kernels, so load_in_4bit is unavailable)")+ elif image_gfx == "gfx906":+ print(f" NOTE: this image was built for gfx906 (ROCm 6.3, no bitsandbytes), not {arch}.")+ print(" Use the generic image: unsloth/unsloth-rocm:latest (bash docker/build.sh --rocm).")+ elif arch in STRIX or arch in RDNA4:+ print(f" NOTE: this image carries per-arch wheels for {image_gfx}, not {arch}. Rebuild:")+ print(f" ROCM_GFX={arch} bash docker/build.sh --rocm")+ else:+ print(f" NOTE: this image carries per-arch wheels for {image_gfx}, not {arch}, which has")+ print(" no per-arch index. Use the generic image: unsloth/unsloth-rocm:latest")+ print(" (bash docker/build.sh --rocm).")+ elif arch == "gfx906":+ if here >= (6, 4):+ print(f" NOTE: {arch} ({fam}) has no kernels in ROCm {image_rocm}: AMD dropped it after 6.3,")+ print(" so rocBLAS will fail on the first matmul. Rebuild on the last ROCm that carries it")+ print(" (ROCM_GFX=gfx906 leaves out bitsandbytes, which has no gfx906 kernels):")+ print(" ROCM_GFX=gfx906 ROCM_VERSION=6.3.4 TORCH_INDEX_URL=https://download.pytorch.org/whl/rocm6.3 \\")+ print(" bash docker/build.sh --rocm")+ else:+ print(f" -> {fam} (no prebuilt bitsandbytes kernels for gfx906: 4-bit needs a source build)")+ elif arch in STRIX or arch in RDNA4:+ print(f" NOTE: {arch} ({fam}) runs best on AMD's per-arch wheels, which carry Strix/RDNA4")+ print(" fixes the generic rocm index lacks. Build that image with:")+ print(f" ROCM_GFX={arch} bash docker/build.sh --rocm")+ print(" This generic image may still work; if training crashes, that is the fix.")+ elif fam:+ print(f" -> {fam}")+ else:+ print(f" NOTE: {arch} is not in the list of arches these wheels are built for.")+ print(" Training may still work if ROCm can JIT-compile for it. If not, set")+ print(" HSA_OVERRIDE_GFX_VERSION to the nearest built arch (RDNA2 cards other")+ print(" than gfx1030: 10.3.0; RDNA3 other than gfx1100: 11.0.0).")++sys.exit(0)+PY++exec "$@"diff --git a/docker/run.sh b/docker/run.shindex 3489419e890..08097ce9d45 100755--- a/docker/run.sh+++ b/docker/run.sh@@ -22,6 +22,10 @@# UNSLOTH_GPUS=none UNSLOTH_ALLOW_CPU=1 \# UNSLOTH_PORTS="-p 8000:8000 -p 8888:8888" bash docker/run.sh#+# AMD hosts: a leading --rocm (or UNSLOTH_ROCM=1) runs the ROCm image and passes+# the AMD device nodes instead of --gpus, which is NVIDIA-only.+# bash docker/run.sh --rocm python /workspace/smoke_test_rocm.py+## Overridable env:# UNSLOTH_IMAGE=unsloth/unsloth:latest image and tag to pull/run# UNSLOTH_GPUS=all "all" | "0" | "0,1" | "none"@@ -33,8 +37,68 @@# UNSLOTH_STUDIO_VOLUME=unsloth-studio named volume for Studio's data (accounts,# chats, outputs) at /opt/unsloth-studio;# set it empty to run without one+# --rocm only:+# UNSLOTH_ROCM=1 same as a leading --rocm+# HSA_OVERRIDE_GFX_VERSION force a gfx target (e.g. 10.3.0)+# UNSLOTH_ROCM_GFX_ARCH gfx arch override (e.g. gfx1151)set -euo pipefail+# --rocm is ours only as the FIRST argument; everything after it is the+# container's command line, so a command's own --rocm is left alone.+ROCM=0+[[ "${UNSLOTH_ROCM:-}" == "1" ]] && ROCM=1+if [[ $# -gt 0 && "$1" == "--rocm" ]]; then+ ROCM=1+ shift+fi++# UNSLOTH_DEV_ROOT prefixes the /dev probes (DESTDIR idiom). It exists so the+# regression tests can stage a fake device tree; leave it unset in normal use.+DEV_ROOT="${UNSLOTH_DEV_ROOT:-}"++# --group-add needs NUMERIC gids: a name is resolved INSIDE the container, where+# the host's video/render groups do not exist.+amd_device_flags() {+ printf '%s\n' --device /dev/kfd+ # docker refuses to start at all over a missing host device, so name /dev/dri+ # only when it exists and let the entrypoint explain the incomplete driver.+ if [[ -e "$DEV_ROOT/dev/dri" ]]; then+ printf '%s\n' --device /dev/dri+ else+ printf "\033[1;33mWARN:\033[0m /dev/kfd is present but /dev/dri is not; passing the compute node alone.\n" >&2+ fi+ command -v getent >/dev/null 2>&1 || return 0+ local _grp _gid+ for _grp in video render; do+ # getent exits nonzero for an unknown group (minimal hosts have no+ # render group), which under pipefail + set -e would kill the assignment.+ _gid="$(getent group "$_grp" | cut -d: -f3)" || _gid=""+ [[ -n "$_gid" ]] && printf '%s\n' --group-add "$_gid"+ done+ return 0+}+# Into GPU_FLAG, one flag per line, with a read loop: macOS ships bash 3.2.+collect_amd_device_flags() {+ local _flag+ GPU_FLAG=()+ while IFS= read -r _flag; do+ GPU_FLAG+=("$_flag")+ done < <(amd_device_flags)+}++if [[ $ROCM -eq 1 ]]; then+ IMAGE="${UNSLOTH_IMAGE:-unsloth/unsloth-rocm:latest}"+ GPUS=none+ if [[ -e "$DEV_ROOT/dev/kfd" ]]; then+ collect_amd_device_flags+ else+ GPU_FLAG=()+ printf "\033[1;33mWARN:\033[0m /dev/kfd is not present, so no AMD GPU can be passed through.\n" >&2+ printf " On Linux install the amdgpu driver and add yourself to the video/render\n" >&2+ printf " groups. Docker Desktop on Windows and macOS has no /dev/kfd at all: the\n" >&2+ printf " ROCm image cannot reach a GPU there, whatever the host card is.\n\n" >&2+ fi+elseIMAGE="${UNSLOTH_IMAGE:-unsloth/unsloth:latest}"GPUS="${UNSLOTH_GPUS:-all}"# Translate index selectors to Docker's `device=` form: a bare integer is a COUNT,@@ -49,6 +113,7 @@ case "$GPUS" in*[!0-9]*) GPU_FLAG=(--gpus "\"device=${GPUS}\"") ;; # comma list / UUID*) GPU_FLAG=(--gpus "\"device=${GPUS}\"") ;; # bare integer indexesac+fiHF_CACHE="${HF_HOME:-$HOME/.cache/huggingface}"TRITON_CACHE="${TRITON_CACHE_DIR:-$HOME/.cache/unsloth-triton}"WORK_DIR="${UNSLOTH_WORKDIR:-$PWD}"@@ -68,9 +133,6 @@ mkdir -p "$HF_CACHE" "$TRITON_CACHE"# vendor found" and exit 125, so entrypoint.sh never runs and its diagnostics never# print. Drop the flag instead and let the container start, so the user gets the# entrypoint's explanation (or, on :latest, Studio in CPU mode).-# UNSLOTH_DEV_ROOT prefixes the /dev probes below (DESTDIR idiom). It exists so the-# regression tests can stage a fake device tree; leave it unset in normal use.-DEV_ROOT="${UNSLOTH_DEV_ROOT:-}"host_has_nvidia() {local listing[[ -e "$DEV_ROOT/dev/nvidiactl" ]] && return 0@@ -80,28 +142,16 @@ host_has_nvidia() {grep -q '^GPU' <<< "${listing}"}-if [[ ${#GPU_FLAG[@]} -gt 0 ]] && ! host_has_nvidia; then+if [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && ! host_has_nvidia; thenprintf "\033[1;33mWARN:\033[0m no NVIDIA GPU on this host; dropping --gpus %s.\n" "$GPUS" >&2printf " 'docker run --gpus' would fail at the daemon (exit 125) before the\n" >&2printf " container starts. Set UNSLOTH_GPUS=none to silence this.\n" >&2GPU_FLAG=()# AMD host: hand llama.cpp/GGUF the render nodes. This is NOT torch acceleration# -- torch in the image is cu128 and torch.cuda.is_available() stays False here.- # --group-add needs NUMERIC gids: a name is resolved INSIDE the container, where- # the host's video/render groups do not exist.+ # Run --rocm instead for a torch that can use the card.if [[ -e "$DEV_ROOT/dev/kfd" && -d "$DEV_ROOT/dev/dri" ]]; then- GPU_FLAG=(--device /dev/kfd --device /dev/dri)- # A missing group is not fatal: getent exits nonzero when the name is not in- # NSS, and under `set -o pipefail` that would take the whole assignment down- # with `set -e` before docker run is ever reached. Trailing `|| _gid=` puts the- # assignment in an OR-list, which suppresses that and leaves the gid empty.- # Minimal hosts really do ship without a render group.- if command -v getent >/dev/null 2>&1; then- for _grp in video render; do- _gid="$(getent group "$_grp" | cut -d: -f3)" || _gid=""- [[ -n "$_gid" ]] && GPU_FLAG+=(--group-add "$_gid")- done- fi+ collect_amd_device_flagsprintf " AMD devices found: passing /dev/kfd and /dev/dri through.\n" >&2# published images only (untagged is :latest); a custom image may carry a HIP or Vulkan buildif [[ "$IMAGE" == unsloth/unsloth || "$IMAGE" == unsloth/unsloth:* ]]; then@@ -122,14 +172,16 @@ fi# UNSLOTH_INSTALL_TOOLKIT=1 says yes without a prompt, =0 never asks; with neither and no terminal, print the one-liner and continue.DOCKER_INFO=""DOCKER_ERR=""-if [[ ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia; then+# A mixed NVIDIA + AMD host under --rocm is not missing anything: it runs the ROCm+# image through the AMD device nodes, so the toolkit is irrelevant there.+if [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia; then# stderr folded in: on failure the captured text IS the daemon's errorDOCKER_INFO="$(docker info 2>&1)" || { DOCKER_ERR="$DOCKER_INFO"; DOCKER_INFO=""; }fiif [[ -n "$DOCKER_ERR" ]]; thenprintf "\033[1;33mWARN:\033[0m 'docker info' failed, so the GPU runtime could not be checked:\n %s\n" "${DOCKER_ERR##*$'\n'}" >&2printf " Start the Docker daemon, or add yourself to the docker group (newgrp docker).\n\n" >&2-elif [[ ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia \+elif [[ $ROCM -eq 0 && ${#GPU_FLAG[@]} -gt 0 ]] && host_has_nvidia \&& ! grep -qi 'Runtimes:.*nvidia' <<<"$DOCKER_INFO"; thenINSTALLER="$(dirname "${BASH_SOURCE[0]}")/install_nvidia_toolkit.sh"printf "\033[1;33mWARN:\033[0m 'docker info' does not list 'nvidia' as a runtime: the NVIDIA\n" >&2@@ -158,6 +210,9 @@ declare -a ENV_FORWARD=(-e HF_HUB_ENABLE_HF_TRANSFER=1)[[ -n "${WANDB_API_KEY:-}" ]] && ENV_FORWARD+=(-e WANDB_API_KEY)[[ -n "${UNSLOTH_LICENSE:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_LICENSE)[[ -n "${UNSLOTH_ALLOW_CPU:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_ALLOW_CPU)+# gfx overrides for cards the installed ROCm build has no kernels for+[[ -n "${HSA_OVERRIDE_GFX_VERSION:-}" ]] && ENV_FORWARD+=(-e HSA_OVERRIDE_GFX_VERSION)+[[ -n "${UNSLOTH_ROCM_GFX_ARCH:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_ROCM_GFX_ARCH)# read by studio_launch.sh; without these it uses a random password and no sshd[[ -n "${JUPYTER_PASSWORD:-}" ]] && ENV_FORWARD+=(-e JUPYTER_PASSWORD)[[ -n "${UNSLOTH_STUDIO_PASSWORD:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_PASSWORD)diff --git a/docker/smoke_test_rocm.py b/docker/smoke_test_rocm.pynew file mode 100644index 00000000000..045dcc8c649--- /dev/null+++ b/docker/smoke_test_rocm.py@@ -0,0 +1,231 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-Present the Unsloth team. See /studio/LICENSE.AGPL-3.0++"""+Smoke test for the Unsloth ROCm image (AMD GPU build).++What this checks (in order, fail-fast):+ 1. torch is a ROCm build (torch.version.hip is not None).+ 2. The runtime device is visible and its gfx arch is supported (RDNA2+).+ 3. bitsandbytes / triton import without ImportError.+ 4. unsloth imports and exposes FastLanguageModel.+ 5. A 5-step LoRA train on a tiny model actually runs forward + backward.++Run inside the container:+ bash docker/run.sh --rocm python /workspace/smoke_test_rocm.py++Skip step 5 (faster, no model download):+ ... python /workspace/smoke_test_rocm.py --skip-train+"""++from __future__ import annotations++import argparse+import sys+++def banner(title: str) -> None:+ print(f"\n=== {title} ===", flush = True)+++def check_torch() -> None:+ banner("torch ROCm build")+ import torch++ # torch.version.hip is the canonical indicator of a ROCm wheel.+ # It is None for CUDA builds.+ if torch.version.hip is None:+ sys.exit(+ f"FAIL: this is not a ROCm torch build ({torch.__version__}). "+ "Re-pull the unsloth-rocm image."+ )+ print(f"torch {torch.__version__}")+ print(f"HIP {torch.version.hip}")++ assert torch.cuda.is_available(), (+ "torch.cuda.is_available() is False: was the container started with "+ "bash docker/run.sh --rocm (or --device /dev/kfd --device /dev/dri and the "+ "video/render group ids)?"+ )+ n = torch.cuda.device_count()+ print(f"GPU count {n}")+ for i in range(n):+ name = torch.cuda.get_device_name(i)+ props = torch.cuda.get_device_properties(i)+ # PyTorch ROCm surfaces the gfx code in gcnArchName (e.g.+ # "gfx1100:sramecc+"); strip the feature suffix for readability.+ arch = getattr(props, "gcnArchName", "").split(":")[0]+ bf16 = torch.cuda.is_bf16_supported()+ print(f"device {i} {name} arch={arch} bf16={bf16}")+ print()+ # ROCm does not expose a reliable sm_X.Y compute capability the way NVIDIA+ # does -- the values from get_device_properties() vary by ROCm version and+ # don't map cleanly to gfx codes. Which arches the wheels carry is decided+ # by the ROCm version and index the image was built with (Dockerfile.rocm);+ # the entrypoint already printed the arch note for this card.+ # A device the runtime lists but cannot run a kernel on shows up here, not+ # in device_count().+ x = torch.ones(64, 64, device = "cuda", dtype = torch.float16)+ y = (x @ x).float().sum().item()+ assert y == 64 * 64 * 64, f"FAIL: fp16 matmul on the GPU returned {y}, expected {64 * 64 * 64}"+ print("fp16 matmul OK")+++def check_imports() -> None:+ banner("dep imports")+ # unsloth must be imported before transformers/trl/peft so its+ # monkey-patches land, and before unsloth_zoo so it sees+ # UNSLOTH_IS_PRESENT. Import order matches the CUDA smoke test.+ import unsloth++ print(f"unsloth {unsloth.__version__}")+ import unsloth_zoo++ print(f"unsloth_zoo {unsloth_zoo.__version__}")++ # not optional: unsloth's fused kernels are triton, and the image's build+ # check pinned it to the ROCm build torch links against+ import triton+ import triton.backends++ print(f"triton {triton.__version__} backends={sorted(triton.backends.backends)}")+ assert "amd" in triton.backends.backends, "FAIL: triton has no amd backend"++ if _bnb_expected():+ import bitsandbytes as bnb+ print(f"bnb {bnb.__version__}")+ else:+ print("bnb not part of a gfx906 build (no prebuilt kernels)")++ import transformers++ print(f"transformers {transformers.__version__}")++ import trl++ print(f"trl {trl.__version__}")++ import peft++ print(f"peft {peft.__version__}")++ # xformers has no ROCm wheel; its absence is expected.+ try:+ import xformers+ print(f"xformers {xformers.__version__}")+ except ImportError:+ print("xformers (not installed -- expected; ROCm uses SDPA fallback)")+++def check_unsloth_import() -> None:+ banner("unsloth FastLanguageModel reachable")+ import unsloth+ from unsloth import FastLanguageModel++ print(f"unsloth {unsloth.__version__}")+ print(f"FastLanguageModel {FastLanguageModel}")+++def _bnb_expected() -> bool:+ """A gfx906 build (ROCM_GFX=gfx906 in the build record) ships no bitsandbytes."""+ try:+ record = open("/etc/unsloth-rocm-build", encoding = "utf-8").read()+ except OSError:+ return True+ return "ROCM_GFX=gfx906\n" not in record+++def check_tiny_train() -> None:+ banner("tiny LoRA train (5 steps)")+ import unsloth # noqa: F401+ from unsloth import FastLanguageModel+ import torch++ four_bit = _bnb_expected()+ model_name = "unsloth/Llama-3.2-1B-Instruct" + ("-bnb-4bit" if four_bit else "")+ print(f"loading {model_name} (load_in_4bit={four_bit})")+ model, tokenizer = FastLanguageModel.from_pretrained(+ model_name = model_name,+ max_seq_length = 512,+ dtype = None,+ load_in_4bit = four_bit,+ )+ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"],+ lora_dropout = 0.0,+ bias = "none",+ use_gradient_checkpointing = "unsloth",+ random_state = 0,+ )++ prompts = [+ "Q: What is the capital of France?\nA:",+ "Q: 2 + 2 = ?\nA:",+ "Q: Name a primary color.\nA:",+ "Q: Hello, who are you?\nA:",+ ] * 2+ enc = tokenizer(prompts, return_tensors = "pt", padding = True, truncation = True, max_length = 64)+ enc = {k: v.cuda() for k, v in enc.items()}+ labels = enc["input_ids"].clone()+ # the padding tokens are not a training target+ labels[enc["attention_mask"] == 0] = -100++ trainable = [p for p in model.parameters() if p.requires_grad]+ assert trainable, "FAIL: get_peft_model left no trainable parameters"+ before = [p.detach().clone() for p in trainable]++ model.train()+ optim = torch.optim.AdamW(trainable, lr = 1e-3)+ losses = []+ for step in range(5):+ out = model(**enc, labels = labels)+ loss = out.loss+ # a NaN here is what the bitsandbytes 4-bit ROCm bug looked like (bnb <= 0.49)+ assert torch.isfinite(loss), f"FAIL: non-finite loss at step {step}: {loss.item()}"+ loss.backward()+ grads = [p.grad for p in trainable if p.grad is not None]+ assert grads, f"FAIL: no gradient reached the LoRA weights at step {step}"+ assert all(+ torch.isfinite(g).all() for g in grads+ ), f"FAIL: non-finite gradient at step {step}"+ optim.step()+ optim.zero_grad(set_to_none = True)+ losses.append(loss.item())+ print(f"step {step} loss={losses[-1]:.4f}", flush = True)++ changed = sum(int(not torch.equal(a, b.detach())) for a, b in zip(before, trainable))+ assert changed, "FAIL: the optimizer steps left every LoRA weight unchanged"+ # the same batch five times over at lr 1e-3: the loss has to come down, or the+ # forward/backward is not computing what it claims+ assert (+ losses[-1] < losses[0]+ ), f"FAIL: loss did not decrease over 5 steps on one batch: {losses}"+ print(+ f"OK: 5 LoRA steps completed, loss {losses[0]:.4f} -> {losses[-1]:.4f}, {changed}/{len(trainable)} LoRA tensors updated"+ )+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument(+ "--skip-train",+ action = "store_true",+ help = "Skip the tiny LoRA training step (no HF download).",+ )+ args = ap.parse_args()++ check_torch()+ check_imports()+ check_unsloth_import()+ if not args.skip_train:+ check_tiny_train()++ banner("all checks passed")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/docker/test_locally-rocm.sh b/docker/test_locally-rocm.shnew file mode 100644index 00000000000..3e3aa07dda8--- /dev/null+++ b/docker/test_locally-rocm.sh@@ -0,0 +1,272 @@+#!/usr/bin/env bash+# End-to-end Docker validation for the unsloth-rocm image.+#+# Runs three blocks:+# 1. Host pre-flight (docker, rocm-smi, /dev/kfd accessible)+# 2. Build the image (no GPU required at build time)+# 3a. Smoke test: 5-step LoRA on Llama-3.2-1B (~1-2 min)+# 3b. Real workload: gpt-oss-20B fine-tuning notebook with max_steps=10+# (~10 min, needs ~30GB free for the model cache)+#+# Usage:+# bash docker/test_locally-rocm.sh # all blocks+# bash docker/test_locally-rocm.sh --skip-notebook # blocks 1-3a only (fast)+# bash docker/test_locally-rocm.sh --skip-build # assume $TAG already built+# TAG=my-image:latest bash docker/test_locally-rocm.sh # name:tag, built via build.sh+# HF_TOKEN=hf_xxx bash docker/test_locally-rocm.sh+#+# Strix APUs / RDNA4 cards (AMD per-arch wheels, see Dockerfile.rocm):+# ROCM_GFX=gfx1151 TAG=unsloth-rocm-strix:test bash docker/test_locally-rocm.sh+#+# All output is teed to $LOG_DIR (default /tmp/unsloth-rocm-test/).+set -uo pipefail++TAG="${TAG:-unsloth-rocm:test}"+LOG_DIR="${LOG_DIR:-/tmp/unsloth-rocm-test}"+SKIP_BUILD=0+SKIP_NOTEBOOK=0+ROCM_VERSION="${ROCM_VERSION:-7.2.4}"+TORCH_INDEX_URL="${TORCH_INDEX_URL:-https://download.pytorch.org/whl/rocm${ROCM_VERSION%.*}}"+ROCM_GFX="${ROCM_GFX:-}"++while [[ $# -gt 0 ]]; do+ case "$1" in+ --skip-build) SKIP_BUILD=1; shift ;;+ --skip-notebook) SKIP_NOTEBOOK=1; shift ;;+ --tag) TAG="$2"; shift 2 ;;+ --log-dir) LOG_DIR="$2"; shift 2 ;;+ --help|-h) sed -n '2,18p' "$0"; exit 0 ;;+ *) echo "Unknown flag: $1" >&2; exit 2 ;;+ esac+done++mkdir -p "$LOG_DIR"++GREEN='\033[1;32m'; RED='\033[1;31m'; YELLOW='\033[1;33m'; BLUE='\033[1;34m'; NC='\033[0m'+banner() { printf "\n${BLUE}==== %s ====${NC}\n" "$*"; }+ok() { printf "${GREEN}OK${NC} %s\n" "$*"; }+warn() { printf "${YELLOW}WARN${NC} %s\n" "$*"; }+err() { printf "${RED}ERROR${NC} %s\n" "$*" >&2; }+fail() { err "$*"; exit 1; }++# AMD GPU device flags used for all `docker run` invocations. --group-add needs+# NUMERIC gids: a name is resolved inside the container, where the host's+# video/render groups do not exist.+AMD_DEVICE_FLAGS=(--device /dev/kfd --device /dev/dri)+for _grp in video render; do+ _gid="$(getent group "$_grp" 2>/dev/null | cut -d: -f3)" || _gid=""+ [[ -n "$_gid" ]] && AMD_DEVICE_FLAGS+=(--group-add "$_gid")+done++# ============================================================================+# Block 1: pre-flight+# ============================================================================+banner "Block 1: host pre-flight"++command -v docker >/dev/null 2>&1 || fail "docker not found on PATH"+echo " docker: $(docker --version)"++DOCKER_INFO_OUT=$(docker info 2>&1)+DOCKER_INFO_RC=$?+if [[ $DOCKER_INFO_RC -ne 0 ]]; then+ err "Cannot talk to the docker daemon as user '$USER'."+ cat >&2 <<MSG++docker info exited $DOCKER_INFO_RC. The most common cause is that your user+is not in the 'docker' group. Fix:++ sudo usermod -aG docker \$USER+ newgrp docker+ docker info | head -3++MSG+ fail "docker daemon unreachable"+fi+echo " daemon: reachable as '$USER'"++if [[ -e /dev/kfd ]]; then+ echo " /dev/kfd: present"+ if command -v rocm-smi >/dev/null 2>&1; then+ echo " host gpu: $(rocm-smi --showproductname 2>/dev/null | grep -m1 'GPU\[' | sed 's/.*: //' || echo '(rocm-smi present)')"+ else+ warn "rocm-smi not on the host PATH (ROCm may still work inside the container)"+ fi+else+ warn "/dev/kfd not found -- ROCm drivers may not be installed or user lacks access"+ warn "Install ROCm: https://rocm.docs.amd.com/en/latest/deploy/linux/quick_start.html"+ warn "Then: sudo usermod -aG video,render \$USER (log out and back in)"+fi++# Check the user is in the video group -- required for /dev/dri access.+if id -nG 2>/dev/null | grep -qw video; then+ echo " video group: ok (current user is a member)"+else+ warn "current user is not in the 'video' group"+ warn "Fix: sudo usermod -aG video,render \$USER (log out/in after)"+fi++ok "pre-flight done"++# ============================================================================+# Block 2: build+# ============================================================================+if [[ $SKIP_BUILD -eq 1 ]]; then+ warn "skipping build (--skip-build); expecting $TAG to exist"+else+ banner "Block 2: build $TAG"++ if [[ -x "build.sh" && -f "Dockerfile.rocm" ]]; then+ BUILD_SH="$PWD/build.sh"+ elif [[ -x "docker/build.sh" ]]; then+ BUILD_SH="$PWD/docker/build.sh"+ else+ fail "Cannot find docker/build.sh. Run from the repo root or docker/ directory."+ fi+ echo " ROCm version: $ROCM_VERSION"+ echo " torch index: ${ROCM_GFX:+AMD per-arch wheels for $ROCM_GFX}${ROCM_GFX:-$TORCH_INDEX_URL}"++ BUILD_LOG="$LOG_DIR/build.log"+ echo " log: $BUILD_LOG"++ # Through build.sh, not a bare docker build: it freezes UNSLOTH_REF and+ # UNSLOTH_ZOO_REF to commits first, so a rerun after main moved cannot reuse+ # the install layer of an earlier build and validate stale code.+ IMAGE_NAME="${TAG%%:*}" TAG="${TAG#*:}" ROCM_VERSION="$ROCM_VERSION" \+ TORCH_INDEX_URL="$TORCH_INDEX_URL" ROCM_GFX="$ROCM_GFX" \+ bash "$BUILD_SH" --rocm 2>&1 | tee "$BUILD_LOG"+ rc=${PIPESTATUS[0]}+ if [[ $rc -ne 0 ]]; then+ fail "build exited $rc -- see $BUILD_LOG"+ fi++ # Sanity-check the build's own self-test ran and passed.+ if grep -q "FAIL: missing packages\|Expected a ROCm torch wheel" "$BUILD_LOG"; then+ fail "build-time sanity check failed -- see $BUILD_LOG"+ fi+ grep -E "OK: torch .* HIP|OK: all required packages" "$BUILD_LOG" || \+ warn "could not find 'OK:' lines in build log -- did the verification step run?"+ ok "built $TAG"+fi++# ============================================================================+# Block 3a: smoke test+# ============================================================================+banner "Block 3a: smoke test (5-step LoRA on Llama-3.2-1B)"+SMOKE_LOG="$LOG_DIR/smoke.log"+echo " log: $SMOKE_LOG"+docker run --rm \+ "${AMD_DEVICE_FLAGS[@]}" \+ "$TAG" python /workspace/smoke_test_rocm.py 2>&1 | tee "$SMOKE_LOG"+rc=${PIPESTATUS[0]}+if [[ $rc -ne 0 ]]; then+ fail "smoke test exited $rc -- see $SMOKE_LOG"+fi+if ! grep -q "all checks passed" "$SMOKE_LOG"; then+ fail "smoke test did not print 'all checks passed' -- see $SMOKE_LOG"+fi+ok "smoke test passed"++# ============================================================================+# Block 3b: gpt-oss-20B fine-tuning notebook+# ============================================================================+if [[ $SKIP_NOTEBOOK -eq 1 ]]; then+ warn "skipping gpt-oss-20B notebook (--skip-notebook)"+else+ banner "Block 3b: gpt-oss-20B fine-tuning notebook (10 LoRA steps)"+ GPT_LOG="$LOG_DIR/gpt_oss.log"+ HOST_RUN_DIR="$LOG_DIR/host"+ mkdir -p "$HOST_RUN_DIR"+ echo " log: $GPT_LOG"+ echo " host dir: $HOST_RUN_DIR"++ cat > "$HOST_RUN_DIR/run_notebook.sh" <<'INNER'+#!/bin/bash+set -e+cd /workspace/host++echo "=== fetch + convert notebook ==="+pip install -q nbformat+NB_REPO_REF="${NB_REPO_REF:-efe20c97a5bba3088b25fe068a4b1c98c0cf3a3a}"+curl -fsSL "https://raw.githubusercontent.com/unslothai/notebooks/${NB_REPO_REF}/nb/gpt-oss-(20B)-Fine-tuning.ipynb" -o nb.ipynb+test -s nb.ipynb || { echo "FAIL: nb.ipynb was not downloaded"; exit 1; }+python - <<'PY'+import nbformat, re+nb = nbformat.read('nb.ipynb', as_version=4)+out, skipped = [], 0+INSTALL_MARKERS = (+ "pip install", "uv pip install", "apt-get install",+ "_original_packages", "COLAB_", "importlib.util.find_spec",+)+for c in nb.cells:+ if c.cell_type != "code":+ continue+ src = c.source or ""+ if any(m in src for m in INSTALL_MARKERS):+ skipped += 1+ first = next((ln for ln in src.splitlines() if ln.strip()), "")[:80]+ out.append(f"# (skipped install/setup cell: {first!r})")+ out.append("")+ continue+ for line in src.splitlines():+ stripped = line.lstrip()+ if stripped.startswith(("!", "%")):+ out.append(f"# (jupyter magic stripped) {line}")+ else:+ out.append(line)+ out.append("")+with open("nb.py", "w") as f:+ f.write("\n".join(out) + "\n")+print(f" converted nb.py: {sum(1 for _ in open('nb.py'))} lines, {skipped} install cell(s) skipped")+PY+test -s nb.py || { echo "FAIL: nb.py was not produced"; exit 1; }+python -c "import ast; ast.parse(open('nb.py').read()); print(' nb.py is valid Python')"++echo+echo "=== patch nb.py: max_steps 30 -> 10 ==="+python - <<'PY'+import re+src = open('nb.py').read()+src = src.replace('max_steps = 30', 'max_steps = 10')+open('nb.py', 'w').write(src)+print(' patched. max_steps now:', re.search(r'max_steps = (\d+)', src).group(1))+PY++echo+echo "=== run gpt-oss-20B fine-tuning ==="+python -u nb.py+INNER+ chmod +x "$HOST_RUN_DIR/run_notebook.sh"++ HF_ARGS=()+ [[ -n "${HF_TOKEN:-}" ]] && HF_ARGS+=(-e HF_TOKEN)+ docker run --rm \+ "${AMD_DEVICE_FLAGS[@]}" \+ --ipc=host \+ --ulimit memlock=-1 \+ --ulimit stack=67108864 \+ -v "$HOST_RUN_DIR:/workspace/host" \+ -v "$HOME/.cache/huggingface:/workspace/.cache/huggingface" \+ "${HF_ARGS[@]}" \+ -e HF_HUB_ENABLE_HF_TRANSFER=1 \+ "$TAG" \+ bash /workspace/host/run_notebook.sh 2>&1 | tee "$GPT_LOG"+ rc=${PIPESTATUS[0]}+ if [[ $rc -ne 0 ]]; then+ fail "gpt-oss-20B notebook exited $rc -- see $GPT_LOG"+ fi+ ok "gpt-oss-20B notebook completed"+fi++# ============================================================================+# Summary+# ============================================================================+banner "summary"+echo " image: $TAG"+echo " log dir: $LOG_DIR"+echo+echo " to paste back for PR validation:"+[[ $SKIP_BUILD -eq 0 ]] && echo " tail -40 $LOG_DIR/build.log"+echo " cat $LOG_DIR/smoke.log"+[[ $SKIP_NOTEBOOK -eq 0 ]] && echo " tail -100 $LOG_DIR/gpt_oss.log"+echo+ok "all blocks completed"diff --git a/tests/python/test_docker_rocm.py b/tests/python/test_docker_rocm.pynew file mode 100644index 00000000000..af566145895--- /dev/null+++ b/tests/python/test_docker_rocm.py@@ -0,0 +1,682 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+"""The AMD ROCm image's host-side plumbing: `docker/run.sh --rocm`,+`docker/build.sh --rocm`, and the container entrypoint's refusal paths.++None of these need an AMD GPU. run.sh and build.sh are driven with a recording+`docker` stub and a staged /dev tree (the UNSLOTH_DEV_ROOT idiom); the+entrypoint is driven the same way with stub `rocm-smi` and `python` binaries,+so every message a user can hit before torch loads is checked here.+"""++import os+import shutil+import stat+import subprocess++import pytest++_HERE = os.path.dirname(os.path.abspath(__file__))+_REPO = os.path.dirname(os.path.dirname(_HERE))+_DOCKER = os.path.join(_REPO, "docker")+_RUN_SH = os.path.join(_DOCKER, "run.sh")+_BUILD_SH = os.path.join(_DOCKER, "build.sh")+_ENTRYPOINT = os.path.join(_DOCKER, "entrypoint-rocm.sh")+_DOCKERFILE = os.path.join(_DOCKER, "Dockerfile.rocm")+_SMOKE = os.path.join(_DOCKER, "smoke_test_rocm.py")+_WORKFLOW = os.path.join(_REPO, ".github", "workflows", "docker-publish-rocm.yml")++_posix_shell = pytest.mark.skipif(+ os.name != "posix" or shutil.which("bash") is None,+ reason = "POSIX shell required",+)+++def _stub(path, body):+ with open(path, "w", encoding = "utf-8") as f:+ f.write("#!/usr/bin/env bash\n" + body)+ os.chmod(path, os.stat(path).st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)+++# ── run.sh --rocm ────────────────────────────────────────────────────────────+++def _run_sh(+ tmp_path,+ args,+ *,+ kfd = True,+ dri = True,+ nvidia = False,+ groups = "both",+ extra_env = None,+):+ # a fresh sandbox per call: a test may drive run.sh twice+ tmp_path = tmp_path / f"run{len(os.listdir(tmp_path))}"+ tmp_path.mkdir()+ bindir = tmp_path / "bin"+ bindir.mkdir()+ argv_log = tmp_path / "argv"+ _stub(+ str(bindir / "docker"),+ 'if [ "$1" = "info" ]; then echo " Runtimes: io.containerd.runc.v2 runc"; exit 0; fi\n'+ 'printf "%s\\n" "$@" > ' + str(argv_log) + "\nexit 0\n",+ )+ if nvidia:+ _stub(str(bindir / "nvidia-smi"), 'echo "GPU 0: NVIDIA H100 (UUID: GPU-abc)"\n')+ else:+ _stub(str(bindir / "nvidia-smi"), "exit 1\n")+ known = {"both": ("44", "992"), "none": (None, None)}+ vid, ren = known[groups]+ _stub(+ str(bindir / "getent"),+ 'case "$2" in\n'+ + (f' video) echo "video:x:{vid}:"; exit 0 ;;\n' if vid else " video) exit 2 ;;\n")+ + (f' render) echo "render:x:{ren}:"; exit 0 ;;\n' if ren else " render) exit 2 ;;\n")+ + "esac\nexit 2\n",+ )+ dev_root = tmp_path / "root"+ (dev_root / "dev").mkdir(parents = True)+ if nvidia:+ (dev_root / "dev" / "nvidiactl").write_text("")+ if kfd:+ (dev_root / "dev" / "kfd").write_text("")+ if dri:+ (dev_root / "dev" / "dri").mkdir()+ env = dict(os.environ)+ env["PATH"] = str(bindir) + ":/usr/bin:/bin"+ env["UNSLOTH_DEV_ROOT"] = str(dev_root)+ env["HOME"] = str(tmp_path / "home")+ env["UNSLOTH_WORKDIR"] = str(tmp_path)+ for leak in (+ "HF_TOKEN",+ "WANDB_API_KEY",+ "UNSLOTH_GPUS",+ "UNSLOTH_ALLOW_CPU",+ "UNSLOTH_STUDIO_VOLUME",+ "UNSLOTH_IMAGE",+ "UNSLOTH_ROCM",+ "HSA_OVERRIDE_GFX_VERSION",+ "UNSLOTH_ROCM_GFX_ARCH",+ ):+ env.pop(leak, None)+ env.update(extra_env or {})+ proc = subprocess.run(+ [shutil.which("bash") or "/bin/bash", _RUN_SH, *args],+ env = env,+ capture_output = True,+ text = True,+ timeout = 120,+ )+ assert proc.returncode == 0, f"run.sh failed: {proc.stderr}"+ argv = argv_log.read_text().splitlines()+ return argv, proc.stderr+++def _image_and_cmd(argv):+ """The positional tail of `docker run`: image, then the container command."""+ # every option run.sh emits takes a value or is a known flag+ flags_with_value = {"--device", "--group-add", "--ulimit", "-v", "-e", "-p", "--gpus"}+ i = 0+ while i < len(argv):+ a = argv[i]+ if a in ("run", "--rm", "-it", "--ipc=host"):+ i += 1+ elif a in flags_with_value:+ i += 2+ elif a.startswith("-"):+ i += 1+ else:+ return argv[i], argv[i + 1 :]+ raise AssertionError(f"no image in {argv}")+++@_posix_shell+class TestRunShRocm:+ def test_rocm_passes_the_device_nodes_and_numeric_gids_not_gpus(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["--rocm", "true"])+ assert "--gpus" not in argv+ assert "/dev/kfd" in argv and "/dev/dri" in argv+ gids = [argv[i + 1] for i, a in enumerate(argv) if a == "--group-add"]+ assert gids == ["44", "992"], argv+ image, cmd = _image_and_cmd(argv)+ assert image == "unsloth/unsloth-rocm:latest"+ assert cmd == ["true"]++ def test_a_missing_dri_node_is_left_out_so_docker_still_starts(self, tmp_path):+ """docker rejects a --device path that does not exist on the host."""+ argv, err = _run_sh(tmp_path, ["--rocm", "true"], dri = False)+ assert "/dev/kfd" in argv and "/dev/dri" not in argv, argv+ assert "/dev/dri is not" in err, err++ def test_the_wrapper_option_is_only_taken_from_the_front(self, tmp_path):+ """A container command's own --rocm belongs to that command."""+ argv, _ = _run_sh(tmp_path, ["--rocm", "python", "train.py", "--rocm"])+ _, cmd = _image_and_cmd(argv)+ assert cmd == ["python", "train.py", "--rocm"], argv++ def test_a_later_rocm_is_not_the_wrapper_option(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["python", "train.py", "--rocm"], nvidia = True)+ assert "--gpus" in argv, argv+ image, cmd = _image_and_cmd(argv)+ assert image == "unsloth/unsloth:latest"+ assert cmd == ["python", "train.py", "--rocm"]++ def test_the_env_form_selects_rocm_too(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["true"], extra_env = {"UNSLOTH_ROCM": "1"})+ image, _ = _image_and_cmd(argv)+ assert image == "unsloth/unsloth-rocm:latest"+ assert "/dev/kfd" in argv++ def test_no_kfd_warns_and_starts_without_devices(self, tmp_path):+ """Docker Desktop has no /dev/kfd; the entrypoint then explains, so the+ container must still start rather than docker failing on a missing node."""+ argv, stderr = _run_sh(tmp_path, ["--rocm", "true"], kfd = False)+ assert "--device" not in argv and "--gpus" not in argv, argv+ assert "/dev/kfd is not present" in stderr and "Docker Desktop" in stderr, stderr++ def test_a_mixed_host_is_not_offered_the_nvidia_toolkit(self, tmp_path):+ """An NVIDIA + AMD box under --rocm runs the ROCm image through the AMD nodes;+ the toolkit prompt is for the --gpus path only."""+ argv, stderr = _run_sh(+ tmp_path, ["--rocm", "true"], nvidia = True, extra_env = {"UNSLOTH_INSTALL_TOOLKIT": "0"}+ )+ assert "--gpus" not in argv+ assert "/dev/kfd" in argv+ assert "Container Toolkit" not in stderr and "no NVIDIA GPU" not in stderr, stderr++ def test_missing_groups_degrade_to_the_devices_alone(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["--rocm", "true"], groups = "none")+ assert "/dev/kfd" in argv and "--group-add" not in argv, argv++ def test_the_gfx_overrides_are_forwarded_only_when_set(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["--rocm", "true"])+ assert "HSA_OVERRIDE_GFX_VERSION" not in argv and "UNSLOTH_ROCM_GFX_ARCH" not in argv+ argv, _ = _run_sh(+ tmp_path,+ ["--rocm", "true"],+ extra_env = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0", "UNSLOTH_ROCM_GFX_ARCH": "gfx1151"},+ )+ env_flags = [argv[i + 1] for i, a in enumerate(argv) if a == "-e"]+ # the dash-only form: docker reads the value from the environment, so it+ # never lands in argv+ assert "HSA_OVERRIDE_GFX_VERSION" in env_flags and "UNSLOTH_ROCM_GFX_ARCH" in env_flags++ def test_the_studio_volume_and_caches_are_mounted_like_the_cuda_path(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["--rocm", "true"])+ mounts = [argv[i + 1] for i, a in enumerate(argv) if a == "-v"]+ assert "unsloth-studio:/opt/unsloth-studio" in mounts, mounts+ assert any(m.endswith(":/workspace/.cache/huggingface") for m in mounts), mounts++ def test_a_custom_image_is_kept(self, tmp_path):+ argv, _ = _run_sh(tmp_path, ["--rocm", "true"], extra_env = {"UNSLOTH_IMAGE": "me/rocm:dev"})+ image, _ = _image_and_cmd(argv)+ assert image == "me/rocm:dev"++ def test_no_mapfile(self):+ """run.sh runs on the host, and macOS ships bash 3.2, which has no mapfile."""+ code = "\n".join(+ ln+ for ln in open(_RUN_SH, encoding = "utf-8").read().splitlines()+ if not ln.lstrip().startswith("#")+ )+ assert "mapfile" not in code and "readarray" not in code++ def test_the_plain_nvidia_path_is_unchanged(self, tmp_path):+ argv, stderr = _run_sh(tmp_path, ["true"], nvidia = True)+ assert argv[argv.index("--gpus") + 1] == "all"+ assert "/dev/kfd" not in argv and "--group-add" not in argv+ assert "rocm" not in stderr.lower(), stderr+++# ── build.sh --rocm ──────────────────────────────────────────────────────────++_SHA_U = "a" * 40+_SHA_Z = "b" * 40+++def _build_sh(+ tmp_path,+ args,+ extra_env = None,+ expect_rc = 0,+):+ tmp_path = tmp_path / f"build{len(os.listdir(tmp_path))}"+ tmp_path.mkdir()+ bindir = tmp_path / "bin"+ bindir.mkdir()+ args_file = tmp_path / "docker-args.txt"+ _stub(str(bindir / "docker"), f'printf "%s\\n" "$@" > {args_file}\n')+ _stub(+ str(bindir / "git"),+ 'if [ "$1" = "ls-remote" ]; then\n'+ ' case "$2" in\n'+ f' *unsloth-zoo*) echo -e "{_SHA_Z}\\tHEAD" ;;\n'+ ' *notebooks*) echo "ls-remote notebooks should not run for --rocm" >&2; exit 3 ;;\n'+ f' *) echo -e "{_SHA_U}\\tHEAD" ;;\n'+ " esac\n exit 0\nfi\nexit 0\n",+ )+ _stub(str(bindir / "curl"), 'echo "curl should not run for --rocm" >&2; exit 1\n')+ env = dict(os.environ)+ env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"+ for leak in ("ROCM_GFX", "ROCM_VERSION", "TORCH_INDEX_URL", "TAG", "IMAGE_NAME"):+ env.pop(leak, None)+ env.update(extra_env or {})+ proc = subprocess.run(+ ["bash", _BUILD_SH, *args], env = env, capture_output = True, text = True, cwd = str(tmp_path)+ )+ assert proc.returncode == expect_rc, proc.stdout + proc.stderr+ argv = args_file.read_text(encoding = "utf-8").splitlines() if args_file.exists() else []+ return proc, argv+++def _build_arg(argv, name):+ for i, item in enumerate(argv):+ if item == "--build-arg" and argv[i + 1].startswith(f"{name}="):+ return argv[i + 1].split("=", 1)[1]+ raise AssertionError(f"--build-arg {name} was never passed: {argv}")+++@_posix_shell+class TestBuildShRocm:+ def test_defaults_are_rocm72_frozen_refs_and_no_cuda_lookups(self, tmp_path):+ proc, argv = _build_sh(tmp_path, ["--rocm"])+ assert "Dockerfile.rocm" in argv+ assert _build_arg(argv, "ROCM_VERSION") == "7.2.4"+ assert _build_arg(argv, "TORCH_INDEX_URL") == "https://download.pytorch.org/whl/rocm7.2"+ assert _build_arg(argv, "ROCM_GFX") == ""+ assert _build_arg(argv, "PYTHON_VERSION") == "3.12"+ assert _build_arg(argv, "UNSLOTH_REF") == _SHA_U+ assert _build_arg(argv, "UNSLOTH_ZOO_REF") == _SHA_Z+ assert argv[argv.index("-t") + 1] == "unsloth-rocm:latest"+ assert "should not run" not in proc.stderr+ assert "run.sh --rocm" in proc.stdout++ def test_gfx_selects_the_per_arch_wheels(self, tmp_path):+ _, argv = _build_sh(tmp_path, ["--rocm", "--gfx", "gfx1151"])+ assert _build_arg(argv, "ROCM_GFX") == "gfx1151"+ _, argv = _build_sh(tmp_path, ["--rocm", "--gfx=gfx1201"])+ assert _build_arg(argv, "ROCM_GFX") == "gfx1201"+ _, argv = _build_sh(tmp_path, ["--rocm"], extra_env = {"ROCM_GFX": "gfx1150"})+ assert _build_arg(argv, "ROCM_GFX") == "gfx1150"++ def test_the_index_follows_the_rocm_version_unless_named(self, tmp_path):+ """ROCM_VERSION=6.3.4 alone must not pair a 6.3 base with the 7.2 wheels: the+ build would pass (torch.version.hip is set either way) and not run."""+ _, argv = _build_sh(tmp_path, ["--rocm"], extra_env = {"ROCM_VERSION": "6.3.4"})+ assert _build_arg(argv, "ROCM_VERSION") == "6.3.4"+ assert _build_arg(argv, "TORCH_INDEX_URL") == "https://download.pytorch.org/whl/rocm6.3"+ _, argv = _build_sh(+ tmp_path,+ ["--rocm"],+ extra_env = {"ROCM_VERSION": "6.3.4", "TORCH_INDEX_URL": "https://example/whl/custom"},+ )+ assert _build_arg(argv, "TORCH_INDEX_URL") == "https://example/whl/custom"+ body = open(_WORKFLOW, encoding = "utf-8").read()+ assert "https://download.pytorch.org/whl/rocm${ROCM%.*}" in body+ local = open(os.path.join(_DOCKER, "test_locally-rocm.sh"), encoding = "utf-8").read()+ assert "rocm${ROCM_VERSION%.*}" in local++ def test_the_local_end_to_end_script_builds_through_build_sh(self):+ """A bare docker build there passed mutable main refs, so a rerun after main+ moved could reuse the install layer and validate stale code."""+ local = open(os.path.join(_DOCKER, "test_locally-rocm.sh"), encoding = "utf-8").read()+ code = "\n".join(ln for ln in local.splitlines() if not ln.lstrip().startswith("#"))+ assert (+ "docker buildx build" not in code and "docker build" not in code+ ), "builds outside build.sh"+ assert 'bash "$BUILD_SH" --rocm' in code++ def test_gfx_without_rocm_is_refused(self, tmp_path):+ proc, argv = _build_sh(tmp_path, ["--gfx", "gfx1151"], expect_rc = 2)+ assert argv == [], "docker build ran anyway"+ assert "--rocm" in proc.stderr++ def test_an_unknown_option_is_refused(self, tmp_path):+ proc, argv = _build_sh(tmp_path, ["--rocm", "--bogus"], expect_rc = 2)+ assert argv == []+ assert "unknown option" in proc.stderr++ def test_the_dockerfile_defaults_match(self):+ body = open(_DOCKERFILE, encoding = "utf-8").read()+ assert "ARG ROCM_VERSION=7.2.4" in body+ assert "ARG TORCH_INDEX_URL=https://download.pytorch.org/whl/rocm7.2" in body+ assert "FROM rocm/dev-ubuntu-24.04:${ROCM_VERSION}" in body+ # a knowingly broken fallback range is worse than a failed build+ assert "bitsandbytes>=0.49" not in body+ assert "bitsandbytes>=0.50.0" in body++ def test_the_workflow_defaults_match_and_its_main_group_is_per_commit(self):+ body = open(_WORKFLOW, encoding = "utf-8").read()+ assert "DEFAULT_ROCM_VERSION: '7.2.4'" in body+ assert "DEFAULT_TORCH_INDEX_URL: 'https://download.pytorch.org/whl/rocm7.2'" in body+ assert "6.2" not in body.replace("ubuntu-22.04", "")+ # per RUN on main: a sha would still pair a scheduled run with a dispatch on+ # an unchanged main, and the group keeps only one pending run+ assert "github.ref == 'refs/heads/main' && github.run_id" in body+ assert "-r{0}', github.run_id" in body, "override sha tags need the run id suffix"+ assert "git ls-remote https://github.com/unslothai/unsloth-zoo" in body+ assert "needs.prepare.outputs.stable == 'true'" in body+ assert "org.opencontainers.image.licenses=Apache-2.0 AND AGPL-3.0-only" in body+++# ── entrypoint-rocm.sh ───────────────────────────────────────────────────────+++def _entrypoint(+ tmp_path,+ *,+ kfd = True,+ readable = True,+ smi_sees_gpu = True,+ python_body = None,+ env_extra = None,+ build_info_gfx = "",+ command = "echo ran",+):+ bindir = tmp_path / "bin"+ bindir.mkdir()+ dev_root = tmp_path / "root"+ (dev_root / "dev").mkdir(parents = True)+ if kfd:+ (dev_root / "dev" / "kfd").write_text("")+ if not readable:+ os.chmod(dev_root / "dev" / "kfd", 0)+ _stub(+ str(bindir / "rocm-smi"),+ 'echo "GPU[0] : GPU ID: 0x1586"\n' if smi_sees_gpu else "echo 'No AMD GPUs specified'\n",+ )+ # the two torch heredocs; stand in for torch on this host+ _stub(str(bindir / "python"), python_body or "cat > /dev/null\nexit 0\n")+ build_info = tmp_path / "build-info"+ build_info.write_text(f"TORCH_INDEX_URL=x\nROCM_GFX={build_info_gfx}\nROCM_VERSION=7.2.4\n")+ dump = tmp_path / "ran"+ env = {+ "PATH": str(bindir) + ":/usr/bin:/bin",+ "HOME": str(tmp_path),+ "UNSLOTH_DEV_ROOT": str(dev_root),+ "UNSLOTH_ROCM_BUILD_INFO": str(build_info),+ }+ env.update(env_extra or {})+ proc = subprocess.run(+ [shutil.which("bash") or "/bin/bash", _ENTRYPOINT, "bash", "-c", f"{command} > {dump}"],+ env = env,+ capture_output = True,+ text = True,+ timeout = 60,+ )+ return proc.returncode, dump.exists(), proc.stderr+++@_posix_shell+class TestRocmEntrypoint:+ def test_no_kfd_refuses_and_names_docker_desktop(self, tmp_path):+ rc, ran, err = _entrypoint(tmp_path, kfd = False)+ assert rc == 1 and not ran+ assert "/dev/kfd not found" in err and "Docker Desktop" in err, err+ # the old advice: a WSL or Docker Desktop host cannot modprobe anything+ assert "modprobe" not in err, err+ assert "run.sh --rocm" in err++ @pytest.mark.skipif(os.geteuid() == 0, reason = "root reads a mode-0 file")+ def test_an_unreadable_kfd_names_the_group_ids(self, tmp_path):+ rc, ran, err = _entrypoint(tmp_path, readable = False)+ assert rc == 1 and not ran+ assert "not readable" in err and "--group-add" in err and "NUMERIC" in err, err++ def test_no_gpu_for_rocm_smi_is_a_note_not_a_refusal(self, tmp_path):+ """Measured on a gfx1151 runner: rocm-smi lists nothing inside the container+ while HIP torch drives the card. torch is the gate; rocm-smi only advises."""+ rc, ran, err = _entrypoint(tmp_path, smi_sees_gpu = False)+ assert rc == 0 and ran, err+ assert "rocm-smi lists no GPU" in err and "/dev/dri" in err, err++ def test_the_skip_flag_runs_the_command_without_probing(self, tmp_path):+ rc, ran, err = _entrypoint(tmp_path, kfd = False, env_extra = {"UNSLOTH_SKIP_GPU_CHECK": "1"})+ assert rc == 0 and ran, err++ def test_a_happy_host_runs_the_command(self, tmp_path):+ rc, ran, err = _entrypoint(tmp_path)+ assert rc == 0 and ran, err++ def test_a_failing_torch_check_stops_before_the_command(self, tmp_path):+ rc, ran, _ = _entrypoint(tmp_path, python_body = "cat > /dev/null\nexit 1\n")+ assert rc == 1 and not ran++ def test_the_torch_check_asserts_a_hip_build_first(self):+ """A CUDA or CPU torch must be named as the image's fault, not the host's."""+ body = open(_ENTRYPOINT, encoding = "utf-8").read()+ check3 = body[body.index("Check 3") : body.index("Check 4")]+ assert "hip_ver is None" in check3 and "not a ROCm build" in check3+ assert "6.2" not in check3, "the ROCm version is read from the build, not hardcoded"++ def test_gfx1033_is_refused_not_spoofed(self, tmp_path):+ """Van Gogh (Steam Deck) computes wrong results under ROCm (studio/ROCM_RDNA2_APU.md);+ install.sh routes it to CPU torch. A HIP-only image can only refuse, and must not+ advise HSA_OVERRIDE_GFX_VERSION, which would hide the silicon from this check."""+ fake = tmp_path / "fake"+ (fake / "torch" / "cuda").mkdir(parents = True)+ (fake / "torch" / "__init__.py").write_text(+ "__version__ = '2.12.1+rocm7.2'\n"+ "class version:\n hip = '7.2.53211'\n"+ "from . import cuda\n"+ )+ (fake / "torch" / "cuda" / "__init__.py").write_text(+ "class _P:\n gcnArchName = 'gfx1033:xnack-'\n"+ "def is_available(): return True\n"+ "def device_count(): return 1\n"+ "def get_device_name(i): return 'AMD Custom GPU 0405'\n"+ "def get_device_properties(i): return _P()\n"+ "def is_bf16_supported(): return False\n"+ )+ python_body = f'PYTHONPATH="{fake}" exec python3 "$@"\n'+ rc, ran, err = _entrypoint(tmp_path, python_body = python_body)+ assert rc == 1 and not ran, err+ assert "gfx1033" in err and "refuses" in err, err+ assert "HSA_OVERRIDE_GFX_VERSION=10.3.0" not in err, err+ # the same fake torch on a supported arch runs the command+ (fake / "torch" / "cuda" / "__init__.py").write_text(+ (fake / "torch" / "cuda" / "__init__.py")+ .read_text()+ .replace("gfx1033:xnack-", "gfx1100:sramecc+")+ )+ (tmp_path / "ok").mkdir()+ rc, ran, err = _entrypoint(tmp_path / "ok", python_body = python_body)+ assert rc == 0 and ran, err+ assert "RDNA 3" in err, err++ def _fake_torch(self, tmp_path, arch):+ fake = tmp_path / "fake"+ (fake / "torch" / "cuda").mkdir(parents = True)+ (fake / "torch" / "__init__.py").write_text(+ "__version__ = '2.12.1+rocm7.2'\nclass version:\n hip = '7.2.53211'\nfrom . import cuda\n"+ )+ (fake / "torch" / "cuda" / "__init__.py").write_text(+ f"class _P:\n gcnArchName = '{arch}'\n"+ "def is_available(): return True\ndef device_count(): return 1\n"+ "def get_device_name(i): return 'AMD GPU'\ndef get_device_properties(i): return _P()\n"+ "def is_bf16_supported(): return False\n"+ )+ return f'PYTHONPATH="{fake}" exec python3 "$@"\n'++ def test_a_spoofed_gfx1033_is_caught_from_the_kernels_topology(self, tmp_path):+ """HSA_OVERRIDE_GFX_VERSION=10.3.0 makes ROCr report gfx1030 for a Steam Deck,+ and run.sh forwards that variable, so gcnArchName alone would wave it through.+ amdkfd's gfx_target_version (100303) is immune to the userland spoof."""+ topo = tmp_path / "topo" / "1"+ topo.mkdir(parents = True)+ (topo / "properties").write_text("vendor_id 4098\ngfx_target_version 100303\n")+ (tmp_path / "topo" / "0").mkdir()+ (tmp_path / "topo" / "0" / "properties").write_text("vendor_id 0\ngfx_target_version 0\n")+ body = self._fake_torch(tmp_path, "gfx1030")+ rc, ran, err = _entrypoint(+ tmp_path,+ python_body = body,+ env_extra = {+ "UNSLOTH_KFD_TOPOLOGY": str(tmp_path / "topo"),+ "HSA_OVERRIDE_GFX_VERSION": "10.3.0",+ },+ )+ assert rc == 1 and not ran, err+ assert "kernel reports a gfx1033" in err and "10.3.0" in err, err+ # the same topology without the spoof: torch already names gfx1033 and the plain refusal fires+ (tmp_path / "b").mkdir()+ rc, ran, err = _entrypoint(+ tmp_path / "b",+ python_body = self._fake_torch(tmp_path / "b", "gfx1033"),+ env_extra = {"UNSLOTH_KFD_TOPOLOGY": str(tmp_path / "topo")},+ )+ assert rc == 1 and not ran and "refuses" in err, err+ # a real gfx1030 with the override set is not refused+ (tmp_path / "c").mkdir()+ (tmp_path / "topo" / "1" / "properties").write_text(+ "vendor_id 4098\ngfx_target_version 100300\n"+ )+ rc, ran, err = _entrypoint(+ tmp_path / "c",+ python_body = self._fake_torch(tmp_path / "c", "gfx1030"),+ env_extra = {+ "UNSLOTH_KFD_TOPOLOGY": str(tmp_path / "topo"),+ "HSA_OVERRIDE_GFX_VERSION": "10.3.0",+ },+ )+ assert rc == 0 and ran, err+ assert "KFD reports: gfx1030" in err, err++ def test_a_per_arch_image_on_a_generic_card_points_at_the_generic_image(self, tmp_path):+ """Dockerfile.rocm refuses ROCM_GFX outside the per-arch families, so the advice+ must not be a rebuild command that fails on the spot."""+ body = self._fake_torch(tmp_path, "gfx1100:sramecc+")+ rc, ran, err = _entrypoint(tmp_path, python_body = body, build_info_gfx = "gfx1151")+ assert rc == 0 and ran, err+ assert "no per-arch index" in err and "ROCM_GFX=gfx1100" not in err, err+ (tmp_path / "d").mkdir()+ rc, ran, err = _entrypoint(+ tmp_path / "d",+ python_body = self._fake_torch(tmp_path / "d", "gfx1201"),+ build_info_gfx = "gfx1151",+ )+ assert rc == 0 and "ROCM_GFX=gfx1201 bash docker/build.sh --rocm" in err, err++ def test_a_per_arch_image_drops_a_stale_gfx_override_and_a_generic_one_keeps_it(self, tmp_path):+ """HSA_OVERRIDE_GFX_VERSION=11.0.0 is the generic-wheel workaround on Strix; a+ gfx1151 image has native kernels the override would hide (install.sh clears it)."""+ body = self._fake_torch(tmp_path, "gfx1151")+ rc, ran, err = _entrypoint(+ tmp_path,+ python_body = body,+ build_info_gfx = "gfx1151",+ env_extra = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ command = "echo ${HSA_OVERRIDE_GFX_VERSION:-unset}",+ )+ assert rc == 0 and ran, err+ assert (tmp_path / "ran").read_text().strip() == "unset"+ assert "ignoring HSA_OVERRIDE_GFX_VERSION=11.0.0" in err, err+ (tmp_path / "g").mkdir()+ rc, ran, err = _entrypoint(+ tmp_path / "g",+ python_body = self._fake_torch(tmp_path / "g", "gfx1100"),+ env_extra = {"HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ command = "echo ${HSA_OVERRIDE_GFX_VERSION:-unset}",+ )+ assert rc == 0 and (tmp_path / "g" / "ran").read_text().strip() == "11.0.0", err++ def test_the_skip_flag_still_drops_a_stale_override_on_a_per_arch_image(self, tmp_path):+ """UNSLOTH_SKIP_GPU_CHECK=1 skips the diagnostics, not the override cleanup."""+ rc, ran, err = _entrypoint(+ tmp_path,+ kfd = False,+ build_info_gfx = "gfx1151",+ env_extra = {"UNSLOTH_SKIP_GPU_CHECK": "1", "HSA_OVERRIDE_GFX_VERSION": "11.0.0"},+ command = "echo ${HSA_OVERRIDE_GFX_VERSION:-unset}",+ )+ assert rc == 0 and ran, err+ assert (tmp_path / "ran").read_text().strip() == "unset"+ assert "ignoring HSA_OVERRIDE_GFX_VERSION" in err and "/dev/kfd" not in err, err++ @staticmethod+ def _build_args(tmp_path, **inputs):+ """Run the prepare job's build_args step as the workflow would."""+ import yaml++ wf = yaml.safe_load(open(_WORKFLOW, encoding = "utf-8"))+ step = next(s for s in wf["jobs"]["prepare"]["steps"] if s.get("id") == "build_args")+ out = tmp_path / f"out{len(os.listdir(tmp_path))}"+ out.write_text("")+ env = {"PATH": os.environ["PATH"], "GITHUB_OUTPUT": str(out)}+ env.update({k: str(v) for k, v in wf["env"].items()})+ env.update({"IN_UNSLOTH": "", "IN_ZOO": "", "IN_ROCM": "", "IN_INDEX": "", "IN_GFX": ""})+ env.update(inputs)+ proc = subprocess.run(+ ["bash", "-e", "-c", step["run"]], env = env, capture_output = True, text = True+ )+ got = dict(ln.split("=", 1) for ln in out.read_text().splitlines() if "=" in ln)+ return proc.returncode, got, proc.stdout + proc.stderr++ def test_gfx906_defaults_to_the_last_rocm_that_carries_it(self, tmp_path):+ """The public :gfx906 tag must name a 6.3 build: a gfx906 dispatch on the+ 7.2.4 default would be tagged and fail on the first matmul."""+ rc, got, log = self._build_args(tmp_path, IN_GFX = "gfx906")+ assert rc == 0, log+ assert got["rocm_version"] == "6.3.4" and got["torch_index_url"].endswith("/rocm6.3"), got+ assert got["gfx_tag"] == "true" and got["stable"] == "false", got+ rc, got, log = self._build_args(tmp_path, IN_GFX = "gfx906", IN_ROCM = "6.3.4")+ assert rc == 0 and got["gfx_tag"] == "true", (got, log)+ rc, got, log = self._build_args(tmp_path, IN_GFX = "gfx906", IN_ROCM = "7.2.4")+ assert rc != 0 and "needs a ROCm 6.3 base" in log, log+ rc, got, log = self._build_args(+ tmp_path, IN_GFX = "gfx906", IN_ROCM = "6.3.4", IN_UNSLOTH = "feature"+ )+ assert rc == 0 and got["gfx_tag"] == "false", got+ rc, got, log = self._build_args(tmp_path, IN_GFX = "gfx1151")+ assert rc == 0 and got["rocm_version"] == "7.2.4" and got["gfx_tag"] == "true", got+ rc, got, log = self._build_args(tmp_path)+ assert rc == 0 and got["stable"] == "true" and got["gfx_tag"] == "false", got++ def test_the_workflow_accepts_a_gfx906_dispatch(self):+ """Dockerfile.rocm relies on ROCM_GFX=gfx906 to leave out bitsandbytes, so the+ dispatch validation must let it through (with a 6.3 base)."""+ body = open(_WORKFLOW, encoding = "utf-8").read()+ assert '""|gfx906|gfx1150|gfx1151|gfx1152|gfx1200|gfx1201) ;;' in body+ docker = open(_DOCKERFILE, encoding = "utf-8").read()+ assert (+ "--build-arg UNSLOTH_REF=<sha>" in docker+ ), "the bare docker build line must not suggest mutable refs"++ def test_a_gfx906_build_ships_without_bitsandbytes(self):+ """No prebuilt bitsandbytes wheel has gfx906 kernels; install.sh skips it for+ gfx906 and the image must too, or its own 4-bit smoke test cannot run."""+ docker = open(_DOCKERFILE, encoding = "utf-8").read()+ assert "gfx906) ;;" in docker+ assert "grep -q '^ROCM_GFX=gfx906$' /etc/unsloth-rocm-build" in docker+ assert "pip uninstall -y bitsandbytes" in docker+ assert 'WANT_BNB = BUILD_GFX != "gfx906"' in docker+ smoke = open(_SMOKE, encoding = "utf-8").read()+ assert "load_in_4bit = four_bit" in smoke and "ROCM_GFX=gfx906" in smoke+ entry = open(_ENTRYPOINT, encoding = "utf-8").read()+ assert "ROCM_GFX=gfx906 ROCM_VERSION=6.3.4" in entry++ def test_the_gfx_tag_needs_every_other_input_at_its_default(self):+ """A feature-branch ref plus rocm_gfx=gfx1151 must not replace the public+ gfx1151 image: the gfx tag is gated like latest, minus the gfx itself."""+ body = open(_WORKFLOW, encoding = "utf-8").read()+ assert "gfx_tag=${GFX_TAG}" in body+ assert (+ 'GFX_TAG=false\n [ "$DEFAULTS" = "true" ] && [ -n "$GFX" ] && GFX_TAG=true'+ in body+ )+ raw = [+ ln+ for ln in body.splitlines()+ if "type=raw,value=${{ needs.prepare.outputs.rocm_gfx }}" in ln+ ]+ assert len(raw) == 1 and "needs.prepare.outputs.gfx_tag == 'true'" in raw[0], raw++ def test_the_arch_table_carries_no_marketing_names(self):+ """Card-name tables live in install.sh and studio/ under a parity test; a+ seventh copy here would drift. Families only."""+ body = open(_ENTRYPOINT, encoding = "utf-8").read()+ import re++ assert not re.search(r"RX\s*\d{4}", body), "marketing names in the entrypoint's arch table"+ assert "gfx906" in body and "6.3" in body, "gfx906 needs the version-aware note"