hc99 commited on
Commit
c13737d
·
verified ·
1 Parent(s): dee9fba

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/graphql-python__graphene/setup.py +93 -0
  2. testbed/huggingface__accelerate/.devcontainer/devcontainer.json +25 -0
  3. testbed/huggingface__accelerate/.github/ISSUE_TEMPLATE/bug-report.yml +58 -0
  4. testbed/huggingface__accelerate/.github/workflows/build-docker-images-release.yml +64 -0
  5. testbed/huggingface__accelerate/.github/workflows/build_and_run_tests.yml +45 -0
  6. testbed/huggingface__accelerate/.github/workflows/build_documentation.yml +17 -0
  7. testbed/huggingface__accelerate/.github/workflows/build_pr_documentation.yml +16 -0
  8. testbed/huggingface__accelerate/.github/workflows/delete_doc_comment.yml +13 -0
  9. testbed/huggingface__accelerate/.github/workflows/nightly.yml +88 -0
  10. testbed/huggingface__accelerate/.github/workflows/quality.yml +17 -0
  11. testbed/huggingface__accelerate/.github/workflows/run_merge_tests.yml +89 -0
  12. testbed/huggingface__accelerate/.github/workflows/stale.yml +28 -0
  13. testbed/huggingface__accelerate/.github/workflows/test.yml +73 -0
  14. testbed/huggingface__accelerate/.gitignore +141 -0
  15. testbed/huggingface__accelerate/CODE_OF_CONDUCT.md +129 -0
  16. testbed/huggingface__accelerate/CONTRIBUTING.md +238 -0
  17. testbed/huggingface__accelerate/LICENSE +201 -0
  18. testbed/huggingface__accelerate/Makefile +67 -0
  19. testbed/huggingface__accelerate/README.md +259 -0
  20. testbed/huggingface__accelerate/benchmarks/README.md +46 -0
  21. testbed/huggingface__accelerate/benchmarks/big_model_inference.py +143 -0
  22. testbed/huggingface__accelerate/benchmarks/measures_util.py +86 -0
  23. testbed/huggingface__accelerate/docker/accelerate-cpu/Dockerfile +35 -0
  24. testbed/huggingface__accelerate/docker/accelerate-gpu/Dockerfile +42 -0
  25. testbed/huggingface__accelerate/docs/Makefile +19 -0
  26. testbed/huggingface__accelerate/docs/README.md +267 -0
  27. testbed/huggingface__accelerate/docs/source/_toctree.yml +78 -0
  28. testbed/huggingface__accelerate/docs/source/basic_tutorials/migration.mdx +123 -0
  29. testbed/huggingface__accelerate/docs/source/basic_tutorials/notebook.mdx +429 -0
  30. testbed/huggingface__accelerate/docs/source/basic_tutorials/overview.mdx +21 -0
  31. testbed/huggingface__accelerate/docs/source/concept_guides/deferring_execution.mdx +107 -0
  32. testbed/huggingface__accelerate/docs/source/concept_guides/gradient_synchronization.mdx +119 -0
  33. testbed/huggingface__accelerate/docs/source/concept_guides/performance.mdx +91 -0
  34. testbed/huggingface__accelerate/docs/source/concept_guides/training_tpu.mdx +164 -0
  35. testbed/huggingface__accelerate/docs/source/index.mdx +71 -0
  36. testbed/huggingface__accelerate/docs/source/package_reference/accelerator.mdx +163 -0
  37. testbed/huggingface__accelerate/docs/source/package_reference/big_modeling.mdx +41 -0
  38. testbed/huggingface__accelerate/docs/source/package_reference/cli.mdx +273 -0
  39. testbed/huggingface__accelerate/docs/source/package_reference/deepspeed.mdx +25 -0
  40. testbed/huggingface__accelerate/docs/source/package_reference/kwargs.mdx +29 -0
  41. testbed/huggingface__accelerate/docs/source/package_reference/launchers.mdx +19 -0
  42. testbed/huggingface__accelerate/docs/source/package_reference/logging.mdx +34 -0
  43. testbed/huggingface__accelerate/docs/source/package_reference/megatron_lm.mdx +29 -0
  44. testbed/huggingface__accelerate/docs/source/package_reference/state.mdx +23 -0
  45. testbed/huggingface__accelerate/docs/source/package_reference/torch_wrappers.mdx +33 -0
  46. testbed/huggingface__accelerate/docs/source/package_reference/tracking.mdx +26 -0
  47. testbed/huggingface__accelerate/docs/source/package_reference/utilities.mdx +104 -0
  48. testbed/huggingface__accelerate/docs/source/quicktour.mdx +505 -0
  49. testbed/huggingface__accelerate/docs/source/usage_guides/big_modeling.mdx +294 -0
  50. testbed/huggingface__accelerate/docs/source/usage_guides/checkpoint.mdx +63 -0
