# ROCm 7.2.2 image for DINOv2 training on MI355X.
# Installs a gfx950-native xformers wheel so the model uses
# memory_efficient_attention.
FROM rocm/pytorch:rocm7.2.2_ubuntu24.04_py3.12_pytorch_release_2.10.0 AS base

ARG USER_ID=1000
ARG GROUP_ID=1000

ENV UV_CACHE_DIR=/workspace/.cache/uv

RUN apt-get update && apt-get install -y wget curl git

RUN pip install --upgrade pip setuptools wheel

WORKDIR /workspace
ENV PYTHONPATH=/workspace

RUN groupadd -g ${GROUP_ID} dinov2user 2>/dev/null || true && \
    useradd -m -s /bin/bash -u ${USER_ID} -g ${GROUP_ID} dinov2user 2>/dev/null || true && \
    chown -R ${USER_ID}:${GROUP_ID} /workspace

COPY pyproject.toml /workspace

RUN pip install -e .

RUN pip install timm torchmetrics lightning-utilities --no-deps

# mmcv-full deps (skipped by --no-deps below) + mmsegmentation for eval scripts
RUN pip install addict yapf ftfy regex omegaconf
RUN pip install mmsegmentation==1.2.0 --no-deps

# xFormers: install a gfx950-native wheel built from xformers v0.0.35 against this exact torch
# (2.10.0+rocm7.2.2). --no-deps keeps AMD's base-image torch in place.
#
# Why a prebuilt wheel and not `pip install xformers`:
#   - The download.pytorch.org/whl/rocm7.2 wheel has NO gfx950 CK kernels (PYTORCH_ROCM_ARCH=None);
#     memory_efficient_attention SIGSEGVs on first launch on MI355X.
#   - A wheel built against a different torch (2.9.1) passes forward but FAILS backward on 2.10.0
#     (CK stride assertion). So the wheel must match this torch.
#
# Before `docker build`, place the resulting wheel in `wheels/` in the Docker
# build context. Docker can only COPY files from that context. The image uses
# `/tmp/wheels/` as a temporary install location and removes it afterward.
# The wheel was produced with (run inside this image, GPU node, as root):
#   git clone --recursive -b v0.0.35 https://github.com/facebookresearch/xformers.git /tmp/xf
#   cd /tmp/xf && PYTORCH_ROCM_ARCH=gfx950 USE_ROCM=1 ROCM_PATH=/opt/rocm MAX_JOBS=16 \
#       pip wheel . --no-build-isolation --no-deps -w wheels/
#   (USE_ROCM=1 is the correct flag -- FORCE_CUDA=1 wrongly selects the nvcc/CUDA path.)
COPY wheels/ /tmp/wheels/
RUN pip install --no-deps /tmp/wheels/xformers-*.whl && rm -rf /tmp/wheels

# Import check only. A real kernel launch (memory_efficient_attention) cannot run during
# `docker build` (no GPU); the gfx950 kernels are verified by a post-build GPU smoke test via srun.
RUN python -c "import xformers; from xformers.ops import memory_efficient_attention; print('xformers', xformers.__version__, 'import OK')"

RUN mkdir -p /workspace/data /workspace/models /workspace/checkpoints

USER ${USER_ID}

CMD ["/bin/bash"]
