Skip to content

The platform for continuously improving AI agents.

13.7 KB
Raw Blame
"""SFT training images keyed by frozen train-stack ids (modal_shared.stacks).

Do not edit pip pins on an existing TRAIN_IMAGES key. Clone the builder, new key.
"""

from __future__ import annotations

import modal

from modal_shared.images import attach_modelfam, attach_sft_assets
from modal_shared.stacks import (
    KEV_REV,
    TRAIN_DECISION,
    TRAIN_INKLING,
    TRAIN_KEV,
    TRAIN_QWEN4,
    TRAIN_U2026_7,
    TRAIN_U2026_8_18,
    TRAIN_U2026_8_GPOS,
    TRAIN_U2026_8_TF510,
    TRAIN_U2026_8_TF515,
    TRAIN_U2026_9_2,
    TRAIN_U2026_10_7,
    TRAIN_U2026_11_9,
)

_SFT_ENV = {
    # Container-local on purpose. Base weights come from the weights Volume's .base_models/
    # snapshot after fetch_base_model; this cache is not a second copy of the catalog.
    "HF_HOME": "/tmp/hf_cache",
    "HF_XET_HIGH_PERFORMANCE": "1",
    "PYTHONUNBUFFERED": "1",
}

_base_cuda = modal.Image.from_registry(
    "nvidia/cuda:12.8.0-devel-ubuntu22.04",
    add_python="3.11",
).apt_install("git")


def _mamba_kernels(image: modal.Image, torch_pin: str) -> modal.Image:
    # Nemotron-H needs fused Mamba kernels. Re-pin torch in the same call —
    # mamba-ssm's install_requires otherwise silently upgrades it.
    return image.pip_install(
        torch_pin,
        "mamba-ssm>=2.2.0",
        "causal-conv1d>=1.4.0",
        extra_options="--no-build-isolation",
    )


def _finish(image: modal.Image, env: dict[str, str]) -> modal.Image:
    return attach_sft_assets(attach_modelfam(image.pip_install("jsonschema==4.26.0").env(env)))


def _clone_trl(image: modal.Image, *, branch: str | None = "v1.10.0") -> modal.Image:
    cmd = "git clone --depth 1"
    if branch:
        cmd += f" --branch {branch}"
    cmd += " https://github.com/huggingface/trl.git /opt/trl_src"
    return image.run_commands(cmd)


def _assert_versions(
    label: str,
    *,
    torch_prefix: str,
    tf_min: tuple[int, int] | None,
    tf_max: tuple[int, int] | None = None,
) -> str:
    tf_check = ""
    if tf_min:
        maj, minor = tf_min
        tf_check += (
            f"assert tuple(int(x) for x in transformers.__version__.split('.')[:2]) "
            f">= ({maj}, {minor}), transformers.__version__; "
        )
    if tf_max:
        maj, minor = tf_max
        tf_check += (
            f"assert tuple(int(x) for x in transformers.__version__.split('.')[:2]) "
            f"< ({maj}, {minor}), transformers.__version__; "
        )
    return (
        'python -c "import torch, transformers; from torch.nn.functional import ScalingType; '
        f"assert torch.__version__.startswith({torch_prefix!r}), torch.__version__; "
        f"{tf_check}"
        f'print({label!r}, torch.__version__, transformers.__version__)"'
    )


def _unsloth_torch27() -> modal.Image:
    return _mamba_kernels(
        _base_cuda.pip_install(
            "torch==2.7.0",
            index_url="https://download.pytorch.org/whl/cu128",
        ).pip_install(
            "unsloth[cu128-torch270]==2026.7.5",
            "unsloth_zoo==2026.7.6",
            "transformers>=5.2.0",
            "datasets>=3.0.0",
            "huggingface_hub>=0.27.0",
            "sentencepiece",
            "protobuf",
        ),
        "torch==2.7.0",
    )