testbed/graphql-python__graphene/setup.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import codecs
3
+ import re
4
+ import sys
5
+
6
+ from setuptools import find_packages, setup
7
+ from setuptools.command.test import test as TestCommand
8
+
9
+ _version_re = re.compile(r"VERSION\s+=\s+(.*)")
10
+
11
+ with open("graphene/__init__.py", "rb") as f:
12
+ version = ast.literal_eval(_version_re.search(f.read().decode("utf-8")).group(1))
13
+
14
+ path_copy = sys.path[:]
15
+
16
+ sys.path.append("graphene")
17
+ try:
18
+ from pyutils.version import get_version
19
+
20
+ version = get_version(version)
21
+ except Exception:
22
+ version = ".".join([str(v) for v in version])
23
+
24
+ sys.path[:] = path_copy
25
+
26
+
27
+ class PyTest(TestCommand):
28
+ user_options = [("pytest-args=", "a", "Arguments to pass to py.test")]
29
+
30
+ def initialize_options(self):
31
+ TestCommand.initialize_options(self)
32
+ self.pytest_args = []
33
+
34
+ def finalize_options(self):
35
+ TestCommand.finalize_options(self)
36
+ self.test_args = []
37
+ self.test_suite = True
38
+
39
+ def run_tests(self):
40
+ # import here, cause outside the eggs aren't loaded
41
+ import pytest
42
+
43
+ errno = pytest.main(self.pytest_args)
44
+ sys.exit(errno)
45
+
46
+
47
+ tests_require = [
48
+ "pytest>=6,<7",
49
+ "pytest-benchmark>=3.4,<4",
50
+ "pytest-cov>=3,<4",
51
+ "pytest-mock>=3,<4",
52
+ "pytest-asyncio>=0.16,<2",
53
+ "snapshottest>=0.6,<1",
54
+ "coveralls>=3.3,<4",
55
+ "mock>=4,<5",
56
+ "pytz==2022.1",
57
+ "iso8601>=1,<2",
58
+ ]
59
+
60
+ dev_requires = ["black==22.3.0", "flake8>=4,<5"] + tests_require
61
+
62
+ setup(
63
+ name="graphene",
64
+ version=version,
65
+ description="GraphQL Framework for Python",
66
+ long_description=codecs.open(
67
+ "README.rst", "r", encoding="ascii", errors="replace"
68
+ ).read(),
69
+ url="https://github.com/graphql-python/graphene",
70
+ author="Syrus Akbary",
71
+ author_email="me@syrusakbary.com",
72
+ license="MIT",
73
+ classifiers=[
74
+ "Development Status :: 3 - Alpha",
75
+ "Intended Audience :: Developers",
76
+ "Topic :: Software Development :: Libraries",
77
+ "Programming Language :: Python :: 3.6",
78
+ "Programming Language :: Python :: 3.7",
79
+ "Programming Language :: Python :: 3.8",
80
+ "Programming Language :: Python :: 3.9",
81
+ "Programming Language :: Python :: 3.10",
82
+ ],
83
+ keywords="api graphql protocol rest relay graphene",
84
+ packages=find_packages(exclude=["examples*"]),
85
+ install_requires=[
86
+ "graphql-core>=3.1,<3.3",
87
+ "graphql-relay>=3.1,<3.3",
88
+ "aniso8601>=8,<10",
89
+ ],
90
+ tests_require=tests_require,
91
+ extras_require={"test": tests_require, "dev": dev_requires},
92
+ cmdclass={"test": PyTest},
93
+ )
testbed/huggingface__accelerate/.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "extensions": [
19
+ // Ensure we have IntelliSense in VSCode when running inside container
20
+ "ms-python.python"
21
+ ],
22
+ "workspaceFolder": "/workspaces/accelerate",
23
+ // Need git for VSCode to color code modifications. Only runs when building environment.
24
+ "onCreateCommand": "apt-get update && apt-get install -y git && pip install -e '.[dev]'"
25
+ }
testbed/huggingface__accelerate/.github/ISSUE_TEMPLATE/bug-report.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F41B Bug Report"
2
+ description: Submit a bug report to help us improve Accelerate
3
+ body:
4
+ - type: textarea
5
+ id: system-info
6
+ attributes:
7
+ label: System Info
8
+ description: Please share your accelerate configuration with us. You can run the command `accelerate env` and copy-paste its outputs below
9
+ render: Shell
10
+ placeholder: accelerate version, OS, python version, numpy version, torch version, and accelerate's configuration
11
+ validations:
12
+ required: true
13
+
14
+ - type: checkboxes
15
+ id: information-scripts-examples
16
+ attributes:
17
+ label: Information
18
+ description: 'The problem arises when using:'
19
+ options:
20
+ - label: "The official example scripts"
21
+ - label: "My own modified scripts"
22
+
23
+ - type: checkboxes
24
+ id: information-tasks
25
+ attributes:
26
+ label: Tasks
27
+ description: "The tasks I am working on are:"
28
+ options:
29
+ - 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`)"
30
+ - label: "My own task or dataset (give details below)"
31
+
32
+ - type: textarea
33
+ id: reproduction
34
+ validations:
35
+ required: true
36
+ attributes:
37
+ label: Reproduction
38
+ description: |
39
+ Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
40
+ If you have code snippets, error messages, stack traces please provide them here as well.
41
+ 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
42
+ Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
43
+
44
+ placeholder: |
45
+ Steps to reproduce the behavior:
46
+
47
+ 1.
48
+ 2.
49
+ 3.
50
+
51
+ - type: textarea
52
+ id: expected-behavior
53
+ validations:
54
+ required: true
55
+ attributes:
56
+ label: Expected behavior
57
+ description: "A clear and concise description of what you would expect to happen."
58
+ render: Shell
testbed/huggingface__accelerate/.github/workflows/build-docker-images-release.yml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@v3
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: ubuntu-latest
25
+ needs: get-version
26
+ steps:
27
+ - name: Set up Docker Buildx
28
+ uses: docker/setup-buildx-action@v1
29
+ - name: Check out code
30
+ uses: actions/checkout@v2
31
+ - name: Login to DockerHub
32
+ uses: docker/login-action@v1
33
+ with:
34
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
35
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
36
+
37
+ - name: Build and Push CPU
38
+ uses: docker/build-push-action@v2
39
+ with:
40
+ context: ./docker/accelerate-cpu
41
+ push: true
42
+ tags: huggingface/accelerate-cpu:${{needs.get-version.outputs.version}}
43
+
44
+ version-cuda:
45
+ name: "Latest Accelerate GPU [version]"
46
+ runs-on: ubuntu-latest
47
+ needs: get-version
48
+ steps:
49
+ - name: Set up Docker Buildx
50
+ uses: docker/setup-buildx-action@v1
51
+ - name: Check out code
52
+ uses: actions/checkout@v2
53
+ - name: Login to DockerHub
54
+ uses: docker/login-action@v1
55
+ with:
56
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
57
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
58
+
59
+ - name: Build and Push GPU
60
+ uses: docker/build-push-action@v2
61
+ with:
62
+ context: ./docker/accelerate-gpu
63
+ push: true
64
+ tags: huggingface/accelerate-gpu:${{needs.get-version.outputs.version}}
testbed/huggingface__accelerate/.github/workflows/build_and_run_tests.yml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@v3.1.0
20
+ with:
21
+ fetch-depth: "2"
22
+
23
+ - name: Get changed files
24
+ id: changed-files
25
+ uses: tj-actions/changed-files@v22.2
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
testbed/huggingface__accelerate/.github/workflows/build_documentation.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ secrets:
17
+ token: ${{ secrets.HUGGINGFACE_PUSH }}
testbed/huggingface__accelerate/.github/workflows/build_pr_documentation.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
testbed/huggingface__accelerate/.github/workflows/delete_doc_comment.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Delete dev documentation
2
+
3
+ on:
4
+ pull_request:
5
+ types: [ closed ]
6
+
7
+
8
+ jobs:
9
+ delete:
10
+ uses: huggingface/doc-builder/.github/workflows/delete_doc_comment.yml@main
11
+ with:
12
+ pr_number: ${{ github.event.number }}
13
+ package: accelerate
testbed/huggingface__accelerate/.github/workflows/nightly.yml ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ jobs:
13
+ run_all_tests_single_gpu:
14
+ runs-on: [self-hosted, docker-gpu, multi-gpu]
15
+ env:
16
+ CUDA_VISIBLE_DEVICES: "0"
17
+ container:
18
+ image: huggingface/accelerate-gpu:latest
19
+ options: --gpus all --shm-size "16gb"
20
+ defaults:
21
+ run:
22
+ working-directory: accelerate/
23
+ shell: bash
24
+ steps:
25
+ - name: Update clone & pip install
26
+ run: |
27
+ source activate accelerate
28
+ git config --global --add safe.directory '*'
29
+ git fetch && git checkout ${{ github.sha }}
30
+ pip install -e . --no-deps
31
+ pip install pytest-reportlog
32
+
33
+ - name: Run test on GPUs
34
+ run: |
35
+ source activate accelerate
36
+ make test
37
+ - name: Run examples on GPUs
38
+ run: |
39
+ source activate accelerate
40
+ pip uninstall comet_ml -y
41
+ make test_examples
42
+
43
+ - name: Generate Report
44
+ if: always()
45
+ run: |
46
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
47
+
48
+ run_all_tests_multi_gpu:
49
+ runs-on: [self-hosted, docker-gpu, multi-gpu]
50
+ env:
51
+ CUDA_VISIBLE_DEVICES: "0,1"
52
+ container:
53
+ image: huggingface/accelerate-gpu:latest
54
+ options: --gpus all --shm-size "16gb"
55
+ defaults:
56
+ run:
57
+ working-directory: accelerate/
58
+ shell: bash
59
+ steps:
60
+ - name: Update clone
61
+ run: |
62
+ source activate accelerate
63
+ git config --global --add safe.directory '*'
64
+ git fetch && git checkout ${{ github.sha }}
65
+ pip install -e . --no-deps
66
+ pip install pytest-reportlog
67
+
68
+ - name: Run core and big modeling tests on GPUs
69
+ run: |
70
+ source activate accelerate
71
+ make test_big_modeling
72
+ make test_core
73
+
74
+ - name: Run Integration tests on GPUs
75
+ run: |
76
+ source activate accelerate
77
+ make test_integrations
78
+
79
+ - name: Run examples on GPUs
80
+ run: |
81
+ source activate accelerate
82
+ pip uninstall comet_ml -y
83
+ make test_examples
84
+
85
+ - name: Generate Report
86
+ if: always()
87
+ run: |
88
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
testbed/huggingface__accelerate/.github/workflows/quality.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@v2
10
+ - name: Set up Python 3.7
11
+ uses: actions/setup-python@v3
12
+ with:
13
+ python-version: 3.7
14
+ - name: Install Python dependencies
15
+ run: pip install -e .[quality]
16
+ - name: Run Quality check
17
+ run: make quality
testbed/huggingface__accelerate/.github/workflows/run_merge_tests.yml ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_all_tests_single_gpu:
13
+ runs-on: [self-hosted, docker-gpu, multi-gpu]
14
+ env:
15
+ CUDA_VISIBLE_DEVICES: "0"
16
+ container:
17
+ image: huggingface/accelerate-gpu:latest
18
+ options: --gpus all --shm-size "16gb"
19
+ defaults:
20
+ run:
21
+ working-directory: accelerate/
22
+ shell: bash
23
+ steps:
24
+ - name: Update clone & pip install
25
+ run: |
26
+ source activate accelerate
27
+ git config --global --add safe.directory '*'
28
+ git fetch && git checkout ${{ github.sha }}
29
+ pip install -e .[testing,test_trackers]
30
+ pip install pytest-reportlog
31
+
32
+ - name: Run CLI tests
33
+ run: |
34
+ source activate accelerate
35
+ make test_cli
36
+
37
+ - name: Run test on GPUs
38
+ run: |
39
+ source activate accelerate
40
+ make test
41
+ - name: Run examples on GPUs
42
+ run: |
43
+ source activate accelerate
44
+ pip uninstall comet_ml -y
45
+ make test_examples
46
+
47
+ - name: Generate Report
48
+ if: always()
49
+ run: |
50
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
51
+
52
+ run_all_tests_multi_gpu:
53
+ runs-on: [self-hosted, docker-gpu, multi-gpu]
54
+ container:
55
+ image: huggingface/accelerate-gpu:latest
56
+ options: --gpus all --shm-size "16gb"
57
+ defaults:
58
+ run:
59
+ working-directory: accelerate/
60
+ shell: bash
61
+ steps:
62
+ - name: Update clone
63
+ run: |
64
+ source activate accelerate
65
+ git config --global --add safe.directory '*'
66
+ git fetch && git checkout ${{ github.sha }}
67
+ pip install -e .[testing,test_trackers]
68
+ pip install pytest-reportlog
69
+
70
+ - name: Run CLI tests
71
+ run: |
72
+ source activate accelerate
73
+ make test_cli
74
+
75
+ - name: Run test on GPUs
76
+ run: |
77
+ source activate accelerate
78
+ make test
79
+
80
+ - name: Run examples on GPUs
81
+ run: |
82
+ source activate accelerate
83
+ pip uninstall comet_ml -y
84
+ make test_examples
85
+
86
+ - name: Generate Report
87
+ if: always()
88
+ run: |
89
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
testbed/huggingface__accelerate/.github/workflows/stale.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ env:
14
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
15
+ steps:
16
+ - uses: actions/checkout@v2
17
+
18
+ - name: Setup Python
19
+ uses: actions/setup-python@v1
20
+ with:
21
+ python-version: 3.7
22
+
23
+ - name: Install requirements
24
+ run: |
25
+ pip install PyGithub
26
+ - name: Close stale issues
27
+ run: |
28
+ python utils/stale.py
testbed/huggingface__accelerate/.github/workflows/test.yml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@v3.1.0
42
+ - name: Set up python 3.7
43
+ uses: actions/setup-python@v3
44
+ with:
45
+ python-version: 3.7
46
+
47
+ - name: Activate python cache
48
+ uses: actions/cache@v3
49
+ with:
50
+ path: |
51
+ ${{ env.pythonLocation }}
52
+ ${{ env.HF_HOME }}
53
+ key: ${{ env.pythonLocation }}-${{ matrix.pytorch-version }}-${{ matrix.test-kind }}-${{ hashFiles('setup.py') }}
54
+
55
+ - name: Install the library
56
+ run: |
57
+ pip install --upgrade pip
58
+ if [[ ${{ matrix.test-kind }} = test_prod ]]; then pip install -e .[test_prod]; fi
59
+ if [[ ${{ matrix.test-kind }} != test_prod ]]; then pip install -e .[testing,test_trackers]; fi
60
+ if [[ ${{ matrix.test-kind }} = test_rest ]]; then pip uninstall comet_ml -y; fi
61
+ if [[ ${{ matrix.pytorch-version }} = minimum ]]; then pip install torch==1.6.0; fi
62
+ pip install pytest-reportlog
63
+
64
+ - name: Run Tests
65
+ env:
66
+ PYTORCH_VERSION: ${{ matrix.pytorch-version }}
67
+ run: |
68
+ make ${{ matrix.test-kind }}
69
+
70
+ - name: Generate Report
71
+ if: always()
72
+ run: |
73
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
testbed/huggingface__accelerate/.gitignore ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
testbed/huggingface__accelerate/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.
testbed/huggingface__accelerate/CONTRIBUTING.md ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ".[quality]"
127
+ ```
128
+
129
+ (If accelerate was already installed in the virtual environment, remove
130
+ it with `pip uninstall accelerate` before reinstalling it in editable
131
+ mode with the `-e` flag.)
132
+
133
+ Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using
134
+ the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers).
135
+
136
+ 5. Develop the features on your branch.
137
+
138
+ As you work on the features, you should make sure that the test suite
139
+ passes. You should run the tests impacted by your changes like this (see
140
+ below an explanation regarding the environment variable):
141
+
142
+ ```bash
143
+ $ pytest tests/<TEST_TO_RUN>.py
144
+ ```
145
+
146
+ > For the following commands leveraging the `make` utility, we recommend using the WSL system when running on
147
+ > Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about).
148
+
149
+ You can also run the full suite with the following command.
150
+
151
+ ```bash
152
+ $ make test
153
+ ```
154
+
155
+ `accelerate` relies on `black` and `isort` to format its source code
156
+ consistently. After you make changes, apply automatic style corrections and code verifications
157
+ that can't be automated in one go with:
158
+
159
+ This target is also optimized to only work with files modified by the PR you're working on.
160
+
161
+ If you prefer to run the checks one after the other, the following command apply the
162
+ style corrections:
163
+
164
+ ```bash
165
+ $ make style
166
+ ```
167
+
168
+ `accelerate` also uses `flake8` and a few custom scripts to check for coding mistakes. Quality
169
+ control runs in CI, however you can also run the same checks with:
170
+
171
+ ```bash
172
+ $ make quality
173
+ ```
174
+
175
+ Once you're happy with your changes, add changed files using `git add` and
176
+ make a commit with `git commit` to record your changes locally:
177
+
178
+ ```bash
179
+ $ git add modified_file.py
180
+ $ git commit
181
+ ```
182
+
183
+ Please write [good commit messages](https://chris.beams.io/posts/git-commit/).
184
+
185
+ It is a good idea to sync your copy of the code with the original
186
+ repository regularly. This way you can quickly account for changes:
187
+
188
+ ```bash
189
+ $ git fetch upstream
190
+ $ git rebase upstream/main
191
+ ```
192
+
193
+ Push the changes to your account using:
194
+
195
+ ```bash
196
+ $ git push -u origin a-descriptive-name-for-my-changes
197
+ ```
198
+
199
+ 6. Once you are satisfied (**and the checklist below is happy too**), go to the
200
+ webpage of your fork on GitHub. Click on 'Pull request' to send your changes
201
+ to the project maintainers for review.
202
+
203
+ 7. It's ok if maintainers ask you for changes. It happens to core contributors
204
+ too! So everyone can see the changes in the Pull request, work in your local
205
+ branch and push the changes to your fork. They will automatically appear in
206
+ the pull request.
207
+
208
+
209
+ ### Checklist
210
+
211
+ 1. The title of your pull request should be a summary of its contribution;
212
+ 2. If your pull request addresses an issue, please mention the issue number in
213
+ the pull request description to make sure they are linked (and people
214
+ consulting the issue know you are working on it);
215
+ 3. To indicate a work in progress please prefix the title with `[WIP]`, or mark
216
+ the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate
217
+ it from PRs ready to be merged;
218
+ 4. Make sure existing tests pass;
219
+ 5. Add high-coverage tests. No quality testing = no merge.
220
+
221
+ See an example of a good PR here: https://github.com/huggingface/accelerate/pull/255
222
+
223
+ ### Tests
224
+
225
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
226
+ the [tests folder](https://github.com/huggingface/accelerate/tree/main/tests).
227
+
228
+ We use `pytest` in order to run the tests. From the root of the
229
+ repository, here's how to run tests with `pytest` for the library:
230
+
231
+ ```bash
232
+ $ python -m pytest -sv ./tests
233
+ ```
234
+
235
+ In fact, that's how `make test` is implemented (sans the `pip install` line)!
236
+
237
+ You can specify a smaller set of tests in order to test only the feature
238
+ you're working on.
testbed/huggingface__accelerate/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.
testbed/huggingface__accelerate/Makefile ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: quality style test docs
2
+
3
+ check_dirs := tests src examples benchmarks
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
+ black --check $(check_dirs)
16
+ isort --check-only $(check_dirs)
17
+ flake8 $(check_dirs)
18
+ doc-builder style src/accelerate docs/source --max_len 119 --check_only
19
+
20
+ # Format source code automatically and check is there are any problems left that need manual fixing
21
+ style:
22
+ black $(check_dirs)
23
+ isort $(check_dirs)
24
+ doc-builder style src/accelerate docs/source --max_len 119
25
+
26
+ # Run tests for the library
27
+ test:
28
+ python -m pytest -s -v ./tests/ --ignore=./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_all.log",)
29
+
30
+ test_big_modeling:
31
+ python -m pytest -s -v ./tests/test_big_modeling.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_big_modeling.log",)
32
+
33
+ test_core:
34
+ python -m pytest -s -v ./tests/ --ignore=./tests/test_examples.py --ignore=./tests/deepspeed --ignore=./tests/test_big_modeling.py \
35
+ --ignore=./tests/fsdp --ignore=./tests/test_cli.py $(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_deepspeed:
41
+ python -m pytest -s -v ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_deepspeed.log",)
42
+
43
+ test_fsdp:
44
+ python -m pytest -s -v ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_fsdp.log",)
45
+
46
+ test_examples:
47
+ python -m pytest -s -v ./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_examples.log",)
48
+
49
+ # Broken down example tests for the CI runners
50
+ test_integrations:
51
+ python -m pytest -s -v ./tests/deepspeed ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_integrations.log",)
52
+
53
+ test_example_differences:
54
+ python -m pytest -s -v ./tests/test_examples.py::ExampleDifferenceTests $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_example_diff.log",)
55
+
56
+ test_checkpoint_epoch:
57
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_epoch.log",)
58
+
59
+ test_checkpoint_step:
60
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_step" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_step.log",)
61
+
62
+ # Same as test but used to install only the base dependencies
63
+ test_prod:
64
+ $(MAKE) test_core
65
+
66
+ test_rest:
67
+ 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",)
testbed/huggingface__accelerate/README.md ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="docs/source/imgs/accelerate_logo.png" width="400"/>
20
+ <br>
21
+ <p>
22
+
23
+ <p align="center">
24
+ <!-- Uncomment when CircleCI is setup
25
+ <a href="https://circleci.com/gh/huggingface/accelerate">
26
+ <img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master">
27
+ </a>
28
+ -->
29
+ <a href="https://github.com/huggingface/accelerate/blob/main/LICENSE">
30
+ <img alt="License" src="https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue">
31
+ </a>
32
+ <a href="https://huggingface.co/docs/accelerate/index.html">
33
+ <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">
34
+ </a>
35
+ <a href="https://github.com/huggingface/accelerate/releases">
36
+ <img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg">
37
+ </a>
38
+ <a href="https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md">
39
+ <img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg">
40
+ </a>
41
+ </p>
42
+
43
+ <h3 align="center">
44
+ <p>Run your *raw* PyTorch training script on any kind of device
45
+ </h3>
46
+
47
+ <h3 align="center">
48
+ <a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a>
49
+ </h3>
50
+
51
+ ## Easy to integrate
52
+
53
+ 🤗 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.
54
+
55
+ 🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.
56
+
57
+ Here is an example:
58
+
59
+ ```diff
60
+ import torch
61
+ import torch.nn.functional as F
62
+ from datasets import load_dataset
63
+ + from accelerate import Accelerator
64
+
65
+ + accelerator = Accelerator()
66
+ - device = 'cpu'
67
+ + device = accelerator.device
68
+
69
+ model = torch.nn.Transformer().to(device)
70
+ optimizer = torch.optim.Adam(model.parameters())
71
+
72
+ dataset = load_dataset('my_dataset')
73
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
74
+
75
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
76
+
77
+ model.train()
78
+ for epoch in range(10):
79
+ for source, targets in data:
80
+ source = source.to(device)
81
+ targets = targets.to(device)
82
+
83
+ optimizer.zero_grad()
84
+
85
+ output = model(source)
86
+ loss = F.cross_entropy(output, targets)
87
+
88
+ - loss.backward()
89
+ + accelerator.backward(loss)
90
+
91
+ optimizer.step()
92
+ ```
93
+
94
+ 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 (fp16).
95
+
96
+ In particular, the same code can then be run without modification on your local machine for debugging or your training environment.
97
+
98
+ 🤗 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:
99
+
100
+ ```diff
101
+ import torch
102
+ import torch.nn.functional as F
103
+ from datasets import load_dataset
104
+ + from accelerate import Accelerator
105
+
106
+ - device = 'cpu'
107
+ + accelerator = Accelerator()
108
+
109
+ - model = torch.nn.Transformer().to(device)
110
+ + model = torch.nn.Transformer()
111
+ optimizer = torch.optim.Adam(model.parameters())
112
+
113
+ dataset = load_dataset('my_dataset')
114
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
115
+
116
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
117
+
118
+ model.train()
119
+ for epoch in range(10):
120
+ for source, targets in data:
121
+ - source = source.to(device)
122
+ - targets = targets.to(device)
123
+
124
+ optimizer.zero_grad()
125
+
126
+ output = model(source)
127
+ loss = F.cross_entropy(output, targets)
128
+
129
+ - loss.backward()
130
+ + accelerator.backward(loss)
131
+
132
+ optimizer.step()
133
+ ```
134
+
135
+ Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
136
+
137
+ ## Launching script
138
+
139
+ 🤗 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.launch` or to write a specific launcher for TPU training!
140
+ On your machine(s) just run:
141
+
142
+ ```bash
143
+ accelerate config
144
+ ```
145
+
146
+ and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
147
+
148
+ ```bash
149
+ accelerate launch my_script.py --args_to_my_script
150
+ ```
151
+
152
+ For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
153
+
154
+ ```bash
155
+ accelerate launch examples/nlp_example.py
156
+ ```
157
+
158
+ This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torch.distributed.launch my_script.py` at your convenance.
159
+
160
+ ## Launching multi-CPU run using MPI
161
+
162
+ 🤗 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.
163
+ Once you have MPI setup on your cluster, just run:
164
+
165
+ ```bash
166
+ mpirun -np 2 python examples/nlp_example.py
167
+ ```
168
+
169
+ ## Launching training using DeepSpeed
170
+
171
+ 🤗 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`.
172
+
173
+ ```python
174
+ from accelerate import Accelerator, DeepSpeedPlugin
175
+
176
+ # deepspeed needs to know your gradient accumulation steps before hand, so don't forget to pass it
177
+ # Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed
178
+ deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
179
+ accelerator = Accelerator(fp16=True, deepspeed_plugin=deepspeed_plugin)
180
+
181
+ # How to save your 🤗 Transformer?
182
+ accelerator.wait_for_everyone()
183
+ unwrapped_model = accelerator.unwrap_model(model)
184
+ unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))
185
+ ```
186
+
187
+ Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.
188
+
189
+ ## Launching your training from a notebook
190
+
191
+ 🤗 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:
192
+
193
+ ```python
194
+ from accelerate import notebook_launcher
195
+
196
+ notebook_launcher(training_function)
197
+ ```
198
+
199
+ 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)
200
+
201
+ ## Why should I use 🤗 Accelerate?
202
+
203
+ 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.
204
+
205
+ ## Why shouldn't I use 🤗 Accelerate?
206
+
207
+ 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.
208
+
209
+ ## Frameworks using 🤗 Accelerate
210
+
211
+ If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around your training loop, some frameworks that are built on top of 🤗 Accelerate are listed below:
212
+
213
+ * [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).
214
+ * [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 train, and inference logic.
215
+ * [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.
216
+ * [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.
217
+ * [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centred 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!
218
+
219
+
220
+ ## Installation
221
+
222
+ This repository is tested on Python 3.6+ and PyTorch 1.4.0+
223
+
224
+ 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/).
225
+
226
+ First, create a virtual environment with the version of Python you're going to use and activate it.
227
+
228
+ 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:
229
+
230
+ ```bash
231
+ pip install accelerate
232
+ ```
233
+
234
+ ## Supported integrations
235
+
236
+ - CPU only
237
+ - multi-CPU on one node (machine)
238
+ - multi-CPU on several nodes (machines)
239
+ - single GPU
240
+ - multi-GPU on one node (machine)
241
+ - multi-GPU on several nodes (machines)
242
+ - TPU
243
+ - FP16 with native AMP (apex on the roadmap)
244
+ - DeepSpeed support (Experimental)
245
+ - PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)
246
+ - Megatron-LM support (Experimental)
247
+
248
+ ## Citing 🤗 Accelerate
249
+
250
+ If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
251
+
252
+ ```bibtex
253
+ @Misc{accelerate,
254
+ title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.},
255
+ author = {Sylvain Gugger, Lysandre Debut, Thomas Wolf, Philipp Schmid, Zachary Mueller, Sourab Mangrulkar},
256
+ howpublished = {\url{https://github.com/huggingface/accelerate}},
257
+ year = {2022}
258
+ }
259
+ ```
testbed/huggingface__accelerate/benchmarks/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 inference_acc.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.
testbed/huggingface__accelerate/benchmarks/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
+
20
+ import transformers
21
+ from accelerate.utils import compute_module_sizes
22
+ from measures_util import end_measure, log_measures, start_measure
23
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer
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()
testbed/huggingface__accelerate/benchmarks/measures_util.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import threading
3
+ import time
4
+
5
+ import torch
6
+
7
+ import psutil
8
+
9
+
10
+ class PeakCPUMemory:
11
+ def __init__(self):
12
+ self.process = psutil.Process()
13
+ self.peak_monitoring = False
14
+
15
+ def peak_monitor(self):
16
+ self.cpu_memory_peak = -1
17
+
18
+ while True:
19
+ self.cpu_memory_peak = max(self.process.memory_info().rss, self.cpu_memory_peak)
20
+
21
+ # can't sleep or will not catch the peak right (this comment is here on purpose)
22
+ if not self.peak_monitoring:
23
+ break
24
+
25
+ def start(self):
26
+ self.peak_monitoring = True
27
+ self.thread = threading.Thread(target=self.peak_monitor)
28
+ self.thread.daemon = True
29
+ self.thread.start()
30
+
31
+ def stop(self):
32
+ self.peak_monitoring = False
33
+ self.thread.join()
34
+ return self.cpu_memory_peak
35
+
36
+
37
+ cpu_peak_tracker = PeakCPUMemory()
38
+
39
+
40
+ def start_measure():
41
+ # Time
42
+ measures = {"time": time.time()}
43
+
44
+ gc.collect()
45
+ torch.cuda.empty_cache()
46
+
47
+ # CPU mem
48
+ measures["cpu"] = psutil.Process().memory_info().rss
49
+ cpu_peak_tracker.start()
50
+
51
+ # GPU mem
52
+ for i in range(torch.cuda.device_count()):
53
+ measures[str(i)] = torch.cuda.memory_allocated(i)
54
+ torch.cuda.reset_peak_memory_stats()
55
+
56
+ return measures
57
+
58
+
59
+ def end_measure(start_measures):
60
+ # Time
61
+ measures = {"time": time.time() - start_measures["time"]}
62
+
63
+ gc.collect()
64
+ torch.cuda.empty_cache()
65
+
66
+ # CPU mem
67
+ measures["cpu"] = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20
68
+ measures["cpu-peak"] = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20
69
+
70
+ # GPU mem
71
+ for i in range(torch.cuda.device_count()):
72
+ measures[str(i)] = (torch.cuda.memory_allocated(i) - start_measures[str(i)]) / 2**20
73
+ measures[f"{i}-peak"] = (torch.cuda.max_memory_allocated(i) - start_measures[str(i)]) / 2**20
74
+
75
+ return measures
76
+
77
+
78
+ def log_measures(measures, description):
79
+ print(f"{description}:")
80
+ print(f"- Time: {measures['time']:.2f}s")
81
+ for i in range(torch.cuda.device_count()):
82
+ print(f"- GPU {i} allocated: {measures[str(i)]:.2f}MiB")
83
+ peak = measures[f"{i}-peak"]
84
+ print(f"- GPU {i} peak: {peak:.2f}MiB")
85
+ print(f"- CPU RAM allocated: {measures['cpu']:.2f}MiB")
86
+ print(f"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB")
testbed/huggingface__accelerate/docker/accelerate-cpu/Dockerfile ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Builds CPU-only Docker image of PyTorch
2
+ # Uses multi-staged approach to reduce size
3
+ # Stage 1
4
+ FROM python:3.7-slim as compile-image
5
+
6
+ ARG DEBIAN_FRONTEND=noninteractive
7
+
8
+ RUN apt update
9
+ RUN apt-get install -y --no-install-recommends \
10
+ build-essential \
11
+ git \
12
+ gcc
13
+
14
+ # Setup virtual environment for Docker
15
+ ENV VIRTUAL_ENV=/opt/venv
16
+ RUN python3 -m venv ${VIRTUAL_ENV}
17
+ # Make sure we use the virtualenv
18
+ ENV PATH="${VIRTUAL_ENV}/bin:$PATH"
19
+ WORKDIR /workspace
20
+ # Install specific CPU torch wheel to save on space
21
+ RUN python3 -m pip install --upgrade --no-cache-dir pip
22
+ RUN python3 -m pip install --no-cache-dir \
23
+ jupyter \
24
+ git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers] \
25
+ --extra-index-url https://download.pytorch.org/whl/cpu
26
+
27
+ # Stage 2
28
+ FROM python:3.7-slim AS build-image
29
+ COPY --from=compile-image /opt/venv /opt/venv
30
+ RUN useradd -ms /bin/bash user
31
+ USER user
32
+
33
+ # Make sure we use the virtualenv
34
+ ENV PATH="/opt/venv/bin:$PATH"
35
+ CMD ["/bin/bash"]
testbed/huggingface__accelerate/docker/accelerate-gpu/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Builds GPU docker image of PyTorch
2
+ # Uses multi-staged approach to reduce size
3
+ # Stage 1
4
+ # Use base conda image to reduce time
5
+ FROM continuumio/miniconda3:latest AS compile-image
6
+ # Specify py version
7
+ ENV PYTHON_VERSION=3.7.3
8
+ # Install apt libs
9
+ RUN apt-get update && \
10
+ apt-get install -y curl git wget && \
11
+ apt-get clean && \
12
+ rm -rf /var/lib/apt/lists*
13
+
14
+ # Create our conda env
15
+ RUN conda create --name accelerate python=${PYTHON_VERSION} ipython jupyter pip
16
+ # We don't install pytorch here yet since CUDA isn't available
17
+ # instead we use the direct torch wheel
18
+ ENV PATH /opt/conda/envs/accelerate/bin:$PATH
19
+ # Activate our bash shell
20
+ RUN chsh -s /bin/bash
21
+ SHELL ["/bin/bash", "-c"]
22
+ # Activate the conda env and install torch + accelerate
23
+ RUN source activate accelerate && \
24
+ python3 -m pip install --no-cache-dir \
25
+ git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers] \
26
+ --extra-index-url https://download.pytorch.org/whl/cu113
27
+
28
+ # Stage 2
29
+ FROM nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04 AS build-image
30
+ COPY --from=compile-image /opt/conda /opt/conda
31
+ ENV PATH /opt/conda/bin:$PATH
32
+
33
+ # Install apt libs
34
+ RUN apt-get update && \
35
+ apt-get install -y curl git wget && \
36
+ apt-get clean && \
37
+ rm -rf /var/lib/apt/lists*
38
+
39
+ RUN echo "source activate accelerate" >> ~/.profile
40
+
41
+ # Activate the virtualenv
42
+ CMD ["/bin/bash"]
testbed/huggingface__accelerate/docs/Makefile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Minimal makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line.
5
+ SPHINXOPTS =
6
+ SPHINXBUILD = sphinx-build
7
+ SOURCEDIR = source
8
+ BUILDDIR = _build
9
+
10
+ # Put it first so that "make" without argument is like "make help".
11
+ help:
12
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
13
+
14
+ .PHONY: help Makefile
15
+
16
+ # Catch-all target: route all unknown targets to Sphinx using the new
17
+ # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
18
+ %: Makefile
19
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
testbed/huggingface__accelerate/docs/README.md ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2023 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
+ # Generating the documentation
18
+
19
+ To generate the documentation, you first have to build it. Several packages are necessary to build the doc,
20
+ you can install them with the following command, at the root of the code repository:
21
+
22
+ ```bash
23
+ pip install -e ".[docs]"
24
+ ```
25
+
26
+ Then you need to install our special tool that builds the documentation:
27
+
28
+ ```bash
29
+ pip install git+https://github.com/huggingface/doc-builder
30
+ ```
31
+
32
+ ---
33
+ **NOTE**
34
+
35
+ You only need to generate the documentation to inspect it locally (if you're planning changes and want to
36
+ check how they look before committing for instance). You don't have to commit the built documentation.
37
+
38
+ ---
39
+
40
+ ## Building the documentation
41
+
42
+ Once you have setup the `doc-builder` and additional packages, you can generate the documentation by
43
+ typing the following command:
44
+
45
+ ```bash
46
+ doc-builder build accelerate docs/source/ --build_dir ~/tmp/test-build
47
+ ```
48
+
49
+ You can adapt the `--build_dir` to set any temporary folder that you prefer. This command will create it and generate
50
+ the MDX files that will be rendered as the documentation on the main website. You can inspect them in your favorite
51
+ Markdown editor.
52
+
53
+ ## Previewing the documentation
54
+
55
+ To preview the docs, first install the `watchdog` module with:
56
+
57
+ ```bash
58
+ pip install watchdog
59
+ ```
60
+
61
+ Then run the following command:
62
+
63
+ ```bash
64
+ doc-builder preview {package_name} {path_to_docs}
65
+ ```
66
+
67
+ For example:
68
+
69
+ ```bash
70
+ doc-builder preview transformers docs/source/en/
71
+ ```
72
+
73
+ The docs will be viewable at [http://localhost:3000](http://localhost:3000). You can also preview the docs once you have opened a PR. You will see a bot add a comment to a link where the documentation with your changes lives.
74
+
75
+ ---
76
+ **NOTE**
77
+
78
+ The `preview` command only works with existing doc files. When you add a completely new file, you need to update `_toctree.yml` & restart `preview` command (`ctrl-c` to stop it & call `doc-builder preview ...` again).
79
+
80
+ ---
81
+
82
+ ## Adding a new element to the navigation bar
83
+
84
+ Accepted files are Markdown (.md or .mdx).
85
+
86
+ Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting
87
+ the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/accelerate/blob/main/docs/source/_toctree.yml) file.
88
+
89
+ ## Renaming section headers and moving sections
90
+
91
+ It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information.
92
+
93
+ Therefore, we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor.
94
+
95
+ So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file:
96
+
97
+ ```
98
+ Sections that were moved:
99
+
100
+ [ <a href="#section-b">Section A</a><a id="section-a"></a> ]
101
+ ```
102
+ and of course, if you moved it to another file, then:
103
+
104
+ ```
105
+ Sections that were moved:
106
+
107
+ [ <a href="../new-file#section-b">Section A</a><a id="section-a"></a> ]
108
+ ```
109
+
110
+ Use the relative style to link to the new file so that the versioned docs continue to work.
111
+
112
+
113
+ ## Writing Documentation - Specification
114
+
115
+ The `huggingface/accelerate` documentation follows the
116
+ [Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings,
117
+ although we can write them directly in Markdown.
118
+
119
+ ### Adding a new tutorial
120
+
121
+ Adding a new tutorial or section is done in two steps:
122
+
123
+ - Add a new file under `./source`. This file can either be ReStructuredText (.rst) or Markdown (.md).
124
+ - Link that file in `./source/_toctree.yml` on the correct toc-tree.
125
+
126
+ Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so
127
+ depending on the intended targets (beginners, more advanced users, or researchers) it should go in sections two, three, or
128
+ four.
129
+
130
+ ### Writing source documentation
131
+
132
+ Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names
133
+ and objects like True, None, or any strings should usually be put in `code`.
134
+
135
+ When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool
136
+ adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or
137
+ function to be in the main package.
138
+
139
+ If you want to create a link to some internal class or function, you need to
140
+ provide its path. For instance: \[\`utils.gather\`\]. This will be converted into a link with
141
+ `utils.gather` in the description. To get rid of the path and only keep the name of the object you are
142
+ linking to in the description, add a ~: \[\`~utils.gather\`\] will generate a link with `gather` in the description.
143
+
144
+ The same works for methods so you can either use \[\`XXXClass.method\`\] or \[~\`XXXClass.method\`\].
145
+
146
+ #### Defining arguments in a method
147
+
148
+ Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and
149
+ an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its
150
+ description:
151
+
152
+ ```
153
+ Args:
154
+ n_layers (`int`): The number of layers of the model.
155
+ ```
156
+
157
+ If the description is too long to fit in one line (more than 119 characters in total), another indentation is necessary
158
+ before writing the description after the argument.
159
+
160
+ Finally, to maintain uniformity if any *one* description is too long to fit on one line, the
161
+ rest of the parameters should follow suit and have an indention before their description.
162
+
163
+ Here's an example showcasing everything so far:
164
+
165
+ ```
166
+ Args:
167
+ gradient_accumulation_steps (`int`, *optional*, default to 1):
168
+ The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with `Accelerator.accumulate`.
169
+ cpu (`bool`, *optional*):
170
+ Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force the execution on one process only.
171
+ ```
172
+
173
+ For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the
174
+ following signature:
175
+
176
+ ```
177
+ def my_function(x: str = None, a: float = 1):
178
+ ```
179
+
180
+ then its documentation should look like this:
181
+
182
+ ```
183
+ Args:
184
+ x (`str`, *optional*):
185
+ This argument controls ... and has a description longer than 119 chars.
186
+ a (`float`, *optional*, defaults to 1):
187
+ This argument is used to ... and has a description longer than 119 chars.
188
+ ```
189
+
190
+ Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even
191
+ if the first line describing your argument type and its default gets long, you can't break it on several lines. You can
192
+ however write as many lines as you want in the indented description (see the example above with `input_ids`).
193
+
194
+ #### Writing a multi-line code block
195
+
196
+ Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown:
197
+
198
+
199
+ ````
200
+ ```python
201
+ # first line of code
202
+ # second line
203
+ # etc
204
+ ```
205
+ ````
206
+
207
+ #### Writing a return block
208
+
209
+ The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation.
210
+ The first line should be the type of the return, followed by a line return. No need to indent further for the elements
211
+ building the return.
212
+
213
+ Here's an example of a single value return:
214
+
215
+ ```
216
+ Returns:
217
+ `List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.
218
+ ```
219
+
220
+ Here's an example of a tuple return, comprising several objects:
221
+
222
+ ```
223
+ Returns:
224
+ `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs:
225
+ - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` --
226
+ Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
227
+ - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) --
228
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
229
+ ```
230
+
231
+ ## Styling the docstring
232
+
233
+ We have an automatic script running with the `make style` comment that will make sure that:
234
+ - the docstrings fully take advantage of the line width
235
+ - all code examples are formatted using black, like the code of the Transformers library
236
+
237
+ This script may have some weird failures if you made a syntax mistake or if you uncover a bug. Therefore, it's
238
+ recommended to commit your changes before running `make style`, so you can revert the changes done by that script
239
+ easily.
240
+
241
+ ## Writing documentation examples
242
+
243
+ The syntax for Example docstrings can look as follows:
244
+
245
+ ```
246
+ Example:
247
+
248
+ ```python
249
+ >>> import time
250
+ >>> from accelerate import Accelerator
251
+ >>> accelerator = Accelerator()
252
+ >>> if accelerator.is_main_process:
253
+ ... time.sleep(2)
254
+ >>> else:
255
+ ... print("I'm waiting for the main process to finish its sleep...")
256
+ >>> accelerator.wait_for_everyone()
257
+ >>> # Should print on every process at the same time
258
+ >>> print("Everyone is here")
259
+ ```
260
+ ```
261
+
262
+ The docstring should give a minimal, clear example of how the respective function
263
+ is to be used in inference and also include the expected (ideally sensible)
264
+ output.
265
+ Often, readers will try out the example before even going through the function
266
+ or class definitions. Therefore, it is of utmost importance that the example
267
+ works as expected.
testbed/huggingface__accelerate/docs/source/_toctree.yml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🤗 Accelerate
4
+ - local: basic_tutorials/install
5
+ title: Installation
6
+ - local: quicktour
7
+ title: Quicktour
8
+ title: Getting started
9
+ - sections:
10
+ - local: basic_tutorials/overview
11
+ title: Overview
12
+ - local: basic_tutorials/migration
13
+ title: Migrating to 🤗 Accelerate
14
+ - local: basic_tutorials/launch
15
+ title: Launching distributed code
16
+ - local: basic_tutorials/notebook
17
+ title: Launching distributed training from Jupyter Notebooks
18
+ title: Tutorials
19
+ - sections:
20
+ - local: usage_guides/training_zoo
21
+ title: Example Zoo
22
+ - local: usage_guides/big_modeling
23
+ title: How perform inference on large models with small resources
24
+ - local: usage_guides/gradient_accumulation
25
+ title: Performing gradient accumulation
26
+ - local: usage_guides/checkpoint
27
+ title: Saving and loading training states
28
+ - local: usage_guides/tracking
29
+ title: Using experiment trackers
30
+ - local: usage_guides/memory
31
+ title: How to avoid CUDA Out-of-Memory
32
+ - local: usage_guides/mps
33
+ title: How to use Apple Silicon M1 GPUs
34
+ - local: usage_guides/deepspeed
35
+ title: How to use DeepSpeed
36
+ - local: usage_guides/fsdp
37
+ title: How to use Fully Sharded Data Parallelism
38
+ - local: usage_guides/megatron_lm
39
+ title: How to use Megatron-LM
40
+ - local: usage_guides/sagemaker
41
+ title: How to use 🤗 Accelerate with SageMaker
42
+ title: How-To Guides
43
+ - sections:
44
+ - local: concept_guides/performance
45
+ title: Comparing performance across distributed setups
46
+ - local: concept_guides/deferring_execution
47
+ title: Executing and deferring jobs
48
+ - local: concept_guides/gradient_synchronization
49
+ title: Gradient synchronization
50
+ - local: concept_guides/training_tpu
51
+ title: TPU best practices
52
+ title: Concepts and fundamentals
53
+ - sections:
54
+ - local: package_reference/accelerator
55
+ title: Main Accelerator class
56
+ - local: package_reference/state
57
+ title: Stateful configuration classes
58
+ - local: package_reference/cli
59
+ title: The Command Line
60
+ - local: package_reference/torch_wrappers
61
+ title: Torch wrapper classes
62
+ - local: package_reference/tracking
63
+ title: Experiment trackers
64
+ - local: package_reference/launchers
65
+ title: Distributed launchers
66
+ - local: package_reference/deepspeed
67
+ title: DeepSpeed utilities
68
+ - local: package_reference/logging
69
+ title: Logging
70
+ - local: package_reference/big_modeling
71
+ title: Working with large models
72
+ - local: package_reference/kwargs
73
+ title: Kwargs handlers
74
+ - local: package_reference/utilities
75
+ title: Utility functions and classes
76
+ - local: package_reference/megatron_lm
77
+ title: Megatron-LM Utilities
78
+ title: "Reference"
testbed/huggingface__accelerate/docs/source/basic_tutorials/migration.mdx ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Migrating your code to 🤗 Accelerate
14
+
15
+ This tutorial will detail how to easily convert existing PyTorch code to use 🤗 Accelerate!
16
+ You'll see that by just changing a few lines of code, 🤗 Accelerate can perform its magic and get you on
17
+ your way towards running your code on distributed systems with ease!
18
+
19
+ ## The base training loop
20
+
21
+ To begin, write out a very basic PyTorch training loop.
22
+
23
+ <Tip>
24
+
25
+ We are under the presumption that `training_dataloader`, `model`, `optimizer`, `scheduler`, and `loss_function` have been defined beforehand.
26
+
27
+ </Tip>
28
+
29
+ ```python
30
+ device = "cuda"
31
+ model.to(device)
32
+
33
+ for batch in training_dataloader:
34
+ optimizer.zero_grad()
35
+ inputs, targets = batch
36
+ inputs = inputs.to(device)
37
+ targets = targets.to(device)
38
+ outputs = model(inputs)
39
+ loss = loss_function(outputs, targets)
40
+ loss.backward()
41
+ optimizer.step()
42
+ scheduler.step()
43
+ ```
44
+
45
+ ## Add in 🤗 Accelerate
46
+
47
+ To start using 🤗 Accelerate, first import and create an [`Accelerator`] instance:
48
+ ```python
49
+ from accelerate import Accelerator
50
+
51
+ accelerator = Accelerator()
52
+ ```
53
+ [`Accelerator`] is the main force behind utilizing all the possible options for distributed training!
54
+
55
+ ### Setting the right device
56
+
57
+ The [`Accelerator`] class knows the right device to move any PyTorch object to at any time, so you should
58
+ change the definition of `device` to come from [`Accelerator`]:
59
+
60
+ ```diff
61
+ - device = 'cuda'
62
+ + device = accelerator.device
63
+ model.to(device)
64
+ ```
65
+
66
+ ### Preparing your objects
67
+
68
+ Next you need to pass all of the important objects related to training into [`~Accelerator.prepare`]. 🤗 Accelerate will
69
+ make sure everything is setup in the current environment for you to start training:
70
+
71
+ ```
72
+ model, optimizer, training_dataloader, scheduler = accelerator.prepare(
73
+ model, optimizer, training_dataloader, scheduler
74
+ )
75
+ ```
76
+ These objects are returned in the same order they were sent in with. By default when using `device_placement=True`, all of the objects that can be sent to the right device will be.
77
+ If you need to work with data that isn't passed to [~Accelerator.prepare] but should be on the active device, you should pass in the `device` you made earlier.
78
+
79
+ <Tip warning={true}>
80
+
81
+ Accelerate will only prepare objects that inherit from their respective PyTorch classes (such as `torch.optim.Optimizer`).
82
+
83
+ </Tip>
84
+
85
+ ### Modifying the training loop
86
+
87
+ Finally, three lines of code need to be changed in the training loop. 🤗 Accelerate's DataLoader classes will automatically handle the device placement by default,
88
+ and [`~Accelerator.backward`] should be used for performing the backward pass:
89
+
90
+ ```diff
91
+ - inputs = inputs.to(device)
92
+ - targets = targets.to(device)
93
+ outputs = model(inputs)
94
+ loss = loss_function(outputs, targets)
95
+ - loss.backward()
96
+ + accelerator.backward(loss)
97
+ ```
98
+
99
+ With that, your training loop is now ready to use 🤗 Accelerate!
100
+
101
+ ## The finished code
102
+
103
+ Below is the final version of the converted code:
104
+
105
+ ```python
106
+ from accelerate import Accelerator
107
+
108
+ accelerator = Accelerator()
109
+
110
+ model, optimizer, training_dataloader, scheduler = accelerator.prepare(
111
+ model, optimizer, training_dataloader, scheduler
112
+ )
113
+
114
+ for batch in training_dataloader:
115
+ optimizer.zero_grad()
116
+ inputs, targets = batch
117
+ outputs = model(inputs)
118
+ loss = loss_function(outputs, targets)
119
+ accelerator.backward(loss)
120
+ optimizer.step()
121
+ scheduler.step()
122
+ ```
123
+
testbed/huggingface__accelerate/docs/source/basic_tutorials/notebook.mdx ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Launching Multi-Node Training from a Jupyter Environment
14
+
15
+ This tutorial teaches you how to fine tune a computer vision model with 🤗 Accelerate from a Jupyter Notebook on a distributed system.
16
+ You will also learn how to setup a few requirements needed for ensuring your environment is configured properly, your data has been prepared properly, and finally how to launch training.
17
+
18
+ <Tip>
19
+
20
+ This tutorial is also available as a Jupyter Notebook [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_cv_example.ipynb)
21
+
22
+ </Tip>
23
+
24
+ ## Configuring the Environment
25
+
26
+ Before any training can be performed, a 🤗 Accelerate config file must exist in the system. Usually this can be done by running the following in a terminal and answering the prompts:
27
+
28
+ ```bash
29
+ accelerate config
30
+ ```
31
+
32
+ However, if general defaults are fine and you are *not* running on a TPU, 🤗Accelerate has a utility to quickly write your GPU configuration into a config file via [`utils.write_basic_config`].
33
+
34
+ The following code will restart Jupyter after writing the configuration, as CUDA code was called to perform this.
35
+
36
+ <Tip warning={true}>
37
+
38
+ CUDA can't be initialized more than once on a multi-node system. It's fine to debug in the notebook and have calls to CUDA, but in order to finally train a full cleanup and restart will need to be performed.
39
+
40
+ </Tip>
41
+
42
+ ```python
43
+ import os
44
+ from accelerate.utils import write_basic_config
45
+
46
+ write_basic_config() # Write a config file
47
+ os._exit(00) # Restart the notebook
48
+ ```
49
+
50
+ ## Preparing the Dataset and Model
51
+
52
+ Next you should prepare your dataset. As mentioned at earlier, great care should be taken when preparing the `DataLoaders` and model to make sure that **nothing** is put on *any* GPU.
53
+
54
+ If you do, it is recommended to put that specific code into a function and call that from within the notebook launcher interface, which will be shown later.
55
+
56
+ Make sure the dataset is downloaded based on the directions [here](https://github.com/huggingface/accelerate/tree/main/examples#simple-vision-example)
57
+
58
+ ```python
59
+ import os, re, torch, PIL
60
+ import numpy as np
61
+
62
+ from torch.optim.lr_scheduler import OneCycleLR
63
+ from torch.utils.data import DataLoader, Dataset
64
+ from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
65
+
66
+ from accelerate import Accelerator
67
+ from accelerate.utils import set_seed
68
+ from timm import create_model
69
+ ```
70
+
71
+ First you need to create a function to extract the class name based on a filename:
72
+
73
+ ```python
74
+ import os
75
+
76
+ data_dir = "../../images"
77
+ fnames = os.listdir(data_dir)
78
+ fname = fnames[0]
79
+ print(fname)
80
+ ```
81
+
82
+ ```python out
83
+ beagle_32.jpg
84
+ ```
85
+
86
+ In the case here, the label is `beagle`. Using regex you can extract the label from the filename:
87
+
88
+ ```python
89
+ import re
90
+
91
+
92
+ def extract_label(fname):
93
+ stem = fname.split(os.path.sep)[-1]
94
+ return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0]
95
+ ```
96
+
97
+ ```python
98
+ extract_label(fname)
99
+ ```
100
+
101
+ And you can see it properly returned the right name for our file:
102
+
103
+ ```python out
104
+ "beagle"
105
+ ```
106
+
107
+ Next a `Dataset` class should be made to handle grabbing the image and the label:
108
+
109
+ ```python
110
+ class PetsDataset(Dataset):
111
+ def __init__(self, file_names, image_transform=None, label_to_id=None):
112
+ self.file_names = file_names
113
+ self.image_transform = image_transform
114
+ self.label_to_id = label_to_id
115
+
116
+ def __len__(self):
117
+ return len(self.file_names)
118
+
119
+ def __getitem__(self, idx):
120
+ fname = self.file_names[idx]
121
+ raw_image = PIL.Image.open(fname)
122
+ image = raw_image.convert("RGB")
123
+ if self.image_transform is not None:
124
+ image = self.image_transform(image)
125
+ label = extract_label(fname)
126
+ if self.label_to_id is not None:
127
+ label = self.label_to_id[label]
128
+ return {"image": image, "label": label}
129
+ ```
130
+
131
+ Now to build the dataset. Outside the training function you can find and declare all the filenames and labels and use them as references inside the
132
+ launched function:
133
+
134
+ ```python
135
+ fnames = [os.path.join("../../images", fname) for fname in fnames if fname.endswith(".jpg")]
136
+ ```
137
+
138
+ Next gather all the labels:
139
+
140
+ ```python
141
+ all_labels = [extract_label(fname) for fname in fnames]
142
+ id_to_label = list(set(all_labels))
143
+ id_to_label.sort()
144
+ label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)}
145
+ ```
146
+
147
+ Next, you should make a `get_dataloaders` function that will return your built dataloaders for you. As mentioned earlier, if data is automatically
148
+ sent to the GPU or a TPU device when building your `DataLoaders`, they must be built using this method.
149
+
150
+ ```python
151
+ def get_dataloaders(batch_size: int = 64):
152
+ "Builds a set of dataloaders with a batch_size"
153
+ random_perm = np.random.permutation(len(fnames))
154
+ cut = int(0.8 * len(fnames))
155
+ train_split = random_perm[:cut]
156
+ eval_split = random_perm[:cut]
157
+
158
+ # For training a simple RandomResizedCrop will be used
159
+ train_tfm = Compose([RandomResizedCrop((224, 224), scale=(0.5, 1.0)), ToTensor()])
160
+ train_dataset = PetsDataset([fnames[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id)
161
+
162
+ # For evaluation a deterministic Resize will be used
163
+ eval_tfm = Compose([Resize((224, 224)), ToTensor()])
164
+ eval_dataset = PetsDataset([fnames[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id)
165
+
166
+ # Instantiate dataloaders
167
+ train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
168
+ eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size * 2, num_workers=4)
169
+ return train_dataloader, eval_dataloader
170
+ ```
171
+
172
+ Finally, you should import the scheduler to be used later:
173
+
174
+ ```python
175
+ from torch.optim.lr_scheduler import CosineAnnealingLR
176
+ ```
177
+
178
+ ## Writing the Training Function
179
+
180
+ Now you can build the training loop. [`notebook_launcher`] works by passing in a function to call that will be ran across the distributed system.
181
+
182
+ Here is a basic training loop for the animal classification problem:
183
+
184
+ <Tip>
185
+
186
+ The code has been split up to allow for explainations on each section. A full version that can be copy and pasted will be available at the end
187
+
188
+ </Tip>
189
+
190
+
191
+ ```python
192
+ def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64):
193
+ set_seed(seed)
194
+ accelerator = Accelerator(mixed_precision=mixed_precision)
195
+ ```
196
+
197
+ First you should set the seed and create an [`Accelerator`] object as early in the training loop as possible.
198
+
199
+ <Tip warning={true}>
200
+
201
+ If training on the TPU, your training loop should take in the model as a parameter and it should be instantiated
202
+ outside of the training loop function. See the [TPU best practices](../concept_guides/training_tpu)
203
+ to learn why
204
+
205
+ </Tip>
206
+
207
+ Next you should build your dataloaders and create your model:
208
+
209
+ ```python
210
+ train_dataloader, eval_dataloader = get_dataloaders(batch_size)
211
+ model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
212
+ ```
213
+
214
+ <Tip>
215
+
216
+ You build the model here so that the seed also controls the new weight initialization
217
+
218
+ </Tip>
219
+
220
+ As you are performing transfer learning in this example, the encoder of the model starts out frozen so the head of the model can be
221
+ trained only initially:
222
+
223
+ ```python
224
+ for param in model.parameters():
225
+ param.requires_grad = False
226
+ for param in model.get_classifier().parameters():
227
+ param.requires_grad = True
228
+ ```
229
+
230
+ Normalizing the batches of images will make training a little faster:
231
+
232
+ ```python
233
+ mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None]
234
+ std = torch.tensor(model.default_cfg["std"])[None, :, None, None]
235
+ ```
236
+
237
+ To make these constants available on the active device, you should set it to the Accelerator's device:
238
+
239
+ ```python
240
+ mean = mean.to(accelerator.device)
241
+ std = std.to(accelerator.device)
242
+ ```
243
+
244
+ Next instantiate the rest of the PyTorch classes used for training:
245
+
246
+ ```python
247
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25)
248
+ lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader))
249
+ ```
250
+
251
+ Before passing everything to [`~Accelerator.prepare`].
252
+
253
+ <Tip>
254
+
255
+ There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the prepare method.
256
+
257
+ </Tip>
258
+
259
+ ```python
260
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
261
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
262
+ )
263
+ ```
264
+
265
+ Now train the model:
266
+
267
+ ```python
268
+ for epoch in range(5):
269
+ model.train()
270
+ for batch in train_dataloader:
271
+ inputs = (batch["image"] - mean) / std
272
+ outputs = model(inputs)
273
+ loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
274
+ accelerator.backward(loss)
275
+ optimizer.step()
276
+ lr_scheduler.step()
277
+ optimizer.zero_grad()
278
+ ```
279
+
280
+ The evaluation loop will look slightly different compared to the training loop. The number of elements passed as well as the overall
281
+ total accuracy of each batch will be added to two constants:
282
+
283
+ ```python
284
+ model.eval()
285
+ accurate = 0
286
+ num_elems = 0
287
+ ```
288
+
289
+ Next you have the rest of your standard PyTorch loop:
290
+
291
+ ```python
292
+ for batch in eval_dataloader:
293
+ inputs = (batch["image"] - mean) / std
294
+ with torch.no_grad():
295
+ outputs = model(inputs)
296
+ predictions = outputs.argmax(dim=-1)
297
+ ```
298
+
299
+ Before finally the last major difference.
300
+
301
+ When performing distributed evaluation, the predictions and labels need to be passed through
302
+ [`~Accelerator.gather`] so that all of the data is available on the current device and a properly calculated metric can be achieved:
303
+
304
+ ```python
305
+ accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"])
306
+ num_elems += accurate_preds.shape[0]
307
+ accurate += accurate_preds.long().sum()
308
+ ```
309
+
310
+ Now you just need to calculate the actual metric for this problem, and you can print it on the main process using [`~Accelerator.print`]:
311
+
312
+ ```python
313
+ eval_metric = accurate.item() / num_elems
314
+ accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}")
315
+ ```
316
+
317
+ A full version of this training loop is available below:
318
+
319
+ ```python
320
+ def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64):
321
+ set_seed(seed)
322
+ # Initialize accelerator
323
+ accelerator = Accelerator(mixed_precision=mixed_precision)
324
+ # Build dataloaders
325
+ train_dataloader, eval_dataloader = get_dataloaders(batch_size)
326
+
327
+ # Instantiate the model (you build the model here so that the seed also controls new weight initaliziations)
328
+ model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
329
+
330
+ # Freeze the base model
331
+ for param in model.parameters():
332
+ param.requires_grad = False
333
+ for param in model.get_classifier().parameters():
334
+ param.requires_grad = True
335
+
336
+ # You can normalize the batches of images to be a bit faster
337
+ mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None]
338
+ std = torch.tensor(model.default_cfg["std"])[None, :, None, None]
339
+
340
+ # To make this constant available on the active device, set it to the accelerator device
341
+ mean = mean.to(accelerator.device)
342
+ std = std.to(accelerator.device)
343
+
344
+ # Intantiate the optimizer
345
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25)
346
+
347
+ # Instantiate the learning rate scheduler
348
+ lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader))
349
+
350
+ # Prepare everything
351
+ # There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the
352
+ # prepare method.
353
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
354
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
355
+ )
356
+
357
+ # Now you train the model
358
+ for epoch in range(5):
359
+ model.train()
360
+ for batch in train_dataloader:
361
+ inputs = (batch["image"] - mean) / std
362
+ outputs = model(inputs)
363
+ loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
364
+ accelerator.backward(loss)
365
+ optimizer.step()
366
+ lr_scheduler.step()
367
+ optimizer.zero_grad()
368
+
369
+ model.eval()
370
+ accurate = 0
371
+ num_elems = 0
372
+ for batch in eval_dataloader:
373
+ inputs = (batch["image"] - mean) / std
374
+ with torch.no_grad():
375
+ outputs = model(inputs)
376
+ predictions = outputs.argmax(dim=-1)
377
+ accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"])
378
+ num_elems += accurate_preds.shape[0]
379
+ accurate += accurate_preds.long().sum()
380
+
381
+ eval_metric = accurate.item() / num_elems
382
+ # Use accelerator.print to print only on the main process.
383
+ accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}")
384
+ ```
385
+
386
+ ## Using the notebook_launcher
387
+
388
+ All that's left is to use the [`notebook_launcher`].
389
+
390
+ You pass in the function, the arguments (as a tuple), and the number of processes to train on. (See the [documentation](../package_reference/launchers) for more information)
391
+
392
+ ```python
393
+ from accelerate import notebook_launcher
394
+ ```
395
+
396
+ ```python
397
+ args = ("fp16", 42, 64)
398
+ notebook_launcher(training_loop, args, num_processes=2)
399
+ ```
400
+
401
+ In the case of running on the TPU, it would look like so:
402
+
403
+ ```python
404
+ model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
405
+
406
+ args = (model, "fp16", 42, 64)
407
+ notebook_launcher(training_loop, args, num_processes=8)
408
+ ```
409
+
410
+ As it's running it will print the progress as well as state how many devices you ran on. This tutorial was ran with two GPUs:
411
+
412
+ ```python out
413
+ Launching training on 2 GPUs.
414
+ epoch 0: 88.12
415
+ epoch 1: 91.73
416
+ epoch 2: 92.58
417
+ epoch 3: 93.90
418
+ epoch 4: 94.71
419
+ ```
420
+
421
+ And that's it!
422
+
423
+ ## Conclusion
424
+
425
+ This notebook showed how to perform distributed training from inside of a Jupyter Notebook. Some key notes to remember:
426
+
427
+ - Make sure to save any code that use CUDA (or CUDA imports) for the function passed to [`notebook_launcher`]
428
+ - Set the `num_processes` to be the number of devices used for training (such as number of GPUs, CPUs, TPUs, etc)
429
+ - If using the TPU, declare your model outside the training loop function
testbed/huggingface__accelerate/docs/source/basic_tutorials/overview.mdx ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Overview
14
+
15
+ Welcome to the 🤗 Accelerate tutorials! These introductory guides will help catch you up to speed on working with 🤗 Accelerate.
16
+ You'll learn how to modify your code to have it work with the API seamlessly, how to launch your script properly,
17
+ and more!
18
+
19
+ These tutorials assume some basic knowledge of Python and familiarity with the PyTorch framework.
20
+
21
+ If you have any questions about 🤗 Accelerate, feel free to join and ask the community on our [forum](https://discuss.huggingface.co/c/accelerate/18).
testbed/huggingface__accelerate/docs/source/concept_guides/deferring_execution.mdx ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Deferring Executions
14
+
15
+ When you run your usual script, instructions are executed in order. Using 🤗 Accelerate to deploy your script on several
16
+ GPUs at the same time introduces a complication: while each process executes all instructions in order, some may be
17
+ faster than others.
18
+
19
+ You might need to wait for all processes to have reached a certain point before executing a given instruction. For
20
+ instance, you shouldn't save a model before being sure every process is done with training, and you wouldn't want to
21
+ continue training before all the model weights have been loaded in. To do this, just write the following line in your code:
22
+
23
+ ```
24
+ accelerator.wait_for_everyone()
25
+ ```
26
+
27
+ This instruction will block all the processes that arrive first until all the other processes have reached that
28
+ point (if you run your script on just one GPU or CPU, this won't do anything).
29
+
30
+ A few example cases for when to use this utility are listed below:
31
+
32
+ <Tip>
33
+
34
+ Some of these are utilized with the [`~Accelerator.main_process_first`] context manager, which utilizes [`~Accelerator.wait_for_everyone`] to
35
+ run a particular set of code on the main process beforehand before triggering and launching the other processes
36
+
37
+ </Tip>
38
+
39
+ ## Downloading a Dataset
40
+
41
+ When downloading a dataset, you should download it first on the main process and then loading the cached dataset in afterwards
42
+
43
+ <Tip>
44
+
45
+ `load_dataset` will perform a lock under the hood to stop multiple downloads from happening at once, but if you are downloading something
46
+ not using this library you should use this method.
47
+
48
+ </Tip>
49
+
50
+ ```python
51
+ with accelerator.main_process_first():
52
+ datasets = load_dataset("glue", "mrpc")
53
+ ```
54
+
55
+ Under the hood this is the same as calling:
56
+
57
+ ```python
58
+ # First do something on the main process
59
+ if accelerator.is_main_process:
60
+ datasets = load_dataset("glue", "mrpc")
61
+ else:
62
+ accelerator.wait_for_everyone()
63
+
64
+ # And then send it to the rest of them
65
+ if not accelerator.is_main_process:
66
+ datasets = load_dataset("glue", "mrpc")
67
+ else:
68
+ accelerator.wait_for_everyone()
69
+ ```
70
+
71
+ ## Saving the `state_dict`
72
+
73
+ When saving the `state_dict` of the model, since you would normally save one file on just the main process
74
+ you should specify that:
75
+
76
+ ```python
77
+ if accelerator.is_main_process:
78
+ model = accelerator.unwrap_model(model)
79
+ torch.save(model.state_dict(), "weights.pth")
80
+ ```
81
+
82
+ ## Loading in the `state_dict`
83
+
84
+ When loading in the `state_dict` to a model, optimizer, or scheduler, you should wait
85
+ for all workers to have the weights loaded in before moving on to training
86
+
87
+ ```python
88
+ with accelerator.main_process_first():
89
+ state = torch.load("weights.pth")
90
+ model.load_state_dict(state)
91
+ ```
92
+
93
+ ## Applying a multi-worker CPU operation
94
+
95
+ Applying a `map()` operation on multiple workers, such as tokenizing should be done on the
96
+ main process first, and then propagated to each one.
97
+
98
+ ```python
99
+ datasets = load_dataset("glue", "mrpc")
100
+
101
+ with accelerator.main_process_first():
102
+ tokenized_datasets = datasets.map(
103
+ tokenize_function,
104
+ batched=True,
105
+ remove_columns=["idx", "sentence1", "sentence2"],
106
+ )
107
+ ```
testbed/huggingface__accelerate/docs/source/concept_guides/gradient_synchronization.mdx ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Gradient Synchronization
14
+
15
+ PyTorch's distributed module operates by communicating back and forth between all of the GPUs in your system.
16
+ This communication takes time, and ensuring all processes know the states of each other happens at particular triggerpoints
17
+ when using the `ddp` module.
18
+
19
+ These triggerpoints are added to the PyTorch model, specifically their `forward()` and `backward()` methods.
20
+ This happens when the model is wrapped with `DistributedDataParallel`:
21
+ ```python
22
+ import torch.nn as nn
23
+ from torch.nn.parallel import DistributedDataParallel
24
+
25
+ model = nn.Linear(10, 10)
26
+ ddp_model = DistributedDataParallel(model)
27
+ ```
28
+ In 🤗 Accelerate this conversion happens automatically when calling [`~Accelerator.prepare`] and passing in your model.
29
+
30
+ ```diff
31
+ + from accelerate import Accelerator
32
+ + accelerator = Accelerator()
33
+ import torch.nn as nn
34
+ - from torch.nn.parallel import DistributedDataParallel
35
+
36
+ model = nn.Linear(10,10)
37
+ + model = accelerator.prepare(model)
38
+ ```
39
+
40
+ ## The slowdown in gradient accumulation
41
+
42
+ You now understand that PyTorch adds hooks to the `forward` and `backward` method of your PyTorch model when
43
+ training in a distributed setup. But how does this risk slowing down your code?
44
+
45
+ In DDP (distributed data parallel), the specific order in which processes are performed and ran are expected
46
+ at specific points and these must also occur at roughly the same time before moving on.
47
+
48
+ The most direct example is when you update all of the parameters in a model through `.backward()`. All instances of the model
49
+ need to have updated their gradients, collated, and updated again before moving onto the next batch of data. But when performing
50
+ gradient accumulation, you accumulate `n` losses and skip `.backward()` until `n` batches have been reached. This
51
+ can cause a significant slowdown since all the processes need to communicate with them more times than needed. How
52
+ can you avoid this overhead?
53
+
54
+ ## Solving the slowdown problem
55
+
56
+ Since you are skipping these batches, their gradients do not need to be synchronized until the point where `.backward()` is actually called.
57
+ PyTorch cannot automagically tell when you need to do this, but they do provide a tool to help through the [`no_sync`](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel.no_sync) context manager
58
+ that is added to your model after converting it to DDP.
59
+
60
+ Under this context manager, PyTorch will skip synchronizing the gradients when `.backward()` is called, and the first call to `.backward()` outside this
61
+ context manager will trigger the synchronization. See an example below:
62
+ ```python
63
+ ddp_model, dataloader = accelerator.prepare(model, dataloader)
64
+
65
+ for index, batch in enumerate(dataloader):
66
+ inputs, targets = batch
67
+ # Trigger gradient synchronization on the last batch
68
+ if index != (len(dataloader) - 1):
69
+ with ddp_model.no_sync():
70
+ # Gradients only accumulate
71
+ outputs = ddp_model(inputs)
72
+ loss = loss_func(outputs)
73
+ accelerator.backward(loss)
74
+ else:
75
+ # Gradients finally sync
76
+ outputs = ddp_model(inputs)
77
+ loss = loss_func(outputs)
78
+ accelerator.backward(loss)
79
+ ```
80
+
81
+ In 🤗 Accelerate to make this an API that can be called no matter the training device (though it may not do anything if you are not in a distributed system!),
82
+ `ddp_model.no_sync` gets replaced with [`~Accelerator.no_sync`] and operates the same way:
83
+
84
+ ```diff
85
+ ddp_model, dataloader = accelerator.prepare(model, dataloader)
86
+
87
+ for index, batch in enumerate(dataloader):
88
+ inputs, targets = batch
89
+ # Trigger gradient synchronization on the last batch
90
+ if index != (len(dataloader)-1):
91
+ - with ddp_model.no_sync():
92
+ + with accelerator.no_sync(model):
93
+ # Gradients only accumulate
94
+ outputs = ddp_model(inputs)
95
+ loss = loss_func(outputs, targets)
96
+ accelerator.backward(loss)
97
+ else:
98
+ # Gradients finally sync
99
+ outputs = ddp_model(inputs)
100
+ loss = loss_func(outputs)
101
+ accelerator.backward(loss)
102
+ ```
103
+
104
+ As you may expect, the [`~Accelerator.accumulate`] function wraps around this conditional check by keeping track of the current batch number, leaving you with the final
105
+ gradient accumulation API:
106
+
107
+ ```python
108
+ ddp_model, dataloader = accelerator.prepare(model, dataloader)
109
+
110
+ for batch in dataloader:
111
+ with accelerator.accumulate(model):
112
+ optimizer.zero_grad()
113
+ inputs, targets = batch
114
+ outputs = model(inputs)
115
+ loss = loss_function(outputs, targets)
116
+ accelerator.backward(loss)
117
+ ```
118
+
119
+ As a result, you should either use *`accelerator.accumulate` or `accelerator.no_sync`* when it comes to API choice.
testbed/huggingface__accelerate/docs/source/concept_guides/performance.mdx ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Comparing performance between different device setups
14
+
15
+ Evaluating and comparing the performance from different setups can be quite tricky if you don't know what to look for.
16
+ For example, you cannot run the same script with the same batch size across TPU, multi-GPU, and single-GPU with Accelerate
17
+ and expect your results to line up.
18
+
19
+ But why?
20
+
21
+ There's three reasons for this that this tutorial will cover:
22
+
23
+ 1. **Setting the right seeds**
24
+ 2. **Observed Batch Sizes**
25
+ 3. **Learning Rates**
26
+
27
+ ## Setting the Seed
28
+
29
+ While this issue has not come up as much, make sure to use [`utils.set_seed`] to fully set the seed in all distributed cases so training will be reproducable:
30
+
31
+ ```python
32
+ from accelerate import set_seed
33
+
34
+ set_seed(42)
35
+ ```
36
+
37
+ Why is this important? Under the hood this will set **5** different seed settings:
38
+
39
+ ```python
40
+ random.seed(seed)
41
+ np.random.seed(seed)
42
+ torch.manual_seed(seed)
43
+ torch.cuda.manual_seed_all(seed)
44
+ # ^^ safe to call this function even if cuda is not available
45
+ if is_tpu_available():
46
+ xm.set_rng_state(seed)
47
+ ```
48
+
49
+ The random state, numpy's state, torch, torch's cuda state, and if TPUs are available torch_xla's cuda state.
50
+
51
+ ## Observed Batch Sizes
52
+
53
+ When training with Accelerate, the batch size passed to the dataloader is the **batch size per GPU**. What this entails is
54
+ a batch size of 64 on two GPUs is truly a batch size of 128. As a result, when testing on a single GPU this needs to be accounted for,
55
+ as well as similarly for TPUs.
56
+
57
+ The below table can be used as a quick reference to try out different batch sizes:
58
+
59
+ <Tip>
60
+
61
+ In this example there are two GPUs for "Multi-GPU" and a TPU pod with 8 workers
62
+
63
+ </Tip>
64
+
65
+ | Single GPU Batch Size | Multi-GPU Equivalent Batch Size | TPU Equivalent Batch Size |
66
+ |-----------------------|---------------------------------|---------------------------|
67
+ | 256 | 128 | 32 |
68
+ | 128 | 64 | 16 |
69
+ | 64 | 32 | 8 |
70
+ | 32 | 16 | 4 |
71
+
72
+ ## Learning Rates
73
+
74
+ As noted in multiple sources[[1](https://aws.amazon.com/blogs/machine-learning/scalable-multi-node-deep-learning-training-using-gpus-in-the-aws-cloud/)][[2](https://docs.nvidia.com/clara/tlt-mi_archive/clara-train-sdk-v2.0/nvmidl/appendix/training_with_multiple_gpus.html)], the learning rate should be scaled *linearly* based on the number of devices present. The below
75
+ snippet shows doing so with Accelerate:
76
+
77
+ <Tip>
78
+
79
+ Since users can have their own learning rate schedulers defined, we leave this up to the user to decide if they wish to scale their
80
+ learning rate or not.
81
+
82
+ </Tip>
83
+
84
+ ```python
85
+ learning_rate = 1e-3
86
+ accelerator = Accelerator()
87
+ learning_rate *= accelerator.num_processes
88
+
89
+ optimizer = AdamW(params=model.parameters(), lr=learning_rate)
90
+ ```
91
+
testbed/huggingface__accelerate/docs/source/concept_guides/training_tpu.mdx ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Training on TPUs with 🤗 Accelerate
14
+
15
+ Training on TPUs can be slightly different than training on multi-gpu, even with 🤗 Accelerate. This guide aims to show you
16
+ where you should be careful and why, as well as the best practices in general.
17
+
18
+ ## Training in a Notebook
19
+
20
+ The main carepoint when training on TPUs comes from the [`notebook_launcher`]. As mentioned in the [notebook tutorial](../usage_guides/notebook), you need to
21
+ restructure your training code into a function that can get passed to the [`notebook_launcher`] function and be careful about not declaring any tensors on the GPU.
22
+
23
+ While on a TPU that last part is not as important, a critical part to understand is that when you launch code from a notebook you do so through a process called **forking**.
24
+ When launching from the command-line, you perform **spawning**, where a python process is not currently running and you *spawn* a new process in. Since your Jupyter notebook is already
25
+ utilizing a python process, you need to *fork* a new process from it to launch your code.
26
+
27
+ Where this becomes important is in regards to declaring your model. On forked TPU processes, it is recommended that you instantiate your model *once* and pass this into your
28
+ training function. This is different than training on GPUs where you create `n` models that have their gradients synced and back-propagated at certain moments. Instead one
29
+ model instance is shared between all the nodes and it is passed back and forth. This is important especially when training on low-resource TPUs such as those provided in Kaggle kernels or
30
+ on Google Colaboratory.
31
+
32
+ Below is an example of a training function passed to the [`notebook_launcher`] if training on CPUs or GPUs:
33
+
34
+ <Tip>
35
+
36
+ This code snippet is based off the one from the `simple_nlp_example` notebook found [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate/simple_nlp_example.ipynb) with slight
37
+ modifications for the sake of simplicity
38
+
39
+ </Tip>
40
+
41
+ ```python
42
+ def training_function():
43
+ # Initialize accelerator
44
+ accelerator = Accelerator()
45
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2)
46
+ train_dataloader, eval_dataloader = create_dataloaders(
47
+ train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"]
48
+ )
49
+
50
+ # Instantiate optimizer
51
+ optimizer = AdamW(params=model.parameters(), lr=hyperparameters["learning_rate"])
52
+
53
+ # Prepare everything
54
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
55
+ # prepare method.
56
+ model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
57
+ model, optimizer, train_dataloader, eval_dataloader
58
+ )
59
+
60
+ num_epochs = hyperparameters["num_epochs"]
61
+ # Now we train the model
62
+ for epoch in range(num_epochs):
63
+ model.train()
64
+ for step, batch in enumerate(train_dataloader):
65
+ outputs = model(**batch)
66
+ loss = outputs.loss
67
+ accelerator.backward(loss)
68
+
69
+ optimizer.step()
70
+ optimizer.zero_grad()
71
+ ```
72
+
73
+ ```python
74
+ from accelerate import notebook_launcher
75
+
76
+ notebook_launcher(training_function)
77
+ ```
78
+
79
+ <Tip>
80
+
81
+ The `notebook_launcher` will default to 8 processes if 🤗 Accelerate has been configured for a TPU
82
+
83
+ </Tip>
84
+
85
+ If you use this example and declare the model *inside* the training loop, then on a low-resource system you will potentially see an error
86
+ like:
87
+
88
+ ```
89
+ ProcessExitedException: process 0 terminated with signal SIGSEGV
90
+ ```
91
+
92
+ This error is *extremely* cryptic but the basic explanation is you ran out of system RAM. You can avoid this entirely by reconfiguring the training function to
93
+ accept a single `model` argument, and declare it in an outside cell:
94
+
95
+ ```python
96
+ # In another Jupyter cell
97
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2)
98
+ ```
99
+
100
+ ```diff
101
+ + def training_function(model):
102
+ # Initialize accelerator
103
+ accelerator = Accelerator()
104
+ - model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2)
105
+ train_dataloader, eval_dataloader = create_dataloaders(
106
+ train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"]
107
+ )
108
+ ...
109
+ ```
110
+
111
+ And finally calling the training function with:
112
+
113
+ ```diff
114
+ from accelerate import notebook_launcher
115
+ - notebook_launcher(training_function)
116
+ + notebook_launcher(training_function, (model,))
117
+ ```
118
+
119
+ <Tip>
120
+
121
+ The above workaround is only needed when launching a TPU instance from a Jupyter Notebook on a low-resource server such as Google Colaboratory or Kaggle. If
122
+ using a script or launching on a much beefier server declaring the model beforehand is not needed.
123
+
124
+ </Tip>
125
+
126
+ ## Mixed Precision and Global Variables
127
+
128
+ As mentioned in the [mixed precision tutorial](../usage_guides/mixed_precision), 🤗 Accelerate supports fp16 and bf16, both of which can be used on TPUs.
129
+ That being said, ideally `bf16` should be utilized as it is extremely efficient to use.
130
+
131
+ There are two "layers" when using `bf16` and 🤗 Accelerate on TPUs, at the base level and at the operation level.
132
+
133
+ At the base level, this is enabled when passing `mixed_precision="bf16"` to `Accelerator`, such as:
134
+ ```python
135
+ accelerator = Accelerator(mixed_precision="bf16")
136
+ ```
137
+ By default this will cast `torch.float` and `torch.double` to `bfloat16` on TPUs.
138
+ The specific configuration being set is an environmental variable of `XLA_USE_BF16` is set to `1`.
139
+
140
+ There is a further configuration you can perform which is setting the `XLA_DOWNCAST_BF16` environmental variable. If set to `1`, then
141
+ `torch.float` is `bfloat16` and `torch.double` is `float32`.
142
+
143
+ This is performed in the `Accelerator` object when passing `downcast_bf16=True`:
144
+ ```python
145
+ accelerator = Accelerator(mixed_precision="bf16", downcast_bf16=True)
146
+ ```
147
+
148
+ Using downcasting instead of bf16 everywhere is good for when you are trying to calculate metrics, log values, and more where raw bf16 tensors would be unusable.
149
+
150
+ ## Training Times on TPUs
151
+
152
+ As you launch your script, you may notice that training seems exceptionally slow at first. This is because TPUs
153
+ first run through a few batches of data to see how much memory to allocate before finally utilizing this configured
154
+ memory allocation extremely efficiently.
155
+
156
+ If you notice that your evaluation code to calculate the metrics of your model takes longer due to a larger batch size being used,
157
+ it is recommended to keep the batch size the same as the training data if it is too slow. Otherwise the memory will reallocate to this
158
+ new batch size after the first few iterations.
159
+
160
+ <Tip>
161
+
162
+ Just because the memory is allocated does not mean it will be used or that the batch size will increase when going back to your training dataloader.
163
+
164
+ </Tip>
testbed/huggingface__accelerate/docs/source/index.mdx ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Accelerate
14
+
15
+ 🤗 Accelerate is a library that enables the same PyTorch code to be run across any distributed configuration by adding just four lines of code! In short, training and inference at scale made simple, efficient and adaptable.
16
+
17
+ ```diff
18
+ + from accelerate import Accelerator
19
+ + accelerator = Accelerator()
20
+
21
+ + model, optimizer, training_dataloader, scheduler = accelerator.prepare(
22
+ + model, optimizer, training_dataloader, scheduler
23
+ + )
24
+
25
+ for batch in training_dataloader:
26
+ optimizer.zero_grad()
27
+ inputs, targets = batch
28
+ inputs = inputs.to(device)
29
+ targets = targets.to(device)
30
+ outputs = model(inputs)
31
+ loss = loss_function(outputs, targets)
32
+ + accelerator.backward(loss)
33
+ optimizer.step()
34
+ scheduler.step()
35
+ ```
36
+
37
+ Built on `torch_xla` and `torch.distributed`, 🤗 Accelerate takes care of the heavy lifting, so you don't have to write any custom code to adapt to these platforms.
38
+ Convert existing codebases to utilize [DeepSpeed](usage_guides/deepspeed), perform [fully sharded data parallelism](usage_guides/fsdp), and have automatic support for mixed-precision training!
39
+
40
+ <Tip>
41
+
42
+ To get a better idea of this process, make sure to check out the [Tutorials](basic_tutorials/overview)!
43
+
44
+ </Tip>
45
+
46
+
47
+ This code can then be launched on any system through Accelerate's CLI interface:
48
+ ```bash
49
+ accelerate launch {my_script.py}
50
+ ```
51
+
52
+ <div class="mt-10">
53
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
54
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./basic_tutorials/overview"
55
+ ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div>
56
+ <p class="text-gray-700">Learn the basics and become familiar with using 🤗 Accelerate. Start here if you are using 🤗 Accelerate for the first time!</p>
57
+ </a>
58
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./usage_guides/gradient_accumulation"
59
+ ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div>
60
+ <p class="text-gray-700">Practical guides to help you achieve a specific goal. Take a look at these guides to learn how to use 🤗 Accelerate to solve real-world problems.</p>
61
+ </a>
62
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./concept_guides/gradient_synchronization"
63
+ ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
64
+ <p class="text-gray-700">High-level explanations for building a better understanding of important topics such as avoiding subtle nuances and pitfalls in distributed training and DeepSpeed.</p>
65
+ </a>
66
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./package_reference/accelerator"
67
+ ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div>
68
+ <p class="text-gray-700">Technical descriptions of how 🤗 Accelerate classes and methods work.</p>
69
+ </a>
70
+ </div>
71
+ </div>
testbed/huggingface__accelerate/docs/source/package_reference/accelerator.mdx ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Accelerator
14
+
15
+ The [`Accelerator`] is the main class provided by 🤗 Accelerate.
16
+ It serves at the main entrypoint for the API.
17
+
18
+ ## Quick adaptation of your code
19
+
20
+ To quickly adapt your script to work on any kind of setup with 🤗 Accelerate just:
21
+
22
+ 1. Initialize an [`Accelerator`] object (that we will call `accelerator` throughout this page) as early as possible in your script.
23
+ 2. Pass your dataloader(s), model(s), optimizer(s), and scheduler(s) to the [`~Accelerator.prepare`] method.
24
+ 3. Remove all the `.cuda()` or `.to(device)` from your code and let the `accelerator` handle the device placement for you.
25
+
26
+ <Tip>
27
+
28
+ Step three is optional, but considered a best practice.
29
+
30
+ </Tip>
31
+
32
+ 4. Replace `loss.backward()` in your code with `accelerator.backward(loss)`
33
+ 5. Gather your predictions and labels before storing them or using them for metric computation using [`~Accelerator.gather`]
34
+
35
+ <Tip warning={true}>
36
+
37
+ Step five is mandatory when using distributed evaluation
38
+
39
+ </Tip>
40
+
41
+ In most cases this is all that is needed. The next section lists a few more advanced use cases and nice features
42
+ you should search for and replace by the corresponding methods of your `accelerator`:
43
+
44
+ ## Advanced recommendations
45
+
46
+ ### Printing
47
+
48
+ `print` statements should be replaced by [`~Accelerator.print`] to be printed once per process
49
+
50
+ ```diff
51
+ - print("My thing I want to print!")
52
+ + accelerator.print("My thing I want to print!")
53
+ ```
54
+
55
+ ### Executing processes
56
+
57
+ #### Once on a single server
58
+
59
+ For statements that should be executed once per server, use [`~Accelerator.is_local_main_process`]:
60
+
61
+ ```python
62
+ if accelerator.is_local_main_process:
63
+ do_thing_once_per_server()
64
+ ```
65
+
66
+ A function can be wrapped using the [`~Accelerator.on_local_main_process`] function to achieve the same
67
+ behavior on a function's execution:
68
+
69
+ ```python
70
+ @accelerator.on_local_main_process
71
+ def do_my_thing():
72
+ "Something done once per server"
73
+ do_thing_once_per_server()
74
+ ```
75
+
76
+ #### Only ever once across all servers
77
+
78
+ For statements that should only ever be executed once, use [`~Accelerator.is_main_process`]:
79
+
80
+ ```python
81
+ if accelerator.is_main_process:
82
+ do_thing_once()
83
+ ```
84
+
85
+ A function can be wrapped using the [`~Accelerator.on_main_process`] function to achieve the same
86
+ behavior on a function's execution:
87
+
88
+ ```python
89
+ @accelerator.on_main_process
90
+ def do_my_thing():
91
+ "Something done once per server"
92
+ do_thing_once()
93
+ ```
94
+
95
+ #### On specific processes
96
+
97
+ If a function should be ran on a specific overall or local process index, there are similar decorators
98
+ to achieve this:
99
+
100
+ ```python
101
+ @accelerator.on_local_process(local_process_idx=0)
102
+ def do_my_thing():
103
+ "Something done on process index 0 on each server"
104
+ do_thing_on_index_zero_on_each_server()
105
+ ```
106
+
107
+ ```python
108
+ @accelerator.on_process(process_index=0)
109
+ def do_my_thing():
110
+ "Something done on process index 0"
111
+ do_thing_on_index_zero()
112
+ ```
113
+
114
+ ### Synchronicity control
115
+
116
+ Use [`~Accelerator.wait_for_everyone`] to make sure all processes join that point before continuing. (Useful before a model save for instance)
117
+
118
+ ### Saving and loading
119
+
120
+ Use [`~Accelerator.unwrap_model`] before saving to remove all special model wrappers added during the distributed process.
121
+
122
+ ```python
123
+ model = MyModel()
124
+ model = accelerator.prepare(model)
125
+ # Unwrap
126
+ model = accelerator.unwrap_model(model)
127
+ ```
128
+
129
+ Use [`~Accelerator.save`] instead of `torch.save`:
130
+
131
+ ```diff
132
+ state_dict = model.state_dict()
133
+ - torch.save(state_dict, "my_state.pkl")
134
+ + accelerator.save(state_dict, "my_state.pkl")
135
+ ```
136
+
137
+ ### Operations
138
+
139
+ Use [`~Accelerator.clip_grad_norm_`] instead of ``torch.nn.utils.clip_grad_norm_`` and [`~Accelerator.clip_grad_value_`] instead of ``torch.nn.utils.clip_grad_value``
140
+
141
+ ### Gradient Accumulation
142
+
143
+ To perform gradient accumulation use [`~Accelerator.accumulate`] and specify a gradient_accumulation_steps.
144
+ This will also automatically ensure the gradients are synced or unsynced when on
145
+ multi-device training, check if the step should actually be performed, and auto-scale the loss:
146
+
147
+ ```diff
148
+ - accelerator = Accelerator()
149
+ + accelerator = Accelerator(gradient_accumulation_steps=2)
150
+
151
+ for (input, label) in training_dataloader:
152
+ + with accelerator.accumulate(model):
153
+ predictions = model(input)
154
+ loss = loss_function(predictions, labels)
155
+ accelerator.backward(loss)
156
+ optimizer.step()
157
+ scheduler.step()
158
+ optimizer.zero_grad()
159
+ ```
160
+
161
+ ## Overall API documentation:
162
+
163
+ [[autodoc]] Accelerator
testbed/huggingface__accelerate/docs/source/package_reference/big_modeling.mdx ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Working with large models
14
+
15
+ ## Dispatching and Offloading Models
16
+
17
+ [[autodoc]] big_modeling.init_empty_weights
18
+ [[autodoc]] big_modeling.cpu_offload
19
+ [[autodoc]] big_modeling.disk_offload
20
+ [[autodoc]] big_modeling.dispatch_model
21
+ [[autodoc]] big_modeling.load_checkpoint_and_dispatch
22
+
23
+ ## Model Hooks
24
+
25
+ ### Hook Classes
26
+
27
+ [[autodoc]] hooks.ModelHook
28
+ [[autodoc]] hooks.AlignDevicesHook
29
+ [[autodoc]] hooks.SequentialHook
30
+
31
+ ### Adding Hooks
32
+
33
+ [[autodoc]] hooks.add_hook_to_module
34
+ [[autodoc]] hooks.attach_execution_device_hook
35
+ [[autodoc]] hooks.attach_align_device_hook
36
+ [[autodoc]] hooks.attach_align_device_hook_on_blocks
37
+
38
+ ### Removing Hooks
39
+
40
+ [[autodoc]] hooks.remove_hook_from_module
41
+ [[autodoc]] hooks.remove_hook_from_submodules
testbed/huggingface__accelerate/docs/source/package_reference/cli.mdx ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # The Command Line
14
+
15
+ Below is a list of all the available commands 🤗 Accelerate with their parameters
16
+
17
+ ## accelerate config
18
+
19
+ **Command**:
20
+
21
+ `accelerate config` or `accelerate-config`
22
+
23
+ Launches a series of prompts to create and save a `default_config.yml` configuration file for your training system. Should
24
+ always be ran first on your machine.
25
+
26
+ **Usage**:
27
+
28
+ ```bash
29
+ accelerate config [arguments]
30
+ ```
31
+
32
+ **Optional Arguments**:
33
+ * `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content
34
+ of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory
35
+ (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`.
36
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
37
+
38
+ ## accelerate config default
39
+
40
+ **Command**:
41
+
42
+ `accelerate config default` or `accelerate-config default`
43
+
44
+ Create a default config file for Accelerate with only a few flags set.
45
+
46
+ **Usage**:
47
+
48
+ ```bash
49
+ accelerate config default [arguments]
50
+ ```
51
+
52
+ **Optional Arguments**:
53
+ * `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content
54
+ of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory
55
+ (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`.
56
+
57
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
58
+ * `--mixed_precision {no,fp16,bf16}` (`str`) -- Whether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.
59
+
60
+ ## accelerate config update
61
+
62
+ **Command**:
63
+
64
+ `accelerate config update` or `accelerate-config update`
65
+
66
+ Update an existing config file with the latest defaults while maintaining the old configuration.
67
+
68
+ **Usage**:
69
+
70
+ ```bash
71
+ accelerate config update [arguments]
72
+ ```
73
+
74
+ **Optional Arguments**:
75
+ * `--config_file CONFIG_FILE` (`str`) -- The path to the config file to update. Will default to a file named default_config.yaml in the cache location, which is the content
76
+ of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory
77
+ (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`.
78
+
79
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
80
+
81
+
82
+ ## accelerate env
83
+
84
+ **Command**:
85
+
86
+ `accelerate env` or `accelerate-env`
87
+
88
+ Lists the contents of the passed 🤗 Accelerate configuration file. Should always be used when opening an issue on the [GitHub repository](https://github.com/huggingface/accelerate).
89
+
90
+ **Usage**:
91
+
92
+ ```bash
93
+ accelerate env [arguments]
94
+ ```
95
+
96
+ **Optional Arguments**:
97
+ * `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content
98
+ of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory
99
+ (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`.
100
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
101
+
102
+ ## accelerate launch
103
+
104
+ **Command**:
105
+
106
+ `accelerate launch` or `accelerate-launch`
107
+
108
+ Launches a specified script on a distributed system with the right parameters.
109
+
110
+ **Usage**:
111
+
112
+ ```bash
113
+ accelerate launch [arguments] {training_script} --{training_script-argument-1} --{training_script-argument-2} ...
114
+ ```
115
+
116
+ **Positional Arguments**:
117
+
118
+ - `{training_script}` -- The full path to the script to be launched in parallel
119
+ - `--{training_script-argument-1}` -- Arguments of the training script
120
+
121
+ **Optional Arguments**:
122
+
123
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
124
+ * `--config_file CONFIG_FILE` (`str`)-- The config file to use for the default values in the launching script.
125
+ * `-m`, `--module` (`bool`) -- Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.
126
+ * `--no_python` (`bool`) -- Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.
127
+ * `--debug` (`bool`) -- Whether to print out the torch.distributed stack trace when something fails.
128
+ * `-q`, `--quiet` (`bool`) -- Silence subprocess errors from the launch stack trace to only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations).
129
+
130
+
131
+ The rest of these arguments are configured through `accelerate config` and are read in from the specified `--config_file` (or default configuration) for their
132
+ values. They can also be passed in manually.
133
+
134
+ **Hardware Selection Arguments**:
135
+
136
+ * `--cpu` (`bool`) -- Whether or not to force the training on the CPU.
137
+ * `--multi_gpu` (`bool`) -- Whether or not this should launch a distributed GPU training.
138
+ * `--mps` (`bool`) -- Whether or not this should use MPS-enabled GPU device on MacOS machines.
139
+ * `--tpu` (`bool`) -- Whether or not this should launch a TPU training.
140
+
141
+ **Resource Selection Arguments**:
142
+
143
+ The following arguments are useful for fine-tuning how available hardware should be used
144
+
145
+ * `--mixed_precision {no,fp16,bf16}` (`str`) -- Whether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.
146
+ * `--num_processes NUM_PROCESSES` (`int`) -- The total number of processes to be launched in parallel.
147
+ * `--num_machines NUM_MACHINES` (`int`) -- The total number of machines used in this training.
148
+ * `--num_cpu_threads_per_process NUM_CPU_THREADS_PER_PROCESS` (`int`) -- The number of CPU threads per process. Can be tuned for optimal performance.
149
+
150
+ **Training Paradigm Arguments**:
151
+
152
+ The following arguments are useful for selecting which training paradigm to use.
153
+
154
+ * `--use_deepspeed` (`bool`) -- Whether or not to use DeepSpeed for training.
155
+ * `--use_fsdp` (`bool`) -- Whether or not to use FullyShardedDataParallel for training.
156
+ * `--use_megatron_lm` (`bool`) -- Whether or not to use Megatron-LM for training.
157
+
158
+ **Distributed GPU Arguments**:
159
+
160
+ The following arguments are only useful when `multi_gpu` is passed or multi-gpu training is configured through `accelerate config`:
161
+
162
+ * `--gpu_ids` (`str`) -- What GPUs (by id) should be used for training on this machine as a comma-seperated list
163
+ * `--same_network` (`bool`) -- Whether all machines used for multinode training exist on the same local network.
164
+ * `--machine_rank MACHINE_RANK` (`int`) -- The rank of the machine on which this script is launched.
165
+ * `--main_process_ip MAIN_PROCESS_IP` (`str`) -- The IP address of the machine of rank 0.
166
+ * `--main_process_port MAIN_PROCESS_PORT` (`int`) -- The port to use to communicate with the machine of rank 0.
167
+ * `--rdzv_conf` (`str`) -- Additional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).
168
+ * `--max_restarts` (`int`) -- Maximum number of worker group restarts before failing.
169
+ * `--monitor_interval` (`float`) -- Interval, in seconds, to monitor the state of workers.
170
+
171
+ **TPU Arguments**:
172
+
173
+ The following arguments are only useful when `tpu` is passed or TPU training is configured through `accelerate config`:
174
+
175
+ * `--main_training_function MAIN_TRAINING_FUNCTION` (`str`) -- The name of the main function to be executed in your script.
176
+ * `--downcast_bf16` (`bool`) -- Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32.
177
+
178
+ **DeepSpeed Arguments**:
179
+
180
+ The following arguments are only useful when `use_deepspeed` is passed or `deepspeed` is configured through `accelerate config`:
181
+
182
+ * `--deepspeed_config_file` (`str`) -- DeepSpeed config file.
183
+ * `--zero_stage` (`int`) -- DeepSpeed's ZeRO optimization stage.
184
+ * `--offload_optimizer_device` (`str`) -- Decides where (none|cpu|nvme) to offload optimizer states.
185
+ * `--offload_param_device` (`str`) -- Decides where (none|cpu|nvme) to offload parameters.
186
+ * `--gradient_accumulation_steps` (`int`) -- No of gradient_accumulation_steps used in your training script.
187
+ * `--gradient_clipping` (`float`) -- Gradient clipping value used in your training script.
188
+ * `--zero3_init_flag` (`str`) -- Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with DeepSpeed ZeRO Stage-3.
189
+ * `--zero3_save_16bit_model` (`str`) -- Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. Only applicable with DeepSpeed ZeRO Stage-3.
190
+ * `--deepspeed_hostfile` (`str`) -- DeepSpeed hostfile for configuring multi-node compute resources.
191
+ * `--deepspeed_exclusion_filter` (`str`) -- DeepSpeed exclusion filter string when using mutli-node setup.
192
+ * `--deepspeed_inclusion_filter` (`str`) -- DeepSpeed inclusion filter string when using mutli-node setup.
193
+ * `--deepspeed_multinode_launcher` (`str`) -- DeepSpeed multi-node launcher to use.
194
+
195
+ **Fully Sharded Data Parallelism Arguments**:
196
+
197
+ The following arguments are only useful when `use_fdsp` is passed or Fully Sharded Data Parallelism is configured through `accelerate config`:
198
+
199
+ * `--fsdp_offload_params` (`str`) -- Decides Whether (true|false) to offload parameters and gradients to CPU.
200
+ * `--fsdp_min_num_params` (`int`) -- FSDP's minimum number of parameters for Default Auto Wrapping.
201
+ * `--fsdp_sharding_strategy` (`int`) -- FSDP's Sharding Strategy.
202
+ * `--fsdp_auto_wrap_policy` (`str`) -- FSDP's auto wrap policy.
203
+ * `--fsdp_transformer_layer_cls_to_wrap` (`str`) -- Transformer layer class name (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` ...
204
+ * `--fsdp_backward_prefetch_policy` (`str`) -- FSDP's backward prefetch policy.
205
+ * `--fsdp_state_dict_type` (`str`) -- FSDP's state dict type.
206
+
207
+ **Megatron-LM Arguments**:
208
+
209
+ The following arguments are only useful when `use_megatron_lm` is passed or Megatron-LM is configured through `accelerate config`:
210
+
211
+ * `--megatron_lm_tp_degree` (``) -- Megatron-LM's Tensor Parallelism (TP) degree.
212
+ * `--megatron_lm_pp_degree` (``) -- Megatron-LM's Pipeline Parallelism (PP) degree.
213
+ * `--megatron_lm_num_micro_batches` (``) -- Megatron-LM's number of micro batches when PP degree > 1.
214
+ * `--megatron_lm_sequence_parallelism` (``) -- Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1.
215
+ * `--megatron_lm_recompute_activations` (``) -- Decides Whether (true|false) to enable Selective Activation Recomputation.
216
+ * `--megatron_lm_use_distributed_optimizer` (``) -- Decides Whether (true|false) to use distributed optimizer which shards optimizer state and gradients across Data Pralellel (DP) ranks.
217
+ * `--megatron_lm_gradient_clipping` (``) -- Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable).
218
+
219
+ **AWS SageMaker Arguments**:
220
+
221
+ The following arguments are only useful when training in SageMaker
222
+
223
+ * `--aws_access_key_id AWS_ACCESS_KEY_ID` (`str`) -- The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job
224
+ * `--aws_secret_access_key AWS_SECRET_ACCESS_KEY` (`str`) -- The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job
225
+
226
+ ## accelerate tpu-config
227
+
228
+ `accelerate tpu-config`
229
+
230
+ **Usage**:
231
+
232
+ ```bash
233
+ accelerate tpu-config [arguments]
234
+ ```
235
+
236
+ **Optional Arguments**:
237
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
238
+
239
+ **Config Arguments**:
240
+
241
+ Arguments that can be configured through `accelerate config`.
242
+
243
+ * `--config_file` (`str`) -- Path to the config file to use for accelerate.
244
+ * `--tpu_name` (`str`) -- The name of the TPU to use. If not specified, will use the TPU specified in the config file.
245
+ * `--tpu_zone` (`str`) -- The zone of the TPU to use. If not specified, will use the zone specified in the config file.
246
+
247
+ **TPU Arguments**:
248
+
249
+ Arguments for options ran inside the TPU.
250
+
251
+ * `--command_file` (`str`) -- The path to the file containing the commands to run on the pod on startup.
252
+ * `--command` (`str`) -- A command to run on the pod. Can be passed multiple times.
253
+ * `--install_accelerate` (`bool`) -- Whether to install accelerate on the pod. Defaults to False.
254
+ * `--accelerate_version` (`str`) -- The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.
255
+ * `--debug` (`bool`) -- If set, will print the command that would be run instead of running it.
256
+
257
+ ## accelerate test
258
+
259
+ `accelerate test` or `accelerate-test`
260
+
261
+ Runs `accelerate/test_utils/test_script.py` to verify that 🤗 Accelerate has been properly configured on your system and runs.
262
+
263
+ **Usage**:
264
+
265
+ ```bash
266
+ accelerate test [arguments]
267
+ ```
268
+
269
+ **Optional Arguments**:
270
+ * `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content
271
+ of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory
272
+ (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`.
273
+ * `-h`, `--help` (`bool`) -- Show a help message and exit
testbed/huggingface__accelerate/docs/source/package_reference/deepspeed.mdx ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Utilities for DeepSpeed
14
+
15
+ [[autodoc]] utils.DeepSpeedPlugin
16
+
17
+ [[autodoc]] utils.DummyOptim
18
+
19
+ [[autodoc]] utils.DummyScheduler
20
+
21
+ [[autodoc]] utils.DeepSpeedEngineWrapper
22
+
23
+ [[autodoc]] utils.DeepSpeedOptimizerWrapper
24
+
25
+ [[autodoc]] utils.DeepSpeedSchedulerWrapper
testbed/huggingface__accelerate/docs/source/package_reference/kwargs.mdx ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Kwargs Handlers
14
+
15
+ The following objects can be passed to the main [`Accelerator`] to customize how some PyTorch objects
16
+ related to distributed training or mixed precision are created.
17
+
18
+
19
+ ## DistributedDataParallelKwargs
20
+
21
+ [[autodoc]] DistributedDataParallelKwargs
22
+
23
+ ## GradScalerKwargs
24
+
25
+ [[autodoc]] GradScalerKwargs
26
+
27
+ ## InitProcessGroupKwargs
28
+
29
+ [[autodoc]] InitProcessGroupKwargs
testbed/huggingface__accelerate/docs/source/package_reference/launchers.mdx ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Launchers
14
+
15
+ Functions for launching training on distributed processes.
16
+
17
+
18
+ [[autodoc]] accelerate.notebook_launcher
19
+ [[autodoc]] accelerate.debug_launcher
testbed/huggingface__accelerate/docs/source/package_reference/logging.mdx ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Logging with Accelerate
14
+
15
+ Accelerate has its own logging utility to handle logging while in a distributed system.
16
+ To utilize this replace cases of `logging` with `accelerate.logging`:
17
+ ```diff
18
+ - import logging
19
+ + from accelerate.logging import get_logger
20
+ - logger = logging.getLogger(__name__)
21
+ + logger = get_logger(__name__)
22
+ ```
23
+
24
+ ## Setting the log level
25
+
26
+ The log level can be set with the `ACCELERATE_LOG_LEVEL` environment variable or by passing
27
+ `log_level` to `get_logger`:
28
+ ```python
29
+ from accelerate.logging import get_logger
30
+
31
+ logger = get_logger(__name__, log_level="INFO")
32
+ ```
33
+
34
+ [[autodoc]] logging.get_logger
testbed/huggingface__accelerate/docs/source/package_reference/megatron_lm.mdx ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Utilities for Megatron-LM
14
+
15
+ [[autodoc]] utils.MegatronLMPlugin
16
+
17
+ [[autodoc]] utils.MegatronLMDummyScheduler
18
+
19
+ [[autodoc]] utils.MegatronLMDummyDataLoader
20
+
21
+ [[autodoc]] utils.AbstractTrainStep
22
+
23
+ [[autodoc]] utils.GPTTrainStep
24
+
25
+ [[autodoc]] utils.BertTrainStep
26
+
27
+ [[autodoc]] utils.T5TrainStep
28
+
29
+ [[autodoc]] utils.avg_losses_across_data_parallel_group
testbed/huggingface__accelerate/docs/source/package_reference/state.mdx ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Stateful Classes
14
+
15
+ Below are variations of a [singleton class](https://en.wikipedia.org/wiki/Singleton_pattern) in the sense that all
16
+ instances share the same state, which is initialized on the first instantiation.
17
+
18
+ These classes are immutable and store information about certain configurations or
19
+ states.
20
+
21
+ [[autodoc]] state.AcceleratorState
22
+
23
+ [[autodoc]] state.GradientState
testbed/huggingface__accelerate/docs/source/package_reference/torch_wrappers.mdx ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Wrapper classes for torch Dataloaders, Optimizers, and Schedulers
14
+
15
+ The internal classes Accelerate uses to prepare objects for distributed training
16
+ when calling [`~Accelerator.prepare`].
17
+
18
+ ## Datasets and DataLoaders
19
+
20
+ [[autodoc]] data_loader.prepare_data_loader
21
+
22
+ [[autodoc]] data_loader.BatchSamplerShard
23
+ [[autodoc]] data_loader.IterableDatasetShard
24
+ [[autodoc]] data_loader.DataLoaderShard
25
+ [[autodoc]] data_loader.DataLoaderDispatcher
26
+
27
+ ## Optimizers
28
+
29
+ [[autodoc]] optimizer.AcceleratedOptimizer
30
+
31
+ ## Schedulers
32
+
33
+ [[autodoc]] scheduler.AcceleratedScheduler
testbed/huggingface__accelerate/docs/source/package_reference/tracking.mdx ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Experiment Tracking
14
+
15
+ ## The Base Tracker Class
16
+
17
+ [[autodoc]] tracking.GeneralTracker
18
+
19
+ ## Integrated Trackers
20
+
21
+ [[autodoc]] tracking.TensorBoardTracker
22
+ - __init__
23
+ [[autodoc]] tracking.WandBTracker
24
+ - __init__
25
+ [[autodoc]] tracking.CometMLTracker
26
+ - __init__
testbed/huggingface__accelerate/docs/source/package_reference/utilities.mdx ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Helpful Utilities
14
+
15
+ Below are a variety of utility functions that 🤗 Accelerate provides, broken down by use-case.
16
+
17
+ ## Data Classes
18
+
19
+ These are basic dataclasses used throughout 🤗 Accelerate and they can be passed in as parameters.
20
+
21
+ [[autodoc]] utils.DistributedType
22
+
23
+ [[autodoc]] utils.LoggerType
24
+
25
+ [[autodoc]] utils.PrecisionType
26
+
27
+ [[autodoc]] utils.ProjectConfiguration
28
+
29
+ ## Data Manipulation and Operations
30
+
31
+ These include data operations that mimic the same `torch` ops but can be used on distributed processes.
32
+
33
+ [[autodoc]] utils.broadcast
34
+
35
+ [[autodoc]] utils.concatenate
36
+
37
+ [[autodoc]] utils.gather
38
+
39
+ [[autodoc]] utils.pad_across_processes
40
+
41
+ [[autodoc]] utils.reduce
42
+
43
+ [[autodoc]] utils.send_to_device
44
+
45
+ ## Environment Checks
46
+
47
+ These functionalities check the state of the current working environment including information about the operating system itself, what it can support, and if particular dependencies are installed.
48
+
49
+ [[autodoc]] utils.is_bf16_available
50
+
51
+ [[autodoc]] utils.is_torch_version
52
+
53
+ [[autodoc]] utils.is_tpu_available
54
+
55
+ ## Environment Configuration
56
+
57
+ [[autodoc]] utils.write_basic_config
58
+
59
+ When setting up 🤗 Accelerate for the first time, rather than running `accelerate config` [~utils.write_basic_config] can be used as an alternative for quick configuration.
60
+
61
+ ## Memory
62
+
63
+ [[autodoc]] utils.get_max_memory
64
+
65
+ [[autodoc]] utils.find_executable_batch_size
66
+
67
+ ## Modeling
68
+
69
+ These utilities relate to interacting with PyTorch models
70
+
71
+ [[autodoc]] utils.extract_model_from_parallel
72
+
73
+ [[autodoc]] utils.get_max_layer_size
74
+
75
+ [[autodoc]] utils.offload_state_dict
76
+
77
+
78
+ ## Parallel
79
+
80
+ These include general utilities that should be used when working in parallel.
81
+
82
+ [[autodoc]] utils.extract_model_from_parallel
83
+
84
+ [[autodoc]] utils.save
85
+
86
+ [[autodoc]] utils.wait_for_everyone
87
+
88
+
89
+ ## Random
90
+
91
+ These utilities relate to setting and synchronizing of all the random states.
92
+
93
+ [[autodoc]] utils.set_seed
94
+
95
+ [[autodoc]] utils.synchronize_rng_state
96
+
97
+ [[autodoc]] utils.synchronize_rng_states
98
+
99
+
100
+ ## PyTorch XLA
101
+
102
+ These include utilities that are useful while using PyTorch with XLA.
103
+
104
+ [[autodoc]] utils.install_xla
testbed/huggingface__accelerate/docs/source/quicktour.mdx ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2021 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Quick tour
14
+
15
+ Let's have a look at the 🤗 Accelerate main features and traps to avoid.
16
+
17
+ ## Main use
18
+
19
+ To use 🤗 Accelerate in your own script, you have to change four things:
20
+
21
+ 1. Import the [`Accelerator`] main class and instantiate one in an `accelerator` object:
22
+
23
+ ```python
24
+ from accelerate import Accelerator
25
+
26
+ accelerator = Accelerator()
27
+ ```
28
+
29
+ This should happen as early as possible in your training script as it will initialize everything necessary for
30
+ distributed training. You don't need to indicate the kind of environment you are in (just one machine with a GPU, one
31
+ machines with several GPUs, several machines with multiple GPUs or a TPU), the library will detect this automatically.
32
+
33
+ 2. Remove the call `.to(device)` or `.cuda()` for your model and input data. The `accelerator` object
34
+ will handle this for you and place all those objects on the right device for you. If you know what you're doing, you
35
+ can leave those `.to(device)` calls but you should use the device provided by the `accelerator` object:
36
+ `accelerator.device`.
37
+
38
+ To fully deactivate the automatic device placement, pass along `device_placement=False` when initializing your
39
+ [`Accelerator`].
40
+
41
+ <Tip warning={true}>
42
+
43
+ If you place your objects manually on the proper device, be careful to create your optimizer after putting your
44
+ model on `accelerator.device` or your training will fail on TPU.
45
+
46
+ </Tip>
47
+
48
+ 3. Pass all objects relevant to training (optimizer, model, training dataloader, learning rate scheduler) to the
49
+ [`~Accelerator.prepare`] method. This will make sure everything is ready for training.
50
+
51
+ ```python
52
+ model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
53
+ model, optimizer, train_dataloader, lr_scheduler
54
+ )
55
+ ```
56
+
57
+ In particular, your training dataloader will be sharded across all GPUs/TPU cores available so that each one sees a
58
+ different portion of the training dataset. Also, the random states of all processes will be synchronized at the
59
+ beginning of each iteration through your dataloader, to make sure the data is shuffled the same way (if you decided to
60
+ use `shuffle=True` or any kind of random sampler).
61
+
62
+ <Tip>
63
+
64
+ The actual batch size for your training will be the number of devices used multiplied by the batch size you set in
65
+ your script: for instance training on 4 GPUs with a batch size of 16 set when creating the training dataloader will
66
+ train at an actual batch size of 64.
67
+
68
+ </Tip>
69
+
70
+ Alternatively, you can use the option `split_batches=True` when creating initializing your
71
+ [`Accelerator`], in which case the batch size will always stay the same, whether your run your
72
+ script on 1, 2, 4 or 64 GPUs.
73
+
74
+ You should execute this instruction as soon as all objects for training are created, before starting your actual
75
+ training loop.
76
+
77
+ <Tip warning={true}>
78
+
79
+ You should only pass the learning rate scheduler to [`~Accelerator.prepare`] when the scheduler needs to be stepped
80
+ at each optimizer step.
81
+
82
+ </Tip>
83
+
84
+ <Tip warning={true}>
85
+
86
+ Your training dataloader may change length when going through this method: if you run on X GPUs, it will have its
87
+ length divided by X (since your actual batch size will be multiplied by X), unless you set
88
+ `split_batches=True`.
89
+
90
+ </Tip>
91
+
92
+ Any instruction using your training dataloader length (for instance if you want to log the number of total training
93
+ steps) should go after the call to [`~Accelerator.prepare`].
94
+
95
+ You can perfectly send your dataloader to [`~Accelerator.prepare`] on its own, but it's best to send the
96
+ model and optimizer to [`~Accelerator.prepare`] together.
97
+
98
+ You may or may not want to send your validation dataloader to [`~Accelerator.prepare`], depending on
99
+ whether you want to run distributed evaluation or not (see below).
100
+
101
+ 4. Replace the line `loss.backward()` by `accelerator.backward(loss)`.
102
+
103
+ And you're all set! With all these changes, your script will run on your local machine as well as on multiple GPUs or a
104
+ TPU! You can either use your favorite tool to launch the distributed training, or you can use the 🤗 Accelerate
105
+ launcher.
106
+
107
+
108
+ ## Distributed evaluation
109
+
110
+ You can perform regular evaluation in your training script, if you leave your validation dataloader out of the
111
+ [`~Accelerator.prepare`] method. In this case, you will need to put the input data on the
112
+ `accelerator.device` manually.
113
+
114
+ To perform distributed evaluation, send along your validation dataloader to the [`~Accelerator.prepare`]
115
+ method:
116
+
117
+ ```python
118
+ validation_dataloader = accelerator.prepare(validation_dataloader)
119
+ ```
120
+
121
+ As for your training dataloader, it will mean that (should you run your script on multiple devices) each device will
122
+ only see part of the evaluation data. This means you will need to group your predictions together. This is very easy to
123
+ do with the [`~Accelerator.gather_for_metrics`] method.
124
+
125
+ ```python
126
+ for inputs, targets in validation_dataloader:
127
+ predictions = model(inputs)
128
+ # Gather all predictions and targets
129
+ all_predictions, all_targets = accelerator.gather_for_metrics((predictions, targets))
130
+ # Example of use with a *Datasets.Metric*
131
+ metric.add_batch(all_predictions, all_targets)
132
+ ```
133
+
134
+ <Tip warning={true}>
135
+
136
+ Similar to the training dataloader, passing your validation dataloader through
137
+ [`~Accelerator.prepare`] may change it: if you run on X GPUs, it will have its length divided by X
138
+ (since your actual batch size will be multiplied by X), unless you set `split_batches=True`.
139
+
140
+ </Tip>
141
+
142
+ Any instruction using your training dataloader length (for instance if you need the number of total training steps
143
+ to create a learning rate scheduler) should go after the call to [`~Accelerator.prepare`].
144
+
145
+ Some data at the end of the dataset may be duplicated so the batch can be divided equally among all workers. As a result, metrics
146
+ should be calculated through the [`~Accelerator.gather_for_metrics`] method to automatically remove the duplicated data while gathering.
147
+
148
+ <Tip>
149
+
150
+ If for some reason you don't wish to have this automatically done, [`~Accelerator.gather`] can be used instead to gather
151
+ the data across all processes and this can manually be done instead.
152
+
153
+ </Tip>
154
+
155
+
156
+ <Tip warning={true}>
157
+
158
+ The [`~Accelerator.gather`] and [`~Accelerator.gather_for_metrics`] methods require the tensors to be all the same size on each process. If
159
+ you have tensors of different sizes on each process (for instance when dynamically padding to the maximum length in
160
+ a batch), you should use the [`~Accelerator.pad_across_processes`] method to pad you tensor to the
161
+ biggest size across processes.
162
+
163
+ </Tip>
164
+
165
+ ## Launching your distributed script
166
+
167
+ You can use the regular commands to launch your distributed training (like `torch.distributed.launch` for
168
+ PyTorch), they are fully compatible with 🤗 Accelerate. The only caveat here is that 🤗 Accelerate uses the environment
169
+ to determine all useful information, so `torch.distributed.launch` should be used with the flag `--use_env`.
170
+
171
+ 🤗 Accelerate also provides a CLI tool that unifies all launchers, so you only have to remember one command. To use it,
172
+ just run:
173
+
174
+ ```bash
175
+ accelerate config
176
+ ```
177
+
178
+ on your machine and reply to the questions asked. This will save a *default_config.yaml* file in your cache folder for
179
+ 🤗 Accelerate. That cache folder is (with decreasing order of priority):
180
+
181
+ - The content of your environment variable `HF_HOME` suffixed with *accelerate*.
182
+ - If it does not exist, the content of your environment variable `XDG_CACHE_HOME` suffixed with
183
+ *huggingface/accelerate*.
184
+ - If this does not exist either, the folder *~/.cache/huggingface/accelerate*
185
+
186
+ You can also specify with the flag `--config_file` the location of the file you want to save.
187
+
188
+ Once this is done, you can test everything is going well on your setup by running:
189
+
190
+ ```bash
191
+ accelerate test
192
+ ```
193
+
194
+ This will launch a short script that will test the distributed environment. If it runs fine, you are ready for the next
195
+ step!
196
+
197
+ Note that if you specified a location for the config file in the previous step, you need to pass it here as well:
198
+
199
+ ```bash
200
+ accelerate test --config_file path_to_config.yaml
201
+ ```
202
+
203
+ Now that this is done, you can run your script with the following command:
204
+
205
+ ```bash
206
+ accelerate launch path_to_script.py --args_for_the_script
207
+ ```
208
+
209
+ If you stored the config file in a non-default location, you can indicate it to the launcher like this:
210
+
211
+ ```bash
212
+ accelerate launch --config_file path_to_config.yaml path_to_script.py --args_for_the_script
213
+ ```
214
+
215
+ You can also override any of the arguments determined by your config file.
216
+ To see the complete list of parameters that you can pass in, run `accelerate launch -h`.
217
+
218
+ Check out the [Launch tutorial](basic_tutorials/launch) for more information about launching your scripts.
219
+
220
+
221
+ ## Launching training from a notebook
222
+
223
+ In Accelerate 0.3.0, a new [`notebook_launcher`] has been introduced to help you launch your training
224
+ function from a notebook. This launcher supports launching a training with TPUs on Colab or Kaggle, as well as training
225
+ on several GPUs (if the machine on which you are running your notebook has them).
226
+
227
+ Just define a function responsible for your whole training and/or evaluation in a cell of the notebook, then execute a
228
+ cell with the following code:
229
+
230
+ ```python
231
+ from accelerate import notebook_launcher
232
+
233
+ notebook_launcher(training_function)
234
+ ```
235
+
236
+ <Tip warning={true}>
237
+
238
+ Your [`Accelerator`] object should only be defined inside the training function. This is because the
239
+ initialization should be done inside the launcher only.
240
+
241
+ </Tip>
242
+
243
+ Check out the [Notebook Launcher tutorial](basic_tutorials/notebook) for more information about training on TPUs.
244
+
245
+
246
+ ## Training on TPU
247
+
248
+ If you want to launch your script on TPUs, there are a few caveats you should be aware of. Behind the scenes, the TPUs
249
+ will create a graph of all the operations happening in your training step (forward pass, backward pass and optimizer
250
+ step). This is why your first step of training will always be very long as building and compiling this graph for
251
+ optimizations takes some time.
252
+
253
+ The good news is that this compilation will be cached so the second step and all the following will be much faster. The
254
+ bad news is that it only applies if all of your steps do exactly the same operations, which implies:
255
+
256
+ - having all tensors of the same length in all your batches
257
+ - having static code (i.e., not a for loop of length that could change from step to step)
258
+
259
+ Having any of the things above change between two steps will trigger a new compilation which will, once again, take a
260
+ lot of time. In practice, that means you must take special care to have all your tensors in your inputs of the same
261
+ shape (so no dynamic padding for instance if you are in an NLP problem) and should not use layers with for loops that
262
+ have different lengths depending on the inputs (such as an LSTM) or the training will be excruciatingly slow.
263
+
264
+ To introduce special behavior in your script for TPUs you can check the `distributed_type` of your
265
+ `accelerator`:
266
+
267
+ ```python docstyle-ignore
268
+ from accelerate import DistributedType
269
+
270
+ if accelerator.distributed_type == DistributedType.TPU:
271
+ # do something of static shape
272
+ else:
273
+ # go crazy and be dynamic
274
+ ```
275
+
276
+ The [NLP example](https://github.com/huggingface/accelerate/blob/main/examples/nlp_example.py) shows an example in a
277
+ situation with dynamic padding.
278
+
279
+ One last thing to pay close attention to: if your model has tied weights (such as language models which tie the weights
280
+ of the embedding matrix with the weights of the decoder), moving this model to the TPU (either yourself or after you
281
+ passed your model to [`~Accelerator.prepare`]) will break the tying. You will need to retie the weights
282
+ after. You can find an example of this in the [run_clm_no_trainer](https://github.com/huggingface/transformers/blob/master/examples/pytorch/language-modeling/run_clm.py) script in
283
+ the Transformers repository.
284
+
285
+ Check out the [TPU tutorial](concept_guides/training_tpu) for more information about training on TPUs.
286
+
287
+
288
+ ## Other caveats
289
+
290
+ We list here all smaller issues you could have in your script conversion and how to resolve them.
291
+
292
+ ### Execute a statement only on one processes
293
+
294
+ Some of your instructions only need to run for one process on a given server: for instance a data download or a log
295
+ statement. To do this, wrap the statement in a test like this:
296
+
297
+ ```python docstyle-ignore
298
+ if accelerator.is_local_main_process:
299
+ # Is executed once per server
300
+ ```
301
+
302
+ Another example is progress bars: to avoid having multiple progress bars in your output, you should only display one on
303
+ the local main process:
304
+
305
+ ```python
306
+ from tqdm.auto import tqdm
307
+
308
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
309
+ ```
310
+
311
+ The *local* means per machine: if you are running your training on two servers with several GPUs, the instruction will
312
+ be executed once on each of those servers. If you need to execute something only once for all processes (and not per
313
+ machine) for instance, uploading the final model to the 🤗 model hub, wrap it in a test like this:
314
+
315
+ ```python docstyle-ignore
316
+ if accelerator.is_main_process:
317
+ # Is executed once only
318
+ ```
319
+
320
+ For printing statements you only want executed once per machine, you can just replace the `print` function by
321
+ `accelerator.print`.
322
+
323
+
324
+ ### Defer execution
325
+
326
+ When you run your usual script, instructions are executed in order. Using 🤗 Accelerate to deploy your script on several
327
+ GPUs at the same time introduces a complication: while each process executes all instructions in order, some may be
328
+ faster than others.
329
+
330
+ You might need to wait for all processes to have reached a certain point before executing a given instruction. For
331
+ instance, you shouldn't save a model before being sure every process is done with training. To do this, just write the
332
+ following line in your code:
333
+
334
+ ```
335
+ accelerator.wait_for_everyone()
336
+ ```
337
+
338
+ This instruction will block all the processes that arrive first until all the other processes have reached that
339
+ point (if you run your script on just one GPU or CPU, this won't do anything).
340
+
341
+
342
+ ### Saving/loading a model
343
+
344
+ Saving the model you trained might need a bit of adjustment: first you should wait for all processes to reach that
345
+ point in the script as shown above, and then, you should unwrap your model before saving it. This is because when going
346
+ through the [`~Accelerator.prepare`] method, your model may have been placed inside a bigger model,
347
+ which deals with the distributed training. This in turn means that saving your model state dictionary without taking
348
+ any precaution will take that potential extra layer into account, and you will end up with weights you can't load back
349
+ in your base model.
350
+
351
+ This is why it's recommended to *unwrap* your model first. Here is an example:
352
+
353
+ ```
354
+ accelerator.wait_for_everyone()
355
+ unwrapped_model = accelerator.unwrap_model(model)
356
+ accelerator.save(unwrapped_model.state_dict(), filename)
357
+ ```
358
+
359
+ If your script contains logic to load a checkpoint, we also recommend you load your weights in the unwrapped model
360
+ (this is only useful if you use the load function after making your model go through
361
+ [`~Accelerator.prepare`]). Here is an example:
362
+
363
+ ```
364
+ unwrapped_model = accelerator.unwrap_model(model)
365
+ unwrapped_model.load_state_dict(torch.load(filename))
366
+ ```
367
+
368
+ Note that since all the model parameters are references to tensors, this will load your weights inside `model`.
369
+
370
+ ## Saving/loading entire states
371
+
372
+ When training your model, you may want to save the current state of the model, optimizer, random generators, and potentially LR schedulers to be restored in the _same script_.
373
+ You can use [`~Accelerator.save_state`] and [`~Accelerator.load_state`] respectively to do so.
374
+
375
+ To further customize where and how states saved through [`~Accelerator.save_state`] the [`~utils.ProjectConfiguration`] class can be used. For example
376
+ if `automatic_checkpoint_naming` is enabled each saved checkpoint will be located then at `Accelerator.project_dir/checkpoints/checkpoint_{checkpoint_number}`.
377
+
378
+ If you have registered any other stateful items to be stored through [`~Accelerator.register_for_checkpointing`] they will also be saved and/or loaded.
379
+
380
+ <Tip>
381
+
382
+ Every object passed to [`~Accelerator.register_for_checkpointing`] must have a `load_state_dict` and `state_dict` function to be stored
383
+
384
+ </Tip>
385
+
386
+
387
+ ### Gradient clipping
388
+
389
+ If you are using gradient clipping in your script, you should replace the calls to
390
+ `torch.nn.utils.clip_grad_norm_` or `torch.nn.utils.clip_grad_value_` with [`~Accelerator.clip_grad_norm_`]
391
+ and [`~Accelerator.clip_grad_value_`] respectively.
392
+
393
+
394
+ ### Mixed Precision training
395
+
396
+ If you are running your training in Mixed Precision with 🤗 Accelerate, you will get the best result with your loss being
397
+ computed inside your model (like in Transformer models for instance). Every computation outside of the model will be
398
+ executed in full precision (which is generally what you want for loss computation, especially if it involves a
399
+ softmax). However you might want to put your loss computation inside the *accelerator.autocast* context manager:
400
+
401
+ ```
402
+ with accelerator.autocast():
403
+ loss = complex_loss_function(outputs, target):
404
+ ```
405
+
406
+ Another caveat with Mixed Precision training is that the gradient will skip a few updates at the beginning and
407
+ sometimes during training: because of the dynamic loss scaling strategy, there are points during training where the
408
+ gradients have overflown, and the loss scaling factor is reduced to avoid this happening again at the next step.
409
+
410
+ This means that you may update your learning rate scheduler when there was no update, which is fine in general, but may
411
+ have an impact when you have very little training data, or if the first learning rate values of your scheduler are very
412
+ important. In this case, you can skip the learning rate scheduler updates when the optimizer step was not done like
413
+ this:
414
+
415
+ ```
416
+ if not accelerator.optimizer_step_was_skipped:
417
+ lr_scheduler.step()
418
+ ```
419
+
420
+ ### Gradient Accumulation
421
+
422
+ To perform gradient accumulation use [`~Accelerator.accumulate`] and specify a `gradient_accumulation_steps`.
423
+ This will also automatically ensure the gradients are synced or unsynced when on multi-device training, check if the step should
424
+ actually be performed, and auto-scale the loss:
425
+
426
+ ```python
427
+ accelerator = Accelerator(gradient_accumulation_steps=2)
428
+ model, optimizer, training_dataloader = accelerator.prepare(model, optimizer, training_dataloader)
429
+
430
+ for input, label in training_dataloader:
431
+ with accelerator.accumulate(model):
432
+ predictions = model(input)
433
+ loss = loss_function(predictions, label)
434
+ accelerator.backward(loss)
435
+ optimizer.step()
436
+ scheduler.step()
437
+ optimizer.zero_grad()
438
+ ```
439
+
440
+ ### DeepSpeed
441
+
442
+ DeepSpeed support is experimental, so the underlying API will evolve in the near future and may have some slight
443
+ breaking changes. In particular, 🤗 Accelerate does not support DeepSpeed config you have written yourself yet, this
444
+ will be added in a next version.
445
+
446
+ <Tip warning={true}>
447
+
448
+ The [`notebook_launcher`] does not support the DeepSpeed integration yet.
449
+
450
+ </Tip>
451
+
452
+ ## Internal mechanism
453
+
454
+ Internally, the library works by first analyzing the environment in which the script is launched to determine which
455
+ kind of distributed setup is used, how many different processes there are and which one the current script is in. All
456
+ that information is stored in the [`~AcceleratorState`].
457
+
458
+ This class is initialized the first time you instantiate an [`~Accelerator`] as well as performing any
459
+ specific initialization your distributed setup needs. Its state is then uniquely shared through all instances of
460
+ [`~state.AcceleratorState`].
461
+
462
+ Then, when calling [`~Accelerator.prepare`], the library:
463
+
464
+ - wraps your model(s) in the container adapted for the distributed setup,
465
+ - wraps your optimizer(s) in a [`~optimizer.AcceleratedOptimizer`],
466
+ - creates a new version of your dataloader(s) in a [`~data_loader.DataLoaderShard`].
467
+
468
+ While the model(s) and optimizer(s) are just put in simple wrappers, the dataloader(s) are re-created. This is mostly
469
+ because PyTorch does not let the user change the `batch_sampler` of a dataloader once it's been created and the
470
+ library handles the sharding of your data between processes by changing that `batch_sampler` to yield every other
471
+ `num_processes` batches.
472
+
473
+ The [`~data_loader.DataLoaderShard`] subclasses `DataLoader` to add the following functionality:
474
+
475
+ - it synchronizes the appropriate random number generator of all processes at each new iteration, to ensure any
476
+ randomization (like shuffling) is done the exact same way across processes.
477
+ - it puts the batches on the proper device before yielding them (unless you have opted out of
478
+ `device_placement=True`).
479
+
480
+ The random number generator synchronization will by default synchronize:
481
+
482
+ - the `generator` attribute of a given sampler (like the PyTorch `RandomSampler`) for PyTorch >= 1.6
483
+ - the main random number generator in PyTorch <=1.5.1
484
+
485
+ You can choose which random number generator(s) to synchronize with the `rng_types` argument of the main
486
+ [`Accelerator`]. In PyTorch >= 1.6, it is recommended to rely on a local `generator` to avoid
487
+ setting the same seed in the main random number generator in all processes.
488
+
489
+ <Tip warning={true}>
490
+
491
+ Synchronization of the main torch (or CUDA or XLA) random number generator will affect any other potential random
492
+ artifacts you could have in your dataset (like random data augmentation) in the sense that all processes will get
493
+ the same random numbers from the torch random modules (so will apply the same random data augmentation if it's
494
+ controlled by torch).
495
+
496
+ </Tip>
497
+
498
+ <Tip>
499
+
500
+ The randomization part of your custom sampler, batch sampler or iterable dataset should be done using a local
501
+ `torch.Generator` object (in PyTorch >= 1.6), see the traditional `RandomSampler`, as an example.
502
+
503
+ </Tip>
504
+
505
+ For more details about the internals, see the [Internals page](package_reference/torch_wrappers).
testbed/huggingface__accelerate/docs/source/usage_guides/big_modeling.mdx ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Handling big models for inference
14
+
15
+ When loading a pretrained model in PyTorch, the usual workflow looks like this:
16
+
17
+ ```py
18
+ import torch
19
+
20
+ my_model = ModelClass(...)
21
+ state_dict = torch.load(checkpoint_file)
22
+ my_model.load_state_dict(state_dict)
23
+ ```
24
+
25
+ In plain English, those steps are:
26
+ 1. Create the model with randomly initialized weights
27
+ 2. Load the model weights (in a dictionary usually called a state dict) from the disk
28
+ 3. Load those weights inside the model
29
+
30
+ While this works very well for regularly sized models, this workflow has some clear limitations when we deal with a huge model: in step 1, we load a full version of the model in RAM, and spend some time randomly initializing the weights (which will be discarded in step 3). In step 2, we load another full version of the model in RAM, with the pretrained weights. If you're loading a model with 6 billions parameters, this means you will need 24GB of RAM for each copy of the model, so 48GB in total (half of it to load the model in FP16).
31
+
32
+ <Tip warning={true}>
33
+
34
+ This API is quite new and still in its experimental stage. While we strive to provide a stable API, it's possible some small parts of the public API will change in the future.
35
+
36
+ </Tip>
37
+
38
+ ## How the Process Works: A Quick Overview
39
+
40
+ <Youtube id="MWCSGj9jEAo" />
41
+
42
+ ## How the Process Works: Working with Code
43
+
44
+ ### Instantiating an empty model
45
+
46
+ The first tool 🤗 Accelerate introduces to help with big models is a context manager [`init_empty_weights`] that helps you initialize a model without using any RAM, so that step 1 can be done on models of any size. Here is how it works:
47
+
48
+ ```py
49
+ from accelerate import init_empty_weights
50
+
51
+ with init_empty_weights():
52
+ my_model = ModelClass(...)
53
+ ```
54
+
55
+ For instance:
56
+
57
+ ```py
58
+ with init_empty_weights():
59
+ model = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
60
+ ```
61
+
62
+ initializes an empty model with a bit more than 100B parameters. Behind the scenes, this relies on the meta device introduced in PyTorch 1.9. During the initialization under the context manager, each time a parameter is created, it is instantly moved on that device.
63
+
64
+ <Tip warning={true}>
65
+
66
+ You can't move a model initialized like this on CPU or another device directly, since it doesn't have any data. It's also very likely that a forward pass with that empty model will fail, as not all operations are supported on the meta device.
67
+
68
+ </Tip>
69
+
70
+ ### Sharded checkpoints
71
+
72
+ It's possible your model is so big that even a single copy won't fit in RAM. That doesn't mean it can't be loaded: if you have one or several GPUs, this is more memory available to store your model. In this case, it's better if your checkpoint is split in several smaller files that we call checkpoint shards.
73
+
74
+ 🤗 Accelerate will handle sharded checkpoints as long as you follow the following format: your checkpoint should be in a folder, with several files containing the partial state dicts, and there should be an index in the JSON format that contains a dictionary mapping parameter names to the file containing their weights. For instance we could have a folder containing:
75
+
76
+ ```bash
77
+ first_state_dict.bin
78
+ index.json
79
+ second_state_dict.bin
80
+ ```
81
+
82
+ with index.json being the following file:
83
+
84
+ ```
85
+ {
86
+ "linear1.weight": "first_state_dict.bin",
87
+ "linear1.bias": "first_state_dict.bin",
88
+ "linear2.weight": "second_state_dict.bin",
89
+ "linear2.bias": "second_state_dict.bin"
90
+ }
91
+ ```
92
+
93
+ and `first_state_dict.bin` containing the weights for `"linear1.weight"` and `"linear1.bias"`, `second_state_dict.bin` the ones for `"linear2.weight"` and `"linear2.bias"`
94
+
95
+ ### Loading weights
96
+
97
+ The second tool 🤗 Accelerate introduces is a function [`load_checkpoint_and_dispatch`], that will allow you to load a checkpoint inside your empty model. This supports full checkpoints (a single file containing the whole state dict) as well as sharded checkpoints. It will also automatically dispatch those weights across the devices you have available (GPUs, CPU RAM), so if you are loading a sharded checkpoint, the maximum RAM usage will be the size of the biggest shard.
98
+
99
+ Here is how we can use this to load the [GPT-J-6B](https://huggingface.co/EleutherAI/gpt-j-6B) model. You clone the sharded version of this model with:
100
+
101
+ ```bash
102
+ git clone https://huggingface.co/sgugger/sharded-gpt-j-6B
103
+ cd sharded-gpt-j-6B
104
+ git-lfs install
105
+ git pull
106
+ ```
107
+
108
+ then we can initialize the model with
109
+
110
+ ```py
111
+ from accelerate import init_empty_weights
112
+ from transformers import AutoConfig, AutoModelForCausalLM
113
+
114
+ checkpoint = "EleutherAI/gpt-j-6B"
115
+ config = AutoConfig.from_pretrained(checkpoint)
116
+
117
+ with init_empty_weights():
118
+ model = AutoModelForCausalLM.from_config(config)
119
+ ```
120
+
121
+ and load the checkpoint we just downloaded with:
122
+
123
+ ```py
124
+ from accelerate import load_checkpoint_and_dispatch
125
+
126
+ model = load_checkpoint_and_dispatch(
127
+ model, "sharded-gpt-j-6B", device_map="auto", no_split_module_classes=["GPTJBlock"]
128
+ )
129
+ ```
130
+
131
+ By passing `device_map="auto"`, we tell 🤗 Accelerate to determine automatically where to put each layer of the model depending on the available resources:
132
+ - first we use the maximum space available on the GPU(s)
133
+ - if we still need space, we store the remaining weights on the CPU
134
+ - if there is not enough RAM, we store the remaining weights on the hard drive as memory-mapped tensors
135
+
136
+ `no_split_module_classes=["GPTJBlock"]` indicates that the modules that are `GPTJBlock` should not be split on different devices. You should set here all blocks that include a residual connection of some kind.
137
+
138
+ You can see the `device_map` that 🤗 Accelerate picked by accessing the `hf_device_map` attribute of your model:
139
+
140
+ ```py
141
+ model.hf_device_map
142
+ ```
143
+
144
+ ```python out
145
+ {'transformer.wte': 0,
146
+ 'transformer.drop': 0,
147
+ 'transformer.h.0': 0,
148
+ 'transformer.h.1': 0,
149
+ 'transformer.h.2': 0,
150
+ 'transformer.h.3': 0,
151
+ 'transformer.h.4': 0,
152
+ 'transformer.h.5': 0,
153
+ 'transformer.h.6': 0,
154
+ 'transformer.h.7': 0,
155
+ 'transformer.h.8': 0,
156
+ 'transformer.h.9': 0,
157
+ 'transformer.h.10': 0,
158
+ 'transformer.h.11': 0,
159
+ 'transformer.h.12': 0,
160
+ 'transformer.h.13': 0,
161
+ 'transformer.h.14': 0,
162
+ 'transformer.h.15': 0,
163
+ 'transformer.h.16': 0,
164
+ 'transformer.h.17': 0,
165
+ 'transformer.h.18': 0,
166
+ 'transformer.h.19': 0,
167
+ 'transformer.h.20': 0,
168
+ 'transformer.h.21': 0,
169
+ 'transformer.h.22': 0,
170
+ 'transformer.h.23': 0,
171
+ 'transformer.h.24': 1,
172
+ 'transformer.h.25': 1,
173
+ 'transformer.h.26': 1,
174
+ 'transformer.h.27': 1,
175
+ 'transformer.ln_f': 1,
176
+ 'lm_head': 1}
177
+ ```
178
+
179
+ You can also design your `device_map` yourself, if you prefer to explicitly decide where each layer should be. In this case, the command above becomes:
180
+
181
+ ```py
182
+ model = load_checkpoint_and_dispatch(model, "sharded-gpt-j-6B", device_map=my_device_map)
183
+ ```
184
+
185
+ ### Run the model
186
+
187
+ Now that we have done this, our model lies across several devices, and maybe the hard drive. But it can still be used as a regular PyTorch model:
188
+
189
+ ```py
190
+ from transformers import AutoTokenizer
191
+
192
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
193
+ inputs = tokenizer("Hello, my name is", return_tensors="pt")
194
+ inputs = inputs.to(0)
195
+ output = model.generate(inputs["input_ids"])
196
+ tokenizer.decode(output[0].tolist())
197
+ ```
198
+
199
+ Behind the scenes, 🤗 Accelerate added hooks to the model, so that:
200
+ - at each layer, the inputs are put on the right device (so even if your model is spread across several GPUs, it works)
201
+ - for the weights offloaded on the CPU, they are put on a GPU just before the forward pass, and cleaned up just after
202
+ - for the weights offloaded on the hard drive, they are loaded in RAM then put on a GPU just before the forward pass, and cleaned up just after
203
+
204
+ This way, you model can run for inference even if it doesn't fit on one of the GPUs or the CPU RAM!
205
+
206
+ <Tip warning={true}>
207
+
208
+ This only supports inference of your model, not training. Most of the computation happens behind `torch.no_grad()` context managers to avoid spending some GPU memory with intermediate activations.
209
+
210
+ </Tip>
211
+
212
+ ### Designing a device map
213
+
214
+ You can let 🤗 Accelerate handle the device map computation by setting `device_map` to one of the supported options (`"auto"`, `"balanced"`, `"balanced_low_0"`, `"sequential"`) or create one yourself, if you want more control over where each layer should go.
215
+
216
+ <Tip>
217
+
218
+ You can derive all sizes of the model (and thus compute a `device_map`) on a model that is on the meta device.
219
+
220
+ </Tip>
221
+
222
+ All the options will produce the same result when you don't have enough GPU memory to accommodate the whole model (which is to fit everything that can on the GPU, then offload weights on the CPU or even on the disk if there is not enough RAM).
223
+
224
+ When you have more GPU memory available than the model size, here the difference between each option:
225
+ - `"auto"` and `"balanced"` evenly split the model on all available GPUs, making it possible for you to use a batch size greater than 1.
226
+ - `"balanced_low_0"` evenly splits the model on all GPUs except the first one, and only puts on GPU 0 what does not fit on the others. This option is great when you need to use GPU 0 for some processing of the outputs, like when using the `generate` function for Transformers models
227
+ - `"sequential"` will fit what it can on GPU 0, then move on GPU 1 and so forth (so won't use the last GPUs if it doesn't need to).
228
+
229
+ <Tip>
230
+
231
+ The options `"auto"` and `"balanced"` produce the same results for now, but the behavior of `"auto"` might change in the future if we find a strategy that makes more sense, while `"balanced"` will stay stable.
232
+
233
+ </Tip>
234
+
235
+ First note that you can limit the memory used on each GPU by using the `max_memory` argument (available in [`infer_auto_device_map`] and in all functions using it). When setting `max_memory`, you should pass along a dictionary containing the GPU identifiers (for instance `0`, `1` etc.) and the `"cpu"` key for the maximum RAM you want used for CPU offload. The values can either be an integer (in bytes) or a string representing a number with its unit, such as `"10GiB"` or `"10GB"`.
236
+
237
+ Here is an example where we don't want to use more than 10GiB on each of two GPUs and no more than 30GiB of CPU RAM for the model weights:
238
+
239
+ ```python
240
+ from accelerate import infer_auto_device_map
241
+
242
+ device_map = infer_auto_device_map(my_model, max_memory={0: "10GiB", 1: "10GiB", "cpu": "30GiB"})
243
+ ```
244
+
245
+ <Tip warning={true}>
246
+
247
+ When a first allocation happens in PyTorch, it loads CUDA kernels which take about 1-2GB of memory depending on the GPU. Therefore you always have less usable memory than the actual size of the GPU. To see how much memory is actually used do `torch.ones(1).cuda()` and look at the memory usage.
248
+
249
+ Therefore when you create memory maps with `max_memory` make sure to adjust the avaialble memory accordingly to avoid out-of-memory errors.
250
+
251
+ </Tip>
252
+
253
+ Additionally, if you do some additional operations with your outputs without placing them back on the CPU (for instance inside the `generate` method of Transformers) and if you placed your inputs on a GPU, that GPU will consume more memory than the others (Accelerate always place the output back to the device of the input). Therefore if you would like to optimize the maximum batch size and you have many GPUs, give the first GPU less memory. For example, with BLOOM-176B on 8x80 A100 setup the close to ideal map is:
254
+
255
+ ```python
256
+ max_memory = {0: "30GIB", 1: "46GIB", 2: "46GIB", 3: "46GIB", 4: "46GIB", 5: "46GIB", 6: "46GIB", 7: "46GIB"}
257
+ ```
258
+ as you can see we gave the remaining 7 GPUs ~50% more memory than GPU 0.
259
+
260
+ If you opt to fully design the `device_map` yourself, it should be a dictionary with keys being module names of your model and values being a valid device identifier (for instance an integer for the GPUs) or `"cpu"` for CPU offload, `"disk"` for disk offload. The keys need to cover the whole model, you can then define your device map as you wish: for instance if your model has two blocks (let's say `block1` and `block2`) which each contain three linear layers (let's say `linear1`, `linear2` and `linear3`), a valid device map can be:
261
+
262
+ ```python
263
+ device_map = {"block1": 0, "block2": 1}
264
+ ```
265
+
266
+ another one that is valid could be:
267
+
268
+ ```python
269
+ device_map = {"block1": 0, "block2.linear1": 0, "block2.linear2": 1, "block2.linear3": 1}
270
+ ```
271
+
272
+ On the other hand, this one is not valid as it does not cover every parameter of the model:
273
+
274
+ ```python
275
+ device_map = {"block1": 0, "block2.linear1": 1, "block2.linear2": 1}
276
+ ```
277
+
278
+ <Tip>
279
+
280
+ To be the most efficient, make sure your device map puts the parameters on the GPUs in a sequential manner (e.g. don't put one of the first weights on GPU 0, then weights on GPU 1 and the last weight back to GPU 0) to avoid making many transfers of data between the GPUs.
281
+
282
+ </Tip>
283
+
284
+ ## Limits and further development
285
+
286
+ We are aware of the current limitations in the API:
287
+
288
+ - While this could theoretically work on just one CPU with potential disk offload, you need at least one GPU to run this API. This will be fixed in further development.
289
+ - [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) tries to maximize GPU and CPU RAM it sees available when you execute it. While PyTorch is very good at managing GPU RAM efficiently (and giving it back when not needed), it's not entirely true with Python and CPU RAM. Therefore, an automatically computed device map might be too intense on the CPU. Move a few modules to the disk device if you get crashes due to lack of RAM.
290
+ - [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) attributes devices sequentially (to avoid moving things back and forth) so if your first layer is bigger than the size of the GPU you have, it will end up with everything on the CPU/Disk.
291
+ - [`load_checkpoint_and_dispatch`] and [`load_checkpoint_in_model`] do not perform any check on the correctness of your state dict compared to your model at the moment (this will be fixed in a future version), so you may get some weird errors if trying to load a checkpoint with mismatched or missing keys.
292
+ - The model parallelism used when your model is split on several GPUs is naive and not optimized, meaning that only one GPU works at a given time and the other sits idle.
293
+ - When weights are offloaded on the CPU/hard drive, there is no pre-fetching (yet, we will work on this for future versions) which means the weights are put on the GPU when they are needed and not before.
294
+ - Hard-drive offloading might be very slow if the hardware you run on does not have fast communication between disk and CPU (like NVMes).
testbed/huggingface__accelerate/docs/source/usage_guides/checkpoint.mdx ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # Checkpointing
14
+
15
+ When training a PyTorch model with 🤗 Accelerate, you may often want to save and continue a state of training. Doing so requires
16
+ saving and loading the model, optimizer, RNG generators, and the GradScaler. Inside 🤗 Accelerate are two convenience functions to achieve this quickly:
17
+ - Use [`~Accelerator.save_state`] for saving everything mentioned above to a folder location
18
+ - Use [`~Accelerator.load_state`] for loading everything stored from an earlier `save_state`
19
+
20
+ To further customize where and how states saved through [`~Accelerator.save_state`] the [`~utils.ProjectConfiguration`] class can be used. For example
21
+ if `automatic_checkpoint_naming` is enabled each saved checkpoint will be located then at `Accelerator.project_dir/checkpoints/checkpoint_{checkpoint_number}`.
22
+
23
+ It should be noted that the expectation is that those states come from the same training script, they should not be from two separate scripts.
24
+
25
+ - By using [`~Accelerator.register_for_checkpointing`], you can register custom objects to be automatically stored or loaded from the two prior functions,
26
+ so long as the object has a `state_dict` **and** a `load_state_dict` functionality. This could include objects such as a learning rate scheduler.
27
+
28
+ Below is a brief example using checkpointing to save and reload a state during training:
29
+
30
+ ```python
31
+ from accelerate import Accelerator
32
+ import torch
33
+
34
+ accelerator = Accelerator(project_dir="my/save/path")
35
+
36
+ my_scheduler = torch.optim.lr_scheduler.StepLR(my_optimizer, step_size=1, gamma=0.99)
37
+ my_model, my_optimizer, my_training_dataloader = accelerator.prepare(my_model, my_optimizer, my_training_dataloader)
38
+
39
+ # Register the LR scheduler
40
+ accelerator.register_for_checkpointing(my_scheduler)
41
+
42
+ # Save the starting state
43
+ accelerator.save_state()
44
+
45
+ device = accelerator.device
46
+ my_model.to(device)
47
+
48
+ # Perform training
49
+ for epoch in range(num_epochs):
50
+ for batch in my_training_dataloader:
51
+ my_optimizer.zero_grad()
52
+ inputs, targets = batch
53
+ inputs = inputs.to(device)
54
+ targets = targets.to(device)
55
+ outputs = my_model(inputs)
56
+ loss = my_loss_function(outputs, targets)
57
+ accelerator.backward(loss)
58
+ my_optimizer.step()
59
+ my_scheduler.step()
60
+
61
+ # Restore previous state
62
+ accelerator.load_state("my/save/path/checkpointing/checkpoint_0")
63
+ ```