├── .github └── workflows │ ├── main.yml │ ├── publish_docs.yml │ └── release_to_pypi.yml ├── .gitignore ├── .python-version ├── CITATION.cff ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs ├── conf.py ├── linkcode_github.py └── source │ ├── api.md │ ├── artifacts │ ├── accelerate_help.txt │ ├── argparse_cli_help.txt │ ├── deepspeed_help.txt │ ├── lightning_help.txt │ ├── torchrun.png │ ├── torchrunx.excalidraw │ ├── torchrunx.png │ ├── transformers_help.txt │ └── tyro_cli_help.txt │ ├── examples │ ├── accelerate.md │ ├── deepspeed.md │ ├── lightning.md │ └── transformers.md │ ├── how_it_works.md │ ├── index.rst │ └── usage │ ├── cli.md │ ├── general.md │ ├── logging.md │ └── slurm.md ├── pyproject.toml ├── scripts ├── build_docs.sh ├── examples │ ├── accelerate_train.py │ ├── deepspeed_train.py │ ├── lightning_train.py │ └── transformers_train.py └── generate_help_menus.sh ├── src └── torchrunx │ ├── __init__.py │ ├── __main__.py │ ├── agent.py │ ├── integrations │ ├── __init__.py │ ├── cli.py │ └── lightning.py │ ├── launcher.py │ ├── py.typed │ ├── utils │ ├── __init__.py │ ├── comm.py │ ├── environment.py │ ├── errors.py │ ├── log_handling.py │ └── log_streaming.py │ └── worker.py ├── tests ├── __init__.py ├── test_ci.py ├── test_func.py ├── test_submitit.py └── test_train_gpu.py └── uv.lock /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: main 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: 8 | - main 9 | 10 | jobs: 11 | 12 | checks: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: astral-sh/setup-uv@v5 17 | with: 18 | version: "0.5.29" 19 | enable-cache: true 20 | - run: uv lock --check 21 | - run: uv sync 22 | - run: uv run --frozen ruff check 23 | if: success() || failure() 24 | - run: uv run --frozen ruff format --check 25 | if: success() || failure() 26 | - run: uv run --frozen pyright 27 | if: success() || failure() 28 | 29 | build-docs: 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: actions/checkout@v4 33 | - uses: astral-sh/setup-uv@v5 34 | with: 35 | version: "0.5.29" 36 | - run: source ./scripts/build_docs.sh 37 | - uses: actions/upload-artifact@v4 38 | with: 39 | name: docs-html-build 40 | path: docs/_build/html 41 | retention-days: 14 42 | 43 | ## 44 | 45 | get-python-pytorch-versions: 46 | runs-on: ubuntu-latest 47 | outputs: 48 | versions: ${{ steps.get-versions.outputs.versions }} 49 | steps: 50 | - name: "Get (Python, PyTorch) versions" 51 | id: get-versions 52 | run: | 53 | MIN_PYTHON_VERSION=3.9 54 | MIN_PYTORCH_VERSION=2.0 55 | 56 | # Get PyTorch versions from PyPI 57 | pytorch_versions=$( 58 | curl -s https://pypi.org/pypi/torch/json | jq -r '.releases | keys[]' | 59 | # strip "patch" from versions 60 | grep -E '\.[0]+$' | sort -V | sed 's/\.0$//' 61 | ) 62 | 63 | # For each PyTorch version, get Python versions that have builds 64 | # Generate JSON list of "python,pytorch" versions 65 | 66 | version_matrix=() 67 | for pytorch_version in $pytorch_versions; do 68 | # Skip if PyTorch version less than minium 69 | if [[ "$(printf '%s\n' "$pytorch_version" "$MIN_PYTORCH_VERSION" | sort -V | head -n 1)" != "$MIN_PYTORCH_VERSION" ]]; then continue; fi 70 | 71 | python_versions=$( 72 | curl -s "https://pypi.org/pypi/torch/$pytorch_version/json" | 73 | jq -r '.urls[].filename | select(test("manylinux1_x86_64")) | capture("(?cp[0-9]+)-") | .cp | 74 | sub("cp(?[0-9])(?[0-9]+)"; "\(.major).\(.minor)")' 75 | ) 76 | 77 | for python_version in $python_versions; do 78 | # Skip if Python version less than minium 79 | if [[ "$(printf '%s\n' "$python_version" "$MIN_PYTHON_VERSION" | sort -V | head -n 1)" != "$MIN_PYTHON_VERSION" ]]; then continue; fi 80 | 81 | version_matrix+=($python_version,$pytorch_version) 82 | done 83 | done 84 | version_matrix=$(printf '%s\n' "${version_matrix[@]}" | jq -R . | jq -s -c .) 85 | 86 | # Write to outputs 87 | echo "versions=$version_matrix" >> $GITHUB_OUTPUT 88 | 89 | test: 90 | runs-on: ubuntu-latest 91 | needs: get-python-pytorch-versions 92 | strategy: 93 | fail-fast: false 94 | matrix: 95 | versions: ${{fromJson(needs.get-python-pytorch-versions.outputs.versions)}} 96 | steps: 97 | - uses: actions/checkout@v4 98 | - uses: astral-sh/setup-uv@v5 99 | with: 100 | version: "0.5.29" 101 | - run: | 102 | IFS=',' read -r python_version pytorch_version <<< ${{ matrix.versions }} 103 | echo "PYTHON_VERSION=$python_version" >> $GITHUB_ENV 104 | echo "PYTORCH_VERSION=$pytorch_version" >> $GITHUB_ENV 105 | if [[ "$pytorch_version" =~ ^2\.(0|1|2)$ ]]; then 106 | echo "NUMPY_VERSION=--with \"numpy<2\"" >> $GITHUB_ENV 107 | fi 108 | - run: uv run --python ${{ env.PYTHON_VERSION }} --with torch~=${{ env.PYTORCH_VERSION }} ${{ env.NUMPY_VERSION }} pytest --verbose tests/test_ci.py 109 | -------------------------------------------------------------------------------- /.github/workflows/publish_docs.yml: -------------------------------------------------------------------------------- 1 | name: publish_docs 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | 10 | publish-docs: 11 | runs-on: ubuntu-latest 12 | permissions: 13 | pages: write 14 | id-token: write 15 | environment: 16 | name: github-pages 17 | url: ${{ steps.deployment.outputs.page_url }} 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: astral-sh/setup-uv@v5 21 | with: 22 | version: "0.5.29" 23 | - run: source ./scripts/build_docs.sh 24 | - uses: actions/configure-pages@v5 25 | - uses: actions/upload-pages-artifact@v3 26 | with: 27 | path: docs/_build/html 28 | - id: deployment 29 | uses: actions/deploy-pages@v4 30 | -------------------------------------------------------------------------------- /.github/workflows/release_to_pypi.yml: -------------------------------------------------------------------------------- 1 | name: release_to_pypi 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | release-to-pypi: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | id-token: write 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: astral-sh/setup-uv@v5 15 | with: 16 | version: "0.5.29" 17 | - run: uv build 18 | - run: uv publish 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | docs/source/README.md 2 | docs/source/contributing.md 3 | docs/source/examples/scripts/ 4 | 5 | torchrunx_logs/ 6 | .ruff_cache/ 7 | .vscode/ 8 | 9 | # Byte-compiled / optimized / DLL files 10 | __pycache__/ 11 | *.py[cod] 12 | *$py.class 13 | 14 | # C extensions 15 | *.so 16 | 17 | # Distribution / packaging 18 | .Python 19 | build/ 20 | develop-eggs/ 21 | dist/ 22 | downloads/ 23 | eggs/ 24 | .eggs/ 25 | lib/ 26 | lib64/ 27 | parts/ 28 | sdist/ 29 | var/ 30 | wheels/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | cover/ 61 | 62 | # Translations 63 | *.mo 64 | *.pot 65 | 66 | # Django stuff: 67 | *.log 68 | local_settings.py 69 | db.sqlite3 70 | db.sqlite3-journal 71 | 72 | # Flask stuff: 73 | instance/ 74 | .webassets-cache 75 | 76 | # Scrapy stuff: 77 | .scrapy 78 | 79 | # Sphinx documentation 80 | docs/_build/ 81 | 82 | # PyBuilder 83 | .pybuilder/ 84 | target/ 85 | 86 | # Jupyter Notebook 87 | .ipynb_checkpoints 88 | 89 | # IPython 90 | profile_default/ 91 | ipython_config.py 92 | 93 | # pyenv 94 | # For a library or package, you might want to ignore these files since the code is 95 | # intended to run in multiple environments; otherwise, check them in: 96 | # .python-version 97 | 98 | # pipenv 99 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 100 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 101 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 102 | # install all needed dependencies. 103 | #Pipfile.lock 104 | 105 | # poetry 106 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 107 | # This is especially recommended for binary packages to ensure reproducibility, and is more 108 | # commonly ignored for libraries. 109 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 110 | #poetry.lock 111 | 112 | # pdm 113 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 114 | #pdm.lock 115 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 116 | # in version control. 117 | # https://pdm.fming.dev/#use-with-ide 118 | .pdm.toml 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.9.20 2 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | title: torchrunx 3 | type: software 4 | authors: 5 | - given-names: Apoorv 6 | family-names: Khandelwal 7 | email: mail@apoorvkh.com 8 | - given-names: Peter 9 | family-names: Curtin 10 | email: peter_curtin@brown.edu 11 | repository-code: 'https://github.com/apoorvkh/torchrunx' 12 | url: 'https://torchrun.xyz' 13 | license: GPL-3.0 14 | year: 2025 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We use the [`uv`](https://github.com/astral-sh/uv) package manager. Simply [install `uv`](https://github.com/astral-sh/uv#installation) and run `uv sync` in this repository to build the environment. Run `source .venv/bin/activate` to activate the environment. 4 | 5 | We use `ruff check` for linting, `ruff format` for formatting, `pyright` for static type checking, and `pytest` for testing. We expect all such checks to pass before merging changes to the main branch. We build wheels with `uv build` and upload to [PyPI](https://pypi.org/project/torchrunx) with `uv publish`. Our CI pipelines are powered by Github Actions. 6 | 7 | ## Pull Requests 8 | 9 | Make a pull request with your changes on Github and we'll try to look at it soon! If addressing a specific issue, mention it in the PR, and offer a short explanation of your fix. If adding a new feature, explain why it's meaningful and belongs in **torchrunx**. 10 | 11 | ## Testing 12 | 13 | `tests/` contains `pytest`-style tests for validating that code changes do not break the core functionality of our library. 14 | 15 | At the moment, we run `pytest tests/test_ci.py` (i.e. simple single-node CPU-only tests) in our Github Actions CI pipeline (`.github/workflows/release.yml`). One can manually run our more involved tests (on GPUs, on multiple machines from SLURM) on their own hardware. 16 | 17 | ## Documentation 18 | 19 | Our documentation is hosted on Github Pages and is updated with every package release. We build our documentation with [Sphinx](https://www.sphinx-doc.org): `source scripts/build_docs.sh`. The documentation will then be generated at `docs/_build/html` (and can be rendered with `python -m http.server --directory docs/_build/html`). 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # torchrunx 🔥 2 | 3 | [![Python Version](https://img.shields.io/python/required-version-toml?tomlFilePath=https%3A%2F%2Fraw.githubusercontent.com%2Fapoorvkh%2Ftorchrunx%2Fmain%2Fpyproject.toml)](https://github.com/apoorvkh/torchrunx/blob/main/pyproject.toml) 4 | [![PyTorch Version](https://img.shields.io/badge/torch-%3E%3D2.0-orange)](https://github.com/pytorch/pytorch) 5 | [![PyPI - Version](https://img.shields.io/pypi/v/torchrunx)](https://pypi.org/project/torchrunx/) 6 | [![Documentation](https://img.shields.io/badge/Documentation-blue)](https://torchrun.xyz) 7 | ![Tests](https://img.shields.io/github/actions/workflow/status/apoorvkh/torchrunx/.github%2Fworkflows%2Fmain.yml) 8 | [![GitHub License](https://img.shields.io/github/license/apoorvkh/torchrunx)](https://github.com/apoorvkh/torchrunx/blob/main/LICENSE) 9 | 10 | By [Apoorv Khandelwal](https://apoorvkh.com) and [Peter Curtin](https://github.com/pmcurtin) 11 | 12 | **The easiest way to run PyTorch on multiple GPUs or machines.** 13 | 14 | --- 15 | 16 | **`torchrunx`** is a *functional* utility for distributing PyTorch code across devices. This is a [more convenient, robust, and featureful](#torchrunx-uniquely-offers) alternative to CLI-based launchers, like `torchrun`, `accelerate launch`, and `deepspeed`. 17 | 18 | It enables complex workflows within a single script and has useful features even if only using 1 GPU. 19 | 20 | ```bash 21 | pip install torchrunx 22 | ``` 23 | 24 | Requires: Linux. If using multiple machines: SSH & shared filesystem. 25 | 26 | --- 27 | 28 |

Example: simple training loop

