Compare commits

..

5 Commits

Author SHA1 Message Date
Wing Lian
993db05b3a fix losses 2026-04-26 10:28:05 -04:00
Wing Lian
1b9520cc8b more train steps 2026-04-25 02:17:48 +00:00
Wing Lian
f77408a3d0 fix tests 2026-04-23 23:47:28 +00:00
Wing Lian
5db4272f69 more steps for loss check 2026-04-23 18:43:18 +00:00
Wing Lian
431888c1de use smaller pretrained models for ci 2026-04-23 13:51:01 +00:00
58 changed files with 839 additions and 527 deletions

View File

@@ -31,11 +31,10 @@ PRs are **greatly welcome**!
Please run below to setup env Please run below to setup env
```bash ```bash
# Install axolotl + dev and test dependencies # Install axolotl + dev and test dependencies from lockfile
export UV_TORCH_BACKEND=cu128 # or cu130 export UV_TORCH_BACKEND=cu128 # or cu130
uv venv --no-project --relocatable uv sync --extra flash-attn --extra deepspeed --group dev --group test
source .venv/bin/activate source .venv/bin/activate
uv pip install --no-build-isolation -e '.[deepspeed]' --group dev --group test
pre-commit install pre-commit install
# test # test

View File

@@ -30,6 +30,14 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- cuda: "128"
cuda_version: 12.8.1
cudnn_version: ""
python_version: "3.11"
pytorch: 2.9.0
torch_cuda_arch_list: "7.0 7.5 8.0 8.6 8.7 8.9 9.0+PTX"
dockerfile: "Dockerfile-base"
platforms: "linux/amd64,linux/arm64"
- cuda: "128" - cuda: "128"
cuda_version: 12.8.1 cuda_version: 12.8.1
cudnn_version: "" cudnn_version: ""
@@ -160,6 +168,14 @@ jobs:
torch_cuda_arch_list: "7.0 7.5 8.0 8.6 8.7 8.9 9.0+PTX" torch_cuda_arch_list: "7.0 7.5 8.0 8.6 8.7 8.9 9.0+PTX"
dockerfile: "Dockerfile-uv-base" dockerfile: "Dockerfile-uv-base"
platforms: "linux/amd64,linux/arm64" platforms: "linux/amd64,linux/arm64"
- cuda: "128"
cuda_version: 12.8.1
cudnn_version: ""
python_version: "3.11"
pytorch: 2.9.0
torch_cuda_arch_list: "7.0 7.5 8.0 8.6 8.7 8.9 9.0+PTX"
dockerfile: "Dockerfile-uv-base"
platforms: "linux/amd64,linux/arm64"
- cuda: "128" - cuda: "128"
cuda_version: 12.8.1 cuda_version: 12.8.1
cudnn_version: "" cudnn_version: ""

View File

@@ -18,6 +18,12 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- cuda: 128
cuda_version: 12.8.1
python_version: "3.11"
pytorch: 2.9.0
axolotl_extras:
platforms: "linux/amd64,linux/arm64"
- cuda: 128 - cuda: 128
cuda_version: 12.8.1 cuda_version: 12.8.1
python_version: "3.11" python_version: "3.11"
@@ -174,6 +180,12 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- cuda: 128
cuda_version: 12.8.1
python_version: "3.11"
pytorch: 2.9.0
axolotl_extras:
platforms: "linux/amd64,linux/arm64"
- cuda: 128 - cuda: 128
cuda_version: 12.8.1 cuda_version: 12.8.1
python_version: "3.11" python_version: "3.11"

View File

@@ -1 +1 @@
0.16.2.dev0 0.16.0.dev0

View File

@@ -24,9 +24,9 @@ WORKDIR /workspace/axolotl
# If AXOLOTL_EXTRAS is set, append it in brackets; don't install deepspeed with arm64 # If AXOLOTL_EXTRAS is set, append it in brackets; don't install deepspeed with arm64
RUN pip uninstall -y causal_conv1d RUN pip uninstall -y causal_conv1d
RUN if [ "$TARGETARCH" = "arm64" ]; then \ RUN if [ "$TARGETARCH" = "arm64" ]; then \
BASE_EXTRAS="optimizers,ray"; \ BASE_EXTRAS="flash-attn,ring-flash-attn,optimizers,ray"; \
else \ else \
BASE_EXTRAS="deepspeed,optimizers,ray"; \ BASE_EXTRAS="deepspeed,flash-attn,ring-flash-attn,optimizers,ray"; \
fi && \ fi && \
if [ "$AXOLOTL_EXTRAS" != "" ]; then \ if [ "$AXOLOTL_EXTRAS" != "" ]; then \
pip install --no-build-isolation -e .[$BASE_EXTRAS,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \ pip install --no-build-isolation -e .[$BASE_EXTRAS,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \

View File

@@ -58,3 +58,19 @@ RUN git lfs install --skip-repo && \
# The base image ships with `pydantic==1.8.2` which is not working # The base image ships with `pydantic==1.8.2` which is not working
pip3 install -U --no-cache-dir pydantic==1.10.10 && \ pip3 install -U --no-cache-dir pydantic==1.10.10 && \
pip3 cache purge pip3 cache purge
# Map Python version (e.g., 3.12 -> cp312)
RUN PYTHON_CP="cp$(echo $PYTHON_VERSION | tr -d '.')" && \
# Map PyTorch version (e.g., 2.9.1 -> torch2.9, 2.10.0 -> torch2.10)
TORCH_TAG="torch$(echo $PYTORCH_VERSION | grep -oP '^\d+\.\d+')" && \
# Map architecture
case "$TARGETARCH" in \
amd64) ARCH_TAG="x86_64" ;; \
arm64) ARCH_TAG="aarch64" ;; \
*) echo "Unsupported architecture: $TARGETARCH"; exit 1 ;; \
esac && \
WHL_VERSION="v0.7.16" && \
WHL_FILE="flash_attn-2.8.3+cu${CUDA}${TORCH_TAG}-${PYTHON_CP}-${PYTHON_CP}-linux_${ARCH_TAG}.whl" && \
wget -nv "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/${WHL_VERSION}/${WHL_FILE}" && \
pip3 install --no-cache-dir "${WHL_FILE}" && \
rm "${WHL_FILE}"

View File

@@ -24,9 +24,9 @@ RUN git fetch origin +$GITHUB_REF && \
# If AXOLOTL_EXTRAS is set, append it in brackets # If AXOLOTL_EXTRAS is set, append it in brackets
RUN if [ "$AXOLOTL_EXTRAS" != "" ] ; then \ RUN if [ "$AXOLOTL_EXTRAS" != "" ] ; then \
pip install --no-build-isolation -e .[deepspeed,mamba-ssm,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \ pip install --no-build-isolation -e .[deepspeed,flash-attn,mamba-ssm,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \
else \ else \
pip install --no-build-isolation -e .[deepspeed,mamba-ssm] $AXOLOTL_ARGS; \ pip install --no-build-isolation -e .[deepspeed,flash-attn,mamba-ssm] $AXOLOTL_ARGS; \
fi fi
# So we can test the Docker image # So we can test the Docker image

View File

@@ -24,9 +24,9 @@ WORKDIR /workspace/axolotl
# If AXOLOTL_EXTRAS is set, append it in brackets; don't install deepspeed with arm64 # If AXOLOTL_EXTRAS is set, append it in brackets; don't install deepspeed with arm64
RUN uv pip uninstall causal_conv1d RUN uv pip uninstall causal_conv1d
RUN if [ "$TARGETARCH" = "arm64" ]; then \ RUN if [ "$TARGETARCH" = "arm64" ]; then \
BASE_EXTRAS="optimizers,ray"; \ BASE_EXTRAS="flash-attn,ring-flash-attn,optimizers,ray"; \
else \ else \
BASE_EXTRAS="deepspeed,optimizers,ray"; \ BASE_EXTRAS="deepspeed,flash-attn,ring-flash-attn,optimizers,ray"; \
fi && \ fi && \
if [ "$AXOLOTL_EXTRAS" != "" ]; then \ if [ "$AXOLOTL_EXTRAS" != "" ]; then \
uv pip install --no-build-isolation -e .[$BASE_EXTRAS,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \ uv pip install --no-build-isolation -e .[$BASE_EXTRAS,$AXOLOTL_EXTRAS] $AXOLOTL_ARGS; \

View File

@@ -38,3 +38,20 @@ RUN uv pip install packaging setuptools wheel psutil \
RUN if [ "$TARGETARCH" = "amd64" ]; then \ RUN if [ "$TARGETARCH" = "amd64" ]; then \
MAMBA_SKIP_CUDA_BUILD=TRUE CAUSAL_CONV1D_SKIP_CUDA_BUILD=TRUE uv pip install --no-build-isolation mamba_ssm causal_conv1d; \ MAMBA_SKIP_CUDA_BUILD=TRUE CAUSAL_CONV1D_SKIP_CUDA_BUILD=TRUE uv pip install --no-build-isolation mamba_ssm causal_conv1d; \
fi fi
# Map Python version (e.g., 3.12 -> cp312)
RUN PYTHON_CP="cp$(echo $PYTHON_VERSION | tr -d '.')" && \
# Map PyTorch version (e.g., 2.9.1 -> torch2.9, 2.10.0 -> torch2.10)
TORCH_TAG="torch$(echo $PYTORCH_VERSION | grep -oP '^\d+\.\d+')" && \
LINUX_TAG="manylinux_" && \
# Map architecture
case "$TARGETARCH" in \
amd64) ARCH_TAG="2_24_x86_64.manylinux_2_28_x86_64" ;; \
arm64) ARCH_TAG="2_34_aarch64" ;; \
*) echo "Unsupported architecture: $TARGETARCH"; exit 1 ;; \
esac && \
WHL_VERSION="v0.7.16" && \
WHL_FILE="flash_attn-2.8.3+cu${CUDA}${TORCH_TAG}-${PYTHON_CP}-${PYTHON_CP}-${LINUX_TAG}${ARCH_TAG}.whl" && \
wget -nv "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/${WHL_VERSION}/${WHL_FILE}" && \
uv pip install --no-cache-dir "${WHL_FILE}" && \
rm "${WHL_FILE}"

View File

