AdithyaSK HF Staff commited on
Commit
35d58b7
·
verified ·
1 Parent(s): 98702f1

Stage Harbor release files 32501-33000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/pr_style_bot.yml +127 -0
  2. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/publish.yml +43 -0
  3. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/slow-tests.yml +112 -0
  4. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests-experimental.yml +71 -0
  5. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests.yml +313 -0
  6. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests_latest.yml +67 -0
  7. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests_transformers_branch.yml +122 -0
  8. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/trufflehog.yml +18 -0
  9. tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/upload_pr_documentation.yml +16 -0
  10. tasks/tasksmith-4fc63afb85cd/tests/source/.gitignore +148 -0
  11. tasks/tasksmith-4fc63afb85cd/tests/source/.pre-commit-config.yaml +17 -0
  12. tasks/tasksmith-4fc63afb85cd/tests/source/AGENTS.md +97 -0
  13. tasks/tasksmith-4fc63afb85cd/tests/source/CITATION.cff +41 -0
  14. tasks/tasksmith-4fc63afb85cd/tests/source/CODE_OF_CONDUCT.md +133 -0
  15. tasks/tasksmith-4fc63afb85cd/tests/source/CONTRIBUTING.md +411 -0
  16. tasks/tasksmith-4fc63afb85cd/tests/source/LICENSE +201 -0
  17. tasks/tasksmith-4fc63afb85cd/tests/source/MANIFEST.in +8 -0
  18. tasks/tasksmith-4fc63afb85cd/tests/source/MIGRATION.md +20 -0
  19. tasks/tasksmith-4fc63afb85cd/tests/source/Makefile +19 -0
  20. tasks/tasksmith-4fc63afb85cd/tests/source/README.md +205 -0
  21. tasks/tasksmith-4fc63afb85cd/tests/source/RELEASE.md +167 -0
  22. tasks/tasksmith-4fc63afb85cd/tests/source/VERSION +1 -0
  23. tasks/tasksmith-4fc63afb85cd/tests/source/assets/logo-dark.png +3 -0
  24. tasks/tasksmith-4fc63afb85cd/tests/source/assets/logo-light.png +3 -0
  25. tasks/tasksmith-4fc63afb85cd/tests/source/docker/trl-dev/Dockerfile +5 -0
  26. tasks/tasksmith-4fc63afb85cd/tests/source/docker/trl/Dockerfile +4 -0
  27. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/_toctree.yml +138 -0
  28. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/async_grpo_trainer.md +80 -0
  29. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/bco_trainer.md +105 -0
  30. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/bema_for_reference_model.md +32 -0
  31. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/callbacks.md +17 -0
  32. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/chat_template_utils.md +13 -0
  33. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/clis.md +703 -0
  34. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/community_tutorials.md +66 -0
  35. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/cpo_trainer.md +126 -0
  36. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/customization.md +113 -0
  37. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/data_utils.md +17 -0
  38. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/dataset_formats.md +1012 -0
  39. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/deepspeed_integration.md +36 -0
  40. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/distributing_training.md +445 -0
  41. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/dpo_trainer.md +295 -0
  42. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/example_overview.md +121 -0
  43. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/experimental_overview.md +31 -0
  44. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gfpo.md +50 -0
  45. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gkd_trainer.md +99 -0
  46. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gold_trainer.md +173 -0
  47. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/grpo_trainer.md +803 -0
  48. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/grpo_with_replay_buffer.md +56 -0
  49. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gspo_token.md +25 -0
  50. tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/index.md +154 -0
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/pr_style_bot.yml ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: PR Style Bot
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+
7
+ permissions:
8
+ contents: write
9
+ pull-requests: write
10
+
11
+ jobs:
12
+ run-style-bot:
13
+ if: >
14
+ contains(github.event.comment.body, '@bot /style') &&
15
+ github.event.issue.pull_request != null
16
+ runs-on: ubuntu-latest
17
+
18
+ steps:
19
+ - name: Extract PR details
20
+ id: pr_info
21
+ uses: actions/github-script@v8
22
+ with:
23
+ script: |
24
+ const prNumber = context.payload.issue.number;
25
+ const { data: pr } = await github.rest.pulls.get({
26
+ owner: context.repo.owner,
27
+ repo: context.repo.repo,
28
+ pull_number: prNumber
29
+ });
30
+
31
+ // We capture both the branch ref and the "full_name" of the head repo
32
+ // so that we can check out the correct repository & branch (including forks).
33
+ core.setOutput("prNumber", prNumber);
34
+ core.setOutput("headRef", pr.head.ref);
35
+ core.setOutput("headRepoFullName", pr.head.repo.full_name);
36
+
37
+ - name: Check out PR branch
38
+ uses: actions/checkout@v6
39
+ env:
40
+ HEADREPOFULLNAME: ${{ steps.pr_info.outputs.headRepoFullName }}
41
+ HEADREF: ${{ steps.pr_info.outputs.headRef }}
42
+ with:
43
+ # Instead of checking out the base repo, use the contributor's repo name
44
+ repository: ${{ env.HEADREPOFULLNAME }}
45
+ ref: ${{ env.HEADREF }}
46
+ # You may need fetch-depth: 0 for being able to push
47
+ fetch-depth: 0
48
+ token: ${{ secrets.GITHUB_TOKEN }}
49
+
50
+ - name: Debug
51
+ env:
52
+ HEADREPOFULLNAME: ${{ steps.pr_info.outputs.headRepoFullName }}
53
+ HEADREF: ${{ steps.pr_info.outputs.headRef }}
54
+ PRNUMBER: ${{ steps.pr_info.outputs.prNumber }}
55
+ run: |
56
+ echo "PR number: ${{ env.PRNUMBER }}"
57
+ echo "Head Ref: ${{ env.HEADREF }}"
58
+ echo "Head Repo Full Name: ${{ env.HEADREPOFULLNAME }}"
59
+
60
+ - name: Set up Python
61
+ uses: actions/setup-python@v6
62
+
63
+ - name: Install dependencies
64
+ run: |
65
+ pip install ruff pre-commit
66
+
67
+ - name: Download Makefile from main branch
68
+ run: |
69
+ curl -o main_Makefile https://raw.githubusercontent.com/huggingface/trl/main/Makefile
70
+
71
+ - name: Compare Makefiles
72
+ run: |
73
+ if ! diff -q main_Makefile Makefile; then
74
+ echo "Error: The Makefile has changed. Please ensure it matches the main branch."
75
+ exit 1
76
+ fi
77
+ echo "No changes in Makefile. Proceeding..."
78
+ rm -rf main_Makefile
79
+
80
+ - name: Run make style and make quality
81
+ run: |
82
+ make precommit || true
83
+
84
+ - name: Commit and push changes
85
+ id: commit_and_push
86
+ env:
87
+ HEADREPOFULLNAME: ${{ steps.pr_info.outputs.headRepoFullName }}
88
+ HEADREF: ${{ steps.pr_info.outputs.headRef }}
89
+ PRNUMBER: ${{ steps.pr_info.outputs.prNumber }}
90
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
91
+ run: |
92
+ echo "HEADREPOFULLNAME: ${{ env.HEADREPOFULLNAME }}, HEADREF: ${{ env.HEADREF }}"
93
+ # Configure git with the Actions bot user
94
+ git config user.name "github-actions[bot]"
95
+ git config user.email "github-actions[bot]@users.noreply.github.com"
96
+
97
+ # Make sure your 'origin' remote is set to the contributor's fork
98
+ git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${{ env.HEADREPOFULLNAME }}.git"
99
+
100
+ # If there are changes after running style/quality, commit them
101
+ if [ -n "$(git status --porcelain)" ]; then
102
+ git add .
103
+ git commit -m "Apply style fixes"
104
+ # Push to the original contributor's forked branch
105
+ git push origin HEAD:${{ env.HEADREF }}
106
+ echo "changes_pushed=true" >> $GITHUB_OUTPUT
107
+ else
108
+ echo "No changes to commit."
109
+ echo "changes_pushed=false" >> $GITHUB_OUTPUT
110
+ fi
111
+
112
+ - name: Comment on PR with workflow run link
113
+ if: steps.commit_and_push.outputs.changes_pushed == 'true'
114
+ uses: actions/github-script@v8
115
+ with:
116
+ script: |
117
+ const prNumber = parseInt(process.env.prNumber, 10);
118
+ const runUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
119
+
120
+ await github.rest.issues.createComment({
121
+ owner: context.repo.owner,
122
+ repo: context.repo.repo,
123
+ issue_number: prNumber,
124
+ body: `Style fixes have been applied. [View the workflow run here](${runUrl}).`
125
+ });
126
+ env:
127
+ prNumber: ${{ steps.pr_info.outputs.prNumber }}
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/publish.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - v*-release
8
+ paths:
9
+ - "VERSION"
10
+
11
+ jobs:
12
+ publish:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v6
16
+
17
+ - name: Read version
18
+ id: get_version
19
+ run: echo "version=$(cat VERSION)" >> $GITHUB_OUTPUT
20
+
21
+ - name: Debug - Show version.txt content
22
+ run: echo "Version is ${{ steps.get_version.outputs.version }}"
23
+
24
+ - name: Set up Python
25
+ uses: actions/setup-python@v6
26
+ with:
27
+ python-version: "3.x"
28
+
29
+ - name: Install dependencies
30
+ run: |
31
+ python -m pip install --upgrade pip
32
+ pip install build twine
33
+
34
+ - name: Build package
35
+ run: python -m build
36
+
37
+ - name: Publish to PyPI
38
+ if: ${{ !contains(steps.get_version.outputs.version, 'dev') }}
39
+ env:
40
+ TWINE_USERNAME: __token__
41
+ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
42
+ run: |
43
+ python -m twine upload dist/*
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/slow-tests.yml ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Slow tests (on push)
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ paths:
7
+ # Run only when python files are modified
8
+ - "trl/**.py"
9
+ - "examples/**.py"
10
+ env:
11
+ RUN_SLOW: "yes"
12
+ IS_GITHUB_CI: "1"
13
+ SLACK_API_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
14
+ TRL_EXPERIMENTAL_SILENCE: 1
15
+
16
+ jobs:
17
+ run_all_tests_single_gpu:
18
+ runs-on:
19
+ group: aws-g4dn-2xlarge
20
+ env:
21
+ CUDA_VISIBLE_DEVICES: "0"
22
+ TEST_TYPE: "single_gpu"
23
+ container:
24
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
25
+ options: --gpus all --shm-size "16gb"
26
+ defaults:
27
+ run:
28
+ shell: bash
29
+ steps:
30
+ - name: Git checkout
31
+ uses: actions/checkout@v6
32
+
33
+ - name: Install system dependencies
34
+ run: |
35
+ apt-get update && apt-get install -y make git curl
36
+
37
+ - name: Install uv
38
+ run: |
39
+ curl -LsSf https://astral.sh/uv/install.sh | sh
40
+
41
+ - name: Create Python virtual environment
42
+ run: |
43
+ uv venv
44
+ uv pip install --upgrade setuptools wheel
45
+
46
+ - name: Install dependencies
47
+ run: |
48
+ source .venv/bin/activate
49
+ uv pip install ".[dev]"
50
+ uv pip install pytest-reportlog
51
+
52
+ - name: Run slow SFT tests on single GPU
53
+ if: always()
54
+ run: |
55
+ source .venv/bin/activate
56
+ make slow_tests
57
+
58
+ - name: Generate Report
59
+ if: always()
60
+ run: |
61
+ source .venv/bin/activate
62
+ uv pip install slack_sdk tabulate
63
+ python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY
64
+
65
+ run_all_tests_multi_gpu:
66
+ runs-on:
67
+ group: aws-g4dn-2xlarge
68
+ env:
69
+ CUDA_VISIBLE_DEVICES: "0,1"
70
+ TEST_TYPE: "multi_gpu"
71
+ container:
72
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
73
+ options: --gpus all --shm-size "16gb"
74
+ defaults:
75
+ run:
76
+ shell: bash
77
+ steps:
78
+ - name: Git checkout
79
+ uses: actions/checkout@v6
80
+
81
+ - name: Install system dependencies
82
+ run: |
83
+ apt-get update && apt-get install -y make git curl
84
+
85
+ - name: Install uv
86
+ run: |
87
+ curl -LsSf https://astral.sh/uv/install.sh | sh
88
+
89
+ - name: Create Python virtual environment
90
+ run: |
91
+ uv venv
92
+ uv pip install --upgrade setuptools wheel
93
+
94
+ - name: Install dependencies
95
+ run: |
96
+ source .venv/bin/activate
97
+ uv pip install ".[dev]"
98
+ uv pip install pytest-reportlog
99
+
100
+ - name: Run slow SFT tests on Multi GPU
101
+ if: always()
102
+ run: |
103
+ source .venv/bin/activate
104
+ make slow_tests
105
+
106
+ - name: Generate Reports
107
+ if: always()
108
+ run: |
109
+ source .venv/bin/activate
110
+ uv pip install slack_sdk tabulate
111
+ python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY
112
+ rm *.txt
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests-experimental.yml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests (experimental)
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ # Run only when relevant files are modified
7
+ - "trl/experimental/**"
8
+ - "tests/experimental/**"
9
+
10
+ env:
11
+ TQDM_DISABLE: 1
12
+ PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True"
13
+ PYTORCH_ALLOC_CONF: "expandable_segments:True"
14
+ TRL_EXPERIMENTAL_SILENCE: 1
15
+
16
+ jobs:
17
+ check_code_quality:
18
+ name: Check code quality
19
+ runs-on: ubuntu-latest
20
+ if: github.event.pull_request.draft == false
21
+ steps:
22
+ - uses: actions/checkout@v6
23
+ - name: Set up Python 3.13
24
+ uses: actions/setup-python@v6
25
+ with:
26
+ python-version: 3.13
27
+ - uses: pre-commit/action@v3.0.1
28
+ with:
29
+ extra_args: --all-files
30
+
31
+ tests:
32
+ name: Tests (experimental)
33
+ runs-on:
34
+ group: aws-g4dn-2xlarge
35
+ container:
36
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
37
+ options: --gpus all
38
+ defaults:
39
+ run:
40
+ shell: bash
41
+ steps:
42
+ - name: Git checkout
43
+ uses: actions/checkout@v6
44
+
45
+ - name: Set up Python 3.13
46
+ uses: actions/setup-python@v6
47
+ with:
48
+ python-version: 3.13
49
+
50
+ - name: Install Make and Git
51
+ run: |
52
+ apt-get update && apt-get install -y make git curl
53
+
54
+ - name: Install uv
55
+ run: |
56
+ curl -LsSf https://astral.sh/uv/install.sh | sh
57
+
58
+ - name: Create Python virtual environment
59
+ run: |
60
+ uv venv
61
+ uv pip install --upgrade setuptools wheel
62
+
63
+ - name: Install dependencies
64
+ run: |
65
+ source .venv/bin/activate
66
+ uv pip install ".[dev]"
67
+
68
+ - name: Test with pytest
69
+ run: |
70
+ source .venv/bin/activate
71
+ make test_experimental
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests.yml ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - ci-*
8
+ pull_request:
9
+ paths:
10
+ # Run only when relevant files are modified
11
+ - ".github/**.yml"
12
+ - "examples/**.py"
13
+ - "scripts/**.py"
14
+ - "tests/**.py"
15
+ - "trl/**.py"
16
+ - "pyproject.toml"
17
+ # Exclude if only experimental code/tests
18
+ - "!trl/experimental/**"
19
+ - "!tests/experimental/**"
20
+
21
+ env:
22
+ TQDM_DISABLE: 1
23
+ CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }}
24
+ PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True"
25
+ PYTORCH_ALLOC_CONF: "expandable_segments:True"
26
+
27
+ jobs:
28
+ check_code_quality:
29
+ name: Check code quality
30
+ runs-on: ubuntu-latest
31
+ if: github.event.pull_request.draft == false
32
+ steps:
33
+ - uses: actions/checkout@v6
34
+ - name: Set up Python 3.12
35
+ uses: actions/setup-python@v6
36
+ with:
37
+ python-version: 3.12
38
+ - uses: pre-commit/action@v3.0.1
39
+ with:
40
+ extra_args: --all-files
41
+
42
+ tests:
43
+ name: Tests
44
+ strategy:
45
+ matrix:
46
+ python-version: ['3.10', '3.11', '3.12', '3.13', '3.14']
47
+ fail-fast: false
48
+ runs-on:
49
+ group: aws-g4dn-2xlarge
50
+ container:
51
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
52
+ options: --gpus all
53
+ defaults:
54
+ run:
55
+ shell: bash
56
+ if: github.event.pull_request.draft == false
57
+ steps:
58
+ - name: Git checkout
59
+ uses: actions/checkout@v6
60
+
61
+ - name: Set up Python ${{ matrix.python-version }}
62
+ uses: actions/setup-python@v6
63
+ with:
64
+ python-version: ${{ matrix.python-version }}
65
+
66
+ - name: Install Make and Git
67
+ run: |
68
+ apt-get update && apt-get install -y make git curl
69
+
70
+ - name: Install uv
71
+ run: |
72
+ curl -LsSf https://astral.sh/uv/install.sh | sh
73
+
74
+ - name: Create Python virtual environment
75
+ run: |
76
+ uv venv
77
+ uv pip install --upgrade setuptools wheel
78
+
79
+ - name: Install dependencies
80
+ run: |
81
+ source .venv/bin/activate
82
+ uv pip install ".[dev]"
83
+
84
+ - name: Test with pytest
85
+ run: |
86
+ source .venv/bin/activate
87
+ make test
88
+
89
+ - name: Post to Slack
90
+ if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
91
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
92
+ with:
93
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
94
+ title: Results with Python ${{ matrix.python-version }} and latest dependencies
95
+ status: ${{ job.status }}
96
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
97
+
98
+ tests_dev:
99
+ name: Tests with dev dependencies
100
+ runs-on:
101
+ group: aws-g4dn-2xlarge
102
+ container:
103
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
104
+ options: --gpus all
105
+ defaults:
106
+ run:
107
+ shell: bash
108
+ if: github.event.pull_request.draft == false
109
+ steps:
110
+ - name: Git checkout
111
+ uses: actions/checkout@v6
112
+
113
+ - name: Set up Python 3.12
114
+ uses: actions/setup-python@v6
115
+ with:
116
+ python-version: '3.12'
117
+
118
+ - name: Install Make and Git
119
+ run: |
120
+ apt-get update && apt-get install -y make git curl
121
+
122
+ - name: Install uv
123
+ run: |
124
+ curl -LsSf https://astral.sh/uv/install.sh | sh
125
+
126
+ - name: Create Python virtual environment
127
+ run: |
128
+ uv venv
129
+ uv pip install --upgrade setuptools wheel
130
+
131
+ - name: Install dependencies
132
+ run: |
133
+ source .venv/bin/activate
134
+ uv pip install ".[dev]"
135
+ uv pip install -U git+https://github.com/huggingface/accelerate.git
136
+ uv pip install -U git+https://github.com/huggingface/datasets.git
137
+ uv pip install -U git+https://github.com/huggingface/transformers.git
138
+ uv pip install -U git+https://github.com/huggingface/peft.git
139
+
140
+ - name: Test with pytest
141
+ run: |
142
+ source .venv/bin/activate
143
+ make test
144
+
145
+ - name: Post to Slack
146
+ if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
147
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
148
+ with:
149
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
150
+ title: Results with Python 3.12 and dev dependencies
151
+ status: ${{ job.status }}
152
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
153
+
154
+ tests_wo_optional_deps:
155
+ name: Tests without optional dependencies
156
+ runs-on:
157
+ group: aws-g4dn-2xlarge
158
+ container:
159
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
160
+ options: --gpus all
161
+ defaults:
162
+ run:
163
+ shell: bash
164
+ if: github.event.pull_request.draft == false
165
+ steps:
166
+ - name: Git checkout
167
+ uses: actions/checkout@v6
168
+
169
+ - name: Set up Python 3.12
170
+ uses: actions/setup-python@v6
171
+ with:
172
+ python-version: '3.12'
173
+
174
+ - name: Install Make and Git
175
+ run: |
176
+ apt-get update && apt-get install -y make git curl
177
+
178
+ - name: Install uv
179
+ run: |
180
+ curl -LsSf https://astral.sh/uv/install.sh | sh
181
+
182
+ - name: Create Python virtual environment
183
+ run: |
184
+ uv venv
185
+ uv pip install --upgrade setuptools wheel
186
+
187
+ - name: Install dependencies
188
+ run: |
189
+ source .venv/bin/activate
190
+ uv pip install ".[test]"
191
+
192
+ - name: Test with pytest
193
+ run: |
194
+ source .venv/bin/activate
195
+ make test
196
+
197
+ - name: Post to Slack
198
+ if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
199
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
200
+ with:
201
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
202
+ title: Results with Python 3.12 without optional dependencies
203
+ status: ${{ job.status }}
204
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
205
+
206
+ tests_min_versions:
207
+ name: Tests with minimum versions
208
+ runs-on:
209
+ group: aws-g4dn-2xlarge
210
+ container:
211
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
212
+ options: --gpus all
213
+ defaults:
214
+ run:
215
+ shell: bash
216
+ if: github.event.pull_request.draft == false
217
+ steps:
218
+ - name: Git checkout
219
+ uses: actions/checkout@v6
220
+
221
+ - name: Set up Python 3.12
222
+ uses: actions/setup-python@v6
223
+ with:
224
+ python-version: '3.12'
225
+
226
+ - name: Install Make and Git
227
+ run: |
228
+ apt-get update && apt-get install -y make git curl
229
+
230
+ - name: Install uv
231
+ run: |
232
+ curl -LsSf https://astral.sh/uv/install.sh | sh
233
+
234
+ - name: Create Python virtual environment
235
+ run: |
236
+ uv venv
237
+ uv pip install --upgrade setuptools wheel
238
+
239
+ - name: Install dependencies
240
+ run: |
241
+ source .venv/bin/activate
242
+ uv pip install ".[dev]"
243
+ uv pip install accelerate==1.4.0
244
+ uv pip install datasets==3.0.0
245
+ uv pip install transformers==4.56.2
246
+
247
+ - name: Test with pytest
248
+ run: |
249
+ source .venv/bin/activate
250
+ make test
251
+
252
+ - name: Post to Slack
253
+ if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
254
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
255
+ with:
256
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
257
+ title: Results with Python 3.12 and minimum dependencies versions
258
+ status: ${{ job.status }}
259
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
260
+
261
+ distributed_smoke:
262
+ name: Distributed smoke tests
263
+ runs-on:
264
+ group: aws-g5-12xlarge-cache
265
+ container:
266
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
267
+ options: --gpus all
268
+ defaults:
269
+ run:
270
+ shell: bash
271
+ if: github.event.pull_request.draft == false
272
+ env:
273
+ CUDA_VISIBLE_DEVICES: "0,1"
274
+ steps:
275
+ - name: Git checkout
276
+ uses: actions/checkout@v6
277
+
278
+ - name: Set up Python 3.12
279
+ uses: actions/setup-python@v6
280
+ with:
281
+ python-version: '3.12'
282
+
283
+ - name: Install Make and Git
284
+ run: |
285
+ apt-get update && apt-get install -y make git curl
286
+
287
+ - name: Install uv
288
+ run: |
289
+ curl -LsSf https://astral.sh/uv/install.sh | sh
290
+
291
+ - name: Create Python virtual environment
292
+ run: |
293
+ uv venv
294
+ uv pip install --upgrade setuptools wheel
295
+
296
+ - name: Install dependencies
297
+ run: |
298
+ source .venv/bin/activate
299
+ uv pip install ".[dev]"
300
+
301
+ - name: Run distributed smoke tests
302
+ run: |
303
+ source .venv/bin/activate
304
+ pytest -v tests/distributed/test_distributed.py
305
+
306
+ - name: Post to Slack
307
+ if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
308
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
309
+ with:
310
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
311
+ title: Results of distributed smoke tests
312
+ status: ${{ job.status }}
313
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests_latest.yml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests latest TRL release with dev dependencies
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 0 * * *' # Runs daily at midnight UTC
6
+
7
+ workflow_dispatch:
8
+
9
+ env:
10
+ TQDM_DISABLE: 1
11
+ CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }}
12
+ TRL_EXPERIMENTAL_SILENCE: 1
13
+
14
+ jobs:
15
+ tests:
16
+ name: Tests latest TRL release with dev dependencies
17
+ runs-on:
18
+ group: aws-g4dn-2xlarge
19
+ container:
20
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
21
+ options: --gpus all
22
+ defaults:
23
+ run:
24
+ shell: bash
25
+ steps:
26
+ - name: Git checkout
27
+ uses: actions/checkout@v6
28
+ with: { ref: v0.29-release }
29
+
30
+ - name: Set up Python 3.12
31
+ uses: actions/setup-python@v6
32
+ with:
33
+ python-version: '3.12'
34
+
35
+ - name: Install Make and Git
36
+ run: |
37
+ apt-get update && apt-get install -y make git curl
38
+
39
+ - name: Install uv
40
+ run: |
41
+ curl -LsSf https://astral.sh/uv/install.sh | sh
42
+
43
+ - name: Create Python virtual environment
44
+ run: |
45
+ uv venv
46
+ uv pip install --upgrade setuptools wheel
47
+
48
+ - name: Install dependencies
49
+ run: |
50
+ source .venv/bin/activate
51
+ uv pip install ".[dev]"
52
+ uv pip install -U git+https://github.com/huggingface/accelerate.git
53
+ uv pip install -U git+https://github.com/huggingface/datasets.git
54
+ uv pip install -U git+https://github.com/huggingface/transformers.git
55
+
56
+ - name: Test with pytest
57
+ run: |
58
+ source .venv/bin/activate
59
+ make test
60
+
61
+ - name: Post to Slack
62
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
63
+ with:
64
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
65
+ title: Results of latest TRL with Python 3.12 and dev dependencies
66
+ status: ${{ job.status }}
67
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/tests_transformers_branch.yml ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests against Transformers branch
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ transformers_ref:
7
+ description: "Transformers git ref (branch, tag, or commit SHA)"
8
+ required: true
9
+ default: "main"
10
+
11
+ env:
12
+ TQDM_DISABLE: 1
13
+ CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }}
14
+ PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True"
15
+ PYTORCH_ALLOC_CONF: "expandable_segments:True"
16
+
17
+ jobs:
18
+ tests_transformers_branch:
19
+ name: Tests with Transformers ${{ inputs.transformers_ref }}
20
+ runs-on:
21
+ group: aws-g4dn-2xlarge
22
+ container:
23
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
24
+ options: --gpus all
25
+ defaults:
26
+ run:
27
+ shell: bash
28
+ steps:
29
+ - name: Git checkout
30
+ uses: actions/checkout@v6
31
+
32
+ - name: Set up Python 3.12
33
+ uses: actions/setup-python@v6
34
+ with:
35
+ python-version: '3.12'
36
+
37
+ - name: Install Make and Git
38
+ run: |
39
+ apt-get update && apt-get install -y make git curl
40
+
41
+ - name: Install uv
42
+ run: |
43
+ curl -LsSf https://astral.sh/uv/install.sh | sh
44
+
45
+ - name: Create Python virtual environment
46
+ run: |
47
+ uv venv
48
+ uv pip install --upgrade setuptools wheel
49
+
50
+ - name: Install dependencies
51
+ run: |
52
+ source .venv/bin/activate
53
+ uv pip install ".[dev]"
54
+ uv pip install -U git+https://github.com/huggingface/transformers.git@${{ inputs.transformers_ref }}
55
+
56
+ - name: Test with pytest
57
+ run: |
58
+ source .venv/bin/activate
59
+ make test
60
+
61
+ - name: Post to Slack
62
+ if: github.ref == 'refs/heads/main' && always()
63
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
64
+ with:
65
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
66
+ title: Results with Transformers ${{ inputs.transformers_ref }}
67
+ status: ${{ job.status }}
68
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
69
+
70
+ distributed_smoke:
71
+ name: Distributed smoke tests with Transformers ${{ inputs.transformers_ref }}
72
+ runs-on:
73
+ group: aws-g5-12xlarge-cache
74
+ container:
75
+ image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
76
+ options: --gpus all
77
+ defaults:
78
+ run:
79
+ shell: bash
80
+ env:
81
+ CUDA_VISIBLE_DEVICES: "0,1"
82
+ steps:
83
+ - name: Git checkout
84
+ uses: actions/checkout@v6
85
+
86
+ - name: Set up Python 3.12
87
+ uses: actions/setup-python@v6
88
+ with:
89
+ python-version: '3.12'
90
+
91
+ - name: Install Make and Git
92
+ run: |
93
+ apt-get update && apt-get install -y make git curl
94
+
95
+ - name: Install uv
96
+ run: |
97
+ curl -LsSf https://astral.sh/uv/install.sh | sh
98
+
99
+ - name: Create Python virtual environment
100
+ run: |
101
+ uv venv
102
+ uv pip install --upgrade setuptools wheel
103
+
104
+ - name: Install dependencies
105
+ run: |
106
+ source .venv/bin/activate
107
+ uv pip install ".[dev]"
108
+ uv pip install -U git+https://github.com/huggingface/transformers.git@${{ inputs.transformers_ref }}
109
+
110
+ - name: Run distributed smoke tests
111
+ run: |
112
+ source .venv/bin/activate
113
+ pytest -v tests/distributed/test_distributed.py
114
+
115
+ - name: Post to Slack
116
+ if: github.ref == 'refs/heads/main' && always()
117
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
118
+ with:
119
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
120
+ title: Results of distributed smoke tests with Transformers ${{ inputs.transformers_ref }}
121
+ status: ${{ job.status }}
122
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/trufflehog.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ on:
2
+ push:
3
+
4
+ name: Secret Leaks
5
+
6
+ jobs:
7
+ trufflehog:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - name: Checkout code
11
+ uses: actions/checkout@v6
12
+ with:
13
+ fetch-depth: 0
14
+ - name: Secret Scanning
15
+ uses: trufflesecurity/trufflehog@v3.93.1
16
+ with:
17
+ # exclude buggy postgres detector that is causing false positives and not relevant to our codebase
18
+ extra_args: --results=verified,unknown --exclude-detectors=postgres
tasks/tasksmith-4fc63afb85cd/tests/source/.github/workflows/upload_pr_documentation.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upload PR Documentation
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows: ["Build PR Documentation"]
6
+ types:
7
+ - completed
8
+
9
+ jobs:
10
+ build:
11
+ uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main
12
+ with:
13
+ package_name: trl
14
+ secrets:
15
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
16
+ comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }}
tasks/tasksmith-4fc63afb85cd/tests/source/.gitignore ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.bak
2
+ .gitattributes
3
+ .last_checked
4
+ .gitconfig
5
+ *.bak
6
+ *.log
7
+ *~
8
+ ~*
9
+ _tmp*
10
+ tmp*
11
+ tags
12
+
13
+ # Byte-compiled / optimized / DLL files
14
+ __pycache__/
15
+ *.py[cod]
16
+ *$py.class
17
+
18
+ # C extensions
19
+ *.so
20
+
21
+ # Distribution / packaging
22
+ .Python
23
+ env/
24
+ build/
25
+ develop-eggs/
26
+ dist/
27
+ downloads/
28
+ eggs/
29
+ .eggs/
30
+ lib/
31
+ lib64/
32
+ parts/
33
+ sdist/
34
+ var/
35
+ wheels/
36
+ *.egg-info/
37
+ .installed.cfg
38
+ *.egg
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .coverage
54
+ .coverage.*
55
+ .cache
56
+ nosetests.xml
57
+ coverage.xml
58
+ *.cover
59
+ .hypothesis/
60
+
61
+ # Translations
62
+ *.mo
63
+ *.pot
64
+
65
+ # Django stuff:
66
+ *.log
67
+ local_settings.py
68
+
69
+ # Flask stuff:
70
+ instance/
71
+ .webassets-cache
72
+
73
+ # Scrapy stuff:
74
+ .scrapy
75
+
76
+ # Sphinx documentation
77
+ docs/_build/
78
+
79
+ # PyBuilder
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # celery beat schedule file
89
+ celerybeat-schedule
90
+
91
+ # SageMath parsed files
92
+ *.sage.py
93
+
94
+ # dotenv
95
+ .env
96
+
97
+ # virtualenv
98
+ .venv
99
+ venv/
100
+ ENV/
101
+
102
+ # Spyder project settings
103
+ .spyderproject
104
+ .spyproject
105
+
106
+ # Rope project settings
107
+ .ropeproject
108
+
109
+ # mkdocs documentation
110
+ /site
111
+
112
+ # mypy
113
+ .mypy_cache/
114
+
115
+ .vscode
116
+ *.swp
117
+
118
+ # osx generated files
119
+ .DS_Store
120
+ .DS_Store?
121
+ .Trashes
122
+ ehthumbs.db
123
+ Thumbs.db
124
+ .idea
125
+
126
+ # pytest
127
+ .pytest_cache
128
+
129
+ # tools/trust-doc-nbs
130
+ docs_src/.last_checked
131
+
132
+ # symlinks to fastai
133
+ docs_src/fastai
134
+ tools/fastai
135
+
136
+ # link checker
137
+ checklink/cookies.txt
138
+
139
+ # .gitconfig is now autogenerated
140
+ .gitconfig
141
+
142
+ # wandb files
143
+ nbs/wandb/
144
+ examples/notebooks/wandb/
145
+ wandb/
146
+
147
+ # uv
148
+ uv.lock
tasks/tasksmith-4fc63afb85cd/tests/source/.pre-commit-config.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ rev: v0.13.3
4
+ hooks:
5
+ - id: ruff-check
6
+ types_or: [ python, pyi ]
7
+ args: [ --fix ]
8
+ - id: ruff-format
9
+ types_or: [ python, pyi ]
10
+
11
+ # - repo: https://github.com/codespell-project/codespell
12
+ # rev: v2.1.0
13
+ # hooks:
14
+ # - id: codespell
15
+ # args:
16
+ # - --ignore-words-list=nd,reacher,thist,ths,magent,ba
17
+ # - --skip=docs/css/termynal.css,docs/js/termynal.js
tasks/tasksmith-4fc63afb85cd/tests/source/AGENTS.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENTS.md
2
+
3
+ ## Repository-specific guidance
4
+
5
+ ### Main code vs experimental code
6
+
7
+ The repository is separated into **main code** and **experimental code**.
8
+
9
+ * **Main code** should remain stable, consistent, and well-tested.
10
+ * **Experimental code** may be less stable and may contain inconsistent patterns or limited testing.
11
+
12
+ Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors.
13
+
14
+ ### Paper implementations
15
+
16
+ If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`.
17
+
18
+ When reviewing such PRs, ensure that `paper_index.md` was updated.
19
+
20
+ ### Code duplication and consistency
21
+
22
+ Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class.
23
+
24
+ This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full.
25
+
26
+ **The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned:
27
+
28
+ - Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …)
29
+ - Same control flow structure (if/elif/else branches in the same order)
30
+ - Same comments (word-for-word when the logic is identical)
31
+ - Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them)
32
+
33
+ **Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep.
34
+
35
+ **When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug.
36
+
37
+ **When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others.
38
+
39
+ ### Simplicity
40
+
41
+ This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality.
42
+
43
+ Concretely:
44
+
45
+ - Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow.
46
+ - Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80.
47
+ - Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today.
48
+ - Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative.
49
+ - When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction.
50
+
51
+ ## Documentation
52
+
53
+ ### Docstrings
54
+
55
+ Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.).
56
+
57
+ Rules:
58
+
59
+ * Types appear in backticks inside parentheses: (`str`)
60
+ * Optional parameters are marked with `*optional*`
61
+ * Defaults are written as: `defaults to <value>`
62
+ * When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)```
63
+ * Union types use `or`: `str` or `None`
64
+ * References to classes use the format: [`~transformers.PreTrainedModel`]
65
+ * Class docstrings may group parameters using headers such as: `> Parameters for X:`
66
+
67
+ Example:
68
+
69
+ ````python
70
+ def method(self, param1: str, param2: int = 1, param3: float | None = None):
71
+ """
72
+ Brief one-line description of what this does.
73
+
74
+ Args:
75
+ param1 (`str`):
76
+ Description of required param.
77
+ param2 (`int`, *optional*, defaults to `1`):
78
+ Description of optional param with default.
79
+ param3 (`float`, *optional*):
80
+ Description of optional param without explicit default.
81
+
82
+ Returns:
83
+ `dict` with keys:
84
+ - `key1` (`list[int]`):
85
+ Description of this key.
86
+
87
+ Examples:
88
+
89
+ ```python
90
+ >>> my_func("hello")
91
+ ```
92
+ """
93
+ ````
94
+
95
+ ### Links to papers
96
+
97
+ When linking to papers, use `https://huggingface.co/papers/<id>` instead of `https://arxiv.org/abs/<id>` (same ID suffix system).
tasks/tasksmith-4fc63afb85cd/tests/source/CITATION.cff ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ title: 'TRL: Transformers Reinforcement Learning'
3
+ message: >-
4
+ If you use this software, please cite it using the
5
+ metadata from this file.
6
+ type: software
7
+ authors:
8
+ - given-names: Leandro
9
+ family-names: von Werra
10
+ - given-names: Younes
11
+ family-names: Belkada
12
+ - given-names: Lewis
13
+ family-names: Tunstall
14
+ - given-names: Edward
15
+ family-names: Beeching
16
+ - given-names: Tristan
17
+ family-names: Thrush
18
+ - given-names: Nathan
19
+ family-names: Lambert
20
+ - given-names: Shengyi
21
+ family-names: Huang
22
+ - given-names: Kashif
23
+ family-names: Rasul
24
+ - given-names: Quentin
25
+ family-names: Gallouédec
26
+ repository-code: 'https://github.com/huggingface/trl'
27
+ abstract: >-
28
+ TRL (Transformers Reinforcement Learning) is an
29
+ open-source toolkit for aligning transformer models via
30
+ post-training. It provides practical, scalable
31
+ implementations of SFT, reward modeling, DPO, and GRPO
32
+ within the Hugging Face ecosystem.
33
+ keywords:
34
+ - transformers
35
+ - reinforcement learning
36
+ - preference optimization
37
+ - language model alignment
38
+ - post-training
39
+ license: Apache-2.0
40
+ version: '0.29'
41
+ date-released: '2020-03-27'
tasks/tasksmith-4fc63afb85cd/tests/source/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, caste, color, religion, or sexual
11
+ identity and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ ## Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the overall
27
+ community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or advances of
32
+ any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email address,
36
+ without their explicit permission
37
+ * Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ ## Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ ## Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official e-mail address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ ## Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
+ feedback@huggingface.co.
65
+ All complaints will be reviewed and investigated promptly and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ ## Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ ### 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ ### 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series of
87
+ actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or permanent
94
+ ban.
95
+
96
+ ### 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ ### 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within the
114
+ community.
115
+
116
+ ## Attribution
117
+
118
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119
+ version 2.1, available at
120
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121
+
122
+ Community Impact Guidelines were inspired by
123
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124
+
125
+ For answers to common questions about this code of conduct, see the FAQ at
126
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127
+ [https://www.contributor-covenant.org/translations][translations].
128
+
129
+ [homepage]: https://www.contributor-covenant.org
130
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131
+ [Mozilla CoC]: https://github.com/mozilla/diversity
132
+ [FAQ]: https://www.contributor-covenant.org/faq
133
+ [translations]: https://www.contributor-covenant.org/translations
tasks/tasksmith-4fc63afb85cd/tests/source/CONTRIBUTING.md ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to contribute to TRL?
2
+
3
+ Everyone is welcome to contribute, and we value everybody's contribution. Code contributions are not the only way to help the community. Answering questions, helping others, and improving the documentation are also immensely valuable.
4
+
5
+ It also helps us if you spread the word! Reference the library in blog posts about the awesome projects it made possible, shout out on Twitter every time it has helped you, or simply ⭐️ the repository to say thank you.
6
+
7
+ However you choose to contribute, please be mindful and respect our [code of conduct](https://github.com/huggingface/trl/blob/main/CODE_OF_CONDUCT.md).
8
+
9
+ **This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).**
10
+
11
+ ## Ways to contribute
12
+
13
+ There are several ways you can contribute to TRL:
14
+
15
+ * Fix outstanding issues with the existing code.
16
+ * Submit issues related to bugs or desired new features.
17
+ * Implement trainers for new post-training algorithms.
18
+ * Contribute to the examples or the documentation.
19
+
20
+ If you don't know where to start, there is a special [Good First Issue](https://github.com/huggingface/trl/labels/%F0%9F%91%B6%20good%20first%20issue) listing. It will give you a list of open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over.
21
+
22
+ For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/trl/labels/%F0%9F%A7%92%20good%20second%20issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀
23
+
24
+ > All contributions are equally valuable to the community. 🥰
25
+
26
+ Before you start contributing make sure you have installed all the dev tools:
27
+
28
+ ```bash
29
+ pip install -e .[dev]
30
+ ```
31
+
32
+ ## Fixing outstanding issues
33
+
34
+ If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#submitting-a-pull-request-pr) and open a Pull Request!
35
+
36
+ ## Submitting a bug-related issue or feature request
37
+
38
+ Do your best to follow these guidelines when submitting a bug-related issue or a feature request. It will make it easier for us to come back to you quickly and with good feedback.
39
+
40
+ ### Did you find a bug?
41
+
42
+ The TRL library is robust and reliable thanks to users who report the problems they encounter.
43
+
44
+ Before you report an issue, we would really appreciate it if you could **make sure the bug was not already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code.
45
+
46
+ Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it:
47
+
48
+ * Your **OS type and version**, **Python**, **PyTorch**, **TRL** and **Transformers** versions.
49
+ * A short, self-contained, code snippet that allows us to reproduce the bug in less than 30s.
50
+ * The *full* traceback if an exception is raised.
51
+ * Attach any other additional information, like screenshots, you think may help.
52
+
53
+ To get the OS and software versions automatically, run the following command:
54
+
55
+ ```bash
56
+ trl env
57
+ ```
58
+
59
+ ### Do you want a new feature?
60
+
61
+ If there is a new feature you'd like to see in TRL, please open an issue and describe:
62
+
63
+ 1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community?
64
+
65
+ Whatever it is, we'd love to hear about it!
66
+
67
+ 2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you.
68
+ 3. Provide a *code snippet* that demonstrates the feature's usage.
69
+ 4. If the feature is related to a paper, please include a link.
70
+
71
+ If your issue is well written we're already 80% of the way there by the time you create it.
72
+
73
+ ## Do you want to implement a new trainer?
74
+
75
+ New post-training methods are published frequently and those that satisfy the following criteria are good candidates to be integrated into TRL:
76
+
77
+ * **Simplicity:** Does the new method achieve similar performance as prior methods, but with less complexity? A good example is Direct Preference Optimization (DPO) [[Rafailov et al, 2023]](https://huggingface.co/papers/2305.18290), which provided a simpler and compelling alternative to RLHF methods.
78
+ * **Efficiency:** Does the new method provide a significant improvement in training efficiency? A good example is Odds Ratio Preference Optimization (ORPO) [[Hong et al, 2023]](https://huggingface.co/papers/2403.07691), which utilizes a similar objective as DPO but requires half the GPU VRAM.
79
+
80
+ Methods that only provide incremental improvements at the expense of added complexity or compute costs are unlikely to be included in TRL.
81
+
82
+ If you want to implement a trainer for a new post-training method, first open an issue and provide the following information:
83
+
84
+ * A short description of the method and a link to the paper.
85
+ * Link to the implementation if it is open-sourced.
86
+ * Link to model weights trained with the method if they are available.
87
+
88
+ Based on the community and maintainer feedback, the next step will be to implement the trainer and config classes. See the following examples for inspiration:
89
+
90
+ * Paired preference optimisation: [`dpo_trainer.py`](./trl/trainer/dpo_trainer.py) and [`dpo_config.py`](./trl/trainer/dpo_config.py)
91
+ * RL-based optimisation: [`rloo_trainer.py`](./trl/trainer/rloo_trainer.py) and [`rloo_config.py`](./trl/trainer/rloo_config.py)
92
+ * Online optimisation: [`online_dpo_trainer.py`](./trl/trainer/online_dpo_trainer.py) and [`online_dpo_config.py`](./trl/trainer/online_dpo_config.py)
93
+
94
+ ## Do you want to add documentation?
95
+
96
+ We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved, such as typos, dead links, and any missing, unclear, or inaccurate content... We'll be happy to make the changes or help you contribute if you're interested!
97
+
98
+ ## Submitting a pull request (PR)
99
+
100
+ Before writing code, we strongly advise you to search through the existing PRs or issues to make sure that nobody is already working on the same thing. If you are unsure, it is always a good idea to open an issue to get some feedback.
101
+
102
+ You will need basic `git` proficiency to be able to contribute to TRL. `git` is not the easiest tool to use but it has the greatest manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro Git](https://git-scm.com/book/en/v2) is a very good reference.
103
+
104
+ Follow these steps to start contributing:
105
+
106
+ 1. Fork the [repository](https://github.com/huggingface/trl) by clicking on the 'Fork' button on the repository's page. This creates a copy of the code under your GitHub user account.
107
+
108
+ 2. Clone your fork to your local disk, and add the base repository as a remote. The following command assumes you have your public SSH key uploaded to GitHub. See the following guide for more [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository).
109
+
110
+ ```bash
111
+ git clone git@github.com:<your Github handle>/trl.git
112
+ cd trl
113
+ git remote add upstream https://github.com/huggingface/trl.git
114
+ ```
115
+
116
+ 3. Create a new branch to hold your development changes, and do this for every new PR you work on.
117
+
118
+ Start by synchronizing your `main` branch with the `upstream/main` branch (more details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)):
119
+
120
+ ```bash
121
+ git checkout main
122
+ git fetch upstream
123
+ git merge upstream/main
124
+ ```
125
+
126
+ Once your `main` branch is synchronized, create a new branch from it:
127
+
128
+ ```bash
129
+ git checkout -b a-descriptive-name-for-my-changes
130
+ ```
131
+
132
+ **Do not** work on the `main` branch.
133
+
134
+ 4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library:
135
+
136
+ ```bash
137
+ pip install -e .[dev]
138
+ ```
139
+
140
+ (If TRL was already installed in the virtual environment, remove it with `pip uninstall trl` before reinstalling it.)
141
+
142
+ Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using the provided Dev Container. Check [the documentation on how to get started with dev containers](https://code.visualstudio.com/docs/remote/containers).
143
+
144
+ 5. Develop the features on your branch.
145
+
146
+ As you work on the features, you should make sure that the test suite passes. You should run the tests impacted by your changes like this (see below an explanation regarding the environment variable):
147
+
148
+ ```bash
149
+ pytest tests/<TEST_TO_RUN>.py
150
+ ```
151
+
152
+ > For the following commands leveraging the `make` utility.
153
+
154
+ You can also run the full suite with the following command.
155
+
156
+ ```bash
157
+ make test
158
+ ```
159
+
160
+ TRL relies on `ruff` for maintaining consistent code formatting across its source files. Before submitting any PR, you should apply automatic style corrections and run code verification checks.
161
+
162
+ We provide a `precommit` target in the `Makefile` that simplifies this process by running all required checks and optimizations on only the files modified by your PR.
163
+
164
+ To apply these checks and corrections in one step, use:
165
+
166
+ ```bash
167
+ make precommit
168
+ ```
169
+
170
+ This command runs the following:
171
+
172
+ * Executes `pre-commit` hooks to automatically fix style issues with `ruff` and other tools.
173
+ * Runs additional scripts such as adding copyright information.
174
+
175
+ If you prefer to apply the style corrections separately or review them individually, the `pre-commit` hook will handle the formatting for the files in question.
176
+
177
+ Once you're happy with your changes, add changed files using `git add` and make a commit with `git commit` to record your changes locally:
178
+
179
+ ```bash
180
+ git add modified_file.py
181
+ git commit
182
+ ```
183
+
184
+ Please write [good commit messages](https://chris.beams.io/posts/git-commit/).
185
+
186
+ It is a good idea to sync your copy of the code with the original
187
+ repository regularly. This way you can quickly account for changes:
188
+
189
+ ```bash
190
+ git fetch upstream
191
+ git rebase upstream/main
192
+ ```
193
+
194
+ Push the changes to your account using:
195
+
196
+ ```bash
197
+ git push -u origin a-descriptive-name-for-my-changes
198
+ ```
199
+
200
+ 6. Once you are satisfied (**and the checklist below is happy too**), go to the webpage of your fork on GitHub. Click on 'Pull request' to send your changes to the project maintainers for review.
201
+
202
+ 7. It's ok if maintainers ask you for changes. It happens to core contributors too! To ensure everyone can review your changes in the pull request, work on your local branch and push the updates to your fork. They will automatically appear in the pull request.
203
+
204
+ ### Checklist
205
+
206
+ 1. The title of your pull request should be a summary of its contribution;
207
+ 2. If your pull request addresses an issue, please mention the issue number in the pull request description to make sure they are linked (and people consulting the issue know you are working on it);
208
+ 3. To indicate a work in progress please prefix the title with `[WIP]`, or mark the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate it from PRs ready to be merged;
209
+ 4. Make sure existing tests pass;
210
+ 5. Add high-coverage tests. No quality testing = no merge.
211
+
212
+ ### Tests
213
+
214
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
215
+ the [tests folder](https://github.com/huggingface/trl/tree/main/tests).
216
+
217
+ We use `pytest` to run the tests. From the root of the
218
+ repository here's how to run tests with `pytest` for the library:
219
+
220
+ ```bash
221
+ python -m pytest -sv ./tests
222
+ ```
223
+
224
+ That's how `make test` is implemented (without the `pip install` line)!
225
+
226
+ You can specify a smaller set of tests to test only the feature
227
+ you're working on.
228
+
229
+ ### Default values guidelines
230
+
231
+ 1. **Use defaults when appropriate**:
232
+
233
+ Provide default values unless the parameter's value varies significantly by use case. For example, datasets or models should not have defaults, but parameters like `learning_rate` should.
234
+
235
+ 2. **Prioritize proven defaults**:
236
+
237
+ Default values should align with those recommended in the original paper or method. Alternatives require strong evidence of superior performance in most cases.
238
+
239
+ 3. **Ensure safety and predictability**:
240
+
241
+ Defaults must be safe, expected and reliable. Avoid settings that could lead to surprising outcomes, such as excessive memory usage or poor performance in edge cases.
242
+
243
+ 4. **Balance consistency and flexibility**:
244
+
245
+ Aim for consistent defaults across similar functions or methods. However, consistency should not be preferred to point 2 or 3.
246
+
247
+ 5. **Opt-in for new features**:
248
+
249
+ Do not enable new features or improvements (e.g., novel loss functions) by default. Users should explicitly opt-in to use these.
250
+
251
+ ### Writing documentation
252
+
253
+ High-quality documentation is crucial for maintaining a project that is easy to use, understand, and extend. When adding new features, ensure they are thoroughly documented to maintain consistency and clarity throughout the project.
254
+
255
+ To illustrate what good documentation looks like, here’s an example of a well-documented function:
256
+
257
+ ````python
258
+ def replicate_str(string: str, n: int, sep: str = " ") -> str:
259
+ r"""
260
+ Replicate a string `n` times with a separator.
261
+
262
+ Args:
263
+ string (`str`):
264
+ String to replicate.
265
+ n (`int`):
266
+ Number of times to replicate the string.
267
+ sep (`str`, *optional*, defaults to `" "`):
268
+ Separator to use between each replication.
269
+
270
+ Returns:
271
+ `str`: The replicated string.
272
+
273
+ Examples:
274
+ ```python
275
+ >>> replicate_str("hello", 3)
276
+ "hello hello hello"
277
+ >>> replicate_str("hello", 3, sep=", ")
278
+ "hello, hello, hello"
279
+ ```
280
+ """
281
+ return sep.join([string] * n)
282
+ ````
283
+
284
+ * **Line Wrapping:** Applied a consistent line wrap at column 120 to improve readability.
285
+ * **Definite Articles:** Removed definite articles where possible to streamline language. (Eg: Changed "The string to replicate" to "String to replicate")
286
+ * **Type Annotations:**
287
+ * Always include type definitions, indicating if a parameter is optional and specifying the default value.
288
+
289
+ * **String Defaults:**
290
+ * Ensured that default string values are wrapped in double quotes:
291
+
292
+ ```txt
293
+ defaults to `"foo"`
294
+ ```
295
+
296
+ * **Dictionary Typing:**
297
+ * Replaced generic `dict` type hints with more explicit `dict[str, Any]` to clarify expected key-value pairs.
298
+ * **Default Value Formatting:**
299
+ * Consistently surrounded default values with backticks for improved formatting:
300
+
301
+ ```txt
302
+ defaults to `4`
303
+ ```
304
+
305
+ * **Sub-sectioning:** When the number of arguments is large, consider breaking them into sub-sections for better readability.
306
+
307
+ ```python
308
+ def calculate_statistics(data: list[float], precision: int = 2, include_variance: bool = False) -> dict[str, float]:
309
+ r"""
310
+ Calculates basic statistics for a given dataset.
311
+
312
+ Args:
313
+ > Data inputs
314
+
315
+ data (`list[float]`):
316
+ A list of numerical values to analyze.
317
+
318
+ > Configuration parameters
319
+
320
+ precision (`int`, *optional*, defaults to `2`):
321
+ Number of decimal places to round the results.
322
+ include_variance (`bool`, *optional*, defaults to `False`):
323
+ Whether to include the variance of the dataset in the results.
324
+
325
+ Returns:
326
+ `dict[str, float]`:
327
+ A dictionary containing calculated statistics such as mean, median, and optionally variance.
328
+ """
329
+ ...
330
+ ```
331
+
332
+ ### Deprecation and backward compatibility
333
+
334
+ Our approach to deprecation and backward compatibility is flexible and based on the feature’s usage and impact. Each deprecation is carefully evaluated, aiming to balance innovation with user needs.
335
+
336
+ When a feature or component is marked for deprecation, its use will emit a warning message. This warning will include:
337
+
338
+ * **Transition Guidance**: Instructions on how to migrate to the alternative solution or replacement.
339
+ * **Removal Version**: The target version when the feature will be removed, providing users with a clear timeframe to transition.
340
+
341
+ Example:
342
+
343
+ ```python
344
+ warnings.warn(
345
+ "The `Trainer.foo` method is deprecated and will be removed in version 0.14.0. "
346
+ "Please use the `Trainer.bar` class instead.",
347
+ FutureWarning,
348
+ stacklevel=2,
349
+ )
350
+ ```
351
+
352
+ The deprecation and removal schedule is based on each feature's usage and impact, with examples at two extremes:
353
+
354
+ * **Experimental or Low-Use Features**: For a feature that is experimental or has limited usage, backward compatibility may not be maintained between releases. Users should therefore anticipate potential breaking changes from one version to the next.
355
+
356
+ * **Widely-Used Components**: For a feature with high usage, we aim for a more gradual transition period of approximately **5 months**, generally scheduling deprecation around **5 minor releases** after the initial warning.
357
+
358
+ These examples represent the two ends of a continuum. The specific timeline for each feature will be determined individually, balancing innovation with user stability needs.
359
+
360
+ ### Working with warnings
361
+
362
+ Warnings play a critical role in guiding users toward resolving potential issues, but they should be used thoughtfully to avoid unnecessary noise. Unlike logging, which provides informational context or operational details, warnings signal conditions that require attention and action. Overusing warnings can dilute their importance, leading users to ignore them entirely.
363
+
364
+ #### Definitions
365
+
366
+ * **Correct**: An operation is correct if it is valid, follows the intended approach, and aligns with the current best practices or guidelines within the codebase. This is the recommended or intended way to perform the operation.
367
+ * **Supported**: An operation is supported if it is technically valid and works within the current codebase, but it may not be the most efficient, optimal, or recommended way to perform the task. This includes deprecated features or legacy approaches that still work but may be phased out in the future.
368
+
369
+ #### Choosing the right message
370
+
371
+ * **Correct → No warning**:
372
+ If the operation is fully valid and expected, no message should be issued. The system is working as intended, so no warning is necessary.
373
+
374
+ * **Correct but deserves attention → No warning, possibly a log message**:
375
+ When an operation is correct but uncommon or requires special attention, providing an informational message can be helpful. This keeps users informed without implying any issue. If available, use the logger to output this message. Example:
376
+
377
+ ```python
378
+ logger.info("This is an informational message about a rare but correct operation.")
379
+ ```
380
+
381
+ * **Correct but very likely a mistake → Warning with option to disable**:
382
+ In rare cases, you may want to issue a warning for a correct operation that’s very likely a mistake. In such cases, you must provide an option to suppress the warning. This can be done with a flag in the function. Example:
383
+
384
+ ```python
385
+ def my_function(foo, bar, _warn=True):
386
+ if foo == bar:
387
+ if _warn:
388
+ logger.warning("foo and bar are the same, this is likely a mistake. Ignore this warning by setting `_warn=False`.")
389
+ # Do something
390
+ ```
391
+
392
+ * **Supported but not correct → Warning**:
393
+ If the operation is technically supported but is deprecated, suboptimal, or could cause future issues (e.g., conflicting arguments), a warning should be raised. This message should be actionable, meaning it must explain how to resolve the issue. Example:
394
+
395
+ ```python
396
+ def my_function(foo, bar):
397
+ if foo and bar:
398
+ logger.warning("Both `foo` and `bar` were provided, but only one is allowed. Ignoring `foo`. Please pass only one of these arguments.")
399
+ # Do something
400
+ ```
401
+
402
+ * **Not supported → Exception**:
403
+ If the operation is invalid or unsupported, raise an exception. This indicates that the operation cannot be performed and requires immediate attention. Example:
404
+
405
+ ```python
406
+ def my_function(foo, bar):
407
+ if foo and bar:
408
+ raise ValueError("Both `foo` and `bar` were provided, but only one is allowed. Please pass only one of these arguments.")
409
+ ```
410
+
411
+ By following this classification, you ensure that warnings, information, and exceptions are used appropriately, providing clear guidance to the user without cluttering the system with unnecessary messages.
tasks/tasksmith-4fc63afb85cd/tests/source/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020-2026 The HuggingFace Team
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
tasks/tasksmith-4fc63afb85cd/tests/source/MANIFEST.in ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ include LICENSE
2
+ include CONTRIBUTING.md
3
+ include README.md
4
+ include trl/accelerate_configs/*.yaml
5
+ include trl/templates/*.md
6
+ include trl/skills/**/*.md
7
+ recursive-exclude * __pycache__
8
+ prune tests
tasks/tasksmith-4fc63afb85cd/tests/source/MIGRATION.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Migrating from TRL v0 to v1
2
+
3
+ This guide covers the breaking changes introduced in TRL v1 and how to update your code. Most structural changes (trainers moved to experimental, removed model classes, etc.) already shipped in v0.29 — if you're already on v0.29, this migration is minimal.
4
+
5
+ ## Changed defaults
6
+
7
+ | Config | Parameter | v0 default | v1 default | Action needed |
8
+ | --- | --- | --- | --- | --- |
9
+ | `GRPOConfig` | `vllm_mode` | `"server"` | `"colocate"` | If you use `use_vllm=True` without specifying `vllm_mode`, vLLM will now run in the same process instead of connecting to a separate server. Set `vllm_mode="server"` explicitly if you rely on server mode. |
10
+ | `RLOOConfig` | `vllm_mode` | `"server"` | `"colocate"` | Same as above. |
11
+
12
+ ## Renamed options
13
+
14
+ | Config | Parameter | v0 value | v1 value | Action needed |
15
+ | --- | --- | --- | --- | --- |
16
+ | `SFTConfig` | `packing` | `"bfd-requeue"` | `"bfd_split"` | Replace `packing="bfd-requeue"` with `packing="bfd_split"`. The old value will still be accepted for a few versions but will be removed in a future release. |
17
+
18
+ ## Migrating from an earlier version
19
+
20
+ Depending on which version you're migrating from, refer to the [release notes](https://github.com/huggingface/trl/releases) for v0.29 and earlier for version-specific changes.
tasks/tasksmith-4fc63afb85cd/tests/source/Makefile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: test precommit common_tests slow_tests tests_gpu test_experimental
2
+
3
+ check_dirs := examples tests trl
4
+
5
+ ACCELERATE_CONFIG_PATH = `pwd`/examples/accelerate_configs
6
+
7
+ test:
8
+ pytest -n auto -m "not slow and not low_priority" -s -v --reruns 5 --reruns-delay 1 --only-rerun '(OSError|Timeout|HTTPError.*502|HTTPError.*504||not less than or equal to 0.01)' tests
9
+
10
+ precommit:
11
+ python scripts/add_copyrights.py
12
+ pre-commit run --all-files
13
+ doc-builder style trl tests docs/source --max_len 119
14
+
15
+ slow_tests:
16
+ pytest -m "slow" tests/ $(if $(IS_GITHUB_CI),--report-log "slow_tests.log",)
17
+
18
+ test_experimental:
19
+ pytest -n auto -s -v tests/experimental
tasks/tasksmith-4fc63afb85cd/tests/source/README.md ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TRL - Transformers Reinforcement Learning
2
+
3
+ <div style="text-align: center">
4
+ <picture>
5
+ <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/TRL%20banner%20light.png">
6
+ <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/trl_banner_dark.png" alt="TRL Banner">
7
+ </picture>
8
+ </div>
9
+
10
+ <hr> <br>
11
+
12
+ <h3 align="center">
13
+ <p>A comprehensive library to post-train foundation models</p>
14
+ </h3>
15
+
16
+ <p align="center">
17
+ <a href="https://github.com/huggingface/trl/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/trl.svg?color=blue"></a>
18
+ <a href="https://huggingface.co/docs/trl/index"><img alt="Documentation" src="https://img.shields.io/website?label=documentation&url=https%3A%2F%2Fhuggingface.co%2Fdocs%2Ftrl%2Findex&down_color=red&down_message=offline&up_color=blue&up_message=online"></a>
19
+ <a href="https://github.com/huggingface/trl/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/trl.svg"></a>
20
+ <a href="https://huggingface.co/trl-lib"><img alt="Hugging Face Hub" src="https://img.shields.io/badge/🤗%20Hub-trl--lib-yellow"></a>
21
+ </p>
22
+
23
+ ## 🎉 What's New
24
+
25
+ **OpenEnv Integration:** TRL now supports **[OpenEnv](https://huggingface.co/blog/openenv)**, the open-source framework from Meta for defining, deploying, and interacting with environments in reinforcement learning and agentic workflows.
26
+
27
+ Explore how to seamlessly integrate TRL with OpenEnv in our [dedicated documentation](https://huggingface.co/docs/trl/openenv).
28
+
29
+ ## Overview
30
+
31
+ TRL is a cutting-edge library designed for post-training foundation models using advanced techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), and Direct Preference Optimization (DPO). Built on top of the [🤗 Transformers](https://github.com/huggingface/transformers) ecosystem, TRL supports a variety of model architectures and modalities, and can be scaled-up across various hardware setups.
32
+
33
+ ## Highlights
34
+
35
+ - **Trainers**: Various fine-tuning methods are easily accessible via trainers like [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer), [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer), [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer), [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer) and more.
36
+
37
+ - **Efficient and scalable**:
38
+ - Leverages [🤗 Accelerate](https://github.com/huggingface/accelerate) to scale from single GPU to multi-node clusters using methods like [DDP](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) and [DeepSpeed](https://github.com/deepspeedai/DeepSpeed).
39
+ - Full integration with [🤗 PEFT](https://github.com/huggingface/peft) enables training on large models with modest hardware via quantization and LoRA/QLoRA.
40
+ - Integrates [🦥 Unsloth](https://github.com/unslothai/unsloth) for accelerating training using optimized kernels.
41
+
42
+ - **Command Line Interface (CLI)**: A simple interface lets you fine-tune with models without needing to write code.
43
+
44
+ ## Installation
45
+
46
+ ### Python Package
47
+
48
+ Install the library using `pip`:
49
+
50
+ ```bash
51
+ pip install trl
52
+ ```
53
+
54
+ ### From source
55
+
56
+ If you want to use the latest features before an official release, you can install TRL from source:
57
+
58
+ ```bash
59
+ pip install git+https://github.com/huggingface/trl.git
60
+ ```
61
+
62
+ ### Repository
63
+
64
+ If you want to use the examples you can clone the repository with the following command:
65
+
66
+ ```bash
67
+ git clone https://github.com/huggingface/trl.git
68
+ ```
69
+
70
+ ## Quick Start
71
+
72
+ For more flexibility and control over training, TRL provides dedicated trainer classes to post-train language models or PEFT adapters on a custom dataset. Each trainer in TRL is a light wrapper around the 🤗 Transformers trainer and natively supports distributed training methods like DDP, DeepSpeed ZeRO, and FSDP.
73
+
74
+ ### `SFTTrainer`
75
+
76
+ Here is a basic example of how to use the [`SFTTrainer`](https://huggingface.co/docs/trl/sft_trainer):
77
+
78
+ ```python
79
+ from trl import SFTTrainer
80
+ from datasets import load_dataset
81
+
82
+ dataset = load_dataset("trl-lib/Capybara", split="train")
83
+
84
+ trainer = SFTTrainer(
85
+ model="Qwen/Qwen2.5-0.5B",
86
+ train_dataset=dataset,
87
+ )
88
+ trainer.train()
89
+ ```
90
+
91
+ ### `GRPOTrainer`
92
+
93
+ [`GRPOTrainer`](https://huggingface.co/docs/trl/grpo_trainer) implements the [Group Relative Policy Optimization (GRPO) algorithm](https://huggingface.co/papers/2402.03300) that is more memory-efficient than PPO and was used to train [Deepseek AI's R1](https://huggingface.co/deepseek-ai/DeepSeek-R1).
94
+
95
+ ```python
96
+ from datasets import load_dataset
97
+ from trl import GRPOTrainer
98
+ from trl.rewards import accuracy_reward
99
+
100
+ dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
101
+
102
+ trainer = GRPOTrainer(
103
+ model="Qwen/Qwen2.5-0.5B-Instruct",
104
+ reward_funcs=accuracy_reward,
105
+ train_dataset=dataset,
106
+ )
107
+ trainer.train()
108
+ ```
109
+
110
+ > [!NOTE]
111
+ > For reasoning models, use the `reasoning_accuracy_reward()` function for better results.
112
+
113
+ ### `DPOTrainer`
114
+
115
+ [`DPOTrainer`](https://huggingface.co/docs/trl/dpo_trainer) implements the popular [Direct Preference Optimization (DPO) algorithm](https://huggingface.co/papers/2305.18290) that was used to post-train [Llama 3](https://huggingface.co/papers/2407.21783) and many other models. Here is a basic example of how to use the `DPOTrainer`:
116
+
117
+ ```python
118
+ from datasets import load_dataset
119
+ from trl import DPOTrainer
120
+
121
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
122
+
123
+ trainer = DPOTrainer(
124
+ model="Qwen3/Qwen-0.6B",
125
+ train_dataset=dataset,
126
+ )
127
+ trainer.train()
128
+ ```
129
+
130
+ ### `RewardTrainer`
131
+
132
+ Here is a basic example of how to use the [`RewardTrainer`](https://huggingface.co/docs/trl/reward_trainer):
133
+
134
+ ```python
135
+ from trl import RewardTrainer
136
+ from datasets import load_dataset
137
+
138
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
139
+
140
+ trainer = RewardTrainer(
141
+ model="Qwen/Qwen2.5-0.5B-Instruct",
142
+ train_dataset=dataset,
143
+ )
144
+ trainer.train()
145
+ ```
146
+
147
+ ## Command Line Interface (CLI)
148
+
149
+ You can use the TRL Command Line Interface (CLI) to quickly get started with post-training methods like Supervised Fine-Tuning (SFT) or Direct Preference Optimization (DPO):
150
+
151
+ **SFT:**
152
+
153
+ ```bash
154
+ trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \
155
+ --dataset_name trl-lib/Capybara \
156
+ --output_dir Qwen2.5-0.5B-SFT
157
+ ```
158
+
159
+ **DPO:**
160
+
161
+ ```bash
162
+ trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
163
+ --dataset_name argilla/Capybara-Preferences \
164
+ --output_dir Qwen2.5-0.5B-DPO
165
+ ```
166
+
167
+ Read more about CLI in the [relevant documentation section](https://huggingface.co/docs/trl/clis) or use `--help` for more details.
168
+
169
+ ## Development
170
+
171
+ If you want to contribute to `trl` or customize it to your needs make sure to read the [contribution guide](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md) and make sure you make a dev install:
172
+
173
+ ```bash
174
+ git clone https://github.com/huggingface/trl.git
175
+ cd trl/
176
+ pip install -e .[dev]
177
+ ```
178
+
179
+ ## Experimental
180
+
181
+ A minimal incubation area is available under `trl.experimental` for unstable / fast-evolving features. Anything there may change or be removed in any release without notice.
182
+
183
+ Example:
184
+
185
+ ```python
186
+ from trl.experimental.new_trainer import NewTrainer
187
+ ```
188
+
189
+ Read more in the [Experimental docs](https://huggingface.co/docs/trl/experimental_overview).
190
+
191
+ ## Citation
192
+
193
+ ```bibtex
194
+ @software{vonwerra2020trl,
195
+ title = {{TRL: Transformers Reinforcement Learning}},
196
+ author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin},
197
+ license = {Apache-2.0},
198
+ url = {https://github.com/huggingface/trl},
199
+ year = {2020}
200
+ }
201
+ ```
202
+
203
+ ## License
204
+
205
+ This repository's source code is available under the [Apache-2.0 License](LICENSE).
tasks/tasksmith-4fc63afb85cd/tests/source/RELEASE.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Making a release
2
+
3
+ > [!NOTE]
4
+ > VERSION needs to be formatted following the `v{major}.{minor}.{patch}` convention. We need to follow this convention to be able to retrieve versioned scripts.
5
+
6
+ ## Major/Minor Release
7
+
8
+ ### 1. Ensure your local repository is up to date with the upstream repository
9
+
10
+ ```bash
11
+ git checkout main
12
+ git pull origin main
13
+ ```
14
+
15
+ > [!WARNING]
16
+ > Do not merge other pull requests into `main` until the release is done. This is to ensure that the release is stable and does not include any untested changes. Announce internally (#trl-internal) to other maintainers that you are doing a release and that they must not merge PRs until the release is done.
17
+
18
+ ### 2. Create a release branch from main
19
+
20
+ ```bash
21
+ git checkout -b release-v{major}.{minor}
22
+ ```
23
+
24
+ ### 3. Change the version in the following files
25
+
26
+ - `.github/workflows/tests_latest.yml`:
27
+
28
+ ```diff
29
+ - with: { ref: v{major}.{minor-1}-release }
30
+ + with: { ref: v{major}.{minor}-release }
31
+ ```
32
+
33
+ - `CITATION.cff`
34
+
35
+ ```diff
36
+ - version: '{major}.{minor-1}'
37
+ + version: '{major}.{minor}'
38
+ ```
39
+
40
+ - `VERSION`
41
+
42
+ ```diff
43
+ - {major}.{minor}.0.dev0
44
+ + {major}.{minor}.0
45
+ ```
46
+
47
+ ### 4. Commit and push these changes
48
+
49
+ ```shell
50
+ git add .github/workflows/tests_latest.yml CITATION.cff VERSION
51
+ git commit -m 'Release: {major}.{minor}'
52
+ git push origin release-v{major}.{minor}
53
+ ```
54
+
55
+ ### 5. Create a pull request
56
+
57
+ from `release-v{major}.{minor}` to `main`, named `Release: v{major}.{minor}`, wait for tests to pass, and request a review.
58
+
59
+ ### 6. Once the pull request is approved, merge it into `main`
60
+
61
+ It will automatically publish the new version of the package on PyPI.
62
+
63
+ ### 7. Add a tag in git to mark the release
64
+
65
+ ```shell
66
+ git checkout main
67
+ git pull origin main
68
+ git tag -a v{major}.{minor}.0 -m 'Adds tag v{major}.{minor}.0 for PyPI'
69
+ git push origin v{major}.{minor}.0
70
+ ```
71
+
72
+ ### 8. Create a branch `v{major}.{minor}-release` for future patch releases
73
+
74
+ ```shell
75
+ git checkout -b v{major}.{minor}-release
76
+ git push origin v{major}.{minor}-release
77
+ ```
78
+
79
+ This ensures that future patch releases (`v{major}.{minor}.1`, `v{major}.{minor}.2`, etc.) can be made separately from `main`.
80
+
81
+ ### 9. Create a GitHub Release
82
+
83
+ 1. Go to the repo’s [releases section](https://github.com/huggingface/trl/releases) on GitHub.
84
+ 2. Click **Draft a new release**.
85
+ 3. Select the `v{major}.{minor}.0` tag you just created in step 7.
86
+ 4. Add a title (`v{major}.{minor}.0`) and a short description of what’s new.
87
+ 5. Click **Publish Release**.
88
+
89
+ ### 10. Bump to dev version
90
+
91
+ 1. Create a branch `bump-dev-version-{major}.{minor+1}` from `main` and checkout to it.
92
+
93
+ ```shell
94
+ git checkout -b bump-dev-version-{major}.{minor+1}
95
+ ```
96
+
97
+ 2. Change the version in file `VERSION`:
98
+
99
+ ```diff
100
+ - {major}.{minor}.0
101
+ + {major}.{minor+1}.0.dev0
102
+ ```
103
+
104
+ 3. Commit and push these changes
105
+
106
+ ```shell
107
+ git add VERSION
108
+ git commit -m '⬆️ Bump dev version'
109
+ git push origin bump-dev-version-{major}.{minor+1}
110
+ ```
111
+
112
+ 4. Create a pull request from `bump-dev-version-{major}.{minor+1}` to `main`, named `⬆️ Bump dev version`, and request urgent review.
113
+
114
+ 5. Once the pull request is approved, merge it into `main`.
115
+
116
+ 6. The codebase is now ready for the next development cycle, inform the team in the #trl-internal channel.
117
+
118
+ ## Making a patch release
119
+
120
+ ### 1. Ensure your local repository is up to date with the upstream repository
121
+
122
+ ```bash
123
+ git checkout v{major}.{minor}-release
124
+ git pull origin main
125
+ ```
126
+
127
+ ### 2. Cherry-pick the changes you want to include in the patch release
128
+
129
+ ```bash
130
+ git cherry-pick <commit-hash-0>
131
+ git cherry-pick <commit-hash-1>
132
+ ...
133
+ ```
134
+
135
+ ### 3. Change the version in the file `VERSION`
136
+
137
+ ```diff
138
+ - {major}.{minor}.{patch-1}
139
+ + {major}.{minor}.{patch}
140
+ ```
141
+
142
+ ### 4. Commit and push these changes
143
+
144
+ ```shell
145
+ git add VERSION
146
+ git commit -m 'Release: {major}.{minor}.{patch}'
147
+ git push origin v{major}.{minor}-release
148
+ ```
149
+
150
+ ### 5. Wait for the CI to pass
151
+
152
+ The CI will automatically publish the new version of the package on PyPI.
153
+
154
+ ### 6. Add a tag in git to mark the release
155
+
156
+ ```shell
157
+ git tag -a v{major}.{minor}.{patch} -m 'Adds tag v{major}.{minor}.{patch} for PyPI'
158
+ git push origin v{major}.{minor}.{patch}
159
+ ```
160
+
161
+ #### 7. Create a GitHub Release
162
+
163
+ 1. Go to the repo’s [releases section](https://github.com/huggingface/trl/releases) on GitHub.
164
+ 2. Click **Draft a new release**.
165
+ 3. Select the `v{major}.{minor}.{patch}` tag you just created in step 7.
166
+ 4. Add a title (`v{major}.{minor}.{patch}`) and a short description of what’s new.
167
+ 5. Click **Publish Release**.
tasks/tasksmith-4fc63afb85cd/tests/source/VERSION ADDED
@@ -0,0 +1 @@
 
 
1
+ 1.0.0.dev0
tasks/tasksmith-4fc63afb85cd/tests/source/assets/logo-dark.png ADDED

Git LFS Details

  • SHA256: ac72e1dc6b93dac4cdae7d10f36a8d274c10a29918d19b5887d764cd3972e1ba
  • Pointer size: 130 Bytes
  • Size of remote file: 30.5 kB
tasks/tasksmith-4fc63afb85cd/tests/source/assets/logo-light.png ADDED

Git LFS Details

  • SHA256: 902ecba8e7b1d2fb4621f3ca38ff0edb968de38f4061d8743b5a4965d3af1f33
  • Pointer size: 131 Bytes
  • Size of remote file: 137 kB
tasks/tasksmith-4fc63afb85cd/tests/source/docker/trl-dev/Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
2
+ RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
3
+ RUN pip install --upgrade pip uv
4
+ RUN uv pip install --system --no-cache "git+https://github.com/huggingface/trl.git#egg=trl[liger,peft,vlm]"
5
+ RUN uv pip install --system kernels liger_kernel peft trackio
tasks/tasksmith-4fc63afb85cd/tests/source/docker/trl/Dockerfile ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
2
+ RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
3
+ RUN pip install --upgrade pip uv
4
+ RUN uv pip install --system trl[liger,peft,vlm] kernels trackio
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/_toctree.yml ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: TRL
4
+ - local: installation
5
+ title: Installation
6
+ - local: quickstart
7
+ title: Quickstart
8
+ title: Getting started
9
+ - sections:
10
+ - local: dataset_formats
11
+ title: Dataset Formats
12
+ - local: paper_index
13
+ title: Paper Index
14
+ title: Conceptual Guides
15
+ - sections: # Sorted alphabetically
16
+ - local: dpo_trainer
17
+ title: DPO
18
+ - local: grpo_trainer
19
+ title: GRPO
20
+ - local: reward_trainer
21
+ title: Reward
22
+ - local: rloo_trainer
23
+ title: RLOO
24
+ - local: sft_trainer
25
+ title: SFT
26
+ title: Trainers
27
+ - sections:
28
+ - local: clis
29
+ title: Command Line Interface (CLI)
30
+ - local: jobs_training
31
+ title: Training using Jobs
32
+ - local: customization
33
+ title: Customizing the Training
34
+ - local: reducing_memory_usage
35
+ title: Reducing Memory Usage
36
+ - local: speeding_up_training
37
+ title: Speeding Up Training
38
+ - local: distributing_training
39
+ title: Distributing Training
40
+ - local: use_model
41
+ title: Using Trained Models
42
+ title: How-to guides
43
+ - sections:
44
+ - local: deepspeed_integration
45
+ title: DeepSpeed
46
+ - local: kernels_hub
47
+ title: Kernels Hub
48
+ - local: liger_kernel_integration
49
+ title: Liger Kernel
50
+ - local: openenv
51
+ title: OpenEnv
52
+ - local: peft_integration
53
+ title: PEFT
54
+ - local: ptt_integration
55
+ title: Post Training Toolkit
56
+ - local: rapidfire_integration
57
+ title: RapidFire AI
58
+ - local: trackio_integration
59
+ title: Trackio
60
+ - local: unsloth_integration
61
+ title: Unsloth
62
+ - local: vllm_integration
63
+ title: vLLM
64
+ title: Integrations
65
+ - sections:
66
+ - local: example_overview
67
+ title: Example Overview
68
+ - local: community_tutorials
69
+ title: Community Tutorials
70
+ - local: lora_without_regret
71
+ title: LoRA Without Regret
72
+ title: Examples
73
+ - sections:
74
+ - sections:
75
+ - local: chat_template_utils
76
+ title: Chat Template Utilities
77
+ - local: data_utils
78
+ title: Data Utilities
79
+ - local: script_utils
80
+ title: Script Utilities
81
+ title: Utilities
82
+ - local: callbacks
83
+ title: Callbacks
84
+ - local: rewards
85
+ title: Reward Functions
86
+ title: API
87
+ - sections:
88
+ - local: experimental_overview
89
+ title: Experimental Overview
90
+ - local: async_grpo_trainer # Sorted alphabetically
91
+ title: Asynchronous GRPO
92
+ - local: bema_for_reference_model
93
+ title: BEMA for Reference Model
94
+ - local: bco_trainer
95
+ title: BCO
96
+ - local: cpo_trainer
97
+ title: CPO
98
+ - local: gfpo
99
+ title: GFPO
100
+ - local: gkd_trainer
101
+ title: GKD
102
+ - local: gold_trainer
103
+ title: GOLD
104
+ - local: grpo_with_replay_buffer
105
+ title: GRPO With Replay Buffer
106
+ - local: gspo_token
107
+ title: GSPO-token
108
+ - local: judges
109
+ title: Judges
110
+ - local: kto_trainer
111
+ title: KTO
112
+ - local: merge_model_callback
113
+ title: MergeModelCallback
114
+ - local: minillm_trainer
115
+ title: MiniLLM
116
+ - local: nash_md_trainer
117
+ title: Nash-MD
118
+ - local: nemo_gym
119
+ title: NeMo Gym
120
+ - local: online_dpo_trainer
121
+ title: Online DPO
122
+ - local: orpo_trainer
123
+ title: ORPO
124
+ - local: papo_trainer
125
+ title: PAPO
126
+ - local: ppo_trainer
127
+ title: PPO
128
+ - local: prm_trainer
129
+ title: PRM
130
+ - local: sdft_trainer
131
+ title: SDFT
132
+ - local: sdpo_trainer
133
+ title: SDPO
134
+ - local: winrate_callback
135
+ title: WinRateCallback
136
+ - local: xpo_trainer
137
+ title: XPO
138
+ title: Experimental
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/async_grpo_trainer.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Asynchronous GRPO
2
+
3
+ > [!IMPORTANT]
4
+ > This trainer requires `vllm>=0.17.1` and `transformers>=5.2.0`. For distributed training, only FSDP2 is supported (DeepSpeed ZeRO is not).
5
+ >
6
+ > Currently, `vllm` and `transformers` have conflicting dependency constraints. To work around this, install vLLM first and then force-install transformers:
7
+ >
8
+ > ```bash
9
+ > pip install 'vllm>=0.17.1'
10
+ > pip install 'transformers>=5.2.0' --no-deps
11
+ > ```
12
+
13
+ ## Overview
14
+
15
+ [`AsyncGRPOTrainer`] implements the same [GRPO](grpo_trainer) algorithm but decouples rollout generation from training. A background worker continuously streams completions from a vLLM server while the training loop consumes them, so generation and gradient updates overlap instead of alternating. The API mirrors [`GRPOTrainer`] — for full details on the GRPO method itself (advantage computation, KL estimation, loss formulation, reward functions, etc.), see the [GRPO Trainer](grpo_trainer) documentation. Not all features from [`GRPOTrainer`] are available; refer to [`AsyncGRPOConfig`] for the supported parameters.
16
+
17
+ This trainer was contributed by [Quentin Gallouédec](https://huggingface.co/qgallouedec) and [Amine Dirhoussi](https://huggingface.co/aminediroHF).
18
+
19
+ ## How it differs from [`GRPOTrainer`]
20
+
21
+ In the standard [`GRPOTrainer`], generation and training are sequential: generate a batch, compute the loss, update weights, repeat. Even in [vLLM colocate mode](grpo_trainer#speed-up-training-with-vllm), where generation runs on the same GPUs, one phase must finish before the other begins.
22
+
23
+ [`AsyncGRPOTrainer`] separates these two concerns:
24
+
25
+ - **Rollout worker** (background thread) — sends prompts to a vLLM server, scores completions with reward functions, computes advantages, and pushes ready-to-train samples into a queue.
26
+ - **Training loop** (main process) — pulls samples from the queue, computes the clipped surrogate loss, and updates the model weights.
27
+
28
+ After every `weight_sync_steps` training steps, the updated weights are transferred to the vLLM server via NCCL so that subsequent generations reflect the latest policy.
29
+
30
+ Because generation and training run concurrently, the training samples may have been generated by a slightly older version of the model. The `max_staleness` parameter controls how many weight updates a sample can lag behind before being discarded.
31
+
32
+ The number of concurrent requests sent to the vLLM server is controlled by `max_inflight_tasks`. By default it is set automatically to `max_staleness × per_device_train_batch_size × gradient_accumulation_steps × num_processes` — the maximum number of samples the trainer can consume before they become stale. Generating more than this is wasteful since the excess samples will be discarded.
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ # train_async_grpo.py
38
+ from datasets import load_dataset
39
+ from trl.experimental.async_grpo import AsyncGRPOTrainer
40
+ from trl.rewards import accuracy_reward
41
+
42
+ dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
43
+
44
+ trainer = AsyncGRPOTrainer(
45
+ model="Qwen/Qwen3-4B",
46
+ reward_funcs=accuracy_reward,
47
+ train_dataset=dataset,
48
+ )
49
+ trainer.train()
50
+ ```
51
+
52
+ The vLLM server and the trainer must run on **separate GPUs**. Use `CUDA_VISIBLE_DEVICES` to partition your GPUs. For example, with 2 GPUs, you can run the vLLM server on GPU 0 and the trainer on GPU 1 as follows:
53
+
54
+ ```bash
55
+ # Terminal 1: vLLM server on GPU 0 (dev mode + NCCL weight transfer are required)
56
+ CUDA_VISIBLE_DEVICES=0 VLLM_SERVER_DEV_MODE=1 vllm serve Qwen/Qwen3-4B \
57
+ --max-model-len 4096 \
58
+ --logprobs-mode processed_logprobs \
59
+ --weight-transfer-config '{"backend":"nccl"}'
60
+ ```
61
+
62
+ > [!TIP]
63
+ > Set `--max-model-len` to the maximum total sequence length (prompt + completion) you expect. A lower value reduces GPU memory usage on the server, freeing more memory for the KV cache and increasing throughput. A good starting point is the prompt length plus `max_completion_length` from your config.
64
+
65
+ ```bash
66
+ # Terminal 2: training on GPU 1
67
+ CUDA_VISIBLE_DEVICES=1 accelerate launch train_async_grpo.py
68
+ ```
69
+
70
+ ## Design philosophy
71
+
72
+ This trainer is intentionally kept minimal and is not meant to grow into a general-purpose solution. If you need a feature that is not supported, we recommend cloning the repository and adapting the trainer to your needs directly. New features will only be considered when there is significant community demand.
73
+
74
+ ## AsyncGRPOConfig
75
+
76
+ [[autodoc]] trl.experimental.async_grpo.AsyncGRPOConfig
77
+
78
+ ## AsyncGRPOTrainer
79
+
80
+ [[autodoc]] trl.experimental.async_grpo.AsyncGRPOTrainer
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/bco_trainer.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BCO Trainer
2
+
3
+ [![model badge](https://img.shields.io/badge/All_models-BCO-blue)](https://huggingface.co/models?other=bco,trl)
4
+
5
+ TRL supports the Binary Classifier Optimization (BCO).
6
+ The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0.
7
+ For a full example have a look at [`examples/scripts/bco.py`].
8
+
9
+ ## Expected dataset type
10
+
11
+ The [`experimental.bco.BCOTrainer`] requires an [unpaired preference dataset](dataset_formats#unpaired-preference).
12
+ The [`experimental.bco.BCOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.
13
+
14
+ ## Expected model format
15
+
16
+ The BCO trainer expects a model of `AutoModelForCausalLM`, compared to PPO that expects `AutoModelForCausalLMWithValueHead` for the value function.
17
+
18
+ ## Using the `BCOTrainer`
19
+
20
+ For a detailed example have a look at the `examples/scripts/bco.py` script. At a high level we need to initialize the `BCOTrainer` with a `model` we wish to train and a reference `ref_model` which we will use to calculate the implicit rewards of the preferred and rejected response.
21
+
22
+ The `beta` refers to the hyperparameter of the implicit reward, and the dataset contains the 3 entries listed above. Note that the `model` and `ref_model` need to have the same architecture (ie decoder only or encoder-decoder).
23
+
24
+ ```python
25
+ from trl.experimental.bco import BCOConfig, BCOTrainer
26
+
27
+ training_args = BCOConfig(
28
+ beta=0.1,
29
+ )
30
+
31
+ bco_trainer = BCOTrainer(
32
+ model,
33
+ model_ref,
34
+ args=training_args,
35
+ train_dataset=train_dataset,
36
+ processing_class=tokenizer,
37
+ )
38
+ ```
39
+
40
+ After this one can then call:
41
+
42
+ ```python
43
+ bco_trainer.train()
44
+ ```
45
+
46
+ ## Underlying Distribution matching (UDM)
47
+
48
+ In practical scenarios, the thumbs-up and thumbs-down datasets are likely to have divergent underlying distributions of prompts.
49
+ Consider an LLM deployed for user feedback: if the model excels in writing tasks but underperforms in coding, the thumbs-up dataset will be dominated by writing-related prompts, while the thumbs-down dataset will contain mostly coding-related prompts.
50
+ If the prompts in your desired and undesired datasets differ a lot, it is useful to enable UDM.
51
+
52
+ Choose an embedding model and tokenizer:
53
+
54
+ ```python
55
+ embedding_model = AutoModel.from_pretrained(your_model_id)
56
+ embedding_tokenizer = AutoTokenizer.from_pretrained(your_model_id)
57
+
58
+ # customize this function depending on your embedding model
59
+ def embed_prompt(input_ids, attention_mask, model):
60
+ outputs = model(input_ids=input_ids, attention_mask=attention_mask)
61
+ return outputs.last_hidden_state.mean(dim=1)
62
+
63
+ embedding_model = Accelerator().prepare_model(self.embedding_model)
64
+ embedding_func = partial(embed_prompt, model=embedding_model)
65
+ ```
66
+
67
+ Set `prompt_sample_size` to define how many prompts are selected to train the UDM classifier and start the training with the provided embedding function:
68
+
69
+ ```python
70
+ training_args = BCOConfig(
71
+ beta=0.1,
72
+ prompt_sample_size=512,
73
+ )
74
+
75
+ bco_trainer = BCOTrainer(
76
+ model,
77
+ model_ref,
78
+ args=training_args,
79
+ train_dataset=train_dataset,
80
+ processing_class=tokenizer,
81
+ embedding_func=embedding_func,
82
+ embedding_tokenizer=self.embedding_tokenizer,
83
+ )
84
+
85
+ bco_trainer.train()
86
+ ```
87
+
88
+ ### For Mixture of Experts Models: Enabling the auxiliary loss
89
+
90
+ MOEs are the most efficient if the load is about equally distributed between experts.
91
+ To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.
92
+
93
+ This option is enabled by setting `output_router_logits=True` in the model config (e.g. MixtralConfig).
94
+ To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: 0.001).
95
+
96
+ ## BCOTrainer
97
+
98
+ [[autodoc]] experimental.bco.BCOTrainer
99
+ - train
100
+ - save_model
101
+ - push_to_hub
102
+
103
+ ## BCOConfig
104
+
105
+ [[autodoc]] experimental.bco.BCOConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/bema_for_reference_model.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BEMA for Reference Model
2
+
3
+ This feature implements the BEMA algorithm to update the reference model during DPO training.
4
+
5
+ ## Usage
6
+
7
+ ```python
8
+ from trl.experimental.bema_for_ref_model import BEMACallback, DPOTrainer
9
+ from datasets import load_dataset
10
+
11
+ dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train")
12
+
13
+ bema_callback = BEMACallback(update_ref_model=True)
14
+
15
+ trainer = DPOTrainer(
16
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
17
+ train_dataset=dataset,
18
+ callbacks=[bema_callback],
19
+ )
20
+ trainer.train()
21
+ ```
22
+
23
+ ## DPOTrainer
24
+
25
+ [[autodoc]] experimental.bema_for_ref_model.DPOTrainer
26
+ - train
27
+ - save_model
28
+ - push_to_hub
29
+
30
+ ## BEMACallback
31
+
32
+ [[autodoc]] experimental.bema_for_ref_model.BEMACallback
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/callbacks.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Callbacks
2
+
3
+ ## RichProgressCallback
4
+
5
+ [[autodoc]] RichProgressCallback
6
+
7
+ ## LogCompletionsCallback
8
+
9
+ [[autodoc]] LogCompletionsCallback
10
+
11
+ ## BEMACallback
12
+
13
+ [[autodoc]] BEMACallback
14
+
15
+ ## WeaveCallback
16
+
17
+ [[autodoc]] WeaveCallback
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/chat_template_utils.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chat template utilities
2
+
3
+ ## clone_chat_template
4
+
5
+ [[autodoc]] clone_chat_template
6
+
7
+ ## is_chat_template_prefix_preserving
8
+
9
+ [[autodoc]] chat_template_utils.is_chat_template_prefix_preserving
10
+
11
+ ## get_training_chat_template
12
+
13
+ [[autodoc]] chat_template_utils.get_training_chat_template
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/clis.md ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Command Line Interfaces (CLIs)
2
+
3
+ TRL provides a powerful command-line interface (CLI) to fine-tune large language models (LLMs) using methods like Supervised Fine-Tuning (SFT), Direct Preference Optimization (DPO), and more. The CLI abstracts away much of the boilerplate, letting you launch training jobs quickly and reproducibly.
4
+
5
+ ## Commands
6
+
7
+ Currently supported commands are:
8
+
9
+ ### Training Commands
10
+
11
+ - `trl dpo`: fine-tune a LLM with DPO
12
+ - `trl grpo`: fine-tune a LLM with GRPO
13
+ - `trl kto`: fine-tune a LLM with KTO
14
+ - `trl reward`: train a Reward Model
15
+ - `trl rloo`: fine-tune a LLM with RLOO
16
+ - `trl sft`: fine-tune a LLM with SFT
17
+
18
+ ### Other Commands
19
+
20
+ - `trl env`: get the system information
21
+ - `trl vllm-serve`: serve a model with vLLM
22
+
23
+ ## Fine-Tuning with the TRL CLI
24
+
25
+ ### Basic Usage
26
+
27
+ You can launch training directly from the CLI by specifying required arguments like the model and dataset:
28
+
29
+ <hfoptions id="trainer">
30
+ <hfoption id="SFT">
31
+
32
+ ```bash
33
+ trl sft \
34
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
35
+ --dataset_name stanfordnlp/imdb
36
+ ```
37
+
38
+ </hfoption>
39
+ <hfoption id="DPO">
40
+
41
+ ```bash
42
+ trl dpo \
43
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
44
+ --dataset_name anthropic/hh-rlhf
45
+ ```
46
+
47
+ </hfoption>
48
+ <hfoption id="Reward">
49
+
50
+ ```bash
51
+ trl reward \
52
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
53
+ --dataset_name trl-lib/ultrafeedback_binarized
54
+ ```
55
+
56
+ </hfoption>
57
+ <hfoption id="GRPO">
58
+
59
+ ```bash
60
+ trl grpo \
61
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
62
+ --dataset_name HuggingFaceH4/Polaris-Dataset-53K \
63
+ --reward_funcs accuracy_reward
64
+ ```
65
+
66
+ </hfoption>
67
+ <hfoption id="RLOO">
68
+
69
+ ```bash
70
+ trl rloo \
71
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
72
+ --dataset_name HuggingFaceH4/Polaris-Dataset-53K \
73
+ --reward_funcs accuracy_reward
74
+ ```
75
+
76
+ </hfoption>
77
+ <hfoption id="KTO">
78
+
79
+ ```bash
80
+ trl kto \
81
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
82
+ --dataset_name trl-lib/kto-mix-14k
83
+ ```
84
+
85
+ </hfoption>
86
+ </hfoptions>
87
+
88
+ ### Using Configuration Files
89
+
90
+ To keep your CLI commands clean and reproducible, you can define all training arguments in a YAML configuration file:
91
+
92
+ <hfoptions id="trainer">
93
+ <hfoption id="SFT">
94
+
95
+ ```yaml
96
+ # sft_config.yaml
97
+ model_name_or_path: Qwen/Qwen2.5-0.5B
98
+ dataset_name: stanfordnlp/imdb
99
+ ```
100
+
101
+ Launch with:
102
+
103
+ ```bash
104
+ trl sft --config sft_config.yaml
105
+ ```
106
+
107
+ </hfoption>
108
+ <hfoption id="DPO">
109
+
110
+ ```yaml
111
+ # dpo_config.yaml
112
+ model_name_or_path: Qwen/Qwen2.5-0.5B
113
+ dataset_name: anthropic/hh-rlhf
114
+ ```
115
+
116
+ Launch with:
117
+
118
+ ```bash
119
+ trl dpo --config dpo_config.yaml
120
+ ```
121
+
122
+ </hfoption>
123
+ <hfoption id="Reward">
124
+
125
+ ```yaml
126
+ # reward_config.yaml
127
+ model_name_or_path: Qwen/Qwen2.5-0.5B
128
+ dataset_name: trl-lib/ultrafeedback_binarized
129
+ ```
130
+
131
+ Launch with:
132
+
133
+ ```bash
134
+ trl reward --config reward_config.yaml
135
+ ```
136
+
137
+ </hfoption>
138
+ <hfoption id="GRPO">
139
+
140
+ ```yaml
141
+ # grpo_config.yaml
142
+ model_name_or_path: Qwen/Qwen2.5-0.5B
143
+ dataset_name: HuggingFaceH4/Polaris-Dataset-53K
144
+ reward_funcs:
145
+ - accuracy_reward
146
+ ```
147
+
148
+ Launch with:
149
+
150
+ ```bash
151
+ trl grpo --config grpo_config.yaml
152
+ ```
153
+
154
+ </hfoption>
155
+ <hfoption id="RLOO">
156
+
157
+ ```yaml
158
+ # rloo_config.yaml
159
+ model_name_or_path: Qwen/Qwen2.5-0.5B
160
+ dataset_name: HuggingFaceH4/Polaris-Dataset-53K
161
+ reward_funcs:
162
+ - accuracy_reward
163
+ ```
164
+
165
+ Launch with:
166
+
167
+ ```bash
168
+ trl rloo --config rloo_config.yaml
169
+ ```
170
+
171
+ </hfoption>
172
+ <hfoption id="KTO">
173
+
174
+ ```yaml
175
+ # kto_config.yaml
176
+ model_name_or_path: Qwen/Qwen2.5-0.5B
177
+ dataset_name: trl-lib/kto-mix-14k
178
+ ```
179
+
180
+ Launch with:
181
+
182
+ ```bash
183
+ trl kto --config kto_config.yaml
184
+ ```
185
+
186
+ </hfoption>
187
+ </hfoptions>
188
+
189
+ ### Scaling Up with Accelerate
190
+
191
+ TRL CLI natively supports [🤗 Accelerate](https://huggingface.co/docs/accelerate), making it easy to scale training across multiple GPUs, machines, or use advanced setups like DeepSpeed — all from the same CLI.
192
+
193
+ You can pass any `accelerate launch` arguments directly to `trl`, such as `--num_processes`. For more information see [Using accelerate launch](https://huggingface.co/docs/accelerate/en/basic_tutorials/launch#using-accelerate-launch).
194
+
195
+ <hfoptions id="trainer">
196
+ <hfoption id="SFT">
197
+
198
+ ```bash
199
+ trl sft \
200
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
201
+ --dataset_name stanfordnlp/imdb \
202
+ --num_processes 4
203
+ ```
204
+
205
+ or, with a config file:
206
+
207
+ ```yaml
208
+ # sft_config.yaml
209
+ model_name_or_path: Qwen/Qwen2.5-0.5B
210
+ dataset_name: stanfordnlp/imdb
211
+ num_processes: 4
212
+ ```
213
+
214
+ Launch with:
215
+
216
+ ```bash
217
+ trl sft --config sft_config.yaml
218
+ ```
219
+
220
+ </hfoption>
221
+ <hfoption id="DPO">
222
+
223
+ ```bash
224
+ trl dpo \
225
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
226
+ --dataset_name anthropic/hh-rlhf \
227
+ --num_processes 4
228
+ ```
229
+
230
+ or, with a config file:
231
+
232
+ ```yaml
233
+ # dpo_config.yaml
234
+ model_name_or_path: Qwen/Qwen2.5-0.5B
235
+ dataset_name: anthropic/hh-rlhf
236
+ num_processes: 4
237
+ ```
238
+
239
+ Launch with:
240
+
241
+ ```bash
242
+ trl dpo --config dpo_config.yaml
243
+ ```
244
+
245
+ </hfoption>
246
+ <hfoption id="Reward">
247
+
248
+ ```bash
249
+ trl reward \
250
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
251
+ --dataset_name trl-lib/ultrafeedback_binarized \
252
+ --num_processes 4
253
+ ```
254
+
255
+ or, with a config file:
256
+
257
+ ```yaml
258
+ # reward_config.yaml
259
+ model_name_or_path: Qwen/Qwen2.5-0.5B
260
+ dataset_name: trl-lib/ultrafeedback_binarized
261
+ num_processes: 4
262
+ ```
263
+
264
+ Launch with:
265
+
266
+ ```bash
267
+ trl reward --config reward_config.yaml
268
+ ```
269
+
270
+ </hfoption>
271
+ <hfoption id="GRPO">
272
+
273
+ ```bash
274
+ trl grpo \
275
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
276
+ --dataset_name HuggingFaceH4/Polaris-Dataset-53K \
277
+ --reward_funcs accuracy_reward \
278
+ --num_processes 4
279
+ ```
280
+
281
+ or, with a config file:
282
+
283
+ ```yaml
284
+ # grpo_config.yaml
285
+ model_name_or_path: Qwen/Qwen2.5-0.5B
286
+ dataset_name: HuggingFaceH4/Polaris-Dataset-53K
287
+ reward_funcs:
288
+ - accuracy_reward
289
+ num_processes: 4
290
+ ```
291
+
292
+ Launch with:
293
+
294
+ ```bash
295
+ trl grpo --config grpo_config.yaml
296
+ ```
297
+
298
+ </hfoption>
299
+ <hfoption id="RLOO">
300
+
301
+ ```bash
302
+ trl rloo \
303
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
304
+ --dataset_name HuggingFaceH4/Polaris-Dataset-53K \
305
+ --reward_funcs accuracy_reward \
306
+ --num_processes 4
307
+ ```
308
+
309
+ or, with a config file:
310
+
311
+ ```yaml
312
+ # rloo_config.yaml
313
+ model_name_or_path: Qwen/Qwen2.5-0.5B
314
+ dataset_name: HuggingFaceH4/Polaris-Dataset-53K
315
+ reward_funcs:
316
+ - accuracy_reward
317
+ num_processes: 4
318
+ ```
319
+
320
+ Launch with:
321
+
322
+ ```bash
323
+ trl rloo --config rloo_config.yaml
324
+ ```
325
+
326
+ </hfoption>
327
+ <hfoption id="KTO">
328
+
329
+ ```bash
330
+ trl kto \
331
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
332
+ --dataset_name trl-lib/kto-mix-14k \
333
+ --num_processes 4
334
+ ```
335
+
336
+ or, with a config file:
337
+
338
+ ```yaml
339
+ # kto_config.yaml
340
+ model_name_or_path: Qwen/Qwen2.5-0.5B
341
+ dataset_name: trl-lib/kto-mix-14k
342
+ num_processes: 4
343
+ ```
344
+
345
+ Launch with:
346
+
347
+ ```bash
348
+ trl kto --config kto_config.yaml
349
+ ```
350
+
351
+ </hfoption>
352
+ </hfoptions>
353
+
354
+ ### Using `--accelerate_config` for Accelerate Configuration
355
+
356
+ The `--accelerate_config` flag lets you easily configure distributed training with [🤗 Accelerate](https://github.com/huggingface/accelerate). This flag accepts either:
357
+
358
+ - the name of a predefined config profile (built into TRL), or
359
+ - a path to a custom Accelerate YAML config file.
360
+
361
+ #### Predefined Config Profiles
362
+
363
+ TRL provides several ready-to-use Accelerate configs to simplify common training setups:
364
+
365
+ | Name | Description |
366
+ | --- | --- |
367
+ | `fsdp1` | Fully Sharded Data Parallel Stage 1 |
368
+ | `fsdp2` | Fully Sharded Data Parallel Stage 2 |
369
+ | `zero1` | DeepSpeed ZeRO Stage 1 |
370
+ | `zero2` | DeepSpeed ZeRO Stage 2 |
371
+ | `zero3` | DeepSpeed ZeRO Stage 3 |
372
+ | `multi_gpu` | Multi-GPU training |
373
+ | `single_gpu` | Single-GPU training |
374
+
375
+ To use one of these, just pass the name to `--accelerate_config`. TRL will automatically load the corresponding config file from `trl/accelerate_config/`.
376
+
377
+ #### Example Usage
378
+
379
+ <hfoptions id="trainer">
380
+ <hfoption id="SFT">
381
+
382
+ ```bash
383
+ trl sft \
384
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
385
+ --dataset_name stanfordnlp/imdb \
386
+ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml
387
+ ```
388
+
389
+ or, with a config file:
390
+
391
+ ```yaml
392
+ # sft_config.yaml
393
+ model_name_or_path: Qwen/Qwen2.5-0.5B
394
+ dataset_name: stanfordnlp/imdb
395
+ accelerate_config: zero2 # or path/to/my/accelerate/config.yaml
396
+ ```
397
+
398
+ Launch with:
399
+
400
+ ```bash
401
+ trl sft --config sft_config.yaml
402
+ ```
403
+
404
+ </hfoption>
405
+ <hfoption id="DPO">
406
+
407
+ ```bash
408
+ trl dpo \
409
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
410
+ --dataset_name anthropic/hh-rlhf \
411
+ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml
412
+ ```
413
+
414
+ or, with a config file:
415
+
416
+ ```yaml
417
+ # dpo_config.yaml
418
+ model_name_or_path: Qwen/Qwen2.5-0.5B
419
+ dataset_name: anthropic/hh-rlhf
420
+ accelerate_config: zero2 # or path/to/my/accelerate/config.yaml
421
+ ```
422
+
423
+ Launch with:
424
+
425
+ ```bash
426
+ trl dpo --config dpo_config.yaml
427
+ ```
428
+
429
+ </hfoption>
430
+ <hfoption id="Reward">
431
+
432
+ ```bash
433
+ trl reward \
434
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
435
+ --dataset_name trl-lib/ultrafeedback_binarized \
436
+ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml
437
+ ```
438
+
439
+ or, with a config file:
440
+
441
+ ```yaml
442
+ # reward_config.yaml
443
+ model_name_or_path: Qwen/Qwen2.5-0.5B
444
+ dataset_name: trl-lib/ultrafeedback_binarized
445
+ accelerate_config: zero2 # or path/to/my/accelerate/config.yaml
446
+ ```
447
+
448
+ Launch with:
449
+
450
+ ```bash
451
+ trl reward --config reward_config.yaml
452
+ ```
453
+
454
+ </hfoption>
455
+ <hfoption id="GRPO">
456
+
457
+ ```bash
458
+ trl grpo \
459
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
460
+ --dataset_name HuggingFaceH4/Polaris-Dataset-53K \
461
+ --reward_funcs accuracy_reward \
462
+ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml
463
+ ```
464
+
465
+ or, with a config file:
466
+
467
+ ```yaml
468
+ # grpo_config.yaml
469
+ model_name_or_path: Qwen/Qwen2.5-0.5B
470
+ dataset_name: HuggingFaceH4/Polaris-Dataset-53K
471
+ reward_funcs:
472
+ - accuracy_reward
473
+ accelerate_config: zero2 # or path/to/my/accelerate/config.yaml
474
+ ```
475
+
476
+ Launch with:
477
+
478
+ ```bash
479
+ trl grpo --config grpo_config.yaml
480
+ ```
481
+
482
+ </hfoption>
483
+ <hfoption id="RLOO">
484
+
485
+ ```bash
486
+ trl rloo \
487
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
488
+ --dataset_name HuggingFaceH4/Polaris-Dataset-53K \
489
+ --reward_funcs accuracy_reward \
490
+ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml
491
+ ```
492
+
493
+ or, with a config file:
494
+
495
+ ```yaml
496
+ # rloo_config.yaml
497
+ model_name_or_path: Qwen/Qwen2.5-0.5B
498
+ dataset_name: HuggingFaceH4/Polaris-Dataset-53K
499
+ reward_funcs:
500
+ - accuracy_reward
501
+ accelerate_config: zero2 # or path/to/my/accelerate/config.yaml
502
+ ```
503
+
504
+ Launch with:
505
+
506
+ ```bash
507
+ trl rloo --config rloo_config.yaml
508
+ ```
509
+
510
+ </hfoption>
511
+ <hfoption id="KTO">
512
+
513
+ ```bash
514
+ trl kto \
515
+ --model_name_or_path Qwen/Qwen2.5-0.5B \
516
+ --dataset_name trl-lib/kto-mix-14k \
517
+ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml
518
+ ```
519
+
520
+ or, with a config file:
521
+
522
+ ```yaml
523
+ # kto_config.yaml
524
+ model_name_or_path: Qwen/Qwen2.5-0.5B
525
+ dataset_name: trl-lib/kto-mix-14k
526
+ accelerate_config: zero2 # or path/to/my/accelerate/config.yaml
527
+ ```
528
+
529
+ Launch with:
530
+
531
+ ```bash
532
+ trl kto --config kto_config.yaml
533
+ ```
534
+
535
+ </hfoption>
536
+ </hfoptions>
537
+
538
+ ### Using dataset mixtures
539
+
540
+ You can use dataset mixtures to combine multiple datasets into a single training dataset. This is useful for training on diverse data sources or when you want to mix different types of data.
541
+
542
+ <hfoptions id="trainer">
543
+ <hfoption id="SFT">
544
+
545
+ ```yaml
546
+ # sft_config.yaml
547
+ model_name_or_path: Qwen/Qwen2.5-0.5B
548
+ datasets:
549
+ - path: stanfordnlp/imdb
550
+ - path: roneneldan/TinyStories
551
+ ```
552
+
553
+ Launch with:
554
+
555
+ ```bash
556
+ trl sft --config sft_config.yaml
557
+ ```
558
+
559
+ </hfoption>
560
+ <hfoption id="DPO">
561
+
562
+ ```yaml
563
+ # dpo_config.yaml
564
+ model_name_or_path: Qwen/Qwen2.5-0.5B
565
+ datasets:
566
+ - path: BAAI/Infinity-Preference
567
+ - path: argilla/Capybara-Preferences
568
+ ```
569
+
570
+ Launch with:
571
+
572
+ ```bash
573
+ trl dpo --config dpo_config.yaml
574
+ ```
575
+
576
+ </hfoption>
577
+ <hfoption id="Reward">
578
+
579
+ ```yaml
580
+ # reward_config.yaml
581
+ model_name_or_path: Qwen/Qwen2.5-0.5B
582
+ datasets:
583
+ - path: trl-lib/tldr-preference
584
+ - path: trl-lib/lm-human-preferences-sentiment
585
+ ```
586
+
587
+ Launch with:
588
+
589
+ ```bash
590
+ trl reward --config reward_config.yaml
591
+ ```
592
+
593
+ </hfoption>
594
+ <hfoption id="GRPO">
595
+
596
+ ```yaml
597
+ # grpo_config.yaml
598
+ model_name_or_path: Qwen/Qwen2.5-0.5B
599
+ datasets:
600
+ - path: HuggingFaceH4/Polaris-Dataset-53K
601
+ - path: trl-lib/DeepMath-103K
602
+ reward_funcs:
603
+ - accuracy_reward
604
+ ```
605
+
606
+ Launch with:
607
+
608
+ ```bash
609
+ trl grpo --config grpo_config.yaml
610
+ ```
611
+
612
+ </hfoption>
613
+ <hfoption id="RLOO">
614
+
615
+ ```yaml
616
+ # rloo_config.yaml
617
+ model_name_or_path: Qwen/Qwen2.5-0.5B
618
+ datasets:
619
+ - path: HuggingFaceH4/Polaris-Dataset-53K
620
+ - path: trl-lib/DeepMath-103K
621
+ reward_funcs:
622
+ - accuracy_reward
623
+ ```
624
+
625
+ Launch with:
626
+
627
+ ```bash
628
+ trl rloo --config rloo_config.yaml
629
+ ```
630
+
631
+ </hfoption>
632
+ <hfoption id="KTO">
633
+
634
+ ```yaml
635
+ # kto_config.yaml
636
+ model_name_or_path: Qwen/Qwen2.5-0.5B
637
+ datasets:
638
+ - path: trl-lib/kto-mix-14k
639
+ - path: argilla/ultrafeedback-binarized-preferences-cleaned
640
+ ```
641
+
642
+ Launch with:
643
+
644
+ ```bash
645
+ trl kto --config kto_config.yaml
646
+ ```
647
+
648
+ </hfoption>
649
+ </hfoptions>
650
+
651
+ To see all the available keywords for defining dataset mixtures, refer to the [`scripts.utils.DatasetConfig`] and [`DatasetMixtureConfig`] classes.
652
+
653
+ ## Getting the System Information
654
+
655
+ You can get the system information by running the following command:
656
+
657
+ ```bash
658
+ trl env
659
+ ```
660
+
661
+ This will print out the system information, including the GPU information, the CUDA version, the PyTorch version, the transformers version, the TRL version, and any optional dependencies that are installed.
662
+
663
+ ```txt
664
+ Copy-paste the following information when reporting an issue:
665
+
666
+ - Platform: Linux-5.15.0-1048-aws-x86_64-with-glibc2.31
667
+ - Python version: 3.11.9
668
+ - PyTorch version: 2.4.1
669
+ - accelerator(s): NVIDIA H100 80GB HBM3
670
+ - Transformers version: 4.45.0.dev0
671
+ - Accelerate version: 0.34.2
672
+ - Accelerate config:
673
+ - compute_environment: LOCAL_MACHINE
674
+ - distributed_type: DEEPSPEED
675
+ - mixed_precision: no
676
+ - use_cpu: False
677
+ - debug: False
678
+ - num_processes: 4
679
+ - machine_rank: 0
680
+ - num_machines: 1
681
+ - rdzv_backend: static
682
+ - same_network: True
683
+ - main_training_function: main
684
+ - enable_cpu_affinity: False
685
+ - deepspeed_config: {'gradient_accumulation_steps': 4, 'offload_optimizer_device': 'none', 'offload_param_device': 'none', 'zero3_init_flag': False, 'zero_stage': 2}
686
+ - downcast_bf16: no
687
+ - tpu_use_cluster: False
688
+ - tpu_use_sudo: False
689
+ - tpu_env: []
690
+ - Datasets version: 3.0.0
691
+ - HF Hub version: 0.24.7
692
+ - TRL version: 0.12.0.dev0+acb4d70
693
+ - bitsandbytes version: 0.41.1
694
+ - DeepSpeed version: 0.15.1
695
+ - Diffusers version: 0.30.3
696
+ - Liger-Kernel version: 0.3.0
697
+ - LLM-Blender version: 0.0.2
698
+ - OpenAI version: 1.46.0
699
+ - PEFT version: 0.12.0
700
+ - vLLM version: not installed
701
+ ```
702
+
703
+ This information is required when reporting an issue.
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/community_tutorials.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Community Tutorials
2
+
3
+ Community tutorials are made by active members of the Hugging Face community who want to share their knowledge and expertise with others. They are a great way to learn about the library and its features, and to get started with core classes and modalities.
4
+
5
+ ## Language Models
6
+
7
+ ### Tutorials
8
+
9
+ | Task | Class | Description | Author | Tutorial | Colab |
10
+ | --- | --- | --- | --- | --- | --- |
11
+ | Reinforcement Learning | [`GRPOTrainer`] | Efficient Online Training with GRPO and vLLM in TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/grpo_vllm_online_training) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/grpo_vllm_online_training.ipynb) |
12
+ | Reinforcement Learning | [`GRPOTrainer`] | Post training an LLM for reasoning with GRPO in TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_llm_grpo_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_llm_grpo_trl.ipynb) |
13
+ | Reinforcement Learning | [`GRPOTrainer`] | Mini-R1: Reproduce Deepseek R1 „aha moment“ a RL tutorial | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/mini-deepseek-r1) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/mini-deepseek-r1-aha-grpo.ipynb) |
14
+ | Reinforcement Learning | [`GRPOTrainer`] | RL on LLaMA 3.1-8B with GRPO and Unsloth optimizations | [Andrea Manzoni](https://huggingface.co/AManzoni) | [Link](https://colab.research.google.com/github/amanzoni1/fine_tuning/blob/main/RL_LLama3_1_8B_GRPO.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/amanzoni1/fine_tuning/blob/main/RL_LLama3_1_8B_GRPO.ipynb) |
15
+ | Instruction tuning | [`SFTTrainer`] | Fine-tuning Google Gemma LLMs using ChatML format with QLoRA | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/fine-tune-google-gemma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/gemma-lora-example.ipynb) |
16
+ | Structured Generation | [`SFTTrainer`] | Fine-tuning Llama-2-7B to generate Persian product catalogs in JSON using QLoRA and PEFT | [Mohammadreza Esmaeilian](https://huggingface.co/Mohammadreza) | [Link](https://huggingface.co/learn/cookbook/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_llm_to_generate_persian_product_catalogs_in_json_format.ipynb) |
17
+ | Preference Optimization | [`DPOTrainer`] | Align Mistral-7b using Direct Preference Optimization for human preference alignment | [Maxime Labonne](https://huggingface.co/mlabonne) | [Link](https://mlabonne.github.io/blog/posts/Fine_tune_Mistral_7b_with_DPO.html) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mlabonne/llm-course/blob/main/Fine_tune_a_Mistral_7b_model_with_DPO.ipynb) |
18
+ | Preference Optimization | [`experimental.orpo.ORPOTrainer`] | Fine-tuning Llama 3 with ORPO combining instruction tuning and preference alignment | [Maxime Labonne](https://huggingface.co/mlabonne) | [Link](https://mlabonne.github.io/blog/posts/2024-04-19_Fine_tune_Llama_3_with_ORPO.html) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1eHNWg9gnaXErdAa8_mcvjMupbSS6rDvi) |
19
+ | Instruction tuning | [`SFTTrainer`] | How to fine-tune open LLMs in 2025 with Hugging Face | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/fine-tune-llms-in-2025) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/fine-tune-llms-in-2025.ipynb) |
20
+ | Step-Level Reasoning | [`GRPOTrainer`] | Supervised Reinforcement Learning (SRL) for step-by-step reasoning with vLLM | [Deepak Swaminathan](https://huggingface.co/s23deepak) | [Link](https://github.com/s23deepak/Supervised-Reinforcement-Learning) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/s23deepak/Supervised-Reinforcement-Learning/blob/main/notebooks/srl_grpo_tutorial.ipynb) |
21
+
22
+ ### Videos
23
+
24
+ | Task | Title | Author | Video |
25
+ | --- | --- | --- | --- |
26
+ | Instruction tuning | Fine-tuning open AI models using Hugging Face TRL | [Wietse Venema](https://huggingface.co/wietsevenema) | [<img src="https://img.youtube.com/vi/cnGyyM0vOes/0.jpg">](https://youtu.be/cnGyyM0vOes) |
27
+ | Instruction tuning | How to fine-tune a smol-LM with Hugging Face, TRL, and the smoltalk Dataset | [Mayurji](https://huggingface.co/iammayur) | [<img src="https://img.youtube.com/vi/jKdXv3BiLu0/0.jpg">](https://youtu.be/jKdXv3BiLu0) |
28
+
29
+
30
+ <details>
31
+ <summary>⚠️ Deprecated features notice for "How to fine-tune a smol-LM with Hugging Face, TRL, and the smoltalk Dataset" (click to expand)</summary>
32
+
33
+ > [!WARNING]
34
+ > The tutorial uses two deprecated features:
35
+ >
36
+ > - `SFTTrainer(..., tokenizer=tokenizer)`: Use `SFTTrainer(..., processing_class=tokenizer)` instead, or simply omit it (it will be inferred from the model).
37
+ > - `setup_chat_format(model, tokenizer)`: Use `SFTConfig(..., chat_template_path="Qwen/Qwen3-0.6B")`, where `chat_template_path` specifies the model whose chat template you want to copy.
38
+
39
+ </details>
40
+
41
+ ## Vision Language Models
42
+
43
+ ### Tutorials
44
+
45
+ | Task | Class | Description | Author | Tutorial | Colab |
46
+ | --- | --- | --- | --- | --- | --- |
47
+ | Visual QA | [`SFTTrainer`] | Fine-tuning Qwen2-VL-7B for visual question answering on ChartQA dataset | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_trl.ipynb) |
48
+ | Visual QA | [`SFTTrainer`] | Fine-tuning SmolVLM with TRL on a consumer GPU | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_smol_vlm_sft_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_smol_vlm_sft_trl.ipynb) |
49
+ | SEO Description | [`SFTTrainer`] | Fine-tuning Qwen2-VL-7B for generating SEO-friendly descriptions from images | [Philipp Schmid](https://huggingface.co/philschmid) | [Link](https://www.philschmid.de/fine-tune-multimodal-llms-with-trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/philschmid/deep-learning-pytorch-huggingface/blob/main/training/fine-tune-multimodal-llms-with-trl.ipynb) |
50
+ | Visual QA | [`DPOTrainer`] | PaliGemma 🤝 Direct Preference Optimization | [Merve Noyan](https://huggingface.co/merve) | [Link](https://github.com/merveenoyan/smol-vision/blob/main/PaliGemma_DPO.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/merveenoyan/smol-vision/blob/main/PaliGemma_DPO.ipynb) |
51
+ | Visual QA | [`DPOTrainer`] | Fine-tuning SmolVLM using direct preference optimization (DPO) with TRL on a consumer GPU | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_dpo_smolvlm_instruct) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_dpo_smolvlm_instruct.ipynb) |
52
+ | Object Detection Grounding | [`SFTTrainer`] | Fine tuning a VLM for Object Detection Grounding using TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_object_detection_grounding) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_object_detection_grounding.ipynb) |
53
+ | Visual QA | [`DPOTrainer`] | Fine-Tuning a Vision Language Model with TRL using MPO | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_mpo) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_mpo.ipynb) |
54
+ | Reinforcement Learning | [`GRPOTrainer`] | Post training a VLM for reasoning with GRPO using TRL | [Sergio Paniego](https://huggingface.co/sergiopaniego) | [Link](https://huggingface.co/learn/cookbook/fine_tuning_vlm_grpo_trl) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/en/fine_tuning_vlm_grpo_trl.ipynb) |
55
+
56
+ ## Speech Language Models
57
+
58
+ ### Tutorials
59
+
60
+ | Task | Class | Description | Author | Tutorial |
61
+ | --- | --- | --- | --- | --- |
62
+ | Text-to-Speech | [`GRPOTrainer`] | Post training a Speech Language Model with GRPO using TRL | [Steven Zheng](https://huggingface.co/Steveeeeeeen) | [Link](https://huggingface.co/blog/Steveeeeeeen/llasa-grpo) |
63
+
64
+ ## Contributing
65
+
66
+ If you have a tutorial that you would like to add to this list, please open a PR to add it. We will review it and merge it if it is relevant to the community.
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/cpo_trainer.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CPO Trainer
2
+
3
+ [![model badge](https://img.shields.io/badge/All_models-CPO-blue)](https://huggingface.co/models?other=cpo,trl)
4
+
5
+ ## Overview
6
+
7
+ Contrastive Preference Optimization (CPO) as introduced in the paper [Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation](https://huggingface.co/papers/2401.08417) by [Haoran Xu](https://huggingface.co/haoranxu), [Amr Sharaf](https://huggingface.co/amrsharaf), [Yunmo Chen](https://huggingface.co/yunmochen), Weiting Tan, Lingfeng Shen, Benjamin Van Durme, [Kenton Murray](https://huggingface.co/Kenton), and [Young Jin Kim](https://huggingface.co/ykim362). At a high level, CPO trains models to avoid generating adequate, but not perfect, translations in Machine Translation (MT) tasks. However, CPO is a general approximation of the DPO loss and can be applied to other domains, such as chat.
8
+
9
+ CPO aims to mitigate two fundamental shortcomings of SFT. First, SFT’s methodology of minimizing the discrepancy between predicted outputs and gold-standard references inherently caps model performance at the quality level of the training data. Secondly, SFT lacks a mechanism to prevent the model from rejecting mistakes in translations. The CPO objective is derived from the DPO objective.
10
+
11
+ ## Quick start
12
+
13
+ This example demonstrates how to train a model using the CPO method. We use the [Qwen 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) as the base model. We use the preference data from the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback). You can view the data in the dataset here:
14
+
15
+ <iframe
16
+ src="https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized/embed/viewer/default/train?row=0"
17
+ frameborder="0"
18
+ width="100%"
19
+ height="560px"
20
+ ></iframe>
21
+
22
+ Below is the script to train the model:
23
+
24
+ ```python
25
+ # train_cpo.py
26
+ from datasets import load_dataset
27
+ from trl.experimental.cpo import CPOConfig, CPOTrainer
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer
29
+
30
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
31
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
32
+ train_dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
33
+
34
+ training_args = CPOConfig(output_dir="Qwen2-0.5B-CPO")
35
+ trainer = CPOTrainer(model=model, args=training_args, processing_class=tokenizer, train_dataset=train_dataset)
36
+ trainer.train()
37
+ ```
38
+
39
+ Execute the script using the following command:
40
+
41
+ ```bash
42
+ accelerate launch train_cpo.py
43
+ ```
44
+
45
+ ## Expected dataset type
46
+
47
+ CPO requires a [preference dataset](dataset_formats#preference). The [`experimental.cpo.CPOTrainer`] supports both [conversational](dataset_formats#conversational) and [standard](dataset_formats#standard) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.
48
+
49
+ ## Example script
50
+
51
+ We provide an example script to train a model using the CPO method. The script is available in [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py)
52
+
53
+ To test the CPO script with the [Qwen2 0.5B model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) on the [UltraFeedback dataset](https://huggingface.co/datasets/trl-lib/ultrafeedback_binarized), run the following command:
54
+
55
+ ```bash
56
+ accelerate launch examples/scripts/cpo.py \
57
+ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \
58
+ --dataset_name trl-lib/ultrafeedback_binarized \
59
+ --num_train_epochs 1 \
60
+ --output_dir Qwen2-0.5B-CPO
61
+ ```
62
+
63
+ ## Logged metrics
64
+
65
+ While training and evaluating, we record the following reward metrics:
66
+
67
+ * `rewards/chosen`: the mean log probabilities of the policy model for the chosen responses scaled by beta
68
+ * `rewards/rejected`: the mean log probabilities of the policy model for the rejected responses scaled by beta
69
+ * `rewards/accuracies`: mean of how often the chosen rewards are > than the corresponding rejected rewards
70
+ * `rewards/margins`: the mean difference between the chosen and corresponding rejected rewards
71
+ * `nll_loss`: the mean negative log likelihood loss of the policy model for the chosen responses
72
+
73
+ ## CPO variants
74
+
75
+ ### Simple Preference Optimization (SimPO)
76
+
77
+ [Simple Preference Optimization](https://huggingface.co/papers/2405.14734) (SimPO) by [Yu Meng](https://huggingface.co/yumeng5), [Mengzhou Xia](https://huggingface.co/mengzhouxia), and [Danqi Chen](https://huggingface.co/cdq10131) proposes a simpler and more effective preference optimization algorithm than DPO without using a reference model. The key designs in SimPO are (1) using length-normalized log likelihood as the implicit reward, and (2) incorporating a target reward margin in the Bradley-Terry ranking objective. The official code can be found at [princeton-nlp/SimPO](https://github.com/princeton-nlp/SimPO).
78
+
79
+ The abstract from the paper is the following:
80
+
81
+ > Direct Preference Optimization (DPO) is a widely used offline preference optimization algorithm that reparameterizes reward functions in reinforcement learning from human feedback (RLHF) to enhance simplicity and training stability. In this work, we propose SimPO, a simpler yet more effective approach. The effectiveness of SimPO is attributed to a key design: using the average log probability of a sequence as the implicit reward. This reward formulation better aligns with model generation and eliminates the need for a reference model, making it more compute and memory efficient. Additionally, we introduce a target reward margin to the Bradley-Terry objective to encourage a larger margin between the winning and losing responses, further enhancing the algorithm's performance. We compare SimPO to DPO and its latest variants across various state-of-the-art training setups, including both base and instruction-tuned models like Mistral and Llama3. We evaluated on extensive instruction-following benchmarks, including AlpacaEval 2, MT-Bench, and the recent challenging Arena-Hard benchmark. Our results demonstrate that SimPO consistently and significantly outperforms existing approaches without substantially increasing response length. Specifically, SimPO outperforms DPO by up to 6.4 points on AlpacaEval 2 and by up to 7.5 points on Arena-Hard. Our top-performing model, built on Llama3-8B-Instruct, achieves a remarkable 44.7 length-controlled win rate on AlpacaEval 2 -- surpassing Claude 3 Opus on the leaderboard, and a 33.8 win rate on Arena-Hard -- making it the strongest 8B open-source model.
82
+
83
+ The SimPO loss is integrated in the [`experimental.cpo.CPOTrainer`], as it's an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, just turn on `loss_type="simpo"` and `cpo_alpha=0.0` in the [`experimental.cpo.CPOConfig`] and set the `simpo_gamma` to a recommended value.
84
+
85
+ ### CPO-SimPO
86
+
87
+ We also offer the combined use of CPO and SimPO, which enables more stable training and improved performance. Learn more details at [CPO-SimPO GitHub](https://github.com/fe1ixxu/CPO_SIMPO). To use this method, simply enable SimPO by setting `loss_type="simpo"` and a non-zero `cpo_alpha` in the [`experimental.cpo.CPOConfig`].
88
+
89
+ ### AlphaPO
90
+
91
+ The [AlphaPO -- Reward shape matters for LLM alignment](https://huggingface.co/papers/2501.03884) (AlphaPO) method by Aman Gupta, Shao Tang, Qingquan Song, Sirou Zhu, [Jiwoo Hong](https://huggingface.co/JW17), Ankan Saha, Viral Gupta, Noah Lee, Eunki Kim, Jason Zhu, Natesh Pillai, and S. Sathiya Keerthi is also implemented in the [`experimental.cpo.CPOTrainer`]. AlphaPO is an alternative method that applies a transformation to the reward function shape in the context of SimPO loss. The abstract from the paper is the following:
92
+
93
+ > Reinforcement Learning with Human Feedback (RLHF) and its variants have made huge strides toward the effective alignment of large language models (LLMs) to follow instructions and reflect human values. More recently, Direct Alignment Algorithms (DAAs) have emerged in which the reward modeling stage of RLHF is skipped by characterizing the reward directly as a function of the policy being learned. Some popular examples of DAAs include Direct Preference Optimization (DPO) and Simple Preference Optimization (SimPO). These methods often suffer from likelihood displacement, a phenomenon by which the probabilities of preferred responses are often reduced undesirably. In this paper, we argue that, for DAAs the reward (function) shape matters. We introduce AlphaPO, a new DAA method that leverages an α-parameter to help change the shape of the reward function beyond the standard log reward. AlphaPO helps maintain fine-grained control over likelihood displacement and overoptimization. Compared to SimPO, one of the best performing DAAs, AlphaPO leads to about 7% to 10% relative improvement in alignment performance for the instruct versions of Mistral-7B and Llama3-8B while achieving 15% to 50% relative improvement over DPO on the same models. The analysis and results presented highlight the importance of the reward shape and how one can systematically change it to affect training dynamics, as well as improve alignment performance.
94
+
95
+ To use this loss as described in the paper, we can set the `loss_type="alphapo"` which automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`, together with `alpha` and `simpo_gamma` to recommended values in the [`experimental.cpo.CPOConfig`]. Alternatively, you can manually set `loss_type="simpo"`, `cpo_alpha=0.0`, together with `alpha` and `simpo_gamma` to recommended values. Other variants of this method are also possible, such as setting `loss_type="ipo"` and `alpha` to any non-zero value.
96
+
97
+ ## Loss functions
98
+
99
+ The CPO algorithm supports several loss functions. The loss function can be set using the `loss_type` parameter in the [`experimental.cpo.CPOConfig`]. The following loss functions are supported:
100
+
101
+ | `loss_type=` | Description |
102
+ | --- | --- |
103
+ | `"sigmoid"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model, and in fact, the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. |
104
+ | `"hinge"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. |
105
+ | `"ipo"` | The [IPO](https://huggingface.co/papers/2310.12036) authors provide a deeper theoretical understanding of the DPO algorithms and identify an issue with overfitting and propose an alternative loss. In this case, the `beta` is the reciprocal of the gap between the log-likelihood ratios of the chosen vs the rejected completion pair, and thus the smaller the `beta`, the larger this gap is. As per the paper, the loss is averaged over log-likelihoods of the completion (unlike DPO, which is summed only). |
106
+ | `"simpo"` | The [SimPO](https://huggingface.co/papers/2405.14734) method is also implemented in the [`experimental.cpo.CPOTrainer`]. SimPO is an alternative loss that adds a reward margin, allows for length normalization, and does not use BC regularization. To use this loss, simply set `loss_type="simpo"` and `cpo_alpha=0.0` in the [`experimental.cpo.CPOConfig`] and `simpo_gamma` to a recommended value. |
107
+ | `"alphapo"` | The [AlphaPO](https://huggingface.co/papers/2501.03884) method is also implemented in the [`experimental.cpo.CPOTrainer`]. This is syntactic sugar that automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`. AlphaPO applies a transformation to the reward function shape in the context of SimPO loss when the `alpha` parameter is non-zero. |
108
+
109
+ ### For Mixture of Experts Models: Enabling the auxiliary loss
110
+
111
+ MOEs are the most efficient if the load is about equally distributed between experts.
112
+ To ensure that we train MOEs similarly during preference-tuning, it is beneficial to add the auxiliary loss from the load balancer to the final loss.
113
+
114
+ This option is enabled by setting `output_router_logits=True` in the model config (e.g., [`~transformers.MixtralConfig`]).
115
+ To scale how much the auxiliary loss contributes to the total loss, use the hyperparameter `router_aux_loss_coef=...` (default: `0.001`) in the model config.
116
+
117
+ ## CPOTrainer
118
+
119
+ [[autodoc]] experimental.cpo.CPOTrainer
120
+ - train
121
+ - save_model
122
+ - push_to_hub
123
+
124
+ ## CPOConfig
125
+
126
+ [[autodoc]] experimental.cpo.CPOConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/customization.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training customization
2
+
3
+ TRL is designed with modularity in mind so that users are able to efficiently customize the training loop for their needs. Below are examples on how you can apply and test different techniques.
4
+
5
+ > [!NOTE]
6
+ > Although these examples use the [`DPOTrainer`], these customization methods apply to most (if not all) trainers in TRL.
7
+
8
+ ## Use different optimizers and schedulers
9
+
10
+ By default, the [`DPOTrainer`] creates a `torch.optim.AdamW` optimizer. You can create and define a different optimizer and pass it to [`DPOTrainer`] as follows:
11
+
12
+ ```python
13
+ from datasets import load_dataset
14
+ from torch import optim
15
+ from transformers import AutoModelForCausalLM
16
+ from trl import DPOTrainer
17
+
18
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
19
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
20
+ optimizer = optim.SGD(model.parameters(), lr=1e-6)
21
+
22
+ trainer = DPOTrainer(
23
+ model=model,
24
+ train_dataset=dataset,
25
+ optimizers=(optimizer, None),
26
+ )
27
+ trainer.train()
28
+ ```
29
+
30
+ ### Add a learning rate scheduler
31
+
32
+ You can also add learning rate schedulers by passing both optimizer and scheduler:
33
+
34
+ ```python
35
+ from torch import optim
36
+
37
+ optimizer = optim.AdamW(model.parameters(), lr=1e-6)
38
+ lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)
39
+
40
+ trainer = DPOTrainer(..., optimizers=(optimizer, lr_scheduler))
41
+ ```
42
+
43
+ ## Pass 8-bit reference models
44
+
45
+ Since `trl` supports all keyword arguments when loading a model from `transformers` using `from_pretrained`, you can also leverage `load_in_8bit` from `transformers` for more memory efficient fine-tuning.
46
+
47
+ Read more about 8-bit model loading in `transformers` [Load in 8bit or 4bit](https://huggingface.co/docs/transformers/en/peft).
48
+
49
+ ```python
50
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
51
+
52
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
53
+ ref_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", quantization_config=quantization_config)
54
+
55
+ trainer = DPOTrainer(..., ref_model=ref_model)
56
+ ```
57
+
58
+ ## Add custom callbacks
59
+
60
+ You can customize the training loop by adding callbacks for logging, monitoring, or early stopping. Callbacks allow you to execute custom code at specific points during training.
61
+
62
+ ```python
63
+ from transformers import TrainerCallback
64
+
65
+
66
+ class CustomLoggingCallback(TrainerCallback):
67
+ def on_log(self, args, state, control, logs=None, **kwargs):
68
+ if logs is not None:
69
+ print(f"Step {state.global_step}: {logs}")
70
+
71
+
72
+ trainer = DPOTrainer(..., callbacks=[CustomLoggingCallback()])
73
+ ```
74
+
75
+ ## Add custom evaluation metrics
76
+
77
+ You can define custom evaluation metrics to track during training. This is useful for monitoring model performance on specific tasks.
78
+
79
+ ```python
80
+ def compute_metrics(eval_preds):
81
+ logits, labels = eval_preds
82
+ # Add your metric computation here
83
+ return {"custom_metric": 0.0}
84
+
85
+
86
+ training_args = DPOConfig(..., eval_strategy="steps", eval_steps=100)
87
+
88
+ trainer = DPOTrainer(..., eval_dataset=eval_dataset, compute_metrics=compute_metrics)
89
+ ```
90
+
91
+ ## Use mixed precision training
92
+
93
+ Mixed precision training can significantly speed up training and reduce memory usage. You can enable it by setting `bf16=True` or `fp16=True` in the training config.
94
+
95
+ ```python
96
+ # Use bfloat16 precision (recommended for modern GPUs)
97
+ training_args = DPOConfig(..., bf16=True)
98
+ ```
99
+
100
+ Note: Use `bf16=True` for Ampere GPUs (A100, RTX 30xx) or newer, and `fp16=True` for older GPUs.
101
+
102
+ ## Use gradient accumulation
103
+
104
+ When training with limited GPU memory, gradient accumulation allows you to simulate larger batch sizes by accumulating gradients over multiple steps before updating weights.
105
+
106
+ ```python
107
+ # Simulate a batch size of 32 with per_device_train_batch_size=4 and gradient_accumulation_steps=8
108
+ training_args = DPOConfig(
109
+ ...,
110
+ per_device_train_batch_size=4,
111
+ gradient_accumulation_steps=8,
112
+ )
113
+ ```
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/data_utils.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data Utilities
2
+
3
+ ## is_conversational
4
+
5
+ [[autodoc]] is_conversational
6
+
7
+ ## maybe_convert_to_chatml
8
+
9
+ [[autodoc]] maybe_convert_to_chatml
10
+
11
+ ## extract_prompt
12
+
13
+ [[autodoc]] extract_prompt
14
+
15
+ ## unpair_preference_dataset
16
+
17
+ [[autodoc]] unpair_preference_dataset
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/dataset_formats.md ADDED
@@ -0,0 +1,1012 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset formats and types
2
+
3
+ This guide provides an overview of the dataset formats and types supported by each trainer in TRL.
4
+
5
+ ## Overview of the dataset formats and types
6
+
7
+ - The *format* of a dataset refers to how the data is structured, typically categorized as either *standard* or *conversational*.
8
+ - The *type* is associated with the specific task the dataset is designed for, such as *prompt-only* or *preference*. Each type is characterized by its columns, which vary according to the task, as shown in the table.
9
+
10
+ <table>
11
+ <tr>
12
+ <th>Type \ Format</th>
13
+ <th>Standard</th>
14
+ <th>Conversational</th>
15
+ </tr>
16
+ <tr>
17
+ <td>Language modeling</td>
18
+ <td>
19
+ <pre><code>{"text": "The sky is blue."}</code></pre>
20
+ </td>
21
+ <td>
22
+ <pre><code>{"messages": [{"role": "user", "content": "What color is the sky?"},
23
+ {"role": "assistant", "content": "It is blue."}]}</code></pre>
24
+ </td>
25
+ </tr>
26
+ <tr>
27
+ <td>Prompt-only</td>
28
+ <td>
29
+ <pre><code>{"prompt": "The sky is"}</code></pre>
30
+ </td>
31
+ <td>
32
+ <pre><code>{"prompt": [{"role": "user", "content": "What color is the sky?"}]}</code></pre>
33
+ </td>
34
+ </tr>
35
+ <tr>
36
+ <td>Prompt-completion</td>
37
+ <td>
38
+ <pre><code>{"prompt": "The sky is",
39
+ "completion": " blue."}</code></pre>
40
+ </td>
41
+ <td>
42
+ <pre><code>{"prompt": [{"role": "user", "content": "What color is the sky?"}],
43
+ "completion": [{"role": "assistant", "content": "It is blue."}]}</code></pre>
44
+ </td>
45
+ </tr>
46
+ </tr>
47
+ <tr>
48
+ <td>Preference</td>
49
+ <td>
50
+ <pre><code>{"prompt": "The sky is",
51
+ "chosen": " blue.",
52
+ "rejected": " green."}</code></pre>
53
+ or, with implicit prompt:
54
+ <pre><code>{"chosen": "The sky is blue.",
55
+ "rejected": "The sky is green."}</code></pre>
56
+ </td>
57
+ <td>
58
+ <pre><code>{"prompt": [{"role": "user", "content": "What color is the sky?"}],
59
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
60
+ "rejected": [{"role": "assistant", "content": "It is green."}]}</code></pre>
61
+ or, with implicit prompt:
62
+ <pre><code>{"chosen": [{"role": "user", "content": "What color is the sky?"},
63
+ {"role": "assistant", "content": "It is blue."}],
64
+ "rejected": [{"role": "user", "content": "What color is the sky?"},
65
+ {"role": "assistant", "content": "It is green."}]}</code></pre>
66
+ </td>
67
+ </tr>
68
+ <td>Unpaired preference</td>
69
+ <td>
70
+ <pre><code>{"prompt": "The sky is",
71
+ "completion": " blue.",
72
+ "label": True}</code></pre>
73
+ </td>
74
+ <td>
75
+ <pre><code>{"prompt": [{"role": "user", "content": "What color is the sky?"}],
76
+ "completion": [{"role": "assistant", "content": "It is green."}],
77
+ "label": False}</code></pre>
78
+ </td>
79
+ </tr>
80
+ </tr>
81
+ <td>Stepwise supervision</td>
82
+ <td>
83
+ <pre><code>{"prompt": "Which number is larger, 9.8 or 9.11?",
84
+ "completions": ["The fractional part of 9.8 is 0.8.",
85
+ "The fractional part of 9.11 is 0.11.",
86
+ "0.11 is greater than 0.8.",
87
+ "Hence, 9.11 > 9.8."],
88
+ "labels": [True, True, False, False]}</code></pre>
89
+ </td>
90
+ <td></td>
91
+ </tr>
92
+ </table>
93
+
94
+ ### Formats
95
+
96
+ #### Standard
97
+
98
+ The standard dataset format typically consists of plain text strings. The columns in the dataset vary depending on the task. This is the format expected by TRL trainers. Below are examples of standard dataset formats for different tasks:
99
+
100
+ ```python
101
+ # Language modeling
102
+ language_modeling_example = {"text": "The sky is blue."}
103
+ # Preference
104
+ preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}
105
+ # Unpaired preference
106
+ unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True}
107
+ ```
108
+
109
+ #### Conversational
110
+
111
+ Conversational datasets are used for tasks involving dialogues or chat interactions between users and assistants. Unlike standard dataset formats, these contain sequences of messages where each message has a `role` (e.g., `"user"` or `"assistant"`) and `content` (the message text).
112
+
113
+ ```python
114
+ messages = [
115
+ {"role": "user", "content": "Hello, how are you?"},
116
+ {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
117
+ {"role": "user", "content": "I'd like to show off how chat templating works!"},
118
+ ]
119
+ ```
120
+
121
+ Just like standard datasets, the columns in conversational datasets vary depending on the task. Below are examples of conversational dataset formats for different tasks:
122
+
123
+ ```python
124
+ # Prompt-completion
125
+ prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
126
+ "completion": [{"role": "assistant", "content": "It is blue."}]}
127
+ # Preference
128
+ preference_example = {
129
+ "prompt": [{"role": "user", "content": "What color is the sky?"}],
130
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
131
+ "rejected": [{"role": "assistant", "content": "It is green."}],
132
+ }
133
+ ```
134
+
135
+ #### Tool Calling
136
+
137
+ Some chat templates support *tool calling*, which allows the model to interact with external functions—referred to as **tools**—during generation. This extends the conversational capabilities of the model by enabling it to output a `"tool_calls"` field instead of a standard `"content"` message whenever it decides to invoke a tool.
138
+
139
+ After the assistant initiates a tool call, the tool executes and returns its output. The assistant can then process this output and continue the conversation accordingly.
140
+
141
+ Here’s a simple example of a tool-calling interaction:
142
+
143
+ ```python
144
+ messages = [
145
+ {"role": "user", "content": "Turn on the living room lights."},
146
+ {"role": "assistant", "tool_calls": [
147
+ {"type": "function", "function": {
148
+ "name": "control_light",
149
+ "arguments": {"room": "living room", "state": "on"}
150
+ }}]
151
+ },
152
+ {"role": "tool", "name": "control_light", "content": "The lights in the living room are now on."},
153
+ {"role": "assistant", "content": "Done!"}
154
+ ]
155
+ ```
156
+
157
+ When preparing datasets for Supervised Fine-Tuning (SFT) with tool calling, it is important that your dataset includes an additional column named `tools`. This column contains the list of available tools for the model, which is usually used by the chat template to construct the system prompt.
158
+
159
+ The tools must be specified in a codified JSON schema format. You can automatically generate this schema from Python function signatures using the [`~transformers.utils.get_json_schema`] utility:
160
+
161
+ ```python
162
+ import json
163
+ from transformers.utils import get_json_schema
164
+
165
+ def control_light(room: str, state: str) -> str:
166
+ """
167
+ Controls the lights in a room.
168
+
169
+ Args:
170
+ room: The name of the room.
171
+ state: The desired state of the light ("on" or "off").
172
+
173
+ Returns:
174
+ str: A message indicating the new state of the lights.
175
+ """
176
+ return f"The lights in {room} are now {state}."
177
+
178
+ # Generate JSON schema
179
+ json_schema = get_json_schema(control_light)
180
+ ```
181
+
182
+ The generated schema would look like:
183
+
184
+ ```python
185
+ {"type": "function", "function": {"name": "control_light", "description": "Controls the lights in a room.", "parameters": {"type": "object", "properties": {"room": {"type": "string", "description": "The name of the room."}, "state": {"type": "string", "description": "The desired state of the light (\"on\" or \"off\")."}}, "required": ["room", "state"]}, "return": {"type": "string", "description": "str: A message indicating the new state of the lights."}}}
186
+ ```
187
+
188
+ A complete dataset entry for SFT might look like:
189
+
190
+ ```python
191
+ {"messages": messages, "tools": [json_schema]}
192
+ ```
193
+
194
+ To get a `Dataset` you need to use the `Json()` type for tool arguments since they are arbitrary JSON objects, and not dictionaries with fixed fields and types:
195
+
196
+ ```python
197
+ from datasets import Dataset
198
+
199
+ data = [
200
+ {"messages": messages1, "tools": [json_schema1]},
201
+ {"messages": messages2, "tools": [json_schema2]},
202
+ ]
203
+ # auto-apply the Json() type
204
+ dataset = Dataset.from_list(data, on_mixed_types="use_json")
205
+
206
+ # or specify the features manually
207
+ from datasets import Features, Json, List, Value
208
+
209
+ features = Features(
210
+ {
211
+ "messages": List({"role": Value("string"), "content": Value("string"), "tool_calls": List(Json())}),
212
+ "tools": List(Json()),
213
+ }
214
+ )
215
+ dataset = Dataset.from_list(data, features=features)
216
+ ```
217
+
218
+ On older versions of `datasets` (<4.7.0) that don't have the `Json()` type, you should store `tools` as a JSON `str` (with `json.dumps([...])`):
219
+
220
+ ```python
221
+ dataset = Dataset.from_list(
222
+ [{"messages": messages1, "tools": json.dumps([json_schema1])},
223
+ {"messages": messages2, "tools": json.dumps([json_schema2])}]
224
+ )
225
+ ```
226
+
227
+ For more detailed information on tool calling, refer to the [Tool Calling section in the `transformers` documentation](https://huggingface.co/docs/transformers/chat_extras#tools-and-rag) and the blog post [Tool Use, Unified](https://huggingface.co/blog/unified-tool-use).
228
+
229
+ ### Harmony
230
+
231
+ The [Harmony response format](https://cookbook.openai.com/articles/openai-harmony) was introduced with the [OpenAI GPT OSS models](https://huggingface.co/collections/openai/gpt-oss-68911959590a1634ba11c7a4). It extends the conversational format by adding richer structure for reasoning, function calls, and metadata about the model’s behavior. Key features include:
232
+
233
+ - **Developer role** – Provides high level instructions (similar to a system prompt) and lists available tools.
234
+ - **Channels** – Separate types of assistant output into distinct streams:
235
+
236
+ - `analysis` – for internal reasoning, from the key `"thinking"`
237
+ - `final` – for the user-facing answer, from the key `"content"`
238
+ - `commentary` – for tool calls or meta notes
239
+
240
+ - **Reasoning effort** – Signals how much thinking the model should show (e.g., `"low"`, `"medium"`, `"high"`).
241
+ - **Model identity** – Explicitly defines the assistant’s persona.
242
+
243
+ ```python
244
+ from transformers import AutoTokenizer
245
+
246
+ tokenizer = AutoTokenizer.from_pretrained("openai/gpt-oss-20b")
247
+
248
+ messages = [
249
+ {"role": "developer", "content": "Use a friendly tone."},
250
+ {"role": "user", "content": "What is the meaning of life?"},
251
+ {"role": "assistant", "thinking": "Deep reflection...", "content": "The final answer is..."},
252
+ ]
253
+
254
+ print(
255
+ tokenizer.apply_chat_template(
256
+ messages,
257
+ tokenize=False,
258
+ reasoning_effort="low",
259
+ model_identity="You are HuggingGPT, a large language model trained by Hugging Face.",
260
+ )
261
+ )
262
+ ```
263
+
264
+ This produces:
265
+
266
+ ```txt
267
+ <|start|>system<|message|>You are HuggingGPT, a large language model trained by Hugging Face.
268
+ Knowledge cutoff: 2024-06
269
+ Current date: 2025-08-03
270
+
271
+ Reasoning: low
272
+
273
+ # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions
274
+
275
+ Use a friendly tone.<|end|><|start|>user<|message|>What is the meaning of life?<|end|><|start|>assistant<|channel|>analysis<|message|>Deep reflection...<|end|><|start|>assistant<|channel|>final<|message|>The final answer is...<|return|>
276
+ ```
277
+
278
+ For full details on message structure, supported fields, and advanced usage, see the [Harmony documentation](https://cookbook.openai.com/articles/openai-harmony).
279
+
280
+ ### Types
281
+
282
+ #### Language modeling
283
+
284
+ A language modeling dataset consists of a column `"text"` (or `"messages"` for conversational datasets) containing a full sequence of text.
285
+
286
+ ```python
287
+ # Standard format
288
+ language_modeling_example = {"text": "The sky is blue."}
289
+ # Conversational format
290
+ language_modeling_example = {"messages": [
291
+ {"role": "user", "content": "What color is the sky?"},
292
+ {"role": "assistant", "content": "It is blue."}
293
+ ]}
294
+ ```
295
+
296
+ #### Prompt-only
297
+
298
+ In a prompt-only dataset, only the initial prompt (the question or partial sentence) is provided under the key `"prompt"`. The training typically involves generating completion based on this prompt, where the model learns to continue or complete the given input.
299
+
300
+ ```python
301
+ # Standard format
302
+ prompt_only_example = {"prompt": "The sky is"}
303
+ # Conversational format
304
+ prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]}
305
+ ```
306
+
307
+ For examples of prompt-only datasets, refer to the [Prompt-only datasets collection](https://huggingface.co/collections/trl-lib/prompt-only-datasets-677ea25245d20252cea00368).
308
+
309
+ > [!TIP]
310
+ > While both the prompt-only and language modeling types are similar, they differ in how the input is handled. In the prompt-only type, the prompt represents a partial input that expects the model to complete or continue, while in the language modeling type, the input is treated as a complete sentence or sequence. These two types are processed differently by TRL. Below is an example showing the difference in the output of the `apply_chat_template` function for each type:
311
+ >
312
+ > ```python
313
+ > from transformers import AutoTokenizer
314
+ > from trl import apply_chat_template
315
+ >
316
+ > tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
317
+ >
318
+ > # Example for prompt-only type
319
+ > prompt_only_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}]}
320
+ > apply_chat_template(prompt_only_example, tokenizer)
321
+ > # Output: {'prompt': '<|user|>\nWhat color is the sky?<|end|>\n<|assistant|>\n'}
322
+ >
323
+ > # Example for language modeling type
324
+ > lm_example = {"messages": [{"role": "user", "content": "What color is the sky?"}]}
325
+ > apply_chat_template(lm_example, tokenizer)
326
+ > # Output: {'text': '<|user|>\nWhat color is the sky?<|end|>\n<|endoftext|>'}
327
+ > ```
328
+ >
329
+ > - The prompt-only output includes a `'<|assistant|>\n'`, indicating the beginning of the assistant’s turn and expecting the model to generate a completion.
330
+ > - In contrast, the language modeling output treats the input as a complete sequence and terminates it with `'<|endoftext|>'`, signaling the end of the text and not expecting any additional content.
331
+
332
+ #### Prompt-completion
333
+
334
+ A prompt-completion dataset includes a `"prompt"` and a `"completion"`.
335
+
336
+ ```python
337
+ # Standard format
338
+ prompt_completion_example = {"prompt": "The sky is", "completion": " blue."}
339
+ # Conversational format
340
+ prompt_completion_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
341
+ "completion": [{"role": "assistant", "content": "It is blue."}]}
342
+ ```
343
+
344
+ For examples of prompt-completion datasets, refer to the [Prompt-completion datasets collection](https://huggingface.co/collections/trl-lib/prompt-completion-datasets-677ea2bb20bbb6bdccada216).
345
+
346
+ #### Preference
347
+
348
+ A preference dataset is used for tasks where the model is trained to choose between two or more possible completions to the same prompt. This dataset includes a `"prompt"`, a `"chosen"` completion, and a `"rejected"` completion. The model is trained to select the `"chosen"` response over the `"rejected"` response.
349
+ Some datasets may not include the `"prompt"` column, in which case the prompt is implicit and directly included in the `"chosen"` and `"rejected"` completions. We recommend using explicit prompts whenever possible.
350
+
351
+ ```python
352
+ # Standard format
353
+ ## Explicit prompt (recommended)
354
+ preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}
355
+ # Implicit prompt
356
+ preference_example = {"chosen": "The sky is blue.", "rejected": "The sky is green."}
357
+
358
+ # Conversational format
359
+ ## Explicit prompt (recommended)
360
+ preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
361
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
362
+ "rejected": [{"role": "assistant", "content": "It is green."}]}
363
+ ## Implicit prompt
364
+ preference_example = {"chosen": [{"role": "user", "content": "What color is the sky?"},
365
+ {"role": "assistant", "content": "It is blue."}],
366
+ "rejected": [{"role": "user", "content": "What color is the sky?"},
367
+ {"role": "assistant", "content": "It is green."}]}
368
+ ```
369
+
370
+ For examples of preference datasets, refer to the [Preference datasets collection](https://huggingface.co/collections/trl-lib/preference-datasets-677e99b581018fcad9abd82c).
371
+
372
+ Some preference datasets can be found with [the tag `dpo` on Hugging Face Hub](https://huggingface.co/datasets?other=dpo). You can also explore the [librarian-bots' DPO Collections](https://huggingface.co/collections/librarian-bots/direct-preference-optimization-datasets-66964b12835f46289b6ef2fc) to identify preference datasets.
373
+
374
+ #### Unpaired preference
375
+
376
+ An unpaired preference dataset is similar to a preference dataset but instead of having `"chosen"` and `"rejected"` completions for the same prompt, it includes a single `"completion"` and a `"label"` indicating whether the completion is preferred or not.
377
+
378
+ ```python
379
+ # Standard format
380
+ unpaired_preference_example = {"prompt": "The sky is", "completion": " blue.", "label": True}
381
+ # Conversational format
382
+ unpaired_preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
383
+ "completion": [{"role": "assistant", "content": "It is blue."}],
384
+ "label": True}
385
+ ```
386
+
387
+ For examples of unpaired preference datasets, refer to the [Unpaired preference datasets collection](https://huggingface.co/collections/trl-lib/unpaired-preference-datasets-677ea22bf5f528c125b0bcdf).
388
+
389
+ #### Stepwise supervision
390
+
391
+ A stepwise (or process) supervision dataset is similar to an [unpaired preference](#unpaired-preference) dataset but includes multiple steps of completions, each with its own label. This structure is useful for tasks that need detailed, step-by-step labeling, such as reasoning tasks. By evaluating each step separately and providing targeted labels, this approach helps identify precisely where the reasoning is correct and where errors occur, allowing for targeted feedback on each part of the reasoning process.
392
+
393
+ ```python
394
+ stepwise_example = {
395
+ "prompt": "Which number is larger, 9.8 or 9.11?",
396
+ "completions": ["The fractional part of 9.8 is 0.8, while the fractional part of 9.11 is 0.11.", "Since 0.11 is greater than 0.8, the number 9.11 is larger than 9.8."],
397
+ "labels": [True, False]
398
+ }
399
+ ```
400
+
401
+ For examples of stepwise supervision datasets, refer to the [Stepwise supervision datasets collection](https://huggingface.co/collections/trl-lib/stepwise-supervision-datasets-677ea27fd4c5941beed7a96e).
402
+
403
+ ## Which dataset type to use?
404
+
405
+ Choosing the right dataset type depends on the task you are working on and the specific requirements of the TRL trainer you are using. Below is a brief overview of the dataset types supported by each TRL trainer.
406
+
407
+ | Trainer | Expected dataset type |
408
+ | --- | --- |
409
+ | [`DPOTrainer`] | [Preference (explicit prompt recommended)](#preference) |
410
+ | [`GRPOTrainer`] | [Prompt-only](#prompt-only) |
411
+ | [`RewardTrainer`] | [Preference (implicit prompt recommended)](#preference) |
412
+ | [`RLOOTrainer`] | [Prompt-only](#prompt-only) |
413
+ | [`SFTTrainer`] | [Language modeling](#language-modeling) or [Prompt-completion](#prompt-completion) |
414
+ | [`experimental.bco.BCOTrainer`] | [Unpaired preference](#unpaired-preference) or [Preference (explicit prompt recommended)](#preference) |
415
+ | [`experimental.cpo.CPOTrainer`] | [Preference (explicit prompt recommended)](#preference) |
416
+ | [`experimental.gkd.GKDTrainer`] | [Prompt-completion](#prompt-completion) |
417
+ | [`experimental.kto.KTOTrainer`] | [Unpaired preference](#unpaired-preference) or [Preference (explicit prompt recommended)](#preference) |
418
+ | [`experimental.nash_md.NashMDTrainer`] | [Prompt-only](#prompt-only) |
419
+ | [`experimental.online_dpo.OnlineDPOTrainer`] | [Prompt-only](#prompt-only) |
420
+ | [`experimental.orpo.ORPOTrainer`] | [Preference (explicit prompt recommended)](#preference) |
421
+ | [`experimental.ppo.PPOTrainer`] | Tokenized language modeling |
422
+ | [`experimental.prm.PRMTrainer`] | [Stepwise supervision](#stepwise-supervision) |
423
+ | [`experimental.xpo.XPOTrainer`] | [Prompt-only](#prompt-only) |
424
+
425
+ ## Using any dataset with TRL: preprocessing and conversion
426
+
427
+ Many datasets come in formats tailored to specific tasks, which might not be directly compatible with TRL. To use such datasets with TRL, you may need to preprocess and convert them into the required format.
428
+
429
+ To make this easier, we provide a set of [example scripts](https://github.com/huggingface/trl/tree/main/examples/datasets) that cover common dataset conversions.
430
+
431
+ ### Example: UltraFeedback dataset
432
+
433
+ Let’s take the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback) as an example. Here's a preview of the dataset:
434
+
435
+ <iframe
436
+ src="https://huggingface.co/datasets/openbmb/UltraFeedback/embed/viewer/default/train"
437
+ frameborder="0"
438
+ width="100%"
439
+ height="560px"
440
+ ></iframe>
441
+
442
+ As shown above, the dataset format does not match the expected structure. It’s not in a conversational format, the column names differ, and the results pertain to different models (e.g., Bard, GPT-4) and aspects (e.g., "helpfulness", "honesty").
443
+
444
+ By using the provided conversion script [`examples/datasets/ultrafeedback.py`](https://github.com/huggingface/trl/tree/main/examples/datasets/ultrafeedback.py), you can transform this dataset into an unpaired preference type, and push it to the Hub:
445
+
446
+ ```sh
447
+ python examples/datasets/ultrafeedback.py --push_to_hub --repo_id trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness
448
+ ```
449
+
450
+ Once converted, the dataset will look like this:
451
+
452
+ <iframe
453
+ src="https://huggingface.co/datasets/trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness/embed/viewer/default/train?row=0"
454
+ frameborder="0"
455
+ width="100%"
456
+ height="560px"
457
+ ></iframe>
458
+
459
+ Now, you can use this dataset with TRL!
460
+
461
+ By adapting the provided scripts or creating your own, you can convert any dataset into a format compatible with TRL.
462
+
463
+ ## Utilities for converting dataset types
464
+
465
+ This section provides example code to help you convert between different dataset types. While some conversions can be performed after applying the chat template (i.e., in the standard format), we recommend performing the conversion before applying the chat template to ensure it works consistently.
466
+
467
+ For simplicity, some of the examples below do not follow this recommendation and use the standard format. However, the conversions can be applied directly to the conversational format without modification.
468
+
469
+ | From \ To | Language modeling | Prompt-completion | Prompt-only | Preference with implicit prompt | Preference | Unpaired preference | Stepwise supervision |
470
+ | --- | --- | --- | --- | --- | --- | --- | --- |
471
+ | Language modeling | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
472
+ | Prompt-completion | [🔗](#from-prompt-completion-to-language-modeling-dataset) | N/A | [🔗](#from-prompt-completion-to-prompt-only-dataset) | N/A | N/A | N/A | N/A |
473
+ | Prompt-only | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
474
+ | Preference with implicit prompt | [🔗](#from-preference-with-implicit-prompt-to-language-modeling-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-completion-dataset) | [🔗](#from-preference-with-implicit-prompt-to-prompt-only-dataset) | N/A | [🔗](#from-implicit-to-explicit-prompt-preference-dataset) | [🔗](#from-preference-with-implicit-prompt-to-unpaired-preference-dataset) | N/A |
475
+ | Preference | [🔗](#from-preference-to-language-modeling-dataset) | [🔗](#from-preference-to-prompt-completion-dataset) | [🔗](#from-preference-to-prompt-only-dataset) | [🔗](#from-explicit-to-implicit-prompt-preference-dataset) | N/A | [🔗](#from-preference-to-unpaired-preference-dataset) | N/A |
476
+ | Unpaired preference | [🔗](#from-unpaired-preference-to-language-modeling-dataset) | [🔗](#from-unpaired-preference-to-prompt-completion-dataset) | [🔗](#from-unpaired-preference-to-prompt-only-dataset) | N/A | N/A | N/A | N/A |
477
+ | Stepwise supervision | [🔗](#from-stepwise-supervision-to-language-modeling-dataset) | [🔗](#from-stepwise-supervision-to-prompt-completion-dataset) | [🔗](#from-stepwise-supervision-to-prompt-only-dataset) | N/A | N/A | [🔗](#from-stepwise-supervision-to-unpaired-preference-dataset) | N/A |
478
+
479
+ ### From prompt-completion to language modeling dataset
480
+
481
+ To convert a prompt-completion dataset into a language modeling dataset, concatenate the prompt and the completion.
482
+
483
+ ```python
484
+ from datasets import Dataset
485
+
486
+ dataset = Dataset.from_dict({
487
+ "prompt": ["The sky is", "The sun is"],
488
+ "completion": [" blue.", " in the sky."],
489
+ })
490
+
491
+ def concat_prompt_completion(example):
492
+ return {"text": example["prompt"] + example["completion"]}
493
+
494
+ dataset = dataset.map(concat_prompt_completion, remove_columns=["prompt", "completion"])
495
+ ```
496
+
497
+ ```python
498
+ >>> dataset[0]
499
+ {'text': 'The sky is blue.'}
500
+ ```
501
+
502
+ ### From prompt-completion to prompt-only dataset
503
+
504
+ To convert a prompt-completion dataset into a prompt-only dataset, remove the completion.
505
+
506
+ ```python
507
+ from datasets import Dataset
508
+
509
+ dataset = Dataset.from_dict({
510
+ "prompt": ["The sky is", "The sun is"],
511
+ "completion": [" blue.", " in the sky."],
512
+ })
513
+
514
+ dataset = dataset.remove_columns("completion")
515
+ ```
516
+
517
+ ```python
518
+ >>> dataset[0]
519
+ {'prompt': 'The sky is'}
520
+ ```
521
+
522
+ ### From preference with implicit prompt to language modeling dataset
523
+
524
+ To convert a preference with implicit prompt dataset into a language modeling dataset, remove the rejected, and rename the column `"chosen"` to `"text"`.
525
+
526
+ ```python
527
+ from datasets import Dataset
528
+
529
+ dataset = Dataset.from_dict({
530
+ "chosen": ["The sky is blue.", "The sun is in the sky."],
531
+ "rejected": ["The sky is green.", "The sun is in the sea."],
532
+ })
533
+
534
+ dataset = dataset.rename_column("chosen", "text").remove_columns("rejected")
535
+ ```
536
+
537
+ ```python
538
+ >>> dataset[0]
539
+ {'text': 'The sky is blue.'}
540
+ ```
541
+
542
+ ### From preference with implicit prompt to prompt-completion dataset
543
+
544
+ To convert a preference dataset with implicit prompt into a prompt-completion dataset, extract the prompt with [`extract_prompt`], remove the rejected, and rename the column `"chosen"` to `"completion"`.
545
+
546
+ ```python
547
+ from datasets import Dataset
548
+ from trl import extract_prompt
549
+
550
+ dataset = Dataset.from_dict({
551
+ "chosen": [
552
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
553
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
554
+ ],
555
+ "rejected": [
556
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
557
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
558
+ ],
559
+ })
560
+ dataset = dataset.map(extract_prompt).remove_columns("rejected").rename_column("chosen", "completion")
561
+ ```
562
+
563
+ ```python
564
+ >>> dataset[0]
565
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}], 'completion': [{'role': 'assistant', 'content': 'It is blue.'}]}
566
+ ```
567
+
568
+ ### From preference with implicit prompt to prompt-only dataset
569
+
570
+ To convert a preference dataset with implicit prompt into a prompt-only dataset, extract the prompt with [`extract_prompt`], and remove the rejected and the chosen.
571
+
572
+ ```python
573
+ from datasets import Dataset
574
+ from trl import extract_prompt
575
+
576
+ dataset = Dataset.from_dict({
577
+ "chosen": [
578
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
579
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
580
+ ],
581
+ "rejected": [
582
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
583
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
584
+ ],
585
+ })
586
+ dataset = dataset.map(extract_prompt).remove_columns(["chosen", "rejected"])
587
+ ```
588
+
589
+ ```python
590
+ >>> dataset[0]
591
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}]}
592
+ ```
593
+
594
+ ### From implicit to explicit prompt preference dataset
595
+
596
+ To convert a preference dataset with implicit prompt into a preference dataset with explicit prompt, extract the prompt with [`extract_prompt`].
597
+
598
+ ```python
599
+ from datasets import Dataset
600
+ from trl import extract_prompt
601
+
602
+ dataset = Dataset.from_dict({
603
+ "chosen": [
604
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
605
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
606
+ ],
607
+ "rejected": [
608
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
609
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
610
+ ],
611
+ })
612
+
613
+ dataset = dataset.map(extract_prompt)
614
+ ```
615
+
616
+ ```python
617
+ >>> dataset[0]
618
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
619
+ 'chosen': [{'role': 'assistant', 'content': 'It is blue.'}],
620
+ 'rejected': [{'role': 'assistant', 'content': 'It is green.'}]}
621
+ ```
622
+
623
+ ### From preference with implicit prompt to unpaired preference dataset
624
+
625
+ To convert a preference dataset with implicit prompt into an unpaired preference dataset, extract the prompt with [`extract_prompt`], and unpair the dataset with [`unpair_preference_dataset`].
626
+
627
+ ```python
628
+ from datasets import Dataset
629
+ from trl import extract_prompt, unpair_preference_dataset
630
+
631
+ dataset = Dataset.from_dict({
632
+ "chosen": [
633
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is blue."}],
634
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sky."}],
635
+ ],
636
+ "rejected": [
637
+ [{"role": "user", "content": "What color is the sky?"}, {"role": "assistant", "content": "It is green."}],
638
+ [{"role": "user", "content": "Where is the sun?"}, {"role": "assistant", "content": "In the sea."}],
639
+ ],
640
+ })
641
+
642
+ dataset = dataset.map(extract_prompt)
643
+ dataset = unpair_preference_dataset(dataset)
644
+ ```
645
+
646
+ ```python
647
+ >>> dataset[0]
648
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
649
+ 'completion': [{'role': 'assistant', 'content': 'It is blue.'}],
650
+ 'label': True}
651
+ ```
652
+
653
+ > [!WARNING]
654
+ > Keep in mind that the `"chosen"` and `"rejected"` completions in a preference dataset can be both good or bad.
655
+ > Before applying [`unpair_preference_dataset`], please ensure that all `"chosen"` completions can be labeled as good and all `"rejected"` completions as bad.
656
+ > This can be ensured by checking absolute rating of each completion, e.g. from a reward model.
657
+
658
+ ### From preference to language modeling dataset
659
+
660
+ To convert a preference dataset into a language modeling dataset, remove the rejected, concatenate the prompt and the chosen into the `"text"` column.
661
+
662
+ ```python
663
+ from datasets import Dataset
664
+
665
+ dataset = Dataset.from_dict({
666
+ "prompt": ["The sky is", "The sun is"],
667
+ "chosen": [" blue.", " in the sky."],
668
+ "rejected": [" green.", " in the sea."],
669
+ })
670
+
671
+ def concat_prompt_chosen(example):
672
+ return {"text": example["prompt"] + example["chosen"]}
673
+
674
+ dataset = dataset.map(concat_prompt_chosen, remove_columns=["prompt", "chosen", "rejected"])
675
+ ```
676
+
677
+ ```python
678
+ >>> dataset[0]
679
+ {'text': 'The sky is blue.'}
680
+ ```
681
+
682
+ ### From preference to prompt-completion dataset
683
+
684
+ To convert a preference dataset into a prompt-completion dataset, remove the rejected, and rename the column `"chosen"` to `"completion"`.
685
+
686
+ ```python
687
+ from datasets import Dataset
688
+
689
+ dataset = Dataset.from_dict({
690
+ "prompt": ["The sky is", "The sun is"],
691
+ "chosen": [" blue.", " in the sky."],
692
+ "rejected": [" green.", " in the sea."],
693
+ })
694
+
695
+ dataset = dataset.remove_columns("rejected").rename_column("chosen", "completion")
696
+ ```
697
+
698
+ ```python
699
+ >>> dataset[0]
700
+ {'prompt': 'The sky is', 'completion': ' blue.'}
701
+ ```
702
+
703
+ ### From preference to prompt-only dataset
704
+
705
+ To convert a preference dataset into a prompt-only dataset, remove the rejected and the chosen.
706
+
707
+ ```python
708
+ from datasets import Dataset
709
+
710
+ dataset = Dataset.from_dict({
711
+ "prompt": ["The sky is", "The sun is"],
712
+ "chosen": [" blue.", " in the sky."],
713
+ "rejected": [" green.", " in the sea."],
714
+ })
715
+
716
+ dataset = dataset.remove_columns(["chosen", "rejected"])
717
+ ```
718
+
719
+ ```python
720
+ >>> dataset[0]
721
+ {'prompt': 'The sky is'}
722
+ ```
723
+
724
+ ### From explicit to implicit prompt preference dataset
725
+
726
+ To convert a preference dataset with explicit prompt into a preference dataset with implicit prompt, concatenate the prompt to both chosen and rejected, and remove the prompt.
727
+
728
+ ```python
729
+ from datasets import Dataset
730
+
731
+ dataset = Dataset.from_dict({
732
+ "prompt": [
733
+ [{"role": "user", "content": "What color is the sky?"}],
734
+ [{"role": "user", "content": "Where is the sun?"}],
735
+ ],
736
+ "chosen": [
737
+ [{"role": "assistant", "content": "It is blue."}],
738
+ [{"role": "assistant", "content": "In the sky."}],
739
+ ],
740
+ "rejected": [
741
+ [{"role": "assistant", "content": "It is green."}],
742
+ [{"role": "assistant", "content": "In the sea."}],
743
+ ],
744
+ })
745
+
746
+ def concat_prompt_to_completions(example):
747
+ return {"chosen": example["prompt"] + example["chosen"], "rejected": example["prompt"] + example["rejected"]}
748
+
749
+ dataset = dataset.map(concat_prompt_to_completions, remove_columns="prompt")
750
+ ```
751
+
752
+ ```python
753
+ >>> dataset[0]
754
+ {'chosen': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is blue.'}],
755
+ 'rejected': [{'role': 'user', 'content': 'What color is the sky?'}, {'role': 'assistant', 'content': 'It is green.'}]}
756
+ ```
757
+
758
+ ### From preference to unpaired preference dataset
759
+
760
+ To convert dataset into an unpaired preference dataset, unpair the dataset with [`unpair_preference_dataset`].
761
+
762
+ ```python
763
+ from datasets import Dataset
764
+ from trl import unpair_preference_dataset
765
+
766
+ dataset = Dataset.from_dict({
767
+ "prompt": [
768
+ [{"role": "user", "content": "What color is the sky?"}],
769
+ [{"role": "user", "content": "Where is the sun?"}],
770
+ ],
771
+ "chosen": [
772
+ [{"role": "assistant", "content": "It is blue."}],
773
+ [{"role": "assistant", "content": "In the sky."}],
774
+ ],
775
+ "rejected": [
776
+ [{"role": "assistant", "content": "It is green."}],
777
+ [{"role": "assistant", "content": "In the sea."}],
778
+ ],
779
+ })
780
+
781
+ dataset = unpair_preference_dataset(dataset)
782
+ ```
783
+
784
+ ```python
785
+ >>> dataset[0]
786
+ {'prompt': [{'role': 'user', 'content': 'What color is the sky?'}],
787
+ 'completion': [{'role': 'assistant', 'content': 'It is blue.'}],
788
+ 'label': True}
789
+ ```
790
+
791
+ > [!WARNING]
792
+ > Keep in mind that the `"chosen"` and `"rejected"` completions in a preference dataset can be both good or bad.
793
+ > Before applying [`unpair_preference_dataset`], please ensure that all `"chosen"` completions can be labeled as good and all `"rejected"` completions as bad.
794
+ > This can be ensured by checking absolute rating of each completion, e.g. from a reward model.
795
+
796
+ ### From unpaired preference to language modeling dataset
797
+
798
+ To convert an unpaired preference dataset into a language modeling dataset, concatenate prompts with good completions into the `"text"` column, and remove the prompt, completion and label columns.
799
+
800
+ ```python
801
+ from datasets import Dataset
802
+
803
+ dataset = Dataset.from_dict({
804
+ "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
805
+ "completion": [" blue.", " in the sky.", " green.", " in the sea."],
806
+ "label": [True, True, False, False],
807
+ })
808
+
809
+ def concatenate_prompt_completion(example):
810
+ return {"text": example["prompt"] + example["completion"]}
811
+
812
+ dataset = dataset.filter(lambda x: x["label"]).map(concatenate_prompt_completion).remove_columns(["prompt", "completion", "label"])
813
+ ```
814
+
815
+ ```python
816
+ >>> dataset[0]
817
+ {'text': 'The sky is blue.'}
818
+ ```
819
+
820
+ ### From unpaired preference to prompt-completion dataset
821
+
822
+ To convert an unpaired preference dataset into a prompt-completion dataset, filter for good labels, then remove the label columns.
823
+
824
+ ```python
825
+ from datasets import Dataset
826
+
827
+ dataset = Dataset.from_dict({
828
+ "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
829
+ "completion": [" blue.", " in the sky.", " green.", " in the sea."],
830
+ "label": [True, True, False, False],
831
+ })
832
+
833
+ dataset = dataset.filter(lambda x: x["label"]).remove_columns(["label"])
834
+ ```
835
+
836
+ ```python
837
+ >>> dataset[0]
838
+ {'prompt': 'The sky is', 'completion': ' blue.'}
839
+ ```
840
+
841
+ ### From unpaired preference to prompt-only dataset
842
+
843
+ To convert an unpaired preference dataset into a prompt-only dataset, remove the completion and the label columns.
844
+
845
+ ```python
846
+ from datasets import Dataset
847
+
848
+ dataset = Dataset.from_dict({
849
+ "prompt": ["The sky is", "The sun is", "The sky is", "The sun is"],
850
+ "completion": [" blue.", " in the sky.", " green.", " in the sea."],
851
+ "label": [True, True, False, False],
852
+ })
853
+
854
+ dataset = dataset.remove_columns(["completion", "label"])
855
+ ```
856
+
857
+ ```python
858
+ >>> dataset[0]
859
+ {'prompt': 'The sky is'}
860
+ ```
861
+
862
+ ### From stepwise supervision to language modeling dataset
863
+
864
+ To convert a stepwise supervision dataset into a language modeling dataset, concatenate prompts with good completions into the `"text"` column.
865
+
866
+ ```python
867
+ from datasets import Dataset
868
+
869
+ dataset = Dataset.from_dict({
870
+ "prompt": ["Blue light", "Water"],
871
+ "completions": [[" scatters more in the atmosphere,", " so the sky is green."],
872
+ [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]],
873
+ "labels": [[True, False], [True, True]],
874
+ })
875
+
876
+ def concatenate_prompt_completions(example):
877
+ completion = "".join(example["completions"])
878
+ return {"text": example["prompt"] + completion}
879
+
880
+ dataset = dataset.filter(lambda x: all(x["labels"])).map(concatenate_prompt_completions, remove_columns=["prompt", "completions", "labels"])
881
+ ```
882
+
883
+ ```python
884
+ >>> dataset[0]
885
+ {'text': 'Blue light scatters more in the atmosphere, so the sky is green.'}
886
+ ```
887
+
888
+ ### From stepwise supervision to prompt-completion dataset
889
+
890
+ To convert a stepwise supervision dataset into a prompt-completion dataset, join the good completions and remove the labels.
891
+
892
+ ```python
893
+ from datasets import Dataset
894
+
895
+ dataset = Dataset.from_dict({
896
+ "prompt": ["Blue light", "Water"],
897
+ "completions": [[" scatters more in the atmosphere,", " so the sky is green."],
898
+ [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]],
899
+ "labels": [[True, False], [True, True]],
900
+ })
901
+
902
+ def join_completions(example):
903
+ completion = "".join(example["completions"])
904
+ return {"completion": completion}
905
+
906
+ dataset = dataset.filter(lambda x: all(x["labels"])).map(join_completions, remove_columns=["completions", "labels"])
907
+ ```
908
+
909
+ ```python
910
+ >>> dataset[0]
911
+ {'prompt': 'Blue light', 'completion': ' scatters more in the atmosphere, so the sky is green.'}
912
+ ```
913
+
914
+ ### From stepwise supervision to prompt-only dataset
915
+
916
+ To convert a stepwise supervision dataset into a prompt-only dataset, remove the completions and the labels.
917
+
918
+ ```python
919
+ from datasets import Dataset
920
+
921
+ dataset = Dataset.from_dict({
922
+ "prompt": ["Blue light", "Water"],
923
+ "completions": [[" scatters more in the atmosphere,", " so the sky is green."],
924
+ [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]],
925
+ "labels": [[True, False], [True, True]],
926
+ })
927
+
928
+ dataset = dataset.remove_columns(["completions", "labels"])
929
+ ```
930
+
931
+ ```python
932
+ >>> dataset[0]
933
+ {'prompt': 'Blue light'}
934
+ ```
935
+
936
+ ### From stepwise supervision to unpaired preference dataset
937
+
938
+ To convert a stepwise supervision dataset into an unpaired preference dataset, join the completions and merge the labels.
939
+
940
+ The method for merging the labels depends on the specific task. In this example, we use the logical AND operation. This means that if the step labels indicate the correctness of individual steps, the resulting label will reflect the correctness of the entire sequence.
941
+
942
+ ```python
943
+ from datasets import Dataset
944
+
945
+ dataset = Dataset.from_dict({
946
+ "prompt": ["Blue light", "Water"],
947
+ "completions": [[" scatters more in the atmosphere,", " so the sky is green."],
948
+ [" forms a less dense structure in ice,", " which causes it to expand when it freezes."]],
949
+ "labels": [[True, False], [True, True]],
950
+ })
951
+
952
+ def merge_completions_and_labels(example):
953
+ return {"prompt": example["prompt"], "completion": "".join(example["completions"]), "label": all(example["labels"])}
954
+
955
+ dataset = dataset.map(merge_completions_and_labels, remove_columns=["completions", "labels"])
956
+ ```
957
+
958
+ ```python
959
+ >>> dataset[0]
960
+ {'prompt': 'Blue light', 'completion': ' scatters more in the atmosphere, so the sky is green.', 'label': False}
961
+ ```
962
+
963
+ ## Vision datasets
964
+
965
+ Some trainers also support fine-tuning vision-language models (VLMs) using image-text pairs. In this scenario, it's recommended to use a conversational format, as each model handles image placeholders in text differently.
966
+
967
+ A conversational vision dataset differs from a standard conversational dataset in two key ways:
968
+
969
+ 1. The dataset must contain the key `images` with the image data (as lists of PIL images) or `image` with a single PIL image.
970
+ 2. The `"content"` field in messages must be a list of dictionaries, where each dictionary specifies the type of data: `"image"` or `"text"`.
971
+
972
+ Example:
973
+
974
+ ```python
975
+ # Textual dataset:
976
+ "content": "What color is the sky?"
977
+
978
+ # Vision dataset:
979
+ "content": [
980
+ {"type": "image"},
981
+ {"type": "text", "text": "What color is the sky in the image?"}
982
+ ]
983
+ ```
984
+
985
+ An example of a conversational vision dataset is the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset). Below is an embedded view of the dataset's training data, allowing you to explore it directly:
986
+
987
+ <iframe
988
+ src="https://huggingface.co/datasets/trl-lib/rlaif-v/embed/viewer/default/train"
989
+ frameborder="0"
990
+ width="100%"
991
+ height="560px"
992
+ ></iframe>
993
+
994
+ > [!NOTE]
995
+ > Mixing text-only and vision-language data in the dataset is possible, but it requires `transformers` version 4.57.0 or later. Example:
996
+ >
997
+ > ```python
998
+ > dataset = Dataset.from_dict({
999
+ > "prompt": [
1000
+ > [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What color is the sky in the image?"}]}],
1001
+ > [{"role": "user", "content": [{"type": "text", "text": "What is the capital of France?"}]}],
1002
+ > ],
1003
+ > "completion": [
1004
+ > [{"role": "assistant", "content": [{"type": "text", "text": "It is blue."}]}],
1005
+ > [{"role": "assistant", "content": [{"type": "text", "text": "Paris."}]}],
1006
+ > ],
1007
+ > "images": [
1008
+ > [PIL.Image.open("path/to/sky_image1.png")],
1009
+ > [],
1010
+ > ],
1011
+ > })
1012
+ > ```
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/deepspeed_integration.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeepSpeed Integration
2
+
3
+ > [!WARNING]
4
+ > Section under construction. Feel free to contribute!
5
+
6
+ TRL supports training with DeepSpeed, a library that implements advanced training optimization techniques. These include optimizer state partitioning, offloading, gradient partitioning, and more.
7
+
8
+ DeepSpeed integrates the [Zero Redundancy Optimizer (ZeRO)](https://huggingface.co/papers/1910.02054), which allows to scale the model size proportional to the number of devices with sustained high efficiency.
9
+
10
+ ![ZeRO Stages](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/zero_stages.png)
11
+
12
+ ## Installation
13
+
14
+ To use DeepSpeed with TRL, install it using the following command:
15
+
16
+ ```bash
17
+ pip install deepspeed
18
+ ```
19
+
20
+ ## Running Training Scripts with DeepSpeed
21
+
22
+ No modifications to your training script are required. Simply run it with the DeepSpeed configuration file:
23
+
24
+ ```bash
25
+ accelerate launch --config_file <ACCELERATE_WITH_DEEPSPEED_CONFIG_FILE.yaml> train.py
26
+ ```
27
+
28
+ We provide ready-to-use DeepSpeed configuration files in the [`examples/accelerate_configs`](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) directory. For example, to run training with ZeRO Stage 2, use the following command:
29
+
30
+ ```bash
31
+ accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml train.py
32
+ ```
33
+
34
+ ## Additional Resources
35
+
36
+ Consult the 🤗 Accelerate [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more information about the DeepSpeed plugin.
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/distributing_training.md ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Distributing Training
2
+
3
+ > [!WARNING]
4
+ > Section under construction. Feel free to contribute!
5
+
6
+ ## Multi-GPU Training with TRL
7
+
8
+ The trainers in TRL use [🤗 Accelerate](https://github.com/huggingface/accelerate) to enable distributed training across multiple GPUs or nodes. To do so, first create an [🤗 Accelerate](https://github.com/huggingface/accelerate) config file by running
9
+
10
+ ```bash
11
+ accelerate config
12
+ ```
13
+
14
+ and answering the questions according to your multi-GPU / multi-node setup. You can then launch distributed training by running:
15
+
16
+ ```bash
17
+ accelerate launch train.py
18
+ ```
19
+
20
+ We also provide config files in the [examples folder](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) that can be used as templates. To use these templates, simply pass the path to the config file when launching a job, e.g.:
21
+
22
+ ```shell
23
+ accelerate launch --config_file examples/accelerate_configs/multi_gpu.yaml train.py <SCRIPT_ARGS>
24
+ ```
25
+
26
+ This automatically distributes the workload across all available GPUs.
27
+
28
+ Under the hood, [🤗 Accelerate](https://github.com/huggingface/accelerate) creates one model per GPU. Each process:
29
+
30
+ - Processes its own batch of data
31
+ - Computes the loss and gradients for that batch
32
+ - Shares gradient updates across all GPUs
33
+
34
+ ![multi gpu](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/multi_gpu.png)
35
+
36
+ The effective batch size is calculated as:
37
+
38
+ $$
39
+ \text{Batch Size} = \text{per\_device\_train\_batch\_size} \times \text{num\_devices} \times \text{gradient\_accumulation\_steps}
40
+ $$
41
+
42
+ To maintain a consistent batch size when scaling to multiple GPUs, make sure to update `per_device_train_batch_size` and `gradient_accumulation_steps` accordingly.
43
+
44
+ Example, these configurations are equivalent, and should yield the same results:
45
+
46
+ | Number of GPUs | Per device batch size | Gradient accumulation steps | Comments |
47
+ | --- | --- | --- | --- |
48
+ | 1 | 32 | 1 | Possibly high memory usage, but faster training |
49
+ | 1 | 4 | 8 | Lower memory usage, slower training |
50
+ | 8 | 4 | 1 | Multi-GPU to get the best of both worlds |
51
+
52
+ > [!TIP]
53
+ > Having one model per GPU can lead to high memory usage, which may not be feasible for large models or low-memory GPUs. In such cases, you can leverage [DeepSpeed](https://github.com/deepspeedai/DeepSpeed), which provides optimizations like model sharding, Zero Redundancy Optimizer, mixed precision training, and offloading to CPU or NVMe. Check out our [DeepSpeed Integration](deepspeed_integration) guide for more details.
54
+
55
+ ## Sequence Parallelism for Long Context Training
56
+
57
+ Sequence Parallelism (also called Context Parallelism) is a parallelization technique that enables training with longer sequences by splitting the sequence dimension across multiple GPUs. Each GPU processes a portion of the sequence, allowing you to train with sequences longer than what would fit on a single GPU's memory.
58
+
59
+ > [!NOTE]
60
+ > **Terminology clarification:** This section describes parallelism techniques for splitting sequences to enable longer context training:
61
+ > - **Context Parallelism (CP)**: Splits sequences across GPUs (implemented as Ring Attention with FSDP2)
62
+ > - **Sequence Parallelism (SP)**: Another form of sequence splitting (implemented as ALST/Ulysses with DeepSpeed)
63
+ >
64
+ > Both CP and SP are different from traditional Sequence Parallelism used with Tensor Parallelism (TP+SP) to reduce activation memory. With the techniques here, parallelism dimensions multiply: `TP=2` and `CP=2` would require 4 GPUs (2×2), whereas traditional `TP+SP=2` only needs 2 GPUs as they share the same ranks.
65
+ >
66
+ > In Accelerate's `ParallelismConfig`:
67
+ > - Use `cp_size` with `cp_backend="torch"` for Ring Attention (FSDP2)
68
+ > - Use `sp_size` with `sp_backend="deepspeed"` for ALST/Ulysses (DeepSpeed)
69
+
70
+ Sequence parallelism is particularly useful when:
71
+
72
+ - You want to train with very long sequences (>32k tokens)
73
+ - Single GPU memory is insufficient for your desired sequence length
74
+ - You need to maintain sequence coherence across the full context
75
+
76
+ ### Available Implementations
77
+
78
+ TRL supports two sequence parallelism implementations, each with different characteristics:
79
+
80
+ 1. **Ring Attention (FSDP2)** - Uses ring-based communication for memory-efficient processing of extremely long sequences
81
+ 2. **ALST/Ulysses (DeepSpeed)** - Uses attention head parallelism for faster training with high-bandwidth interconnects
82
+
83
+ > [!IMPORTANT]
84
+ > **Sequence Length Terminology:** When using Context Parallelism, the sequence is split across GPUs, introducing two concepts:
85
+ > - **Global sequence length**: The full sequence length before splitting across GPUs
86
+ > - **Micro sequence length**: The sequence length per GPU after splitting
87
+ >
88
+ > In TRL, `max_seq_length` (or `max_length`) refers to the **global sequence length**. The framework automatically handles splitting into micro sequences:
89
+ > - **Ring Attention (FSDP2)**: Uses `cp_size` to split sequences. With `max_seq_length=8192` and `cp_size=4`, each GPU processes 2048 tokens.
90
+ > - **ALST/Ulysses (DeepSpeed)**: Uses `sp_size` (with `sp_backend="deepspeed"`) to split sequences. With `max_seq_length=8192` and `sp_size=2`, each GPU processes 4096 tokens.
91
+ >
92
+ > The Trainer automatically accounts for context parallelism when calculating batch sizes and training metrics.
93
+
94
+ ### Choosing Between Ring Attention and Ulysses
95
+
96
+ The comparison table below highlights the key differences between the two approaches:
97
+
98
+ | Feature | Ring Attention (FSDP2) | ALST/Ulysses (DeepSpeed) |
99
+ |---------|----------|-------------------------|
100
+ | **Method** | Ring Self-Attention | Attention Head Parallelism |
101
+ | **Backend** | PyTorch FSDP2 | DeepSpeed ZeRO |
102
+ | **Attention** | SDPA only | Flash Attention 2 or SDPA |
103
+ | **Minimum Accelerate** | 1.11.0+ | 1.12.0+ |
104
+ | **Minimum DeepSpeed** | N/A | 0.18.1+ |
105
+ | **Sequence Divisibility** | `cp_size * 2` | `sp_size` |
106
+ | **Zero Stage** | N/A | ZeRO Stage 1/2/3 |
107
+
108
+ **Ring Attention is better when:**
109
+ - You need to handle extremely long sequences (1M+ tokens)
110
+ - The model has limited attention heads (Ring Attention is not constrained by head count)
111
+ - You want flexibility in scaling to any sequence length
112
+ - Network topology is limited (Ring Attention works with simple P2P ring communication)
113
+
114
+ **Ulysses is better when:**
115
+ - You have high-bandwidth, low-latency interconnects (NVLink, InfiniBand)
116
+ - The model has many attention heads that can be split across GPUs
117
+ - You want lower communication volume
118
+ - You want faster training speed for moderate sequence lengths (up to ~500k tokens)
119
+
120
+ **Key Trade-offs:**
121
+ - **Communication Volume:** Ulysses has lower communication volume, making it more efficient with good interconnects. Ring Attention has higher communication volume but is more flexible with different network topologies.
122
+ - **Attention Head Constraints:** Ulysses is limited by the number of attention heads (requires `num_heads >= sp_size`). Ring Attention scales with sequence length regardless of model architecture.
123
+ - **Network Sensitivity:** Ulysses all-to-all communication is sensitive to network latency. Ring Attention uses P2P ring communication which is more tolerant of varying network conditions.
124
+
125
+ For a detailed comparison, see the [Ulysses and Ring Attention blog post](https://huggingface.co/blog/exploding-gradients/ulysses-ring-attention).
126
+
127
+ ### Ring Attention Implementation (FSDP2)
128
+
129
+ Ring Attention uses a ring-like communication pattern where each GPU processes a portion of the sequence and passes information to the next GPU in the ring.
130
+
131
+ #### Requirements and Limitations
132
+
133
+ 1. **Accelerate 1.11.0 or higher** is required for Ring Attention / Context Parallelism support
134
+ 2. **FSDP2 (PyTorch FSDP v2)** is required as the distributed training backend
135
+ 3. **SDPA attention** - Flash Attention is currently not supported
136
+ 4. **Sequence length divisibility** - sequences must be divisible by `cp_size * 2`. This is automatically handled using the `pad_to_multiple_of` parameter in the data collator.
137
+
138
+ #### Configuration
139
+
140
+ ##### Accelerate Configuration
141
+
142
+ Use one of the provided accelerate config files (e.g. [`context_parallel_2gpu.yaml`](https://github.com/huggingface/trl/blob/main/examples/accelerate_configs/context_parallel_2gpu.yaml) for 2 GPUs):
143
+
144
+ ```yaml
145
+ compute_environment: LOCAL_MACHINE
146
+ debug: false
147
+ distributed_type: FSDP
148
+ downcast_bf16: 'no'
149
+ enable_cpu_affinity: false
150
+ fsdp_config:
151
+ fsdp_activation_checkpointing: true # Enable activation checkpointing for memory efficiency
152
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
153
+ fsdp_cpu_ram_efficient_loading: true
154
+ fsdp_offload_params: false
155
+ fsdp_reshard_after_forward: true
156
+ fsdp_state_dict_type: FULL_STATE_DICT
157
+ fsdp_version: 2
158
+ machine_rank: 0
159
+ main_training_function: main
160
+ mixed_precision: bf16
161
+ num_machines: 1
162
+ num_processes: 2 # Number of GPUs
163
+ rdzv_backend: static
164
+ same_network: true
165
+ tpu_env: []
166
+ tpu_use_cluster: false
167
+ tpu_use_sudo: false
168
+ use_cpu: false
169
+ parallelism_config:
170
+ parallelism_config_dp_replicate_size: 1
171
+ parallelism_config_dp_shard_size: 1
172
+ parallelism_config_tp_size: 1
173
+ parallelism_config_cp_size: 2 # Context parallel size
174
+ ```
175
+
176
+ ##### Training Configuration
177
+
178
+ ```python
179
+ from trl import SFTConfig
180
+
181
+ training_args = SFTConfig(
182
+ # required
183
+ pad_to_multiple_of=4, # ensures divisibility by cp_size * 2
184
+ # to get the most out of CP
185
+ max_length=16384, # long sequence length
186
+ packing=True, # use packing to reduce padding
187
+ use_liger_kernel=True, # compatible with CP
188
+ gradient_checkpointing=False, # The activation_checkpointing in FSDP config and the gradient_checkpointing in training arg can't be set to True simultaneously
189
+ per_device_train_batch_size=1,
190
+ ...
191
+ )
192
+ ```
193
+
194
+ Then, launch your training script with the appropriate accelerate config file:
195
+
196
+ ```bash
197
+ accelerate launch --config_file context_parallel_2gpu.yaml train.py
198
+ ```
199
+
200
+ #### Best Practices
201
+
202
+ 1. **Use the `pad_to_multiple_of` parameter** - This is now the recommended way to ensure sequence length divisibility:
203
+ - For `cp_size=2`: use `pad_to_multiple_of=4` (since `cp_size * 2 = 4`)
204
+ - For `cp_size=4`: use `pad_to_multiple_of=8` (since `cp_size * 2 = 8`)
205
+ - The data collator automatically pads sequences to the required multiple, ensuring compatibility with CP
206
+
207
+ 2. **Use packing with padding** - The default BFD (Best Fit Decreasing) strategy works perfectly:
208
+ - Preserves sequence boundaries and maintains training quality
209
+ - Works seamlessly with both `padding_free=True` and standard padding modes
210
+
211
+ 3. **Combine with other memory optimizations** like Liger kernels, bfloat16, and gradient checkpointing
212
+
213
+ 4. **Start with smaller context parallel sizes** (2-4 GPUs) before scaling up
214
+
215
+ 5. **Monitor memory usage** across all GPUs to ensure balanced workload
216
+
217
+ #### Benchmarking Ring Attention
218
+
219
+ We benchmarked Ring Attention to highlight its potential improvements in training efficiency.
220
+ Our experiments were conducted using **1, 2, 4, and 8 H100 GPUs**, though the results can be extended to larger clusters with more nodes and GPUs.
221
+
222
+ For the setup, we fine-tuned an **8B model** ([Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B)) using the provided accelerate configuration
223
+ ([`context_parallel_2gpu.yaml`](https://github.com/huggingface/trl/blob/main/examples/accelerate_configs/context_parallel_2gpu.yaml)).
224
+ We adjusted `num_processes` and `parallelism_config_cp_size` based on the number of GPUs for each run.
225
+ Training was performed with the [sft.py](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) example script, combined with the parameters described above.
226
+
227
+ The results below summarize the **maximum trainable sequence length** and **iterations per second** for different numbers of GPUs. A value marked as `OOM` indicates that the configuration ran out of memory and could not be trained.
228
+
229
+ These results show that **Context Parallelism (CP) scales effectively with more GPUs**, enabling training on much longer sequences. With **8 GPUs**, context lengths of over **300k tokens** become feasible, unlocking training with extremely long contexts while maintaining reasonable throughput.
230
+
231
+ <div class="flex justify-center">
232
+ <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/context_parallelism_max_length_plot.png" alt="CP Max content length" width="45%"/>
233
+ <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/context_parallelism_s_it_plot.png" alt="CP seconds/iteration" width="45%"/>
234
+ </div>
235
+
236
+ > [!TIP]
237
+ > Accelerate also supports **N-Dimensional Parallelism (ND-parallelism)**, which enables you to combine different parallelization strategies to efficiently distribute model training across multiple GPUs.
238
+ >
239
+ > You can learn more and explore configuration examples in the [Accelerate ND-parallelism guide](https://github.com/huggingface/accelerate/blob/main/examples/torch_native_parallelism/README.md#nd-parallelism).
240
+
241
+ ### ALST/Ulysses Implementation (DeepSpeed)
242
+
243
+ ALST (Arctic Long Sequence Training) / Ulysses uses attention head parallelism to split long sequences across GPUs, working with DeepSpeed's ZeRO optimizer.
244
+
245
+ > [!NOTE]
246
+ > **Technical Note on Parallelism Configuration:**
247
+ > - **DeepSpeed ALST/Ulysses** uses `sp_size` with `sp_backend="deepspeed"` in both YAML and Python API
248
+ > - **Ring Attention (FSDP2)** uses `cp_size` with `cp_backend="torch"`
249
+ >
250
+ > The Trainer automatically accounts for both CP and SP when calculating effective batch sizes and training metrics.
251
+
252
+ #### Requirements and Limitations
253
+
254
+ 1. **DeepSpeed 0.18.1 or higher** is required
255
+ 2. **Accelerate 1.12.0 or higher** is required for ALST/Ulysses sequence parallelism support
256
+ 3. **Attention implementation** - Flash Attention 2 recommended (clean output), SDPA works as fallback
257
+ 4. **Sequence length divisibility** - sequences must be divisible by `sp_size`. Use `pad_to_multiple_of` in your training config.
258
+ 5. **Parallelism configuration** - You must ensure `dp_replicate_size × dp_shard_size × sp_size = num_processes`
259
+
260
+ #### Configuration
261
+
262
+ ##### Accelerate Configuration
263
+
264
+ Use the provided accelerate config file ([`alst_ulysses_4gpu.yaml`](https://github.com/huggingface/trl/blob/main/examples/accelerate_configs/alst_ulysses_4gpu.yaml)):
265
+
266
+ ```yaml
267
+ compute_environment: LOCAL_MACHINE
268
+ debug: false
269
+ deepspeed_config:
270
+ zero_stage: 3
271
+ seq_parallel_communication_data_type: bf16
272
+ distributed_type: DEEPSPEED
273
+ mixed_precision: bf16
274
+ num_machines: 1
275
+ num_processes: 4 # Number of GPUs
276
+ parallelism_config:
277
+ parallelism_config_dp_replicate_size: 1
278
+ parallelism_config_dp_shard_size: 2 # Enables 2D parallelism with SP
279
+ parallelism_config_tp_size: 1
280
+ parallelism_config_sp_size: 2 # Sequence parallel size
281
+ parallelism_config_sp_backend: deepspeed
282
+ parallelism_config_sp_seq_length_is_variable: true
283
+ parallelism_config_sp_attn_implementation: flash_attention_2
284
+ ```
285
+
286
+ ##### Training Configuration
287
+
288
+ ```python
289
+ from trl import SFTConfig
290
+
291
+ training_args = SFTConfig(
292
+ # required
293
+ pad_to_multiple_of=2, # Must equal sp_size
294
+ # to get the most out of SP
295
+ max_seq_length=4096,
296
+ packing=True,
297
+ attn_implementation="flash_attention_2",
298
+ per_device_train_batch_size=1,
299
+ ...
300
+ )
301
+ ```
302
+
303
+ Then, launch your training script with the appropriate accelerate config file:
304
+
305
+ ```bash
306
+ accelerate launch --config_file examples/accelerate_configs/alst_ulysses_4gpu.yaml train.py
307
+ ```
308
+
309
+ #### 2D Parallelism
310
+
311
+ The 4 GPU configuration above automatically enables 2D parallelism by combining Data Parallelism (DP) with Sequence Parallelism (SP). With `sp_size=2` and `dp_shard_size=2`, the 4 GPUs are organized as:
312
+ - 2 sequence parallel groups (processing the same data split across sequences)
313
+ - 2 data parallel groups (processing different data)
314
+
315
+ To adjust the parallelism for different GPU counts, modify the YAML config:
316
+
317
+ | GPUs | sp_size | dp_shard_size | Use Case | YAML Changes |
318
+ |------|---------|---------------|----------|--------------|
319
+ | 4 | 2 | 2 | Balanced - longer sequences + more data | `num_processes: 4`, `sp_size: 2`, `dp_shard_size: 2` |
320
+ | 4 | 4 | 1 | Pure SP for maximum sequence length | `num_processes: 4`, `sp_size: 4`, `dp_shard_size: 1` |
321
+ | 8 | 2 | 4 | Large-scale training | `num_processes: 8`, `sp_size: 2`, `dp_shard_size: 4` |
322
+
323
+ #### Best Practices
324
+
325
+ 1. **Use `pad_to_multiple_of`** to ensure sequences are divisible by `sp_size`
326
+ 2. **Use Flash Attention 2** for clean output (SDPA works but shows packing warnings)
327
+ 3. **Start with `sp_size=2`** before scaling to larger values
328
+ 4. **Use DeepSpeed ZeRO Stage 3** for large models
329
+ 5. **Combine with memory optimizations** like Liger kernels and gradient checkpointing
330
+ 6. **Validate parallelism config**: Ensure `dp_replicate_size × dp_shard_size × sp_size = num_processes`
331
+
332
+ #### Complete Example
333
+
334
+ Here's how to run ALST/Ulysses training using the built-in [`sft.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) script with 4 GPUs:
335
+
336
+ ```bash
337
+ accelerate launch --config_file examples/accelerate_configs/alst_ulysses_4gpu.yaml \
338
+ trl/scripts/sft.py \
339
+ --model_name_or_path Qwen/Qwen2-0.5B \
340
+ --dataset_name trl-lib/Capybara \
341
+ --learning_rate 2e-4 \
342
+ --max_steps 100 \
343
+ --max_seq_length 4096 \
344
+ --packing \
345
+ --packing_strategy wrapped \
346
+ --torch_dtype bfloat16 \
347
+ --attn_implementation flash_attention_2 \
348
+ --output_dir output-alst-4gpu \
349
+ --logging_steps 10 \
350
+ --report_to trackio
351
+ ```
352
+
353
+ This command automatically:
354
+ - Configures 2D parallelism (SP=2, DP=2) across 4 GPUs
355
+ - Uses Flash Attention 2 for clean training
356
+ - Enables packing with automatic padding to ensure sequence divisibility
357
+ - Leverages DeepSpeed ZeRO Stage 3 for memory efficiency
358
+
359
+ ### Further Reading
360
+
361
+ #### General Resources
362
+ - [Hugging Face Blog: Understanding Ulysses and Ring Attention](https://huggingface.co/blog/exploding-gradients/ulysses-ring-attention) - Detailed comparison of Ring Attention vs Ulysses approaches
363
+ - [Accelerate: Context Parallelism Guide](https://huggingface.co/docs/accelerate/concept_guides/context_parallelism)
364
+ - [Hugging Face Blog: Enabling Long-Context Training with Sequence Parallelism in Axolotl](https://huggingface.co/blog/axolotl-ai-co/long-context-with-sequence-parallelism-in-axolotl)
365
+
366
+ #### Ring Attention (FSDP2)
367
+ - [Ultrascale Playbook - Context Parallelism](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=context_parallelism)
368
+ - [Accelerate Example: 128k Sequence Length](https://github.com/huggingface/accelerate/blob/main/examples/torch_native_parallelism/README.md#context-parallelism-128k-sequence-length)
369
+ - [Accelerate ND-parallelism Guide](https://github.com/huggingface/accelerate/blob/main/examples/torch_native_parallelism/README.md#nd-parallelism)
370
+
371
+ #### ALST/Ulysses (DeepSpeed)
372
+ - [DeepSpeed Sequence Parallelism Documentation](https://www.deepspeed.ai/tutorials/ds-sequence/)
373
+ - [Snowflake Engineering Blog: Arctic Long Sequence Training (ALST)](https://www.snowflake.com/en/engineering-blog/arctic-long-sequence-training-multi-million-token-ai/)
374
+
375
+ ## Multi-Node Training
376
+
377
+ When a single machine doesn't have enough GPUs, TRL can scale training across multiple machines (nodes) using [🤗 Accelerate](https://huggingface.co/docs/accelerate/basic_tutorials/launch#multi-node-training).
378
+
379
+ ### Accelerate Configuration
380
+ Create an `accelerate` config file (e.g., `multi_node.yaml`) for multi-node training. Key fields:
381
+
382
+ ```yaml
383
+ compute_environment: LOCAL_MACHINE
384
+ distributed_type: MULTI_GPU
385
+ num_machines: 2
386
+ machine_rank: 0 # 0 for main node, 1 for second node
387
+ main_process_ip: 10.0.0.1 # IP of rank 0 node
388
+ main_process_port: 29500
389
+ num_processes: 16 # total processes across nodes
390
+ mixed_precision: bf16
391
+ use_cpu: false
392
+ same_network: true
393
+ ```
394
+
395
+ Adjust `num_processes` to match the total number of GPUs across all nodes.
396
+
397
+ > [!NOTE]
398
+ > Replace `10.0.0.1` with the actual IP address of the rank 0 (main) node.
399
+
400
+ ### Launching
401
+
402
+ #### Option 1: Manual Launch (Non-HPC)
403
+
404
+ Run the following on each node manually:
405
+ ```bash
406
+ # Node 0 (main node)
407
+ accelerate launch --config_file multi_node.yaml --machine_rank 0 train.py
408
+
409
+ # Node 1
410
+ accelerate launch --config_file multi_node.yaml --machine_rank 1 train.py
411
+ ```
412
+ #### Option 2: SLURM Launch (HPC Clusters)
413
+
414
+ For clusters using SLURM job scheduler, create a job script (e.g., `slurm_job.sh`):
415
+ ```bash
416
+ #!/bin/bash
417
+ #SBATCH --nodes=2
418
+ #SBATCH --gpus-per-node=8
419
+ #SBATCH --job-name=trl_multi
420
+
421
+ srun accelerate launch --config_file multi_node.yaml train.py
422
+ ```
423
+
424
+ Then submit the job:
425
+ ```bash
426
+ sbatch slurm_job.sh
427
+ ```
428
+
429
+ SLURM automatically distributes the training across all requested nodes and GPUs, and `srun` configures the necessary environment variables for multi-node communication.
430
+
431
+ **Key SLURM directives:**
432
+ - `--nodes=2`: Request 2 compute nodes
433
+ - `--gpus-per-node=8`: Allocate 8 GPUs per node (16 total)
434
+ - `--job-name`: Label for tracking in the job queue
435
+
436
+ You can combine multi-node with DeepSpeed by setting `distributed_type: DEEPSPEED` and adding a `deepspeed_config` block. See the [DeepSpeed integration guide](https://huggingface.co/docs/trl/en/deepspeed_integration).
437
+
438
+ ### Further Reading
439
+
440
+ - [Accelerate: Launching Scripts](https://huggingface.co/docs/accelerate/basic_tutorials/launch)
441
+ - [Accelerate: Example Zoo](https://huggingface.co/docs/accelerate/usage_guides/training_zoo)
442
+ - [SLURM Workload Manager Documentation](https://slurm.schedmd.com/) - For cluster job scheduling
443
+
444
+
445
+
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/dpo_trainer.md ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DPO Trainer
2
+
3
+ [![All_models-DPO-blue](https://img.shields.io/badge/All_models-DPO-blue)](https://huggingface.co/models?other=dpo,trl) [![smol_course-Chapter_2-yellow](https://img.shields.io/badge/smol_course-Chapter_2-yellow)](https://github.com/huggingface/smol-course/tree/main/2_preference_alignment)
4
+
5
+ ## Overview
6
+
7
+ TRL supports the Direct Preference Optimization (DPO) Trainer for training language models, as described in the paper [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290) by [Rafael Rafailov](https://huggingface.co/rmrafailov), Archit Sharma, Eric Mitchell, [Stefano Ermon](https://huggingface.co/ermonste), [Christopher D. Manning](https://huggingface.co/manning), [Chelsea Finn](https://huggingface.co/cbfinn).
8
+
9
+ The abstract from the paper is the following:
10
+
11
+ > While large-scale unsupervised language models (LMs) learn broad world knowledge and some reasoning skills, achieving precise control of their behavior is difficult due to the completely unsupervised nature of their training. Existing methods for gaining such steerability collect human labels of the relative quality of model generations and fine-tune the unsupervised LM to align with these preferences, often with reinforcement learning from human feedback (RLHF). However, RLHF is a complex and often unstable procedure, first fitting a reward model that reflects the human preferences, and then fine-tuning the large unsupervised LM using reinforcement learning to maximize this estimated reward without drifting too far from the original model. In this paper we introduce a new parameterization of the reward model in RLHF that enables extraction of the corresponding optimal policy in closed form, allowing us to solve the standard RLHF problem with only a simple classification loss. The resulting algorithm, which we call Direct Preference Optimization (DPO), is stable, performant, and computationally lightweight, eliminating the need for sampling from the LM during fine-tuning or performing significant hyperparameter tuning. Our experiments show that DPO can fine-tune LMs to align with human preferences as well as or better than existing methods. Notably, fine-tuning with DPO exceeds PPO-based RLHF in ability to control sentiment of generations, and matches or improves response quality in summarization and single-turn dialogue while being substantially simpler to implement and train.
12
+
13
+ This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and later refactored by [Quentin Gallouédec](https://huggingface.co/qgallouedec).
14
+
15
+ ## Quick start
16
+
17
+ This example demonstrates how to train a language model using the [`DPOTrainer`] from TRL. We train a [Qwen 3 0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) model on the [UltraFeedback dataset](https://huggingface.co/datasets/openbmb/UltraFeedback).
18
+
19
+ ```python
20
+ from trl import DPOTrainer
21
+ from datasets import load_dataset
22
+
23
+ trainer = DPOTrainer(
24
+ model="Qwen/Qwen3-0.6B",
25
+ train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"),
26
+ )
27
+ trainer.train()
28
+ ```
29
+
30
+ <iframe src="https://trl-lib-trackio.hf.space/?project=trl-documentation&metrics=train*&sidebar=hidden&runs=dpo_qwen3-0.6B_ultrafeedback" style="width: 100%; min-width: 300px; max-width: 800px;" height="830" frameBorder="0"></iframe>
31
+
32
+ ## Expected dataset type and format
33
+
34
+ DPO requires a [preference](dataset_formats#preference) dataset. The [`DPOTrainer`] is compatible with both [standard](dataset_formats#standard) and [conversational](dataset_formats#conversational) dataset formats. When provided with a conversational dataset, the trainer will automatically apply the chat template to the dataset.
35
+
36
+ ```python
37
+ # Standard format
38
+ ## Explicit prompt (recommended)
39
+ preference_example = {"prompt": "The sky is", "chosen": " blue.", "rejected": " green."}
40
+ # Implicit prompt
41
+ preference_example = {"chosen": "The sky is blue.", "rejected": "The sky is green."}
42
+
43
+ # Conversational format
44
+ ## Explicit prompt (recommended)
45
+ preference_example = {"prompt": [{"role": "user", "content": "What color is the sky?"}],
46
+ "chosen": [{"role": "assistant", "content": "It is blue."}],
47
+ "rejected": [{"role": "assistant", "content": "It is green."}]}
48
+ ## Implicit prompt
49
+ preference_example = {"chosen": [{"role": "user", "content": "What color is the sky?"},
50
+ {"role": "assistant", "content": "It is blue."}],
51
+ "rejected": [{"role": "user", "content": "What color is the sky?"},
52
+ {"role": "assistant", "content": "It is green."}]}
53
+ ```
54
+
55
+ If your dataset is not in one of these formats, you can preprocess it to convert it into the expected format. Here is an example with the [Vezora/Code-Preference-Pairs](https://huggingface.co/datasets/Vezora/Code-Preference-Pairs) dataset:
56
+
57
+ ```python
58
+ from datasets import load_dataset
59
+
60
+ dataset = load_dataset("Vezora/Code-Preference-Pairs")
61
+
62
+
63
+ def preprocess_function(example):
64
+ return {
65
+ "prompt": [{"role": "user", "content": example["input"]}],
66
+ "chosen": [{"role": "assistant", "content": example["accepted"]}],
67
+ "rejected": [{"role": "assistant", "content": example["rejected"]}],
68
+ }
69
+
70
+
71
+ dataset = dataset.map(preprocess_function, remove_columns=["instruction", "input", "accepted", "ID"])
72
+ print(next(iter(dataset["train"])))
73
+ ```
74
+
75
+ ```json
76
+ {
77
+ "prompt": [{"role": "user", "content": "Create a nested loop to print every combination of numbers [...]"}],
78
+ "chosen": [{"role": "assistant", "content": "Here is an example of a nested loop in Python [...]"}],
79
+ "rejected": [{"role": "assistant", "content": "Here is an example of a nested loop in Python [...]"}],
80
+ }
81
+ ```
82
+
83
+ ## Looking deeper into the DPO method
84
+
85
+ Direct Preference Optimization (DPO) is a training method designed to align a language model with preference data. Instead of supervised input–output pairs, the model is trained on pairs of completions to the same prompt, where one completion is preferred over the other. The objective directly optimizes the model to widen the margin between the log-likelihoods of preferred and dispreferred completions, relative to a reference model, without requiring an explicit reward model. In practice, this is typically achieved by suppressing the likelihood of dispreferred completions rather than by increasing the likelihood of preferred ones.
86
+
87
+ This section breaks down how DPO works in practice, covering the key steps: **preprocessing** and **loss computation**.
88
+
89
+ ### Preprocessing and tokenization
90
+
91
+ During training, each example is expected to contain a prompt along with a preferred (`chosen`) and a dispreferred (`rejected`) completion. For more details on the expected formats, see [Dataset formats](dataset_formats).
92
+ The [`DPOTrainer`] tokenizes each input using the model's tokenizer.
93
+
94
+ ### Computing the loss
95
+
96
+ ![dpo_figure](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/dpo_figure.png)
97
+
98
+ The loss used in DPO is defined as follows:
99
+ $$
100
+ \mathcal{L}_{\mathrm{DPO}}(\theta) = -\mathbb{E}_{(x,y^{+},y^{-})}\!\left[\log \sigma\!\left(\beta\Big(\log\frac{\pi_{\theta}(y^{+}\!\mid x)}{\pi_{\mathrm{ref}}(y^{+}\!\mid x)}-\log \frac{\pi_{\theta}(y^{-}\!\mid x)}{\pi_{\mathrm{ref}}(y^{-}\!\mid x)}\Big)\right)\right]
101
+ $$
102
+
103
+ where \\( x \\) is the prompt, \\( y^+ \\) is the preferred completion and \\( y^- \\) is the dispreferred completion. \\( \pi_{\theta} \\) is the policy model being trained, \\( \pi_{\mathrm{ref}} \\) is the reference model, \\( \sigma \\) is the sigmoid function, and \\( \beta > 0 \\) is a hyperparameter that controls the strength of the preference signal.
104
+
105
+ #### Loss Types
106
+
107
+ Several formulations of the objective have been proposed in the literature. Initially, the objective of DPO was defined as presented above.
108
+
109
+ | `loss_type=` | Description |
110
+ | --- | --- |
111
+ | `"sigmoid"` (default) | Given the preference data, we can fit a binary classifier according to the Bradley-Terry model and in fact the [DPO](https://huggingface.co/papers/2305.18290) authors propose the sigmoid loss on the normalized likelihood via the `logsigmoid` to fit a logistic regression. |
112
+ | `"hinge"` | The [RSO](https://huggingface.co/papers/2309.06657) authors propose to use a hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. In this case, the `beta` is the reciprocal of the margin. |
113
+ | `"ipo"` | The [IPO](https://huggingface.co/papers/2310.12036) authors argue the logit transform can overfit and propose the identity transform to optimize preferences directly; TRL exposes this as `loss_type="ipo"`. |
114
+ | `"exo_pair"` | The [EXO](https://huggingface.co/papers/2402.00856) authors propose reverse-KL preference optimization. `label_smoothing` must be strictly greater than `0.0`; a recommended value is `1e-3` (see Eq. 16 for the simplified pairwise variant). The full method uses `K>2` SFT completions and approaches PPO as `K` grows. |
115
+ | `"nca_pair"` | The [NCA](https://huggingface.co/papers/2402.05369) authors shows that NCA optimizes the absolute likelihood for each response rather than the relative likelihood. |
116
+ | `"robust"` | The [Robust DPO](https://huggingface.co/papers/2403.00409) authors propose an unbiased DPO loss under noisy preferences. Use `label_smoothing` in [`DPOConfig`] to model label-flip probability; valid values are in the range `[0.0, 0.5)`. |
117
+ | `"bco_pair"` | The [BCO](https://huggingface.co/papers/2404.04656) authors train a binary classifier whose logit serves as a reward so that the classifier maps {prompt, chosen completion} pairs to 1 and {prompt, rejected completion} pairs to 0. For unpaired data, we recommend the dedicated [`experimental.bco.BCOTrainer`]. |
118
+ | `"sppo_hard"` | The [SPPO](https://huggingface.co/papers/2405.00675) authors claim that SPPO is capable of solving the Nash equilibrium iteratively by pushing the chosen rewards to be as large as 1/2 and the rejected rewards to be as small as -1/2 and can alleviate data sparsity issues. The implementation approximates this algorithm by employing hard label probabilities, assigning 1 to the winner and 0 to the loser. |
119
+ | `"aot"` or `loss_type="aot_unpaired"` | The [AOT](https://huggingface.co/papers/2406.05882) authors propose Distributional Preference Alignment via Optimal Transport. `loss_type="aot"` is for paired data; `loss_type="aot_unpaired"` is for unpaired data. Both enforce stochastic dominance via sorted quantiles; larger per-GPU batch sizes help. |
120
+ | `"apo_zero"` or `loss_type="apo_down"` | The [APO](https://huggingface.co/papers/2408.06266) method introduces an anchored objective. `apo_zero` boosts winners and downweights losers (useful when the model underperforms the winners). `apo_down` downweights both, with stronger pressure on losers (useful when the model already outperforms winners). |
121
+ | `"discopop"` | The [DiscoPOP](https://huggingface.co/papers/2406.08414) paper uses LLMs to discover more efficient offline preference optimization losses. In the paper the proposed DiscoPOP loss (which is a log-ratio modulated loss) outperformed other optimization losses on different tasks (IMDb positive text generation, Reddit TLDR summarization, and Alpaca Eval 2.0). |
122
+ | `"sft"` | SFT (Supervised Fine-Tuning) loss is the negative log likelihood loss, used to train the model to generate preferred responses. |
123
+
124
+ ## Logged metrics
125
+
126
+ While training and evaluating we record the following reward metrics:
127
+
128
+ * `global_step`: The total number of optimizer steps taken so far.
129
+ * `epoch`: The current epoch number, based on dataset iteration.
130
+ * `num_tokens`: The total number of tokens processed so far.
131
+ * `loss`: The average cross-entropy loss computed over non-masked tokens in the current logging interval.
132
+ * `entropy`: The average entropy of the model's predicted token distribution over non-masked tokens.
133
+ * `mean_token_accuracy`: The proportion of non-masked tokens for which the model’s top-1 prediction matches the token from the chosen completion.
134
+ * `learning_rate`: The current learning rate, which may change dynamically if a scheduler is used.
135
+ * `grad_norm`: The L2 norm of the gradients, computed before gradient clipping.
136
+ * `logits/chosen`: The average logit values assigned by the model to the tokens in the chosen completion.
137
+ * `logits/rejected`: The average logit values assigned by the model to the tokens in the rejected completion.
138
+ * `logps/chosen`: The average log-probability assigned by the model to the tokens in the chosen completion.
139
+ * `logps/rejected`: The average log-probability assigned by the model to the tokens in the rejected completion.
140
+ * `rewards/chosen`: The average implicit reward computed for the chosen completion, computed as \\( \beta \log \frac{\pi_{\theta}(y^{+}\!\mid x)}{\pi_{\mathrm{ref}}(y^{+}\!\mid x)} \\).
141
+ * `rewards/rejected`: The average implicit reward computed for the rejected completion, computed as \\( \beta \log \frac{\pi_{\theta}(y^{-}\!\mid x)}{\pi_{\mathrm{ref}}(y^{-}\!\mid x)} \\).
142
+ * `rewards/margins`: The average implicit reward margin between the chosen and rejected completions.
143
+ * `rewards/accuracies`: The proportion of examples where the implicit reward for the chosen completion is higher than that for the rejected completion.
144
+
145
+ ## Customization
146
+
147
+ ### Compatibility and constraints
148
+
149
+ Some argument combinations are intentionally restricted in the current [`DPOTrainer`] implementation:
150
+
151
+ * `use_weighting=True` is not supported with `loss_type="aot"` or `loss_type="aot_unpaired"`.
152
+ * With `use_liger_kernel=True`:
153
+ * only a single `loss_type` is supported,
154
+ * `compute_metrics` is not supported,
155
+ * `precompute_ref_log_probs=True` is not supported.
156
+ * `sync_ref_model=True` is not supported when training with PEFT models that do not keep a standalone `ref_model`.
157
+ * `sync_ref_model=True` cannot be combined with `precompute_ref_log_probs=True`.
158
+ * `precompute_ref_log_probs=True` is not supported with `IterableDataset` (train or eval).
159
+
160
+ ### Multi-loss combinations
161
+
162
+ The DPO trainer supports combining multiple loss functions with different weights, enabling more sophisticated optimization strategies. This is particularly useful for implementing algorithms like MPO (Mixed Preference Optimization). MPO is a training approach that combines multiple optimization objectives, as described in the paper [Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization](https://huggingface.co/papers/2411.10442).
163
+
164
+ To combine multiple losses, specify the loss types and corresponding weights as lists:
165
+
166
+ ```python
167
+ # MPO: Combines DPO (sigmoid) for preference and BCO (bco_pair) for quality
168
+ training_args = DPOConfig(
169
+ loss_type=["sigmoid", "bco_pair", "sft"], # loss types to combine
170
+ loss_weights=[0.8, 0.2, 1.0] # corresponding weights, as used in the MPO paper
171
+ )
172
+ ```
173
+
174
+ ### Model initialization
175
+
176
+ You can directly pass the kwargs of the [`~transformers.AutoModelForCausalLM.from_pretrained()`] method to the [`DPOConfig`]. For example, if you want to load a model in a different precision, analogous to
177
+
178
+ ```python
179
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B", dtype=torch.bfloat16)
180
+ ```
181
+
182
+ you can do so by passing the `model_init_kwargs={"dtype": torch.bfloat16}` argument to the [`DPOConfig`].
183
+
184
+ ```python
185
+ from trl import DPOConfig
186
+
187
+ training_args = DPOConfig(
188
+ model_init_kwargs={"dtype": torch.bfloat16},
189
+ )
190
+ ```
191
+
192
+ Note that all keyword arguments of [`~transformers.AutoModelForCausalLM.from_pretrained()`] are supported.
193
+
194
+ ### Train adapters with PEFT
195
+
196
+ We support tight integration with 🤗 PEFT library, allowing any user to conveniently train adapters and share them on the Hub, rather than training the entire model.
197
+
198
+ ```python
199
+ from datasets import load_dataset
200
+ from trl import DPOTrainer
201
+ from peft import LoraConfig
202
+
203
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
204
+
205
+ trainer = DPOTrainer(
206
+ "Qwen/Qwen3-0.6B",
207
+ train_dataset=dataset,
208
+ peft_config=LoraConfig(),
209
+ )
210
+
211
+ trainer.train()
212
+ ```
213
+
214
+ You can also continue training your [`~peft.PeftModel`]. For that, first load a `PeftModel` outside [`DPOTrainer`] and pass it directly to the trainer without the `peft_config` argument being passed.
215
+
216
+ ```python
217
+ from datasets import load_dataset
218
+ from trl import DPOTrainer
219
+ from peft import AutoPeftModelForCausalLM
220
+
221
+ model = AutoPeftModelForCausalLM.from_pretrained("trl-lib/Qwen3-4B-LoRA", is_trainable=True)
222
+ dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
223
+
224
+ trainer = DPOTrainer(
225
+ model=model,
226
+ train_dataset=dataset,
227
+ )
228
+
229
+ trainer.train()
230
+ ```
231
+
232
+ > [!TIP]
233
+ > When training adapters, you typically use a higher learning rate (≈1e‑5) than full fine-tuning since only new parameters are being learned.
234
+ >
235
+ > ```python
236
+ > DPOConfig(learning_rate=1e-5, ...)
237
+ > ```
238
+
239
+ ### Train with Liger Kernel
240
+
241
+ Liger Kernel is a collection of Triton kernels for LLM training that boosts multi-GPU throughput by 20%, cuts memory use by 60% (enabling up to 4× longer context), and works seamlessly with tools like FlashAttention, PyTorch FSDP, and DeepSpeed. For more information, see [Liger Kernel Integration](liger_kernel_integration).
242
+
243
+ ### Rapid Experimentation for DPO
244
+
245
+ RapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple DPO configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration).
246
+
247
+ ### Train with Unsloth
248
+
249
+ Unsloth is an open‑source framework for fine‑tuning and reinforcement learning that trains LLMs (like Llama, Mistral, Gemma, DeepSeek, and more) up to 2× faster with up to 70% less VRAM, while providing a streamlined, Hugging Face–compatible workflow for training, evaluation, and deployment. For more information, see [Unsloth Integration](unsloth_integration).
250
+
251
+ ## Tool Calling with DPO
252
+
253
+ The [`DPOTrainer`] fully supports fine-tuning models with _tool calling_ capabilities. In this case, each dataset example should include:
254
+
255
+ * The conversation messages (prompt, chosen and rejected), including any tool calls (`tool_calls`) and tool responses (`tool` role messages)
256
+ * The list of available tools in the `tools` column, typically provided as JSON schemas
257
+
258
+ For details on the expected dataset structure, see the [Dataset Format — Tool Calling](dataset_formats#tool-calling) section.
259
+
260
+ ## Training Vision Language Models
261
+
262
+ [`DPOTrainer`] fully supports training Vision-Language Models (VLMs). To train a VLM, provide a dataset with either an `image` column (single image per sample) or an `images` column (list of images per sample). For more information on the expected dataset structure, see the [Dataset Format — Vision Dataset](dataset_formats#vision-dataset) section.
263
+ An example of such a dataset is the [RLAIF-V Dataset](https://huggingface.co/datasets/HuggingFaceH4/rlaif-v_formatted) dataset.
264
+
265
+ ```python
266
+ from trl import DPOConfig, DPOTrainer
267
+ from datasets import load_dataset
268
+
269
+ trainer = DPOTrainer(
270
+ model="Qwen/Qwen2.5-VL-3B-Instruct",
271
+ args=DPOConfig(max_length=None),
272
+ train_dataset=load_dataset("HuggingFaceH4/rlaif-v_formatted", split="train"),
273
+ )
274
+ trainer.train()
275
+ ```
276
+
277
+ > [!TIP]
278
+ > For VLMs, truncating may remove image tokens, leading to errors during training. To avoid this, set `max_length=None` in the [`DPOConfig`]. This allows the model to process the full sequence length without truncating image tokens.
279
+ >
280
+ > ```python
281
+ > DPOConfig(max_length=None, ...)
282
+ > ```
283
+ >
284
+ > Only use `max_length` when you've verified that truncation won't remove image tokens for the entire dataset.
285
+
286
+ ## DPOTrainer
287
+
288
+ [[autodoc]] DPOTrainer
289
+ - train
290
+ - save_model
291
+ - push_to_hub
292
+
293
+ ## DPOConfig
294
+
295
+ [[autodoc]] DPOConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/example_overview.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Examples
2
+
3
+ This directory contains a collection of examples that demonstrate how to use the TRL library for various applications. We provide both **scripts** for advanced use cases and **notebooks** for an easy start and interactive experimentation.
4
+
5
+ The notebooks are self-contained and can run on **free Colab**, while the scripts can run on **single GPU, multi-GPU, or DeepSpeed** setups.
6
+
7
+ **Getting Started**
8
+
9
+ Install TRL and additional dependencies as follows:
10
+
11
+ ```bash
12
+ pip install --upgrade trl[quantization]
13
+ ```
14
+
15
+ Check for additional optional dependencies [here](https://github.com/huggingface/trl/blob/main/pyproject.toml).
16
+
17
+ For scripts, you will also need an 🤗 Accelerate config (recommended for multi-gpu settings):
18
+
19
+ ```bash
20
+ accelerate config # will prompt you to define the training configuration
21
+ ```
22
+
23
+ This allows you to run scripts with `accelerate launch` in single or multi-GPU settings.
24
+
25
+ ## Notebooks
26
+
27
+ These notebooks are easier to run and are designed for quick experimentation with TRL. The list of notebooks can be found in the [`trl/examples/notebooks/`](https://github.com/huggingface/trl/tree/main/examples/notebooks/) directory.
28
+
29
+
30
+ | Notebook | Description | Open in Colab |
31
+ |----------|-------------|---------------|
32
+ | [`grpo_trl_lora_qlora.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_trl_lora_qlora.ipynb) | GRPO using QLoRA on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_trl_lora_qlora.ipynb) |
33
+ | [`grpo_agent.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_agent.ipynb) | GRPO for agent training | Not available due to OOM with Colab GPUs |
34
+ | [`grpo_rnj_1_instruct.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_rnj_1_instruct.ipynb) | GRPO rnj-1-instruct with QLoRA using TRL on Colab to add reasoning capabilities | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_rnj_1_instruct.ipynb) |
35
+ | [`sft_ministral3_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_ministral3_vl.ipynb) | Supervised Fine-Tuning (SFT) Ministral 3 with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_ministral3_vl.ipynb) |
36
+ | [`grpo_ministral3_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_ministral3_vl.ipynb) | GRPO Ministral 3 with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_ministral3_vl.ipynb) |
37
+ | [`sft_nemotron_3.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_nemotron_3.ipynb) | SFT with LoRA on NVIDIA Nemotron 3 models | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_nemotron_3.ipynb) |
38
+ | [`sft_trl_lora_qlora.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_trl_lora_qlora.ipynb) | Supervised Fine-Tuning (SFT) using QLoRA on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_trl_lora_qlora.ipynb) |
39
+ | [`sft_qwen_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_qwen_vl.ipynb) | Supervised Fine-Tuning (SFT) Qwen3-VL with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_qwen_vl.ipynb) |
40
+ | [`sft_tool_calling.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/sft_tool_calling.ipynb) | Teaching tool calling to a model without native tool-calling support using SFT with QLoRA | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/sft_tool_calling.ipynb) |
41
+ | [`grpo_qwen3_vl.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_qwen3_vl.ipynb) | GRPO Qwen3-VL with QLoRA using TRL on free Colab | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_qwen3_vl.ipynb) |
42
+
43
+ ### OpenEnv Notebooks
44
+
45
+ These notebooks demonstrate how to train models with [OpenEnv](openenv) environments using [`GRPOTrainer`]'s `environment_factory`. The BrowserGym notebook uses the lower-level `rollout_func` API instead. See the [OpenEnv Integration](openenv) guide for more details.
46
+
47
+ | Notebook | Description | Open in Colab |
48
+ |----------|-------------|---------------|
49
+ | [`openenv_wordle_grpo.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/openenv_wordle_grpo.ipynb) | GRPO to play Wordle on an OpenEnv environment | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/openenv_wordle_grpo.ipynb) |
50
+ | [`openenv_sudoku_grpo.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/openenv_sudoku_grpo.ipynb) | GRPO to play Sudoku on an OpenEnv environment | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/openenv_sudoku_grpo.ipynb) |
51
+ | [`grpo_functiongemma_browsergym_openenv.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/grpo_functiongemma_browsergym_openenv.ipynb) | GRPO on FunctionGemma in the BrowserGym environment | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/notebooks/grpo_functiongemma_browsergym_openenv.ipynb) |
52
+
53
+ ## Scripts
54
+
55
+ Scripts are maintained in the [`trl/scripts`](https://github.com/huggingface/trl/blob/main/trl/scripts) and [`examples/scripts`](https://github.com/huggingface/trl/blob/main/examples/scripts) directories. They show how to use different trainers such as [`SFTTrainer`], [`PPOTrainer`], [`DPOTrainer`], [`GRPOTrainer`], and more.
56
+
57
+ | File | Description |
58
+ | --- | --- |
59
+ | [`examples/scripts/bco.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/bco.py) | This script shows how to use the [`experimental.kto.KTOTrainer`] with the BCO loss to fine-tune a model to increase instruction-following, truthfulness, honesty, and helpfulness using the [openbmb/UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) dataset. |
60
+ | [`examples/scripts/cpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/cpo.py) | This script shows how to use the [`experimental.cpo.CPOTrainer`] to fine-tune a model to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. |
61
+ | [`trl/scripts/dpo.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/dpo.py) | This script shows how to use the [`DPOTrainer`] to fine-tune a model. |
62
+ | [`examples/scripts/dpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/dpo_vlm.py) | This script shows how to use the [`DPOTrainer`] to fine-tune a Vision Language Model to reduce hallucinations using the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset) dataset. |
63
+ | [`examples/scripts/evals/judge_tldr.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/evals/judge_tldr.py) | This script shows how to use [`experimental.judges.HfPairwiseJudge`] or [`experimental.judges.OpenAIPairwiseJudge`] to judge model generations. |
64
+ | [`examples/scripts/gkd.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gkd.py) | This script shows how to use the [`experimental.gkd.GKDTrainer`] to fine-tune a model. |
65
+ | [`trl/scripts/grpo.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/grpo.py) | This script shows how to use the [`GRPOTrainer`] to fine-tune a model. |
66
+ | [`trl/scripts/grpo_agent.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/grpo_agent.py) | This script shows how to use the [`GRPOTrainer`] to fine-tune a model to enable agentic usage. |
67
+ | [`examples/scripts/grpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_vlm.py) | This script shows how to use the [`GRPOTrainer`] to fine-tune a multimodal model for reasoning using the [lmms-lab/multimodal-open-r1-8k-verified](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified) dataset. |
68
+ | [`examples/scripts/gspo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gspo.py) | This script shows how to use GSPO via the [`GRPOTrainer`] to fine-tune model for reasoning using the [AI-MO/NuminaMath-TIR](https://huggingface.co/datasets/AI-MO/NuminaMath-TIR) dataset. |
69
+ | [`examples/scripts/gspo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/gspo_vlm.py) | This script shows how to use GSPO via the [`GRPOTrainer`] to fine-tune a multimodal model for reasoning using the [lmms-lab/multimodal-open-r1-8k-verified](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified) dataset. |
70
+ | [`examples/scripts/kto.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/kto.py) | This script shows how to use the [`experimental.kto.KTOTrainer`] to fine-tune a model. |
71
+ | [`examples/scripts/mpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/mpo_vlm.py) | This script shows how to use MPO via the [`DPOTrainer`] to align a model based on preferences using the [HuggingFaceH4/rlaif-v_formatted](https://huggingface.co/datasets/HuggingFaceH4/rlaif-v_formatted) dataset and a set of loss weights with weights. |
72
+ | [`examples/scripts/nash_md.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/nash_md.py) | This script shows how to use the [`experimental.nash_md.NashMDTrainer`] to fine-tune a model. |
73
+ | [`examples/scripts/nemo_gym/train_multi_environment.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/nemo_gym/train_multi_environment.py) | This script shows how to use the [`GRPOTrainer`] to train language models in NVIDIA NeMo-Gym environments. Supports multi-turn and tool calling environments, and multi-environment training. See the [NeMo-Gym Integration](nemo_gym) guide for setup and usage. |
74
+ | [`examples/scripts/online_dpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/online_dpo.py) | This script shows how to use the [`experimental.online_dpo.OnlineDPOTrainer`] to fine-tune a model. |
75
+ | [`examples/scripts/online_dpo_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/online_dpo_vlm.py) | This script shows how to use the [`experimental.online_dpo.OnlineDPOTrainer`] to fine-tune a a Vision Language Model. |
76
+ | [`examples/scripts/orpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/orpo.py) | This script shows how to use the [`experimental.orpo.ORPOTrainer`] to fine-tune a model to increase helpfulness and harmlessness using the [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf) dataset. |
77
+ | [`examples/scripts/ppo/ppo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo/ppo.py) | This script shows how to use the [`experimental.ppo.PPOTrainer`] to fine-tune a model to improve its ability to continue text with positive sentiment or physically descriptive language. |
78
+ | [`examples/scripts/ppo/ppo_tldr.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo/ppo_tldr.py) | This script shows how to use the [`experimental.ppo.PPOTrainer`] to fine-tune a model to improve its ability to generate TL;DR summaries. |
79
+ | [`examples/scripts/prm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/prm.py) | This script shows how to use the [`experimental.prm.PRMTrainer`] to fine-tune a Process-supervised Reward Model (PRM). |
80
+ | [`examples/scripts/reward_modeling.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/reward_modeling.py) | This script shows how to use the [`RewardTrainer`] to train an Outcome Reward Model (ORM) on your own dataset. |
81
+ | [`examples/scripts/rloo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/rloo.py) | This script shows how to use the [`RLOOTrainer`] to fine-tune a model to improve its ability to solve math questions. |
82
+ | [`trl/scripts/sft.py`](https://github.com/huggingface/trl/blob/main/trl/scripts/sft.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a model. |
83
+ | [`examples/scripts/sft_gemma3.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_gemma3.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Gemma 3 model. |
84
+ | [`examples/scripts/sft_nemotron_3.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_nemotron_3.py) | This script shows how to use the [`SFTTrainer`] to fine-tune an NVIDIA Nemotron 3 model. |
85
+ | [`examples/scripts/sft_tiny_aya_tool_calling.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_tiny_aya_tool_calling.py) | This script shows how to use the [`SFTTrainer`] to teach tool calling to a model without native tool-calling support using the [bebechien/SimpleToolCalling](https://huggingface.co/datasets/bebechien/SimpleToolCalling) dataset. |
86
+ | [`examples/scripts/sft_video_llm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_video_llm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Video Language Model. |
87
+ | [`examples/scripts/sft_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Vision Language Model in a chat setting. The script has only been tested with [LLaVA 1.5](https://huggingface.co/llava-hf/llava-1.5-7b-hf), [LLaVA 1.6](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf), and [Llama-3.2-11B-Vision-Instruct](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision-Instruct) models, so users may see unexpected behaviour in other model architectures. |
88
+ | [`examples/scripts/sft_vlm_gemma3.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm_gemma3.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a Gemma 3 model on vision to text tasks. |
89
+ | [`examples/scripts/sft_vlm_smol_vlm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/sft_vlm_smol_vlm.py) | This script shows how to use the [`SFTTrainer`] to fine-tune a SmolVLM model. |
90
+ | [`examples/scripts/xpo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/xpo.py) | This script shows how to use the [`experimental.xpo.XPOTrainer`] to fine-tune a model. |
91
+
92
+ ### OpenEnv Scripts
93
+
94
+ These scripts demonstrate how to train models with [OpenEnv](openenv) environments using [`GRPOTrainer`]'s `environment_factory`. See the [OpenEnv Integration](openenv) guide for more details.
95
+
96
+ | File | Description |
97
+ | --- | --- |
98
+ | [`examples/scripts/openenv/echo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/echo.py) | GRPO training with the Echo environment (minimal example). |
99
+ | [`examples/scripts/openenv/wordle.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/wordle.py) | GRPO training with the Wordle (TextArena) environment. |
100
+ | [`examples/scripts/openenv/catch.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/catch.py) | GRPO training with the Catch (OpenSpiel) environment. |
101
+ | [`examples/scripts/openenv/sudoku.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/sudoku.py) | GRPO training with the Sudoku environment. |
102
+ | [`examples/scripts/openenv/multi_env.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/multi_env.py) | Multi-environment GRPO training: Wordle + Catch in the same training run. |
103
+ | [`examples/scripts/openenv/browsergym.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/browsergym.py) | GRPO training with the BrowserGym environment for VLMs. |
104
+ | [`examples/scripts/openenv/browsergym_llm.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/browsergym_llm.py) | GRPO training with the BrowserGym environment for LLMs. |
105
+ | [`examples/scripts/openenv/carla.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/openenv/carla.py) | GRPO training with the CARLA environment for autonomous driving. |
106
+
107
+ ## Distributed Training (for scripts)
108
+
109
+ You can run scripts on multiple GPUs with 🤗 Accelerate:
110
+
111
+ ```shell
112
+ accelerate launch --config_file=examples/accelerate_configs/multi_gpu.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script
113
+ ```
114
+
115
+ For DeepSpeed ZeRO-{1,2,3}:
116
+
117
+ ```shell
118
+ accelerate launch --config_file=examples/accelerate_configs/deepspeed_zero{1,2,3}.yaml --num_processes {NUM_GPUS} path_to_script.py --all_arguments_of_the_script
119
+ ```
120
+
121
+ Adjust `NUM_GPUS` and `--all_arguments_of_the_script` as needed.
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/experimental_overview.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experimental
2
+
3
+ This directory contains a minimal, clearly separated space for fast iteration on new ideas.
4
+
5
+ > [!WARNING]
6
+ > **Stability contract:** Anything under `trl.experimental` may change or be removed in *any* release (including patch versions) without prior deprecation. Do not rely on these APIs for production workloads.
7
+
8
+ ## Promotion Path (Simple)
9
+
10
+ 1. **Prototype outside the main repo:** Start development in your own fork or a separate repository to iterate quickly.
11
+ 2. **Experimental inclusion:** Once it’s ready for early users, move the idea into `trl.experimental.<feature>`.
12
+ 3. **Improve:** Add tests, a short doc/example, and demonstrate the usage.
13
+ 4. **Promote:** Once the API proves stable and there is clear interest or adoption from the community, move it into `trl.<feature>` (stable module).
14
+
15
+ ## FAQ
16
+
17
+ **Why not just use branches?**
18
+ Because branches are not shipped to users; experimental code inside the package lets early adopters try things and give feedback.
19
+
20
+ **Can these APIs change or vanish without warning?**
21
+ Yes. Anything inside `trl.experimental` can change or disappear in *any* release.
22
+
23
+ **Should I use this in production?**
24
+ Only if you are fine with updating your code quickly when things change.
25
+
26
+ **Will maintainers promptly fix issues in `trl.experimental`?**
27
+ Not necessarily. The experimental module is a playground for new ideas, and maintainers may not prioritize bug fixes or feature requests there. Issues may remain unresolved until (or unless) the feature graduates to the stable API.
28
+
29
+ **How to silence the runtime notice?**
30
+
31
+ Use: `export TRL_EXPERIMENTAL_SILENCE=1`.
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gfpo.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GFPO
2
+
3
+ This feature implements the GFPO algorithm to enforce concise reasoning in the model's output generation, as proposed in the paper [Sample More to Think Less: Group Filtered Policy Optimization for Concise Reasoning](https://huggingface.co/papers/2508.09726).
4
+
5
+ ## Usage
6
+
7
+ To activate GFPO in [`GFPOTrainer`]:
8
+
9
+ - set `num_remains_in_group` in [`GFPOConfig`]
10
+ - define a group filter function and set it to `group_filter_func` in [`GFPOTrainer`]. `group_filter_func` will score the `num_generations` completions and The GFPOTrainer filters groups according to their scores to get top `num_remains_in_group` completions as a new group. Model will be trained on the filtered group.
11
+
12
+ ```python
13
+ # train_gfpo.py
14
+ from trl.experimental.gfpo import GFPOConfig, GFPOTrainer
15
+
16
+ # dummy group filter to scores the completions based on its indice in group
17
+ class GroupFilter:
18
+ def __call__(self, group_completions, group_rewards, **kwargs):
19
+ group_scores = []
20
+ for completions, rewards in zip(group_completions, group_rewards):
21
+ scores = [float(i) for i in range(len(completions))]
22
+ group_scores.append(scores)
23
+ return group_scores
24
+
25
+ training_args = GFPOConfig(
26
+ output_dir="Qwen3-0.6B-GFPO",
27
+ per_device_train_batch_size=4,
28
+ num_remains_in_group=2,
29
+ bf16=True,
30
+ )
31
+ trainer = GFPOTrainer(
32
+ model="Qwen/Qwen3-0.6B",
33
+ reward_funcs=...,
34
+ train_dataset=...,
35
+ args=training_args,
36
+ group_filter_func=GroupFilter(),
37
+ )
38
+ trainer.train()
39
+ ```
40
+
41
+ ## GFPOTrainer
42
+
43
+ [[autodoc]] experimental.gfpo.GFPOTrainer
44
+ - train
45
+ - save_model
46
+ - push_to_hub
47
+
48
+ ## GFPOConfig
49
+
50
+ [[autodoc]] experimental.gfpo.GFPOConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gkd_trainer.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generalized Knowledge Distillation Trainer
2
+
3
+ [![model badge](https://img.shields.io/badge/All_models-GKD-blue)](https://huggingface.co/models?other=gkd,trl)
4
+
5
+ ## Overview
6
+
7
+ Generalized Knowledge Distillation (GKD) was proposed in [On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes](https://huggingface.co/papers/2306.13649) by Rishabh Agarwal, Nino Vieillard, Yongchao Zhou, Piotr Stanczyk, Sabela Ramos, Matthieu Geist, and Olivier Bachem.
8
+
9
+ The abstract from the paper is the following:
10
+
11
+ > Knowledge distillation (KD) is widely used for compressing a teacher model to reduce its inference cost and memory footprint, by training a smaller student model. However, current KD methods for auto-regressive sequence models suffer from distribution mismatch between output sequences seen during training and those generated by the student during inference. To address this issue, we introduce Generalized Knowledge Distillation (GKD). Instead of solely relying on a fixed set of output sequences, GKD trains the student on its self-generated output sequences by leveraging feedback from the teacher on such sequences. Unlike supervised KD approaches, GKD also offers the flexibility to employ alternative loss functions between the student and teacher, which can be useful when the student lacks the expressivity to mimic the teacher's distribution. Furthermore, GKD facilitates the seamless integration of distillation with RL fine-tuning (RLHF). We demonstrate the efficacy of GKD for distilling auto-regressive language models on summarization, translation, and arithmetic reasoning tasks, and task-agnostic distillation for instruction-tuning.
12
+
13
+ The key aspects of GKD are:
14
+
15
+ 1. It addresses the train-inference distribution mismatch in auto-regressive sequence models by training the student model on its self-generated output sequences.
16
+ 2. GKD allows flexibility in choosing different divergence measures between student and teacher models via the generalized Jensen-Shannon Divergence (JSD), which can be useful when the student lacks the capacity to fully mimic the teacher.
17
+
18
+ This post-training method was contributed by [Kashif Rasul](https://huggingface.co/kashif) and [Lewis Tunstall](https://huggingface.co/lewtun).
19
+
20
+ ## Usage tips
21
+
22
+ The [`experimental.gkd.GKDTrainer`] is a wrapper around the [`SFTTrainer`] class that takes in a teacher model argument. It needs three parameters to be set via the [`experimental.gkd.GKDConfig`] namely:
23
+
24
+ * `lmbda`: controls the student data fraction, i.e., the proportion of on-policy student-generated outputs. When `lmbda=0.0`, the loss reduces to supervised JSD where the student is trained with the token-level probabilities of the teacher. When `lmbda=1.0`, the loss reduces to on-policy JSD, where the student generates output sequences and token-specific feedback on these sequences from the teacher. For values in between [0, 1] it is random between the two based on the `lmbda` value for each batch.
25
+ * `seq_kd`: controls whether to perform Sequence-Level KD (can be viewed as supervised FT on teacher-generated out). When `seq_kd=True` and `lmbda=0.0`, the loss reduces to supervised JSD, where the teacher generates output sequences and the student receives token-specific feedback on these sequences from the teacher.
26
+ * `beta`: controls the interpolation in the generalized Jensen-Shannon Divergence. When `beta=0.0` the loss approximates forward KL divergence, while for `beta=1.0` the loss approximates reverse KL divergence. For values in between [0, 1] it interpolates between the two.
27
+
28
+ The authors find that on-policy data (high `lmbda`) performs better and the optimal `beta` varied depending on the task and evaluation method.
29
+
30
+ > [!WARNING]
31
+ > Make sure that `attn_implementation="kernels-community/flash-attn2"` when training [Gemma models](https://huggingface.co/models?other=gemma2). Otherwise you will encounter NaNs in the logits due to the [soft capping technique](https://huggingface.co/blog/gemma2#soft-capping-and-attention-implementations) adopted by this architecture.
32
+
33
+ The basic API is as follows:
34
+
35
+ ```python
36
+ from datasets import Dataset
37
+ from transformers import AutoModelForCausalLM, AutoTokenizer
38
+ from trl.experimental.gkd import GKDConfig, GKDTrainer
39
+
40
+ NUM_DUMMY_SAMPLES = 100
41
+
42
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
43
+ # The model to optimise
44
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
45
+ # The teacher model to calculate the KL divergence against
46
+ teacher_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-1.5B-Instruct")
47
+
48
+ train_dataset = Dataset.from_dict(
49
+ {
50
+ "messages": [
51
+ [
52
+ {"role": "user", "content": "Hi, how are you?"},
53
+ {"role": "assistant", "content": "I'm great thanks"},
54
+ ]
55
+ ]
56
+ * NUM_DUMMY_SAMPLES
57
+ }
58
+ )
59
+ eval_dataset = Dataset.from_dict(
60
+ {
61
+ "messages": [
62
+ [
63
+ {"role": "user", "content": "What colour is the sky?"},
64
+ {"role": "assistant", "content": "The sky is blue"},
65
+ ]
66
+ ]
67
+ * NUM_DUMMY_SAMPLES
68
+ }
69
+ )
70
+
71
+ training_args = GKDConfig(output_dir="gkd-model", per_device_train_batch_size=1)
72
+ trainer = GKDTrainer(
73
+ model=model,
74
+ teacher_model=teacher_model,
75
+ args=training_args,
76
+ processing_class=tokenizer,
77
+ train_dataset=train_dataset,
78
+ eval_dataset=eval_dataset,
79
+ )
80
+ trainer.train()
81
+ ```
82
+
83
+ ### Expected dataset type
84
+
85
+ The dataset should be formatted as a list of "messages" where each message is a list of dictionaries with the following keys:
86
+
87
+ * `role`: either `system`, `assistant` or `user`
88
+ * `content`: the message content
89
+
90
+ ## GKDTrainer
91
+
92
+ [[autodoc]] experimental.gkd.GKDTrainer
93
+ - train
94
+ - save_model
95
+ - push_to_hub
96
+
97
+ ## GKDConfig
98
+
99
+ [[autodoc]] experimental.gkd.GKDConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gold_trainer.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # General Online Logit Distillation (GOLD) Trainer
2
+
3
+ [![All_models-GOLD-blue](https://img.shields.io/badge/All_models-GOLD-blue)](https://huggingface.co/models?other=sft,gold)
4
+
5
+ ## Overview
6
+
7
+ General Online Logit Distillation (GOLD) is an extension of Universal Logit Distillation (ULD) that supports
8
+ student/teacher pairs with different tokenizers. It aligns the textual spans produced by both tokenizers and merges the
9
+ associated logits so no completion tokens are dropped. This enables cross-tokenizer knowledge distillation, including
10
+ mixed model families (for example, LLaMA students with Qwen teachers).
11
+
12
+ Key capabilities:
13
+
14
+ 1. **Cross-tokenizer alignment** – GOLD incrementally decodes the student and teacher tokens, groups passages with the same visible text, and merges probabilities inside each group. This guarantees loss terms are computed over the full completion even when token boundaries differ.
15
+ 2. **Hybrid ULD loss** – when `uld_use_hybrid_loss` is enabled, GOLD compares exact vocabulary matches directly and falls back to the original sorted-probability ULD loss for unmatched tokens. This improves stability for students whose vocabularies only partially overlap with the teacher.
16
+ 3. **Seamless integration with GKD** – GOLD inherits the on-policy vs. off-policy scheduling from the [`experimental.gkd.GKDTrainer`], so you can combine sequence-level KD, generalized JSD, and cross-tokenizer distillation in a single training run.
17
+
18
+ > [!NOTE]
19
+ > GOLD is currently part of the `trl.experimental` namespace. APIs may change without notice while the feature is iterated on.
20
+
21
+ ## Usage tips
22
+
23
+ The [`GOLDTrainer`] subclasses [`SFTTrainer`] and accepts the same datasets as other TRL trainers (lists of ChatML style
24
+ messages). Important configuration flags on [`GOLDConfig`] include:
25
+
26
+ * `use_uld_loss` – toggles Universal Logit Distillation. Set this to `True` for cross-tokenizer setups.
27
+ * `teacher_tokenizer_name_or_path` – required when `use_uld_loss=True`; GOLD uses the teacher tokenizer to align tokens.
28
+ * `uld_use_hybrid_loss`, `uld_hybrid_matched_weight`, `uld_hybrid_unmatched_weight` – enables and weights the hybrid
29
+ matched/unmatched loss.
30
+ * `beta`, `lmbda`, `seq_kd` – inherited from [`experimental.gkd.GKDConfig`], controlling the generalized JSD interpolation and on-policy
31
+ sampling ratio.
32
+ * `num_generations`, `generation_batch_size` – control buffered rollout generation across gradient accumulation windows.
33
+ `generation_batch_size` is the number of unique prompts per worker per optimizer step.
34
+ * `model_revision` – controls which student model revision GOLD loads for training and generation.
35
+
36
+ A minimal end-to-end example:
37
+
38
+ ```python
39
+ from datasets import load_dataset
40
+ from trl.experimental.gold import GOLDConfig, GOLDTrainer
41
+
42
+ train_dataset = load_dataset(
43
+ "HuggingFaceTB/OpenR1-Math-220k-default-verified",
44
+ "all",
45
+ split="train[:1024]",
46
+ )
47
+
48
+ trainer = GOLDTrainer(
49
+ model="meta-llama/Llama-3.2-1B-Instruct",
50
+ teacher_model="Qwen/Qwen2.5-0.5B-Instruct",
51
+ args=GOLDConfig(output_dir="gold-model", use_uld_loss=True, teacher_tokenizer_name_or_path="Qwen/Qwen2.5-0.5B-Instruct"),
52
+ train_dataset=train_dataset,
53
+ )
54
+ trainer.train()
55
+ ```
56
+
57
+ For quick-start workflows you can rely on string identifiers as shown above—the trainer will load the model and tokenizer for you. Explicitly instantiating `AutoModelForCausalLM`, `AutoTokenizer`, or populating `GOLDConfig` is recommended only for advanced use cases where you need fine-grained control over initialization.
58
+
59
+ A more explicit setup might look like this when you need to customise model loading, tokenizer settings, or training arguments:
60
+
61
+ ```python
62
+ from datasets import load_dataset
63
+ from trl import GOLDConfig, GOLDTrainer
64
+ from transformers import AutoModelForCausalLM, AutoTokenizer
65
+
66
+ student_name = "meta-llama/Llama-3.2-1B-Instruct"
67
+ teacher_name = "Qwen/Qwen2.5-0.5B-Instruct"
68
+
69
+ tokenizer = AutoTokenizer.from_pretrained(student_name)
70
+ if tokenizer.pad_token is None:
71
+ tokenizer.pad_token = tokenizer.eos_token
72
+
73
+ model = AutoModelForCausalLM.from_pretrained(student_name)
74
+ teacher_model = AutoModelForCausalLM.from_pretrained(teacher_name)
75
+
76
+ train_dataset = load_dataset(
77
+ "HuggingFaceTB/Countdown-Task-GOLD",
78
+ "verified_Qwen2.5-0.5B-Instruct",
79
+ split="train",
80
+ )
81
+
82
+ training_args = GOLDConfig(
83
+ output_dir="gold-model",
84
+ per_device_train_batch_size=1,
85
+ teacher_model_name_or_path=teacher_name,
86
+ teacher_tokenizer_name_or_path=teacher_name,
87
+ use_uld_loss=True,
88
+ uld_use_hybrid_loss=True,
89
+ )
90
+
91
+ trainer = GOLDTrainer(
92
+ model=model,
93
+ teacher_model=teacher_model,
94
+ args=training_args,
95
+ processing_class=tokenizer,
96
+ train_dataset=train_dataset,
97
+ )
98
+ trainer.train()
99
+ ```
100
+
101
+ > [!NOTE]
102
+ > GOLD buffers one full optimizer-window generation batch (`per_device_train_batch_size * gradient_accumulation_steps`)
103
+ > and reuses it across accumulation steps. If the final batch is undersized, GOLD warns and drops that last batch
104
+ > (`Dropping last batch due to unexpected batch size`). Set `dataloader_drop_last=True` to avoid this warning.
105
+
106
+ ### Expected dataset type
107
+
108
+ GOLD requires a [conversational](dataset_formats#conversational) [language modeling](dataset_formats#language_modeling) dataset, e.g.:
109
+
110
+ ```python
111
+ {"messages": [{"role": "user", "content": "What color is the sky?"},
112
+ {"role": "assistant", "content": "It is blue."}]}
113
+ ```
114
+
115
+ `GOLDTrainer` keeps the raw messages so the ChatML collator can construct prompts and completions with the correct
116
+ boundaries.
117
+
118
+ ## How Token Merging Works
119
+
120
+ When student and teacher use different tokenizers, the same text may be split differently:
121
+
122
+ - **Student**: `"Hugging Face"` → 1 token
123
+ - **Teacher**: `"Hugging"`, `" Face"` → 2 tokens
124
+
125
+ GOLD aligns these sequences and merges the teacher's multi-token probabilities into a single distribution that can be compared with the student's single-token distribution.
126
+
127
+ ### Probability Merging
128
+
129
+ For a teacher sequence of tokens `[token₀, token₁, ..., tokenₖ]` that maps to a single student token, GOLD computes:
130
+
131
+ ```
132
+ P_merged(y) = P(y | context) × P(token₁ | token₀, context) × ... × P(tokenₖ | ..., context)
133
+ ```
134
+
135
+ where:
136
+ - `P(y | context)` is the marginal probability distribution over all vocabulary tokens at the first position
137
+ - `P(tokenᵢ | ..., context)` are **scalar** conditional probabilities of the actual tokens that were generated
138
+
139
+ **Key insight**: Only the conditional probabilities of the **actual continuation tokens** are extracted as scalars. The full marginal distribution at the first position is then scaled by multiplying these scalar probabilities.
140
+
141
+ This ensures:
142
+ 1. **Correct joint probability** for the actual generated sequence (by the chain rule)
143
+ 2. **Reasonable approximation** for counterfactual tokens (scaled by the same continuation likelihood)
144
+ 3. **Unnormalized distributions** that preserve the correct relative probabilities for ULD loss computation
145
+
146
+ ### Example
147
+
148
+ Given:
149
+ ```
150
+ P(x₀): ["HF": 0.6, "is": 0.3, "cool": 0.1]
151
+ P(x₁ | "HF"): ["HF": 0.05, "is": 0.9, "cool": 0.05]
152
+ ```
153
+
154
+ If tokens 0 and 1 are merged, and the actual sequence was `["HF", "is"]`:
155
+ ```
156
+ P_merged("HF") = 0.6 × 0.9 = 0.54 ✓ (correct joint probability)
157
+ P_merged("is") = 0.3 × 0.9 = 0.27
158
+ P_merged("cool") = 0.1 × 0.9 = 0.09
159
+ ```
160
+
161
+ The merged distribution is unnormalized (sums to 0.81), but this is intentional and correct for ULD loss computation, which uses sorting and L1 distance.
162
+
163
+ ## GOLDTrainer
164
+
165
+ [[autodoc]] experimental.gold.GOLDTrainer
166
+ - train
167
+ - generate_on_policy_outputs
168
+ - save_model
169
+ - push_to_hub
170
+
171
+ ## GOLDConfig
172
+
173
+ [[autodoc]] experimental.gold.GOLDConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/grpo_trainer.md ADDED
@@ -0,0 +1,803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GRPO Trainer
2
+
3
+ [![model badge](https://img.shields.io/badge/All_models-GRPO-blue)](https://huggingface.co/models?other=grpo,trl)
4
+
5
+ ## Overview
6
+
7
+ TRL supports the GRPO Trainer for training language models, as described in the paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300) by [Zhihong Shao](https://huggingface.co/syhia), [Peiyi Wang](https://huggingface.co/peiyiwang89), [Qihao Zhu](https://huggingface.co/zqh11), Runxin Xu, [Junxiao Song](https://huggingface.co/haha-point), Mingchuan Zhang, Y. K. Li, Y. Wu, [Daya Guo](https://huggingface.co/guoday).
8
+
9
+ The abstract from the paper is the following:
10
+
11
+ > Mathematical reasoning poses a significant challenge for language models due to its complex and structured nature. In this paper, we introduce DeepSeekMath 7B, which continues pre-training DeepSeek-Coder-Base-v1.5 7B with 120B math-related tokens sourced from Common Crawl, together with natural language and code data. DeepSeekMath 7B has achieved an impressive score of 51.7% on the competition-level MATH benchmark without relying on external toolkits and voting techniques, approaching the performance level of Gemini-Ultra and GPT-4. Self-consistency over 64 samples from DeepSeekMath 7B achieves 60.9% on MATH. The mathematical reasoning capability of DeepSeekMath is attributed to two key factors: First, we harness the significant potential of publicly available web data through a meticulously engineered data selection pipeline. Second, we introduce Group Relative Policy Optimization (GRPO), a variant of Proximal Policy Optimization (PPO), that enhances mathematical reasoning abilities while concurrently optimizing the memory usage of PPO.
12
+
13
+ This post-training method was contributed by [Quentin Gallouédec](https://huggingface.co/qgallouedec).
14
+
15
+ ## Quick start
16
+
17
+ This example demonstrates how to train a model using the GRPO method. We train a [Qwen 0.5B Instruct model](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) with the prompts from the [DeepMath-103K dataset](https://huggingface.co/datasets/trl-lib/DeepMath-103K). You can view the data in the dataset here:
18
+
19
+ <iframe
20
+ src="https://huggingface.co/datasets/trl-lib/DeepMath-103K/embed/viewer/default/train?row=0"
21
+ frameborder="0"
22
+ width="100%"
23
+ height="560px"
24
+ ></iframe>
25
+
26
+ Below is the script to train the model.
27
+
28
+ ```python
29
+ # train_grpo.py
30
+ from datasets import load_dataset
31
+ from trl import GRPOTrainer
32
+ from trl.rewards import accuracy_reward
33
+
34
+ dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
35
+
36
+ trainer = GRPOTrainer(
37
+ model="Qwen/Qwen2-0.5B-Instruct",
38
+ reward_funcs=accuracy_reward,
39
+ train_dataset=dataset,
40
+ )
41
+ trainer.train()
42
+ ```
43
+
44
+ Execute the script using the following command:
45
+
46
+ ```bash
47
+ accelerate launch train_grpo.py
48
+ ```
49
+
50
+ Distributed across 8 GPUs, the training takes approximately 1 day.
51
+
52
+ ![GRPO curves](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/grpo_curves.png)
53
+
54
+ ## Looking deeper into the GRPO method
55
+
56
+ GRPO is an online learning algorithm, meaning it improves iteratively by using the data generated by the trained model itself during training. The intuition behind GRPO objective is to maximize the advantage of the generated completions, while ensuring that the model remains close to the reference policy. To understand how GRPO works, it can be broken down into four main steps: **Generating completions**, **computing the advantage**, **estimating the KL divergence**, and **computing the loss**.
57
+
58
+ ![GRPO visual](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/grpo_visual.png)
59
+
60
+ ### Generating completions
61
+
62
+ At each training step, we sample a batch of prompts and generate a set of \\( G \\) completions for each prompt (denoted as \\( o_i \\)).
63
+
64
+ ### Computing the advantage
65
+
66
+ For each of the \\( G \\) sequences, we compute the reward using a reward model or reward function. To align with the comparative nature of reward models—typically trained on datasets of comparisons between outputs for the same question—the advantage is calculated to reflect these relative comparisons. It is normalized as follows:
67
+
68
+ $$\hat{A}_{i,t} = \frac{r_i - \text{mean}(\mathbf{r})}{\text{std}(\mathbf{r})}$$
69
+
70
+ This approach gives the method its name: **Group Relative Policy Optimization (GRPO)**.
71
+
72
+ > [!TIP]
73
+ > It was shown in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that scaling by \\( \text{std}(\mathbf{r}) \\) may cause a question-level difficulty bias. You can disable this scaling by setting `scale_rewards=False` in [`GRPOConfig`].
74
+ > Note that turning off std-based scaling also removes variance normalization, so update magnitudes depend directly on the raw reward scale and batch composition.
75
+
76
+ > [!TIP]
77
+ > As shown in [Part I: Tricks or Traps? A Deep Dive into RL for LLM Reasoning (Lite PPO)](https://huggingface.co/papers/2508.08221), calculating the mean at the local (group) level and the standard deviation at the global (batch) level enables more robust reward shaping. You can use this scaling strategy by setting `scale_rewards="batch"` in [`GRPOConfig`].
78
+
79
+ ### Estimating the KL divergence
80
+
81
+ KL divergence is estimated using the approximator introduced by [Schulman et al. (2020)](http://joschu.net/blog/kl-approx.html). The approximator is defined as follows:
82
+
83
+ $$\mathbb{D}_{\text{KL}}\left[\pi_\theta \|\pi_{\text{ref}}\right] = \frac{\pi_{\text{ref}}(o_{i,t} \mid q, o_{i,<t})}{\pi_\theta(o_{i,t} \mid q, o_{i,<t})} - \log \frac{\pi_{\text{ref}}(o_{i,t} \mid q, o_{i,<t})}{\pi_\theta(o_{i,t} \mid q, o_{i,<t})} - 1,
84
+ $$
85
+
86
+ ### Computing the loss
87
+
88
+ The objective is to maximize the advantage while ensuring that the model remains close to the reference policy. Consequently, the loss is defined as follows:
89
+
90
+ $$
91
+ \mathcal{L}_{\text{GRPO}}(\theta) = -\frac{1}{\sum_{i=1}^G |o_i|} \sum_{i=1}^G \sum_{t=1}^{|o_i|} \left[ \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\left[\pi_\theta(o_{i,t} \mid q, o_{i,< t})\right]_{\text{no grad}}} \hat{A}_{i,t} - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right] \right],
92
+ $$
93
+
94
+ where the first term represents the scaled advantage and the second term penalizes deviations from the reference policy through KL divergence.
95
+
96
+ > [!TIP]
97
+ > Note that compared to the original formulation in [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300), we don't scale by \\( \frac{1}{|o_i|} \\) because it was shown in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that this introduces a response-level length bias. More details in [loss types](#loss-types).
98
+
99
+ > [!TIP]
100
+ > Note that compared to the original formulation in [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300), we use \\( \beta = 0.0 \\) by default, meaning that the KL divergence term is not used. This choice is motivated by several recent studies (e.g., [Open-Reasoner-Zero: An Open Source Approach to Scaling Up Reinforcement Learning on the Base Model](https://huggingface.co/papers/2503.24290)) which have shown that the KL divergence term is not essential for training with GRPO. As a result, it has become common practice to exclude it (e.g. [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783), [DAPO: An Open-Source LLM Reinforcement Learning System at Scale](https://huggingface.co/papers/2503.14476)). If you wish to include the KL divergence term, you can set `beta` in [`GRPOConfig`] to a non-zero value.
101
+
102
+ In the original paper, this formulation is generalized to account for multiple updates after each generation (denoted \\( \mu \\), can be set with `num_iterations` in [`GRPOConfig`]) by leveraging the **clipped surrogate objective**:
103
+
104
+ $$
105
+ \mathcal{L}_{\text{GRPO}}(\theta) = - \frac{1}{\sum_{i=1}^G |o_i|} \sum_{i=1}^G \sum_{t=1}^{|o_i|} \left[ \min \left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})} \hat{A}_{i,t}, \, \text{clip}\left( \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})}, 1 - \epsilon, 1 + \epsilon \right) \hat{A}_{i,t} \right) - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right] \right],
106
+ $$
107
+
108
+ where \\(\text{clip}(\cdot, 1 - \epsilon, 1 + \epsilon) \\) ensures that updates do not deviate excessively from the reference policy by bounding the policy ratio between \\( 1 - \epsilon \\) and \\( 1 + \epsilon \\).
109
+ When \\( \mu = 1 \\) (default in TRL), the clipped surrogate objective simplifies to the original objective.
110
+
111
+ #### Loss Types
112
+
113
+ Several formulations of the objective have been proposed in the literature. Initially, the objective of GRPO was defined as follows:
114
+
115
+ $$
116
+ \mathcal{L}_{\text{GRPO}}(\theta) = - \frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} l_{i,t},
117
+ $$
118
+
119
+ where
120
+
121
+ $$
122
+ l_{i,t} = \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\left[\pi_\theta(o_{i,t} \mid q, o_{i,< t})\right]_{\text{no grad}}} \hat{A}_{i,t} - \beta \mathbb{D}_{\text{KL}}\left[\pi_\theta \| \pi_{\text{ref}}\right].
123
+ $$
124
+
125
+ The [DAPO paper](https://huggingface.co/papers/2503.14476) highlights the limitations of the GRPO algorithm’s sample-level loss in long-CoT scenarios, where longer responses are under-penalized, leading to poorer quality outputs. The proposed solution is a token-level normalization, which better handles longer sequences by assigning more balanced rewards to individual tokens, regardless of response length:
126
+
127
+ $$
128
+ \mathcal{L}_{\text{DAPO}}(\theta) = - \frac{1}{\sum_{i=1}^G |o_i|} \sum_{i=1}^G \sum_{t=1}^{|o_i|} l_{i,t},
129
+ $$
130
+
131
+ To use this formulation, set `loss_type="dapo"` in [`GRPOConfig`].
132
+
133
+ Furthermore, it was demonstrated in the paper [Understanding R1-Zero-Like Training: A Critical Perspective](https://huggingface.co/papers/2503.20783) that the initial GRPO formulation introduces a response length bias. They show that while the DAPO formulation reduces this bias, it does not eliminate it completely. To fully remove this bias, they propose dividing by a constant instead of the sequence length, resulting in the following formulation:
134
+
135
+ $$
136
+ \mathcal{L}_{\text{Dr. GRPO}}(\theta) = - \frac{1}{LG} \sum_{i=1}^G \sum_{t=1}^{|o_i|} l_{i,t},
137
+ $$
138
+
139
+ This constant is recommended to be the maximum completion length. To use this formulation, set `loss_type="dr_grpo"` in the [`GRPOConfig`].
140
+
141
+ Alternatively, in the [SAPO paper](https://huggingface.co/papers/2511.20347), the Qwen team proposes replacing the "hard" clipping mechanism of GRPO with a smooth, temperature-controlled soft gating mechanism. While GRPO zeroes out gradients when the policy deviates too far from the reference, SAPO uses a soft trust region that smoothly decays the gradient weight. This allows the model to retain useful learning signals from "near-on-policy" tokens while suppressing noise from extreme deviations.
142
+
143
+ The loss function is defined as:
144
+
145
+ $$
146
+ \mathcal{L}_{\text{SAPO}}(\theta) = - \frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} f_{i,t} \left( \frac{\pi_\theta(o_{i,t} | q, o_{i,<t})}{\pi_{\theta_{old}}(o_{i,t} | q, o_{i,<t})} \right) \hat{A}_{i,t}
147
+ $$
148
+
149
+ The soft-gating function \\( f_{i,t} \\) is defined using the sigmoid function \\( \sigma \\) as:
150
+
151
+ $$
152
+ f_{i,t}(x) = \sigma \left( \tau_{i,t} (x - 1) \right) \cdot \frac{4}{\tau_{i,t}}
153
+ $$
154
+
155
+ The temperature \\( \tau_{i,t} \\) is chosen based on the sign of the advantage \\( \hat{A}_{i,t} \\):
156
+
157
+ $$
158
+ \tau_{i,t} = \begin{cases}
159
+ \tau_{\text{pos}}, & \text{if } \hat{A}_{i,t} > 0 \\
160
+ \tau_{\text{neg}}, & \text{otherwise}
161
+ \end{cases}
162
+ $$
163
+
164
+ They recommend using asymmetric temperatures, \\( \tau_{\text{neg}} > \tau_{\text{pos}} \\) (defaults are \\( \tau_{\text{pos}}=1.0, \tau_{\text{neg}}=1.05 \\) ). This ensures that the model is penalized more strictly for "bad" actions to prevent instability, while being more permissive with "good" actions.
165
+
166
+ To use this formulation, set `loss_type="sapo"` in the [`GRPOConfig`].
167
+
168
+ ## Logged metrics
169
+
170
+ While training and evaluating, we record the following reward metrics:
171
+
172
+ - `num_tokens`: The total number of tokens processed so far, including both prompts and completions. When using tools, only non-tool tokens are counted.
173
+ - `step_time`: The average time (in seconds) taken per training step (including generation).
174
+ - `completions/mean_length`: The average length of generated completions. When using tools, only non-tool tokens are counted.
175
+ - `completions/min_length`: The minimum length of generated completions. When using tools, only non-tool tokens are counted.
176
+ - `completions/max_length`: The maximum length of generated completions. When using tools, only non-tool tokens are counted.
177
+ - `completions/mean_terminated_length`: The average length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.
178
+ - `completions/min_terminated_length`: The minimum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.
179
+ - `completions/max_terminated_length`: The maximum length of generated completions that terminate with EOS. When using tools, only non-tool tokens are counted.
180
+ - `completions/clipped_ratio`: The ratio of truncated (clipped) completions.
181
+ - `reward/{reward_func_name}/mean`: The average reward from a specific reward function.
182
+ - `reward/{reward_func_name}/std`: The standard deviation of the reward from a specific reward function.
183
+ - `reward`: The overall average reward after summing rewards across functions (weighted by `reward_weights`).
184
+ - `reward_std`: The standard deviation of summed rewards across functions (weighted by `reward_weights`), computed over the full batch.
185
+ - `frac_reward_zero_std`: The fraction of samples in the generation batch with a reward std of zero, implying there is little diversity for that prompt (all answers are correct or incorrect).
186
+ - `entropy`: Average entropy of token predictions across generated completions. (If `mask_truncated_completions=True`, masked sequences tokens are excluded.)
187
+ - `kl`: The average KL divergence between the model and the reference model, calculated over generated completions. Logged only if `beta` is nonzero.
188
+ - `clip_ratio/region_mean`: The ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities where the GRPO objective is clipped to stay within the trust region: \\( \text{clip}\left( r_{i,t}(\theta), 1 - \epsilon_\mathrm{low}, 1 + \epsilon_\mathrm{high} \right)\,, \quad r_{i,t}(\theta) = \frac{\pi_\theta(o_{i,t} \mid q, o_{i,< t})}{\pi_{\theta_{\text{old}}}(o_{i,t} \mid q, o_{i,< t})} \\). A higher value means more tokens are clipped, which constrains how much the policy $\pi_\theta$ can change.
189
+ - `clip_ratio/low_mean`: The average ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the lower bound of the trust region: \\(r_{i,t}(\theta) < 1 - \epsilon_\mathrm{low}\\).
190
+ - `clip_ratio/low_min`: The minimum ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the lower bound of the trust region: \\(r_{i,t}(\theta) < 1 - \epsilon_\mathrm{low}\\).
191
+ - `clip_ratio/high_mean`: The average ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the upper bound of the trust region: \\(r_{i,t}(\theta) > 1 + \epsilon_\mathrm{high}\\).
192
+ - `clip_ratio/high_max`: The maximum ratio of token (or sequence, if `importance_sampling_level="sequence"`) probabilities that were clipped on the upper bound of the trust region: \\(r_{i,t}(\theta) > 1 + \epsilon_\mathrm{high}\\).
193
+
194
+ ## Customization
195
+
196
+ ### Speed up training with vLLM-powered generation
197
+
198
+ Generation is often the main bottleneck when training with online methods. To accelerate generation, you can use [vLLM](https://github.com/vllm-project/vllm), a high-throughput, low-latency inference engine for LLMs. To enable it, first install the package with
199
+
200
+ ```shell
201
+ pip install trl[vllm]
202
+ ```
203
+
204
+ We support two ways of using vLLM during training: **server mode** and **colocate mode**.
205
+
206
+ > [!TIP]
207
+ > By default, Truncated Importance Sampling is activated for vLLM generation to address the generation-training mismatch that occurs when using different frameworks. This can be turned off by setting `vllm_importance_sampling_correction=False`. For more information, see [Truncated Importance Sampling](paper_index#truncated-importance-sampling)
208
+
209
+ #### Option 1: Colocate mode
210
+
211
+ In this mode, vLLM runs inside the trainer process and shares GPU memory with the training model. This avoids launching a separate server and can improve GPU utilization, but may lead to memory contention on the training GPUs. This is the default mode.
212
+
213
+ ```python
214
+ from trl import GRPOConfig
215
+
216
+ training_args = GRPOConfig(
217
+ ...,
218
+ use_vllm=True, # vllm_mode="colocate" by default
219
+ )
220
+ ```
221
+
222
+ #### Option 2: Server mode
223
+
224
+ In this mode, vLLM runs in a separate process (and using separate GPUs) and communicates with the trainer via HTTP. This is ideal if you have dedicated GPUs for inference.
225
+
226
+ 1. **Start the vLLM server**:
227
+
228
+ ```bash
229
+ trl vllm-serve --model <model_name>
230
+ ```
231
+
232
+ 2. **Enable server mode in your training script**:
233
+
234
+ ```python
235
+ from trl import GRPOConfig
236
+
237
+ training_args = GRPOConfig(
238
+ ...,
239
+ use_vllm=True,
240
+ vllm_mode="server",
241
+ )
242
+ ```
243
+
244
+ > [!WARNING]
245
+ > Make sure that the server is using different GPUs than the trainer, otherwise you may run into NCCL errors. You can specify the GPUs to use with the `CUDA_VISIBLE_DEVICES` environment variable.
246
+
247
+ > [!TIP]
248
+ > Depending on the model size and the overall GPU memory requirements for training, you may need to adjust the `vllm_gpu_memory_utilization` parameter in [`GRPOConfig`] to avoid underutilization or out-of-memory errors.
249
+ >
250
+ > We provide a [HF Space](https://huggingface.co/spaces/trl-lib/recommend-vllm-memory) to help estimate the recommended GPU memory utilization based on your model configuration and experiment settings. Simply use it as follows to get `vllm_gpu_memory_utilization` recommendation:
251
+ >
252
+ > <iframe src="https://trl-lib-recommend-vllm-memory.hf.space" frameborder="0" width="850" height="450"></iframe>
253
+ >
254
+ > If the recommended value does not work in your environment, we suggest adding a small buffer (e.g., +0.05 or +0.1) to the recommended value to ensure stability.
255
+ >
256
+ > If you still find you are getting out-of-memory errors set `vllm_enable_sleep_mode` to True and the vllm parameters and cache will be offloaded during the optimization step. For more information, see [Reducing Memory Usage with vLLM Sleep Mode](reducing_memory_usage#vllm-sleep-mode).
257
+
258
+ > [!TIP]
259
+ > By default, GRPO uses `MASTER_ADDR=localhost` and `MASTER_PORT=12345` for vLLM, but you can override these values by setting the environment variables accordingly.
260
+
261
+ For more information, see [Speeding up training with vLLM](speeding_up_training#vllm-for-fast-generation-in-online-methods).
262
+
263
+
264
+ #### Dealing with the Training-Inference Mismatch
265
+ While vLLM greatly accelerates inference, it also decouples the inference engine from the training engine. In theory these engines are mathematically identical, in practice however they can produce different outputs due to precision effects and hardware specific optimizations. This divergence reflects the different optimization objectives of the two systems. This divergence reflects the distinct optimization goals of the two systems. Inference engines aim to maximize sampling throughput, typically measured in tokens per second, while maintaining acceptable sampling fidelity. Training frameworks instead focus on numerical stability and precision for gradient computation, often using higher precision formats like FP32 for master weights and optimizer states. These differing priorities and constraints introduce an inevitable, albeit subtle, mismatch between training and inference.
266
+
267
+ This mismatch leads to a biased gradient update which has been observed to destabilize training ([[1]](https://fengyao.notion.site/off-policy-rl)[[2]](https://yingru.notion.site/When-Speed-Kills-Stability-Demystifying-RL-Collapse-from-the-Training-Inference-Mismatch-271211a558b7808d8b12d403fd15edda)[[3]](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/#true-on-policy-rl)[[4]](https://huggingface.co/papers/2510.26788)[[5]](https://huggingface.co/papers/2510.18855)). For simplicity, consider the REINFORCE policy gradient:
268
+
269
+ $$
270
+ \nabla_\theta \mathcal{J}(x,\theta)
271
+ = \mathbb{E}_{y \sim \pi^\text{train}(\cdot \mid x,\theta)}
272
+ \left[ \nabla_\theta \log \pi^\text{train}(y \mid x,\theta) \cdot R(x,y) \right]
273
+ $$
274
+
275
+ Here \\( x \\) denotes prompts sampled from some data distribution, and \\( \pi^\text{train} \\) is the policy implemented by the training engine. With vLLM in the loop we obtain a separate inference policy \\( \pi^\text{inference} \\), so the effective policy gradient becomes
276
+
277
+ $$
278
+ \nabla_\theta \mathcal{J}_{\text{biased}}(x,\theta)
279
+ = \mathbb{E}_{y \sim \pi^\text{inference}(\cdot \mid x,\theta)}
280
+ \left[ \nabla_\theta \log \pi^\text{train}(y \mid x,\theta) \cdot R(x,y) \right].
281
+ $$
282
+
283
+ This turns an otherwise on policy RL problem into an off policy one.
284
+
285
+ The standard way to correct for this distribution shift is **importance sampling (IS)**. We provide two IS variants: [Truncated Importance Sampling (TIS)](paper_index#truncated-importance-sampling) and [Masked Importance Sampling (MIS)](paper_index#masked-importance-sampling). Both variants can be applied either at the token level or at the sequence level.Let \\( \rho \\) denote the importance weight, for example \\( \rho_t \\) per token or \\( \rho_{\text{seq}} \\) per sequence. Under TIS, ratios larger than `vllm_importance_sampling_cap` are clipped,
286
+
287
+ $$
288
+ \rho \leftarrow \min(\rho, C).
289
+ $$
290
+
291
+ Under MIS, ratios larger than `vllm_importance_sampling_cap` are set to zero, so those samples do not contribute to the gradient. In other words, large ratio samples are downweighted under TIS and discarded under MIS. The configuration flag `vllm_importance_sampling_mode` chooses both the IS variant (masking or truncation) and the granularity (token level or sequence level).
292
+
293
+ Importance sampling is the principled algorithmic response to the training–inference mismatch. However, there are also more direct approaches that attempt to reduce the mismatch between the two engines themselves. Most of these are engineering solutions. For example, [MiniMax M1 uses an FP32 language model head](https://huggingface.co/papers/2506.13585) in the inference engine. Thinking Machines has explored [deterministic inference kernels](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/), although this comes with a significant efficiency cost. vLLM has shown [bitwise consistent policies](https://blog.vllm.ai/2025/11/10/bitwise-consistent-train-inference.html) by building on the batch invariant deterministic kernels from Thinking Machines, but as of November 2025 there remains a substantial throughput penalty relative to standard vLLM inference.
294
+
295
+ ### GRPO at scale: train a 70B+ Model on multiple nodes
296
+
297
+ When training large models like **Qwen2.5-72B**, you need several key optimizations to make the training efficient and scalable across multiple GPUs and nodes. These include:
298
+
299
+ - **DeepSpeed ZeRO Stage 3**: ZeRO leverages data parallelism to distribute model states (weights, gradients, optimizer states) across multiple GPUs and CPUs, reducing memory and compute requirements on each device. Since large models cannot fit on a single GPU, using ZeRO Stage 3 is required for training such models. For more details, see [DeepSpeed Integration](deepspeed_integration).
300
+ - **Accelerate**: Accelerate is a library that simplifies distributed training across multiple GPUs and nodes. It provides a simple API to launch distributed training and handles the complexities of distributed training, such as data parallelism, gradient accumulation, and distributed data loading. For more details, see [Distributing Training](distributing_training).
301
+ - **vLLM**: See the previous section on how to use vLLM to speed up generation.
302
+
303
+ Below is an example SLURM script to train a 70B model with GRPO on multiple nodes. This script trains a model on 4 nodes and uses the 5th node for vLLM-powered generation.
304
+
305
+ ```sh
306
+ #!/bin/bash
307
+ #SBATCH --nodes=5
308
+ #SBATCH --gres=gpu:8
309
+
310
+ # Get the list of allocated nodes
311
+ NODELIST=($(scontrol show hostnames $SLURM_JOB_NODELIST))
312
+
313
+ # Assign the first 4 nodes for training and the 5th node for vLLM
314
+ TRAIN_NODES="${NODELIST[@]:0:4}" # Nodes 0, 1, 2, 3 for training
315
+ VLLM_NODE="${NODELIST[4]}" # Node 4 for vLLM
316
+
317
+ # Run training on the first 4 nodes (Group 1)
318
+ srun --nodes=4 --ntasks=4 --nodelist="${NODELIST[@]:0:4}" accelerate launch \
319
+ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
320
+ --num_processes 32 \
321
+ --num_machines 4 \
322
+ --main_process_ip ${NODELIST[0]} \
323
+ --machine_rank $SLURM_PROCID \
324
+ --rdzv_backend c10d \
325
+ train_grpo.py \
326
+ --server_ip $VLLM_NODE &
327
+
328
+ # Run vLLM server on the 5th node (Group 2)
329
+ srun --nodes=1 --ntasks=1 --nodelist="${NODELIST[4]}" trl vllm-serve --model Qwen/Qwen2.5-72B --tensor_parallel_size 8 &
330
+
331
+ wait
332
+ ```
333
+
334
+ ```python
335
+ import argparse
336
+
337
+ from datasets import load_dataset
338
+ from trl import GRPOTrainer, GRPOConfig
339
+ from trl.rewards import accuracy_reward
340
+
341
+ def main():
342
+ parser = argparse.ArgumentParser()
343
+ parser.add_argument("--vllm_server_host", type=str, default="", help="The server IP")
344
+ args = parser.parse_args()
345
+
346
+ dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
347
+
348
+ training_args = GRPOConfig(
349
+ per_device_train_batch_size=4,
350
+ use_vllm=True,
351
+ vllm_mode="server",
352
+ vllm_server_host=args.vllm_server_host.replace("ip-", "").replace("-", "."), # from ip-X-X-X-X to X.X.X.X
353
+ )
354
+
355
+ trainer = GRPOTrainer(
356
+ model="Qwen/Qwen2.5-72B",
357
+ args=training_args,
358
+ reward_funcs=accuracy_reward,
359
+ train_dataset=dataset
360
+ )
361
+ trainer.train()
362
+
363
+ if __name__=="__main__":
364
+ main()
365
+ ```
366
+
367
+ ### Using a custom reward function
368
+
369
+ The [`GRPOTrainer`] supports using custom reward functions instead of dense reward models. To ensure compatibility, your reward function must satisfy the following requirements:
370
+
371
+ Reward functions can be either synchronous Python callables or asynchronous `async def` coroutines. When you provide multiple asynchronous reward functions, they are awaited concurrently (run in parallel via `asyncio.gather`) so their latency overlaps.
372
+
373
+ 1. **Input arguments**:
374
+ - The function must accept the following as keyword arguments:
375
+ - `prompts` (contains the prompts),
376
+ - `completions` (contains the generated completions),
377
+ - `completion_ids` (contains the tokenized completions),
378
+ - `trainer_state` ([`~transformers.TrainerState`]): The current state of the trainer. This can be used to implement dynamic reward functions, such as curriculum learning, where the reward is adjusted based on the training progress.
379
+ - `log_extra`: a callable `log_extra(column: str, values: list)` to add extra columns to the completions table. See Example 6. In distributed training, it's important that all processes log the same set of keys.
380
+ - `log_metric`: a callable `log_metric(name: str, value: float)` to log scalar metrics as plots alongside `kl`, `entropy`, etc. See Example 6. In distributed training, it's important that all processes log the same set of keys.
381
+ - `environments`: a list of environment instances, one per completion. Only present when `environment_factory` is provided. Use this to read state accumulated during the episode (e.g., `env.reward`).
382
+ - All column names (but `prompt`) that the dataset may have. For example, if the dataset contains a column named `ground_truth`, the function will be called with `ground_truth` as a keyword argument.
383
+
384
+ The easiest way to comply with this requirement is to use `**kwargs` in the function signature.
385
+ - Depending on the dataset format, the input will vary:
386
+ - For [standard format](dataset_formats#standard), `prompts` and `completions` will be lists of strings.
387
+ - For [conversational format](dataset_formats#conversational), `prompts` and `completions` will be lists of message dictionaries.
388
+
389
+ 2. **Return value**: The function must return a list of floats. Each float represents the reward corresponding to a single completion.
390
+
391
+ #### Example 1: Reward longer completions
392
+
393
+ Below is an example of a reward function for a standard format that rewards longer completions:
394
+
395
+ ```python
396
+ def reward_func(completion_ids, **kwargs):
397
+ """Reward function that assigns higher scores to longer completions (in terms of token count)."""
398
+ return [float(len(ids)) for ids in completion_ids]
399
+ ```
400
+
401
+ You can test it as follows:
402
+
403
+ ```python
404
+ >>> prompts = ["The sky is", "The sun is"] # not used in the reward function, but the trainer will pass it
405
+ >>> completions = [" blue.", " in the sky."] # not used in the reward function, but the trainer will pass it
406
+ >>> completion_ids = [[6303, 13], [304, 279, 12884, 13]]
407
+ >>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids)
408
+ [2.0, 4.0]
409
+ ```
410
+
411
+ #### Example 1.1: Reward longer completions (based on the number of characters)
412
+
413
+ Same as the previous example, but this time the reward function is based on the number of characters instead of tokens.
414
+
415
+ ```python
416
+ def reward_func(completions, **kwargs):
417
+ """Reward function that assigns higher scores to longer completions (in terms of character count)."""
418
+ return [float(len(completion)) for completion in completions]
419
+ ```
420
+
421
+ You can test it as follows:
422
+
423
+ ```python
424
+ >>> prompts = ["The sky is", "The sun is"]
425
+ >>> completions = [" blue.", " in the sky."]
426
+ >>> completion_ids = [[6303, 13], [304, 279, 12884, 13]] # not used in the reward function, but the trainer will pass it
427
+ >>> reward_func(prompts=prompts, completions=completions, completion_ids=completion_ids)
428
+ [6.0, 12.0]
429
+ ```
430
+
431
+ #### Example 2: Reward completions with a specific format
432
+
433
+ Below is an example of a reward function that checks if the completion has a specific format. This example is inspired by the _format reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948).
434
+ It is designed for a conversational format, where prompts and completions consist of structured messages.
435
+
436
+ ```python
437
+ import re
438
+
439
+ def format_reward_func(completions, **kwargs):
440
+ """Reward function that checks if the completion has a specific format."""
441
+ pattern = r"^<think>.*?</think><answer>.*?</answer>$"
442
+ completion_contents = [completion[0]["content"] for completion in completions]
443
+ matches = [re.match(pattern, content) for content in completion_contents]
444
+ return [1.0 if match else 0.0 for match in matches]
445
+ ```
446
+
447
+ You can test this function as follows:
448
+
449
+ ```python
450
+ >>> prompts = [
451
+ ... [{"role": "assistant", "content": "What is the result of (1 + 2) * 4?"}],
452
+ ... [{"role": "assistant", "content": "What is the result of (3 + 1) * 2?"}],
453
+ ... ]
454
+ >>> completions = [
455
+ ... [{"role": "assistant", "content": "<think>The sum of 1 and 2 is 3, which we multiply by 4 to get 12.</think><answer>(1 + 2) * 4 = 12</answer>"}],
456
+ ... [{"role": "assistant", "content": "The sum of 3 and 1 is 4, which we multiply by 2 to get 8. So (3 + 1) * 2 = 8."}],
457
+ ... ]
458
+ >>> format_reward_func(prompts=prompts, completions=completions)
459
+ [1.0, 0.0]
460
+ ```
461
+
462
+ #### Example 3: Reward completions based on a reference
463
+
464
+ Below is an example of a reward function that checks if the completion is correct. This example is inspired by the _accuracy reward_ function used in the paper [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://huggingface.co/papers/2501.12948).
465
+ This example is designed for [standard format](dataset_formats#standard), where the dataset contains a column named `ground_truth`.
466
+
467
+ ```python
468
+ import re
469
+
470
+ def reward_func(completions, ground_truth, **kwargs):
471
+ # Regular expression to capture content inside \boxed{}
472
+ matches = [re.search(r"\\boxed\{(.*?)\}", completion) for completion in completions]
473
+ contents = [match.group(1) if match else "" for match in matches]
474
+ # Reward 1 if the content is the same as the ground truth, 0 otherwise
475
+ return [1.0 if c == gt else 0.0 for c, gt in zip(contents, ground_truth)]
476
+ ```
477
+
478
+ You can test this function as follows:
479
+
480
+ ```python
481
+ >>> prompts = ["Problem: Solve the equation $2x + 3 = 7$. Solution:", "Problem: Solve the equation $3x - 5 = 10$."]
482
+ >>> completions = [r" The solution is \boxed{2}.", r" The solution is \boxed{6}."]
483
+ >>> ground_truth = ["2", "5"]
484
+ >>> reward_func(prompts=prompts, completions=completions, ground_truth=ground_truth)
485
+ [1.0, 0.0]
486
+ ```
487
+
488
+ #### Example 4: Multi-task reward functions
489
+
490
+ Below is an example of using multiple reward functions in the [`GRPOTrainer`]. In this example, we define two task-specific reward functions: `math_reward_func` and `coding_reward_func`. The `math_reward_func` rewards math problems based on their correctness, while the `coding_reward_func` rewards coding problems based on whether the solution works.
491
+
492
+ ```python
493
+ from datasets import Dataset
494
+ from trl import GRPOTrainer
495
+
496
+ # Define a dataset that contains both math and coding problems
497
+ dataset = Dataset.from_list(
498
+ [
499
+ {"prompt": "What is 2+2?", "task": "math"},
500
+ {"prompt": "Write a function that returns the sum of two numbers.", "task": "code"},
501
+ {"prompt": "What is 3*4?", "task": "math"},
502
+ {"prompt": "Write a function that returns the product of two numbers.", "task": "code"},
503
+ ]
504
+ )
505
+
506
+ # Math-specific reward function
507
+ def math_reward_func(prompts, completions, task, **kwargs):
508
+ rewards = []
509
+ for prompt, completion, t in zip(prompts, completions, task):
510
+ if t == "math":
511
+ # Calculate math-specific reward
512
+ correct = check_math_solution(prompt, completion)
513
+ reward = 1.0 if correct else -1.0
514
+ rewards.append(reward)
515
+ else:
516
+ # Return None for non-math tasks
517
+ rewards.append(None)
518
+ return rewards
519
+
520
+ # Coding-specific reward function
521
+ def coding_reward_func(prompts, completions, task, **kwargs):
522
+ rewards = []
523
+ for prompt, completion, t in zip(prompts, completions, task):
524
+ if t == "coding":
525
+ # Calculate coding-specific reward
526
+ works = test_code_solution(prompt, completion)
527
+ reward = 1.0 if works else -1.0
528
+ rewards.append(reward)
529
+ else:
530
+ # Return None for non-coding tasks
531
+ rewards.append(None)
532
+ return rewards
533
+
534
+ # Use both task-specific reward functions
535
+ trainer = GRPOTrainer(
536
+ model="Qwen/Qwen2-0.5B-Instruct",
537
+ reward_funcs=[math_reward_func, coding_reward_func],
538
+ train_dataset=dataset,
539
+ )
540
+
541
+ trainer.train()
542
+ ```
543
+
544
+ In this example, the `math_reward_func` and `coding_reward_func` are designed to work with a mixed dataset that contains both math and coding problems. The `task` column in the dataset is used to determine which reward function to apply to each problem. If there is no relevant reward function for a sample in the dataset, the reward function will return `None`, and the [`GRPOTrainer`] will continue with the valid functions and tasks. This allows the [`GRPOTrainer`] to handle multiple reward functions with different applicability.
545
+
546
+ Note that the [`GRPOTrainer`] will ignore the `None` rewards returned by the reward functions and only consider the rewards returned by the relevant functions. This ensures that the model is trained on the relevant tasks and ignores the tasks for which there is no relevant reward function.
547
+
548
+ #### Example 5: Asynchronous reward functions
549
+
550
+ Custom reward functions can also be defined as `async def` coroutines. This is useful if your reward depends on slow I/O (for example, calling a remote service). When you pass multiple async reward functions, [`GRPOTrainer`] executes them concurrently so their latency overlaps.
551
+
552
+ Below is a minimal example of an async reward function that simulates an I/O-bound operation:
553
+
554
+ ```python
555
+ import asyncio
556
+
557
+ async def async_reward_func(prompts, completions, **kwargs):
558
+ # Simulate an I/O-bound call (e.g., HTTP request, database lookup)
559
+ await asyncio.sleep(0.01)
560
+ # Simple toy reward: 1.0 if the completion is non-empty, else 0.0
561
+ return [1.0 if completion else 0.0 for completion in completions]
562
+ ```
563
+
564
+ #### Example 6: Logging extra columns and metrics
565
+
566
+ Below is an example of a reward function that logs extra columns to the completions table and scalar metrics as plots.
567
+
568
+ ```python
569
+ import re
570
+
571
+ def reward_func(completions, ground_truth, log_extra=None, log_metric=None, **kwargs):
572
+ extracted = [re.search(r"\\boxed\{(.*?)\}", c) for c in completions]
573
+ extracted = [m.group(1) if m else None for m in extracted]
574
+ rewards = [1.0 if e == gt else 0.0 for e, gt in zip(extracted, ground_truth)]
575
+
576
+ if log_extra:
577
+ log_extra("golden_answer", list(ground_truth))
578
+ log_extra("extracted_answer", [e or "[none]" for e in extracted])
579
+
580
+ if log_metric:
581
+ log_metric("accuracy", sum(rewards) / len(rewards))
582
+
583
+ return rewards
584
+ ```
585
+
586
+ #### Passing the reward function to the trainer
587
+
588
+ To use your custom reward function, pass it to the [`GRPOTrainer`] as follows:
589
+
590
+ ```python
591
+ from trl import GRPOTrainer
592
+
593
+ trainer = GRPOTrainer(
594
+ reward_funcs=reward_func,
595
+ ...,
596
+ )
597
+ ```
598
+
599
+ You can pass several reward functions as a list; this list may include both synchronous and asynchronous functions:
600
+
601
+ ```python
602
+ from trl import GRPOTrainer
603
+
604
+ trainer = GRPOTrainer(
605
+ reward_funcs=[reward_func, async_reward_func1, async_reward_func2],
606
+ ...,
607
+ )
608
+ ```
609
+
610
+ and the reward will be computed as the sum of the rewards from each function, or the weighted sum if `reward_weights` is provided in the config.
611
+
612
+ Note that [`GRPOTrainer`] supports multiple reward functions of different types. See the parameters documentation for more details.
613
+
614
+ ### Rapid Experimentation for GRPO
615
+
616
+ RapidFire AI is an open-source experimentation engine that sits on top of TRL and lets you launch multiple GRPO configurations at once, even on a single GPU. Instead of trying configurations sequentially, RapidFire lets you **see all their learning curves earlier, stop underperforming runs, and clone promising ones with new settings in flight** without restarting. For more information, see [RapidFire AI Integration](rapidfire_integration).
617
+
618
+ ## Agent Training
619
+
620
+ GRPO supports **agent training** through the `tools` argument in [`GRPOTrainer`].
621
+ This parameter expects a list of Python functions (sync or async) that define the tools available to the agent:
622
+
623
+ ```python
624
+ from trl import GRPOTrainer
625
+
626
+ trainer = GRPOTrainer(
627
+ tools=[tool1, tool2],
628
+ ...,
629
+ )
630
+ ```
631
+
632
+ Each tool must be a standard Python function with **type-hinted arguments and return types**, along with a **Google-style docstring** describing its purpose, arguments, and return value.
633
+ For more details, see the [Passing tools guide](https://huggingface.co/docs/transformers/en/chat_extras#passing-tools).
634
+
635
+ Example:
636
+
637
+ ```python
638
+ from trl import GRPOTrainer
639
+
640
+ def multiply(a: int, b: int) -> int:
641
+ """
642
+ Multiplies two integers.
643
+
644
+ Args:
645
+ a: The first integer.
646
+ b: The second integer.
647
+
648
+ Returns:
649
+ The product of the two integers.
650
+ """
651
+ return a * b
652
+
653
+ async def async_add(a: int, b: int) -> int:
654
+ """
655
+ Asynchronously adds two integers.
656
+
657
+ Args:
658
+ a: The first integer.
659
+ b: The second integer.
660
+
661
+ Returns:
662
+ The sum of the two integers.
663
+ """
664
+ return a + b
665
+
666
+ trainer = GRPOTrainer(
667
+ tools=[multiply, async_add],
668
+ ...,
669
+ )
670
+ ```
671
+
672
+ You can also provide tools through `environment_factory`. In this mode, [`GRPOTrainer`] creates one environment instance per rollout and exposes the environment's public methods as tools.
673
+
674
+ > [!IMPORTANT]
675
+ > `environment_factory` requires `transformers>=5.2.0`.
676
+
677
+ The following is a minimal example of using `environment_factory` to define a simple environment with an `increment` method, which is exposed as a tool to the agent:
678
+
679
+ ```python
680
+ from datasets import Dataset
681
+ from trl import GRPOConfig, GRPOTrainer
682
+
683
+ instructions = [f"Increment the counter by {i}." for i in range(1, 7)]
684
+ dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": instruction}] for instruction in instructions]})
685
+
686
+ def reward_func(environments, **kwargs): # dummy reward: the reward is the current value of the counter
687
+ return [environment.counter for environment in environments]
688
+
689
+ class IncrementEnv:
690
+ def reset(self, **kwargs) -> str | None: # required; receives sampled row fields as kwargs (e.g., `prompt`)
691
+ self.counter = 0
692
+ return "Counter reset to 0.\n"
693
+
694
+ def increment(self, step: int) -> int: # the other public methods of the environment are exposed as tools
695
+ """
696
+ Increment the internal counter.
697
+
698
+ Args:
699
+ step: Value to add to the counter.
700
+
701
+ Returns:
702
+ The updated counter value.
703
+ """
704
+ self.counter += step
705
+ return self.counter
706
+
707
+ trainer = GRPOTrainer(
708
+ model="Qwen/Qwen3-0.6B",
709
+ args=GRPOConfig(chat_template_kwargs={"enable_thinking": False}),
710
+ train_dataset=dataset,
711
+ reward_funcs=reward_func,
712
+ environment_factory=IncrementEnv,
713
+ )
714
+ trainer.train()
715
+ ```
716
+
717
+ `reset` can return either `None` or a string. In GRPO, when it returns a string, that string is appended to the last user message before generation.
718
+
719
+ ### Supported Models
720
+
721
+ Tested with:
722
+
723
+ - [**Qwen3**](https://huggingface.co/collections/Qwen/qwen3) — e.g., `Qwen/Qwen3-0.6B`
724
+ - [**Qwen3.5**](https://huggingface.co/collections/Qwen/qwen35) — e.g., `Qwen/Qwen3.5-2B`
725
+
726
+ > [!TIP]
727
+ > Compatibility with all LLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub — or better yet, submit a pull request with the required changes.
728
+
729
+ ### Quick Start
730
+
731
+ Use [grpo\_agent.py](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_agent.py) to fine-tune a LLM for agentic workflows.
732
+
733
+ ```bash
734
+ accelerate launch \
735
+ --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \
736
+ examples/scripts/grpo_agent.py \
737
+ --model_name_or_path Qwen/Qwen3-0.6B
738
+ ...
739
+ ```
740
+
741
+ ## Vision-Language Model (VLM) Training
742
+
743
+ GRPO supports training Vision-Language Models (VLMs) on multimodal datasets containing both text and images.
744
+
745
+ ### Supported Models
746
+
747
+ Tested with:
748
+
749
+ - **Gemma3** — e.g., `google/gemma-3-4b-it`
750
+ - **LLaVA-NeXT** — e.g., `llava-hf/llava-v1.6-mistral-7b-hf`
751
+ - **Qwen2-VL** — e.g., `Qwen/Qwen2-VL-2B-Instruct`
752
+ - **Qwen2.5-VL** — e.g., `Qwen/Qwen2.5-VL-3B-Instruct`
753
+ - **SmolVLM2** — e.g., `HuggingFaceTB/SmolVLM2-2.2B-Instruct`
754
+
755
+ > [!TIP]
756
+ > Compatibility with all VLMs is not guaranteed. If you believe a model should be supported, feel free to open an issue on GitHub — or better yet, submit a pull request with the required changes.
757
+
758
+ ### Quick Start
759
+
760
+ Use [grpo\_vlm.py](https://github.com/huggingface/trl/blob/main/examples/scripts/grpo_vlm.py) to fine-tune a VLM. Example command for training on [`lmms-lab/multimodal-open-r1-8k-verified`](https://huggingface.co/datasets/lmms-lab/multimodal-open-r1-8k-verified):
761
+
762
+ ```bash
763
+ accelerate launch \
764
+ --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \
765
+ examples/scripts/grpo_vlm.py \
766
+ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
767
+ --output_dir grpo-Qwen2.5-VL-3B-Instruct \
768
+ --learning_rate 1e-5 \
769
+ --dtype bfloat16 \
770
+ --max_completion_length 1024 \
771
+ --use_vllm \
772
+ --vllm_mode colocate \
773
+ --use_peft \
774
+ --lora_target_modules "q_proj", "v_proj" \
775
+ --log_completions
776
+ ```
777
+
778
+ ### Configuration Tips
779
+
780
+ - Use LoRA on vision-language projection layers
781
+ - Enable 4-bit quantization to reduce memory usage
782
+ - VLMs are memory-intensive — start with smaller batch sizes
783
+ - Most models are compatible with vLLM (`server` and `colocate` modes)
784
+
785
+ ### Dataset Format
786
+
787
+ Each training sample should include:
788
+
789
+ - `prompt`: Text formatted via the processor's chat template
790
+ - `image`/`images`: PIL Image or list of PIL Images
791
+
792
+ The trainer automatically handles image-to-tensor conversion via the model’s image processor.
793
+
794
+ ## GRPOTrainer
795
+
796
+ [[autodoc]] GRPOTrainer
797
+ - train
798
+ - save_model
799
+ - push_to_hub
800
+
801
+ ## GRPOConfig
802
+
803
+ [[autodoc]] GRPOConfig
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/grpo_with_replay_buffer.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GRPO With Replay Buffer
2
+
3
+ This experimental trainer, trains a model with GRPO but replaces groups (and corresponding completions) that have 0 standard deviation with groups with high rewards and standard deviation that've been used to train a model in prior batches.
4
+
5
+ ## Usage
6
+
7
+ ```python
8
+ import torch
9
+ from trl.experimental.grpo_with_replay_buffer import GRPOWithReplayBufferConfig, GRPOWithReplayBufferTrainer
10
+ from datasets import load_dataset
11
+
12
+ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train")
13
+
14
+ # Guarantee that some rewards have 0 std
15
+ def custom_reward_func(completions, **kwargs):
16
+ if torch.rand(1).item() < 0.25:
17
+ return [0] * len(completions) # simulate some None rewards
18
+ else:
19
+ return torch.rand(len(completions)).tolist()
20
+
21
+ training_args = GRPOWithReplayBufferConfig(
22
+ output_dir="./tmp",
23
+ learning_rate=1e-4,
24
+ per_device_train_batch_size=4,
25
+ num_generations=4,
26
+ max_completion_length=8,
27
+ replay_buffer_size=8,
28
+ report_to="none",
29
+ )
30
+
31
+ trainer = GRPOWithReplayBufferTrainer(
32
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
33
+ reward_funcs=[custom_reward_func],
34
+ args=training_args,
35
+ train_dataset=dataset,
36
+ )
37
+
38
+ previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
39
+
40
+ trainer.train()
41
+ ```
42
+
43
+ ## GRPOWithReplayBufferTrainer
44
+
45
+ [[autodoc]] experimental.grpo_with_replay_buffer.GRPOWithReplayBufferTrainer
46
+ - train
47
+ - save_model
48
+ - push_to_hub
49
+
50
+ ## GRPOWithReplayBufferConfig
51
+
52
+ [[autodoc]] experimental.grpo_with_replay_buffer.GRPOWithReplayBufferConfig
53
+
54
+ ## ReplayBuffer
55
+
56
+ [[autodoc]] experimental.grpo_with_replay_buffer.ReplayBuffer
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/gspo_token.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GSPO-token
2
+
3
+ In the paper [Group Sequence Policy Optimization](https://huggingface.co/papers/2507.18071), the authors propose a token-level objective variant to GSPO, called GSPO-token. To use GSPO-token, you can use the `GRPOTrainer` class in `trl.experimental.gspo_token`.
4
+
5
+ ## Usage
6
+
7
+ ```python
8
+ from trl.experimental.gspo_token import GRPOTrainer
9
+ from trl import GRPOConfig
10
+
11
+ training_args = GRPOConfig(
12
+ importance_sampling_level="sequence_token",
13
+ ...
14
+ )
15
+ ```
16
+
17
+ > [!WARNING]
18
+ > To leverage GSPO-token, the user will need to provide the per-token advantage \\( \hat{A_{i,t}} \\) for each token \\( t \\) in the sequence \\( i \\) (i.e., make \\( \hat{A_{i,t}} \\) varies with \\( t \\)—which isn't the case here, \\( \hat{A_{i,t}}=\hat{A_{i}} \\)). Otherwise, GSPO-Token gradient is just equivalent to the original GSPO implementation.
19
+
20
+ ## GRPOTrainer
21
+
22
+ [[autodoc]] experimental.gspo_token.GRPOTrainer
23
+ - train
24
+ - save_model
25
+ - push_to_hub
tasks/tasksmith-4fc63afb85cd/tests/source/docs/source/index.md ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div style="text-align: center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/trl_banner_light.png">
4
+ <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/trl_banner_dark.png">
5
+ </picture>
6
+ </div>
7
+
8
+ # TRL - Transformers Reinforcement Learning
9
+
10
+ TRL is a full stack library where we provide a set of tools to train transformer language models with methods like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), Direct Preference Optimization (DPO), Reward Modeling, and more.
11
+ The library is integrated with 🤗 [transformers](https://github.com/huggingface/transformers).
12
+
13
+ ## 🎉 What's New
14
+
15
+ **OpenEnv Integration:** TRL now supports **[OpenEnv](https://huggingface.co/blog/openenv)**, the open-source framework from Meta for defining, deploying, and interacting with environments in reinforcement learning and agentic workflows.
16
+
17
+ Explore how to seamlessly integrate TRL with OpenEnv in our [dedicated documentation](openenv).
18
+
19
+ ## Taxonomy
20
+
21
+ Below is the current list of TRL trainers, organized by method type (⚡️ = vLLM support; 🧪 = experimental).
22
+
23
+ <div style="display: flex; justify-content: space-between; width: 100%; gap: 2rem;">
24
+ <div style="flex: 1; min-width: 0;">
25
+
26
+ ### Online methods
27
+
28
+ - [`GRPOTrainer`](grpo_trainer) ⚡️
29
+ - [`RLOOTrainer`](rloo_trainer) ⚡️
30
+ - [`OnlineDPOTrainer`](online_dpo_trainer) 🧪 ⚡️
31
+ - [`NashMDTrainer`](nash_md_trainer) 🧪 ⚡️
32
+ - [`PPOTrainer`](ppo_trainer) 🧪
33
+ - [`XPOTrainer`](xpo_trainer) 🧪 ⚡️
34
+
35
+ ### Reward modeling
36
+
37
+ - [`RewardTrainer`](reward_trainer)
38
+ - [`PRMTrainer`](prm_trainer) 🧪
39
+
40
+ </div>
41
+ <div style="flex: 1; min-width: 0;">
42
+
43
+ ### Offline methods
44
+
45
+ - [`SFTTrainer`](sft_trainer)
46
+ - [`DPOTrainer`](dpo_trainer)
47
+ - [`BCOTrainer`](bco_trainer) 🧪
48
+ - [`CPOTrainer`](cpo_trainer) 🧪
49
+ - [`KTOTrainer`](kto_trainer) 🧪
50
+ - [`ORPOTrainer`](orpo_trainer) 🧪
51
+
52
+ ### Knowledge distillation
53
+
54
+ - [`GKDTrainer`](gkd_trainer) 🧪
55
+ - [`MiniLLMTrainer`](minillm_trainer) 🧪
56
+
57
+ </div>
58
+ </div>
59
+
60
+ You can also explore TRL-related models, datasets, and demos in the [TRL Hugging Face organization](https://huggingface.co/trl-lib).
61
+
62
+ ## Learn
63
+
64
+ Learn post-training with TRL and other libraries in 🤗 [smol course](https://github.com/huggingface/smol-course).
65
+
66
+ ## Contents
67
+
68
+ The documentation is organized into the following sections:
69
+
70
+ - **Getting Started**: installation and quickstart guide.
71
+ - **Conceptual Guides**: dataset formats, training FAQ, and understanding logs.
72
+ - **How-to Guides**: reducing memory usage, speeding up training, distributing training, etc.
73
+ - **Integrations**: DeepSpeed, Liger Kernel, PEFT, etc.
74
+ - **Examples**: example overview, community tutorials, etc.
75
+ - **API**: trainers, utils, etc.
76
+
77
+ ## Blog posts
78
+
79
+ <div class="mt-10">
80
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
81
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/openenv">
82
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/openenv/thumbnail.png" alt="thumbnail" class="mt-0">
83
+ <p class="text-gray-500 text-sm">Published October 23, 2025</p>
84
+ <p class="text-gray-700">Building the Open Agent Ecosystem Together: Introducing OpenEnv</p>
85
+ </a>
86
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/trl-vlm-alignment">
87
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/trl_vlm/thumbnail.png" alt="thumbnail" class="mt-0">
88
+ <p class="text-gray-500 text-sm">Published on August 7, 2025</p>
89
+ <p class="text-gray-700">Vision Language Model Alignment in TRL ⚡️</p>
90
+ </a>
91
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/vllm-colocate">
92
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/vllm-colocate/thumbnail.png" alt="thumbnail" class="mt-0">
93
+ <p class="text-gray-500 text-sm">Published on June 3, 2025</p>
94
+ <p class="text-gray-700">NO GPU left behind: Unlocking Efficiency with Co-located vLLM in TRL</p>
95
+ </a>
96
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/liger-grpo">
97
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/liger-grpo/thumbnail.png" alt="thumbnail" class="mt-0">
98
+ <p class="text-gray-500 text-sm">Published on May 25, 2025</p>
99
+ <p class="text-gray-700">🐯 Liger GRPO meets TRL</p>
100
+ </a>
101
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/open-r1">
102
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/open-r1/thumbnails.png" alt="thumbnail" class="mt-0">
103
+ <p class="text-gray-500 text-sm">Published on January 28, 2025</p>
104
+ <p class="text-gray-700">Open-R1: a fully open reproduction of DeepSeek-R1</p>
105
+ </a>
106
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/dpo_vlm">
107
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/dpo_vlm/thumbnail.png" alt="thumbnail" class="mt-0">
108
+ <p class="text-gray-500 text-sm">Published on July 10, 2024</p>
109
+ <p class="text-gray-700">Preference Optimization for Vision Language Models with TRL</p>
110
+ </a>
111
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/putting_rl_back_in_rlhf_with_rloo">
112
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/putting_rl_back_in_rlhf_with_rloo/thumbnail.png" alt="thumbnail" class="mt-0">
113
+ <p class="text-gray-500 text-sm">Published on June 12, 2024</p>
114
+ <p class="text-gray-700">Putting RL back in RLHF</p>
115
+ </a>
116
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/trl-ddpo">
117
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/166_trl_ddpo/thumbnail.png" alt="thumbnail" class="mt-0">
118
+ <p class="text-gray-500 text-sm">Published on September 29, 2023</p>
119
+ <p class="text-gray-700">Finetune Stable Diffusion Models with DDPO via TRL</p>
120
+ </a>
121
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/dpo-trl">
122
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/157_dpo_trl/dpo_thumbnail.png" alt="thumbnail" class="mt-0">
123
+ <p class="text-gray-500 text-sm">Published on August 8, 2023</p>
124
+ <p class="text-gray-700">Fine-tune Llama 2 with DPO</p>
125
+ </a>
126
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/stackllama">
127
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/138_stackllama/thumbnail.png" alt="thumbnail" class="mt-0">
128
+ <p class="text-gray-500 text-sm">Published on April 5, 2023</p>
129
+ <p class="text-gray-700">StackLLaMA: A hands-on guide to train LLaMA with RLHF</p>
130
+ </a>
131
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/trl-peft">
132
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/133_trl_peft/thumbnail.png" alt="thumbnail" class="mt-0">
133
+ <p class="text-gray-500 text-sm">Published on March 9, 2023</p>
134
+ <p class="text-gray-700">Fine-tuning 20B LLMs with RLHF on a 24GB consumer GPU</p>
135
+ </a>
136
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/blog/rlhf">
137
+ <img src="https://raw.githubusercontent.com/huggingface/blog/main/assets/120_rlhf/thumbnail.png" alt="thumbnail" class="mt-0">
138
+ <p class="text-gray-500 text-sm">Published on December 9, 2022</p>
139
+ <p class="text-gray-700">Illustrating Reinforcement Learning from Human Feedback</p>
140
+ </a>
141
+ </div>
142
+ </div>
143
+
144
+ ## Talks
145
+
146
+ <div class="mt-10">
147
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
148
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/Fine%20tuning%20with%20TRL%20(Oct%2025).pdf">
149
+ <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/Fine%20tuning%20with%20TRL%20(Oct%2025).png" alt="thumbnail" class="mt-0">
150
+ <p class="text-gray-500 text-sm">Talk given on October 30, 2025</p>
151
+ <p class="text-gray-700">Fine tuning with TRL</p>
152
+ </a>
153
+ </div>
154
+ </div>