AdithyaSK HF Staff commited on
Commit
6fb8e66
·
verified ·
1 Parent(s): e546047

Stage Harbor release files 70001-70500

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-b1dd32dfa88b/environment/source/.devcontainer/devcontainer.json +29 -0
  2. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/ISSUE_TEMPLATE/bug-report.yml +63 -0
  3. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/PULL_REQUEST_TEMPLATE.md +47 -0
  4. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build-docker-images-release.yml +104 -0
  5. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_and_run_tests.yml +50 -0
  6. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_docker_images.yml +116 -0
  7. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_documentation.yml +18 -0
  8. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_pr_documentation.yml +17 -0
  9. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/fp8_runner.yml +37 -0
  10. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/gaudi3_scheduled.yml +87 -0
  11. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/integration_tests.yml +58 -0
  12. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/nightly.yml +233 -0
  13. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/pr_style_bot.yml +19 -0
  14. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/quality.yml +24 -0
  15. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/run_merge_tests.yml +188 -0
  16. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/self_hosted_integration_tests.yml +127 -0
  17. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/stale.yml +33 -0
  18. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/test.yml +70 -0
  19. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/test_imports.yml +55 -0
  20. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/trufflehog.yml +15 -0
  21. tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/upload_pr_documentation.yml +16 -0
  22. tasks/tasksmith-b1dd32dfa88b/environment/source/.gitignore +144 -0
  23. tasks/tasksmith-b1dd32dfa88b/environment/source/.pre-commit-config.yaml +13 -0
  24. tasks/tasksmith-b1dd32dfa88b/environment/source/CODE_OF_CONDUCT.md +129 -0
  25. tasks/tasksmith-b1dd32dfa88b/environment/source/CONTRIBUTING.md +249 -0
  26. tasks/tasksmith-b1dd32dfa88b/environment/source/Dockerfile +7 -0
  27. tasks/tasksmith-b1dd32dfa88b/environment/source/LICENSE +201 -0
  28. tasks/tasksmith-b1dd32dfa88b/environment/source/Makefile +101 -0
  29. tasks/tasksmith-b1dd32dfa88b/environment/source/README.md +277 -0
  30. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/README.md +5 -0
  31. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/big_model_inference/README.md +46 -0
  32. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/big_model_inference/big_model_inference.py +143 -0
  33. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/big_model_inference/measures_util.py +104 -0
  34. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/Dockerfile +12 -0
  35. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/ddp.py +123 -0
  36. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/distrib_deepspeed.py +161 -0
  37. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/fp8_utils.py +118 -0
  38. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/non_distributed.py +118 -0
  39. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/Dockerfile +12 -0
  40. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/README.md +32 -0
  41. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/ddp.py +158 -0
  42. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/distrib_deepspeed.py +213 -0
  43. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/fp8_utils.py +116 -0
  44. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/fsdp.py +173 -0
  45. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/non_distributed.py +145 -0
  46. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/Dockerfile +15 -0
  47. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/README.md +32 -0
  48. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/ddp.py +144 -0
  49. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/distrib_deepspeed.py +191 -0
  50. tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/fp8_utils.py +116 -0