@@ -77,9 +77,8 @@ Make sure you have an [editable install](https://setuptools.pypa.io/en/latest/us
```bash ```bash
export UV_TORCH_BACKEND=cu128 # or cu130 export UV_TORCH_BACKEND=cu128 # or cu130
uv venv --no-project --relocatable uv sync --extra flash-attn --extra deepspeed --group dev --group test
source .venv/bin/activate source .venv/bin/activate
uv pip install --no-build-isolation -e '.[deepspeed]' --group dev --group test
``` ```
#### Remote Hosts #### Remote Hosts
@@ -219,9 +218,8 @@ docker run --privileged --gpus '"all"' --shm-size 10g --rm -it --name axolotl --
You will now be in the container. Next, install Axolotl with dev dependencies: You will now be in the container. Next, install Axolotl with dev dependencies:
```bash ```bash
uv venv --no-project --relocatable uv sync --extra flash-attn --extra deepspeed --group dev --group test
source .venv/bin/activate source .venv/bin/activate
uv pip install --no-build-isolation -e '.[deepspeed]' --group dev --group test
``` ```
### Attach To Container ### Attach To Container

View File

@@ -10,16 +10,13 @@ This section describes the different Docker images that are released by AxolotlA
[Docker Hub](https://hub.docker.com/u/axolotlai). [Docker Hub](https://hub.docker.com/u/axolotlai).
::: {.callout-important} ::: {.callout-important}
### Switch to the `-uv` images For Blackwell GPUs, please use the tags with PyTorch 2.9.1 and CUDA 12.8.
:::
Each image below ships a **uv variant** that uses [uv](https://docs.astral.sh/uv/) with a relocatable venv ::: {.callout-tip}
(`/workspace/axolotl-venv`) instead of Miniconda + pip. Append `-uv` to the image name Each image below is available in a **uv variant** that uses [uv](https://docs.astral.sh/uv/) with
(e.g. `axolotlai/axolotl-uv`, `axolotlai/axolotl-base-uv`, `axolotlai/axolotl-cloud-uv`). Tags follow the a relocatable venv (`/workspace/axolotl-venv`) instead of Miniconda + pip. Append `-uv` to the image name
same format as their non-uv counterparts. (e.g. `axolotlai/axolotl-base-uv`). Tags follow the same format. We recommend the uv images for new deployments.
**We recommend switching to the `-uv` images early.** In the near future we will publish the uv-based
build to the non-uv tags as well. The non-uv names will continue to work, but they will start serving
the uv image.
::: :::
## Base ## Base
@@ -88,7 +85,7 @@ Tags examples:
- `main-py3.12-cu130-2.10.0` - `main-py3.12-cu130-2.10.0`
- `main-latest` - `main-latest`
- `main-20260315-py3.11-cu128-2.9.1` - `main-20260315-py3.11-cu128-2.9.1`
- `0.16.1` - `0.12.0`
## Cloud ## Cloud

View File

@@ -57,7 +57,7 @@ description: Frequently asked questions
**Q: vLLM is not working with Axolotl** **Q: vLLM is not working with Axolotl**
> A: We currently recommend torch 2.10 for use with `vllm`. Please ensure you use the right version. For Docker, please use the `main-py3.12-cu128-2.10.0` tag (note: torch 2.10 images are built with Python 3.12). > A: We currently recommend torch 2.6.0 for use with `vllm`. Please ensure you use the right version. For Docker, please use the `main-py3.11-cu124-2.6.0` tag.
**Q: FA2 2.8.0 `undefined symbol` runtime error on CUDA 12.4** **Q: FA2 2.8.0 `undefined symbol` runtime error on CUDA 12.4**

View File

@@ -15,7 +15,7 @@ This guide covers all the ways you can install and set up Axolotl for your envir
- NVIDIA GPU (Ampere architecture or newer for `bf16` and Flash Attention) or AMD GPU - NVIDIA GPU (Ampere architecture or newer for `bf16` and Flash Attention) or AMD GPU
- Python ≥3.11 - Python ≥3.11
- PyTorch ≥2.9.1 - PyTorch ≥2.9.0
## Installation {#sec-installation} ## Installation {#sec-installation}
@@ -36,9 +36,9 @@ source $HOME/.local/bin/env
Choose your CUDA version (e.g. `cu128`, `cu130`), create a venv, and install: Choose your CUDA version (e.g. `cu128`, `cu130`), create a venv, and install:
```{.bash} ```{.bash}
export UV_TORCH_BACKEND=cu128 # or cu130 export UV_TORCH_BACKEND=cu128 # or cu130
uv venv uv venv --no-project --relocatable
source .venv/bin/activate source .venv/bin/activate
uv pip install --no-build-isolation axolotl[deepspeed] uv pip install --no-build-isolation axolotl[flash-attn,deepspeed]
``` ```
### Edge/Development Build {#sec-edge-build} ### Edge/Development Build {#sec-edge-build}
@@ -49,11 +49,12 @@ For the latest features between releases:
git clone https://github.com/axolotl-ai-cloud/axolotl.git git clone https://github.com/axolotl-ai-cloud/axolotl.git
cd axolotl cd axolotl
export UV_TORCH_BACKEND=cu128 # or cu130 export UV_TORCH_BACKEND=cu128 # or cu130
uv venv uv sync --extra flash-attn --extra deepspeed
source .venv/bin/activate source .venv/bin/activate
uv pip install --no-build-isolation -e '.[deepspeed]'
``` ```
`uv sync` creates a `.venv`, installs exact pinned versions from `uv.lock`, and sets up an editable install automatically.
### Docker {#sec-docker} ### Docker {#sec-docker}
```{.bash} ```{.bash}
@@ -131,11 +132,11 @@ source $HOME/.local/bin/env
# Create a fresh venv (recommended for a clean start) # Create a fresh venv (recommended for a clean start)
export UV_TORCH_BACKEND=cu128 # or cu130 export UV_TORCH_BACKEND=cu128 # or cu130
uv venv uv venv --no-project --relocatable
source .venv/bin/activate source .venv/bin/activate
# Reinstall axolotl # Reinstall axolotl
uv pip install --no-build-isolation axolotl[deepspeed] uv pip install --no-build-isolation axolotl[flash-attn,deepspeed]
``` ```
## Using pip (Alternative) {#sec-pip} ## Using pip (Alternative) {#sec-pip}
@@ -150,13 +151,13 @@ Follow the instructions at: [https://pytorch.org/get-started/locally/](https://p
```{.bash} ```{.bash}
pip3 install -U packaging setuptools wheel ninja pip3 install -U packaging setuptools wheel ninja
pip3 install --no-build-isolation axolotl[deepspeed] pip3 install --no-build-isolation axolotl[flash-attn,deepspeed]
``` ```
For editable/development installs: For editable/development installs:
```{.bash} ```{.bash}
pip3 install -U packaging setuptools wheel ninja pip3 install -U packaging setuptools wheel ninja
pip3 install --no-build-isolation -e '.[deepspeed]' pip3 install --no-build-isolation -e '.[flash-attn,deepspeed]'
``` ```
## Troubleshooting {#sec-troubleshooting} ## Troubleshooting {#sec-troubleshooting}

View File

@@ -15,7 +15,7 @@ Thanks to the team at LiquidAI for giving us early access to prepare for these r
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have a compatible version of Pytorch installed # Ensure you have a compatible version of Pytorch installed
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. Run one of the finetuning examples below. 2. Run one of the finetuning examples below.

View File

@@ -11,11 +11,11 @@ This guide shows how to fine-tune it with Axolotl with multi-turn conversations
Here is an example of how to install from main for pip: Here is an example of how to install from main for pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
git clone https://github.com/axolotl-ai-cloud/axolotl.git git clone https://github.com/axolotl-ai-cloud/axolotl.git
cd axolotl cd axolotl
uv pip install --no-build-isolation -e '.' uv pip install --no-build-isolation -e '.[flash-attn]'
# Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy # Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy
python scripts/cutcrossentropy_install.py | sh python scripts/cutcrossentropy_install.py | sh

View File

@@ -13,11 +13,11 @@ Thanks to the team at Arcee.ai for using Axolotl in supervised fine-tuning the A
Here is an example of how to install from main for pip: Here is an example of how to install from main for pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
git clone https://github.com/axolotl-ai-cloud/axolotl.git git clone https://github.com/axolotl-ai-cloud/axolotl.git
cd axolotl cd axolotl
uv pip install --no-build-isolation -e '.' uv pip install --no-build-isolation -e '.[flash-attn]'
# Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy # Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy
python scripts/cutcrossentropy_install.py | sh python scripts/cutcrossentropy_install.py | sh

View File

@@ -36,7 +36,12 @@
"id": "msOCO4NRmRLa" "id": "msOCO4NRmRLa"
}, },
"outputs": [], "outputs": [],
"source": "%%capture\n# This step can take ~5-10 minutes to install dependencies\n!pip install --no-build-isolation \"axolotl>=0.16.1\"\n!pip install \"cut-cross-entropy[transformers] @ git+https://github.com/axolotl-ai-cloud/ml-cross-entropy.git@fec1a88\"" "source": [
"%%capture\n",
"# This step can take ~5-10 minutes to install dependencies\n",
"!pip install --no-build-isolation axolotl[flash-attn]>=0.9.1\n",
"!pip install \"cut-cross-entropy[transformers] @ git+https://github.com/axolotl-ai-cloud/ml-cross-entropy.git@fec1a88\""
]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",

View File

@@ -15,8 +15,8 @@ Thanks to the team at MistralAI for giving us early access to prepare for this r
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. Install [Cut Cross Entropy](https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy) to reduce training VRAM usage 2. Install [Cut Cross Entropy](https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy) to reduce training VRAM usage

View File

@@ -9,8 +9,8 @@ Gemma-3n is a family of multimodal models from Google found on [HuggingFace](htt
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. In addition to Axolotl's requirements, Gemma-3n requires: 2. In addition to Axolotl's requirements, Gemma-3n requires:

View File

@@ -13,8 +13,8 @@ This guide shows how to fine-tune it with Axolotl with multi-turn conversations
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. Choose one of the following configs below for training the 20B model. (for 120B, see [below](#training-120b)) 2. Choose one of the following configs below for training the 20B model. (for 120B, see [below](#training-120b))

View File

@@ -11,11 +11,11 @@ This guide shows how to fine-tune it with Axolotl with multi-turn conversations
Here is an example of how to install from main for pip: Here is an example of how to install from main for pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.7.1 min)
git clone https://github.com/axolotl-ai-cloud/axolotl.git git clone https://github.com/axolotl-ai-cloud/axolotl.git
cd axolotl cd axolotl
uv pip install --no-build-isolation -e '.' uv pip install --no-build-isolation -e '.[flash-attn]'
# Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy # Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy
python scripts/cutcrossentropy_install.py | sh python scripts/cutcrossentropy_install.py | sh

View File

@@ -9,11 +9,11 @@ Tencent released a family of opensource models called HunYuan with varying param
Here is an example of how to install from main for pip: Here is an example of how to install from main for pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
git clone https://github.com/axolotl-ai-cloud/axolotl.git git clone https://github.com/axolotl-ai-cloud/axolotl.git
cd axolotl cd axolotl
uv pip install --no-build-isolation -e '.' uv pip install --no-build-isolation -e '.[flash-attn]'
# Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy # Install CCE https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy
python scripts/cutcrossentropy_install.py | sh python scripts/cutcrossentropy_install.py | sh

View File

@@ -13,8 +13,8 @@ Thanks to the team at MistralAI for giving us early access to prepare for these
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.7.0 min)
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. Install [Cut Cross Entropy](https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy) to reduce training VRAM usage 2. Install [Cut Cross Entropy](https://docs.axolotl.ai/docs/custom_integrations.html#cut-cross-entropy) to reduce training VRAM usage

View File

@@ -11,7 +11,7 @@ This guide shows how to fine-tune it with Axolotl with multi-turn conversations
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have a compatible version of Pytorch installed # Ensure you have a compatible version of Pytorch installed
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
# Install Cut Cross Entropy # Install Cut Cross Entropy
python scripts/cutcrossentropy_install.py | sh python scripts/cutcrossentropy_install.py | sh

View File

@@ -13,7 +13,7 @@ This guide shows how to fine-tune SmolVLM2 models with Axolotl.
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have a compatible version of Pytorch installed # Ensure you have a compatible version of Pytorch installed
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. Install an extra dependency: 2. Install an extra dependency:

View File

@@ -11,8 +11,8 @@ Thanks to the team at MistralAI for giving us early access to prepare for this r
Here is an example of how to install from pip: Here is an example of how to install from pip:
```bash ```bash
# Ensure you have Pytorch installed (Pytorch 2.9.1 min) # Ensure you have Pytorch installed (Pytorch 2.6.0 min)
uv pip install --no-build-isolation 'axolotl>=0.16.1' uv pip install --no-build-isolation 'axolotl[flash-attn]>=0.12.0'
``` ```
2. Please install the below. 2. Please install the below.

View File

@@ -12,7 +12,7 @@ requires-python = ">=3.10"
dependencies = [ dependencies = [
# Core ML stack # Core ML stack
"torch>=2.9.1", "torch>=2.6.0",
"packaging==26.0", "packaging==26.0",
"huggingface_hub>=1.1.7", "huggingface_hub>=1.1.7",
"peft>=0.19.1,<0.20.0", "peft>=0.19.1,<0.20.0",
@@ -79,7 +79,7 @@ dependencies = [
# Platform-specific (Linux only) # Platform-specific (Linux only)
"bitsandbytes==0.49.1 ; sys_platform != 'darwin'", "bitsandbytes==0.49.1 ; sys_platform != 'darwin'",
"triton>=3.4.0 ; sys_platform != 'darwin'", "triton>=3.4.0 ; sys_platform != 'darwin'",
"xformers>=0.0.33.post2 ; sys_platform != 'darwin' and platform_machine != 'aarch64'", "xformers>=0.0.23.post1 ; sys_platform != 'darwin'",
"liger-kernel==0.7.0 ; sys_platform != 'darwin'", "liger-kernel==0.7.0 ; sys_platform != 'darwin'",
"torchao==0.17.0 ; sys_platform != 'darwin' and platform_machine != 'aarch64'", "torchao==0.17.0 ; sys_platform != 'darwin' and platform_machine != 'aarch64'",

View File

@@ -370,7 +370,7 @@ class HFCausalTrainerBuilder(TrainerBuilderBase):
data_collator_kwargs = { data_collator_kwargs = {
"padding": True, # True/"longest" is the default "padding": True, # True/"longest" is the default
} }
multiple = getattr(self.cfg, "pad_to_multiple_of", None) or 64 multiple = 64
if self.cfg.pad_to_sequence_len: if self.cfg.pad_to_sequence_len:
data_collator_kwargs["pad_to_multiple_of"] = multiple * math.ceil( data_collator_kwargs["pad_to_multiple_of"] = multiple * math.ceil(
self.cfg.sequence_len / multiple self.cfg.sequence_len / multiple

View File

@@ -228,47 +228,9 @@ class HFRLTrainerBuilder(TrainerBuilderBase):
return training_args, trainer_kwargs return training_args, trainer_kwargs
def build_collator(self, **kwargs):
"""Build a data collator for preference-tuning trainers.
Returns None for RL types that provide their own collator (e.g. GRPO,
KTO), letting the trainer construct its default. For DPO/IPO/ORPO/SIMPO
returns an ``AxolotlDPODataCollatorWithPadding`` when
``pad_to_multiple_of`` is set, otherwise None (so the trainer
falls back to the TRL default).
"""
if self.cfg.rl not in (
RLType.DPO,
RLType.IPO,
RLType.ORPO,
RLType.SIMPO,
):
return None
pad_to_multiple_of = getattr(self.cfg, "pad_to_multiple_of", None)
if not pad_to_multiple_of:
return None
from axolotl.utils.collators.dpo import AxolotlDPODataCollatorWithPadding
LOG.info(
f"Using AxolotlDPODataCollatorWithPadding with pad_to_multiple_of="
f"{pad_to_multiple_of}"
)
is_enc_dec = getattr(self.model.config, "is_encoder_decoder", False)
return AxolotlDPODataCollatorWithPadding(
pad_token_id=self.tokenizer.pad_token_id,
is_encoder_decoder=is_enc_dec,
pad_to_multiple_of=pad_to_multiple_of,
**kwargs,
)
def build(self, total_num_steps): def build(self, total_num_steps):
training_args, trainer_kwargs = self._build_training_arguments(total_num_steps) training_args, trainer_kwargs = self._build_training_arguments(total_num_steps)
if (data_collator := self.build_collator()) is not None:
trainer_kwargs["data_collator"] = data_collator
if self.eval_dataset: if self.eval_dataset:
trainer_kwargs["eval_dataset"] = self.eval_dataset trainer_kwargs["eval_dataset"] = self.eval_dataset
if ( if (

View File

@@ -11,7 +11,7 @@ kd_ce_alpha: 0.1
kd_alpha: 0.9 kd_alpha: 0.9
kd_temperature: 1.0 kd_temperature: 1.0
torch_compile: True # recommended to reduce vram torch_compile: True # torch>=2.6.0, recommended to reduce vram
datasets: datasets:
- path: ... - path: ...

View File

@@ -407,10 +407,7 @@ def selective_log_softmax(logits, index) -> torch.Tensor:
K = index.shape[-1] K = index.shape[-1]
original_index_shape = index.shape original_index_shape = index.shape
try: flat_logits = logits.reshape(-1, V).contiguous()
flat_logits = logits.view(-1, V)
except RuntimeError:
flat_logits = logits.reshape(-1, V).contiguous()
flat_index = index.reshape(-1, K).contiguous() flat_index = index.reshape(-1, K).contiguous()
BLOCK_V = 4096 BLOCK_V = 4096

View File

@@ -6,7 +6,6 @@ from .batching import (
PretrainingBatchSamplerDataCollatorForSeq2Seq, PretrainingBatchSamplerDataCollatorForSeq2Seq,
V2BatchSamplerDataCollatorForSeq2Seq, V2BatchSamplerDataCollatorForSeq2Seq,
) )
from .dpo import AxolotlDPODataCollatorWithPadding
from .mamba import MambaDataCollator from .mamba import MambaDataCollator
__all__ = [ __all__ = [
@@ -14,6 +13,5 @@ __all__ = [
"BatchSamplerDataCollatorForSeq2Seq", "BatchSamplerDataCollatorForSeq2Seq",
"V2BatchSamplerDataCollatorForSeq2Seq", "V2BatchSamplerDataCollatorForSeq2Seq",
"PretrainingBatchSamplerDataCollatorForSeq2Seq", "PretrainingBatchSamplerDataCollatorForSeq2Seq",
"AxolotlDPODataCollatorWithPadding",
"MambaDataCollator", "MambaDataCollator",
] ]

View File

@@ -1,128 +0,0 @@
"""DPO/ORPO/IPO/KTO data collator with pad_to_multiple_of support.
Extends TRL's DPODataCollatorWithPadding to round padded sequence lengths
up to a fixed multiple. This stabilizes Triton autotune caches for kernels
that key on sequence length (e.g. fla's linear attention kernels used by
Qwen3.5), which otherwise re-autotune on every distinct batch length.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import torch
from torch.nn.utils.rnn import pad_sequence
from trl.experimental.utils import DPODataCollatorWithPadding
from trl.trainer.utils import pad
def _round_up(length: int, multiple: int) -> int:
return ((length + multiple - 1) // multiple) * multiple
@dataclass
class AxolotlDPODataCollatorWithPadding(DPODataCollatorWithPadding):
"""DPO data collator that pads to a multiple of ``pad_to_multiple_of``.
Args:
pad_token_id: Tokenizer pad token id (inherited).
is_encoder_decoder: Whether the model is encoder-decoder (inherited).
pad_to_multiple_of: If set, padded lengths are rounded up to this
multiple. Helps stabilize Triton autotune caches.
"""
pad_to_multiple_of: int | None = None
def __call__(self, features: list[dict[str, Any]]) -> dict[str, Any]:
pad_to_mult = self.pad_to_multiple_of
padded_batch: dict[str, Any] = {}
for k in features[0].keys():
if k.endswith(
("_input_ids", "_attention_mask", "_labels", "_pixel_values")
):
if self.is_encoder_decoder:
if k.endswith("_pixel_values"):
to_pad = [
torch.tensor(ex[k], dtype=torch.float32) for ex in features
]
else:
to_pad = [torch.LongTensor(ex[k]) for ex in features]
if k.startswith("prompt") and k.endswith("input_ids"):
if self.pad_token_id is None:
raise ValueError(
"Padding is enabled, but the tokenizer is not configured with a padding token."
)
padding_value = self.pad_token_id
elif k.endswith("_attention_mask"):
padding_value = 0
elif k.endswith("_pixel_values"):
padding_value = 0
elif (
k.startswith(("chosen", "rejected", "completion"))
or "decoder" in k
):
padding_value = -100
else:
raise ValueError(f"Unexpected key in batch '{k}'")
padded = pad_sequence(
to_pad, batch_first=True, padding_value=padding_value
)
if pad_to_mult:
cur = padded.shape[1]
target = _round_up(cur, pad_to_mult)
if target > cur:
extra = target - cur
pad_shape = list(padded.shape)
pad_shape[1] = extra
filler = torch.full(
pad_shape,
padding_value,
dtype=padded.dtype,
device=padded.device,
)
padded = torch.cat([padded, filler], dim=1)
padded_batch[k] = padded
else:
if k.endswith("_input_ids"):
if self.pad_token_id is None:
raise ValueError(
"Padding is enabled, but the tokenizer is not configured with a padding token."
)
padding_value = self.pad_token_id
elif k.endswith("_labels"):
padding_value = -100
elif k.endswith("_attention_mask"):
padding_value = 0
elif k.endswith("_pixel_values"):
padding_value = 0
else:
raise ValueError(f"Unexpected key in batch '{k}'")
padding_side = (
"left"
if k in ("prompt_input_ids", "prompt_attention_mask")
else "right"
)
dtype = (
torch.float32 if k.endswith("_pixel_values") else torch.int64
)
to_pad = [torch.tensor(ex[k], dtype=dtype) for ex in features]
# trl.pad() natively supports pad_to_multiple_of
padded_batch[k] = pad(
to_pad,
padding_value=padding_value,
padding_side=padding_side,
pad_to_multiple_of=pad_to_mult,
)
elif k.endswith("_logps"):
padded_batch[k] = torch.tensor([ex[k] for ex in features])
else:
padded_batch[k] = [ex[k] for ex in features]
return padded_batch

View File

@@ -673,12 +673,6 @@ class AxolotlInputConfig(
"description": "Pad inputs so each step uses constant sized buffers. This will reduce memory fragmentation and may prevent OOMs, by re-using memory more efficiently. Defaults to True if `sample_packing` enabled" "description": "Pad inputs so each step uses constant sized buffers. This will reduce memory fragmentation and may prevent OOMs, by re-using memory more efficiently. Defaults to True if `sample_packing` enabled"
}, },
) )
pad_to_multiple_of: int | None = Field(
default=None,
json_schema_extra={
"description": ("Pad each batch to a multiple of this value.")
},
)
curriculum_sampling: bool | None = Field( curriculum_sampling: bool | None = Field(
default=None, default=None,
json_schema_extra={ json_schema_extra={
@@ -1016,7 +1010,7 @@ class AxolotlInputConfig(
torch_compile: Literal["auto"] | bool | None = Field( torch_compile: Literal["auto"] | bool | None = Field(
default=None, default=None,
json_schema_extra={ json_schema_extra={
"description": "Whether to use torch.compile and which backend to use." "description": "Whether to use torch.compile and which backend to use. setting to `auto` will enable torch compile when torch>=2.6.0"
}, },
) )
torch_compile_backend: str | None = Field( torch_compile_backend: str | None = Field(

View File

@@ -119,15 +119,49 @@ def download_smollm2_135m_gptq_model():
@pytest.fixture(scope="session", autouse=True) @pytest.fixture(scope="session", autouse=True)
def download_qwen_2_5_half_billion_model(): def download_qwen3_half_billion_model():
# download the model # download the model (still used as the KD teacher in tests/e2e/integrations/test_kd.py)
snapshot_download_w_retry("Qwen/Qwen2.5-0.5B", repo_type="model") snapshot_download_w_retry("Qwen/Qwen3-0.6B", repo_type="model")
@pytest.fixture(scope="session", autouse=True) @pytest.fixture(scope="session", autouse=True)
def download_qwen3_half_billion_model(): def download_tiny_llama_model():
# download the model snapshot_download_w_retry("axolotl-ai-co/tiny-llama-50m", repo_type="model")
snapshot_download_w_retry("Qwen/Qwen3-0.6B", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_mistral_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-mistral-25m", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_mixtral_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-mixtral-30m", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_phi_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-phi-64m", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_falcon_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-falcon-42m", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_qwen2_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-qwen2-129m", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_qwen3_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-qwen3-129m", repo_type="model")
@pytest.fixture(scope="session", autouse=True)
def download_tiny_gemma2_model():
snapshot_download_w_retry("axolotl-ai-co/tiny-gemma2-137m", repo_type="model")
@pytest.fixture(scope="session", autouse=True) @pytest.fixture(scope="session", autouse=True)
@@ -620,7 +654,15 @@ def fixture_min_base_cfg():
) )
def test_load_fixtures( def test_load_fixtures(
download_smollm2_135m_model, download_smollm2_135m_model,
download_qwen_2_5_half_billion_model, download_qwen3_half_billion_model,
download_tiny_llama_model,
download_tiny_mistral_model,
download_tiny_mixtral_model,
download_tiny_phi_model,
download_tiny_falcon_model,
download_tiny_qwen2_model,
download_tiny_qwen3_model,
download_tiny_gemma2_model,
download_tatsu_lab_alpaca_dataset, download_tatsu_lab_alpaca_dataset,
download_mhenrichsen_alpaca_2k_dataset, download_mhenrichsen_alpaca_2k_dataset,
download_mhenrichsen_alpaca_2k_w_revision_dataset, download_mhenrichsen_alpaca_2k_w_revision_dataset,

View File

@@ -10,7 +10,10 @@ from axolotl.utils import get_pytorch_version
from axolotl.utils.config import normalize_config, prepare_plugins, validate_config from axolotl.utils.config import normalize_config, prepare_plugins, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from tests.e2e.utils import check_model_output_exists from tests.e2e.utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
)
@pytest.fixture() @pytest.fixture()
@@ -35,13 +38,16 @@ def min_cfg(temp_dir):
"num_epochs": 1, "num_epochs": 1,
"micro_batch_size": 8, "micro_batch_size": 8,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"learning_rate": 0.00001, "learning_rate": 5e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"output_dir": temp_dir, "output_dir": temp_dir,
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 10, "max_steps": 40,
"warmup_steps": 5,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
@@ -64,11 +70,18 @@ class TestCutCrossEntropyIntegration:
else: else:
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=2.2,
max_final=2.0,
)
def test_qwen2_w_cce(self, temp_dir): def test_qwen2_w_cce(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"plugins": [ "plugins": [
"axolotl.integrations.cut_cross_entropy.CutCrossEntropyPlugin", "axolotl.integrations.cut_cross_entropy.CutCrossEntropyPlugin",
], ],
@@ -87,13 +100,15 @@ class TestCutCrossEntropyIntegration:
"num_epochs": 1, "num_epochs": 1,
"micro_batch_size": 4, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"output_dir": temp_dir, "output_dir": temp_dir,
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 10, "max_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -108,6 +123,13 @@ class TestCutCrossEntropyIntegration:
else: else:
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"attention_type", "attention_type",
@@ -136,3 +158,10 @@ class TestCutCrossEntropyIntegration:
else: else:
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=2.2,
max_final=2.0,
)

View File

@@ -24,7 +24,7 @@ from axolotl.monkeypatch.lora_kernels import (
) )
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
MODEL_NAME = "Qwen/Qwen3-0.6B" MODEL_NAME = "axolotl-ai-co/tiny-qwen3-129m"
DEVICE = "cuda" DEVICE = "cuda"
DTYPE = torch.bfloat16 DTYPE = torch.bfloat16

View File

@@ -1,23 +1,22 @@
"""Test module for DistMuon optimizer with FSDP2 multi-GPU functionality.""" """Test module for DistMuon optimizer with FSDP2 multi-GPU functionality."""
import os
from pathlib import Path from pathlib import Path
import torch
import yaml import yaml
from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils import execute_subprocess_async
from tbparse import SummaryReader
from transformers.testing_utils import get_torch_dist_unique_port from transformers.testing_utils import get_torch_dist_unique_port
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from tests.e2e.utils import most_recent_subdir, require_torch_2_7_0 from tests.e2e.utils import check_tensorboard_loss_decreased, require_torch_2_7_0
AXOLOTL_ROOT = Path(__file__).parent.parent.parent.parent AXOLOTL_ROOT = Path(__file__).parent.parent.parent.parent
def verify_training_success(temp_dir): def verify_training_success(temp_dir):
"""Verify that training completed successfully by checking artifacts and loss.""" """Verify that training completed successfully artifacts, no-NaN, loss
stayed in qwen2-pretraining scale (tiny-qwen2-129m final pretrain CE ~3.92).
"""
output_path = Path(temp_dir) output_path = Path(temp_dir)
model_files = list(output_path.glob("*.bin")) + list( model_files = list(output_path.glob("*.bin")) + list(
@@ -30,19 +29,13 @@ def verify_training_success(temp_dir):
"No checkpoint files found - training may have failed" "No checkpoint files found - training may have failed"
) )
tb_log_path = most_recent_subdir(temp_dir + "/runs") check_tensorboard_loss_decreased(
if tb_log_path: temp_dir + "/runs",
event_files = sorted(os.listdir(tb_log_path)) initial_window=10,
if event_files: final_window=10,
event_file = os.path.join(tb_log_path, event_files[0]) max_initial=5.0,
reader = SummaryReader(event_file) max_final=4.7,
df = reader.scalars )
train_loss_df = df[df.tag == "train/train_loss"]
if len(train_loss_df) > 0:
final_loss = train_loss_df.value.values[-1]
assert not torch.isnan(torch.tensor(final_loss)), (
f"Training loss is NaN: {final_loss}"
)
class TestDistMuon: class TestDistMuon:
@@ -52,7 +45,7 @@ class TestDistMuon:
def test_fft_sft(self, temp_dir): def test_fft_sft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -63,11 +56,12 @@ class TestDistMuon:
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.02, "learning_rate": 2e-3,
"optimizer": "muon", "optimizer": "muon",
"weight_decay": 0.01, "weight_decay": 0.01,
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
@@ -82,6 +76,9 @@ class TestDistMuon:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
} }
) )
@@ -109,7 +106,7 @@ class TestDistMuon:
def test_lora_sft(self, temp_dir): def test_lora_sft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -122,14 +119,15 @@ class TestDistMuon:
"adapter": "lora", "adapter": "lora",
"lora_r": 8, "lora_r": 8,
"lora_alpha": 16, "lora_alpha": 16,
"lora_dropout": 0.05, "lora_dropout": 0.0,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.02, "learning_rate": 2e-3,
"optimizer": "muon", "optimizer": "muon",
"weight_decay": 0.01, "weight_decay": 0.01,
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
@@ -144,6 +142,9 @@ class TestDistMuon:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
} }
) )

View File

@@ -1,24 +1,23 @@
"""Test module for FSDP1 multi-GPU functionality.""" """Test module for FSDP1 multi-GPU functionality."""
import os
from pathlib import Path from pathlib import Path
import pytest import pytest
import torch
import yaml import yaml
from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils import execute_subprocess_async
from tbparse import SummaryReader
from transformers.testing_utils import get_torch_dist_unique_port from transformers.testing_utils import get_torch_dist_unique_port
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from tests.e2e.utils import most_recent_subdir from tests.e2e.utils import check_tensorboard_loss_decreased
AXOLOTL_ROOT = Path(__file__).parent.parent.parent.parent AXOLOTL_ROOT = Path(__file__).parent.parent.parent.parent
def verify_training_success(temp_dir): def verify_training_success(temp_dir):
"""Verify that training completed successfully by checking artifacts and loss.""" """Verify that training completed successfully artifacts, no-NaN, loss
stayed in qwen2-pretraining scale (tiny-qwen2-129m final pretrain CE ~3.92).
"""
output_path = Path(temp_dir) output_path = Path(temp_dir)
model_files = list(output_path.glob("*.bin")) + list( model_files = list(output_path.glob("*.bin")) + list(
@@ -31,19 +30,13 @@ def verify_training_success(temp_dir):
"No checkpoint files found - training may have failed" "No checkpoint files found - training may have failed"
) )
tb_log_path = most_recent_subdir(temp_dir + "/runs") check_tensorboard_loss_decreased(
if tb_log_path: temp_dir + "/runs",
event_files = sorted(os.listdir(tb_log_path)) initial_window=10,
if event_files: final_window=10,
event_file = os.path.join(tb_log_path, event_files[0]) max_initial=5.0,
reader = SummaryReader(event_file) max_final=4.7,
df = reader.scalars )
train_loss_df = df[df.tag == "train/train_loss"]
if len(train_loss_df) > 0:
final_loss = train_loss_df.value.values[-1]
assert not torch.isnan(torch.tensor(final_loss)), (
f"Training loss is NaN: {final_loss}"
)
class TestFSDP1: class TestFSDP1:
@@ -56,7 +49,7 @@ class TestFSDP1:
def test_fft_sft(self, temp_dir, fsdp_cpu_ram_efficient_loading): def test_fft_sft(self, temp_dir, fsdp_cpu_ram_efficient_loading):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -67,11 +60,12 @@ class TestFSDP1:
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -87,6 +81,9 @@ class TestFSDP1:
"fsdp_use_orig_params": False, "fsdp_use_orig_params": False,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
} }
) )
@@ -126,7 +123,7 @@ class TestFSDP1:
def test_lora_sft(self, temp_dir, adapter_config): def test_lora_sft(self, temp_dir, adapter_config):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -140,14 +137,15 @@ class TestFSDP1:
"load_in_4bit": adapter_config["load_in_4bit"], "load_in_4bit": adapter_config["load_in_4bit"],
"lora_r": 8, "lora_r": 8,
"lora_alpha": 16, "lora_alpha": 16,
"lora_dropout": 0.05, "lora_dropout": 0.0,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -163,6 +161,9 @@ class TestFSDP1:
"fsdp_use_orig_params": False, "fsdp_use_orig_params": False,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
} }
) )
@@ -190,7 +191,7 @@ class TestFSDP1:
def test_dpo_fft(self, temp_dir): def test_dpo_fft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"rl": "dpo", "rl": "dpo",
@@ -203,11 +204,11 @@ class TestFSDP1:
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 20,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -223,6 +224,9 @@ class TestFSDP1:
"fsdp_use_orig_params": False, "fsdp_use_orig_params": False,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
} }
) )
@@ -262,7 +266,7 @@ class TestFSDP1:
def test_dpo_lora(self, temp_dir, adapter_config): def test_dpo_lora(self, temp_dir, adapter_config):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"load_in_4bit": adapter_config["load_in_4bit"], "load_in_4bit": adapter_config["load_in_4bit"],
"rl": "dpo", "rl": "dpo",
"chat_template": "chatml", "chat_template": "chatml",
@@ -281,11 +285,11 @@ class TestFSDP1:
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 20,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -301,6 +305,9 @@ class TestFSDP1:
"fsdp_use_orig_params": False, "fsdp_use_orig_params": False,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": "auto", "bf16": "auto",
"tf32": True, "tf32": True,
} }

View File

@@ -1,24 +1,23 @@
"""Test module for FSDP2 multi-GPU functionality.""" """Test module for FSDP2 multi-GPU functionality."""
import os
from pathlib import Path from pathlib import Path
import pytest import pytest
import torch
import yaml import yaml
from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils import execute_subprocess_async
from tbparse import SummaryReader
from transformers.testing_utils import get_torch_dist_unique_port from transformers.testing_utils import get_torch_dist_unique_port
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from tests.e2e.utils import most_recent_subdir, require_torch_2_7_0 from tests.e2e.utils import check_tensorboard_loss_decreased, require_torch_2_7_0
AXOLOTL_ROOT = Path(__file__).parent.parent.parent.parent AXOLOTL_ROOT = Path(__file__).parent.parent.parent.parent
def verify_training_success(temp_dir): def verify_training_success(temp_dir):
"""Verify that training completed successfully by checking artifacts and loss.""" """Verify that training completed successfully artifacts, no-NaN, loss
stayed in qwen2-pretraining scale (tiny-qwen2-129m final pretrain CE ~3.92).
"""
output_path = Path(temp_dir) output_path = Path(temp_dir)
model_files = list(output_path.glob("*.bin")) + list( model_files = list(output_path.glob("*.bin")) + list(
@@ -31,19 +30,13 @@ def verify_training_success(temp_dir):
"No checkpoint files found - training may have failed" "No checkpoint files found - training may have failed"
) )
tb_log_path = most_recent_subdir(temp_dir + "/runs") check_tensorboard_loss_decreased(
if tb_log_path: temp_dir + "/runs",
event_files = sorted(os.listdir(tb_log_path)) initial_window=10,
if event_files: final_window=10,
event_file = os.path.join(tb_log_path, event_files[0]) max_initial=5.0,
reader = SummaryReader(event_file) max_final=4.7,
df = reader.scalars )
train_loss_df = df[df.tag == "train/train_loss"]
if len(train_loss_df) > 0:
final_loss = train_loss_df.value.values[-1]
assert not torch.isnan(torch.tensor(final_loss)), (
f"Training loss is NaN: {final_loss}"
)
class TestFSDP2: class TestFSDP2:
@@ -57,7 +50,7 @@ class TestFSDP2:
def test_fft_sft(self, temp_dir, fsdp_cpu_ram_efficient_loading): def test_fft_sft(self, temp_dir, fsdp_cpu_ram_efficient_loading):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -68,11 +61,12 @@ class TestFSDP2:
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -86,6 +80,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
} }
) )
@@ -114,7 +111,7 @@ class TestFSDP2:
def test_lora_sft(self, temp_dir, peft_use_dora): def test_lora_sft(self, temp_dir, peft_use_dora):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -128,14 +125,15 @@ class TestFSDP2:
"adapter": "lora", "adapter": "lora",
"lora_r": 8, "lora_r": 8,
"lora_alpha": 16, "lora_alpha": 16,
"lora_dropout": 0.05, "lora_dropout": 0.0,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -149,6 +147,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
# explicitly disable LORA kernels, as they may be auto-enabled # explicitly disable LORA kernels, as they may be auto-enabled
"lora_mlp_kernel": False, "lora_mlp_kernel": False,
@@ -180,7 +181,7 @@ class TestFSDP2:
def test_lora_sft_kernels(self, temp_dir): def test_lora_sft_kernels(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -195,11 +196,12 @@ class TestFSDP2:
"lora_alpha": 16, "lora_alpha": 16,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -213,6 +215,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
"lora_mlp_kernel": True, "lora_mlp_kernel": True,
"lora_qkv_kernel": True, "lora_qkv_kernel": True,
@@ -243,7 +248,7 @@ class TestFSDP2:
def test_qlora_sft(self, temp_dir): def test_qlora_sft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -257,14 +262,15 @@ class TestFSDP2:
"adapter": "qlora", "adapter": "qlora",
"lora_r": 8, "lora_r": 8,
"lora_alpha": 16, "lora_alpha": 16,
"lora_dropout": 0.05, "lora_dropout": 0.0,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -278,6 +284,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
} }
) )
@@ -305,7 +314,7 @@ class TestFSDP2:
def test_qlora_sft_kernels(self, temp_dir): def test_qlora_sft_kernels(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -321,11 +330,12 @@ class TestFSDP2:
"lora_alpha": 16, "lora_alpha": 16,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 80,
"warmup_steps": 5,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -339,6 +349,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
"bf16": True, "bf16": True,
"lora_mlp_kernel": True, "lora_mlp_kernel": True,
"lora_qkv_kernel": True, "lora_qkv_kernel": True,
@@ -370,7 +383,7 @@ class TestFSDP2:
def test_dpo_fft(self, temp_dir): def test_dpo_fft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"rl": "dpo", "rl": "dpo",
@@ -383,11 +396,11 @@ class TestFSDP2:
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 20,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -401,6 +414,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
} }
) )
@@ -428,7 +444,7 @@ class TestFSDP2:
def test_dpo_lora(self, temp_dir): def test_dpo_lora(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"rl": "dpo", "rl": "dpo",
"chat_template": "chatml", "chat_template": "chatml",
@@ -445,11 +461,11 @@ class TestFSDP2:
"lora_dropout": 0.05, "lora_dropout": 0.05,
"lora_target_linear": True, "lora_target_linear": True,
"num_epochs": 1, "num_epochs": 1,
"max_steps": 2, "max_steps": 20,
"micro_batch_size": 2, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-3,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
@@ -463,6 +479,9 @@ class TestFSDP2:
"reshard_after_forward": True, "reshard_after_forward": True,
}, },
"use_tensorboard": True, "use_tensorboard": True,
"seed": 42,
"sample_packing": True,
"pad_to_sequence_len": True,
} }
) )

View File

@@ -40,7 +40,7 @@ def _run_training(temp_dir, cfg):
def _base_lora_fsdp2_config(temp_dir, **overrides): def _base_lora_fsdp2_config(temp_dir, **overrides):
"""Base config for LoRA + FSDP2 + kernel tests.""" """Base config for LoRA + FSDP2 + kernel tests."""
cfg = { cfg = {
"base_model": "Qwen/Qwen3-0.6B", "base_model": "axolotl-ai-co/tiny-qwen3-129m",
"sequence_len": 512, "sequence_len": 512,
"val_set_size": 0.0, "val_set_size": 0.0,
"datasets": [ "datasets": [

View File

@@ -8,7 +8,7 @@ from accelerate.test_utils import execute_subprocess_async, get_torch_dist_uniqu
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from tests.e2e.utils import check_tensorboard, require_torch_2_7_0 from tests.e2e.utils import check_tensorboard_loss_decreased, require_torch_2_7_0
class TestTensorParallel: class TestTensorParallel:
@@ -21,7 +21,7 @@ class TestTensorParallel:
def test_fft_sft(self, temp_dir): def test_fft_sft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [
@@ -63,6 +63,6 @@ class TestTensorParallel:
] ]
) )
check_tensorboard( check_tensorboard_loss_decreased(
temp_dir + "/runs", "train/train_loss", 1.0, "Train Loss (%s) is too high" temp_dir + "/runs", max_initial=5.0, max_final=4.7
) )

View File

@@ -32,12 +32,12 @@ from axolotl.utils.dict import DictDefault
MODEL_CONFIGS = [ MODEL_CONFIGS = [
{ {
"name": "trl-internal-testing/tiny-MistralForCausalLM-0.2", "name": "axolotl-ai-co/tiny-mistral-25m",
"expected_activation": apply_lora_mlp_swiglu, "expected_activation": apply_lora_mlp_swiglu,
"dtype": torch.float16, "dtype": torch.float16,
}, },
{ {
"name": "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", "name": "axolotl-ai-co/tiny-qwen2-129m",
"expected_activation": apply_lora_mlp_swiglu, "expected_activation": apply_lora_mlp_swiglu,
"dtype": torch.float16, "dtype": torch.float16,
}, },
@@ -47,7 +47,7 @@ MODEL_CONFIGS = [
"dtype": torch.float32, "dtype": torch.float32,
}, },
{ {
"name": "trl-internal-testing/tiny-Gemma2ForCausalLM", "name": "axolotl-ai-co/tiny-gemma2-137m",
"expected_activation": apply_lora_mlp_geglu, "expected_activation": apply_lora_mlp_geglu,
"dtype": torch.float16, "dtype": torch.float16,
}, },
@@ -159,7 +159,7 @@ def test_swiglu_mlp_integration(small_llama_model):
def test_geglu_model_integration(): def test_geglu_model_integration():
"""Test GeGLU activation with Gemma model.""" """Test GeGLU activation with Gemma model."""
model = AutoModelForCausalLM.from_pretrained( model = AutoModelForCausalLM.from_pretrained(
"trl-internal-testing/tiny-Gemma2ForCausalLM", "axolotl-ai-co/tiny-gemma2-137m",
dtype=torch.float16, dtype=torch.float16,
device_map="cuda:0", device_map="cuda:0",
) )

View File

@@ -4,14 +4,16 @@ E2E tests for falcon
import unittest import unittest
import pytest
from axolotl.common.datasets import load_datasets from axolotl.common.datasets import load_datasets
from axolotl.train import train from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from ..utils import check_model_output_exists, with_temp_dir from ..utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestFalconPatched(unittest.TestCase): class TestFalconPatched(unittest.TestCase):
@@ -19,13 +21,12 @@ class TestFalconPatched(unittest.TestCase):
Test case for Falcon models Test case for Falcon models
""" """
@pytest.mark.skip(reason="no tiny models for testing with safetensors")
@with_temp_dir @with_temp_dir
def test_qlora(self, temp_dir): def test_qlora(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "illuin/tiny-random-FalconForCausalLM", "base_model": "axolotl-ai-co/tiny-falcon-42m",
"flash_attention": True, "flash_attention": False,
"sample_packing": True, "sample_packing": True,
"sequence_len": 2048, "sequence_len": 2048,
"load_in_4bit": True, "load_in_4bit": True,
@@ -47,17 +48,20 @@ class TestFalconPatched(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -66,14 +70,20 @@ class TestFalconPatched(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=6.0,
max_final=4.7,
)
@pytest.mark.skip(reason="no tiny models for testing with safetensors")
@with_temp_dir @with_temp_dir
def test_ft(self, temp_dir): def test_ft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "illuin/tiny-random-FalconForCausalLM", "base_model": "axolotl-ai-co/tiny-falcon-42m",
"flash_attention": True, "flash_attention": False,
"sample_packing": True, "sample_packing": True,
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.05, "val_set_size": 0.05,
@@ -88,17 +98,20 @@ class TestFalconPatched(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -107,3 +120,10 @@ class TestFalconPatched(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=6.0,
max_final=4.7,
)

View File

@@ -9,7 +9,12 @@ from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from ..utils import check_model_output_exists, require_torch_2_6_0, with_temp_dir from ..utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
require_torch_2_6_0,
with_temp_dir,
)
class TestMistral(unittest.TestCase): class TestMistral(unittest.TestCase):
@@ -22,7 +27,7 @@ class TestMistral(unittest.TestCase):
def test_lora_packing(self, temp_dir): def test_lora_packing(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "trl-internal-testing/tiny-MistralForCausalLM-0.2", "base_model": "axolotl-ai-co/tiny-mistral-25m",
"flash_attention": True, "flash_attention": True,
"sample_packing": True, "sample_packing": True,
"sequence_len": 1024, "sequence_len": 1024,
@@ -45,17 +50,20 @@ class TestMistral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 5, "max_steps": 50,
"save_steps": 3, "logging_steps": 1,
"eval_steps": 4, "save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -64,12 +72,19 @@ class TestMistral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.5,
max_final=4.3,
)
@with_temp_dir @with_temp_dir
def test_ft_packing(self, temp_dir): def test_ft_packing(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "trl-internal-testing/tiny-MistralForCausalLM-0.2", "base_model": "axolotl-ai-co/tiny-mistral-25m",
"flash_attention": True, "flash_attention": True,
"sample_packing": True, "sample_packing": True,
"sequence_len": 1024, "sequence_len": 1024,
@@ -86,17 +101,20 @@ class TestMistral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 5, "max_steps": 50,
"save_steps": 3, "logging_steps": 1,
"eval_steps": 4, "save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -105,3 +123,10 @@ class TestMistral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.5,
max_final=4.3,
)

View File

@@ -9,7 +9,11 @@ from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from ..utils import check_model_output_exists, with_temp_dir from ..utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestMixtral(unittest.TestCase): class TestMixtral(unittest.TestCase):
@@ -21,8 +25,7 @@ class TestMixtral(unittest.TestCase):
def test_qlora(self, temp_dir): def test_qlora(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": True, "flash_attention": True,
"sample_packing": True, "sample_packing": True,
"sequence_len": 2048, "sequence_len": 2048,
@@ -30,7 +33,7 @@ class TestMixtral(unittest.TestCase):
"adapter": "qlora", "adapter": "qlora",
"lora_r": 16, "lora_r": 16,
"lora_alpha": 32, "lora_alpha": 32,
"lora_dropout": 0.1, "lora_dropout": 0.0,
"lora_target_linear": True, "lora_target_linear": True,
"val_set_size": 0.05, "val_set_size": 0.05,
"special_tokens": {}, "special_tokens": {},
@@ -41,17 +44,21 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 3e-3,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 5, "max_steps": 80,
"save_steps": 3, "warmup_steps": 5,
"eval_steps": 4, "logging_steps": 1,
"save_steps": 80,
"eval_steps": 80,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -60,13 +67,19 @@ class TestMixtral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=10,
final_window=10,
max_initial=6.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_ft(self, temp_dir): def test_ft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": True, "flash_attention": True,
"sample_packing": True, "sample_packing": True,
"sequence_len": 2048, "sequence_len": 2048,
@@ -79,17 +92,21 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 5e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 5, "max_steps": 80,
"save_steps": 3, "warmup_steps": 5,
"eval_steps": 4, "logging_steps": 1,
"save_steps": 80,
"eval_steps": 80,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -98,3 +115,10 @@ class TestMixtral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=6.0,
max_final=4.7,
)

View File

@@ -22,8 +22,7 @@ class TestModelPatches(unittest.TestCase):
def test_mixtral_multipack(self, temp_dir): def test_mixtral_multipack(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": True, "flash_attention": True,
"sample_packing": True, "sample_packing": True,
"sequence_len": 2048, "sequence_len": 2048,
@@ -57,7 +56,7 @@ class TestModelPatches(unittest.TestCase):
def test_mistral_multipack(self, temp_dir): def test_mistral_multipack(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "trl-internal-testing/tiny-MistralForCausalLM-0.2", "base_model": "axolotl-ai-co/tiny-mistral-25m",
"flash_attention": True, "flash_attention": True,
"sample_packing": True, "sample_packing": True,
"sequence_len": 2048, "sequence_len": 2048,

View File

@@ -9,7 +9,11 @@ from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from ..utils import check_model_output_exists, with_temp_dir from ..utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestPhiMultipack(unittest.TestCase): class TestPhiMultipack(unittest.TestCase):
@@ -21,7 +25,7 @@ class TestPhiMultipack(unittest.TestCase):
def test_ft_packed(self, temp_dir): def test_ft_packed(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "microsoft/phi-1_5", "base_model": "axolotl-ai-co/tiny-phi-64m",
"model_type": "PhiForCausalLM", "model_type": "PhiForCausalLM",
"tokenizer_type": "AutoTokenizer", "tokenizer_type": "AutoTokenizer",
"sequence_len": 1024, "sequence_len": 1024,
@@ -43,17 +47,20 @@ class TestPhiMultipack(unittest.TestCase):
"dataset_shard_num": 10, "dataset_shard_num": 10,
"dataset_shard_idx": 0, "dataset_shard_idx": 0,
"num_epochs": 1, "num_epochs": 1,
"micro_batch_size": 1, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 5, "max_steps": 50,
"eval_steps": 3, "logging_steps": 1,
"save_steps": 4, "eval_steps": 50,
"save_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
@@ -63,12 +70,19 @@ class TestPhiMultipack(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=6.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_qlora_packed(self, temp_dir): def test_qlora_packed(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "microsoft/phi-1_5", "base_model": "axolotl-ai-co/tiny-phi-64m",
"model_type": "PhiForCausalLM", "model_type": "PhiForCausalLM",
"tokenizer_type": "AutoTokenizer", "tokenizer_type": "AutoTokenizer",
"sequence_len": 1024, "sequence_len": 1024,
@@ -94,17 +108,20 @@ class TestPhiMultipack(unittest.TestCase):
"dataset_shard_num": 10, "dataset_shard_num": 10,
"dataset_shard_idx": 0, "dataset_shard_idx": 0,
"num_epochs": 1, "num_epochs": 1,
"micro_batch_size": 1, "micro_batch_size": 2,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 5, "max_steps": 50,
"eval_steps": 3, "logging_steps": 1,
"save_steps": 4, "eval_steps": 50,
"save_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
@@ -114,3 +131,10 @@ class TestPhiMultipack(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=6.0,
max_final=4.7,
)

View File

@@ -18,7 +18,7 @@ from transformers import AutoModelForCausalLM
# Import the actual trainer methods we want to test # Import the actual trainer methods we want to test
from axolotl.core.trainers.grpo.async_trainer import AsyncGRPOTrainer from axolotl.core.trainers.grpo.async_trainer import AsyncGRPOTrainer
MODEL_NAME = "Qwen/Qwen3-0.6B" MODEL_NAME = "axolotl-ai-co/tiny-qwen3-129m"
def _fix_patched_attention(model): def _fix_patched_attention(model):

View File

@@ -4,14 +4,16 @@ E2E tests for falcon
import unittest import unittest
import pytest
from axolotl.common.datasets import load_datasets from axolotl.common.datasets import load_datasets
from axolotl.train import train from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from .utils import check_model_output_exists, with_temp_dir from .utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestFalcon(unittest.TestCase): class TestFalcon(unittest.TestCase):
@@ -19,13 +21,12 @@ class TestFalcon(unittest.TestCase):
Test case for falcon Test case for falcon
""" """
@pytest.mark.skip(reason="no tiny models for testing with safetensors")
@with_temp_dir @with_temp_dir
def test_lora(self, temp_dir): def test_lora(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "illuin/tiny-random-FalconForCausalLM", "base_model": "axolotl-ai-co/tiny-falcon-42m",
"flash_attention": True, "flash_attention": False,
"sequence_len": 1024, "sequence_len": 1024,
"load_in_8bit": True, "load_in_8bit": True,
"adapter": "lora", "adapter": "lora",
@@ -49,17 +50,21 @@ class TestFalcon(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "warmup_steps": 5,
"eval_steps": 10, "logging_steps": 1,
"save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
@@ -69,14 +74,20 @@ class TestFalcon(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@pytest.mark.skip(reason="no tiny models for testing with safetensors")
@with_temp_dir @with_temp_dir
def test_lora_added_vocab(self, temp_dir): def test_lora_added_vocab(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "illuin/tiny-random-FalconForCausalLM", "base_model": "axolotl-ai-co/tiny-falcon-42m",
"flash_attention": True, "flash_attention": False,
"sequence_len": 1024, "sequence_len": 1024,
"load_in_8bit": True, "load_in_8bit": True,
"adapter": "lora", "adapter": "lora",
@@ -104,17 +115,21 @@ class TestFalcon(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "warmup_steps": 5,
"eval_steps": 10, "logging_steps": 1,
"save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
@@ -124,14 +139,20 @@ class TestFalcon(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@pytest.mark.skip(reason="no tiny models for testing with safetensors")
@with_temp_dir @with_temp_dir
def test_ft(self, temp_dir): def test_ft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "illuin/tiny-random-FalconForCausalLM", "base_model": "axolotl-ai-co/tiny-falcon-42m",
"flash_attention": True, "flash_attention": False,
"sequence_len": 1024, "sequence_len": 1024,
"val_set_size": 0.02, "val_set_size": 0.02,
"special_tokens": { "special_tokens": {
@@ -145,17 +166,23 @@ class TestFalcon(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "sample_packing": True,
"pad_to_sequence_len": True,
"micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 5e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 80,
"save_steps": 10, "warmup_steps": 5,
"eval_steps": 10, "logging_steps": 1,
"save_steps": 80,
"eval_steps": 80,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
@@ -165,3 +192,10 @@ class TestFalcon(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=10,
final_window=10,
max_initial=5.0,
max_final=4.7,
)

View File

@@ -11,7 +11,11 @@ from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from .utils import check_model_output_exists, with_temp_dir from .utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestMistral(unittest.TestCase): class TestMistral(unittest.TestCase):
@@ -23,7 +27,7 @@ class TestMistral(unittest.TestCase):
def test_lora(self, temp_dir): def test_lora(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "trl-internal-testing/tiny-MistralForCausalLM-0.2", "base_model": "axolotl-ai-co/tiny-mistral-25m",
"flash_attention": True, "flash_attention": True,
"sequence_len": 1024, "sequence_len": 1024,
"load_in_8bit": True, "load_in_8bit": True,
@@ -45,16 +49,18 @@ class TestMistral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
@@ -64,12 +70,19 @@ class TestMistral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=4.5,
max_final=4.3,
)
@with_temp_dir @with_temp_dir
def test_ft(self, temp_dir): def test_ft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "trl-internal-testing/tiny-MistralForCausalLM-0.2", "base_model": "axolotl-ai-co/tiny-mistral-25m",
"flash_attention": True, "flash_attention": True,
"sequence_len": 1024, "sequence_len": 1024,
"val_set_size": 0.02, "val_set_size": 0.02,
@@ -85,16 +98,18 @@ class TestMistral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_torch_fused", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
if is_torch_bf16_gpu_available(): if is_torch_bf16_gpu_available():
@@ -108,3 +123,10 @@ class TestMistral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=4.5,
max_final=4.3,
)

View File

@@ -12,7 +12,11 @@ from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from .utils import check_model_output_exists, with_temp_dir from .utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestMixtral(unittest.TestCase): class TestMixtral(unittest.TestCase):
@@ -24,8 +28,7 @@ class TestMixtral(unittest.TestCase):
def test_qlora_w_fa2(self, temp_dir): def test_qlora_w_fa2(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": True, "flash_attention": True,
"sequence_len": 1024, "sequence_len": 1024,
"load_in_4bit": True, "load_in_4bit": True,
@@ -51,16 +54,18 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
@@ -74,13 +79,19 @@ class TestMixtral(unittest.TestCase):
== torch.float32 == torch.float32
) )
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_qlora_wo_fa2(self, temp_dir): def test_qlora_wo_fa2(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": False, "flash_attention": False,
"sequence_len": 1024, "sequence_len": 1024,
"load_in_4bit": True, "load_in_4bit": True,
@@ -106,16 +117,18 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
@@ -129,13 +142,19 @@ class TestMixtral(unittest.TestCase):
== torch.float32 == torch.float32
) )
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_16bit_lora_w_fa2(self, temp_dir): def test_16bit_lora_w_fa2(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": True, "flash_attention": True,
"sequence_len": 1024, "sequence_len": 1024,
"adapter": "lora", "adapter": "lora",
@@ -160,16 +179,18 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
if is_torch_bf16_gpu_available(): if is_torch_bf16_gpu_available():
@@ -187,13 +208,19 @@ class TestMixtral(unittest.TestCase):
== torch.float32 == torch.float32
) )
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_16bit_lora_wo_fa2(self, temp_dir): def test_16bit_lora_wo_fa2(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": False, "flash_attention": False,
"sequence_len": 1024, "sequence_len": 1024,
"adapter": "lora", "adapter": "lora",
@@ -218,16 +245,18 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
@@ -245,13 +274,19 @@ class TestMixtral(unittest.TestCase):
== torch.float32 == torch.float32
) )
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_ft(self, temp_dir): def test_ft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "hf-internal-testing/Mixtral-tiny", "base_model": "axolotl-ai-co/tiny-mixtral-30m",
"tokenizer_config": "LoneStriker/Mixtral-8x7B-v0.1-HF",
"flash_attention": True, "flash_attention": True,
"sequence_len": 1024, "sequence_len": 1024,
"val_set_size": 0.02, "val_set_size": 0.02,
@@ -263,16 +298,18 @@ class TestMixtral(unittest.TestCase):
}, },
], ],
"num_epochs": 2, "num_epochs": 2,
"micro_batch_size": 2, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "adamw_bnb_8bit", "optimizer": "adamw_bnb_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"max_steps": 20, "max_steps": 50,
"save_steps": 10, "logging_steps": 1,
"eval_steps": 10, "save_steps": 50,
"eval_steps": 50,
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
} }
) )
if is_torch_bf16_gpu_available(): if is_torch_bf16_gpu_available():
@@ -286,3 +323,10 @@ class TestMixtral(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)

View File

@@ -13,6 +13,7 @@ from axolotl.utils.dict import DictDefault
from .utils import ( from .utils import (
check_model_output_exists, check_model_output_exists,
check_tensorboard_loss_decreased,
require_torch_2_5_1, require_torch_2_5_1,
require_torch_2_6_0, require_torch_2_6_0,
require_torch_2_7_0, require_torch_2_7_0,
@@ -243,20 +244,18 @@ class TestCustomOptimizers(unittest.TestCase):
def test_came_pytorch(self, temp_dir): def test_came_pytorch(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "JackFram/llama-68m", "base_model": "axolotl-ai-co/tiny-llama-50m",
"tokenizer_type": "LlamaTokenizer", "tokenizer_type": "AutoTokenizer",
"sequence_len": 1024, "sequence_len": 1024,
"load_in_8bit": True, "load_in_8bit": True,
"adapter": "lora", "adapter": "lora",
"lora_r": 8, "lora_r": 8,
"lora_alpha": 16, "lora_alpha": 16,
"lora_dropout": 0.05, "lora_dropout": 0.0,
"lora_target_linear": True, "lora_target_linear": True,
"val_set_size": 0.1, "val_set_size": 0.1,
"special_tokens": { "special_tokens": {
"unk_token": "<unk>", "pad_token": "<|endoftext|>",
"bos_token": "<s>",
"eos_token": "</s>",
}, },
"datasets": [ "datasets": [
{ {
@@ -265,16 +264,22 @@ class TestCustomOptimizers(unittest.TestCase):
}, },
], ],
"num_epochs": 1, "num_epochs": 1,
"sample_packing": True,
"pad_to_sequence_len": True,
"micro_batch_size": 8, "micro_batch_size": 8,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 1e-4,
"optimizer": "came_pytorch", "optimizer": "came_pytorch",
"adam_beta3": 0.9999, "adam_beta3": 0.9999,
"adam_epsilon2": 1e-16, "adam_epsilon2": 1e-16,
"max_steps": 5, "max_steps": 80,
"warmup_steps": 5,
"logging_steps": 1,
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
@@ -284,6 +289,13 @@ class TestCustomOptimizers(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=10,
final_window=10,
max_initial=4.0,
max_final=3.0,
)
@require_torch_2_7_0 @require_torch_2_7_0

View File

@@ -9,7 +9,11 @@ from axolotl.train import train
from axolotl.utils.config import normalize_config, validate_config from axolotl.utils.config import normalize_config, validate_config
from axolotl.utils.dict import DictDefault from axolotl.utils.dict import DictDefault
from .utils import check_model_output_exists, with_temp_dir from .utils import (
check_model_output_exists,
check_tensorboard_loss_decreased,
with_temp_dir,
)
class TestPhi(unittest.TestCase): class TestPhi(unittest.TestCase):
@@ -21,7 +25,7 @@ class TestPhi(unittest.TestCase):
def test_phi_ft(self, temp_dir): def test_phi_ft(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "microsoft/phi-1_5", "base_model": "axolotl-ai-co/tiny-phi-64m",
"model_type": "AutoModelForCausalLM", "model_type": "AutoModelForCausalLM",
"tokenizer_type": "AutoTokenizer", "tokenizer_type": "AutoTokenizer",
"sequence_len": 2048, "sequence_len": 2048,
@@ -41,18 +45,22 @@ class TestPhi(unittest.TestCase):
"dataset_shard_num": 10, "dataset_shard_num": 10,
"dataset_shard_idx": 0, "dataset_shard_idx": 0,
"num_epochs": 1, "num_epochs": 1,
"micro_batch_size": 1, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "paged_adamw_8bit", "optimizer": "adamw_torch_fused",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
"max_steps": 10, "max_steps": 50,
"save_steps": 10, "warmup_steps": 5,
"eval_steps": 10, "logging_steps": 1,
"save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -61,12 +69,19 @@ class TestPhi(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)
@with_temp_dir @with_temp_dir
def test_phi_qlora(self, temp_dir): def test_phi_qlora(self, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "microsoft/phi-1_5", "base_model": "axolotl-ai-co/tiny-phi-64m",
"model_type": "AutoModelForCausalLM", "model_type": "AutoModelForCausalLM",
"tokenizer_type": "AutoTokenizer", "tokenizer_type": "AutoTokenizer",
"sequence_len": 2048, "sequence_len": 2048,
@@ -90,18 +105,22 @@ class TestPhi(unittest.TestCase):
"dataset_shard_num": 10, "dataset_shard_num": 10,
"dataset_shard_idx": 0, "dataset_shard_idx": 0,
"num_epochs": 1, "num_epochs": 1,
"micro_batch_size": 1, "micro_batch_size": 4,
"gradient_accumulation_steps": 1, "gradient_accumulation_steps": 1,
"output_dir": temp_dir, "output_dir": temp_dir,
"learning_rate": 0.00001, "learning_rate": 2e-4,
"optimizer": "paged_adamw_8bit", "optimizer": "paged_adamw_8bit",
"lr_scheduler": "cosine", "lr_scheduler": "cosine",
"flash_attention": True, "flash_attention": True,
"max_steps": 10, "max_steps": 50,
"save_steps": 10, "warmup_steps": 5,
"eval_steps": 10, "logging_steps": 1,
"save_steps": 50,
"eval_steps": 50,
"bf16": "auto", "bf16": "auto",
"save_first_step": False, "save_first_step": False,
"use_tensorboard": True,
"seed": 42,
} }
) )
cfg = validate_config(cfg) cfg = validate_config(cfg)
@@ -110,3 +129,10 @@ class TestPhi(unittest.TestCase):
train(cfg=cfg, dataset_meta=dataset_meta) train(cfg=cfg, dataset_meta=dataset_meta)
check_model_output_exists(temp_dir, cfg) check_model_output_exists(temp_dir, cfg)
check_tensorboard_loss_decreased(
temp_dir + "/runs",
initial_window=5,
final_window=5,
max_initial=5.0,
max_final=4.7,
)

View File

@@ -18,7 +18,7 @@ class TestPreprocess:
cfg = DictDefault( cfg = DictDefault(
{ {
"base_model": "Qwen/Qwen2.5-0.5B", "base_model": "axolotl-ai-co/tiny-qwen2-129m",
"sequence_len": 2048, "sequence_len": 2048,
"val_set_size": 0.01, "val_set_size": 0.01,
"datasets": [ "datasets": [

View File

@@ -45,7 +45,7 @@ def _get_fake_quant_config_dtype(config):
@pytest.fixture() @pytest.fixture()
def model(): def model():
dummy_model = AutoModelForCausalLM.from_pretrained( dummy_model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2-0.5B", "axolotl-ai-co/tiny-qwen2-129m",
device_map="auto", device_map="auto",
dtype=torch.bfloat16, dtype=torch.bfloat16,
) )

View File

@@ -17,7 +17,7 @@ class TestE2eQwen:
Test cases for qwen models Test cases for qwen models
""" """
@pytest.mark.parametrize("base_model", ["Qwen/Qwen2-0.5B", "Qwen/Qwen2.5-0.5B"]) @pytest.mark.parametrize("base_model", ["axolotl-ai-co/tiny-qwen2-129m"])
def test_dpo(self, base_model, temp_dir): def test_dpo(self, base_model, temp_dir):
cfg = DictDefault( cfg = DictDefault(
{ {

View File

@@ -199,6 +199,106 @@ def check_tensorboard(
assert df.value.values[-1] > 1e-5, "Expected loss to be greater than zero" assert df.value.values[-1] > 1e-5, "Expected loss to be greater than zero"
def check_tensorboard_loss_decreased(
temp_run_dir: str,
tag: str | None = None,
initial_window: int = 1,
final_window: int = 1,
min_delta: float | None = None,
max_initial: float | None = None,
max_final: float | None = None,
max_loss_ratio: float = 0.95,
) -> None:
"""Check that training actually learned — loss went down and stayed in
a sensible range.
Used with the tiny ``axolotl-ai-co/tiny-*`` CI models, where pretraining
was brief enough that final loss won't clear the absolute thresholds used
for 135M+ models — but the training pipeline should still behave.
``train/train_loss`` is only logged once (end-of-training aggregate). The
per-step tag is ``train/loss`` for SFT/LM trainers and may vary across
trainers (e.g. DPO). When ``tag`` is None we try common per-step tags in
order and use the first with enough samples.
Two kinds of regression we guard against:
1. **Loss blew up.** A silent bug (e.g. broken label masking) can start
training at an absurdly high loss. ``max_initial`` / ``max_final``
assert the measured means stay at-or-below bounds measured from a
known-good run. Both are optional but strongly encouraged — loss
going *down* from a bad starting scale still looks like "learning."
2. **Loss didn't go down enough.** ``max_loss_ratio`` (default 0.95)
requires ``final <= initial * ratio``. A default below 1.0 means the
final window mean must sit at least 5% below the initial window mean
— real learning, not noise that happened to land below start. Only
raise this for configs where a smaller drop is expected *and*
documented (e.g. DPO with near-trivial pairs); in that case you are
intentionally weakening the test.
``min_delta`` is optional; when set, additionally requires
``final + min_delta <= initial`` — use for configs with enough signal
to demand a specific minimum absolute drop.
"""
tb_log_path = most_recent_subdir(temp_run_dir)
event_file = os.path.join(tb_log_path, sorted(os.listdir(tb_log_path))[0])
reader = SummaryReader(event_file)
df = reader.scalars
if tag is None:
candidates = ["train/loss", "train/train_loss"]
else:
candidates = [tag]
required = initial_window + final_window
chosen_tag, values = None, None
for candidate in candidates:
sub = df[df.tag == candidate]
if len(sub) >= required:
chosen_tag = candidate
values = sub.value.values
break
available = sorted({t for t in df.tag.unique() if "loss" in t.lower()})
assert values is not None, (
f"None of the tags {candidates} had ≥{required} logged steps. "
f"Loss tags present: {available}"
)
initial = float(values[:initial_window].mean())
final = float(values[-final_window:].mean())
print(
f"[check_tensorboard_loss_decreased] tag={chosen_tag} n={len(values)} "
f"initial_mean{initial_window}={initial:.4f} final_mean{final_window}={final:.4f}"
)
assert final > 1e-5, "Expected loss to be greater than zero"
assert final <= initial * max_loss_ratio, (
f"Loss did not decrease for {chosen_tag}: "
f"initial(mean of first {initial_window})={initial:.4f}, "
f"final(mean of last {final_window})={final:.4f}, "
f"ratio={final / initial:.4f} (max allowed {max_loss_ratio}). "
f"Expected final <= initial — training did not learn."
)
if min_delta is not None:
assert final + min_delta <= initial, (
f"Expected loss to decrease by at least {min_delta} for {chosen_tag}: "
f"initial={initial:.4f}, final={final:.4f}, delta={initial - final:.4f}"
)
if max_initial is not None:
assert initial <= max_initial, (
f"Initial loss {initial:.4f} is above the expected max {max_initial}. "
f"Absolute scale is wrong — probably a silent regression "
f"(e.g. bad label masking) that bumped the starting point."
)
if max_final is not None:
assert final <= max_final, (
f"Final loss {final:.4f} is above the expected max {max_final}. "
f"Absolute scale is wrong — probably a silent regression "
f"(e.g. bad label masking) that bumped the endpoint."
)
def check_model_output_exists(temp_dir: str, cfg: DictDefault) -> None: def check_model_output_exists(temp_dir: str, cfg: DictDefault) -> None:
""" """
helper function to check if a model output file exists after training helper function to check if a model output file exists after training