def _unsloth_torch210() -> modal.Image:
    # Frozen 2026.8 / torch 2.10 layer. Do not edit — copy into a new stack instead.
    return _mamba_kernels(
        _base_cuda.pip_install(
            "torch==2.10.0",
            index_url="https://download.pytorch.org/whl/cu128",
        ).pip_install(
            "unsloth[cu128-torch2100]==2026.8.5",
            "unsloth_zoo==2026.8.4",
            "datasets>=3.0.0",
            "huggingface_hub>=0.27.0",
            "sentencepiece",
            "protobuf",
        ),
        "torch==2.10.0",
    )


_u2026_7 = _finish(
    _clone_trl(_unsloth_torch27()),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_7,
    },
)

_u2026_8_tf510 = _finish(
    _clone_trl(_unsloth_torch210().pip_install("transformers>=5.10.2")).run_commands(
        _assert_versions("u2026_8_tf510-ok", torch_prefix="2.10", tf_min=(5, 10)),
        "python -c \"import mamba_ssm; print('mamba-ok')\"",
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_8_TF510,
    },
)

_u2026_8_tf515 = _finish(
    _clone_trl(_unsloth_torch210().pip_install("transformers>=5.15.0")).run_commands(
        _assert_versions("u2026_8_tf515-ok", torch_prefix="2.10", tf_min=(5, 15)),
        'python -c "from transformers import MuseGlimmerForConditionalGeneration"',
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_8_TF515,
    },
)


def _unsloth_torch210_818() -> modal.Image:
    # New stack: Unsloth 2026.8.18 (improved GC offload). Do not retag older keys.
    return _mamba_kernels(
        _base_cuda.pip_install(
            "torch==2.10.0",
            index_url="https://download.pytorch.org/whl/cu128",
        ).pip_install(
            "unsloth[cu128-torch2100]==2026.8.18",
            "unsloth_zoo==2026.8.12",
            "datasets>=3.0.0",
            "huggingface_hub>=0.27.0",
            "sentencepiece",
            "protobuf",
        ),
        "torch==2.10.0",
    )


_u2026_8_18 = _finish(
    _clone_trl(_unsloth_torch210_818().pip_install("transformers>=5.10.2")).run_commands(
        _assert_versions("u2026_8_18-ok", torch_prefix="2.10", tf_min=(5, 10)),
        "python -c \"import mamba_ssm; print('mamba-ok')\"",
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_8_18,
    },
)


def _unsloth_torch210_92() -> modal.Image:
    # Qwen3.8: Unsloth 2026.8.18's get_model_name rejects unsloth/Qwen3.8-27B.
    return _mamba_kernels(
        _base_cuda.pip_install(
            "torch==2.10.0",
            index_url="https://download.pytorch.org/whl/cu128",
        ).pip_install(
            "unsloth[cu128-torch2100]==2026.9.2",
            "unsloth_zoo==2026.9.1",
            "datasets>=3.0.0",
            "huggingface_hub>=0.27.0",
            "sentencepiece",
            "protobuf",
        ),
        "torch==2.10.0",
    )


def _unsloth_torch210_107() -> modal.Image:
    # Qwen and Llama. 2026.10.7 caps transformers at 5.17, so this is not a second upgrade.
    return _base_cuda.pip_install(
        "torch==2.10.0",
        index_url="https://download.pytorch.org/whl/cu128",
    ).pip_install(
        "unsloth[cu128-torch2100]==2026.10.7",
        "unsloth_zoo==2026.10.7",
        "transformers==5.17.0",
        "datasets>=3.0.0",
        "huggingface_hub>=0.27.0",
        "sentencepiece",
        "protobuf",
    )


def _unsloth_torch210_119() -> modal.Image:
    # Gemma 4. transformers 5.15+ raises AmbiguousGlobalPerLayerAttributeError on head_dim.
    return _base_cuda.pip_install(
        "torch==2.10.0",
        index_url="https://download.pytorch.org/whl/cu128",
    ).pip_install(
        "unsloth[cu128-torch2100]==2026.11.9",
        "unsloth_zoo==2026.11.9",
        "transformers>=5.10.2,<5.15",
        "datasets>=3.0.0",
        "huggingface_hub>=0.34.0",
        "sentencepiece",
        "protobuf",
    )