tasks/tasksmith-b1dd32dfa88b/environment/source/.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // File only needed for VSCode users to have proper Docker based interpreters
2
+ {
3
+ "name": "accelerate_dev_environment",
4
+ "build": {
5
+ // ACTION NEEDED: comment/uncomment the relevant line depending on whether you are in a CPU/GPU environment
6
+ "dockerfile": "../docker/accelerate-cpu/Dockerfile"
7
+ // "dockerfile": "../docker/accelerate-gpu/Dockerfile"
8
+ },
9
+ "runArgs": [
10
+ // ACTION NEEDED: uncomment the next line if your local machine has GPUs available
11
+ // "--gpus", "all",
12
+ // Enable the docker container to access system resources
13
+ "--ipc", "host"
14
+ ],
15
+ "remoteEnv": {
16
+ "PYTHONPATH": "${containerEnv:PATH}:${containerWorkspaceFolder}"
17
+ },
18
+ "customizations": {
19
+ "vscode": {
20
+ "extensions": [
21
+ // Ensure we have IntelliSense in VSCode when running inside container
22
+ "ms-python.python"
23
+ ]
24
+ }
25
+ },
26
+ "workspaceFolder": "/workspaces/accelerate",
27
+ // Need git for VSCode to color code modifications. Only runs when building environment.
28
+ "onCreateCommand": "apt-get update && apt-get install -y git && pip install -e '.[dev]'"
29
+ }
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/ISSUE_TEMPLATE/bug-report.yml ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F41B Bug Report"
2
+ description: Submit a bug report to help us improve Accelerate
3
+ body:
4
+ - type: markdown
5
+ attributes:
6
+ value: |
7
+ Thanks for taking the time to submit a bug report! 🐛
8
+ If this is not a bug related to the Accelerate library directly, but instead a general question about your code or the library specifically please use the [forums](https://discuss.huggingface.co/c/accelerate/18).
9
+
10
+ - type: textarea
11
+ id: system-info
12
+ attributes:
13
+ label: System Info
14
+ description: Please share your accelerate configuration with us. You can run the command `accelerate env` and copy-paste its outputs below
15
+ render: Shell
16
+ placeholder: accelerate version, OS, python version, numpy version, torch version, and accelerate's configuration
17
+ validations:
18
+ required: true
19
+
20
+ - type: checkboxes
21
+ id: information-scripts-examples
22
+ attributes:
23
+ label: Information
24
+ description: 'The problem arises when using:'
25
+ options:
26
+ - label: "The official example scripts"
27
+ - label: "My own modified scripts"
28
+
29
+ - type: checkboxes
30
+ id: information-tasks
31
+ attributes:
32
+ label: Tasks
33
+ description: "The tasks I am working on are:"
34
+ options:
35
+ - label: "One of the scripts in the examples/ folder of Accelerate or an officially supported `no_trainer` script in the `examples` folder of the `transformers` repo (such as `run_no_trainer_glue.py`)"
36
+ - label: "My own task or dataset (give details below)"
37
+
38
+ - type: textarea
39
+ id: reproduction
40
+ validations:
41
+ required: true
42
+ attributes:
43
+ label: Reproduction
44
+ description: |
45
+ Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
46
+ If you have code snippets, error messages, stack traces please provide them here as well.
47
+ Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
48
+ Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
49
+
50
+ placeholder: |
51
+ Steps to reproduce the behavior:
52
+
53
+ 1.
54
+ 2.
55
+ 3.
56
+
57
+ - type: textarea
58
+ id: expected-behavior
59
+ validations:
60
+ required: true
61
+ attributes:
62
+ label: Expected behavior
63
+ description: "A clear and concise description of what you would expect to happen."
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What does this PR do?
2
+
3
+ <!--
4
+ Congratulations! You've made it this far! You're not quite done yet though.
5
+
6
+ Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.
7
+
8
+ Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.
9
+
10
+ Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
11
+ -->
12
+
13
+ <!-- Remove if not applicable -->
14
+
15
+ Fixes # (issue)
16
+
17
+
18
+ ## Before submitting
19
+ - [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
20
+ - [ ] Did you read the [contributor guideline](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md#submitting-a-pull-request-pr),
21
+ Pull Request section?
22
+ - [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
23
+ to it if that's the case.
24
+ - [ ] Did you make sure to update the documentation with your changes? Here are the
25
+ [documentation guidelines](https://github.com/huggingface/accelerate/tree/main/docs), and
26
+ [here are tips on formatting docstrings](https://github.com/huggingface/accelerate/tree/main/docs#writing-documentation---specification).
27
+ - [ ] Did you write any new necessary tests?
28
+
29
+
30
+ ## Who can review?
31
+
32
+ Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
33
+ members/contributors who may be interested in your PR.
34
+
35
+ <!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @
36
+
37
+ If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
38
+
39
+ - Big modeling: @SunMarc
40
+ - Fully-Sharded Data Parallism: @SunMarc @zach-huggingface
41
+ - DeepSpeed: @SunMarc @zach-huggingface
42
+ - Command Line Interface: @SunMarc @zach-huggingface
43
+ - Documentation: @SunMarc @zach-huggingface
44
+ - Core parts of the library: @BenjaminBossan @SunMarc @zach-huggingface
45
+ - Maintained examples: @SunMarc or @zach-huggingface
46
+
47
+ -->
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build-docker-images-release.yml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Docker images (releases)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ release:
6
+ types: [published]
7
+
8
+ concurrency:
9
+ group: docker-image-builds
10
+ cancel-in-progress: false
11
+
12
+ jobs:
13
+ get-version:
14
+ runs-on: ubuntu-latest
15
+ outputs:
16
+ version: ${{ steps.step1.outputs.version }}
17
+ steps:
18
+ - uses: actions/checkout@4
19
+ - id: step1
20
+ run: echo "version=$(python setup.py --version)" >> $GITHUB_OUTPUT
21
+
22
+ version-cpu:
23
+ name: "Latest Accelerate CPU [version]"
24
+ runs-on:
25
+ group: aws-general-8-plus
26
+ needs: get-version
27
+ steps:
28
+ - name: Set up Docker Buildx
29
+ uses: docker/setup-buildx-action@v2
30
+ - name: Login to DockerHub
31
+ uses: docker/login-action@v2
32
+ with:
33
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
34
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
35
+
36
+ - name: Build and Push CPU
37
+ uses: docker/build-push-action@v4
38
+ with:
39
+ file: docker/accelerate-cpu/Dockerfile
40
+ push: true
41
+ tags: huggingface/accelerate:cpu-release-${{ needs.get-version.outputs.version }}
42
+
43
+ version-cuda:
44
+ name: "Latest Accelerate GPU [version]"
45
+ runs-on:
46
+ group: aws-g6-4xlarge-plus
47
+ needs: get-version
48
+ steps:
49
+ - name: Set up Docker Buildx
50
+ uses: docker/setup-buildx-action@v2
51
+ - name: Login to DockerHub
52
+ uses: docker/login-action@v2
53
+ with:
54
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
55
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
56
+
57
+ - name: Build and Push GPU
58
+ uses: docker/build-push-action@v4
59
+ with:
60
+ file: docker/accelerate-gpu/Dockerfile
61
+ push: true
62
+ tags: huggingface/accelerate:gpu-release-${{needs.get-version.outputs.version}}
63
+
64
+ version-cuda-deepspeed:
65
+ name: "Latest Accelerate GPU DeepSpeed [version]"
66
+ runs-on:
67
+ group: aws-g6-4xlarge-plus
68
+ needs: get-version
69
+ steps:
70
+ - name: Set up Docker Buildx
71
+ uses: docker/setup-buildx-action@v2
72
+ - name: Login to DockerHub
73
+ uses: docker/login-action@v2
74
+ with:
75
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
76
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
77
+
78
+ - name: Build and Push GPU
79
+ uses: docker/build-push-action@v4
80
+ with:
81
+ file: docker/accelerate-gpu-deepspeed/Dockerfile
82
+ push: true
83
+ tags: huggingface/accelerate:gpu-deepspeed-release-${{needs.get-version.outputs.version}}
84
+
85
+ version-cuda-fp8-transformerengine:
86
+ name: "Latest Accelerate GPU FP8 TransformerEngine [version]"
87
+ runs-on:
88
+ group: aws-g6-4xlarge-plus
89
+ needs: get-version
90
+ steps:
91
+ - name: Set up Docker Buildx
92
+ uses: docker/setup-buildx-action@v2
93
+ - name: Login to DockerHub
94
+ uses: docker/login-action@v2
95
+ with:
96
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
97
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
98
+
99
+ - name: Build and Push GPU
100
+ uses: docker/build-push-action@v4
101
+ with:
102
+ file: docker/accelerate-gpu/Dockerfile
103
+ push: true
104
+ tags: huggingface/accelerate:gpu-fp8-transformerengine-release-${{needs.get-version.outputs.version}}
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_and_run_tests.yml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Trigger docker images and run tests
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ workflow_dispatch:
8
+
9
+ env:
10
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
11
+
12
+ jobs:
13
+ check-for-source:
14
+ runs-on: ubuntu-latest
15
+ name: Check if setup was changed
16
+ outputs:
17
+ changed: ${{ steps.was_changed.outputs.changed }}
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ with:
21
+ fetch-depth: "2"
22
+
23
+ - name: Get changed files
24
+ id: changed-files
25
+ uses: tj-actions/changed-files@3f54ebb830831fc121d3263c1857cfbdc310cdb9 #v42
26
+
27
+ - name: Was setup changed
28
+ id: was_changed
29
+ run: |
30
+ for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
31
+ if [ `basename "${file}"` == "setup.py" ]; then
32
+ echo "changed=1" >> $GITHUB_OUTPUT
33
+ fi
34
+ done
35
+
36
+ build-docker-containers:
37
+ needs: check-for-source
38
+ if: (github.event_name == 'push') && (needs.check-for-source.outputs.changed == '1')
39
+ uses: ./.github/workflows/build_docker_images.yml
40
+ secrets: inherit
41
+
42
+ run-merge-tests:
43
+ needs: build-docker-containers
44
+ if: always()
45
+ uses: ./.github/workflows/run_merge_tests.yml
46
+
47
+ run-integration-tests:
48
+ needs: build-docker-containers
49
+ if: always()
50
+ uses: ./.github/workflows/self_hosted_integration_tests.yml
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_docker_images.yml ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Docker images (scheduled)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ workflow_call:
6
+ schedule:
7
+ - cron: "0 1 * * *"
8
+
9
+ concurrency:
10
+ group: docker-image-builds
11
+ cancel-in-progress: false
12
+
13
+ jobs:
14
+ latest-cpu:
15
+ name: "Latest Accelerate CPU [dev]"
16
+ runs-on:
17
+ group: aws-general-8-plus
18
+ steps:
19
+ - name: Set up Docker Buildx
20
+ uses: docker/setup-buildx-action@v2
21
+ - name: Login to DockerHub
22
+ uses: docker/login-action@v2
23
+ with:
24
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
25
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
26
+ - name: Get current date
27
+ id: date
28
+ run: |
29
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
30
+ - name: Build and Push CPU
31
+ uses: docker/build-push-action@v4
32
+ with:
33
+ file: docker/accelerate-cpu/Dockerfile
34
+ push: true
35
+ tags: |
36
+ huggingface/accelerate:cpu-nightly
37
+ huggingface/accelerate:cpu-nightly-${{ env.date }}
38
+
39
+ latest-cuda:
40
+ name: "Latest Accelerate GPU [dev]"
41
+ runs-on:
42
+ group: aws-g6-4xlarge-plus
43
+ steps:
44
+ - name: Set up Docker Buildx
45
+ uses: docker/setup-buildx-action@v2
46
+ - name: Login to DockerHub
47
+ uses: docker/login-action@v2
48
+ with:
49
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
50
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
51
+ - name: Get current date
52
+ id: date
53
+ run: |
54
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
55
+ - name: Build and Push GPU
56
+ uses: docker/build-push-action@v4
57
+ with:
58
+ file: docker/accelerate-gpu/Dockerfile
59
+ push: true
60
+ tags: |
61
+ huggingface/accelerate:gpu-nightly
62
+ huggingface/accelerate:gpu-nightly-${{ env.date }}
63
+
64
+ latest-cuda-deepspeed:
65
+ name: "Latest Accelerate GPU DeepSpeed [dev]"
66
+ runs-on:
67
+ group: aws-g6-4xlarge-plus
68
+ steps:
69
+ - name: Set up Docker Buildx
70
+ uses: docker/setup-buildx-action@v2
71
+ - name: Login to DockerHub
72
+ uses: docker/login-action@v2
73
+ with:
74
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
75
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
76
+ - name: Get current date
77
+ id: date
78
+ run: |
79
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
80
+ - name: Build and Push GPU
81
+ uses: docker/build-push-action@v4
82
+ with:
83
+ file: docker/accelerate-gpu-deepspeed/Dockerfile
84
+ push: true
85
+ tags: |
86
+ huggingface/accelerate:gpu-deepspeed-nightly
87
+ huggingface/accelerate:gpu-deepspeed-nightly-${{ env.date }}
88
+
89
+ latest-cuda-fp8-transformerengine:
90
+ name: "Latest Accelerate GPU FP8 TransformerEngine [dev]"
91
+ runs-on:
92
+ group: aws-g6-4xlarge-plus
93
+ steps:
94
+ - name: Set up Docker Buildx
95
+ uses: docker/setup-buildx-action@v2
96
+ - name: Login to DockerHub
97
+ uses: docker/login-action@v2
98
+ with:
99
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
100
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
101
+ - name: Get current date
102
+ id: date
103
+ run: |
104
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
105
+ # Get the previous month
106
+ echo "base_year=$(date -d 'last month' '+%y')" >> $GITHUB_ENV
107
+ echo "base_month=$(date -d 'last month' '+%m')" >> $GITHUB_ENV
108
+ - name: Build and Push GPU
109
+ uses: docker/build-push-action@v4
110
+ with:
111
+ file: benchmarks/fp8/transformer_engine/Dockerfile
112
+ push: true
113
+ tags: huggingface/accelerate:gpu-fp8-transformerengine-nightly-${{ env.date }}
114
+ build-args: |
115
+ BASE_YEAR=${{ env.base_year }}
116
+ BASE_MONTH=${{ env.base_month }}
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_documentation.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build documentation
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - doc-builder*
8
+ - v*-release
9
+
10
+ jobs:
11
+ build:
12
+ uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main
13
+ with:
14
+ commit_sha: ${{ github.sha }}
15
+ package: accelerate
16
+ custom_container: huggingface/transformers-doc-builder
17
+ secrets:
18
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/build_pr_documentation.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build PR Documentation
2
+
3
+ on:
4
+ pull_request:
5
+
6
+ concurrency:
7
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
8
+ cancel-in-progress: true
9
+
10
+ jobs:
11
+ build:
12
+ uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main
13
+ with:
14
+ commit_sha: ${{ github.event.pull_request.head.sha }}
15
+ pr_number: ${{ github.event.number }}
16
+ package: accelerate
17
+ custom_container: huggingface/transformers-doc-builder
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/fp8_runner.yml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test FP8 Runner
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ env:
7
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
8
+ jobs:
9
+ set-prev-day:
10
+ runs-on: ubuntu-latest
11
+ outputs:
12
+ prev-day: ${{ steps.set-prev-day.outputs.prev-day }}
13
+ steps:
14
+ - name: Set PREV_DAY
15
+ id: set-prev-day
16
+ run: |
17
+ PREV_DAY=$(date -d "yesterday" '+%Y-%m-%d')
18
+ echo "prev-day=$PREV_DAY" >> $GITHUB_OUTPUT
19
+ run-fp8-tests:
20
+ needs: set-prev-day
21
+ runs-on:
22
+ group: aws-g6e-12xlarge
23
+ container:
24
+ image: huggingface/accelerate:gpu-fp8-transformerengine-nightly-${{ needs.set-prev-day.outputs.prev-day }}
25
+ options: --gpus all --shm-size "16gb"
26
+ steps:
27
+ - uses: actions/checkout@v3
28
+ - name: Install the library
29
+ run: |
30
+ pip install -e .[test_prod,test_fp8]
31
+ - name: Show installed libraries
32
+ run: |
33
+ pip freeze
34
+ - name: Run TE FP8 tests
35
+ run: |
36
+ python -m pytest -s -v ./tests/test_fp8.py
37
+
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/gaudi3_scheduled.yml ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Gaudi3 tests (scheduled)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule: # every day at 6 AM UTC
6
+ - cron: "0 6 * * *"
7
+
8
+ concurrency:
9
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ run-gaudi3-tests:
14
+ runs-on:
15
+ group: itac-bm-emr-gaudi3-dell-2gaudi
16
+
17
+ container:
18
+ image: docker://vault.habana.ai/gaudi-docker/1.21.1/ubuntu22.04/habanalabs/pytorch-installer-2.6.0:latest
19
+ options: --runtime=habana --shm-size=64G --cap-add=sys_nice --env HABANA_VISIBLE_DEVICES
20
+ env:
21
+ OMPI_MCA_btl_vader_single_copy_mechanism: none
22
+ PT_ENABLE_INT64_SUPPORT: 1
23
+ PT_HPU_LAZY_MODE: 0
24
+ RUN_SLOW: 1
25
+
26
+ steps:
27
+ - name: HL-SMI (1)
28
+ run: |
29
+ hl-smi
30
+ echo "HABANA_VISIBLE_DEVICES=${HABANA_VISIBLE_DEVICES}"
31
+ echo "HABANA_VISIBLE_MODULES=${HABANA_VISIBLE_MODULES}"
32
+
33
+ - name: Extract HPU visible modules
34
+ id: add-modules
35
+ run: |
36
+ export HABANA_VISIBLE_MODULES=$(hl-smi -Q module_id -f csv,noheader | tr '\n' ',' | sed 's/,$//')
37
+ echo "HABANA_VISIBLE_MODULES=${HABANA_VISIBLE_MODULES}" >> $GITHUB_ENV
38
+
39
+ - name: HL-SMI (2)
40
+ run: |
41
+ hl-smi
42
+ echo "HABANA_VISIBLE_DEVICES=${HABANA_VISIBLE_DEVICES}"
43
+ echo "HABANA_VISIBLE_MODULES=${HABANA_VISIBLE_MODULES}"
44
+
45
+ - name: Checkout to Accelerate
46
+ uses: actions/checkout@v4
47
+
48
+ - name: Install Accelerate with Transformers & DeepSpeed
49
+ run: |
50
+ pip install -e .[testing] \
51
+ git+https://github.com/HabanaAI/DeepSpeed.git@1.20.0 \
52
+ git+https://github.com/huggingface/transformers.git
53
+
54
+ - name: Run CLI tests
55
+ if: ${{ !cancelled() && (success() || failure()) }}
56
+ run: |
57
+ make test_cli
58
+
59
+ - name: Run Core tests
60
+ if: ${{ !cancelled() && (success() || failure()) }}
61
+ run: |
62
+ make test_core
63
+
64
+ - name: Run Big Modeling tests
65
+ if: ${{ !cancelled() && (success() || failure()) }}
66
+ run: |
67
+ make test_big_modeling
68
+
69
+ - name: Run DeepSpeed integration tests
70
+ if: ${{ !cancelled() && (success() || failure()) }}
71
+ run: |
72
+ make test_deepspeed
73
+
74
+ - name: Run FSDP integration tests
75
+ if: ${{ !cancelled() && (success() || failure()) }}
76
+ run: |
77
+ make test_fsdp
78
+
79
+ - name: Run TP integration tests
80
+ if: ${{ !cancelled() && (success() || failure()) }}
81
+ run: |
82
+ make test_tp
83
+
84
+ - name: Run Examples tests
85
+ if: ${{ !cancelled() && (success() || failure()) }}
86
+ run: |
87
+ make test_examples
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/integration_tests.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CI for specifically ensuring integrations work fine (`transformers` mainly)
2
+ # Useful tips:
3
+ # - New integrations to test should have its own job, and follow a strategy method where we check both
4
+ # the pypi and github versions.
5
+ # - When checking the latest release of the integration, use
6
+ # git checkout $(git describe --tags `git rev-list --tags --max-count=1`) to get the latest release.
7
+
8
+ name: Integration Tests
9
+
10
+ on:
11
+ pull_request:
12
+ paths:
13
+ - "src/**"
14
+ - "tests/**"
15
+ - ".github/**"
16
+ - "examples/**"
17
+ - "setup.py"
18
+ types: [opened, synchronize, reopened]
19
+
20
+ env:
21
+ HF_HOME: ~/hf_cache
22
+
23
+ jobs:
24
+ run-trainer-tests:
25
+ runs-on: ubuntu-latest
26
+ strategy:
27
+ fail-fast: false
28
+ steps:
29
+ - uses: actions/checkout@v4
30
+ - name: Set up python 3.9
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: 3.9
34
+ cache: 'pip'
35
+ cache-dependency-path: 'setup.py'
36
+
37
+ - name: Install Accelerate from source
38
+ run: |
39
+ pip install --upgrade pip
40
+ pip install -e .
41
+
42
+ - name: Clone and install transformers
43
+ run: |
44
+ cd ..
45
+ git clone https://github.com/huggingface/transformers
46
+ cd transformers
47
+ pip install .[torch,testing]
48
+
49
+ - name: Show installed libraries
50
+ run: |
51
+ pip freeze
52
+
53
+ - name: Run Trainer tests
54
+ env:
55
+ WANDB_DISABLED: true
56
+ run: |
57
+ cd ../transformers
58
+ pytest -sv tests/trainer
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/nightly.yml ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Self-hosted runner with slow tests (scheduled)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule:
6
+ - cron: "0 2 * * *"
7
+
8
+ env:
9
+ RUN_SLOW: "yes"
10
+ IS_GITHUB_CI: "1"
11
+ SLACK_API_TOKEN: ${{ secrets.SLACK_API_TOKEN }}
12
+
13
+
14
+ jobs:
15
+ run_core_tests_single_gpu:
16
+ runs-on:
17
+ group: aws-g6-4xlarge-plus
18
+ env:
19
+ CUDA_VISIBLE_DEVICES: "0"
20
+ TEST_TYPE: "single_gpu"
21
+ container:
22
+ image: huggingface/accelerate:gpu-nightly
23
+ options: --gpus all --shm-size "16gb"
24
+ defaults:
25
+ run:
26
+ shell: bash
27
+ steps:
28
+ - name: Update clone & pip install
29
+ run: |
30
+ source activate accelerate
31
+ git clone https://github.com/huggingface/accelerate;
32
+ cd accelerate;
33
+ git checkout ${{ github.sha }};
34
+ pip install -e . --no-deps
35
+ pip install pytest-reportlog tabulate
36
+
37
+ - name: Show installed libraries
38
+ run: |
39
+ source activate accelerate;
40
+ pip freeze
41
+
42
+ - name: Run test on GPUs
43
+ working-directory: accelerate
44
+ run: |
45
+ source activate accelerate
46
+ make test
47
+
48
+ - name: Run examples on GPUs
49
+ working-directory: accelerate
50
+ if: always()
51
+ run: |
52
+ source activate accelerate
53
+ pip uninstall comet_ml -y
54
+ make test_examples
55
+
56
+ - name: Generate Report
57
+ working-directory: accelerate
58
+ if: always()
59
+ run: |
60
+ pip install slack_sdk tabulate
61
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
62
+
63
+ run_deepspeed_tests_single_gpu:
64
+ runs-on:
65
+ group: aws-g6-4xlarge-plus
66
+ env:
67
+ CUDA_VISIBLE_DEVICES: "0"
68
+ TEST_TYPE: "single_gpu_deepspeed"
69
+ container:
70
+ image: huggingface/accelerate:gpu-deepspeed-nightly
71
+ options: --gpus all --shm-size "16gb"
72
+ defaults:
73
+ run:
74
+ shell: bash
75
+ steps:
76
+ - name: Update clone & pip install
77
+ run: |
78
+ source activate accelerate
79
+ git clone https://github.com/huggingface/accelerate;
80
+ cd accelerate;
81
+ git checkout ${{ github.sha }};
82
+ pip install -e . --no-deps
83
+ pip install pytest-reportlog tabulate
84
+
85
+ - name: Show installed libraries
86
+ run: |
87
+ source activate accelerate;
88
+ pip freeze
89
+
90
+ - name: Run test on GPUs
91
+ working-directory: accelerate
92
+ run: |
93
+ source activate accelerate
94
+ make test_deepspeed
95
+
96
+ - name: Run Integration tests on GPUs
97
+ working-directory: accelerate
98
+ if: always()
99
+ run: |
100
+ source activate accelerate
101
+ make test_integrations
102
+
103
+ - name: Run examples on GPUs
104
+ working-directory: accelerate
105
+ if: always()
106
+ run: |
107
+ source activate accelerate
108
+ pip uninstall comet_ml -y
109
+ make test_examples
110
+
111
+ - name: Generate Report
112
+ working-directory: accelerate
113
+ if: always()
114
+ run: |
115
+ pip install slack_sdk tabulate
116
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
117
+
118
+ run_core_tests_multi_gpu:
119
+ runs-on:
120
+ group: aws-g6-12xlarge-plus
121
+ env:
122
+ CUDA_VISIBLE_DEVICES: "0,1"
123
+ TEST_TYPE: "multi_gpu"
124
+ container:
125
+ image: huggingface/accelerate:gpu-nightly
126
+ options: --gpus all --shm-size "16gb"
127
+ defaults:
128
+ run:
129
+ shell: bash
130
+ steps:
131
+ - name: Update clone
132
+ run: |
133
+ source activate accelerate
134
+ git clone https://github.com/huggingface/accelerate;
135
+ cd accelerate;
136
+ git checkout ${{ github.sha }};
137
+ pip install -e . --no-deps
138
+ pip install pytest-reportlog tabulate
139
+
140
+ - name: Show installed libraries
141
+ run: |
142
+ source activate accelerate;
143
+ pip freeze
144
+
145
+ - name: Run core and big modeling tests on GPUs
146
+ working-directory: accelerate
147
+ run: |
148
+ source activate accelerate
149
+ make test_core
150
+ make test_big_modeling
151
+ make test_cli
152
+
153
+ - name: Run Integration tests on GPUs
154
+ working-directory: accelerate
155
+ if: always()
156
+ run: |
157
+ source activate accelerate
158
+ make test_integrations
159
+
160
+ - name: Run examples on GPUs
161
+ working-directory: accelerate
162
+ if: always()
163
+ run: |
164
+ source activate accelerate
165
+ pip uninstall comet_ml -y
166
+ make test_examples
167
+
168
+ - name: Generate Report
169
+ working-directory: accelerate
170
+ if: always()
171
+ run: |
172
+ pip install slack_sdk tabulate
173
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
174
+
175
+ run_deepspeed_tests_multi_gpu:
176
+ runs-on:
177
+ group: aws-g6-12xlarge-plus
178
+ env:
179
+ CUDA_VISIBLE_DEVICES: "0,1"
180
+ TEST_TYPE: "multi_gpu_deepspeed"
181
+ container:
182
+ image: huggingface/accelerate:gpu-deepspeed-nightly
183
+ options: --gpus all --shm-size "16gb"
184
+ defaults:
185
+ run:
186
+ shell: bash
187
+ steps:
188
+ - name: Update clone
189
+ run: |
190
+ source activate accelerate
191
+ git clone https://github.com/huggingface/accelerate;
192
+ cd accelerate;
193
+ git checkout ${{ github.sha }};
194
+ pip install -e . --no-deps
195
+ pip install pytest-reportlog tabulate
196
+
197
+ - name: Show installed libraries
198
+ run: |
199
+ source activate accelerate;
200
+ pip freeze
201
+
202
+ - name: Run DeepSpeed tests
203
+ working-directory: accelerate
204
+ run: |
205
+ source activate accelerate
206
+ make test_deepspeed
207
+
208
+ - name: Run Integration tests on GPUs
209
+ working-directory: accelerate
210
+ if: always()
211
+ run: |
212
+ source activate accelerate
213
+ make test_integrations
214
+
215
+ - name: Run examples on GPUs
216
+ working-directory: accelerate
217
+ if: always()
218
+ run: |
219
+ source activate accelerate
220
+ pip uninstall comet_ml -y
221
+ make test_examples
222
+
223
+ - name: Generate Report
224
+ working-directory: accelerate
225
+ if: always()
226
+ run: |
227
+ pip install slack_sdk tabulate
228
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
229
+
230
+
231
+ run-integration-tests:
232
+ if: always()
233
+ uses: ./.github/workflows/self_hosted_integration_tests.yml
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/pr_style_bot.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To run this bot, comment "@bot /style" on a PR
2
+ name: Style Bot
3
+
4
+ on:
5
+ issue_comment:
6
+ types: [created]
7
+
8
+ permissions:
9
+ contents: write
10
+ pull-requests: write
11
+
12
+ jobs:
13
+ style:
14
+ uses: huggingface/huggingface_hub/.github/workflows/style-bot-action.yml@main
15
+ with:
16
+ python_quality_dependencies: "[quality]"
17
+ style_command_type: "default"
18
+ secrets:
19
+ bot_token: ${{ secrets.GITHUB_TOKEN }}
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/quality.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Quality Check
2
+
3
+ on: [pull_request]
4
+
5
+ jobs:
6
+ quality:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v4
10
+ - name: Set up Python 3.9
11
+ uses: actions/setup-python@v5
12
+ with:
13
+ python-version: 3.9
14
+ cache: 'pip'
15
+ cache-dependency-path: 'setup.py'
16
+ - name: Install Python dependencies
17
+ run: pip install -e .[quality]
18
+ - name: Run Quality check
19
+ run: make quality
20
+ - name: Check if failure
21
+ if: ${{ failure() }}
22
+ run: |
23
+ echo "Quality check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and rerun 'make style; make quality;'" >> $GITHUB_STEP_SUMMARY
24
+
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/run_merge_tests.yml ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Self-hosted runner tests (push to "main")
2
+
3
+ on:
4
+ workflow_call:
5
+ workflow_dispatch:
6
+
7
+ env:
8
+ TESTING_MOCKED_DATALOADERS: "1"
9
+ IS_GITHUB_CI: "1"
10
+
11
+ jobs:
12
+ run_core_tests_single_gpu:
13
+ runs-on:
14
+ group: aws-g6-4xlarge-plus
15
+ env:
16
+ CUDA_VISIBLE_DEVICES: "0"
17
+ container:
18
+ image: huggingface/accelerate:gpu-nightly
19
+ options: --gpus all --shm-size "16gb"
20
+ defaults:
21
+ run:
22
+ shell: bash
23
+ steps:
24
+ - name: Install accelerate
25
+ run: |
26
+ source activate accelerate;
27
+ git clone https://github.com/huggingface/accelerate;
28
+ cd accelerate;
29
+ git checkout ${{ github.sha }};
30
+ pip install -e .[testing,test_trackers] -U;
31
+ pip install pytest-reportlog tabulate ;
32
+
33
+ - name: Show installed libraries
34
+ run: |
35
+ source activate accelerate;
36
+ pip freeze
37
+
38
+ - name: Run CLI tests (use make cli)
39
+ working-directory: accelerate
40
+ run: |
41
+ source activate accelerate;
42
+ make test_cli
43
+
44
+ - name: Run test on GPUs
45
+ working-directory: accelerate
46
+ if: always()
47
+ run: |
48
+ source activate accelerate;
49
+ make test
50
+ - name: Run examples on GPUs
51
+ working-directory: accelerate
52
+ if: always()
53
+ run: |
54
+ source activate accelerate;
55
+ pip uninstall comet_ml -y;
56
+ make test_examples
57
+
58
+ - name: Generate Report
59
+ working-directory: accelerate
60
+ if: always()
61
+ run: |
62
+ pip install tabulate;
63
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
64
+
65
+ run_deepspeed_tests_single_gpu:
66
+ runs-on:
67
+ group: aws-g6-4xlarge-plus
68
+ env:
69
+ CUDA_VISIBLE_DEVICES: "0"
70
+ container:
71
+ image: huggingface/accelerate:gpu-deepspeed-nightly
72
+ options: --gpus all --shm-size "16gb"
73
+ defaults:
74
+ run:
75
+ shell: bash
76
+ steps:
77
+ - name: Install accelerate
78
+ run: |
79
+ source activate accelerate;
80
+ git clone https://github.com/huggingface/accelerate;
81
+ cd accelerate;
82
+ git checkout ${{ github.sha }};
83
+ pip install -e .[testing,test_trackers] -U;
84
+ pip install pytest-reportlog tabulate ;
85
+
86
+ - name: Show installed libraries
87
+ run: |
88
+ source activate accelerate;
89
+ pip freeze
90
+
91
+ - name: Run test on GPUs
92
+ working-directory: accelerate
93
+ if: always()
94
+ run: |
95
+ source activate accelerate;
96
+ make test_deepspeed
97
+
98
+ - name: Generate Report
99
+ working-directory: accelerate
100
+ if: always()
101
+ run: |
102
+ pip install tabulate;
103
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
104
+
105
+ run_core_tests_multi_gpu:
106
+ runs-on:
107
+ group: aws-g6-12xlarge-plus
108
+ env:
109
+ CUDA_VISIBLE_DEVICES: 0,1
110
+ container:
111
+ image: huggingface/accelerate:gpu-nightly
112
+ options: --gpus all --shm-size "16gb"
113
+ defaults:
114
+ run:
115
+ shell: bash
116
+ steps:
117
+ - name: Update clone
118
+ run: |
119
+ source activate accelerate;
120
+ git clone https://github.com/huggingface/accelerate;
121
+ cd accelerate;
122
+ git checkout ${{ github.sha }};
123
+ pip install -e .[testing,test_trackers] -U;
124
+ pip install pytest-reportlog tabulate
125
+
126
+ - name: Show installed libraries
127
+ run: |
128
+ source activate accelerate;
129
+ pip freeze
130
+
131
+ - name: Run test on GPUs
132
+ working-directory: accelerate
133
+ run: |
134
+ source activate accelerate;
135
+ make test
136
+
137
+ - name: Run examples on GPUs
138
+ working-directory: accelerate
139
+ if: always()
140
+ run: |
141
+ source activate accelerate;
142
+ pip uninstall comet_ml -y;
143
+ make test_examples
144
+
145
+ - name: Generate Report
146
+ working-directory: accelerate
147
+ if: always()
148
+ run: |
149
+ source activate accelerate;
150
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
151
+
152
+ run_deepspeed_tests_multi_gpu:
153
+ runs-on:
154
+ group: aws-g6-12xlarge-plus
155
+ container:
156
+ image: huggingface/accelerate:gpu-deepspeed-nightly
157
+ options: --gpus all --shm-size "16gb"
158
+ defaults:
159
+ run:
160
+ shell: bash
161
+ steps:
162
+ - name: Install accelerate
163
+ run: |
164
+ source activate accelerate;
165
+ git clone https://github.com/huggingface/accelerate;
166
+ cd accelerate;
167
+ git checkout ${{ github.sha }};
168
+ pip install -e .[testing,test_trackers] -U;
169
+ pip install pytest-reportlog tabulate ;
170
+
171
+ - name: Show installed libraries
172
+ run: |
173
+ source activate accelerate;
174
+ pip freeze
175
+
176
+ - name: Run test on GPUs
177
+ working-directory: accelerate
178
+ if: always()
179
+ run: |
180
+ source activate accelerate;
181
+ make test_deepspeed
182
+
183
+ - name: Generate Report
184
+ working-directory: accelerate
185
+ if: always()
186
+ run: |
187
+ pip install tabulate;
188
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/self_hosted_integration_tests.yml ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CI for specifically ensuring integrations work fine (`transformers` mainly) on GPUs
2
+ # Useful tips:
3
+ # - `working-directory` should be set to the root of the repo, which is cloned on the actual CI runner.
4
+ # It follows the directory structure of `actions-runner/_work/{repo_name}/{repo_name}/{cloned_repo} on
5
+ # prem, but in Actions setting `working-directory` looks just in the `{repo_name}` level.
6
+ # - New integrations to test should have its own job, and follow a strategy method where we check both
7
+ # the pypi and github versions.
8
+ # - Workflow call lets this be called from `build_and_run_tests.yml`
9
+ # - When using a docker container, it's recommended to set `--shm-size`, we use 16gb.
10
+ name: Integration Tests (push to "main")
11
+
12
+ on:
13
+ workflow_call:
14
+ workflow_dispatch:
15
+
16
+ env:
17
+ HF_HOME: ~/hf_cache
18
+
19
+ defaults:
20
+ run:
21
+ shell: bash
22
+
23
+ jobs:
24
+ run-trainer-tests:
25
+ container:
26
+ image: huggingface/accelerate:gpu-deepspeed-nightly
27
+ options: --gpus all --shm-size "16gb"
28
+ runs-on:
29
+ group: aws-g6-12xlarge-plus
30
+ strategy:
31
+ fail-fast: false
32
+ matrix:
33
+ cuda_visible_devices: [
34
+ "0",
35
+ "0,1"
36
+ ]
37
+ steps:
38
+ - name: Install transformers
39
+ run: |
40
+ source activate accelerate;
41
+ git clone https://github.com/huggingface/transformers --depth 1;
42
+ cd transformers;
43
+ pip install .[torch,deepspeed-testing];
44
+ cd ..;
45
+
46
+ - name: Install accelerate
47
+ run: |
48
+ source activate accelerate;
49
+ git clone https://github.com/huggingface/accelerate;
50
+ cd accelerate;
51
+ git checkout ${{ github.sha }} ;
52
+ pip install -e .[testing];
53
+ pip uninstall comet_ml wandb dvclive -y
54
+ cd ..;
55
+
56
+ - name: Show installed libraries
57
+ run: |
58
+ source activate accelerate;
59
+ pip freeze
60
+
61
+ - name: Run trainer tests
62
+ working-directory: transformers/
63
+ env:
64
+ CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }}
65
+ WANDB_DISABLED: true
66
+ run: |
67
+ source activate accelerate;
68
+ pytest -sv tests/trainer
69
+
70
+ - name: Run deepspeed tests
71
+ working-directory: transformers/
72
+ env:
73
+ CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }}
74
+ WANDB_DISABLED: true
75
+ if: always()
76
+ run: |
77
+ source activate accelerate;
78
+ pytest -sv tests/deepspeed
79
+
80
+ - name: Run transformers examples tests
81
+ working-directory: transformers/
82
+ env:
83
+ CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }}
84
+ WANDB_DISABLED: true
85
+ run: |
86
+ source activate accelerate
87
+ pip install -r examples/pytorch/_tests_requirements.txt
88
+ pytest -sv examples/pytorch/test_accelerate_examples.py examples/pytorch/test_pytorch_examples.py
89
+
90
+ run-skorch-tests:
91
+ container:
92
+ image: huggingface/accelerate:gpu-nightly
93
+ options: --gpus all --shm-size "16gb"
94
+ runs-on:
95
+ group: aws-g6-12xlarge-plus
96
+ strategy:
97
+ fail-fast: false
98
+ steps:
99
+ - name: Install accelerate
100
+ run:
101
+ source activate accelerate;
102
+ git clone https://github.com/huggingface/accelerate;
103
+ cd accelerate;
104
+ git checkout ${{ github.sha }};
105
+ pip install -e .[testing];
106
+ cd ..
107
+
108
+ - name: Install skorch
109
+ run: |
110
+ source activate accelerate
111
+ git clone https://github.com/skorch-dev/skorch;
112
+ cd skorch;
113
+ git config --global --add safe.directory '*'
114
+ git checkout master && git pull
115
+ pip install .[testing]
116
+ pip install flaky
117
+
118
+ - name: Show installed libraries
119
+ run: |
120
+ source activate accelerate;
121
+ pip freeze
122
+
123
+ - name: Run skorch tests
124
+ working-directory: skorch/
125
+ run: |
126
+ source activate accelerate;
127
+ pytest -sv -k TestAccelerate
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/stale.yml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Stale Bot
2
+
3
+ on:
4
+ schedule:
5
+ - cron: "0 15 * * *"
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ close_stale_issues:
10
+ name: Close Stale Issues
11
+ if: github.repository == 'huggingface/accelerate'
12
+ runs-on: ubuntu-latest
13
+ permissions:
14
+ issues: write
15
+ pull-requests: write
16
+ env:
17
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+
21
+ - name: Setup Python
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: 3.9
25
+ cache: 'pip'
26
+ cache-dependency-path: 'setup.py'
27
+
28
+ - name: Install requirements
29
+ run: |
30
+ pip install PyGithub
31
+ - name: Close stale issues
32
+ run: |
33
+ python utils/stale.py
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/test.yml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Tests
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ - "src/**"
7
+ - "tests/**"
8
+ - ".github/**"
9
+ - "examples/**"
10
+ - "setup.py"
11
+ types: [opened, synchronize, reopened]
12
+
13
+ env:
14
+ HF_HOME: ~/hf_cache
15
+ TESTING_MOCKED_DATALOADERS: "1"
16
+ IS_GITHUB_CI: "1"
17
+
18
+ jobs:
19
+ run-tests:
20
+ runs-on: ubuntu-latest
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ pytorch-version: [
25
+ latest,
26
+ minimum,
27
+ ]
28
+ test-kind: [
29
+ test_prod,
30
+ test_core,
31
+ test_cli,
32
+ test_big_modeling,
33
+ test_deepspeed,
34
+ test_fsdp,
35
+ test_example_differences,
36
+ test_checkpoint_step,
37
+ test_checkpoint_epoch,
38
+ test_rest
39
+ ]
40
+ steps:
41
+ - uses: actions/checkout@v4
42
+ - name: Set up python 3.9
43
+ uses: actions/setup-python@v5
44
+ with:
45
+ python-version: 3.9
46
+ cache: 'pip'
47
+ cache-dependency-path: 'setup.py'
48
+
49
+ - name: Install the library
50
+ run: |
51
+ if [[ ${{ matrix.test-kind }} = test_prod ]]; then pip install -e .[test_prod]; fi
52
+ if [[ ${{ matrix.test-kind }} != test_prod ]]; then pip install -e .[testing,test_trackers]; fi
53
+ if [[ ${{ matrix.test-kind }} = test_rest ]]; then pip uninstall comet_ml -y; fi
54
+ if [[ ${{ matrix.pytorch-version }} = minimum ]]; then pip install torchvision==0.18.1 torch==2.3.1; fi
55
+ pip install pytest-reportlog tabulate setuptools importlib_metadata
56
+
57
+ - name: Show installed libraries
58
+ run: |
59
+ pip freeze
60
+
61
+ - name: Run Tests
62
+ env:
63
+ PYTORCH_VERSION: ${{ matrix.pytorch-version }}
64
+ run: |
65
+ make ${{ matrix.test-kind }}
66
+
67
+ - name: Generate Report
68
+ if: always()
69
+ run: |
70
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/test_imports.yml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Import Tests
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ - "src/**"
7
+ - "tests/**"
8
+ - ".github/**"
9
+ - "examples/**"
10
+ - "setup.py"
11
+ types: [opened, synchronize, reopened]
12
+
13
+ env:
14
+ HF_HOME: ~/hf_cache
15
+ TESTING_MOCKED_DATALOADERS: "1"
16
+ IS_GITHUB_CI: "1"
17
+
18
+ jobs:
19
+ run-tests:
20
+ runs-on: ubuntu-latest
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ pytorch-version: [
25
+ latest,
26
+ minimum,
27
+ ]
28
+ steps:
29
+ - uses: actions/checkout@v4
30
+ - name: Set up python 3.9
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: 3.9
34
+ cache: 'pip'
35
+ cache-dependency-path: 'setup.py'
36
+
37
+ - name: Install the library
38
+ run: |
39
+ pip install -e .
40
+ pip install pytest-reportlog tabulate setuptools git+https://github.com/muellerzr/import-timer
41
+
42
+ - name: Show installed libraries
43
+ run: |
44
+ pip freeze
45
+
46
+ - name: Run Import Tests
47
+ env:
48
+ PYTORCH_VERSION: ${{ matrix.pytorch-version }}
49
+ run: |
50
+ pytest -sv tests/test_imports.py
51
+
52
+ - name: Generate Report
53
+ if: always()
54
+ run: |
55
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-b1dd32dfa88b/environment/source/.github/workflows/trufflehog.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@v4
12
+ with:
13
+ fetch-depth: 0
14
+ - name: Secret Scanning
15
+ uses: trufflesecurity/trufflehog@main
tasks/tasksmith-b1dd32dfa88b/environment/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: accelerate
14
+ secrets:
15
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
16
+ comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }}
tasks/tasksmith-b1dd32dfa88b/environment/source/.gitignore ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
130
+
131
+ # VSCode
132
+ .vscode
133
+
134
+ # IntelliJ
135
+ .idea
136
+
137
+ # Mac .DS_Store
138
+ .DS_Store
139
+
140
+ # More test things
141
+ wandb
142
+
143
+ # ruff
144
+ .ruff_cache
tasks/tasksmith-b1dd32dfa88b/environment/source/.pre-commit-config.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ rev: v0.2.1
4
+ hooks:
5
+ - id: ruff
6
+ args:
7
+ - --fix
8
+ - id: ruff-format
9
+ - repo: https://github.com/pre-commit/pre-commit-hooks
10
+ rev: v4.5.0
11
+ hooks:
12
+ - id: check-merge-conflict
13
+ - id: check-yaml
tasks/tasksmith-b1dd32dfa88b/environment/source/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, religion, or sexual identity
11
+ 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
27
+ overall community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or
32
+ advances of 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
36
+ address, 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
87
+ of 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
94
+ permanent 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
114
+ the community.
115
+
116
+ ## Attribution
117
+
118
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119
+ version 2.0, available at
120
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
121
+
122
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
123
+ enforcement ladder](https://github.com/mozilla/diversity).
124
+
125
+ [homepage]: https://www.contributor-covenant.org
126
+
127
+ For answers to common questions about this code of conduct, see the FAQ at
128
+ https://www.contributor-covenant.org/faq. Translations are available at
129
+ https://www.contributor-covenant.org/translations.
tasks/tasksmith-b1dd32dfa88b/environment/source/CONTRIBUTING.md ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # How to contribute to 🤗 Accelerate?
18
+
19
+ Everyone is welcome to contribute, and we value everybody's contribution. Code
20
+ is thus not the only way to help the community. Answering questions, helping
21
+ others, reaching out and improving the documentations are immensely valuable to
22
+ the community.
23
+
24
+ It also helps us if you spread the word: reference the library from blog posts
25
+ on the awesome projects it made possible, shout out on Twitter every time it has
26
+ helped you, or simply star the repo to say "thank you".
27
+
28
+ Whichever way you choose to contribute, please be mindful to respect our
29
+ [code of conduct](https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md).
30
+
31
+ ## You can contribute in so many ways!
32
+
33
+ Some of the ways you can contribute to Accelerate:
34
+ * Fixing outstanding issues with the existing code;
35
+ * Contributing to the examples or to the documentation;
36
+ * Submitting issues related to bugs or desired new features.
37
+
38
+ ## Submitting a new issue or feature request
39
+
40
+ Do your best to follow these guidelines when submitting an issue or a feature
41
+ request. It will make it easier for us to come back to you quickly and with good
42
+ feedback.
43
+
44
+ ### Did you find a bug?
45
+
46
+ The 🤗 Accelerate library is robust and reliable thanks to the users who notify us of
47
+ the problems they encounter. So thank you for reporting an issue.
48
+
49
+ First, we would really appreciate it if you could **make sure the bug was not
50
+ already reported** (use the search bar on Github under Issues).
51
+
52
+ Did not find it? :( So we can act quickly on it, please follow these steps:
53
+
54
+ * Include your **OS type and version**, the versions of **Python** and **PyTorch**.
55
+ * A short, self-contained, code snippet that allows us to reproduce the bug in
56
+ less than 30s;
57
+ * Provide the with your Accelerate configuration (located by default in `~/.cache/huggingface/accelerate/default_config.yaml`)
58
+
59
+ ### Do you want a new feature?
60
+
61
+ A good feature request addresses the following points:
62
+
63
+ 1. Motivation first:
64
+ * Is it related to a problem/frustration with the library? If so, please explain
65
+ why. Providing a code snippet that demonstrates the problem is best.
66
+ * Is it related to something you would need for a project? We'd love to hear
67
+ about it!
68
+ * Is it something you worked on and think could benefit the community?
69
+ Awesome! Tell us what problem it solved for you.
70
+ 2. Write a *full paragraph* describing the feature;
71
+ 3. Provide a **code snippet** that demonstrates its future use;
72
+ 4. In case this is related to a paper, please attach a link;
73
+ 5. Attach any additional information (drawings, screenshots, etc.) you think may help.
74
+
75
+ If your issue is well written we're already 80% of the way there by the time you
76
+ post it.
77
+
78
+ ## Submitting a pull request (PR)
79
+
80
+ Before writing code, we strongly advise you to search through the existing PRs or
81
+ issues to make sure that nobody is already working on the same thing. If you are
82
+ unsure, it is always a good idea to open an issue to get some feedback.
83
+
84
+ You will need basic `git` proficiency to be able to contribute to
85
+ 🤗 Accelerate. `git` is not the easiest tool to use but it has the greatest
86
+ manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
87
+ Git](https://git-scm.com/book/en/v2) is a very good reference.
88
+
89
+ Follow these steps to start contributing:
90
+
91
+ 1. Fork the [repository](https://github.com/huggingface/accelerate) by
92
+ clicking on the 'Fork' button on the repository's page. This creates a copy of the code
93
+ under your GitHub user account.
94
+
95
+ 2. Clone your fork to your local disk, and add the base repository as a remote. The following command
96
+ assumes you have your public SSH key uploaded to GitHub. See the following guide for more
97
+ [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository).
98
+
99
+ ```bash
100
+ $ git clone git@github.com:<your Github handle>/accelerate.git
101
+ $ cd accelerate
102
+ $ git remote add upstream https://github.com/huggingface/accelerate.git
103
+ ```
104
+
105
+ 3. Create a new branch to hold your development changes, and do this for every new PR you work on.
106
+
107
+ Start by synchronizing your `main` branch with the `upstream/main` branch (ore details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)):
108
+
109
+ ```bash
110
+ $ git checkout main
111
+ $ git fetch upstream
112
+ $ git merge upstream/main
113
+ ```
114
+
115
+ Once your `main` branch is synchronized, create a new branch from it:
116
+
117
+ ```bash
118
+ $ git checkout -b a-descriptive-name-for-my-changes
119
+ ```
120
+
121
+ **Do not** work on the `main` branch.
122
+
123
+ 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:
124
+
125
+ ```bash
126
+ $ pip install -e ".[dev]"
127
+ ```
128
+
129
+ This will install all testing and linting/code quality dependencies for the library (see `quality`, `test_dev`,
130
+ `test_prod` targets in [`setup.py`](./setup.py)).
131
+
132
+ (If accelerate was already installed in the virtual environment, remove
133
+ it with `pip uninstall accelerate` before reinstalling it in editable
134
+ mode with the `-e` flag).
135
+
136
+ Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using
137
+ the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers).
138
+
139
+ 5. Develop the features on your branch.
140
+
141
+ As you work on the features, you should make sure that the test suite
142
+ passes. You should run the tests impacted by your changes like this (see
143
+ below an explanation regarding the environment variable):
144
+
145
+ ```bash
146
+ $ pytest tests/<TEST_TO_RUN>.py
147
+ ```
148
+
149
+ > For the following commands leveraging the `make` utility, we recommend using the WSL system when running on
150
+ > Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about).
151
+
152
+ You can also run the full suite with the following command.
153
+
154
+ ```bash
155
+ $ make test
156
+ ```
157
+
158
+ `accelerate` relies on `ruff` to format its source code
159
+ consistently. After you make changes, apply automatic style corrections and code verifications
160
+ that can't be automated in one go with:
161
+
162
+ This target is also optimized to only work with files modified by the PR you're working on.
163
+
164
+ If you prefer to run the checks one after the other, the following command apply the
165
+ style corrections:
166
+
167
+ ```bash
168
+ $ make style
169
+ ```
170
+
171
+ `accelerate` also uses a few custom scripts to check for coding mistakes. Quality
172
+ control runs in CI, however you can also run the same checks with:
173
+
174
+ ```bash
175
+ $ make quality
176
+ ```
177
+
178
+ You can also set up [`pre-commit`](https://pre-commit.com/) to run these checks
179
+ automatically as Git commit hooks.
180
+
181
+ ```bash
182
+ $ pip install pre-commit
183
+ $ pre-commit install
184
+ ```
185
+
186
+ Once you're happy with your changes, add changed files using `git add` and
187
+ make a commit with `git commit` to record your changes locally:
188
+
189
+ ```bash
190
+ $ git add modified_file.py
191
+ $ git commit
192
+ ```
193
+
194
+ Please write [good commit messages](https://chris.beams.io/posts/git-commit/).
195
+
196
+ It is a good idea to sync your copy of the code with the original
197
+ repository regularly. This way you can quickly account for changes:
198
+
199
+ ```bash
200
+ $ git fetch upstream
201
+ $ git rebase upstream/main
202
+ ```
203
+
204
+ Push the changes to your account using:
205
+
206
+ ```bash
207
+ $ git push -u origin a-descriptive-name-for-my-changes
208
+ ```
209
+
210
+ 6. Once you are satisfied (**and the checklist below is happy too**), go to the
211
+ webpage of your fork on GitHub. Click on 'Pull request' to send your changes
212
+ to the project maintainers for review.
213
+
214
+ 7. It's ok if maintainers ask you for changes. It happens to core contributors
215
+ too! So everyone can see the changes in the Pull request, work in your local
216
+ branch and push the changes to your fork. They will automatically appear in
217
+ the pull request.
218
+
219
+
220
+ ### Checklist
221
+
222
+ 1. The title of your pull request should be a summary of its contribution;
223
+ 2. If your pull request addresses an issue, please mention the issue number in
224
+ the pull request description to make sure they are linked (and people
225
+ consulting the issue know you are working on it);
226
+ 3. To indicate a work in progress please prefix the title with `[WIP]`, or mark
227
+ the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate
228
+ it from PRs ready to be merged;
229
+ 4. Make sure existing tests pass;
230
+ 5. Add high-coverage tests. No quality testing = no merge.
231
+
232
+ See an example of a good PR here: https://github.com/huggingface/accelerate/pull/255
233
+
234
+ ### Tests
235
+
236
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
237
+ the [tests folder](https://github.com/huggingface/accelerate/tree/main/tests).
238
+
239
+ We use `pytest` in order to run the tests. From the root of the
240
+ repository, here's how to run tests with `pytest` for the library:
241
+
242
+ ```bash
243
+ $ python -m pytest -sv ./tests
244
+ ```
245
+
246
+ In fact, that's how `make test` is implemented (sans the `pip install` line)!
247
+
248
+ You can specify a smaller set of tests in order to test only the feature
249
+ you're working on.
tasks/tasksmith-b1dd32dfa88b/environment/source/Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /workspace
3
+ RUN python -m pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu torch==2.11.0+cpu numpy==2.5.3 packaging==26.3 psutil==7.2.2 pyyaml==6.0.3 huggingface_hub==1.31.0 safetensors==0.8.0 pytest==8.4.2 setuptools==78.1.0 wheel==0.48.0
4
+ COPY . /workspace
5
+ RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
6
+ RUN rm -rf /workspace/.git /root/.cache/pip
7
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
tasks/tasksmith-b1dd32dfa88b/environment/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 [yyyy] [name of copyright owner]
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-b1dd32dfa88b/environment/source/Makefile ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: quality style test docs utils
2
+
3
+ check_dirs := .
4
+
5
+ # Check that source code meets quality standards
6
+
7
+ extra_quality_checks:
8
+ python utils/check_copies.py
9
+ python utils/check_dummies.py
10
+ python utils/check_repo.py
11
+ doc-builder style src/accelerate docs/source --max_len 119
12
+
13
+ # this target runs checks on all files
14
+ quality:
15
+ ruff check $(check_dirs)
16
+ ruff format --check $(check_dirs)
17
+ doc-builder style src/accelerate docs/source --max_len 119 --check_only
18
+
19
+ # Format source code automatically and check is there are any problems left that need manual fixing
20
+ style:
21
+ ruff check $(check_dirs) --fix
22
+ ruff format $(check_dirs)
23
+ doc-builder style src/accelerate docs/source --max_len 119
24
+
25
+ # Run tests for the library
26
+ test_core:
27
+ python -m pytest -s -v ./tests/ \
28
+ --ignore=./tests/test_big_modeling.py \
29
+ --ignore=./tests/test_modeling_utils.py \
30
+ --ignore=./tests/test_examples.py \
31
+ --ignore=./tests/test_cli.py \
32
+ --ignore=./tests/deepspeed \
33
+ --ignore=./tests/fsdp \
34
+ --ignore=./tests/tp \
35
+ $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_core.log",)
36
+
37
+ test_cli:
38
+ python -m pytest -s -v ./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_cli.log",)
39
+
40
+ test_big_modeling:
41
+ python -m pytest -s -v ./tests/test_big_modeling.py ./tests/test_modeling_utils.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_big_modeling.log",)
42
+
43
+ test_deepspeed:
44
+ python -m pytest -s -v ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_deepspeed.log",)
45
+
46
+ test_fsdp:
47
+ python -m pytest -s -v ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_fsdp.log",)
48
+
49
+ test_tp:
50
+ python -m pytest -s -v ./tests/tp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_tp.log",)
51
+
52
+ # Since the new version of pytest will *change* how things are collected, we need `deepspeed` to
53
+ # run after test_core and test_cli
54
+ test:
55
+ $(MAKE) test_core
56
+ $(MAKE) test_cli
57
+ $(MAKE) test_big_modeling
58
+ $(MAKE) test_deepspeed
59
+ $(MAKE) test_fsdp
60
+ $(MAKE) test_tp
61
+
62
+ test_examples:
63
+ python -m pytest -s -v ./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_examples.log",)
64
+
65
+ # Broken down example tests for the CI runners
66
+ test_integrations:
67
+ python -m pytest -s -v ./tests/deepspeed ./tests/fsdp ./tests/tp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_integrations.log",)
68
+
69
+ test_example_differences:
70
+ python -m pytest -s -v ./tests/test_examples.py::ExampleDifferenceTests $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_example_diff.log",)
71
+
72
+ test_checkpoint_epoch:
73
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_epoch.log",)
74
+
75
+ test_checkpoint_step:
76
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_step" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_step.log",)
77
+
78
+ # Same as test but used to install only the base dependencies
79
+ test_prod:
80
+ $(MAKE) test_core
81
+
82
+ test_rest:
83
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "not by_step and not by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_rest.log",)
84
+
85
+ # For developers to prepare a release
86
+ prepare_release:
87
+ rm -rf dist build
88
+ python setup.py bdist_wheel sdist
89
+
90
+ # Make sure this is ran in a fresh venv of some form
91
+ install_test_release:
92
+ pip uninstall accelerate -y
93
+ pip install -i https://testpypi.python.org/pypi --extra-index-url https://pypi.org/simple accelerate$(if $(version),==$(version),)
94
+
95
+ # Run as `make target=testpypi upload_release`
96
+ upload_release:
97
+ @if [ "$(target)" != "testpypi" ] && [ "$(target)" != "pypi" ]; then \
98
+ echo "Error: target must be either 'testpypi' or 'pypi'"; \
99
+ exit 1; \
100
+ fi
101
+ twine upload dist/* -r $(target)
tasks/tasksmith-b1dd32dfa88b/environment/source/README.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ <p align="center">
18
+ <br>
19
+ <img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png" width="400"/>
20
+ <br>
21
+ <p>
22
+
23
+ <p align="center">
24
+ <!-- Uncomment when CircleCI is set up
25
+ <a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a>
26
+ -->
27
+ <a href="https://github.com/huggingface/accelerate/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue"></a>
28
+ <a href="https://huggingface.co/docs/accelerate/index.html"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/accelerate/index.html.svg?down_color=red&down_message=offline&up_message=online"></a>
29
+ <a href="https://github.com/huggingface/accelerate/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg"></a>
30
+ <a href="https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
31
+ </p>
32
+
33
+ <h3 align="center">
34
+ <p>Run your *raw* PyTorch training script on any kind of device
35
+ </h3>
36
+
37
+ <h3 align="center">
38
+ <a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a>
39
+ </h3>
40
+
41
+ ## Easy to integrate
42
+
43
+ 🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16.
44
+
45
+ 🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.
46
+
47
+ Here is an example:
48
+
49
+ ```diff
50
+ import torch
51
+ import torch.nn.functional as F
52
+ from datasets import load_dataset
53
+ + from accelerate import Accelerator
54
+
55
+ + accelerator = Accelerator()
56
+ - device = 'cpu'
57
+ + device = accelerator.device
58
+
59
+ model = torch.nn.Transformer().to(device)
60
+ optimizer = torch.optim.Adam(model.parameters())
61
+
62
+ dataset = load_dataset('my_dataset')
63
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
64
+
65
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
66
+
67
+ model.train()
68
+ for epoch in range(10):
69
+ for source, targets in data:
70
+ source = source.to(device)
71
+ targets = targets.to(device)
72
+
73
+ optimizer.zero_grad()
74
+
75
+ output = model(source)
76
+ loss = F.cross_entropy(output, targets)
77
+
78
+ - loss.backward()
79
+ + accelerator.backward(loss)
80
+
81
+ optimizer.step()
82
+ ```
83
+
84
+ As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16).
85
+
86
+ In particular, the same code can then be run without modification on your local machine for debugging or your training environment.
87
+
88
+ 🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further:
89
+
90
+ ```diff
91
+ import torch
92
+ import torch.nn.functional as F
93
+ from datasets import load_dataset
94
+ + from accelerate import Accelerator
95
+
96
+ - device = 'cpu'
97
+ + accelerator = Accelerator()
98
+
99
+ - model = torch.nn.Transformer().to(device)
100
+ + model = torch.nn.Transformer()
101
+ optimizer = torch.optim.Adam(model.parameters())
102
+
103
+ dataset = load_dataset('my_dataset')
104
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
105
+
106
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
107
+
108
+ model.train()
109
+ for epoch in range(10):
110
+ for source, targets in data:
111
+ - source = source.to(device)
112
+ - targets = targets.to(device)
113
+
114
+ optimizer.zero_grad()
115
+
116
+ output = model(source)
117
+ loss = F.cross_entropy(output, targets)
118
+
119
+ - loss.backward()
120
+ + accelerator.backward(loss)
121
+
122
+ optimizer.step()
123
+ ```
124
+
125
+ Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
126
+
127
+ ## Launching script
128
+
129
+ 🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training!
130
+ On your machine(s) just run:
131
+
132
+ ```bash
133
+ accelerate config
134
+ ```
135
+
136
+ and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
137
+
138
+ ```bash
139
+ accelerate launch my_script.py --args_to_my_script
140
+ ```
141
+
142
+ For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
143
+
144
+ ```bash
145
+ accelerate launch examples/nlp_example.py
146
+ ```
147
+
148
+ This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.
149
+
150
+ You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`.
151
+
152
+ For example, here is how to launch on two GPUs:
153
+
154
+ ```bash
155
+ accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py
156
+ ```
157
+
158
+ To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).
159
+
160
+ Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)
161
+
162
+ ## Launching multi-CPU run using MPI
163
+
164
+ 🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well.
165
+ Once you have MPI setup on your cluster, just run:
166
+ ```bash
167
+ accelerate config
168
+ ```
169
+ Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun.
170
+ Then, use `accelerate launch` with your script like:
171
+ ```bash
172
+ accelerate launch examples/nlp_example.py
173
+ ```
174
+ Alternatively, you can use mpirun directly, without using the CLI like:
175
+ ```bash
176
+ mpirun -np 2 python examples/nlp_example.py
177
+ ```
178
+
179
+ ## Launching training using DeepSpeed
180
+
181
+ 🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`.
182
+
183
+ ```python
184
+ from accelerate import Accelerator, DeepSpeedPlugin
185
+
186
+ # deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it
187
+ # Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed
188
+ deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
189
+ accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin)
190
+
191
+ # How to save your 🤗 Transformer?
192
+ accelerator.wait_for_everyone()
193
+ unwrapped_model = accelerator.unwrap_model(model)
194
+ unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))
195
+ ```
196
+
197
+ Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.
198
+
199
+ ## Launching your training from a notebook
200
+
201
+ 🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add:
202
+
203
+ ```python
204
+ from accelerate import notebook_launcher
205
+
206
+ notebook_launcher(training_function)
207
+ ```
208
+
209
+ An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
210
+
211
+ ## Why should I use 🤗 Accelerate?
212
+
213
+ You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object.
214
+
215
+ ## Why shouldn't I use 🤗 Accelerate?
216
+
217
+ You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them.
218
+
219
+ ## Frameworks using 🤗 Accelerate
220
+
221
+ If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below:
222
+
223
+ * [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development.
224
+ * [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76).
225
+ * [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic.
226
+ * [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms.
227
+ * [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses.
228
+ * [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products.
229
+ * [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library.
230
+ * [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so.
231
+ * [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves!
232
+ * [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion.
233
+ * [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric.
234
+ * [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side).
235
+
236
+
237
+ ## Installation
238
+
239
+ This repository is tested on Python 3.8+ and PyTorch 1.10.0+
240
+
241
+ You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
242
+
243
+ First, create a virtual environment with the version of Python you're going to use and activate it.
244
+
245
+ Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows:
246
+
247
+ ```bash
248
+ pip install accelerate
249
+ ```
250
+
251
+ ## Supported integrations
252
+
253
+ - CPU only
254
+ - multi-CPU on one node (machine)
255
+ - multi-CPU on several nodes (machines)
256
+ - single GPU
257
+ - multi-GPU on one node (machine)
258
+ - multi-GPU on several nodes (machines)
259
+ - TPU
260
+ - FP16/BFloat16 mixed precision
261
+ - FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)
262
+ - DeepSpeed support (Experimental)
263
+ - PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)
264
+ - Megatron-LM support (Experimental)
265
+
266
+ ## Citing 🤗 Accelerate
267
+
268
+ If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
269
+
270
+ ```bibtex
271
+ @Misc{accelerate,
272
+ title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.},
273
+ author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},
274
+ howpublished = {\url{https://github.com/huggingface/accelerate}},
275
+ year = {2022}
276
+ }
277
+ ```
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Benchmarks
2
+
3
+ The folders below contain suites to test various functionalities in Accelerate.
4
+
5
+ See their relevant README.md's for more information.
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/big_model_inference/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Big model inference benchmarks
2
+
3
+ Running inference with Accelerate on big models.
4
+
5
+ ## Setup
6
+
7
+ These benchmarks use the `transformers` library:
8
+
9
+ ```bash
10
+ pip install transformers
11
+ ```
12
+
13
+ To reproduce or test a new setup, run
14
+
15
+ ```py
16
+ python big_model_inference.py model_name
17
+ ```
18
+
19
+ This script supports `gpt-j-6b`, `gpt-neox`, `opt` (30B version) and `T0pp` out of the box, but you can specify any valid checkpoint for `model_name`.
20
+
21
+ To force a different `torch_dtype` than the one in the config: `--torch_dtype xxx`.
22
+
23
+ If you get an error linked to disk offload, you need to add the option `--disk-offload`
24
+
25
+ ## Results
26
+
27
+ On a setup with two Titan RTXs (24GB of RAM) and 32GB of RAM, we get the following benchmarks (T0pp does not run in float16, which is why it's not included).
28
+
29
+ | Model | Model load time | Generation time | dtype | GPU 0 use | GPU 1 use | CPU use | Disk offload |
30
+ |:-----:|:---------------:|:---------------:|:-----:|:---------:|:---------:|:-------:|:------------:|
31
+ | GPT-J-6B | 8.7s | 0.05s per token | float16 | 11.7GB | 0GB | 0GB | no |
32
+ | GPT-J-6B | 12.4s | 0.06s per token | float32 | 21.9GB | 1.5GB | 0GB | no |
33
+ | GPT-Neo-X-20B | 30.9s | 0.08s per token | float16 | 21.5GB | 18GB | 0GB | no |
34
+ | GPT-Neo-X-20B | 78.2s | 10.72s per token | float32 | 20.3GB | 22.7 GB | 24.4GB | yes |
35
+ | T0pp (11B) | 29.4s | 0.05s per token | float32 | 21.1GB | 21.3GB | 0GB | no |
36
+ | OPT-30B | 34.5s | 2.37s per token | float16 | 20.7GB | 22.3GB | 14.1GB | no |
37
+ | OPT-30B | 112.3s | 33.9s per token | float32 | 20.2GB | 21.2GB | 23.5GB | yes |
38
+
39
+ Note on the results:
40
+ - using two GPUs instead of one does not slow down generation
41
+ - using CPU offload slows down a bit (see OPT-30b)
42
+ - using disk offload slows down a lot (need to implement prefetching)
43
+
44
+ You will also note that Accelerate does not use anymore GPU and CPU RAM than necessary:
45
+ - peak GPU memory is exactly the size of the model put on a given GPU
46
+ - peak CPU memory is either the size of the biggest checkpoint shard or the part of the model offloaded on CPU, whichever is bigger.
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/big_model_inference/big_model_inference.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+ import time
17
+
18
+ import torch
19
+ import transformers
20
+ from measures_util import end_measure, log_measures, start_measure
21
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer
22
+
23
+ from accelerate.utils import compute_module_sizes
24
+
25
+
26
+ DEFAULT_MODELS = {
27
+ "gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"},
28
+ "gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"},
29
+ "opt": {"is_causal": True, "model": "facebook/opt-30b"},
30
+ "T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"},
31
+ }
32
+
33
+ PROMPTS = [
34
+ "Hello, my name is",
35
+ "Are unicorns real? Unicorns are",
36
+ "For the first time in several years,",
37
+ "My name is Julien and I am",
38
+ "The goal of life is",
39
+ "Whenever I'm sad, I like to",
40
+ ]
41
+
42
+
43
+ def parse_args():
44
+ parser = argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate.")
45
+ parser.add_argument("model_name", type=str, default=None, help="The name of the model to try.")
46
+ parser.add_argument(
47
+ "--tokenizer_name", type=str, default=None, help="The name of the tokenizer (if different from the model."
48
+ )
49
+ parser.add_argument("--is_causal", type=bool, default=None, help="Whether or not the model is causal.")
50
+ parser.add_argument(
51
+ "--model_revision", type=str, default=None, help="The revision to use for the model checkpoint."
52
+ )
53
+ parser.add_argument("--torch_dtype", type=str, default=None, help="The dtype for the model.")
54
+ parser.add_argument("--disk_offload", action="store_true")
55
+
56
+ args = parser.parse_args()
57
+
58
+ # Sanitize args
59
+ if args.model_name in DEFAULT_MODELS:
60
+ defaults = DEFAULT_MODELS[args.model_name]
61
+ args.model_name = defaults["model"]
62
+ if args.tokenizer_name is None:
63
+ args.tokenizer_name = defaults.get("tokenizer", args.model_name)
64
+ if args.is_causal is None:
65
+ args.is_causal = defaults["is_causal"]
66
+ if args.model_revision is None:
67
+ args.model_revision = defaults.get("model_revision", "main")
68
+
69
+ if args.is_causal is None:
70
+ raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it.")
71
+ if args.tokenizer_name is None:
72
+ args.tokenizer_name = args.model_name
73
+ if args.model_revision is None:
74
+ args.model_revision = "main"
75
+
76
+ return args
77
+
78
+
79
+ def main():
80
+ transformers.utils.logging.set_verbosity_error()
81
+ args = parse_args()
82
+
83
+ if args.torch_dtype is None:
84
+ config = AutoConfig.from_pretrained(args.model_name)
85
+ torch_dtype = getattr(config, "torch_dtype", torch.float32)
86
+ else:
87
+ torch_dtype = getattr(torch, args.torch_dtype)
88
+ model_cls = AutoModelForCausalLM if args.is_causal else AutoModelForSeq2SeqLM
89
+ kwargs = {
90
+ "torch_dtype": torch_dtype,
91
+ "revision": args.model_revision,
92
+ }
93
+ if args.disk_offload:
94
+ kwargs["offload_folder"] = "tmp_offload"
95
+ kwargs["offload_state_dict"] = True
96
+
97
+ start_measures = start_measure()
98
+ model = model_cls.from_pretrained(args.model_name, device_map="auto", **kwargs)
99
+ end_measures = end_measure(start_measures)
100
+ log_measures(end_measures, "Model loading")
101
+
102
+ module_sizes = compute_module_sizes(model)
103
+ device_size = {v: 0 for v in model.hf_device_map.values()}
104
+ for module, device in model.hf_device_map.items():
105
+ device_size[device] += module_sizes[module]
106
+ message = "\n".join([f"- {device}: {size // 2**20}MiB" for device, size in device_size.items()])
107
+ print(f"\nTheoretical use:\n{message}")
108
+
109
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name)
110
+
111
+ start_measures = start_measure()
112
+ generation_times = []
113
+ gen_tokens = []
114
+ texts_outs = []
115
+ for prompt in PROMPTS:
116
+ inputs = tokenizer(prompt, return_tensors="pt").to(0)
117
+ tokens = inputs["input_ids"][0].tolist()
118
+ before_generate = time.time()
119
+ outputs = model.generate(inputs["input_ids"])
120
+ after_generate = time.time()
121
+ outputs = outputs[0].tolist()
122
+ num_gen_tokens = len(outputs) if outputs[: len(tokens)] != tokens else len(outputs) - len(tokens)
123
+ generation_time = after_generate - before_generate
124
+
125
+ text_out = tokenizer.decode(outputs, skip_special_tokens=True)
126
+ texts_outs.append(text_out)
127
+ generation_times.append(generation_time)
128
+ gen_tokens.append(num_gen_tokens)
129
+ print(f"Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n")
130
+
131
+ end_measures = end_measure(start_measures)
132
+ log_measures(end_measures, "Model generation")
133
+
134
+ generation_times_per_token = [gen / tok for gen, tok in zip(generation_times, gen_tokens)]
135
+ avg_gen = sum(generation_times_per_token) / len(generation_times)
136
+ print(f"Average time of generation per token: {avg_gen:.2f}s")
137
+ print(f"First generation (avg time per token): {generation_times_per_token[0]:.2f}s")
138
+ avg_gen = sum(generation_times_per_token[1:]) / (len(generation_times_per_token) - 1)
139
+ print(f"Average time of generation per token (excluding the first): {avg_gen:.2f}s")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/big_model_inference/measures_util.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import gc
15
+ import threading
16
+ import time
17
+
18
+ import psutil
19
+ import torch
20
+
21
+ from accelerate.test_utils.testing import get_backend
22
+
23
+
24
+ torch_device_type, _, _ = get_backend()
25
+ torch_accelerator_module = getattr(torch, torch_device_type, torch.cuda)
26
+
27
+
28
+ class PeakCPUMemory:
29
+ def __init__(self):
30
+ self.process = psutil.Process()
31
+ self.peak_monitoring = False
32
+
33
+ def peak_monitor(self):
34
+ self.cpu_memory_peak = -1
35
+
36
+ while True:
37
+ self.cpu_memory_peak = max(self.process.memory_info().rss, self.cpu_memory_peak)
38
+
39
+ # can't sleep or will not catch the peak right (this comment is here on purpose)
40
+ if not self.peak_monitoring:
41
+ break
42
+
43
+ def start(self):
44
+ self.peak_monitoring = True
45
+ self.thread = threading.Thread(target=self.peak_monitor)
46
+ self.thread.daemon = True
47
+ self.thread.start()
48
+
49
+ def stop(self):
50
+ self.peak_monitoring = False
51
+ self.thread.join()
52
+ return self.cpu_memory_peak
53
+
54
+
55
+ cpu_peak_tracker = PeakCPUMemory()
56
+
57
+
58
+ def start_measure():
59
+ # Time
60
+ measures = {"time": time.time()}
61
+
62
+ gc.collect()
63
+ torch_accelerator_module.empty_cache()
64
+
65
+ # CPU mem
66
+ measures["cpu"] = psutil.Process().memory_info().rss
67
+ cpu_peak_tracker.start()
68
+
69
+ # GPU mem
70
+ for i in range(torch_accelerator_module.device_count()):
71
+ measures[str(i)] = torch_accelerator_module.memory_allocated(i)
72
+ torch_accelerator_module.reset_peak_memory_stats()
73
+
74
+ return measures
75
+
76
+
77
+ def end_measure(start_measures):
78
+ # Time
79
+ measures = {"time": time.time() - start_measures["time"]}
80
+
81
+ gc.collect()
82
+ torch_accelerator_module.empty_cache()
83
+
84
+ # CPU mem
85
+ measures["cpu"] = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20
86
+ measures["cpu-peak"] = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20
87
+
88
+ # GPU mem
89
+ for i in range(torch_accelerator_module.device_count()):
90
+ measures[str(i)] = (torch_accelerator_module.memory_allocated(i) - start_measures[str(i)]) / 2**20
91
+ measures[f"{i}-peak"] = (torch_accelerator_module.max_memory_allocated(i) - start_measures[str(i)]) / 2**20
92
+
93
+ return measures
94
+
95
+
96
+ def log_measures(measures, description):
97
+ print(f"{description}:")
98
+ print(f"- Time: {measures['time']:.2f}s")
99
+ for i in range(torch_accelerator_module.device_count()):
100
+ print(f"- {torch_device_type} {i} allocated: {measures[str(i)]:.2f}MiB")
101
+ peak = measures[f"{i}-peak"]
102
+ print(f"- {torch_device_type} {i} peak: {peak:.2f}MiB")
103
+ print(f"- CPU RAM allocated: {measures['cpu']:.2f}MiB")
104
+ print(f"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB")
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ghcr.io/azure/msamp
2
+
3
+ RUN pip install transformers evaluate datasets
4
+ RUN git clone https://github.com/huggingface/accelerate
5
+
6
+ RUN cd accelerate && \
7
+ pip install -e . && \
8
+ cd benchmarks/fp8
9
+
10
+ CMD ["bash"]
11
+
12
+
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/ddp.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `MS-AMP`.
17
+
18
+ This particular script verifies this for DDP training.
19
+ """
20
+
21
+ import evaluate
22
+ import msamp
23
+ import torch
24
+ from fp8_utils import evaluate_model, get_training_utilities
25
+ from torch.nn.parallel import DistributedDataParallel as DDP
26
+
27
+ from accelerate import Accelerator
28
+ from accelerate.state import AcceleratorState
29
+ from accelerate.utils import FP8RecipeKwargs, get_grad_scaler, set_seed
30
+
31
+
32
+ MODEL_NAME = "bert-base-cased"
33
+ METRIC = evaluate.load("glue", "mrpc")
34
+
35
+
36
+ def train_baseline(opt_level="O2"):
37
+ set_seed(42)
38
+ scaler = get_grad_scaler()
39
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
40
+ accelerator = Accelerator()
41
+ device = accelerator.device
42
+
43
+ model, optimizer = msamp.initialize(model, optimizer, opt_level=opt_level)
44
+
45
+ model.to(device)
46
+
47
+ # Convert the model to DDP
48
+ device_ids, output_device = [accelerator.local_process_index], accelerator.local_process_index
49
+ model = DDP(model, device_ids=device_ids, output_device=output_device)
50
+
51
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
52
+ model.train()
53
+
54
+ for i, batch in enumerate(train_dataloader):
55
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
56
+ outputs = model(**batch)
57
+ loss = outputs.loss
58
+ scaler.scale(loss).backward()
59
+ optimizer.step()
60
+ optimizer.zero_grad()
61
+ lr_scheduler.step()
62
+
63
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
64
+
65
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
66
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
67
+ )
68
+ assert trained_model_results["f1"] > base_model_results["f1"], (
69
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
70
+ )
71
+
72
+ return base_model_results, trained_model_results
73
+
74
+
75
+ def train_integration(opt_level="O2"):
76
+ kwargs_handlers = [FP8RecipeKwargs(backend="msamp", opt_level=opt_level)]
77
+ AcceleratorState()._reset_state(True)
78
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=kwargs_handlers)
79
+ set_seed(42)
80
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
81
+ MODEL_NAME, accelerator=accelerator
82
+ )
83
+
84
+ model, optimizer = accelerator.prepare(model, optimizer)
85
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
86
+ model.train()
87
+ for i, batch in enumerate(train_dataloader):
88
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
89
+ outputs = model(**batch)
90
+ loss = outputs.loss
91
+ accelerator.backward(loss)
92
+ optimizer.step()
93
+ optimizer.zero_grad()
94
+ lr_scheduler.step()
95
+
96
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
97
+
98
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
99
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
100
+ )
101
+ assert trained_model_results["f1"] > base_model_results["f1"], (
102
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
103
+ )
104
+
105
+ return base_model_results, trained_model_results
106
+
107
+
108
+ if __name__ == "__main__":
109
+ for opt_level in ["O1", "O2"]:
110
+ baseline_not_trained, baseline_trained = train_baseline(opt_level)
111
+ accelerator_not_trained, accelerator_trained = train_integration(opt_level)
112
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
113
+ f"Accuracy not the same for untrained baseline and accelerator using opt_level={opt_level}: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
114
+ )
115
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
116
+ f"F1 not the same for untrained baseline and accelerator using opt_level={opt_level}: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
117
+ )
118
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
119
+ f"Accuracy not the same for trained baseline and accelerator using opt_level={opt_level}: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
120
+ )
121
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
122
+ f"F1 not the same for trained baseline and accelerator using opt_level={opt_level}: {baseline_trained['f1']} == {accelerator_trained['f1']}"
123
+ )
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/distrib_deepspeed.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `MS-AMP`.
17
+
18
+ This particular script verifies this for DeepSpeed training.
19
+
20
+ NOTE: MS-AMP does *not* support ZeRO-3.
21
+ """
22
+
23
+ # import msamp.deepspeed as msamp_deepspeed
24
+ import evaluate
25
+ import torch
26
+ from fp8_utils import evaluate_model, get_training_utilities
27
+ from msamp import deepspeed as msamp_deepspeed
28
+
29
+ from accelerate import Accelerator, DeepSpeedPlugin
30
+ from accelerate.state import AcceleratorState
31
+ from accelerate.utils import set_seed
32
+
33
+
34
+ MODEL_NAME = "bert-base-cased"
35
+ METRIC = evaluate.load("glue", "mrpc")
36
+
37
+
38
+ def train_baseline(zero_stage: int = 1, opt_level: str = "O1"):
39
+ set_seed(42)
40
+ accelerator = Accelerator()
41
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
42
+ MODEL_NAME, accelerator=accelerator
43
+ )
44
+
45
+ import numpy as np
46
+
47
+ config = {
48
+ "train_batch_size": 32,
49
+ "train_micro_batch_size_per_gpu": 16,
50
+ "gradient_accumulation_steps": 1,
51
+ "zero_optimization": {
52
+ "stage": zero_stage,
53
+ "offload_optimizer": {"device": "none", "nvme_path": None},
54
+ "offload_param": {"device": "none", "nvme_path": None},
55
+ },
56
+ "gradient_clipping": 1.0,
57
+ "steps_per_print": np.inf,
58
+ "bf16": {"enabled": True},
59
+ "fp16": {"enabled": False},
60
+ "zero_allow_untested_optimizer": True,
61
+ "msamp": {
62
+ "enabled": True,
63
+ "opt_level": opt_level,
64
+ },
65
+ }
66
+ (
67
+ model,
68
+ optimizer,
69
+ _,
70
+ _,
71
+ ) = msamp_deepspeed.initialize(
72
+ model=model,
73
+ optimizer=optimizer,
74
+ config_params=config,
75
+ )
76
+
77
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
78
+ model.train()
79
+
80
+ for _ in range(2):
81
+ for batch in train_dataloader:
82
+ outputs = model(**batch)
83
+ loss = outputs.loss
84
+ model.backward(loss)
85
+ model.step()
86
+ for _ in range(accelerator.num_processes):
87
+ lr_scheduler.step()
88
+
89
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
90
+ model.destroy()
91
+ torch.cuda.empty_cache()
92
+ AcceleratorState()._reset_state(True)
93
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
94
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
95
+ )
96
+ assert trained_model_results["f1"] > base_model_results["f1"], (
97
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
98
+ )
99
+
100
+ return base_model_results, trained_model_results
101
+
102
+
103
+ def train_integration(zero_stage: int = 1, opt_level: str = "O1"):
104
+ set_seed(42)
105
+ deepspeed_plugin = DeepSpeedPlugin(
106
+ zero_stage=zero_stage,
107
+ enable_msamp=True,
108
+ msamp_opt_level=opt_level,
109
+ )
110
+ accelerator = Accelerator(mixed_precision="fp8", deepspeed_plugin=deepspeed_plugin)
111
+ accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = 16
112
+
113
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
114
+ MODEL_NAME, accelerator=accelerator
115
+ )
116
+
117
+ model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
118
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
119
+ model.train()
120
+ for _ in range(2):
121
+ for batch in train_dataloader:
122
+ outputs = model(**batch)
123
+ loss = outputs.loss
124
+ accelerator.backward(loss)
125
+ optimizer.step()
126
+ lr_scheduler.step()
127
+ optimizer.zero_grad()
128
+
129
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
130
+ model.destroy()
131
+ torch.cuda.empty_cache()
132
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
133
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
134
+ )
135
+ assert trained_model_results["f1"] > base_model_results["f1"], (
136
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
137
+ )
138
+
139
+ AcceleratorState()._reset_state(True)
140
+ return base_model_results, trained_model_results
141
+
142
+
143
+ if __name__ == "__main__":
144
+ for zero_stage in [1, 2]:
145
+ for opt_level in ["O1", "O2", "O3"]:
146
+ baseline_not_trained, baseline_trained = train_baseline(zero_stage, opt_level)
147
+ accelerator_not_trained, accelerator_trained = train_integration(zero_stage, opt_level)
148
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
149
+ f"ZERO stage {zero_stage}, opt_level={opt_level}:\nAccuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
150
+ )
151
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
152
+ f"ZERO stage {zero_stage}, opt_level={opt_level}:\nF1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
153
+ )
154
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
155
+ f"ZERO stage {zero_stage}, opt_level={opt_level}:\nAccuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
156
+ )
157
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
158
+ f"ZERO stage {zero_stage}, opt_level={opt_level}:\nF1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
159
+ )
160
+
161
+ torch.distributed.destroy_process_group()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/fp8_utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+
16
+
17
+ def get_dataloaders(model_name: str, batch_size: int = 16):
18
+ from datasets import load_dataset
19
+ from torch.utils.data import DataLoader
20
+ from transformers import AutoTokenizer
21
+
22
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
23
+ datasets = load_dataset("glue", "mrpc")
24
+
25
+ def tokenize_function(examples):
26
+ # max_length=None => use the model max length (it's actually the default)
27
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
28
+ return outputs
29
+
30
+ # Apply the method we just defined to all the examples in all the splits of the dataset
31
+ # starting with the main process first:
32
+ tokenized_datasets = datasets.map(
33
+ tokenize_function,
34
+ batched=True,
35
+ remove_columns=["idx", "sentence1", "sentence2"],
36
+ )
37
+
38
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
39
+ # transformers library
40
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
41
+
42
+ def collate_fn(examples):
43
+ return tokenizer.pad(
44
+ examples,
45
+ padding="longest",
46
+ pad_to_multiple_of=16, # Specific for FP8
47
+ return_tensors="pt",
48
+ )
49
+
50
+ # Instantiate dataloaders.
51
+ train_dataloader = DataLoader(
52
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
53
+ )
54
+ eval_dataloader = DataLoader(
55
+ tokenized_datasets["validation"],
56
+ shuffle=False,
57
+ collate_fn=collate_fn,
58
+ batch_size=16,
59
+ drop_last=True,
60
+ )
61
+
62
+ return train_dataloader, eval_dataloader
63
+
64
+
65
+ def get_training_utilities(model_name: str, batch_size: int = 16, accelerator=None):
66
+ """
67
+ Returns a tuple of:
68
+ - Model
69
+ - Optimizer
70
+ - Train dataloader (prepared)
71
+ - Eval dataloader (prepared)
72
+ - LR Scheduler
73
+ Suitable for training on the MRPC dataset
74
+ """
75
+ from torch.optim import AdamW
76
+ from transformers import AutoModelForSequenceClassification, get_linear_schedule_with_warmup
77
+
78
+ from accelerate import Accelerator
79
+
80
+ if accelerator is None:
81
+ accelerator = Accelerator()
82
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
83
+ train_dataloader, eval_dataloader = get_dataloaders(model_name, batch_size)
84
+ optimizer = AdamW(model.parameters(), lr=0.0001)
85
+ lr_scheduler = get_linear_schedule_with_warmup(
86
+ optimizer=optimizer,
87
+ num_warmup_steps=100,
88
+ num_training_steps=len(train_dataloader) * 2,
89
+ )
90
+ train_dataloader, eval_dataloader = accelerator.prepare(train_dataloader, eval_dataloader)
91
+ return model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
92
+
93
+
94
+ def get_named_parameters(model):
95
+ """
96
+ Same thing as `Accelerator.get_named_parameters` Returns a list of the named parameters of the model (extracted
97
+ from parallel)
98
+ """
99
+ from accelerate.utils import extract_model_from_parallel
100
+
101
+ model = extract_model_from_parallel(model)
102
+ return {n: p for n, p in model.named_parameters()}
103
+
104
+
105
+ def evaluate_model(model, dataloader, metric, accelerator=None):
106
+ "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
107
+ model.eval()
108
+ for step, batch in enumerate(dataloader):
109
+ with torch.no_grad():
110
+ # W/ MS-AMP, we need to cast while evaluating
111
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
112
+ outputs = model(**batch)
113
+ predictions = outputs.logits.argmax(dim=-1)
114
+ references = batch["labels"]
115
+ if accelerator is not None and accelerator.num_processes > 1:
116
+ predictions, references = accelerator.gather_for_metrics((predictions, references))
117
+ metric.add_batch(predictions=predictions, references=references)
118
+ return metric.compute()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/ms_amp/non_distributed.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `MS-AMP`.
17
+
18
+ This particular script verifies this for single GPU training.
19
+ """
20
+
21
+ import evaluate
22
+ import msamp
23
+ import torch
24
+ from fp8_utils import evaluate_model, get_training_utilities
25
+
26
+ from accelerate import Accelerator
27
+ from accelerate.state import AcceleratorState
28
+ from accelerate.utils import FP8RecipeKwargs, get_grad_scaler, set_seed
29
+
30
+
31
+ MODEL_NAME = "bert-base-cased"
32
+ METRIC = evaluate.load("glue", "mrpc")
33
+
34
+
35
+ def train_baseline(opt_level="O2"):
36
+ set_seed(42)
37
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
38
+
39
+ model, optimizer = msamp.initialize(model, optimizer, opt_level=opt_level)
40
+ model.to("cuda")
41
+
42
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC)
43
+ model.train()
44
+ scaler = get_grad_scaler()
45
+
46
+ for batch in train_dataloader:
47
+ batch = batch.to("cuda")
48
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
49
+ outputs = model(**batch)
50
+ loss = outputs.loss
51
+ loss = scaler.scale(loss)
52
+ loss.backward()
53
+ optimizer.step()
54
+ optimizer.zero_grad()
55
+ lr_scheduler.step()
56
+
57
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
58
+
59
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
60
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
61
+ )
62
+ assert trained_model_results["f1"] > base_model_results["f1"], (
63
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
64
+ )
65
+
66
+ return base_model_results, trained_model_results
67
+
68
+
69
+ def train_integration(opt_level="O2"):
70
+ kwargs_handlers = [FP8RecipeKwargs(backend="msamp", opt_level=opt_level)]
71
+ AcceleratorState()._reset_state(True)
72
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=kwargs_handlers)
73
+ set_seed(42)
74
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
75
+ MODEL_NAME, accelerator=accelerator
76
+ )
77
+
78
+ model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
79
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC)
80
+ model.train()
81
+
82
+ for batch in train_dataloader:
83
+ outputs = model(**batch)
84
+ loss = outputs.loss
85
+ accelerator.backward(loss)
86
+ optimizer.step()
87
+ optimizer.zero_grad()
88
+ lr_scheduler.step()
89
+
90
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
91
+
92
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
93
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
94
+ )
95
+ assert trained_model_results["f1"] > base_model_results["f1"], (
96
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
97
+ )
98
+
99
+ return base_model_results, trained_model_results
100
+
101
+
102
+ if __name__ == "__main__":
103
+ for opt_level in ["O1", "O2"]:
104
+ baseline_not_trained, baseline_trained = train_baseline(opt_level)
105
+ accelerator_not_trained, accelerator_trained = train_integration(opt_level)
106
+
107
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
108
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
109
+ )
110
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
111
+ f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
112
+ )
113
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
114
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
115
+ )
116
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
117
+ f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
118
+ )
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvcr.io/nvidia/pytorch:24.07-py3
2
+
3
+ RUN pip install transformers evaluate datasets
4
+ RUN git clone https://github.com/huggingface/accelerate.git
5
+
6
+ RUN cd accelerate && \
7
+ pip install -e . && \
8
+ cd benchmarks/fp8
9
+
10
+ RUN /bin/bash
11
+
12
+
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FP8 Benchmarks
2
+
3
+ Comparing and running [torchao](https://github.com/pytorch/ao/tree/main/torchao/float8) FP8 with accelerate
4
+
5
+ ## Overview
6
+
7
+ This repo provides scripts which compare native `torchao` model training against `accelerate`'s own integration. Each modeling type is segmented out via a script, supporting the following:
8
+
9
+ * Single GPU training (`non_distributed.py`)
10
+ * Multi-GPU training via DistributedDataParallelism (`ddp.py`)
11
+ * Fully Sharded Data Parallelism (`fsdp.py`)
12
+ * DeepSpeed ZeRO 1-3 (`deepspeed.py`)
13
+
14
+ To run them, it's recommended to use a docker image (see the attached `Dockerfile`) and not install `torchao` manually.
15
+
16
+ ## Running:
17
+
18
+ There are official Docker images located at `huggingface/accelerate:gpu-fp8-torchao-nightly` which can be used.
19
+
20
+ You can run all scripts using the core `accelerate launch` command without any `accelerate config` being needed.
21
+
22
+ For single GPU, run it via `python`:
23
+
24
+ ```bash
25
+ python non_distributed.py
26
+ ```
27
+
28
+ For the rest, run it via `accelerate launch`:
29
+
30
+ ```bash
31
+ accelerate launch ddp.py # or distrib_deepspeed.py, ddp.py
32
+ ```
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/ddp.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `torchao`.
17
+
18
+ This particular script verifies this for DDP training.
19
+ """
20
+
21
+ from functools import partial
22
+
23
+ import evaluate
24
+ import torch
25
+ from fp8_utils import get_training_utilities
26
+ from torch.nn.parallel import DistributedDataParallel as DDP
27
+ from torchao.float8 import convert_to_float8_training
28
+
29
+ from accelerate import Accelerator
30
+ from accelerate.state import AcceleratorState
31
+ from accelerate.utils import AORecipeKwargs, set_seed
32
+
33
+
34
+ MODEL_NAME = "bert-base-cased"
35
+ METRIC = evaluate.load("glue", "mrpc")
36
+
37
+
38
+ def evaluate_model(model, dataloader, metric, accelerator=None):
39
+ "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
40
+ model.eval()
41
+ for step, batch in enumerate(dataloader):
42
+ with torch.no_grad():
43
+ outputs = model(**batch)
44
+ predictions = outputs.logits.argmax(dim=-1)
45
+ references = batch["labels"]
46
+ if accelerator is not None and accelerator.num_processes > 1:
47
+ predictions, references = accelerator.gather_for_metrics((predictions, references))
48
+ metric.add_batch(predictions=predictions, references=references)
49
+ return metric.compute()
50
+
51
+
52
+ def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None):
53
+ if isinstance(module, torch.nn.Linear):
54
+ if module.in_features % 16 != 0 or module.out_features % 16 != 0:
55
+ return False
56
+ # For stability reasons, we skip the first and last linear layers
57
+ # Otherwise can lead to the model not training or converging properly
58
+ if fqn in (first_layer_name, last_layer_name):
59
+ return False
60
+ return True
61
+
62
+
63
+ def train_baseline():
64
+ set_seed(42)
65
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
66
+ first_linear = None
67
+ last_linear = None
68
+ for name, module in model.named_modules():
69
+ if isinstance(module, torch.nn.Linear):
70
+ if first_linear is None:
71
+ first_linear = name
72
+ last_linear = name
73
+ func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear)
74
+ accelerator = Accelerator()
75
+ device = accelerator.device
76
+ model.to(device)
77
+
78
+ convert_to_float8_training(model, module_filter_fn=func)
79
+
80
+ # Convert the model to DDP
81
+ device_ids, output_device = [accelerator.local_process_index], accelerator.local_process_index
82
+ model = DDP(model, device_ids=device_ids, output_device=output_device)
83
+
84
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
85
+ model.train()
86
+
87
+ for batch in train_dataloader:
88
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
89
+ batch = batch.to(device)
90
+ outputs = model(**batch)
91
+ loss = outputs.loss
92
+ loss.backward()
93
+ optimizer.step()
94
+ optimizer.zero_grad()
95
+ lr_scheduler.step()
96
+
97
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
98
+
99
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
100
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
101
+ )
102
+ assert trained_model_results["f1"] > base_model_results["f1"], (
103
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
104
+ )
105
+
106
+ return base_model_results, trained_model_results
107
+
108
+
109
+ def train_integration():
110
+ AcceleratorState()._reset_state(True)
111
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[AORecipeKwargs()])
112
+ set_seed(42)
113
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
114
+ MODEL_NAME, accelerator=accelerator
115
+ )
116
+
117
+ model, optimizer = accelerator.prepare(model, optimizer)
118
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
119
+ model.train()
120
+
121
+ for batch in train_dataloader:
122
+ outputs = model(**batch)
123
+ loss = outputs.loss
124
+ accelerator.backward(loss)
125
+ optimizer.step()
126
+ optimizer.zero_grad()
127
+ lr_scheduler.step()
128
+
129
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
130
+
131
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
132
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
133
+ )
134
+ assert trained_model_results["f1"] > base_model_results["f1"], (
135
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
136
+ )
137
+
138
+ return base_model_results, trained_model_results
139
+
140
+
141
+ if __name__ == "__main__":
142
+ baseline_not_trained, baseline_trained = train_baseline()
143
+ accelerator_not_trained, accelerator_trained = train_integration()
144
+
145
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
146
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
147
+ )
148
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
149
+ f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
150
+ )
151
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
152
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
153
+ )
154
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
155
+ f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
156
+ )
157
+
158
+ torch.distributed.destroy_process_group()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/distrib_deepspeed.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `torchao`.
17
+
18
+ This particular script verifies this for deepspeed training.
19
+ """
20
+
21
+ from functools import partial
22
+ from unittest.mock import patch
23
+
24
+ import deepspeed
25
+ import evaluate
26
+ import torch
27
+ from fp8_utils import evaluate_model, get_training_utilities
28
+ from torchao.float8 import convert_to_float8_training
29
+ from transformers.integrations import HfDeepSpeedConfig
30
+
31
+ from accelerate import Accelerator, DeepSpeedPlugin
32
+ from accelerate.state import AcceleratorState
33
+ from accelerate.utils import AORecipeKwargs, set_seed
34
+
35
+
36
+ MODEL_NAME = "bert-base-cased"
37
+ METRIC = evaluate.load("glue", "mrpc")
38
+
39
+
40
+ def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None):
41
+ if isinstance(module, torch.nn.Linear):
42
+ if module.in_features % 16 != 0 or module.out_features % 16 != 0:
43
+ return False
44
+ # For stability reasons, we skip the first and last linear layers
45
+ # Otherwise can lead to the model not training or converging properly
46
+ if fqn in (first_layer_name, last_layer_name):
47
+ return False
48
+ return True
49
+
50
+
51
+ def train_baseline(zero_stage: int = 1):
52
+ set_seed(42)
53
+ # This forces transformers to think Zero-3 Init should be used
54
+ with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock:
55
+ mock.return_value = zero_stage == 3
56
+
57
+ config = HfDeepSpeedConfig(
58
+ {
59
+ "train_micro_batch_size_per_gpu": 16,
60
+ "gradient_accumulation_steps": 1,
61
+ "zero_optimization": {"stage": zero_stage},
62
+ }
63
+ )
64
+ plugin = DeepSpeedPlugin(hf_ds_config=config)
65
+ accelerator = Accelerator(deepspeed_plugin=plugin)
66
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
67
+ MODEL_NAME, accelerator=accelerator
68
+ )
69
+ first_linear = None
70
+ last_linear = None
71
+ for name, module in model.named_modules():
72
+ if isinstance(module, torch.nn.Linear):
73
+ if first_linear is None:
74
+ first_linear = name
75
+ last_linear = name
76
+ func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear)
77
+
78
+ convert_to_float8_training(model, module_filter_fn=func)
79
+
80
+ import numpy as np
81
+
82
+ config = {
83
+ "train_batch_size": 32,
84
+ "train_micro_batch_size_per_gpu": 16,
85
+ "gradient_accumulation_steps": 1,
86
+ "zero_optimization": {
87
+ "stage": zero_stage,
88
+ "offload_optimizer": {"device": "none", "nvme_path": None},
89
+ "offload_param": {"device": "none", "nvme_path": None},
90
+ "stage3_gather_16bit_weights_on_model_save": False,
91
+ },
92
+ "gradient_clipping": 1.0,
93
+ "steps_per_print": np.inf,
94
+ "bf16": {"enabled": True},
95
+ "fp16": {"enabled": False},
96
+ "zero_allow_untested_optimizer": True,
97
+ }
98
+
99
+ (
100
+ model,
101
+ optimizer,
102
+ _,
103
+ lr_scheduler,
104
+ ) = deepspeed.initialize(
105
+ model=model,
106
+ optimizer=optimizer,
107
+ lr_scheduler=lr_scheduler,
108
+ config_params=config,
109
+ )
110
+
111
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
112
+ model.train()
113
+
114
+ model_outputs = []
115
+ data = []
116
+
117
+ for batch in train_dataloader:
118
+ outputs = model(**batch)
119
+ data.append(batch.to("cpu"))
120
+ model_outputs.append(outputs.logits.to("cpu"))
121
+ loss = outputs.loss
122
+ model.backward(loss)
123
+ model.step()
124
+ for _ in range(accelerator.num_processes):
125
+ lr_scheduler.step()
126
+
127
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
128
+ model.destroy()
129
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
130
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
131
+ )
132
+ assert trained_model_results["f1"] > base_model_results["f1"], (
133
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
134
+ )
135
+
136
+ del config
137
+ return base_model_results, trained_model_results, model_outputs, data
138
+
139
+
140
+ def train_integration(zero_stage: int = 1):
141
+ set_seed(42)
142
+ AcceleratorState()._reset_state(True)
143
+ config = HfDeepSpeedConfig(
144
+ {
145
+ "train_micro_batch_size_per_gpu": 16,
146
+ "gradient_accumulation_steps": 1,
147
+ "zero_optimization": {"stage": zero_stage},
148
+ }
149
+ )
150
+ deepspeed_plugin = DeepSpeedPlugin(
151
+ hf_ds_config=config,
152
+ )
153
+ # This forces transformers to think Zero-3 Init should be used
154
+ with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock:
155
+ mock.return_value = zero_stage == 3
156
+ accelerator = Accelerator(
157
+ mixed_precision="fp8", kwargs_handlers=[AORecipeKwargs()], deepspeed_plugin=deepspeed_plugin
158
+ )
159
+
160
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
161
+ MODEL_NAME, accelerator=accelerator
162
+ )
163
+
164
+ model, optimizer, lr_scheduler, train_dataloader, eval_dataloader = accelerator.prepare(
165
+ model, optimizer, lr_scheduler, train_dataloader, eval_dataloader
166
+ )
167
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
168
+ model.train()
169
+ model_outputs = []
170
+ data = []
171
+ for batch in train_dataloader:
172
+ outputs = model(**batch)
173
+ data.append(batch.to("cpu"))
174
+ model_outputs.append(outputs.logits.to("cpu"))
175
+ loss = outputs.loss
176
+ accelerator.backward(loss)
177
+ optimizer.step()
178
+ lr_scheduler.step()
179
+ optimizer.zero_grad()
180
+
181
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
182
+ model.destroy()
183
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
184
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
185
+ )
186
+ assert trained_model_results["f1"] > base_model_results["f1"], (
187
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
188
+ )
189
+
190
+ del config
191
+ return base_model_results, trained_model_results, model_outputs, data
192
+
193
+
194
+ if __name__ == "__main__":
195
+ for zero_stage in [1, 2, 3]:
196
+ baseline_not_trained, baseline_trained, baseline_outputs, baseline_data = train_baseline(zero_stage)
197
+ accelerator_not_trained, accelerator_trained, accelerator_outputs, accelerator_data = train_integration(
198
+ zero_stage
199
+ )
200
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
201
+ f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
202
+ )
203
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
204
+ f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
205
+ )
206
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
207
+ f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
208
+ )
209
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
210
+ f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
211
+ )
212
+ AcceleratorState()._reset_state(True)
213
+ torch.distributed.destroy_process_group()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/fp8_utils.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+
16
+
17
+ def get_dataloaders(model_name: str, batch_size: int = 16):
18
+ from datasets import load_dataset
19
+ from torch.utils.data import DataLoader
20
+ from transformers import AutoTokenizer
21
+
22
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
23
+ datasets = load_dataset("glue", "mrpc")
24
+
25
+ def tokenize_function(examples):
26
+ # max_length=None => use the model max length (it's actually the default)
27
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
28
+ return outputs
29
+
30
+ # Apply the method we just defined to all the examples in all the splits of the dataset
31
+ # starting with the main process first:
32
+ tokenized_datasets = datasets.map(
33
+ tokenize_function,
34
+ batched=True,
35
+ remove_columns=["idx", "sentence1", "sentence2"],
36
+ )
37
+
38
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
39
+ # transformers library
40
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
41
+
42
+ def collate_fn(examples):
43
+ return tokenizer.pad(
44
+ examples,
45
+ padding="longest",
46
+ pad_to_multiple_of=16, # Specific for FP8
47
+ return_tensors="pt",
48
+ )
49
+
50
+ # Instantiate dataloaders.
51
+ train_dataloader = DataLoader(
52
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
53
+ )
54
+ eval_dataloader = DataLoader(
55
+ tokenized_datasets["validation"],
56
+ shuffle=False,
57
+ collate_fn=collate_fn,
58
+ batch_size=16,
59
+ drop_last=True,
60
+ )
61
+
62
+ return train_dataloader, eval_dataloader
63
+
64
+
65
+ def get_training_utilities(model_name: str, batch_size: int = 16, accelerator=None, prepare=True):
66
+ """
67
+ Returns a tuple of:
68
+ - Model
69
+ - Optimizer
70
+ - Train dataloader (prepared)
71
+ - Eval dataloader (prepared)
72
+ - LR Scheduler
73
+ Suitable for training on the MRPC dataset
74
+ """
75
+ from torch.optim import AdamW
76
+ from transformers import AutoModelForSequenceClassification, get_linear_schedule_with_warmup
77
+
78
+ from accelerate import Accelerator
79
+
80
+ if accelerator is None:
81
+ accelerator = Accelerator()
82
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
83
+ train_dataloader, eval_dataloader = get_dataloaders(model_name, batch_size)
84
+ optimizer = AdamW(model.parameters(), lr=0.0001)
85
+ lr_scheduler = get_linear_schedule_with_warmup(
86
+ optimizer=optimizer,
87
+ num_warmup_steps=100,
88
+ num_training_steps=len(train_dataloader) * 2,
89
+ )
90
+ train_dataloader, eval_dataloader = accelerator.prepare(train_dataloader, eval_dataloader)
91
+ return model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
92
+
93
+
94
+ def get_named_parameters(model):
95
+ """
96
+ Same thing as `Accelerator.get_named_parameters` Returns a list of the named parameters of the model (extracted
97
+ from parallel)
98
+ """
99
+ from accelerate.utils import extract_model_from_parallel
100
+
101
+ model = extract_model_from_parallel(model)
102
+ return {n: p for n, p in model.named_parameters()}
103
+
104
+
105
+ def evaluate_model(model, dataloader, metric, accelerator=None):
106
+ "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
107
+ model.eval()
108
+ for step, batch in enumerate(dataloader):
109
+ with torch.no_grad():
110
+ outputs = model(**batch)
111
+ predictions = outputs.logits.argmax(dim=-1)
112
+ references = batch["labels"]
113
+ if accelerator is not None and accelerator.num_processes > 1:
114
+ predictions, references = accelerator.gather_for_metrics((predictions, references))
115
+ metric.add_batch(predictions=predictions, references=references)
116
+ return metric.compute()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/fsdp.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `torchao`.
17
+
18
+ This particular script verifies this for FSDP training.
19
+ """
20
+
21
+ from functools import partial
22
+
23
+ import evaluate
24
+ import torch
25
+ from fp8_utils import get_training_utilities
26
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
27
+ from torch.distributed.fsdp import MixedPrecision
28
+ from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
29
+ from torchao.float8 import convert_to_float8_training
30
+ from transformers.models.bert import BertLayer
31
+
32
+ from accelerate import Accelerator
33
+ from accelerate import FullyShardedDataParallelPlugin as FSDPPlugin
34
+ from accelerate.state import AcceleratorState
35
+ from accelerate.utils import AORecipeKwargs, set_seed
36
+
37
+
38
+ MODEL_NAME = "bert-base-cased"
39
+ METRIC = evaluate.load("glue", "mrpc")
40
+
41
+ FSDP_WRAP_POLICY = partial(transformer_auto_wrap_policy, transformer_layer_cls={BertLayer})
42
+
43
+
44
+ def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None):
45
+ if isinstance(module, torch.nn.Linear):
46
+ if module.in_features % 16 != 0 or module.out_features % 16 != 0:
47
+ return False
48
+ # For stability reasons, we skip the first and last linear layers
49
+ # Otherwise can lead to the model not training or converging properly
50
+ if fqn in (first_layer_name, last_layer_name):
51
+ return False
52
+ return True
53
+
54
+
55
+ def evaluate_model(model, dataloader, metric, accelerator=None):
56
+ "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
57
+ model.eval()
58
+ for step, batch in enumerate(dataloader):
59
+ with torch.no_grad():
60
+ outputs = model(**batch)
61
+ predictions = outputs.logits.argmax(dim=-1)
62
+ references = batch["labels"]
63
+ if accelerator is not None and accelerator.num_processes > 1:
64
+ predictions, references = accelerator.gather_for_metrics((predictions, references))
65
+ metric.add_batch(predictions=predictions, references=references)
66
+ return metric.compute()
67
+
68
+
69
+ def train_baseline():
70
+ set_seed(42)
71
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
72
+ first_linear = None
73
+ last_linear = None
74
+ for name, module in model.named_modules():
75
+ if isinstance(module, torch.nn.Linear):
76
+ if first_linear is None:
77
+ first_linear = name
78
+ last_linear = name
79
+ func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear)
80
+ accelerator = Accelerator()
81
+ device = accelerator.device
82
+ model.to(device)
83
+
84
+ convert_to_float8_training(model, module_filter_fn=func)
85
+
86
+ # Convert the model to FSDP
87
+ model = FSDP(
88
+ model,
89
+ use_orig_params=True,
90
+ mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
91
+ auto_wrap_policy=FSDP_WRAP_POLICY,
92
+ )
93
+
94
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
95
+ model.train()
96
+
97
+ for batch in train_dataloader:
98
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
99
+ batch = batch.to(device)
100
+ outputs = model(**batch)
101
+ loss = outputs.loss
102
+ loss.backward()
103
+ optimizer.step()
104
+ optimizer.zero_grad()
105
+ lr_scheduler.step()
106
+
107
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
108
+
109
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
110
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
111
+ )
112
+ assert trained_model_results["f1"] > base_model_results["f1"], (
113
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
114
+ )
115
+
116
+ return base_model_results, trained_model_results
117
+
118
+
119
+ def train_integration():
120
+ AcceleratorState()._reset_state(True)
121
+ fsdp_plugin = FSDPPlugin(
122
+ auto_wrap_policy=FSDP_WRAP_POLICY,
123
+ use_orig_params=True,
124
+ mixed_precision_policy=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
125
+ )
126
+ accelerator = Accelerator(mixed_precision="fp8", fsdp_plugin=fsdp_plugin, kwargs_handlers=[AORecipeKwargs()])
127
+ set_seed(42)
128
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
129
+ MODEL_NAME, accelerator=accelerator
130
+ )
131
+
132
+ model, optimizer = accelerator.prepare(model, optimizer)
133
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
134
+ model.train()
135
+
136
+ for batch in train_dataloader:
137
+ outputs = model(**batch)
138
+ loss = outputs.loss
139
+ accelerator.backward(loss)
140
+ optimizer.step()
141
+ optimizer.zero_grad()
142
+ lr_scheduler.step()
143
+
144
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
145
+
146
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
147
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
148
+ )
149
+ assert trained_model_results["f1"] > base_model_results["f1"], (
150
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
151
+ )
152
+
153
+ return base_model_results, trained_model_results
154
+
155
+
156
+ if __name__ == "__main__":
157
+ baseline_not_trained, baseline_trained = train_baseline()
158
+ accelerator_not_trained, accelerator_trained = train_integration()
159
+
160
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
161
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
162
+ )
163
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
164
+ f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
165
+ )
166
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
167
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
168
+ )
169
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
170
+ f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
171
+ )
172
+
173
+ torch.distributed.destroy_process_group()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/torchao/non_distributed.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `torchao`.
17
+
18
+ This particular script verifies this for single GPU training.
19
+ """
20
+
21
+ from functools import partial
22
+
23
+ import evaluate
24
+ import torch
25
+ from fp8_utils import get_training_utilities
26
+ from torchao.float8 import convert_to_float8_training
27
+
28
+ from accelerate import Accelerator
29
+ from accelerate.state import AcceleratorState
30
+ from accelerate.utils import AORecipeKwargs, set_seed
31
+
32
+
33
+ MODEL_NAME = "bert-base-cased"
34
+ METRIC = evaluate.load("glue", "mrpc")
35
+
36
+
37
+ def evaluate_model(model, dataloader, metric, accelerator=None):
38
+ "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
39
+ model.eval()
40
+ for step, batch in enumerate(dataloader):
41
+ with torch.no_grad():
42
+ outputs = model(**batch)
43
+ predictions = outputs.logits.argmax(dim=-1)
44
+ references = batch["labels"]
45
+ if accelerator is not None and accelerator.num_processes > 1:
46
+ predictions, references = accelerator.gather_for_metrics((predictions, references))
47
+ metric.add_batch(predictions=predictions, references=references)
48
+ return metric.compute()
49
+
50
+
51
+ def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None):
52
+ if isinstance(module, torch.nn.Linear):
53
+ if module.in_features % 16 != 0 or module.out_features % 16 != 0:
54
+ return False
55
+ # For stability reasons, we skip the first and last linear layers
56
+ # Otherwise can lead to the model not training or converging properly
57
+ if fqn in (first_layer_name, last_layer_name):
58
+ return False
59
+ return True
60
+
61
+
62
+ def train_baseline():
63
+ set_seed(42)
64
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
65
+ first_linear = None
66
+ last_linear = None
67
+ for name, module in model.named_modules():
68
+ if isinstance(module, torch.nn.Linear):
69
+ if first_linear is None:
70
+ first_linear = name
71
+ last_linear = name
72
+
73
+ func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear)
74
+ model.to("cuda")
75
+ convert_to_float8_training(model, module_filter_fn=func)
76
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC)
77
+ model.train()
78
+
79
+ for batch in train_dataloader:
80
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
81
+ outputs = model(**batch)
82
+ loss = outputs.loss
83
+ loss.backward()
84
+ optimizer.step()
85
+ optimizer.zero_grad()
86
+ lr_scheduler.step()
87
+
88
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
89
+
90
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
91
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
92
+ )
93
+ assert trained_model_results["f1"] > base_model_results["f1"], (
94
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
95
+ )
96
+
97
+ return base_model_results, trained_model_results
98
+
99
+
100
+ def train_integration():
101
+ set_seed(42)
102
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[AORecipeKwargs()])
103
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
104
+ MODEL_NAME, accelerator=accelerator
105
+ )
106
+ model = accelerator.prepare(model)
107
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC)
108
+ model.train()
109
+
110
+ for batch in train_dataloader:
111
+ outputs = model(**batch)
112
+ loss = outputs.loss
113
+ loss.backward()
114
+ optimizer.step()
115
+ optimizer.zero_grad()
116
+ lr_scheduler.step()
117
+
118
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
119
+
120
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
121
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
122
+ )
123
+ assert trained_model_results["f1"] > base_model_results["f1"], (
124
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
125
+ )
126
+
127
+ return base_model_results, trained_model_results
128
+
129
+
130
+ if __name__ == "__main__":
131
+ baseline_not_trained, baseline_trained = train_baseline()
132
+ AcceleratorState._reset_state(True)
133
+ accelerator_not_trained, accelerator_trained = train_integration()
134
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
135
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
136
+ )
137
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
138
+ f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
139
+ )
140
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
141
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
142
+ )
143
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
144
+ f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
145
+ )
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_YEAR=25
2
+ ARG BASE_MONTH=03
3
+
4
+ FROM nvcr.io/nvidia/pytorch:${BASE_YEAR}.${BASE_MONTH}-py3
5
+
6
+ RUN pip install transformers evaluate datasets
7
+ RUN git clone https://github.com/huggingface/accelerate.git
8
+
9
+ RUN cd accelerate && \
10
+ pip install -e .[deepspeed] && \
11
+ cd benchmarks/fp8
12
+
13
+ RUN /bin/bash
14
+
15
+
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FP8 Benchmarks
2
+
3
+ Comparing and running [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) FP8 with accelerate
4
+
5
+ ## Overview
6
+
7
+ This repo provides scripts which compare native TransformerEngine model training against `accelerate`'s own integration. Each modeling type is segmented out via a script, supporting the following:
8
+
9
+ * Single GPU training (`non_distributed.py`)
10
+ * Multi-GPU training via DistributedDataParallelism (`ddp.py`)
11
+ * Fully Sharded Data Parallelism (`fsdp.py`)
12
+ * DeepSpeed ZeRO 1-3 (`deepspeed.py`)
13
+
14
+ To run them, it's recommended to use a docker image (see the attached `Dockerfile`) and not install `TransformerEngine` manually.
15
+
16
+ ## Running:
17
+
18
+ There are official Docker images located at `huggingface/accelerate:gpu-fp8-transformerengine-nightly` which can be used.
19
+
20
+ You can run all scripts using the core `accelerate launch` command without any `accelerate config` being needed.
21
+
22
+ For single GPU, run it via `python`:
23
+
24
+ ```bash
25
+ python non_distributed.py
26
+ ```
27
+
28
+ For the rest, run it via `accelerate launch`:
29
+
30
+ ```bash
31
+ accelerate launch ddp.py # or distrib_deepspeed.py, ddp.py
32
+ ```
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/ddp.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`.
17
+
18
+ This particular script verifies this for DDP training.
19
+ """
20
+
21
+ import evaluate
22
+ import torch
23
+ import transformer_engine.common.recipe as te_recipe
24
+ import transformer_engine.pytorch as te
25
+ from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities
26
+ from torch.nn.parallel import DistributedDataParallel as DDP
27
+ from transformer_engine.common.recipe import DelayedScaling
28
+
29
+ from accelerate import Accelerator
30
+ from accelerate.state import AcceleratorState
31
+ from accelerate.utils import FP8RecipeKwargs, set_seed
32
+ from accelerate.utils.transformer_engine import convert_model
33
+
34
+
35
+ MODEL_NAME = "bert-base-cased"
36
+ METRIC = evaluate.load("glue", "mrpc")
37
+
38
+
39
+ def train_baseline():
40
+ set_seed(42)
41
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
42
+ accelerator = Accelerator()
43
+ device = accelerator.device
44
+ model.to(device)
45
+
46
+ # Convert the model to TE
47
+ old_named_params = get_named_parameters(model)
48
+
49
+ with torch.no_grad():
50
+ convert_model(model)
51
+
52
+ FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"}
53
+ fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS)
54
+
55
+ new_named_params = get_named_parameters(model)
56
+
57
+ # Convert the model to DDP
58
+ device_ids, output_device = [accelerator.local_process_index], accelerator.local_process_index
59
+ model = DDP(model, device_ids=device_ids, output_device=output_device)
60
+
61
+ mapping = {p: new_named_params[n] for n, p in old_named_params.items()}
62
+ for param_group in optimizer.param_groups:
63
+ param_group["params"] = [mapping[p] for p in param_group["params"]]
64
+
65
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
66
+ model.train()
67
+
68
+ for _ in range(2):
69
+ for batch in train_dataloader:
70
+ with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
71
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
72
+ batch = batch.to(device)
73
+ outputs = model(**batch)
74
+ loss = outputs.loss
75
+ loss.backward()
76
+ optimizer.step()
77
+ optimizer.zero_grad()
78
+ lr_scheduler.step()
79
+
80
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
81
+
82
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
83
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
84
+ )
85
+ assert trained_model_results["f1"] > base_model_results["f1"], (
86
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
87
+ )
88
+
89
+ return base_model_results, trained_model_results
90
+
91
+
92
+ def train_integration():
93
+ FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"}
94
+ kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)]
95
+ AcceleratorState()._reset_state(True)
96
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=kwargs_handlers)
97
+ set_seed(42)
98
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
99
+ MODEL_NAME, accelerator=accelerator
100
+ )
101
+
102
+ model, optimizer = accelerator.prepare(model, optimizer)
103
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
104
+ model.train()
105
+
106
+ for _ in range(2):
107
+ for batch in train_dataloader:
108
+ outputs = model(**batch)
109
+ loss = outputs.loss
110
+ accelerator.backward(loss)
111
+ optimizer.step()
112
+ optimizer.zero_grad()
113
+ lr_scheduler.step()
114
+
115
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
116
+
117
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
118
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
119
+ )
120
+ assert trained_model_results["f1"] > base_model_results["f1"], (
121
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
122
+ )
123
+
124
+ return base_model_results, trained_model_results
125
+
126
+
127
+ if __name__ == "__main__":
128
+ baseline_not_trained, baseline_trained = train_baseline()
129
+ accelerator_not_trained, accelerator_trained = train_integration()
130
+
131
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
132
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
133
+ )
134
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
135
+ f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
136
+ )
137
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
138
+ f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
139
+ )
140
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
141
+ f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
142
+ )
143
+
144
+ torch.distributed.destroy_process_group()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/distrib_deepspeed.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`.
17
+
18
+ This particular script verifies this for DDP training.
19
+ """
20
+
21
+ from unittest.mock import patch
22
+
23
+ import deepspeed
24
+ import evaluate
25
+ import torch
26
+ import transformer_engine.common.recipe as te_recipe
27
+ import transformer_engine.pytorch as te
28
+ from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities
29
+ from transformer_engine.common.recipe import DelayedScaling
30
+
31
+ from accelerate import Accelerator, DeepSpeedPlugin
32
+ from accelerate.state import AcceleratorState
33
+ from accelerate.utils import FP8RecipeKwargs, set_seed
34
+ from accelerate.utils.transformer_engine import convert_model
35
+
36
+
37
+ MODEL_NAME = "bert-base-cased"
38
+ METRIC = evaluate.load("glue", "mrpc")
39
+
40
+
41
+ def train_baseline(zero_stage: int = 1):
42
+ # This forces transformers to think Zero-3 Init should be used
43
+ with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock:
44
+ mock.return_value = zero_stage == 3
45
+ set_seed(42)
46
+
47
+ accelerator = Accelerator()
48
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
49
+ MODEL_NAME, accelerator=accelerator
50
+ )
51
+
52
+ # Convert the model to TE
53
+ old_named_params = get_named_parameters(model)
54
+
55
+ with torch.no_grad():
56
+ convert_model(model)
57
+ new_named_params = get_named_parameters(model)
58
+
59
+ mapping = {p: new_named_params[n] for n, p in old_named_params.items()}
60
+ for param_group in optimizer.param_groups:
61
+ param_group["params"] = [mapping[p] for p in param_group["params"]]
62
+
63
+ FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"}
64
+ fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS)
65
+
66
+ import numpy as np
67
+
68
+ config = {
69
+ "train_batch_size": 16,
70
+ "train_micro_batch_size_per_gpu": 16,
71
+ "gradient_accumulation_steps": 1,
72
+ "zero_optimization": {
73
+ "stage": zero_stage,
74
+ "offload_optimizer": {"device": "none", "nvme_path": None},
75
+ "offload_param": {"device": "none", "nvme_path": None},
76
+ "stage3_gather_16bit_weights_on_model_save": False,
77
+ },
78
+ "gradient_clipping": 1.0,
79
+ "steps_per_print": np.inf,
80
+ "bf16": {"enabled": True},
81
+ "fp16": {"enabled": False},
82
+ "zero_allow_untested_optimizer": True,
83
+ }
84
+
85
+ (
86
+ model,
87
+ optimizer,
88
+ _,
89
+ _,
90
+ ) = deepspeed.initialize(
91
+ model=model,
92
+ optimizer=optimizer,
93
+ config_params=config,
94
+ )
95
+
96
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
97
+ model.train()
98
+
99
+ model_outputs = []
100
+ data = []
101
+
102
+ for _ in range(2):
103
+ for batch in train_dataloader:
104
+ with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
105
+ outputs = model(**batch)
106
+ data.append(batch.to("cpu"))
107
+ model_outputs.append(outputs.logits.to("cpu"))
108
+ loss = outputs.loss
109
+ model.backward(loss)
110
+ model.step()
111
+ for _ in range(accelerator.num_processes):
112
+ lr_scheduler.step()
113
+
114
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
115
+ model.destroy()
116
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
117
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
118
+ )
119
+ assert trained_model_results["f1"] > base_model_results["f1"], (
120
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
121
+ )
122
+
123
+ return base_model_results, trained_model_results, model_outputs, data
124
+
125
+
126
+ def train_integration(zero_stage: int = 1):
127
+ set_seed(42)
128
+ FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"}
129
+ kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)]
130
+ AcceleratorState()._reset_state(True)
131
+ deepspeed_plugin = DeepSpeedPlugin(
132
+ zero_stage=zero_stage,
133
+ zero3_init_flag=zero_stage == 3,
134
+ )
135
+ accelerator = Accelerator(
136
+ mixed_precision="fp8", kwargs_handlers=kwargs_handlers, deepspeed_plugin=deepspeed_plugin
137
+ )
138
+ accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = 16
139
+
140
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
141
+ MODEL_NAME, accelerator=accelerator
142
+ )
143
+
144
+ model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
145
+ base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
146
+ model.train()
147
+ model_outputs = []
148
+ data = []
149
+ for _ in range(2):
150
+ for batch in train_dataloader:
151
+ outputs = model(**batch)
152
+ data.append(batch.to("cpu"))
153
+ model_outputs.append(outputs.logits.to("cpu"))
154
+ loss = outputs.loss
155
+ accelerator.backward(loss)
156
+ optimizer.step()
157
+ lr_scheduler.step()
158
+ optimizer.zero_grad()
159
+
160
+ trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
161
+ model.destroy()
162
+ assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
163
+ f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
164
+ )
165
+ assert trained_model_results["f1"] > base_model_results["f1"], (
166
+ f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
167
+ )
168
+
169
+ return base_model_results, trained_model_results, model_outputs, data
170
+
171
+
172
+ if __name__ == "__main__":
173
+ for zero_stage in [1, 2, 3]:
174
+ baseline_not_trained, baseline_trained, baseline_outputs, baseline_data = train_baseline(zero_stage)
175
+ accelerator_not_trained, accelerator_trained, accelerator_outputs, accelerator_data = train_integration(
176
+ zero_stage
177
+ )
178
+ assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
179
+ f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
180
+ )
181
+ assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
182
+ f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
183
+ )
184
+ assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
185
+ f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
186
+ )
187
+ assert baseline_trained["f1"] == accelerator_trained["f1"], (
188
+ f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
189
+ )
190
+
191
+ torch.distributed.destroy_process_group()
tasks/tasksmith-b1dd32dfa88b/environment/source/benchmarks/fp8/transformer_engine/fp8_utils.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+
16
+
17
+ def get_dataloaders(model_name: str, batch_size: int = 16):
18
+ from datasets import load_dataset
19
+ from torch.utils.data import DataLoader
20
+ from transformers import AutoTokenizer
21
+
22
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
23
+ datasets = load_dataset("glue", "mrpc")
24
+
25
+ def tokenize_function(examples):
26
+ # max_length=None => use the model max length (it's actually the default)
27
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
28
+ return outputs
29
+
30
+ # Apply the method we just defined to all the examples in all the splits of the dataset
31
+ # starting with the main process first:
32
+ tokenized_datasets = datasets.map(
33
+ tokenize_function,
34
+ batched=True,
35
+ remove_columns=["idx", "sentence1", "sentence2"],
36
+ )
37
+
38
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
39
+ # transformers library
40
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
41
+
42
+ def collate_fn(examples):
43
+ return tokenizer.pad(
44
+ examples,
45
+ padding="longest",
46
+ pad_to_multiple_of=16, # Specific for FP8
47
+ return_tensors="pt",
48
+ )
49
+
50
+ # Instantiate dataloaders.
51
+ train_dataloader = DataLoader(
52
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
53
+ )
54
+ eval_dataloader = DataLoader(
55
+ tokenized_datasets["validation"],
56
+ shuffle=False,
57
+ collate_fn=collate_fn,
58
+ batch_size=16,
59
+ drop_last=True,
60
+ )
61
+
62
+ return train_dataloader, eval_dataloader
63
+
64
+
65
+ def get_training_utilities(model_name: str, batch_size: int = 16, accelerator=None):
66
+ """
67
+ Returns a tuple of:
68
+ - Model
69
+ - Optimizer
70
+ - Train dataloader (prepared)
71
+ - Eval dataloader (prepared)
72
+ - LR Scheduler
73
+ Suitable for training on the MRPC dataset
74
+ """
75
+ from torch.optim import AdamW
76
+ from transformers import AutoModelForSequenceClassification, get_linear_schedule_with_warmup
77
+
78
+ from accelerate import Accelerator
79
+
80
+ if accelerator is None:
81
+ accelerator = Accelerator()
82
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
83
+ train_dataloader, eval_dataloader = get_dataloaders(model_name, batch_size)
84
+ optimizer = AdamW(model.parameters(), lr=0.0001)
85
+ lr_scheduler = get_linear_schedule_with_warmup(
86
+ optimizer=optimizer,
87
+ num_warmup_steps=100,
88
+ num_training_steps=len(train_dataloader) * 2,
89
+ )
90
+ train_dataloader, eval_dataloader = accelerator.prepare(train_dataloader, eval_dataloader)
91
+ return model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
92
+
93
+
94
+ def get_named_parameters(model):
95
+ """
96
+ Same thing as `Accelerator.get_named_parameters` Returns a list of the named parameters of the model (extracted
97
+ from parallel)
98
+ """
99
+ from accelerate.utils import extract_model_from_parallel
100
+
101
+ model = extract_model_from_parallel(model)
102
+ return {n: p for n, p in model.named_parameters()}
103
+
104
+
105
+ def evaluate_model(model, dataloader, metric, accelerator=None):
106
+ "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
107
+ model.eval()
108
+ for step, batch in enumerate(dataloader):
109
+ with torch.no_grad():
110
+ outputs = model(**batch)
111
+ predictions = outputs.logits.argmax(dim=-1)
112
+ references = batch["labels"]
113
+ if accelerator is not None and accelerator.num_processes > 1:
114
+ predictions, references = accelerator.gather_for_metrics((predictions, references))
115
+ metric.add_batch(predictions=predictions, references=references)
116
+ return metric.compute()