29 | 30 | Suppose we have some distributed training function (which needs to run on every GPU): 31 | 32 | ```python 33 | def distributed_training(model: nn.Module, num_steps: int) -> nn.Module: ... 34 | ``` 35 | 36 |
37 | Implementation of distributed_training (click to expand) 38 | 39 | ```python 40 | from __future__ import annotations 41 | import os 42 | import torch 43 | import torch.nn as nn 44 | 45 | def distributed_training(model: nn.Module, num_steps: int = 10) -> nn.Module | None: 46 | rank = int(os.environ['RANK']) 47 | local_rank = int(os.environ['LOCAL_RANK']) 48 | 49 | model.to(local_rank) 50 | ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=[local_rank]) 51 | optimizer = torch.optim.AdamW(ddp_model.parameters()) 52 | 53 | for step in range(num_steps): 54 | optimizer.zero_grad() 55 | 56 | inputs = torch.randn(5, 10).to(local_rank) 57 | labels = torch.randn(5, 10).to(local_rank) 58 | outputs = ddp_model(inputs) 59 | 60 | torch.nn.functional.mse_loss(outputs, labels).backward() 61 | optimizer.step() 62 | 63 | if rank == 0: 64 | return model.cpu() 65 | ``` 66 | 67 |
68 | 69 | We can distribute and run this function (e.g. on 2 machines x 2 GPUs) using **`torchrunx`**! 70 | 71 | ```python 72 | import logging 73 | import torchrunx 74 | 75 | logging.basicConfig(level=logging.INFO) 76 | 77 | launcher = torchrunx.Launcher( 78 | hostnames = ["localhost", "second_machine"], # or IP addresses 79 | workers_per_host = "gpu" # default, or just: 2 80 | ) 81 | 82 | results = launcher.run( 83 | distributed_training, 84 | model = nn.Linear(10, 10), 85 | num_steps = 10 86 | ) 87 | ``` 88 | 89 | Once completed, you can retrieve the results and process them as you wish. 90 | 91 | ```python 92 | trained_model: nn.Module = results.rank(0) 93 | # or: results.index(hostname="localhost", local_rank=0) 94 | 95 | # and continue your script 96 | torch.save(trained_model.state_dict(), "outputs/model.pth") 97 | ``` 98 | 99 | **See more examples where we fine-tune LLMs using:** 100 | - [Transformers](https://torchrun.xyz/examples/transformers.html) 101 | - [DeepSpeed](https://torchrun.xyz/examples/deepspeed.html) 102 | - [PyTorch Lightning](https://torchrun.xyz/examples/lightning.html) 103 | - [Accelerate](https://torchrun.xyz/examples/accelerate.html) 104 | 105 | **Refer to our [API](https://torchrun.xyz/api.html) and [Usage](https://torchrun.xyz/usage/general.html) for many more capabilities!** 106 | 107 | --- 108 | 109 | ## `torchrunx` uniquely offers 110 | 111 | 1. **An automatic launcher that "just works" for everyone** 🚀 112 | 113 | > `torchrunx` is an SSH-based, pure-Python library that is universally easy to install.
114 | > No system-specific dependencies and orchestration for *automatic* multi-node distribution. 115 | 116 | 2. **Conventional CLI commands** 🖥️ 117 | 118 | > Run familiar commands, like `python my_script.py ...`, and customize arguments as you wish. 119 | > 120 | > Other launchers override `python` in a cumbersome way: e.g. `torchrun --nproc_per_node=2 --nnodes=2 --node_rank=0 --master_addr=100.43.331.111 --master_port=1234 my_script.py ...`. 121 | 122 | 3. **Support for more complex workflows in a single script** 🎛️ 123 | 124 | > Your workflow may have steps that are complex (e.g. pre-train, fine-tune, test) or may different parallelizations (e.g. training on 8 GPUs, testing on 1 GPU). In these cases, CLI-based launchers require each step to live in its own script. Our library treats these steps in a modular way, so they can cleanly fit together in a single script! 125 | > 126 | > 127 | > We clean memory leaks as we go, so previous steps won't crash or adversely affect future steps. 128 | 129 | 4. **Better handling of system failures. No more zombies!** 🧟 130 | 131 | > With `torchrun`, your "work" is inherently coupled to your main Python process. If the system kills one of your workers (e.g. due to RAM OOM or segmentation faults), there is no way to fail gracefully in Python. Your processes might hang for 10 minutes (the NCCL timeout) or become perpetual zombies. 132 | > 133 | > 134 | > `torchrunx` decouples "launcher" and "worker" processes. If the system kills a worker, our launcher immediately raises a `WorkerFailure` exception, which users can handle as they wish. We always clean up all nodes, so no more zombies! 135 | 136 | 5. **Bonus features** 🎁 137 | 138 | > - Return objects from distributed functions. 139 | > - [Automatic detection of SLURM environments.](https://torchrun.xyz/usage/slurm.html) 140 | > - Start multi-node training from Python notebooks! 141 | > - Our library is fully typed! 142 | > - Custom, fine-grained handling of [logging](https://torchrun.xyz/usage/logging.html), [environment variables](https://torchrun.xyz/usage/general.html#environment-variables), and [exception propagation](https://torchrun.xyz/usage/general.html#exceptions). We have nice defaults too: no more interleaved logs and irrelevant exceptions! 143 | 144 | **On our [roadmap](https://github.com/apoorvkh/torchrunx/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement): higher-order parallelism, support for debuggers, and more!** 145 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | """Configuration file for the Sphinx documentation builder.""" 2 | from glob import glob 3 | import os 4 | import re 5 | import shutil 6 | 7 | shutil.copyfile("../README.md", "source/README.md") 8 | readme_f_str = open("source/README.md", "r").read() 9 | readme_f_str = readme_f_str.replace("", '

').replace("", "

") 10 | readme_f_str = re.sub(r"https://torchrun\.xyz/(.+?)\.html", r"./\1.md", readme_f_str) 11 | open("source/README.md", "w").write(readme_f_str) 12 | 13 | shutil.copyfile("../CONTRIBUTING.md", "source/contributing.md") 14 | 15 | os.makedirs("source/examples/scripts", exist_ok=True) 16 | [shutil.copy(f, "source/examples/scripts/") for f in glob("../scripts/examples/*.py")] 17 | html_extra_path = list(glob("source/examples/scripts/*.py")) 18 | 19 | project = "torchrunx" 20 | copyright = 'Apoorv Khandelwal & Peter Curtin' 21 | github_username = "apoorvkh" 22 | github_repository = "torchrunx" 23 | html_theme = "furo" 24 | language = "en" 25 | 26 | extensions = [ 27 | "sphinx.ext.autodoc", 28 | "myst_parser", # support markdown 29 | "sphinx.ext.intersphinx", # link to external docs 30 | "sphinx.ext.napoleon", # for google style docstrings 31 | "sphinx.ext.linkcode", # link to github source 32 | # sidebar 33 | "sphinx_toolbox.sidebar_links", 34 | "sphinx_toolbox.github", 35 | ] 36 | 37 | maximum_signature_line_length = 90 38 | autodoc_member_order = "bysource" 39 | 40 | intersphinx_mapping = { 41 | 'python': ('https://docs.python.org/3.9', None), 42 | } 43 | 44 | from docs.linkcode_github import generate_linkcode_resolve_fn 45 | linkcode_resolve = generate_linkcode_resolve_fn(project, github_username, github_repository) 46 | -------------------------------------------------------------------------------- /docs/linkcode_github.py: -------------------------------------------------------------------------------- 1 | ## sphinx.ext.linkcode configuration 2 | # Link code to Github source 3 | # From: https://github.com/scikit-learn/scikit-learn/blob/main/doc/sphinxext/github_link.py 4 | 5 | import inspect 6 | import os 7 | import subprocess 8 | import sys 9 | from operator import attrgetter 10 | 11 | 12 | def generate_linkcode_resolve_fn(package, github_username, github_repository): 13 | 14 | try: 15 | revision = ( 16 | subprocess.check_output("git rev-parse --short HEAD".split()).strip().decode("utf-8") 17 | ) 18 | except (subprocess.CalledProcessError, OSError): 19 | print("Failed to execute git to get revision") 20 | revision = None 21 | 22 | url_fmt = ( 23 | f"https://github.com/{github_username}/{github_repository}/" 24 | "blob/{revision}/src/{package}/{path}#L{lineno}" 25 | ) 26 | 27 | def linkcode_resolve(domain, info): 28 | if revision is None: 29 | return 30 | if domain not in ("py", "pyx"): 31 | return 32 | if not info.get("module") or not info.get("fullname"): 33 | return 34 | 35 | class_name = info["fullname"].split(".")[0] 36 | module = __import__(info["module"], fromlist=[class_name]) 37 | obj = attrgetter(info["fullname"])(module) 38 | 39 | # Unwrap the object to get the correct source 40 | # file in case that is wrapped by a decorator 41 | obj = inspect.unwrap(obj) 42 | 43 | try: 44 | fn = inspect.getsourcefile(obj) 45 | except Exception: 46 | fn = None 47 | if not fn: 48 | try: 49 | fn = inspect.getsourcefile(sys.modules[obj.__module__]) 50 | except Exception: 51 | fn = None 52 | if not fn: 53 | return 54 | 55 | fn = os.path.relpath(fn, start=os.path.dirname(__import__(package).__file__)) 56 | try: 57 | lineno = inspect.getsourcelines(obj)[1] 58 | except Exception: 59 | lineno = "" 60 | return url_fmt.format(revision=revision, package=package, path=fn, lineno=lineno) 61 | 62 | return linkcode_resolve 63 | -------------------------------------------------------------------------------- /docs/source/api.md: -------------------------------------------------------------------------------- 1 | # API 2 | 3 | ```{eval-rst} 4 | .. automodule:: torchrunx 5 | :members: 6 | ``` 7 | -------------------------------------------------------------------------------- /docs/source/artifacts/accelerate_help.txt: -------------------------------------------------------------------------------- 1 | usage: accelerate_train.py [-h] [OPTIONS] 2 | 3 | ╭─ options ──────────────────────────────────────────────────────────────────╮ 4 | │ -h, --help │ 5 | │ show this help message and exit │ 6 | │ --batch-size INT │ 7 | │ (required) │ 8 | │ --output-dir PATH │ 9 | │ (required) │ 10 | ╰────────────────────────────────────────────────────────────────────────────╯ 11 | ╭─ launcher options ─────────────────────────────────────────────────────────╮ 12 | │ For configuring the function launch environment. │ 13 | │ ────────────────────────────────────────────────────────────────────────── │ 14 | │ --launcher.hostnames {[STR [STR ...]]}|{auto,slurm} │ 15 | │ Nodes to launch the function on. By default, infer from SLURM, else │ 16 | │ ``["localhost"]``. (default: auto) │ 17 | │ --launcher.workers-per-host INT|{[INT [INT ...]]}|{cpu,gpu} │ 18 | │ Number of processes to run per node. By default, number of GPUs per │ 19 | │ host. (default: gpu) │ 20 | │ --launcher.ssh-config-file {None}|STR|PATHLIKE │ 21 | │ For connecting to nodes. By default, ``"~/.ssh/config"`` or │ 22 | │ ``"/etc/ssh/ssh_config"``. (default: None) │ 23 | │ --launcher.backend {None,nccl,gloo,mpi,ucc} │ 24 | │ `Backend │ 25 | │ 8 |

python accelerate_train.py --help

(expand)
9 | 10 | ```{eval-rst} 11 | .. literalinclude:: ../artifacts/accelerate_help.txt 12 | ``` 13 | 14 | 15 | ## Training GPT-2 on WikiText in One Line 16 | 17 | The following command installs dependencies and runs our script (for example, with `GPT-2` on `WikiText`). For multi-node training (+ if not using SLURM), you should also pass e.g. `--launcher.hostnames node1 node2`. 18 | 19 | Pre-requisite: [uv](https://docs.astral.sh/uv) 20 | 21 | ```bash 22 | uv run --python "3.12" https://torchrun.xyz/accelerate_train.py \ 23 | --batch-size 8 --output-dir output \ 24 | --model.name gpt2 \ 25 | --dataset.path "Salesforce/wikitext" --dataset.name "wikitext-2-v1" --dataset.split "train" --dataset.num-samples 80 26 | ``` 27 | 28 | ## Script 29 | 30 | ```{eval-rst} 31 | .. literalinclude:: ./scripts/accelerate_train.py 32 | :start-after: # [docs:start-after] 33 | ``` 34 | -------------------------------------------------------------------------------- /docs/source/examples/deepspeed.md: -------------------------------------------------------------------------------- 1 | # DeepSpeed 2 | 3 | Here's an example script that uses `torchrunx` with [DeepSpeed](https://www.deepspeed.ai) to fine-tune any causal language model (from `transformers`) on any text dataset (from `datasets`) with any number of GPUs or nodes. 4 | 5 | [https://torchrun.xyz/deepspeed_train.py](https://raw.githubusercontent.com/apoorvkh/torchrunx/refs/heads/main/scripts/examples/deepspeed_train.py) 6 | 7 |
8 |

python deepspeed_train.py --help

(expand)
9 | 10 | ```{eval-rst} 11 | .. literalinclude:: ../artifacts/deepspeed_help.txt 12 | ``` 13 |
14 | 15 | ## Training GPT-2 on WikiText 16 | 17 | Deepspeed requires additional (non-Python) dependencies. Use the following commands to set up a project. [source: [Apoorv's Blog — Managing Project Dependencies](https://blog.apoorvkh.com/posts/project-dependencies.html)] 18 | 19 | Pre-requisite: [pixi](https://pixi.sh) 20 | 21 | ```bash 22 | pixi init my-project --format pyproject 23 | cd my-project 24 | 25 | # Install dependencies 26 | pixi project channel add "conda-forge" "nvidia/label/cuda-12.4.0" 27 | pixi add "python=3.12.7" "cuda=12.4.0" "gcc=11.4.0" "gxx=11.4.0" 28 | pixi add --pypi "torch==2.5.1" "deepspeed" "datasets" "tensorboard" "torch" "torchrunx" "transformers" "tyro" 29 | 30 | cat < .env 31 | export PYTHONNOUSERSITE="1" 32 | export LIBRARY_PATH="\$CONDA_PREFIX/lib" 33 | export LD_LIBRARY_PATH="\$CONDA_PREFIX/lib" 34 | export CUDA_HOME="\$CONDA_PREFIX" 35 | EOF 36 | 37 | # Activate environment 38 | pixi shell 39 | source .env 40 | ``` 41 | 42 | Download [deepspeed_train.py](https://raw.githubusercontent.com/apoorvkh/torchrunx/refs/heads/main/docs/source/examples/scripts/deepspeed_train.py) and create `deepspeed_config.json` with: 43 | 44 | ```json 45 | { 46 | "train_batch_size": 8, 47 | "gradient_accumulation_steps": 1, 48 | "optimizer": { 49 | "type": "Adam", 50 | "params": { "lr": 0.00015 } 51 | }, 52 | "fp16": { "enabled": true }, 53 | "zero_optimization": true, 54 | "tensorboard": { 55 | "enabled": true, 56 | "output_path": "output/tensorboard/", 57 | "job_name": "gpt2_wikitext" 58 | } 59 | } 60 | ``` 61 | 62 | ```bash 63 | python deepspeed_train.py --model-name gpt2 --deepspeed-config deepspeed_config.json --checkpoint-dir output \ 64 | --dataset.path "Salesforce/wikitext" --dataset.name "wikitext-2-v1" --dataset.split "train" --dataset.num-samples 80 65 | ``` 66 | 67 | For multi-node training (+ if not using SLURM), you should also pass e.g. `--launcher.hostnames node1 node2`. 68 | 69 | You can visualize the logs with: 70 | 71 | ```bash 72 | tensorboard --logdir output/tensorboard/gpt2_wikitext 73 | ``` 74 | 75 | ## Script 76 | 77 | ```{eval-rst} 78 | .. literalinclude:: ./scripts/deepspeed_train.py 79 | ``` 80 | -------------------------------------------------------------------------------- /docs/source/examples/lightning.md: -------------------------------------------------------------------------------- 1 | # PyTorch Lightning 2 | 3 | Here's an example script that uses `torchrunx` with [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/) to fine-tune any causal language model (from `transformers`) on any text dataset (from `datasets`) with any number of GPUs or nodes. 4 | 5 | [https://torchrun.xyz/lightning_train.py](https://raw.githubusercontent.com/apoorvkh/torchrunx/refs/heads/main/scripts/examples/lightning_train.py) 6 | 7 |
8 |

python lightning_train.py --help

(expand)
9 | 10 | ```{eval-rst} 11 | .. literalinclude:: ../artifacts/lightning_help.txt 12 | ``` 13 |
14 | 15 | ## Training GPT-2 on WikiText in One Line 16 | 17 | The following command runs our script end-to-end: installing all dependencies, downloading model and data, training, etc. 18 | 19 | Pre-requisite: [uv](https://docs.astral.sh/uv) 20 | 21 | ```bash 22 | uv run --python "3.12" https://torchrun.xyz/lightning_train.py \ 23 | --model.name gpt2 \ 24 | --dataset.path "Salesforce/wikitext" --dataset.name "wikitext-2-v1" --dataset.split "train" --dataset.num-samples 80 25 | ``` 26 | 27 | For multi-node training (+ if not using SLURM), you should also pass e.g. `--launcher.hostnames node1 node2`. 28 | 29 | ## Script 30 | 31 | ```{eval-rst} 32 | .. literalinclude:: ./scripts/lightning_train.py 33 | :start-after: # [docs:start-after] 34 | ``` 35 | -------------------------------------------------------------------------------- /docs/source/examples/transformers.md: -------------------------------------------------------------------------------- 1 | # Transformers 2 | 3 | Here's an example script that uses `torchrunx` with [`transformers.Trainer`](https://huggingface.co/docs/transformers/en/main_classes/trainer) to fine-tune any causal language model (from `transformers`) on any text dataset (from `datasets`) with any number of GPUs or nodes. 4 | 5 | [https://torchrun.xyz/transformers_train.py](https://raw.githubusercontent.com/apoorvkh/torchrunx/refs/heads/main/scripts/examples/transformers_train.py) 6 | 7 |
8 |

python transformers_train.py --help

(expand)
9 | 10 | ```{eval-rst} 11 | .. literalinclude:: ../artifacts/transformers_help.txt 12 | ``` 13 |
14 | 15 | ## Training GPT-2 on WikiText in One Line 16 | 17 | The following command runs our script end-to-end: installing all dependencies, downloading model and data, training, logging to TensorBoard, etc. For multi-node training (+ if not using SLURM), you should also pass e.g. `--launcher.hostnames node1 node2`. 18 | 19 | Pre-requisite: [uv](https://docs.astral.sh/uv) 20 | 21 | ```bash 22 | uv run --python "3.12" https://torchrun.xyz/transformers_train.py \ 23 | --model.name gpt2 \ 24 | --dataset.path "Salesforce/wikitext" --dataset.name "wikitext-2-v1" --dataset.split "train" --dataset.num-samples 80 \ 25 | --trainer.output-dir output --trainer.per-device-train-batch-size 4 --trainer.report-to tensorboard 26 | ``` 27 | 28 | You can visualize the logs with: 29 | 30 | ```bash 31 | uv run --with tensorboard tensorboard --logdir output/runs 32 | ``` 33 | 34 | ## Script 35 | 36 | ```{eval-rst} 37 | .. literalinclude:: ./scripts/transformers_train.py 38 | :start-after: # [docs:start-after] 39 | ``` 40 | -------------------------------------------------------------------------------- /docs/source/how_it_works.md: -------------------------------------------------------------------------------- 1 | # How It Works 2 | 3 | Suppose you want to run a script (`train.py`) on `N` machines (or "nodes") with `M` GPUs each. 4 | 5 | You'll need to start a new process for each GPU. Each process will execute your script in parallel and select its GPU based on the process rank. Your script will also form a [distributed group](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) so the processes may communicate with each other (e.g. passing tensors). 6 | 7 | ## `torchrun` 8 | 9 | Normally, you'd do this by running the `torchrun --node-rank {i} ... train.py ...` command on every machine. In short, you'll end up with a topology like: 10 | 11 | ![torchrun diagram](./artifacts/torchrun.png) 12 | 13 | As a side effect of this structure, every process will run until (1) script completion or (2) another process stops communicating (e.g. if killed by the system for abnormal reasons). The status of other processes is not actively communicated: so if some process is indeed killed, it would take 10 minutes (by default) for the remaining processes to time-out. Also, since this approach parallelizes the entire script, we can't catch and handle these system-level issues as exceptions. 14 | 15 | ## `torchrunx` 🔥 16 | 17 | `torchrunx` offers a functional interface, with a launcher–worker topology, instead. 18 | 19 | ![torchrunx diagram](./artifacts/torchrunx.png) 20 | 21 | {func}`torchrunx.Launcher.run` runs in the current, *launcher* process. It uses SSH to start an *agent* process on every node (specified in `hostnames`), which in turn spawn `M` *worker* processes. The workers form a distributed process group and each executes `func(*args, **kwargs)` in parallel. Once all workers are finished, all of their returned values are propagated to the initial launcher process. Our agents constantly communicate (over their own GLOO-backend distributed group), so any agent or worker failures are immediately propagated, and all launched processes are terminated. Worker exceptions and system failures are propagated to and raised by {func}`torchrunx.Launcher.run`. 22 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ./README.md 2 | :parser: myst_parser.sphinx_ 3 | 4 | .. toctree:: 5 | :hidden: 6 | 7 | api 8 | how_it_works 9 | contributing 10 | 11 | .. toctree:: 12 | :caption: Usage 13 | :hidden: 14 | 15 | ./usage/general.md 16 | ./usage/cli.md 17 | ./usage/logging.md 18 | ./usage/slurm.md 19 | 20 | .. toctree:: 21 | :caption: Examples 22 | :hidden: 23 | 24 | ./examples/transformers.md 25 | ./examples/deepspeed.md 26 | ./examples/lightning.md 27 | ./examples/accelerate.md 28 | 29 | .. sidebar-links:: 30 | :github: 31 | :pypi: torchrunx 32 | -------------------------------------------------------------------------------- /docs/source/usage/cli.md: -------------------------------------------------------------------------------- 1 | # From the CLI 2 | 3 | ## With `argparse` 4 | 5 | We provide some utilities to extend an {obj}`argparse.ArgumentParser` with arguments for building a {obj}`torchrunx.Launcher`. 6 | 7 | ```python 8 | from argparse import ArgumentParser 9 | from torchrunx.integrations.parsing import add_torchrunx_argument_group, launcher_from_args 10 | 11 | if __name__ == '__main__': 12 | parser = ArgumentParser() 13 | add_torchrunx_argument_group(parser) 14 | args = parser.parse_args() 15 | 16 | launcher = launcher_from_args(args) 17 | launcher.run(...) 18 | ``` 19 | 20 | `python ... --help` then results in: 21 | 22 | ```{eval-rst} 23 | .. literalinclude:: ../artifacts/argparse_cli_help.txt 24 | ``` 25 | 26 | ## With automatic CLI tools 27 | 28 | We can also automatically populate {mod}`torchrunx.Launcher` arguments using most CLI tools, e.g. [`tyro`](https://brentyi.github.io/tyro/) or any that [generate interfaces from dataclasses](https://brentyi.github.io/tyro/goals_and_alternatives). 29 | 30 | ```python 31 | import torchrunx 32 | import tyro 33 | 34 | if __name__ == "__main__": 35 | launcher = tyro.cli(torchrunx.Launcher) 36 | results = launcher.run(...) 37 | ``` 38 | 39 | `python ... --help` then results in: 40 | 41 | ```{eval-rst} 42 | .. literalinclude:: ../artifacts/tyro_cli_help.txt 43 | :lines: 3- 44 | ``` 45 | -------------------------------------------------------------------------------- /docs/source/usage/general.md: -------------------------------------------------------------------------------- 1 | # General 2 | 3 | ## Multiple functions in one script 4 | 5 | Consider multiple stages of training: pre-training, supervised fine-tuning, RLHF, etc. 6 | 7 | Normally, this kind of work is delegated to multiple scripts. Why? Each stage is complicated (prone to memory leaks) and we don't want them to interfere with each other. They may even require different degrees of parallelism. 8 | 9 | `torchrunx` solves these problems — even within a single script — by modularizing workloads into isolated, self-cleaning processes. 10 | 11 | ```python 12 | # 2 nodes x 8 GPUs 13 | train_launcher = torchrunx.Launcher(hostnames=["node1", "node2"], workers_per_host=8) 14 | # 1 GPU 15 | eval_launcher = torchrunx.Launcher(hostnames=["node1"], workers_per_host=1) 16 | 17 | # Training & testing 18 | 19 | pretrained_model = train_launcher.run(train).rank(0) 20 | pretrained_acc = eval_launcher.run(evaluation, model=pretrained_model).rank(0) 21 | print(f"Pre-trained model accuracy: {pretrained_acc}") 22 | 23 | finetuned_model = train_launcher.run(finetuning, model=pretrained_model).rank(0) 24 | finetuned_acc = eval_launcher.run(evaluation, model=finetuned_model).rank(0) 25 | print(f"Fine-tuned model accuracy: {finetuned_acc}") 26 | ``` 27 | 28 | ## Exceptions 29 | 30 | Exceptions that are raised in workers will be raised by the launcher process. A {mod}`torchrunx.AgentFailedError` or {mod}`torchrunx.WorkerFailedError` will be raised if any agent or worker dies unexpectedly (e.g. if sent a signal from the OS, due to segmentation faults or OOM). 31 | 32 | You can catch these errors and handle them as you wish! 33 | 34 | ```python 35 | for config in configs: # e.g. hyper-parameter sweep 36 | try: 37 | torchrunx.Launcher().run(train, config) 38 | except torch.cuda.OutOfMemoryError: 39 | print(f"{config} results in OOM... continuing...") 40 | ``` 41 | 42 | If you are expecting intermittent failures, you can catch errors and invoke retries: 43 | 44 | ```python 45 | for retry in range(3): 46 | try: 47 | torchrunx.Launcher().run(train, resume_from_checkpoint=True) 48 | except torchrunx.WorkerFailedError as e: 49 | print(f"Error occurred: {e}") 50 | print(f"Retrying ({retry}) ...") 51 | else: # if run() is successful 52 | break 53 | ``` 54 | 55 | ## Environment variables 56 | 57 | Environment variables in the launcher process that pattern match the [``copy_env_vars``](../api.md#torchrunx.Launcher.copy_env_vars) argument are automatically copied to agents and workers. We set useful defaults for Python and PyTorch. You could replace these. Or extend these like: 58 | 59 | ```python 60 | torchrunx.Launcher(copy_env_vars=( 61 | torchrunx.DEFAULT_ENV_VARS_FOR_COPY + ("HF_HOME", "WANDB_*",) 62 | )) 63 | ``` 64 | 65 | You can also pass (1) specific environment variables and values via [``extra_env_vars``](../api.md#torchrunx.Launcher.extra_env_vars) or (2) a ``.env``-style file via [``env_file``](../api.md#torchrunx.Launcher.env_file). Our agents `source {env_file}`. 66 | 67 | Finally, we set the following environment variables in each worker: `LOCAL_RANK`, `RANK`, `LOCAL_WORLD_SIZE`, `WORLD_SIZE`, `MASTER_ADDR`, and `MASTER_PORT`. 68 | -------------------------------------------------------------------------------- /docs/source/usage/logging.md: -------------------------------------------------------------------------------- 1 | # Custom Logging 2 | 3 | We forward all agent and worker logs (i.e. from {mod}`logging`, `stdout`, and `stderr`) to the launcher process. 4 | 5 | ## Defaults 6 | 7 | By default, the logs from the rank 0 agent and rank 0 worker are handled by loggers on the launcher process (and so they should be printed to `stdout`/`stderr`). You may control these logs like: 8 | 9 | ```python 10 | logging.basicConfig(level=logging.INFO) 11 | logging.getLogger("torchrunx").setLevel(logging.DEBUG) 12 | logging.getLogger("torchrunx.node1").setLevel(logging.INFO) 13 | logging.getLogger("torchrunx.node1.1").setLevel(logging.INFO) # worker 1 (local rank) on node 1 14 | ``` 15 | 16 | Also, logs from all agents and workers are written to a directory (by the current timestamp) in `$TORCHRUNX_LOG_DIR` (default: `./torchrunx_logs`). These can be controlled using `$TORCHRUNX_LOG_LEVEL` (default: `INFO`). 17 | 18 | ## Customization 19 | 20 | You can fully customize how logs are processed using {func}`torchrunx.Launcher.set_logging_handlers`. You should provide it a factory function that constructs and returns a list of {obj}`logging.Handler` objects. Each {obj}`logging.Handler` controls where logs should be written. You can also add a filter to restrict the handler to the logs of a specific agent or worker. 21 | 22 | Here's an example: 23 | 24 | ```python 25 | from torchrunx.utils.log_handling import RedirectHandler, get_handler_filter 26 | 27 | def custom_handlers() -> list[logging.Handler]: 28 | 29 | # Handler: redirect logs from (host 0, agent) to logger on launcher process 30 | redirect_handler = RedirectHandler() 31 | redirect_handler.addFilter(get_handler_filter( 32 | hostname=hostnames[0], local_rank=None, log_level=logging.DEBUG 33 | )) 34 | 35 | # Handler: output logs from (host 0, worker 0) to "output.txt" 36 | file_handler = logging.FileHandler("output.txt") 37 | file_handler.addFilter(get_handler_filter( 38 | hostname=hostnames[0], local_rank=0, log_level=logging.DEBUG 39 | )) 40 | 41 | return [ 42 | redirect_handler, 43 | file_handler, 44 | ] 45 | ``` 46 | 47 | ```python 48 | torchrunx.Launcher(...).set_logging_handlers(custom_handlers).run(...) 49 | ``` 50 | 51 | Finally, you can control library-specific logging (within the worker processes) by modifying the distributed function: 52 | 53 | ```python 54 | def distributed_function(): 55 | logging.getLogger("transformers").setLevel(logging.DEBUG) 56 | 57 | logger = logging.getLogger("my_app") 58 | logger.info("Hello world!") 59 | ... 60 | 61 | torchrunx.Launcher(...).run(distributed_function) 62 | ``` 63 | -------------------------------------------------------------------------------- /docs/source/usage/slurm.md: -------------------------------------------------------------------------------- 1 | # Using SLURM 2 | 3 | Normally, you are expected to provide the `hostnames` argument in {obj}`torchrunx.Launcher` to specify which nodes you would like to launch your function onto. 4 | 5 | If your script is running within a SLURM allocation and you set `hostnames` to `"auto"` (default) or `"slurm"`, we will automatically detect the available nodes and distribute your function onto all of these. A {exc}`RuntimeError` will be raised if `hostnames="slurm"` but no SLURM allocation is detected. 6 | 7 | ## With `sbatch` 8 | 9 | You could have a script (`train.py`) that includes: 10 | 11 | ```python 12 | def distributed_training(): 13 | ... 14 | 15 | if __name__ == "__main__": 16 | torchrunx.Launcher( 17 | hostnames = "slurm", 18 | workers_per_host = "gpu" 19 | ).run(distributed_training) 20 | ``` 21 | 22 | And some `run.batch` file (e.g. allocating 2 nodes with 2 GPUs each): 23 | 24 | ```bash 25 | #!/bin/bash 26 | #SBATCH --job-name=torchrunx 27 | #SBATCH --time=1:00:00 28 | #SBATCH --ntasks-per-node=1 29 | #SBATCH --nodes=2 30 | #SBATCH --gpus-per-node=2 31 | 32 | # TODO: load your virutal environment 33 | python train.py 34 | ``` 35 | 36 | `sbatch run.batch` should then run `python train.py` (the launcher process) on the primary machine in your SLURM allocation. The launcher will automatically distribute the training function onto both allocated nodes (and also parallelize it across the allocated GPUs). 37 | 38 | ## With `submitit` 39 | 40 | If we use the [`submitit`](https://github.com/facebookincubator/submitit) Python library, we can do all of this from a single python script. 41 | 42 | ```python 43 | def distributed_training(): 44 | ... 45 | 46 | def launch_training(): 47 | torchrunx.Launcher( 48 | hostnames = "slurm", 49 | workers_per_host = "gpu" 50 | ).run(distributed_training) 51 | 52 | if __name__ == "__main__": 53 | executor = submitit.SlurmExecutor(folder="slurm_outputs") 54 | executor.update_parameters( 55 | use_srun=False, time=60, ntasks_per_node=1, 56 | nodes=2, gpus_per_node=2 57 | ) 58 | executor.submit(launch_training) 59 | ``` 60 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "torchrunx" 7 | version = "0.3.1" 8 | authors = [ 9 | { name = "Apoorv Khandelwal", email = "mail@apoorvkh.com" }, 10 | { name = "Peter Curtin", email = "peter_curtin@brown.edu" }, 11 | ] 12 | description = "Automatically initialize distributed PyTorch environments" 13 | readme = "README.md" 14 | license = { file = "LICENSE" } 15 | urls = { Repository = "https://github.com/apoorvkh/torchrunx.git", Documentation = "https://torchrun.xyz" } 16 | requires-python = ">=3.9" 17 | dependencies = [ 18 | "cloudpickle>=3.0", 19 | "fabric>=3.2", 20 | "torch>=2.0", 21 | # torch.distributed depends on numpy 22 | # torch<=2.2 needs numpy<2 23 | "numpy>=1.20", 24 | "typing-extensions>=4.9.0", 25 | ] 26 | [dependency-groups] 27 | dev = ["ruff==0.9.5", "pyright[nodejs]==1.1.393", "pytest==8.3.4"] 28 | test-extras = ["submitit", "transformers"] 29 | docs = [ 30 | "sphinx==7.4.7", 31 | "furo==2024.8.6", 32 | "myst-parser==3.0.1", 33 | "sphinx-toolbox==3.8.2", 34 | ] 35 | 36 | [tool.ruff] 37 | include = ["pyproject.toml", "src/**/*.py", "tests/**/*.py"] 38 | exclude = ["docs"] 39 | line-length = 100 40 | src = ["src", "tests"] 41 | [tool.ruff.lint] 42 | select = ["ALL"] 43 | ignore = [ 44 | "TC003", # no type checking blocks for stdlib 45 | "D104", # package docstrings 46 | "ANN401", # self / cls / Any annotations 47 | "BLE001", # blind exceptions 48 | "TD", # todo syntax 49 | "FIX002", # existing todos 50 | "PLR0913", # too many arguments 51 | "DTZ005", # datetime timezone 52 | "S301", # bandit: pickle 53 | "S603", 54 | "S607", # bandit: subprocess 55 | "COM812", 56 | "ISC001", # conflict with formatter 57 | "G004" # f-string in logging 58 | ] 59 | [tool.ruff.lint.per-file-ignores] 60 | "tests/**/*.py" = [ 61 | "D", 62 | "S101", # allow asserts 63 | "T201", # allow prints 64 | ] 65 | [tool.ruff.lint.pydocstyle] 66 | convention = "google" 67 | 68 | [tool.pyright] 69 | include = ["src", "tests"] 70 | pythonVersion = "3.9" 71 | pythonPlatform = "Linux" 72 | -------------------------------------------------------------------------------- /scripts/build_docs.sh: -------------------------------------------------------------------------------- 1 | uv run --group docs python -m sphinx --builder html --doctree-dir docs/_build/.doctrees --conf-dir docs --show-traceback docs/source docs/_build/html 2 | -------------------------------------------------------------------------------- /scripts/examples/accelerate_train.py: -------------------------------------------------------------------------------- 1 | # /// script 2 | # requires-python = ">=3.9" 3 | # dependencies = [ 4 | # "accelerate", 5 | # "datasets", 6 | # "torch", 7 | # "transformers", 8 | # "tyro", 9 | # ] 10 | # /// 11 | 12 | # [docs:start-after] 13 | from __future__ import annotations 14 | 15 | import functools 16 | import logging 17 | import os 18 | from dataclasses import dataclass 19 | from pathlib import Path 20 | from typing import Annotated 21 | 22 | import torch 23 | import tyro 24 | from accelerate import Accelerator 25 | from datasets import load_dataset 26 | from torch.utils.data import Dataset 27 | from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel 28 | 29 | import torchrunx 30 | 31 | logging.basicConfig(level=logging.INFO) 32 | 33 | 34 | @dataclass 35 | class ModelConfig: 36 | name: str 37 | 38 | 39 | @dataclass 40 | class DatasetConfig: 41 | path: str 42 | name: str | None = None 43 | split: str | None = None 44 | text_column: str = "text" 45 | num_samples: int | None = None 46 | 47 | 48 | def load_training_data( 49 | tokenizer_name: str, 50 | dataset_config: DatasetConfig, 51 | ) -> Dataset: 52 | # Load dataset 53 | 54 | dataset = load_dataset( 55 | dataset_config.path, name=dataset_config.name, split=dataset_config.split 56 | ) 57 | if dataset_config.num_samples is not None: 58 | dataset = dataset.select(range(dataset_config.num_samples)) 59 | 60 | # Build tokenizer 61 | 62 | os.environ["TOKENIZERS_PARALLELISM"] = "false" # to suppress warnings 63 | tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) 64 | if tokenizer.pad_token is None: 65 | tokenizer.pad_token = tokenizer.eos_token 66 | tokenize_fn = functools.partial( 67 | tokenizer, 68 | max_length=tokenizer.model_max_length, 69 | truncation=True, 70 | padding="max_length", 71 | ) 72 | 73 | # Tokenize dataset 74 | 75 | return dataset.map( 76 | tokenize_fn, 77 | batched=True, 78 | input_columns=[dataset_config.text_column], 79 | remove_columns=[dataset_config.text_column], 80 | ).map(lambda x: {"labels": x["input_ids"]}) 81 | 82 | 83 | def train( 84 | model: PreTrainedModel, 85 | train_dataset: Dataset, 86 | batch_size: int, 87 | output_dir: Path, 88 | ) -> Path: 89 | accelerator = Accelerator() 90 | 91 | optimizer = torch.optim.Adam(model.parameters()) 92 | train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size) 93 | 94 | model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader) 95 | 96 | model.train() 97 | for batch_idx, batch in enumerate(train_dataloader): 98 | device_batch = {k: torch.stack(v, dim=0).to(accelerator.device) for k, v in batch.items()} 99 | optimizer.zero_grad() 100 | 101 | loss = model(**device_batch).loss 102 | print(f"Step {batch_idx}, loss: {loss.item()}", flush=True, end="") 103 | accelerator.backward(loss) 104 | 105 | optimizer.step() 106 | 107 | accelerator.wait_for_everyone() 108 | accelerator.save_state(output_dir=output_dir, safe_serialization=False) 109 | return output_dir / "pytorch_model.bin" 110 | 111 | 112 | def main( 113 | launcher: torchrunx.Launcher, 114 | model_config: Annotated[ModelConfig, tyro.conf.arg(name="model")], 115 | dataset_config: Annotated[DatasetConfig, tyro.conf.arg(name="dataset")], 116 | batch_size: int, 117 | output_dir: Path, 118 | ): 119 | model = AutoModelForCausalLM.from_pretrained(model_config.name) 120 | train_dataset = load_training_data( 121 | tokenizer_name=model_config.name, dataset_config=dataset_config 122 | ) 123 | 124 | # Launch training 125 | results = launcher.run(train, model, train_dataset, batch_size, output_dir) 126 | 127 | # Loading trained model from checkpoint 128 | checkpoint_path = results.rank(0) 129 | trained_model = AutoModelForCausalLM.from_pretrained( 130 | model_config.name, state_dict=torch.load(checkpoint_path) 131 | ) 132 | 133 | 134 | if __name__ == "__main__": 135 | tyro.cli(main) 136 | -------------------------------------------------------------------------------- /scripts/examples/deepspeed_train.py: -------------------------------------------------------------------------------- 1 | # /// script 2 | # requires-python = ">=3.9" 3 | # dependencies = [ 4 | # "datasets", 5 | # "deepspeed", 6 | # "tensorboard", 7 | # "torch", 8 | # "torchrunx", 9 | # "transformers", 10 | # "tyro", 11 | # ] 12 | # /// 13 | 14 | # [docs:start-after] 15 | from __future__ import annotations 16 | 17 | import functools 18 | import logging 19 | import os 20 | from dataclasses import dataclass 21 | from pathlib import Path 22 | from typing import Annotated 23 | 24 | import deepspeed 25 | import torch 26 | import tyro 27 | from datasets import load_dataset 28 | from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint 29 | from torch.utils.data import Dataset 30 | from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel 31 | 32 | import torchrunx 33 | 34 | logging.basicConfig(level=logging.INFO) 35 | 36 | 37 | @dataclass 38 | class DatasetConfig: 39 | path: str 40 | name: str | None = None 41 | split: str | None = None 42 | text_column: str = "text" 43 | num_samples: int | None = None 44 | 45 | 46 | def load_training_data( 47 | tokenizer_name: str, 48 | dataset_config: DatasetConfig, 49 | ) -> Dataset: 50 | # Load dataset 51 | 52 | dataset = load_dataset( 53 | dataset_config.path, name=dataset_config.name, split=dataset_config.split 54 | ) 55 | if dataset_config.num_samples is not None: 56 | dataset = dataset.select(range(dataset_config.num_samples)) 57 | 58 | # Build tokenizer 59 | 60 | os.environ["TOKENIZERS_PARALLELISM"] = "false" # to suppress warnings 61 | tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) 62 | if tokenizer.pad_token is None: 63 | tokenizer.pad_token = tokenizer.eos_token 64 | tokenize_fn = functools.partial( 65 | tokenizer, 66 | max_length=tokenizer.model_max_length, 67 | truncation=True, 68 | padding="max_length", 69 | ) 70 | 71 | # Tokenize dataset 72 | 73 | return dataset.map( 74 | tokenize_fn, 75 | batched=True, 76 | input_columns=[dataset_config.text_column], 77 | remove_columns=[dataset_config.text_column], 78 | ).map(lambda x: {"labels": x["input_ids"]}) 79 | 80 | 81 | def train( 82 | model: PreTrainedModel, 83 | train_dataset: Dataset, 84 | deepspeed_config: str | dict, 85 | checkpoint_dir: str, 86 | ) -> None: 87 | model_engine, _, data_loader, _ = deepspeed.initialize( 88 | model=model, 89 | model_parameters=model.parameters(), 90 | training_data=train_dataset, 91 | config=deepspeed_config, 92 | ) 93 | 94 | model_engine.train() 95 | 96 | for step, batch in enumerate(data_loader): 97 | input_batch = {k: torch.stack(v).T.to(model_engine.device) for k, v in batch.items()} 98 | loss = model_engine(**input_batch).loss 99 | model_engine.backward(loss) 100 | model_engine.step() 101 | print(f"Step {step}, loss: {loss.item()}", flush=True, end="") 102 | 103 | model_engine.save_checkpoint(checkpoint_dir) 104 | 105 | 106 | def main( 107 | model_name: str, 108 | deepspeed_config: Path, 109 | checkpoint_dir: Path, 110 | dataset_config: Annotated[DatasetConfig, tyro.conf.arg(name="dataset")], 111 | launcher: torchrunx.Launcher, 112 | ): 113 | model = AutoModelForCausalLM.from_pretrained(model_name) 114 | train_dataset = load_training_data(tokenizer_name=model_name, dataset_config=dataset_config) 115 | 116 | # Launch training 117 | launcher.run(train, model, train_dataset, str(deepspeed_config), str(checkpoint_dir)) 118 | 119 | # Loading trained model from checkpoint 120 | state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) 121 | trained_model = AutoModelForCausalLM.from_pretrained(model_name) 122 | trained_model.load_state_dict(state_dict) 123 | 124 | 125 | if __name__ == "__main__": 126 | tyro.cli(main) 127 | -------------------------------------------------------------------------------- /scripts/examples/lightning_train.py: -------------------------------------------------------------------------------- 1 | # /// script 2 | # requires-python = ">=3.9" 3 | # dependencies = [ 4 | # "datasets", 5 | # "lightning", 6 | # "torch", 7 | # "torchrunx", 8 | # "transformers", 9 | # "tyro", 10 | # ] 11 | # /// 12 | 13 | # [docs:start-after] 14 | from __future__ import annotations 15 | 16 | import functools 17 | import logging 18 | import os 19 | from dataclasses import dataclass 20 | from typing import Annotated 21 | 22 | import lightning as L 23 | import torch 24 | import tyro 25 | from datasets import load_dataset 26 | from torch.utils.data import Dataset 27 | from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel 28 | 29 | import torchrunx 30 | from torchrunx.integrations.lightning import TorchrunxClusterEnvironment 31 | 32 | logging.basicConfig(level=logging.INFO) 33 | 34 | 35 | @dataclass 36 | class ModelConfig: 37 | name: str 38 | 39 | 40 | @dataclass 41 | class DatasetConfig: 42 | path: str 43 | name: str | None = None 44 | split: str | None = None 45 | text_column: str = "text" 46 | num_samples: int | None = None 47 | 48 | 49 | def load_training_data( 50 | tokenizer_name: str, 51 | dataset_config: DatasetConfig, 52 | ) -> Dataset: 53 | # Load dataset 54 | 55 | dataset = load_dataset( 56 | dataset_config.path, name=dataset_config.name, split=dataset_config.split 57 | ) 58 | if dataset_config.num_samples is not None: 59 | dataset = dataset.select(range(dataset_config.num_samples)) 60 | 61 | # Build tokenizer 62 | 63 | os.environ["TOKENIZERS_PARALLELISM"] = "false" # to suppress warnings 64 | tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) 65 | if tokenizer.pad_token is None: 66 | tokenizer.pad_token = tokenizer.eos_token 67 | tokenize_fn = functools.partial( 68 | tokenizer, 69 | max_length=tokenizer.model_max_length, 70 | truncation=True, 71 | padding="max_length", 72 | ) 73 | 74 | # Tokenize dataset 75 | 76 | return dataset.map( 77 | tokenize_fn, 78 | batched=True, 79 | input_columns=[dataset_config.text_column], 80 | remove_columns=[dataset_config.text_column], 81 | ).map(lambda x: {"labels": x["input_ids"]}) 82 | 83 | 84 | class CausalLMLightningWrapper(L.LightningModule): 85 | def __init__(self, model): 86 | super().__init__() 87 | self.model = model 88 | 89 | def training_step(self, batch, *args): # pyright: ignore 90 | device_batch = {k: torch.stack(v, dim=0).to(self.model.device) for k, v in batch.items()} 91 | loss = self.model(**device_batch).loss 92 | self.log("train_loss", loss) 93 | return loss 94 | 95 | def configure_optimizers(self): 96 | optimizer = torch.optim.Adam(self.parameters(), lr=1e-5) 97 | return optimizer 98 | 99 | 100 | def train(model: PreTrainedModel, train_dataset: Dataset) -> str: 101 | lightning_model = CausalLMLightningWrapper(model) 102 | 103 | train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=8) 104 | 105 | trainer = L.Trainer( 106 | accelerator="gpu", 107 | max_epochs=1, 108 | strategy="ddp", 109 | plugins=[TorchrunxClusterEnvironment()], 110 | enable_checkpointing=False, 111 | ) 112 | 113 | trainer.fit(model=lightning_model, train_dataloaders=train_loader) 114 | checkpoint = f"{trainer.log_dir}/final.ckpt" 115 | trainer.save_checkpoint(checkpoint) 116 | 117 | return checkpoint 118 | 119 | 120 | def main( 121 | launcher: torchrunx.Launcher, 122 | model_config: Annotated[ModelConfig, tyro.conf.arg(name="model")], 123 | dataset_config: Annotated[DatasetConfig, tyro.conf.arg(name="dataset")], 124 | ): 125 | model = AutoModelForCausalLM.from_pretrained(model_config.name) 126 | train_dataset = load_training_data( 127 | tokenizer_name=model_config.name, dataset_config=dataset_config 128 | ) 129 | 130 | # Launch training 131 | results = launcher.run(train, model, train_dataset) 132 | 133 | # Loading trained model from checkpoint 134 | checkpoint_path = results.rank(0) 135 | dummy_model = AutoModelForCausalLM.from_pretrained(model_config.name) 136 | trained_model = CausalLMLightningWrapper(dummy_model) 137 | trained_model.load_state_dict(torch.load(checkpoint_path)["state_dict"]) 138 | trained_model = trained_model.model 139 | 140 | 141 | if __name__ == "__main__": 142 | tyro.cli(main) 143 | -------------------------------------------------------------------------------- /scripts/examples/transformers_train.py: -------------------------------------------------------------------------------- 1 | # /// script 2 | # requires-python = ">=3.9" 3 | # dependencies = [ 4 | # "datasets", 5 | # "tensorboard", 6 | # "torchrunx", 7 | # "transformers[torch]", 8 | # "tyro", 9 | # ] 10 | # /// 11 | 12 | # [docs:start-after] 13 | from __future__ import annotations 14 | 15 | import functools 16 | import logging 17 | import os 18 | from dataclasses import dataclass 19 | from typing import Annotated 20 | 21 | import tyro 22 | from datasets import Dataset, load_dataset 23 | from transformers import ( 24 | AutoModelForCausalLM, 25 | AutoTokenizer, 26 | PreTrainedModel, 27 | Trainer, 28 | TrainingArguments, 29 | trainer_utils, 30 | ) 31 | 32 | import torchrunx 33 | 34 | logging.basicConfig(level=logging.INFO) 35 | 36 | @dataclass 37 | class ModelConfig: 38 | name: str 39 | 40 | 41 | @dataclass 42 | class DatasetConfig: 43 | path: str 44 | name: str | None = None 45 | split: str | None = None 46 | text_column: str = "text" 47 | num_samples: int | None = None 48 | 49 | 50 | def load_training_data( 51 | tokenizer_name: str, 52 | dataset_config: DatasetConfig, 53 | ) -> Dataset: 54 | # Load dataset 55 | 56 | dataset = load_dataset( 57 | dataset_config.path, name=dataset_config.name, split=dataset_config.split 58 | ) 59 | if dataset_config.num_samples is not None: 60 | dataset = dataset.select(range(dataset_config.num_samples)) 61 | 62 | # Build tokenizer 63 | 64 | os.environ["TOKENIZERS_PARALLELISM"] = "false" # to suppress warnings 65 | tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) 66 | if tokenizer.pad_token is None: 67 | tokenizer.pad_token = tokenizer.eos_token 68 | tokenize_fn = functools.partial( 69 | tokenizer, 70 | max_length=tokenizer.model_max_length, 71 | truncation=True, 72 | padding="max_length", 73 | ) 74 | 75 | # Tokenize dataset 76 | 77 | return dataset.map( 78 | tokenize_fn, 79 | batched=True, 80 | input_columns=[dataset_config.text_column], 81 | remove_columns=[dataset_config.text_column], 82 | ).map(lambda x: {"labels": x["input_ids"]}) 83 | 84 | 85 | def train( 86 | model: PreTrainedModel, 87 | train_dataset: Dataset, 88 | training_args: TrainingArguments, 89 | ) -> str: 90 | trainer = Trainer(model=model, train_dataset=train_dataset, args=training_args) 91 | trainer.train() 92 | return trainer_utils.get_last_checkpoint(training_args.output_dir) 93 | 94 | 95 | def main( 96 | launcher: torchrunx.Launcher, 97 | model_config: Annotated[ModelConfig, tyro.conf.arg(name="model")], 98 | dataset_config: Annotated[DatasetConfig, tyro.conf.arg(name="dataset")], 99 | training_args: Annotated[TrainingArguments, tyro.conf.arg(name="trainer", help="")], 100 | ): 101 | model = AutoModelForCausalLM.from_pretrained(model_config.name) 102 | train_dataset = load_training_data( 103 | tokenizer_name=model_config.name, dataset_config=dataset_config 104 | ) 105 | 106 | # Launch training 107 | results = launcher.run(train, model, train_dataset, training_args) 108 | 109 | # Loading trained model from checkpoint 110 | checkpoint_path = results.rank(0) 111 | trained_model = AutoModelForCausalLM.from_pretrained(checkpoint_path) 112 | 113 | 114 | if __name__ == "__main__": 115 | tyro.cli(main) 116 | -------------------------------------------------------------------------------- /scripts/generate_help_menus.sh: -------------------------------------------------------------------------------- 1 | mkdir docs/source/artifacts 2 | 3 | uv run python -c "from argparse import ArgumentParser; from torchrunx.integrations.parsing import add_torchrunx_argument_group; parser = ArgumentParser(); add_torchrunx_argument_group(parser); parser.parse_args()" --help > docs/source/artifacts/argparse_cli_help.txt 4 | uv run --with tyro python -c "import torchrunx; import tyro; tyro.cli(torchrunx.Launcher)" --help > docs/source/artifacts/tyro_cli_help.txt 5 | 6 | uv run --with . scripts/examples/transformers_train.py --help > docs/source/artifacts/transformers_help.txt 7 | uv run --with . scripts/examples/deepspeed_train.py --help > docs/source/artifacts/deepspeed_help.txt 8 | uv run --with . scripts/examples/lightning_train.py --help > docs/source/artifacts/lightning_help.txt 9 | uv run --with . scripts/examples/accelerate_train.py --help > docs/source/artifacts/accelerate_help.txt 10 | -------------------------------------------------------------------------------- /src/torchrunx/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib.metadata 2 | 3 | from .launcher import DEFAULT_ENV_VARS_FOR_COPY, Launcher, LaunchResult 4 | from .utils.errors import AgentFailedError, WorkerFailedError 5 | 6 | __version__ = importlib.metadata.version(__package__ or __name__) 7 | 8 | __all__ = [ # noqa: RUF022 9 | "DEFAULT_ENV_VARS_FOR_COPY", 10 | "Launcher", 11 | "LaunchResult", 12 | "AgentFailedError", 13 | "WorkerFailedError", 14 | ] 15 | -------------------------------------------------------------------------------- /src/torchrunx/__main__.py: -------------------------------------------------------------------------------- 1 | """CLI entrypoint used for starting agents on different nodes.""" 2 | 3 | from argparse import ArgumentParser 4 | 5 | from .agent import main 6 | 7 | if __name__ == "__main__": 8 | parser = ArgumentParser() 9 | parser.add_argument("--launcher-hostname", type=str) 10 | parser.add_argument("--launcher-port", type=int) 11 | parser.add_argument("--logger-port", type=int) 12 | parser.add_argument("--world-size", type=int) 13 | parser.add_argument("--rank", type=int) 14 | parser.add_argument("--hostname", type=str) 15 | args = parser.parse_args() 16 | 17 | main( 18 | launcher_hostname=args.launcher_hostname, 19 | launcher_port=args.launcher_port, 20 | world_size=args.world_size, 21 | rank=args.rank, 22 | logger_hostname=args.launcher_hostname, 23 | logger_port=args.logger_port, 24 | hostname=args.hostname, 25 | ) 26 | -------------------------------------------------------------------------------- /src/torchrunx/agent.py: -------------------------------------------------------------------------------- 1 | """Primary logic for agent processes.""" 2 | 3 | from __future__ import annotations 4 | 5 | __all__ = ["main"] 6 | 7 | import logging 8 | import os 9 | import socket 10 | import sys 11 | import tempfile 12 | 13 | import torch 14 | import torch.distributed.elastic.multiprocessing as dist_mp 15 | 16 | from .utils.comm import ( 17 | AgentPayload, 18 | AgentStatus, 19 | LauncherAgentGroup, 20 | get_open_port, 21 | ) 22 | from .utils.log_streaming import log_records_to_socket, redirect_stdio_to_logger 23 | from .worker import WorkerArgs, worker_entrypoint 24 | 25 | 26 | def main( 27 | launcher_hostname: str, 28 | launcher_port: int, 29 | world_size: int, 30 | rank: int, 31 | logger_hostname: str, 32 | logger_port: int, 33 | hostname: str, 34 | ) -> None: 35 | """Main function for agent processes (started on each node). 36 | 37 | This function spawns local worker processes (which run the target function). All agents monitor 38 | their worker statuses (including returned objects and raised exceptions) and communicate these 39 | with each other (and launcher). All agents terminate if failure occurs in any agent. 40 | 41 | Arguments: 42 | launcher_hostname: Hostname of the launcher process. 43 | launcher_port: Port for the process group on the launcher. 44 | world_size: Number of agents + 1 (launcher). 45 | rank: Rank of this agent. 46 | logger_hostname: Hostname of the logging server. 47 | logger_port: Port for the logging server. 48 | hostname: Hostname of this agent. 49 | """ 50 | # Setup logging & stream logs to server 51 | 52 | log_records_to_socket( 53 | hostname=hostname, local_rank=None, logger_hostname=logger_hostname, logger_port=logger_port 54 | ) 55 | 56 | logger = logging.getLogger() 57 | redirect_stdio_to_logger(logger) 58 | 59 | logger.debug("Initializing launcher-agent group.") 60 | 61 | launcher_agent_group = LauncherAgentGroup( 62 | launcher_hostname=launcher_hostname, 63 | launcher_port=launcher_port, 64 | world_size=world_size, 65 | rank=rank, 66 | ) 67 | 68 | agent_rank = launcher_agent_group.rank - 1 69 | 70 | logger.debug("Synchronizing launcher and agents.") 71 | 72 | payload = AgentPayload( 73 | hostname=socket.getfqdn(), 74 | port=get_open_port(), 75 | process_id=os.getpid(), 76 | ) 77 | 78 | launcher_payload, agent_payloads = launcher_agent_group.sync_payloads(payload=payload) 79 | 80 | hostname = launcher_payload.hostnames[agent_rank] 81 | worker_world_size = launcher_payload.worker_world_size 82 | worker_global_ranks = launcher_payload.worker_global_ranks[agent_rank] 83 | num_workers = len(worker_global_ranks) 84 | 85 | logger.info(f"Starting {num_workers} worker processes.") 86 | 87 | ctx = dist_mp.start_processes( 88 | name=f"{hostname}_", 89 | entrypoint=worker_entrypoint, 90 | args={ 91 | i: ( 92 | WorkerArgs( 93 | function=launcher_payload.fn, 94 | logger_hostname=logger_hostname, 95 | logger_port=logger_port, 96 | master_hostname=agent_payloads[0].hostname, 97 | master_port=agent_payloads[0].port, 98 | backend=launcher_payload.backend, 99 | rank=worker_global_ranks[i], 100 | local_rank=i, 101 | node_rank=agent_rank, 102 | local_world_size=num_workers, 103 | world_size=worker_world_size, 104 | hostname=launcher_payload.hostnames[agent_rank], 105 | timeout=launcher_payload.timeout, 106 | ).serialize(), 107 | ) 108 | for i in range(num_workers) 109 | }, 110 | # environment variables from agent are already automatically copied to workers 111 | envs={i: {} for i in range(num_workers)}, 112 | # we handle logging ourselves, so we can discard these 113 | **( 114 | {"logs_specs": dist_mp.DefaultLogsSpecs(log_dir=tempfile.mkdtemp())} 115 | if torch.__version__ >= "2.3" 116 | else {"log_dir": tempfile.mkdtemp()} 117 | ), # pyright: ignore [reportArgumentType] 118 | ) 119 | 120 | # Monitor and communicate agent statuses 121 | # Terminate gracefully upon failure 122 | 123 | logger.debug("Entering worker monitoring and agent communication loop.") 124 | 125 | try: 126 | status = None 127 | while True: 128 | if status is None or status.state == "running": 129 | # status can contain ExceptionFromWorker or WorkerFailedError 130 | status = AgentStatus.from_result(result=ctx.wait(5)) 131 | 132 | # can raise AgentFailedError in launcher and all agents 133 | agent_statuses = launcher_agent_group.sync_agent_statuses(status=status) 134 | 135 | all_done = all(s.state == "done" for s in agent_statuses) 136 | any_failed = any(s.state == "failed" for s in agent_statuses) 137 | if all_done or any_failed: 138 | logger.info(f"Workers exited {'with' if any_failed else 'without'} errors.") 139 | break 140 | finally: 141 | ctx.close() 142 | sys.stdout.flush() 143 | sys.stderr.flush() 144 | launcher_agent_group.shutdown() 145 | 146 | logger.debug("Terminating agent process.") 147 | -------------------------------------------------------------------------------- /src/torchrunx/integrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apoorvkh/torchrunx/44446340838d62e1996c716919b0b836554ba143/src/torchrunx/integrations/__init__.py -------------------------------------------------------------------------------- /src/torchrunx/integrations/cli.py: -------------------------------------------------------------------------------- 1 | """Utilities for building a Launcher from argparse command-line arguments.""" 2 | 3 | from __future__ import annotations 4 | 5 | __all__ = ["add_torchrunx_argument_group", "launcher_from_args"] 6 | 7 | from argparse import ArgumentParser, Namespace 8 | from typing import Literal 9 | 10 | from torchrunx import DEFAULT_ENV_VARS_FOR_COPY, Launcher 11 | 12 | 13 | def add_torchrunx_argument_group(parser: ArgumentParser) -> None: 14 | """Add an argument group for torchrunx.Launcher to an ArgumentParser.""" 15 | group = parser.add_argument_group("torchrunx") 16 | 17 | group.add_argument( 18 | "--hostnames", 19 | type=str, 20 | nargs="+", 21 | default="auto", 22 | help="Nodes to launch the function on. Default: 'auto'. Use 'slurm' to infer from SLURM.", 23 | ) 24 | 25 | group.add_argument( 26 | "--workers-per-host", 27 | type=str, 28 | nargs="+", 29 | default="gpu", 30 | help="Processes to run per node. Can be 'cpu', 'gpu', or list[int]. Default: 'gpu'.", 31 | ) 32 | 33 | group.add_argument( 34 | "--ssh-config-file", 35 | type=str, 36 | default=None, 37 | help="Path to SSH config file. Default: '~/.ssh/config' or '/etc/ssh/ssh_config'.", 38 | ) 39 | 40 | group.add_argument( 41 | "--backend", 42 | type=str, 43 | choices=["nccl", "gloo", "mpi", "ucc", "None"], 44 | default="nccl", 45 | help="For worker process group. Default: 'nccl'. Use 'gloo' for CPU. 'None' to disable.", 46 | ) 47 | 48 | group.add_argument( 49 | "--timeout", 50 | type=int, 51 | default=600, 52 | help="Worker process group timeout in seconds. Default: 600.", 53 | ) 54 | 55 | group.add_argument( 56 | "--copy-env-vars", 57 | type=str, 58 | nargs="+", 59 | default=DEFAULT_ENV_VARS_FOR_COPY, 60 | help="Environment variables to copy to workers. Supports Unix pattern matching.", 61 | ) 62 | 63 | group.add_argument( 64 | "--extra-env-vars", 65 | type=str, 66 | nargs="*", 67 | default=None, 68 | help="Additional environment variables as key=value pairs.", 69 | ) 70 | 71 | group.add_argument( 72 | "--env-file", type=str, default=None, help="Path to a .env file with environment variables." 73 | ) 74 | 75 | 76 | def launcher_from_args(args: Namespace) -> Launcher: 77 | """Create a torchrunx.Launcher from argparse.Namespace.""" 78 | _hostnames: list[str] = args.hostnames 79 | hostnames: list[str] | Literal["auto", "slurm"] 80 | if _hostnames == ["auto"]: 81 | hostnames = "auto" 82 | elif _hostnames == ["slurm"]: 83 | hostnames = "slurm" 84 | else: 85 | hostnames = _hostnames 86 | 87 | _workers_per_host: list[str] = args.workers_per_host 88 | workers_per_host: int | list[int] | Literal["cpu", "gpu"] 89 | 90 | if _workers_per_host == ["cpu"]: 91 | workers_per_host = "cpu" 92 | elif _workers_per_host == ["gpu"]: 93 | workers_per_host = "gpu" 94 | elif len(_workers_per_host) == 1: 95 | workers_per_host = int(_workers_per_host[0]) 96 | else: 97 | workers_per_host = [int(w) for w in _workers_per_host] 98 | 99 | ssh_config_file: str | None = args.ssh_config_file 100 | 101 | _backend: str = args.backend 102 | backend: Literal["nccl", "gloo", "mpi", "ucc"] | None 103 | if _backend == "None": # noqa: SIM108 104 | backend = None 105 | else: 106 | backend = _backend # pyright: ignore [reportAssignmentType] 107 | 108 | timeout: int = args.timeout 109 | 110 | copy_env_vars: tuple[str, ...] = tuple(args.copy_env_vars) 111 | 112 | _extra_env_vars: list[str] | None = args.extra_env_vars 113 | extra_env_vars: dict[str, str] | None 114 | if _extra_env_vars is not None: 115 | extra_env_vars = dict(var.split("=", 1) for var in _extra_env_vars) 116 | else: 117 | extra_env_vars = None 118 | 119 | env_file: str | None = args.env_file 120 | 121 | return Launcher( 122 | hostnames=hostnames, 123 | workers_per_host=workers_per_host, 124 | ssh_config_file=ssh_config_file, 125 | backend=backend, 126 | timeout=timeout, 127 | copy_env_vars=copy_env_vars, 128 | extra_env_vars=extra_env_vars, 129 | env_file=env_file, 130 | ) 131 | -------------------------------------------------------------------------------- /src/torchrunx/integrations/lightning.py: -------------------------------------------------------------------------------- 1 | """Integration with PyTorch Lightning Trainer.""" 2 | 3 | from lightning.fabric.plugins.environments.torchelastic import ( # pyright: ignore [reportMissingImports] 4 | TorchElasticEnvironment, 5 | ) 6 | 7 | 8 | class TorchrunxClusterEnvironment(TorchElasticEnvironment): 9 | """Compatible ClusterEnvironment for PyTorch Lightning.""" 10 | 11 | @staticmethod 12 | def detect() -> bool: 13 | """Force use of the TorchElasticEnvironment.""" 14 | return True 15 | -------------------------------------------------------------------------------- /src/torchrunx/launcher.py: -------------------------------------------------------------------------------- 1 | """For launching functions with our library.""" 2 | 3 | from __future__ import annotations 4 | 5 | __all__ = ["DEFAULT_ENV_VARS_FOR_COPY", "LaunchResult", "Launcher"] 6 | 7 | import fnmatch 8 | import itertools 9 | import logging 10 | import os 11 | import socket 12 | import typing 13 | from dataclasses import dataclass, field 14 | from functools import partial 15 | from multiprocessing import Event, Process 16 | from typing import Generic, TypeVar 17 | 18 | import torch.distributed as dist 19 | from typing_extensions import ParamSpec, Self 20 | 21 | from .utils.comm import ( 22 | LauncherAgentGroup, 23 | LauncherPayload, 24 | get_open_port, 25 | ) 26 | from .utils.environment import ( 27 | build_launch_command, 28 | execute_command, 29 | resolve_environment, 30 | ) 31 | from .utils.errors import ExceptionFromWorker, WorkerFailedError 32 | from .utils.log_handling import default_handlers 33 | from .utils.log_streaming import LoggingServerArgs, start_logging_server 34 | 35 | DEFAULT_ENV_VARS_FOR_COPY = ( 36 | "PATH", 37 | "LD_LIBRARY", 38 | "LIBRARY_PATH", 39 | "PYTHON*", 40 | "CUDA*", 41 | "TORCH*", 42 | "PYTORCH*", 43 | "NCCL*", 44 | ) 45 | 46 | FunctionP = ParamSpec("FunctionP") 47 | FunctionR = TypeVar("FunctionR") 48 | 49 | 50 | @dataclass 51 | class Launcher: 52 | """For configuring the function launch environment.""" 53 | 54 | hostnames: list[str] | typing.Literal["auto", "slurm"] = "auto" 55 | """Nodes to launch the function on. By default, infer from SLURM, else ``["localhost"]``.""" 56 | workers_per_host: int | list[int] | typing.Literal["cpu", "gpu"] = "gpu" 57 | """Number of processes to run per node. By default, number of GPUs per host.""" 58 | ssh_config_file: str | os.PathLike | None = None 59 | """For connecting to nodes. By default, ``"~/.ssh/config"`` or ``"/etc/ssh/ssh_config"``.""" 60 | backend: typing.Literal["nccl", "gloo", "mpi", "ucc"] | None = "nccl" 61 | """`Backend `_ 62 | for worker process group. By default, NCCL (GPU backend). 63 | Use GLOO for CPU backend. ``None`` for no process group.""" 64 | timeout: int = 600 65 | """Worker process group timeout (seconds).""" 66 | copy_env_vars: tuple[str, ...] = DEFAULT_ENV_VARS_FOR_COPY 67 | """Environment variables to copy from the launcher process to workers. 68 | Supports Unix pattern matching syntax.""" 69 | extra_env_vars: dict[str, str] | None = None 70 | """Additional environment variables to load onto workers.""" 71 | env_file: str | os.PathLike | None = None 72 | """Path to a ``.env`` file, containing environment variables to load onto workers.""" 73 | 74 | handler_factory: typing.Callable[[], list[logging.Handler]] | typing.Literal["auto"] | None = ( 75 | field(default="auto", init=False) 76 | ) 77 | 78 | def set_logging_handlers( 79 | self, 80 | handler_factory: typing.Callable[[], list[logging.Handler]] | typing.Literal["auto"] | None, 81 | ) -> Self: 82 | """Provide a ``handler_factory`` function to customize processing of agent/worker logs. 83 | 84 | Parameters: 85 | handler_factory: Function that constructs and returns :obj:`logging.Handler` objects. 86 | See `Custom Logging `_ for more details. 87 | """ 88 | self.handler_factory = handler_factory 89 | return self 90 | 91 | def run( # noqa: C901, PLR0912, PLR0915 92 | self, 93 | func: typing.Callable[FunctionP, FunctionR], 94 | *args: FunctionP.args, 95 | **kwargs: FunctionP.kwargs, 96 | ) -> LaunchResult[FunctionR]: 97 | """Distribute a function onto specified nodes and parallelize across workers. 98 | 99 | Raises: 100 | RuntimeError: Configuration issues. 101 | Exception: Exceptions raised in worker processes are propagated. 102 | WorkerFailedError: If a worker fails (e.g. from a segmentation fault). 103 | AgentFailedError: If an agent fails, e.g. from an OS signal. 104 | """ 105 | logger = logging.getLogger(__package__) 106 | 107 | if not dist.is_available(): 108 | msg = "The torch.distributed package is not available." 109 | raise RuntimeError(msg) 110 | 111 | logger.debug("Preparing launch environment.") 112 | 113 | ### 114 | 115 | hostnames, workers_per_host = resolve_environment( 116 | self.hostnames, self.workers_per_host, ssh_config_file=self.ssh_config_file 117 | ) 118 | ssh_config_file = self.ssh_config_file 119 | backend = self.backend 120 | timeout = self.timeout 121 | 122 | env_vars = { 123 | k: v 124 | for k, v in os.environ.items() 125 | if any(fnmatch.fnmatch(k, e) for e in self.copy_env_vars) 126 | } 127 | if self.extra_env_vars is not None: 128 | env_vars.update(self.extra_env_vars) 129 | env_file = self.env_file 130 | 131 | if self.handler_factory is None: 132 | 133 | def handler_factory() -> list[logging.Handler]: 134 | return [] 135 | elif self.handler_factory == "auto": 136 | handler_factory = partial(default_handlers, hostnames, workers_per_host) 137 | else: 138 | handler_factory = self.handler_factory 139 | 140 | ### 141 | 142 | launcher_hostname = socket.getfqdn() 143 | launcher_port = get_open_port() 144 | logging_port = get_open_port() 145 | world_size = len(hostnames) + 1 146 | 147 | stop_logging_event = None 148 | log_process = None 149 | launcher_agent_group = None 150 | 151 | _cumulative_workers = [0, *itertools.accumulate(workers_per_host)] 152 | worker_global_ranks = [ 153 | list(range(_cumulative_workers[n], _cumulative_workers[n + 1])) 154 | for n in range(len(hostnames)) 155 | ] 156 | payload = LauncherPayload( 157 | fn=partial(func, *args, **kwargs), 158 | hostnames=hostnames, 159 | worker_global_ranks=worker_global_ranks, 160 | worker_world_size=sum(workers_per_host), 161 | backend=backend, 162 | timeout=timeout, 163 | ) 164 | agent_payloads = None 165 | 166 | try: 167 | logger.debug("Starting logging server.") 168 | 169 | # Start logging server (recieves LogRecords from agents/workers) 170 | 171 | logging_server_args = LoggingServerArgs( 172 | handler_factory=handler_factory, 173 | logging_hostname=launcher_hostname, 174 | logging_port=logging_port, 175 | ) 176 | 177 | stop_logging_event = Event() 178 | 179 | log_process = Process( 180 | target=start_logging_server, 181 | args=(logging_server_args.serialize(), stop_logging_event), 182 | daemon=True, 183 | ) 184 | 185 | log_process.start() 186 | 187 | # Start agents on each node 188 | 189 | for i, hostname in enumerate(hostnames): 190 | logger.info(f'Launching "{func.__name__}" on {hostname}.') 191 | 192 | execute_command( 193 | command=build_launch_command( 194 | launcher_hostname=launcher_hostname, 195 | launcher_port=launcher_port, 196 | logger_port=logging_port, 197 | world_size=world_size, 198 | rank=i + 1, 199 | env_vars=env_vars, 200 | env_file=env_file, 201 | hostname=hostname, 202 | ), 203 | hostname=hostname, 204 | ssh_config_file=ssh_config_file, 205 | ) 206 | 207 | logger.debug("Initializing launcher-agent group.") 208 | 209 | # Initialize launcher-agent process group 210 | # ranks = (launcher, agent_{hostnames[0]}, ..., agent[-1]) 211 | 212 | launcher_agent_group = LauncherAgentGroup[FunctionR]( 213 | launcher_hostname=launcher_hostname, 214 | launcher_port=launcher_port, 215 | world_size=world_size, 216 | rank=0, 217 | ) 218 | 219 | # Sync initial payloads between launcher and agents 220 | 221 | logger.debug("Synchronizing launcher and agents.") 222 | launcher_payload, agent_payloads = launcher_agent_group.sync_payloads(payload=payload) 223 | 224 | # Monitor agent statuses (until failed or done) 225 | 226 | logger.debug("Entering agent monitoring loop.") 227 | 228 | while True: 229 | # could raise AgentFailedError 230 | agent_statuses = launcher_agent_group.sync_agent_statuses(status=None) 231 | 232 | # raises specific exception if any agent fails 233 | for s in agent_statuses: 234 | for v in s.return_values: 235 | if isinstance(v, ExceptionFromWorker): 236 | raise v.exception 237 | if isinstance(v, WorkerFailedError): 238 | raise v 239 | 240 | if all(s.state == "done" for s in agent_statuses): 241 | logger.info("All workers completed successfully.") 242 | return_values: list[list[FunctionR]] = [s.return_values for s in agent_statuses] # pyright: ignore [reportAssignmentType] 243 | return LaunchResult.from_returns(hostnames, return_values) 244 | finally: 245 | # cleanup: SIGTERM all agents 246 | if agent_payloads is not None: 247 | for agent_payload, agent_hostname in zip(agent_payloads, hostnames): 248 | logger.debug("Killing PID %s on %s.", agent_payload.process_id, agent_hostname) 249 | 250 | execute_command( 251 | command=f"kill {agent_payload.process_id}", 252 | hostname=agent_hostname, 253 | ssh_config_file=ssh_config_file, 254 | ) 255 | 256 | if launcher_agent_group is not None: 257 | logger.debug("Killing launcher-agent group.") 258 | launcher_agent_group.shutdown() 259 | 260 | logger.debug("Stopping logging server.") 261 | 262 | if stop_logging_event is not None: 263 | stop_logging_event.set() 264 | if log_process is not None: 265 | log_process.kill() 266 | 267 | 268 | @dataclass 269 | class LaunchResult(Generic[FunctionR]): 270 | """Container for objects returned from workers after successful launches.""" 271 | 272 | results: dict[str, list[FunctionR]] # [hostname][local_rank] -> FunctionR 273 | 274 | @classmethod 275 | def from_returns(cls, hostnames: list[str], return_values: list[list[FunctionR]]) -> Self: # noqa: D102 276 | return cls(results=dict(zip(hostnames, return_values))) 277 | 278 | def index(self, hostname: str, locak_rank: int) -> FunctionR: 279 | """Get return value from worker by host and local rank.""" 280 | return self.results[hostname][locak_rank] 281 | 282 | def rank(self, i: int) -> FunctionR: 283 | """Get return value from worker by global rank.""" 284 | for results_per_host in self.results.values(): 285 | if i < len(results_per_host): 286 | return results_per_host[i] 287 | i -= len(results_per_host) 288 | raise IndexError 289 | -------------------------------------------------------------------------------- /src/torchrunx/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apoorvkh/torchrunx/44446340838d62e1996c716919b0b836554ba143/src/torchrunx/py.typed -------------------------------------------------------------------------------- /src/torchrunx/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apoorvkh/torchrunx/44446340838d62e1996c716919b0b836554ba143/src/torchrunx/utils/__init__.py -------------------------------------------------------------------------------- /src/torchrunx/utils/comm.py: -------------------------------------------------------------------------------- 1 | """Utilities for Launcher-Agent communication.""" 2 | 3 | from __future__ import annotations 4 | 5 | __all__ = [ 6 | "AgentPayload", 7 | "AgentStatus", 8 | "ExceptionFromWorker", 9 | "LauncherAgentGroup", 10 | "LauncherPayload", 11 | "get_open_port", 12 | ] 13 | 14 | import datetime 15 | import socket 16 | from contextlib import closing 17 | from dataclasses import dataclass, field 18 | from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, TypeVar 19 | 20 | import cloudpickle 21 | import torch.distributed as dist 22 | from typing_extensions import Self 23 | 24 | from .errors import AgentFailedError, ExceptionFromWorker, WorkerFailedError 25 | 26 | if TYPE_CHECKING: 27 | from torch.distributed.elastic.multiprocessing.api import RunProcsResult 28 | 29 | 30 | def get_open_port() -> int: 31 | """Return an open port number.""" 32 | with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: 33 | s.bind(("", 0)) 34 | return s.getsockname()[1] 35 | 36 | 37 | ObjectT = TypeVar("ObjectT", bound=Any) 38 | FunctionR = TypeVar("FunctionR") 39 | 40 | 41 | @dataclass 42 | class LauncherAgentGroup(Generic[FunctionR]): 43 | """Initializes a GLOO distributed process group between launcher and all agents.""" 44 | 45 | launcher_hostname: str 46 | launcher_port: int 47 | world_size: int 48 | rank: int 49 | 50 | def __post_init__(self) -> None: 51 | """Initialize process group. 52 | 53 | Raises: 54 | torch.distributed.DistStoreError: if group initialization times out. 55 | """ 56 | self.group = dist.init_process_group( 57 | backend="gloo", 58 | world_size=self.world_size, 59 | rank=self.rank, 60 | store=dist.TCPStore( # pyright: ignore [reportPrivateImportUsage] 61 | host_name=self.launcher_hostname, 62 | port=self.launcher_port, 63 | world_size=self.world_size, 64 | is_master=(self.rank == 0), 65 | ), 66 | timeout=datetime.timedelta(seconds=30), 67 | ) 68 | 69 | def _all_gather(self, obj: ObjectT) -> list[ObjectT]: 70 | """Gather object from each rank to list (in rank-order). 71 | 72 | Raises: 73 | AgentFailedError: if any agent fails (observed by this communication). 74 | """ 75 | try: 76 | rank_obj = cloudpickle.dumps((self.rank, obj)) 77 | all_gather_list = [b""] * self.world_size 78 | 79 | dist.all_gather_object( 80 | object_list=all_gather_list, obj=rank_obj, group=self.group 81 | ) # raises RuntimeError if timeout 82 | 83 | rank_obj_list: list[tuple[int, ObjectT]] = sorted( 84 | [cloudpickle.loads(o) for o in all_gather_list] 85 | ) 86 | return [obj for _, obj in rank_obj_list] 87 | except RuntimeError as e: 88 | # occurs if launcher or any agent dies and communication times out 89 | raise AgentFailedError from e 90 | 91 | def sync_payloads( 92 | self, 93 | payload: LauncherPayload | AgentPayload, 94 | ) -> tuple[LauncherPayload, list[AgentPayload]]: 95 | """All-gather payloads across launcher and all agents.""" 96 | payloads = self._all_gather(payload) 97 | launcher_payload: LauncherPayload = payloads[0] # pyright: ignore [reportAssignmentType] 98 | agent_payloads: list[AgentPayload] = payloads[1:] # pyright: ignore [reportAssignmentType] 99 | return launcher_payload, agent_payloads 100 | 101 | def sync_agent_statuses( 102 | self, status: AgentStatus[FunctionR] | None 103 | ) -> list[AgentStatus[FunctionR]]: 104 | """All-gather agent statuses across launcher and all agents.""" 105 | # only launcher has status = None 106 | agent_statuses: list[AgentStatus[FunctionR]] = self._all_gather(status)[1:] # pyright: ignore [reportAssignmentType] 107 | return agent_statuses 108 | 109 | def shutdown(self) -> None: 110 | """Terminate process group.""" 111 | dist.destroy_process_group(group=self.group) 112 | 113 | 114 | @dataclass 115 | class LauncherPayload: 116 | """Payload from launcher to agents with runtime information.""" 117 | 118 | fn: Callable 119 | hostnames: list[str] 120 | worker_global_ranks: list[list[int]] 121 | worker_world_size: int 122 | backend: Literal["nccl", "gloo", "mpi", "ucc"] | None 123 | timeout: int 124 | 125 | 126 | @dataclass 127 | class AgentPayload: 128 | """Payload corresponding to each agent.""" 129 | 130 | hostname: str 131 | port: int 132 | process_id: int 133 | 134 | 135 | @dataclass 136 | class AgentStatus(Generic[FunctionR]): 137 | """Status of each agent (to be synchronized in LauncherAgentGroup). 138 | 139 | Attributes: 140 | state: Whether the agent is running, failed, or done. 141 | return_values: Objects returned (or exceptions raised) by workers (indexed by local rank). 142 | """ 143 | 144 | state: Literal["running", "failed", "done"] 145 | return_values: list[FunctionR | WorkerFailedError | ExceptionFromWorker] = field( 146 | default_factory=list 147 | ) # indexed by local rank 148 | 149 | @classmethod 150 | def from_result(cls, result: RunProcsResult | None) -> Self: 151 | """Convert RunProcsResult (from polling worker process context) to AgentStatus.""" 152 | if result is None: 153 | return cls(state="running") 154 | 155 | for local_rank, failure in result.failures.items(): 156 | result.return_values[local_rank] = WorkerFailedError(failure.message) 157 | 158 | return_values = [result.return_values[key] for key in sorted(result.return_values.keys())] 159 | 160 | failed = any(isinstance(v, (ExceptionFromWorker, WorkerFailedError)) for v in return_values) 161 | state = "failed" if failed else "done" 162 | 163 | return cls( 164 | state=state, 165 | return_values=return_values, 166 | ) 167 | -------------------------------------------------------------------------------- /src/torchrunx/utils/environment.py: -------------------------------------------------------------------------------- 1 | """Utilities for determining hosts and workers in environment.""" 2 | 3 | from __future__ import annotations 4 | 5 | from typing import Literal 6 | 7 | from typing_extensions import TypeAlias 8 | 9 | __all__ = [ 10 | "auto_hosts", 11 | "build_launch_command", 12 | "execute_command", 13 | "get_cpus_per_host", 14 | "get_gpus_per_host", 15 | "in_slurm_job", 16 | "slurm_hosts", 17 | ] 18 | 19 | import ipaddress 20 | import os 21 | import shlex 22 | import socket 23 | import subprocess 24 | import sys 25 | from pathlib import Path 26 | 27 | import fabric 28 | 29 | Hostnames: TypeAlias = list[str] 30 | WorkersPerHost: TypeAlias = list[int] 31 | 32 | 33 | def resolve_environment( 34 | hostnames: list[str] | Literal["auto", "slurm"], 35 | workers_per_host: int | list[int] | Literal["cpu", "gpu"], 36 | *, 37 | ssh_config_file: str | os.PathLike | None = None, 38 | ) -> tuple[Hostnames, WorkersPerHost]: 39 | if hostnames == "auto": 40 | hostnames = auto_hosts() 41 | elif hostnames == "slurm": 42 | hostnames = slurm_hosts() 43 | 44 | if isinstance(workers_per_host, int): 45 | workers_per_host = [workers_per_host] * len(hostnames) 46 | elif workers_per_host == "cpu": 47 | workers_per_host = get_cpus_per_host(hostnames, ssh_config_file=ssh_config_file) 48 | elif workers_per_host == "gpu": 49 | gpus_per_host: list[int] = get_gpus_per_host(hostnames, ssh_config_file=ssh_config_file) 50 | if any(g == 0 for g in gpus_per_host): 51 | hosts_without_gpus = [h for h, g in zip(hostnames, gpus_per_host) if g == 0] 52 | msg = f'workers_per_host="gpu", but no GPUs detected on: {hosts_without_gpus}.' 53 | raise RuntimeError(msg) 54 | workers_per_host = gpus_per_host 55 | 56 | return hostnames, workers_per_host 57 | 58 | 59 | def auto_hosts() -> list[str]: 60 | """Automatically determine hostnames to launch to.""" 61 | if in_slurm_job(): 62 | return slurm_hosts() 63 | return ["localhost"] 64 | 65 | 66 | def in_slurm_job() -> bool: 67 | """Check if current process is running in a Slurm allocation.""" 68 | return "SLURM_JOB_ID" in os.environ or "SLURM_JOBID" in os.environ 69 | 70 | 71 | def slurm_hosts() -> list[str]: 72 | """Retrieves hostnames of Slurm-allocated nodes.""" 73 | if not in_slurm_job(): 74 | msg = "Not in a SLURM job" 75 | raise RuntimeError(msg) 76 | 77 | return subprocess.check_output(["scontrol", "show", "hostnames"]).decode().strip().split("\n") 78 | 79 | 80 | def get_cpus_per_host( 81 | hostnames: list[str], *, ssh_config_file: str | os.PathLike | None = None 82 | ) -> list[int]: 83 | """Count the number of GPUs on each host.""" 84 | python = shlex.quote(sys.executable) 85 | command = f"{python} -c \"import os; print(len(os.sched_getaffinity(0)), end='')\"" 86 | return [ 87 | int( 88 | execute_command( 89 | command, hostname, ssh_config_file=ssh_config_file, return_stdout_stderr=True 90 | )[0] 91 | ) 92 | for hostname in hostnames 93 | ] 94 | 95 | 96 | def get_gpus_per_host( 97 | hostnames: list[str], *, ssh_config_file: str | os.PathLike | None = None 98 | ) -> list[int]: 99 | """Count the number of GPUs on each host.""" 100 | python = shlex.quote(sys.executable) 101 | command = f"{python} -c \"import torch; print(torch.cuda.device_count(), end='')\"" 102 | return [ 103 | int( 104 | execute_command( 105 | command, 106 | hostname, 107 | ssh_config_file=ssh_config_file, 108 | return_stdout_stderr=True, 109 | )[0] 110 | ) 111 | for hostname in hostnames 112 | ] 113 | 114 | 115 | def build_launch_command( 116 | launcher_hostname: str, 117 | launcher_port: int, 118 | logger_port: int, 119 | world_size: int, 120 | rank: int, 121 | env_vars: dict[str, str], 122 | env_file: str | os.PathLike | None, 123 | hostname: str, 124 | ) -> str: 125 | """Generator for command to launch torchrunx on an agent.""" 126 | # shlex.quote prevents shell injection here (resolves S602 in execute_command) 127 | 128 | commands = [] 129 | 130 | commands.append(f"cd {shlex.quote(str(Path.cwd()))}") 131 | 132 | env_exports = [shlex.quote(f"{k}={v}") for k, v in env_vars.items()] 133 | if len(env_exports) > 0: 134 | commands.append("export " + " ".join(env_exports)) 135 | 136 | if env_file is not None: 137 | commands.append("source " + shlex.quote(str(env_file))) 138 | 139 | python = shlex.quote(sys.executable) 140 | launcher_hostname = shlex.quote(launcher_hostname) 141 | hostname = shlex.quote(hostname) 142 | 143 | commands.append( 144 | f"{python} -u -m torchrunx " 145 | f"--launcher-hostname {launcher_hostname} " 146 | f"--launcher-port {launcher_port} " 147 | f"--logger-port {logger_port} " 148 | f"--world-size {world_size} " 149 | f"--rank {rank} " 150 | f"--hostname {hostname}", 151 | ) 152 | 153 | return " && ".join(commands) 154 | 155 | 156 | def execute_command( 157 | command: str, 158 | hostname: str, 159 | *, 160 | ssh_config_file: str | os.PathLike | None = None, 161 | return_stdout_stderr: bool = False, 162 | ) -> tuple[str, str]: 163 | """Run a command on local or remote host (using SSH).""" 164 | is_localhost = True 165 | _hostname_or_ip = hostname 166 | try: 167 | _ip = ipaddress.ip_address(_hostname_or_ip) 168 | except ValueError: 169 | _ip = ipaddress.ip_address(socket.gethostbyname(_hostname_or_ip)) 170 | if not _ip.is_loopback: 171 | # compare local interface addresses between host and localhost 172 | _host_addrs = [addr[4][0] for addr in socket.getaddrinfo(str(_ip), None)] 173 | _localhost_addrs = [addr[4][0] for addr in socket.getaddrinfo(socket.gethostname(), None)] 174 | is_localhost = len(set(_host_addrs) & set(_localhost_addrs)) > 0 175 | 176 | if is_localhost: 177 | # S602: subprocess.Popen is called with shell=True (https://docs.python.org/3.9/library/subprocess.html#security-considerations) 178 | # Made sure to shlex.quote arguments in build_command to prevent shell injection 179 | process = subprocess.Popen( # noqa: S602 180 | command, 181 | shell=True, 182 | text=True, 183 | stdout=subprocess.PIPE, 184 | stderr=subprocess.PIPE, 185 | ) 186 | 187 | if return_stdout_stderr: 188 | stdout, stderr = process.communicate() 189 | return stdout, stderr 190 | else: 191 | runtime_ssh_path = ssh_config_file 192 | if isinstance(ssh_config_file, os.PathLike): 193 | runtime_ssh_path = str(ssh_config_file) 194 | 195 | with fabric.Connection( 196 | host=hostname, 197 | config=fabric.Config(runtime_ssh_path=runtime_ssh_path), 198 | ) as conn: 199 | promise = conn.run(command, asynchronous=True, hide=True) 200 | 201 | if return_stdout_stderr: 202 | results = promise.join() 203 | return results.stdout, results.stderr 204 | 205 | return ("", "") 206 | -------------------------------------------------------------------------------- /src/torchrunx/utils/errors.py: -------------------------------------------------------------------------------- 1 | """Exception classes for agents and workers.""" 2 | 3 | from dataclasses import dataclass 4 | 5 | __all__ = [ 6 | "AgentFailedError", 7 | "ExceptionFromWorker", 8 | "WorkerFailedError", 9 | ] 10 | 11 | 12 | class AgentFailedError(Exception): 13 | """Raised if agent fails (e.g. if signal received).""" 14 | 15 | 16 | class WorkerFailedError(Exception): 17 | """Raised if a worker fails (e.g. if signal recieved or segmentation fault).""" 18 | 19 | 20 | @dataclass 21 | class ExceptionFromWorker: 22 | """Container for exceptions raised inside workers (from user script).""" 23 | 24 | exception: Exception 25 | -------------------------------------------------------------------------------- /src/torchrunx/utils/log_handling.py: -------------------------------------------------------------------------------- 1 | """Utilities for intercepting logs in worker processes and handling these in the Launcher.""" 2 | 3 | from __future__ import annotations 4 | 5 | __all__ = [ 6 | "RedirectHandler", 7 | "default_handlers", 8 | "file_handlers", 9 | "get_handler_filter", 10 | ] 11 | 12 | import datetime 13 | import logging 14 | import os 15 | from logging import LogRecord 16 | from pathlib import Path 17 | from typing import Callable 18 | 19 | 20 | def get_handler_filter( 21 | hostname: str, 22 | local_rank: int | None, # None indicates agent 23 | log_level: int = logging.NOTSET, 24 | ) -> Callable[[LogRecord], bool]: 25 | """Get an agent- or worker- specific filter to apply to :obj:`logging.Handler`.""" 26 | return lambda record: ( 27 | record.hostname == hostname # pyright: ignore [reportAttributeAccessIssue] 28 | and record.local_rank == local_rank # pyright: ignore [reportAttributeAccessIssue] 29 | and record.levelno >= log_level 30 | ) 31 | 32 | 33 | class RedirectHandler(logging.Handler): 34 | """For handling logs from hostname/rank with a corresponding logger in the launcher process.""" 35 | 36 | def emit(self, record: LogRecord) -> None: 37 | """Handle log record using corresponding logger.""" 38 | logger = logging.getLogger(record.name) 39 | if logger.isEnabledFor(record.levelno): 40 | logger.handle(record) 41 | 42 | 43 | def file_handlers( 44 | hostnames: list[str], 45 | workers_per_host: list[int], 46 | log_dir: str | os.PathLike = Path("torchrunx_logs"), 47 | log_level: int = logging.NOTSET, 48 | ) -> list[logging.Handler]: 49 | """Handler builder function for writing logs for all workers/agents to a directory. 50 | 51 | Files are named with hostname and the local_rank (for workers). 52 | """ 53 | handlers = [] 54 | 55 | timestamp = datetime.datetime.now().isoformat(timespec="seconds") 56 | log_dir = Path(log_dir) / timestamp 57 | log_dir.mkdir(parents=True, exist_ok=True) 58 | 59 | formatter = logging.Formatter( 60 | "%(asctime)s:%(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" 61 | ) 62 | 63 | for hostname, num_workers in zip(hostnames, workers_per_host): 64 | for local_rank in [None, *range(num_workers)]: 65 | local_rank_str = f"[{local_rank}]" if local_rank is not None else "" 66 | file_path = log_dir / f"{hostname}{local_rank_str}.log" 67 | 68 | h = logging.FileHandler(file_path) 69 | h.addFilter(get_handler_filter(hostname, local_rank, log_level=log_level)) 70 | h.setFormatter(formatter) 71 | 72 | handlers.append(h) 73 | 74 | return handlers 75 | 76 | 77 | def default_handlers(hostnames: list[str], workers_per_host: list[int]) -> list[logging.Handler]: 78 | """Constructs default :obj:`logging.Handler` objects. 79 | 80 | Logs for the rank 0 agent and rank 0 worker are redirected to loggers in the launcher process. 81 | Logs for all hosts/workers are written to files in ``$TORCHRUNX_LOG_DIR`` (named by timestamp, 82 | hostname, local_rank). 83 | """ 84 | log_dir = Path(os.environ.get("TORCHRUNX_LOG_DIR", "torchrunx_logs")) 85 | 86 | file_log_level = os.environ.get("TORCHRUNX_LOG_LEVEL", "INFO") 87 | if file_log_level.isdigit(): 88 | file_log_level = int(file_log_level) 89 | elif file_log_level in logging._nameToLevel: # noqa: SLF001 90 | file_log_level = logging._nameToLevel[file_log_level] # noqa: SLF001 91 | else: 92 | msg = ( 93 | f"Invalid value for $TORCHRUNX_LOG_LEVEL: {file_log_level}. " 94 | f"Should be a positive integer or any of: {', '.join(logging._nameToLevel.keys())}." # noqa: SLF001 95 | ) 96 | raise ValueError(msg) 97 | 98 | redirect_agent_0_handler = RedirectHandler() 99 | redirect_agent_0_handler.addFilter(get_handler_filter(hostnames[0], None)) 100 | 101 | redirect_worker_0_handler = RedirectHandler() 102 | redirect_worker_0_handler.addFilter(get_handler_filter(hostnames[0], 0)) 103 | 104 | return [ 105 | redirect_agent_0_handler, 106 | redirect_worker_0_handler, 107 | *file_handlers(hostnames, workers_per_host, log_dir=log_dir, log_level=file_log_level), 108 | ] 109 | -------------------------------------------------------------------------------- /src/torchrunx/utils/log_streaming.py: -------------------------------------------------------------------------------- 1 | """Utilities for intercepting logs in worker processes and handling these in the Launcher.""" 2 | 3 | from __future__ import annotations 4 | 5 | __all__ = [ 6 | "LoggingServerArgs", 7 | "log_records_to_socket", 8 | "redirect_stdio_to_logger", 9 | "start_logging_server", 10 | ] 11 | 12 | import logging 13 | import os 14 | import pickle 15 | import signal 16 | import struct 17 | import sys 18 | from dataclasses import dataclass 19 | from logging import Handler, Logger 20 | from logging.handlers import SocketHandler 21 | from multiprocessing.synchronize import Event as EventClass 22 | from socketserver import StreamRequestHandler, ThreadingTCPServer 23 | from threading import Thread 24 | from typing import Callable 25 | 26 | import cloudpickle 27 | from typing_extensions import Self 28 | 29 | ## Launcher utilities 30 | 31 | 32 | class _LogRecordSocketReceiver(ThreadingTCPServer): 33 | """TCP server for recieving Agent/Worker log records in Launcher. 34 | 35 | Uses threading to avoid bottlenecks (i.e. "out-of-order" logs in Launcher process). 36 | """ 37 | 38 | def __init__(self, host: str, port: int, handlers: list[Handler]) -> None: 39 | """Processing streamed bytes as LogRecord objects.""" 40 | self.host = host 41 | self.port = port 42 | 43 | class _LogRecordStreamHandler(StreamRequestHandler): 44 | def handle(self) -> None: 45 | while True: 46 | chunk_size = 4 47 | chunk = self.connection.recv(chunk_size) 48 | if len(chunk) < chunk_size: 49 | break 50 | slen = struct.unpack(">L", chunk)[0] 51 | chunk = self.connection.recv(slen) 52 | while len(chunk) < slen: 53 | chunk = chunk + self.connection.recv(slen - len(chunk)) 54 | obj = pickle.loads(chunk) 55 | 56 | ## Transform log record 57 | 58 | record: WorkerLogRecord = logging.makeLogRecord(obj) # pyright: ignore [reportAssignmentType] 59 | 60 | if record.name != "root": 61 | record.msg = f"{record.name}:{record.msg}" 62 | 63 | record.name = f"torchrunx.{record.hostname}" 64 | if record.local_rank is not None: 65 | record.name += f".{record.local_rank}" 66 | 67 | ## Handle log record 68 | 69 | for handler in handlers: 70 | handler.handle(record) 71 | 72 | super().__init__( 73 | server_address=(host, port), 74 | RequestHandlerClass=_LogRecordStreamHandler, 75 | bind_and_activate=True, 76 | ) 77 | self.daemon_threads = True 78 | 79 | def shutdown(self) -> None: 80 | """Override BaseServer.shutdown() with added timeout (to avoid hanging).""" 81 | self._BaseServer__shutdown_request = True 82 | self._BaseServer__is_shut_down.wait(timeout=3) # pyright: ignore[reportAttributeAccessIssue] 83 | 84 | 85 | @dataclass 86 | class LoggingServerArgs: 87 | """Arguments for starting a :class:`_LogRecordSocketReceiver`.""" 88 | 89 | handler_factory: Callable[[], list[Handler]] 90 | logging_hostname: str 91 | logging_port: int 92 | 93 | def serialize(self) -> bytes: 94 | """Serialize :class:`LoggingServerArgs` for passing to a new process.""" 95 | return cloudpickle.dumps(self) 96 | 97 | @classmethod 98 | def from_bytes(cls, serialized: bytes) -> Self: 99 | """Deserialize bytes to :class:`LoggingServerArgs`.""" 100 | return cloudpickle.loads(serialized) 101 | 102 | 103 | def start_logging_server(serialized_args: bytes, stop_event: EventClass) -> None: 104 | """Serve :class:`_LogRecordSocketReceiver` until stop event triggered.""" 105 | args = LoggingServerArgs.from_bytes(serialized_args) 106 | 107 | log_handlers = args.handler_factory() 108 | 109 | log_receiver = _LogRecordSocketReceiver( 110 | host=args.logging_hostname, 111 | port=args.logging_port, 112 | handlers=log_handlers, 113 | ) 114 | 115 | try: 116 | log_receiver.serve_forever() 117 | except KeyboardInterrupt: 118 | sys.exit(128 + signal.SIGINT) 119 | 120 | while not stop_event.is_set(): 121 | pass 122 | 123 | log_receiver.shutdown() 124 | log_receiver.server_close() 125 | 126 | 127 | ## Agent/worker utilities 128 | 129 | 130 | def redirect_stdio_to_logger(logger: Logger) -> None: 131 | """Redirect stderr/stdout: send output to logger at every flush.""" 132 | logging.captureWarnings(capture=True) 133 | 134 | def redirect_fd_to_logger(read_fd: int, level: int) -> None: 135 | for line in os.fdopen(read_fd): 136 | logger.log(level, line.rstrip()) 137 | 138 | # create (r, w) pipe and start logging all outputs from r 139 | read_out_fd, write_out_fd = os.pipe() 140 | Thread( 141 | target=redirect_fd_to_logger, 142 | kwargs={"read_fd": read_out_fd, "level": logging.INFO}, 143 | daemon=True, 144 | ).start() 145 | # flush buffer before redirecting stdout 146 | sys.stdout.flush() 147 | # pipe: r <-> stdout instead of r <-> w 148 | os.dup2(write_out_fd, sys.stdout.fileno()) # set stdout fd to pipe 149 | os.close(write_out_fd) 150 | 151 | # repeat for stderr 152 | read_err_fd, write_err_fd = os.pipe() 153 | Thread( 154 | target=redirect_fd_to_logger, 155 | kwargs={"read_fd": read_err_fd, "level": logging.ERROR}, 156 | daemon=True, 157 | ).start() 158 | sys.stderr.flush() 159 | os.dup2(write_err_fd, sys.stderr.fileno()) 160 | os.close(write_err_fd) 161 | 162 | 163 | @dataclass 164 | class WorkerLogRecord(logging.LogRecord): 165 | """Adding hostname, local_rank attributes to LogRecord. local_rank=None for Agent.""" 166 | 167 | hostname: str 168 | local_rank: int | None 169 | 170 | @classmethod 171 | def from_record(cls, record: logging.LogRecord, hostname: str, local_rank: int | None) -> Self: 172 | record.hostname = hostname 173 | record.local_rank = local_rank 174 | record.__class__ = cls 175 | return record # pyright: ignore [reportReturnType] 176 | 177 | 178 | def log_records_to_socket( 179 | hostname: str, 180 | local_rank: int | None, # None indicates agent 181 | logger_hostname: str, 182 | logger_port: int, 183 | ) -> None: 184 | """Encode LogRecords with hostname/local_rank. Send to TCP socket on Launcher.""" 185 | logging.root.setLevel(logging.NOTSET) 186 | 187 | old_factory = logging.getLogRecordFactory() 188 | 189 | def record_factory(*args, **kwargs) -> WorkerLogRecord: # noqa: ANN002, ANN003 190 | record = old_factory(*args, **kwargs) 191 | return WorkerLogRecord.from_record(record, hostname, local_rank) 192 | 193 | logging.setLogRecordFactory(record_factory) 194 | 195 | logging.root.addHandler(SocketHandler(host=logger_hostname, port=logger_port)) 196 | -------------------------------------------------------------------------------- /src/torchrunx/worker.py: -------------------------------------------------------------------------------- 1 | """Arguments and entrypoint for the worker processes.""" 2 | 3 | from __future__ import annotations 4 | 5 | import datetime 6 | import logging 7 | import os 8 | import sys 9 | import traceback 10 | from dataclasses import asdict, dataclass 11 | from typing import Any, Callable, Literal 12 | 13 | import cloudpickle 14 | import torch.distributed as dist 15 | from typing_extensions import Self 16 | 17 | from .utils.errors import ExceptionFromWorker 18 | from .utils.log_streaming import log_records_to_socket, redirect_stdio_to_logger 19 | 20 | __all__ = ["WorkerArgs", "worker_entrypoint"] 21 | 22 | 23 | @dataclass 24 | class WorkerArgs: 25 | """Arguments passed from agent to spawned workers.""" 26 | 27 | function: Callable 28 | logger_hostname: str 29 | logger_port: int 30 | master_hostname: str 31 | master_port: int 32 | backend: Literal["nccl", "gloo", "mpi", "ucc"] | None 33 | rank: int 34 | local_rank: int 35 | node_rank: int 36 | local_world_size: int 37 | world_size: int 38 | hostname: str 39 | timeout: int 40 | 41 | def serialize(self) -> bytes: 42 | """Arguments must be serialized (to bytes) before passed to spawned workers.""" 43 | return cloudpickle.dumps(asdict(self)) 44 | 45 | @classmethod 46 | def from_bytes(cls, b: bytes) -> Self: 47 | """Deserialize the bytes back into a WorkerArgs object.""" 48 | return cls(**cloudpickle.loads(b)) 49 | 50 | 51 | def worker_entrypoint(serialized_worker_args: bytes) -> Any | ExceptionFromWorker: 52 | """Function called by spawned worker processes. 53 | 54 | Workers first prepare a process group (for communicating with all other workers). 55 | They then invoke the user-provided function. 56 | Logs are transmitted to the launcher process. 57 | """ 58 | worker_args = WorkerArgs.from_bytes(serialized_worker_args) 59 | 60 | # Start logging to the logging server (i.e. the launcher) 61 | 62 | log_records_to_socket( 63 | hostname=worker_args.hostname, 64 | local_rank=worker_args.local_rank, 65 | logger_hostname=worker_args.logger_hostname, 66 | logger_port=worker_args.logger_port, 67 | ) 68 | 69 | logger = logging.getLogger() 70 | redirect_stdio_to_logger(logger) 71 | 72 | # Set rank/world environment variables 73 | 74 | os.environ["RANK"] = str(worker_args.rank) 75 | os.environ["LOCAL_RANK"] = str(worker_args.local_rank) 76 | os.environ["GROUP_RANK"] = str(worker_args.node_rank) 77 | os.environ["LOCAL_WORLD_SIZE"] = str(worker_args.local_world_size) 78 | os.environ["WORLD_SIZE"] = str(worker_args.world_size) 79 | os.environ["MASTER_ADDR"] = worker_args.master_hostname 80 | os.environ["MASTER_PORT"] = str(worker_args.master_port) 81 | 82 | # Prepare the process group (e.g. for communication within the user's function) 83 | 84 | if worker_args.backend is not None: 85 | backend = worker_args.backend 86 | 87 | dist.init_process_group( 88 | backend=backend, 89 | world_size=worker_args.world_size, 90 | rank=worker_args.rank, 91 | store=dist.TCPStore( # pyright: ignore [reportPrivateImportUsage] 92 | host_name=worker_args.master_hostname, 93 | port=worker_args.master_port, 94 | world_size=worker_args.world_size, 95 | is_master=(worker_args.rank == 0), 96 | ), 97 | timeout=datetime.timedelta(seconds=worker_args.timeout), 98 | ) 99 | 100 | # Invoke the user's function on this worker 101 | 102 | try: 103 | return worker_args.function() 104 | except Exception as e: 105 | traceback.print_exc() 106 | return ExceptionFromWorker(exception=e) 107 | finally: 108 | sys.stdout.flush() 109 | sys.stderr.flush() 110 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apoorvkh/torchrunx/44446340838d62e1996c716919b0b836554ba143/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_ci.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import os 3 | import tempfile 4 | import time 5 | from pathlib import Path 6 | from typing import NoReturn 7 | 8 | import pytest 9 | import torch 10 | import torch.distributed as dist 11 | 12 | import torchrunx as trx 13 | 14 | 15 | def test_simple_localhost() -> None: 16 | def dist_func() -> torch.Tensor: 17 | rank = int(os.environ["RANK"]) 18 | 19 | w = torch.rand((100, 100)) if rank == 0 else torch.zeros((100, 100)) 20 | 21 | dist.broadcast(w, 0) 22 | 23 | i = torch.rand((500, 100)) # batch, dim 24 | o = torch.matmul(i, w) 25 | 26 | dist.all_reduce(o, op=dist.ReduceOp.SUM) 27 | 28 | print(i) 29 | 30 | return o.detach() 31 | 32 | tmp = tempfile.mkdtemp() 33 | os.environ["TORCHRUNX_DIR"] = tmp 34 | 35 | r = trx.Launcher( 36 | workers_per_host=2, 37 | backend="gloo", 38 | ).run(dist_func) 39 | 40 | assert torch.all(r.rank(0) == r.rank(1)) 41 | 42 | 43 | def test_logging() -> None: 44 | def dist_func() -> None: 45 | rank = int(os.environ["RANK"]) 46 | print(f"worker rank: {rank}") 47 | 48 | tmp = tempfile.mkdtemp() 49 | os.environ["TORCHRUNX_LOG_DIR"] = tmp 50 | 51 | num_workers = 2 52 | 53 | before_timestamp = datetime.datetime.now() 54 | 55 | time.sleep(1) 56 | 57 | trx.Launcher( 58 | workers_per_host=num_workers, 59 | backend="gloo", 60 | ).run( 61 | dist_func, 62 | ) 63 | 64 | after_timestamp = datetime.datetime.now() 65 | 66 | log_dirs = next(os.walk(tmp), (None, [], None))[1] 67 | 68 | assert len(log_dirs) == 1 69 | 70 | # this should error if mis-formatted 71 | log_timestamp = datetime.datetime.fromisoformat(log_dirs[0]) 72 | 73 | assert before_timestamp <= log_timestamp <= after_timestamp 74 | 75 | log_files = next(os.walk(f"{tmp}/{log_dirs[0]}"), (None, None, []))[2] 76 | 77 | assert len(log_files) == num_workers + 1 78 | 79 | for file in log_files: 80 | with Path(f"{tmp}/{log_dirs[0]}/{file}").open() as f: 81 | contents = f.read() 82 | print(contents) 83 | if file.endswith("[0].log"): 84 | assert "worker rank: 0\n" in contents 85 | elif file.endswith("[1].log"): 86 | assert "worker rank: 1\n" in contents 87 | 88 | 89 | def test_error() -> None: 90 | def error_func() -> NoReturn: 91 | msg = "abcdefg" 92 | raise ValueError(msg) 93 | 94 | tmp = tempfile.mkdtemp() 95 | os.environ["TORCHRUNX_DIR"] = tmp 96 | 97 | with pytest.raises(ValueError) as excinfo: # noqa: PT011 98 | trx.Launcher( 99 | workers_per_host=1, 100 | backend="gloo", 101 | ).run( 102 | error_func, 103 | ) 104 | 105 | assert "abcdefg" in str(excinfo.value) 106 | 107 | 108 | if __name__ == "__main__": 109 | test_simple_localhost() 110 | -------------------------------------------------------------------------------- /tests/test_func.py: -------------------------------------------------------------------------------- 1 | import os 2 | from functools import reduce 3 | from operator import add 4 | 5 | import torch 6 | import torch.distributed as dist 7 | 8 | import torchrunx as trx 9 | 10 | 11 | def test_launch() -> None: 12 | result = trx.Launcher(hostnames="slurm").run(simple_matmul) 13 | 14 | result_values = reduce(add, result.results.values()) 15 | 16 | t = True 17 | for i in range(len(result_values)): 18 | t = t and torch.all(result_values[i] == result_values[0]) 19 | 20 | assert t, "Not all tensors equal" 21 | 22 | 23 | def simple_matmul() -> torch.Tensor: 24 | rank = int(os.environ["RANK"]) 25 | local_rank = int(os.environ["LOCAL_RANK"]) 26 | device = torch.device(local_rank) if torch.cuda.is_available() else torch.device("cpu") 27 | 28 | if rank == 0: 29 | w = torch.rand((100, 100), device=device) # in_dim, out_dim 30 | else: 31 | w = torch.zeros((100, 100), device=device) 32 | 33 | dist.broadcast(w, 0) 34 | 35 | i = torch.rand((500, 100), device=device) # batch, dim 36 | o = torch.matmul(i, w) 37 | dist.all_reduce(o, op=dist.ReduceOp.SUM) 38 | print(i) 39 | return o.detach().cpu() 40 | 41 | 42 | if __name__ == "__main__": 43 | test_launch() 44 | -------------------------------------------------------------------------------- /tests/test_submitit.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import copy 4 | 5 | import submitit # pyright: ignore [reportMissingImports] 6 | import torch 7 | from torch.utils.data import Dataset 8 | from transformers import ( # pyright: ignore [reportMissingImports] 9 | BertForMaskedLM, 10 | Trainer, 11 | TrainingArguments, 12 | ) 13 | 14 | import torchrunx as trx 15 | 16 | 17 | class DummyDataset(Dataset): 18 | def __init__(self, max_text_length: int = 16, num_samples: int = 20000) -> None: 19 | super().__init__() 20 | self.input_ids = torch.randint(0, 30522, (num_samples, max_text_length)) 21 | self.labels = copy.deepcopy(self.input_ids) 22 | 23 | def __len__(self) -> int: 24 | return len(self.input_ids) 25 | 26 | def __getitem__(self, index: int) -> dict[str, torch.Tensor]: 27 | return { 28 | "input_ids": self.input_ids[index], 29 | "labels": self.labels[index], 30 | } 31 | 32 | 33 | def main() -> None: 34 | model = BertForMaskedLM.from_pretrained("bert-base-uncased") 35 | train_dataset = DummyDataset() 36 | 37 | ## Training 38 | 39 | training_arguments = TrainingArguments( 40 | output_dir="output", 41 | do_train=True, 42 | per_device_train_batch_size=16, 43 | max_steps=20, 44 | ) 45 | 46 | trainer = Trainer( 47 | model=model, 48 | args=training_arguments, 49 | train_dataset=train_dataset, 50 | ) 51 | 52 | trainer.train() 53 | 54 | 55 | def launch() -> None: 56 | trx.Launcher(hostnames="slurm").run(main) 57 | 58 | 59 | def test_submitit() -> None: 60 | executor = submitit.SlurmExecutor(folder="logs") 61 | 62 | executor.update_parameters( 63 | time=60, 64 | nodes=1, 65 | ntasks_per_node=1, 66 | mem="32G", 67 | cpus_per_task=4, 68 | gpus_per_node=2, 69 | constraint="geforce3090", 70 | partition="3090-gcondo", 71 | stderr_to_stdout=True, 72 | use_srun=False, 73 | ) 74 | 75 | executor.submit(launch).result() 76 | 77 | 78 | if __name__ == "__main__": 79 | executor = submitit.SlurmExecutor(folder="logs") 80 | 81 | executor.update_parameters( 82 | time=60, 83 | nodes=1, 84 | ntasks_per_node=1, 85 | mem="32G", 86 | cpus_per_task=4, 87 | gpus_per_node=2, 88 | constraint="geforce3090", 89 | partition="3090-gcondo", 90 | stderr_to_stdout=True, 91 | use_srun=False, 92 | ) 93 | 94 | executor.submit(launch) 95 | -------------------------------------------------------------------------------- /tests/test_train_gpu.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import torch 4 | 5 | import torchrunx as trx 6 | 7 | 8 | class MLP(torch.nn.Module): 9 | def __init__(self) -> None: 10 | super().__init__() 11 | self.a = torch.nn.Linear(10, 10, bias=False) 12 | self.b = torch.nn.Linear(10, 1, bias=False) 13 | 14 | def forward(self, x: torch.Tensor) -> torch.Tensor: 15 | return self.b(self.a(x)) 16 | 17 | 18 | def worker() -> None: 19 | local_rank = int(os.environ["LOCAL_RANK"]) 20 | print("init model") 21 | model = MLP().to(local_rank) 22 | print("init ddp") 23 | ddp_model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank]) 24 | 25 | inp = torch.randn(10, 10).to(local_rank) 26 | print("train") 27 | 28 | for _ in range(20): 29 | output = ddp_model(inp) 30 | loss = output.sum() 31 | loss.backward() 32 | 33 | 34 | def test_distributed_train() -> None: 35 | trx.Launcher( 36 | backend="nccl", 37 | ).run(worker) 38 | 39 | 40 | if __name__ == "__main__": 41 | test_distributed_train() 42 | --------------------------------------------------------------------------------