def _unsloth_inkling() -> modal.Image:
    # Install 5.24.1 after Unsloth. 2026.11.9's own pin stops below 5.15, which
    # does not contain Inkling2Loop.
    return (
        _base_cuda.pip_install(
            "torch==2.10.0",
            index_url="https://download.pytorch.org/whl/cu128",
        )
        .pip_install(
            "unsloth[cu128-torch2100]==2026.11.9",
            "unsloth_zoo==2026.11.9",
            "datasets>=3.0.0",
            "huggingface_hub>=0.34.0",
            "sentencepiece",
            "protobuf",
        )
        .pip_install("transformers==5.24.1", "compressed-tensors>=0.15.0")
        # 2026.11.9 dequantizes Inkling experts without their per-expert scale.
        # This commit keeps the released NVFP4 / MXFP8 stacks packed.
        .run_commands(
            "pip install --no-deps "
            "git+https://github.com/unslothai/unsloth.git@174067b17e794edd9f39bec0f1b182d9790fcbec"
        )
    )


_QWEN4_UNSLOTH = "56397f9d7b06177d035239ebed233a17646e5d42"
_QWEN4_ZOO = "12361e94e592c794d5b90032cac55babc61deaa5"


def _unsloth_qwen4() -> modal.Image:
    # 2026.11.9 supplies the CUDA deps. Its own pin refuses transformers 5.26,
    # which is the first release with qwen4_moe. The git overlay is that loader.
    return (
        _base_cuda.pip_install(
            "torch==2.10.0",
            index_url="https://download.pytorch.org/whl/cu128",
        )
        .pip_install(
            "unsloth[cu128-torch2100]==2026.11.9",
            "unsloth_zoo==2026.11.9",
            "datasets>=3.0.0",
            "huggingface_hub>=0.34.0",
            "sentencepiece",
            "protobuf",
            "tiktoken",
        )
        .pip_install("transformers==5.26.0", "xgrammar")
        .run_commands(
            f"pip install --no-deps git+https://github.com/unslothai/unsloth.git@{_QWEN4_UNSLOTH}",
            f"pip install --no-deps git+https://github.com/unslothai/unsloth-zoo.git@{_QWEN4_ZOO}",
        )
    )


_qwen4 = _finish(
    _clone_trl(_unsloth_qwen4()).run_commands(
        _assert_versions("qwen4_56397f9-ok", torch_prefix="2.10", tf_min=(5, 26)),
        'python -c "from unsloth import FastModel"',
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_QWEN4,
    },
)


_inkling = _finish(
    _clone_trl(_unsloth_inkling()).run_commands(
        _assert_versions("inkling_174067b-ok", torch_prefix="2.10", tf_min=(5, 24)),
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_INKLING,
    },
)


_u2026_11_9 = _finish(
    _clone_trl(_unsloth_torch210_119()).run_commands(
        _assert_versions("u2026_11_9-ok", torch_prefix="2.10", tf_min=(5, 10), tf_max=(5, 15)),
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_11_9,
    },
)


_u2026_10_7 = _finish(
    _clone_trl(_unsloth_torch210_107()).run_commands(
        _assert_versions("u2026_10_7-ok", torch_prefix="2.10", tf_min=(5, 17)),
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_10_7,
    },
)


_u2026_9_2 = _finish(
    _clone_trl(_unsloth_torch210_92().pip_install("transformers>=5.10.2")).run_commands(
        _assert_versions("u2026_9_2-ok", torch_prefix="2.10", tf_min=(5, 10)),
        "python -c \"import mamba_ssm; print('mamba-ok')\"",
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_9_2,
    },
)

# Keep Unsloth's transformers pin (≤5.5): upgrading to 5.10+ remaps MoE experts
# to fused gate_up_proj and drops the bnb-4bit per-expert weights (random init →
# loss ~17 / token_acc 0). kernels keeps MXFP4 from silently dequantizing to bf16.
# Cap kernels<0.15: 0.15+ requires version= on LayerRepository and crashes
# transformers≤5.5 import (hub_kernels.py) before training starts.
_u2026_8_gptoss = _finish(
    _clone_trl(_unsloth_torch210().pip_install("kernels>=0.12.0,<0.15")).run_commands(
        _assert_versions("u2026_8_gptoss-ok", torch_prefix="2.10", tf_min=None),
        "python -c \"import kernels; print('kernels-ok')\"",
    ),
    {
        **_SFT_ENV,
        "TRL_SRC": "/opt/trl_src",
        "UNSLOTH_IMAGE": TRAIN_U2026_8_GPOS,
        # Fused forward binds load_balancing_loss_func by value and crashes on
        # gate_logits=(). Disable compile so stock forward + empty-tuple guard apply.
        "UNSLOTH_COMPILE_DISABLE": "1",
    },
)

# Every image in this module needs modal_shared attached, even ones whose
# functions never call resolve(): Modal re-imports the whole entrypoint file
# to reconstruct any function in it, and that file top-level-imports this
# module, regardless of which specific Function/image is being invoked.
light_image = attach_modelfam(modal.Image.debian_slim(python_version="3.11"))

_decision = _finish(
    _base_cuda.pip_install(
        "torch==2.10.0",
        "torchvision==0.25.0",
        index_url="https://download.pytorch.org/whl/cu128",
    ).pip_install(
        "unsloth==2026.10.3",
        "unsloth_zoo==2026.10.3",
        "transformers==5.17.0",
        "trl==1.13.0",
        "datasets==4.7.0",
        "sentencepiece",
        "protobuf",
        "bitsandbytes==0.49.2",
    ),
    {
        **_SFT_ENV,
        "UNSLOTH_IMAGE": TRAIN_DECISION,
        "UNSLOTH_DISABLE_STATISTICS": "1",
        # Default block compile does not finish a Qwen3.5 decision step.
        "UNSLOTH_COMPILE_DISABLE": "1",
    },
)

_kev = _finish(
    _base_cuda.pip_install(
        "torch==2.8.0",
        index_url="https://download.pytorch.org/whl/cu128",
    )
    .pip_install(
        "transformers==5.17.0",
        "peft==0.22.0",
        "accelerate==1.16.0",
        "datasets==5.2.0",
        "pydantic==2.14.4",
        "safetensors==0.8.0",
        "sentencepiece==0.2.3",
        "protobuf==7.36.2",
        "huggingface_hub==1.33.0",
        "einops==0.8.2",
        # The image is Python 3.11. NumPy 2.5 requires 3.12.
        "numpy==2.4.6",
    )
    .run_commands(
        "git clone https://github.com/jaredpalmer/kev.git /opt/kev"
        f" && git -C /opt/kev checkout {KEV_REV}"
    ),
    {
        **_SFT_ENV,
        "UNSLOTH_IMAGE": TRAIN_KEV,
        "PYTHONPATH": "/opt/kev",
    },
)

TRAIN_IMAGES: dict[str, modal.Image] = {
    TRAIN_DECISION: _decision,
    TRAIN_KEV: _kev,
    TRAIN_U2026_7: _u2026_7,
    TRAIN_U2026_8_TF510: _u2026_8_tf510,
    TRAIN_U2026_8_TF515: _u2026_8_tf515,
    TRAIN_U2026_8_GPOS: _u2026_8_gptoss,
    TRAIN_U2026_8_18: _u2026_8_18,
    TRAIN_U2026_9_2: _u2026_9_2,
    TRAIN_U2026_10_7: _u2026_10_7,
    TRAIN_U2026_11_9: _u2026_11_9,
    TRAIN_INKLING: _inkling,
    TRAIN_QWEN4: _qwen4,
}