├── tpu_pod_commander ├── __init__.py └── cli.py ├── setup.py ├── examples ├── run_job.py └── tpu_pod_setup.py ├── .gitignore ├── README.md └── LICENSE /tpu_pod_commander/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='tpu_pod_commander', 5 | version='0.1.7', 6 | license='Apache-2.0', 7 | description='TPU pod commander is a command line tool to manage cloud TPU pods.', 8 | url='https://github.com/young-geng/tpu_pod_commander', 9 | packages=find_packages(include=['tpu_pod_commander']), 10 | python_requires=">=3.8", 11 | install_requires=[ 12 | 'absl-py', 13 | 'mlxu>=0.2.0', 14 | ], 15 | entry_points={ 16 | 'console_scripts': [ 17 | 'tpc = tpu_pod_commander.cli:run_cli', 18 | ], 19 | }, 20 | classifiers=[ 21 | 'Development Status :: 3 - Alpha', 22 | 'Intended Audience :: Developers', 23 | 'License :: OSI Approved :: Apache Software License', 24 | 'Programming Language :: Python :: 3 :: Only', 25 | ], 26 | ) -------------------------------------------------------------------------------- /examples/run_job.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script demonstrates how to install software and conda evnironment on a TPU 3 | pod. You can run this setup with the following tpc command: 4 | 5 | tpc upload+launch run_job.py 6 | """ 7 | 8 | 9 | # Defines the bash script that will be executed on the TPU instance to set up 10 | # the environment. 11 | launch_script = r"""#! /bin/bash 12 | 13 | source ~/miniforge3/bin/activate mintext 14 | python /path/to/my/python/job.py 15 | 16 | read # This will pause the script so tmux session will not close immediately 17 | """ 18 | 19 | 20 | # Specify all the parameters to TPC via the configure_tpc function 21 | # Change these acchording to your project and zone and TPU pod name 22 | configure_tpc( # type: ignore 23 | project='my-gcp-project', 24 | zone='europe-west4-b', 25 | name='my-tpu-pod', 26 | upload_path='/path/to/my/data:/path/to/remote/data', 27 | launch_script=launch_script, 28 | ) -------------------------------------------------------------------------------- /examples/tpu_pod_setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script demonstrates how to install software and conda evnironment on a TPU 3 | pod. You can run this setup with the following tpc command: 4 | 5 | tpc launch tpu_pod_setup.py 6 | 7 | The envrionment dependencies specified here is token from the 8 | (mintext project)[https://github.com/young-geng/mintext]. 9 | """ 10 | 11 | 12 | # Defines the bash script that will be executed on the TPU instance to set up 13 | # the environment. 14 | launch_script = r"""#! /bin/bash 15 | 16 | sudo apt-get update && sudo apt-get install -y \ 17 | build-essential \ 18 | python-is-python3 \ 19 | tmux \ 20 | htop \ 21 | git \ 22 | nodejs \ 23 | bmon \ 24 | p7zip-full \ 25 | nfs-common 26 | 27 | 28 | # install miniforge 29 | rm -rf ~/Miniforge3-Linux-x86_64.sh 30 | wget -P ~/ https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh 31 | bash ~/Miniforge3-Linux-x86_64.sh -b 32 | 33 | 34 | cat > $HOME/tpu_environment.yml <<- EndOfFile 35 | name: mintext 36 | channels: 37 | - pytorch 38 | - conda-forge 39 | dependencies: 40 | - python=3.10 41 | - pip 42 | - numpy<2 43 | - scipy 44 | - matplotlib 45 | - seaborn 46 | - jupyter 47 | - tqdm 48 | - pytorch=2.3.0 49 | - cpuonly 50 | - pip: 51 | - -f https://storage.googleapis.com/jax-releases/libtpu_releases.html 52 | - jax[tpu]==0.4.28 53 | - scalax>=0.2.1 54 | - flax==0.8.3 55 | - optax==0.2.2 56 | - transformers==4.41.0 57 | - torch==2.3.0 58 | - orbax-checkpoint==0.5.14 59 | - tensorflow-cpu==2.16.1 60 | - sentencepiece 61 | - datasets 62 | - tpu_pod_commander>=0.1.1 63 | - mlxu>=0.2.0 64 | - einops 65 | - gcsfs 66 | EndOfFile 67 | 68 | 69 | # install dependencies 70 | source ~/miniforge3/bin/activate 71 | conda env create -f $HOME/tpu_environment.yml 72 | conda activate mintext 73 | conda clean -a -y 74 | """ 75 | 76 | 77 | # Specify all the parameters to TPC via the configure_tpc function 78 | # Change these acchording to your project and zone and TPU pod name 79 | configure_tpc( # type: ignore 80 | project='my-gcp-project', 81 | zone='europe-west4-b', 82 | name='my-tpu-pod', 83 | launch_script=launch_script, 84 | ) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TPU Pod Commander 2 | TPU Pod Commander is a package for setting up and launching jobs on Google Cloud TPU pods. 3 | 4 | ## Installation 5 | To install TPU Pod Commander, you need to intall the gcloud cli first. Follow 6 | [the instructions here](https://cloud.google.com/sdk/docs/install) to install it. 7 | After installing the gcloud cli, you can install TPU Pod Commander by running the following command: 8 | ```bash 9 | pip install tpu_pod_commander 10 | ``` 11 | 12 | 13 | ## Usage 14 | After installing TPU Pod Commander, the command `tpc` will be available in your 15 | shell. TPC commands are all organized in the following format: 16 | ```bash 17 | tpc [config_file.py] [--flags=value ...] 18 | ``` 19 | where `` is the action to perform, and paramters are specified jointly 20 | by the optional config file and the flags. There is a one-to-one correspondence 21 | between the flags and the parameters in the config file. When both are specified, 22 | the flags will override the parameters in the config file. 23 | 24 | 25 | ### Actions 26 | The following is a list of available actions: 27 | - `list`: List all TPU pods in a given zone of a project. 28 | - `create`: Create a TPU pod. 29 | - `delete`: Delete a TPU pod. 30 | - `queue`: Create a TPU pod via queued resources API. 31 | - `ls_queue`: List all queued TPU pods. 32 | - `cancel_queue`: Cancel a queued TPU pod. 33 | - `describe`: Get the details of a TPU pod. 34 | - `ips`: List the external IPs of all the hosts in a TPU pod. 35 | - `upload`: Upload files to a TPU pod. 36 | - `run`: Run a command on all the hosts of a TPU pod. 37 | - `launch`: Launch a shell script job in a tmux session on all the hosts of a TPU pod. 38 | - `check`: Check the status of a job running in the tmux session on a TPU pod. 39 | - `stop`: Stop a job running in the tmux session on a TPU pod. 40 | - `reboot`: Reboot all the hosts in a TPU pod. 41 | - `unlock`: Remove the libtpu lock files on all hosts of a TPU pod. 42 | - `stop+unlock`: Perform `stop` and `unlock` actions in sequence. 43 | - `relaunch`: Perform `stop` and `launch` actions in sequence. 44 | - `upload+launch`: Perform `upload` and `launch` actions in sequence. 45 | 46 | 47 | ### Config File and Flags 48 | The optional config file is a Python file that contains the parameters for the 49 | action. It should be in the following format: 50 | ```python 51 | configure_tpc( 52 | key=value, 53 | ... 54 | ) 55 | ``` 56 | Note that no import statement is needed in the config file to use the 57 | `configure_tpc` function. The paramters for `configure_tpc` has one-to-one 58 | correspondence with the flags for the action, so for example specifying 59 | `--zone=us-central1-a` in the command line flags is equivalent to specifying 60 | `zone='us-central1-a'` in the config file. When both are specified for one 61 | parameter, the flag will override the corresponding parameter in the config file. 62 | 63 | The following is a list of available paramters: 64 | - `zone`: The zone of the TPU pod. 65 | - `project`: The GCP project of the TPU pod. 66 | - `name`: The name of the TPU pod. 67 | - `accelerator_type`: The type and size of the TPU pod, for example, `v4-256`. 68 | - `runtime_version`: The runtime software version of the TPU pod. 69 | - `reserved`: Whether the TPU pod should be created under reserved quota, default to `False`. 70 | - `spot`: Whether the TPU pod should be created as a preemptible instance, default to `False`. 71 | - `upload_path`: a comma-separated list of `:` pairs to upload. 72 | - `upload_remove_remote`: Whether to remove the remote files before uploading. Default to `True`. 73 | - `command`: The command to run on the TPU pod. 74 | - `launch_script_path`: The path to load the content of the launch script. 75 | - `launch_script`: The content of the launch script. When both `launch_script_path` 76 | and `launch_script` are specified, the script content will be loaded from 77 | `launch_script_path` and override the `launch_script` parameter. 78 | - `launch_script_remote_path`: The remote path on TPU pod to save the launch script, 79 | default to `~/tpc_launch_script.sh`. 80 | - `tpu_user`: The username to use when connecting to the TPU pod. Default to current user. 81 | - `tmux_session_name`: The name of the tmux session to create when launching a job. 82 | Default to `tpc`. 83 | - `show_command`: Whether to show the gcloud command when excuting an action. Default to `True`. 84 | 85 | 86 | 87 | Not all parameters are needed for all actions. The following is a list of required 88 | parameters for each action: 89 | - **`list`**: `zone`, `project`. 90 | - **`create`**: `zone`, `project`, `name`, `accelerator_type`, `runtime_version`. 91 | - **`delete`**: `zone`, `project`, `name`. 92 | - **`queue`**: `zone`, `project`, `name`, `accelerator_type`, `runtime_version`. 93 | - **`ls_queue`**: `zone`, `project`. 94 | - **`cancel_queue`**: `zone`, `project`, `name`. 95 | - **`describe`**: `zone`, `project`, `name`. 96 | - **`ips`**: `zone`, `project`, `name`. 97 | - **`upload`**: `zone`, `project`, `name`, `upload_path`. 98 | - **`run`**: `zone`, `project`, `name`, `command`. 99 | - **`launch`**: `zone`, `project`, `name`, `launch_script_path` or `launch_script`. 100 | - **`check`**: `zone`, `project`, `name`. 101 | - **`stop`**: `zone`, `project`, `name`. 102 | - **`reboot`**: `zone`, `project`, `name`. 103 | - **`unlock`**: `zone`, `project`, `name`. 104 | - **`relaunch`**: `zone`, `project`, `name`, `launch_script_path` or `launch_script`. 105 | - **`upload+launch`**: `zone`, `project`, `name`, `upload_path`, `launch_script_path` or `launch_script`. 106 | 107 | 108 | ## Examples 109 | See the [examples](examples) directory for some example config files and 110 | the corresponding commands. 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /tpu_pod_commander/cli.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import re 4 | import tempfile 5 | import time 6 | from absl.flags import argparse_flags 7 | import mlxu 8 | 9 | 10 | FLAGS, FLAGS_DEF = mlxu.define_flags_with_default( 11 | zone=str, 12 | project=str, 13 | name=str, 14 | accelerator_type=str, 15 | runtime_version=str, 16 | reserved=bool, 17 | spot=bool, 18 | upload_path=str, 19 | upload_remove_remote=bool, 20 | command=str, 21 | launch_script_path=str, 22 | launch_script=str, 23 | launch_script_remote_path=str, 24 | tpu_user=str, 25 | tmux_session_name=str, 26 | show_command=bool, 27 | ) 28 | 29 | 30 | def configure_tpc(**kwargs): 31 | for key, value in kwargs.items(): 32 | if key not in FLAGS_DEF: 33 | raise ValueError(f"Invalid config key: {key}") 34 | elif getattr(FLAGS, key) is None: 35 | # If we haven't overridden the config with a flag, use the config 36 | setattr(FLAGS, key, value) 37 | 38 | 39 | def _assert_flags(**kwargs): 40 | for key in kwargs: 41 | assert getattr(FLAGS, key) is not None, f"Missing required flag: {key}" 42 | 43 | 44 | def _execute_shell(cmd, print_output=True): 45 | """ Run a command in shell and print its output """ 46 | if FLAGS.show_command: 47 | print(f'Running command: \n{cmd}\n') 48 | process = subprocess.Popen( 49 | cmd, 50 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, shell=True, 51 | env=os.environ, 52 | ) 53 | output_lines = [] 54 | while True: 55 | output = process.stdout.readline() 56 | if output == '' and process.poll() is not None: 57 | break 58 | if output: 59 | if print_output: 60 | print(output.strip()) 61 | output_lines.append(output.strip()) 62 | 63 | rc = process.poll() 64 | if rc != 0: 65 | raise ValueError(f"Command failed with return code {rc}") 66 | return rc, '\n'.join(output_lines) 67 | 68 | 69 | def _subcommand_list(): 70 | _assert_flags( 71 | zone=True, 72 | project=True, 73 | ) 74 | _execute_shell( 75 | f'gcloud compute tpus tpu-vm list ' 76 | f'--zone={FLAGS.zone} ' 77 | f'--project={FLAGS.project} ' 78 | f'--quiet ' 79 | ) 80 | 81 | 82 | def _subcommand_create(): 83 | _assert_flags( 84 | zone=True, 85 | project=True, 86 | name=True, 87 | accelerator_type=True, 88 | runtime_version=True, 89 | ) 90 | resource_type_flag = '' 91 | if FLAGS.reserved: 92 | resource_type_flag = '--reserved' 93 | elif FLAGS.spot: 94 | resource_type_flag = '--spot' 95 | _execute_shell( 96 | f'gcloud alpha compute tpus tpu-vm create {FLAGS.name} ' 97 | f'--zone={FLAGS.zone} ' 98 | f'--project={FLAGS.project} ' 99 | f'--version={FLAGS.runtime_version} ' 100 | f'--accelerator-type={FLAGS.accelerator_type} ' 101 | f'--quiet ' 102 | f'{resource_type_flag}' 103 | ) 104 | 105 | 106 | def _subcommand_delete(): 107 | _assert_flags( 108 | zone=True, 109 | project=True, 110 | name=True, 111 | ) 112 | _execute_shell( 113 | f'gcloud alpha compute tpus tpu-vm delete {FLAGS.name} ' 114 | f'--zone={FLAGS.zone} ' 115 | f'--project={FLAGS.project} ' 116 | f'--quiet ' 117 | ) 118 | 119 | 120 | def _subcommand_queue(): 121 | assert not FLAGS.reserved or not FLAGS.spot, "Cannot specify both reserved and spot" 122 | resource_type_flag = '' 123 | if FLAGS.reserved: 124 | resource_type_flag = '--reserved' 125 | elif FLAGS.spot: 126 | resource_type_flag = '--spot' 127 | 128 | _assert_flags( 129 | zone=True, 130 | project=True, 131 | name=True, 132 | accelerator_type=True, 133 | runtime_version=True, 134 | ) 135 | _execute_shell( 136 | f'gcloud alpha compute tpus queued-resources create {FLAGS.name} ' 137 | f'--node-id={FLAGS.name} ' 138 | f'--zone={FLAGS.zone} ' 139 | f'--project={FLAGS.project} ' 140 | f'--accelerator-type={FLAGS.accelerator_type} ' 141 | f'--runtime-version={FLAGS.runtime_version} ' 142 | f'--quiet ' 143 | f'{resource_type_flag}' 144 | ) 145 | 146 | 147 | def _subcommand_ls_queue(): 148 | _assert_flags( 149 | zone=True, 150 | project=True, 151 | ) 152 | _execute_shell( 153 | f'gcloud alpha compute tpus queued-resources list ' 154 | f'--zone={FLAGS.zone} ' 155 | f'--project={FLAGS.project} ' 156 | f'--quiet ' 157 | ) 158 | 159 | 160 | def _subcommand_cancel_queue(): 161 | _assert_flags( 162 | name=True, 163 | zone=True, 164 | project=True, 165 | ) 166 | _execute_shell( 167 | f'gcloud alpha compute tpus queued-resources delete {FLAGS.name} ' 168 | f'--zone={FLAGS.zone} ' 169 | f'--project={FLAGS.project} ' 170 | f'--quiet ' 171 | ) 172 | 173 | 174 | def _subcommand_describe(): 175 | _assert_flags( 176 | zone=True, 177 | project=True, 178 | name=True, 179 | ) 180 | _execute_shell( 181 | f'gcloud compute tpus tpu-vm describe {FLAGS.name} ' 182 | f'--zone={FLAGS.zone} ' 183 | f'--project={FLAGS.project} ' 184 | f'--quiet ' 185 | ) 186 | 187 | 188 | def _get_tpu_ips(): 189 | _assert_flags( 190 | zone=True, 191 | project=True, 192 | name=True, 193 | ) 194 | _, output = _execute_shell( 195 | f'gcloud compute tpus tpu-vm describe {FLAGS.name} ' 196 | f'--zone={FLAGS.zone} ' 197 | f'--project={FLAGS.project} ' 198 | f'--quiet ', 199 | print_output=False, 200 | ) 201 | 202 | ips = [] 203 | for line in output.split('\n'): 204 | ips.extend(re.findall(r'externalIp: ([0-9\.]+)$', line)) 205 | return ips 206 | 207 | 208 | def _subcommand_ips(): 209 | for ip in _get_tpu_ips(): 210 | print(ip) 211 | 212 | 213 | def _subcommand_upload(): 214 | _assert_flags( 215 | zone=True, 216 | project=True, 217 | name=True, 218 | upload_path=True, 219 | ) 220 | for path in FLAGS.upload_path.split(','): 221 | local_path, remote_path = path.split(':') 222 | if FLAGS.upload_remove_remote: 223 | _ssh_run_command(f'rm -rf {remote_path}') 224 | _execute_shell( 225 | f'gcloud alpha compute tpus tpu-vm scp ' 226 | f'{local_path} ' 227 | f'{FLAGS.tpu_user}@{FLAGS.name}:{remote_path} ' 228 | f'--recurse ' 229 | f'--worker=all ' 230 | f'--quiet ' 231 | f'--zone={FLAGS.zone} ' 232 | f'--project={FLAGS.project} ' 233 | ) 234 | 235 | 236 | def _ssh_run_command(command): 237 | _assert_flags( 238 | zone=True, 239 | project=True, 240 | name=True, 241 | tpu_user=True, 242 | ) 243 | _execute_shell( 244 | f'gcloud alpha compute tpus tpu-vm ssh ' 245 | f'{FLAGS.tpu_user}@{FLAGS.name} ' 246 | f'--zone={FLAGS.zone} ' 247 | f'--project={FLAGS.project} ' 248 | f'--worker=all ' 249 | f'--quiet ' 250 | f'--command="{command}" ' 251 | ) 252 | 253 | 254 | def _subcommand_run(): 255 | _assert_flags( 256 | command=True, 257 | ) 258 | _ssh_run_command(FLAGS.command) 259 | 260 | 261 | def _subcommand_launch(): 262 | _assert_flags( 263 | zone=True, 264 | project=True, 265 | name=True, 266 | tpu_user=True, 267 | tmux_session_name=True, 268 | launch_script=True, 269 | launch_script_remote_path=True, 270 | ) 271 | with tempfile.NamedTemporaryFile(mode='w') as f: 272 | f.write(FLAGS.launch_script) 273 | f.flush() 274 | os.chmod(f.name, 0o755) 275 | _ssh_run_command(f'rm -f {FLAGS.launch_script_remote_path}') 276 | _execute_shell( 277 | f'gcloud alpha compute tpus tpu-vm scp ' 278 | f'{f.name} ' 279 | f'{FLAGS.tpu_user}@{FLAGS.name}:{FLAGS.launch_script_remote_path} ' 280 | f'--worker=all ' 281 | f'--quiet ' 282 | f'--zone={FLAGS.zone} ' 283 | f'--project={FLAGS.project} ' 284 | ) 285 | 286 | _ssh_run_command( 287 | f'tmux new-session -d -s {FLAGS.tmux_session_name} {FLAGS.launch_script_remote_path}' 288 | ) 289 | 290 | 291 | def _subcommand_check(): 292 | _assert_flags( 293 | tmux_session_name=True, 294 | ) 295 | _ssh_run_command(f'tmux capture-pane -pt {FLAGS.tmux_session_name} -S -2000') 296 | 297 | 298 | def _subcommand_stop(): 299 | _assert_flags( 300 | tmux_session_name=True, 301 | ) 302 | _ssh_run_command(f'tmux kill-session -t {FLAGS.tmux_session_name} || :') 303 | 304 | 305 | def _subcommand_reboot(): 306 | _ssh_run_command(f'tmux new-session -d -s reboot sudo reboot') 307 | 308 | 309 | def _subcommand_unlock(): 310 | _ssh_run_command(f'sudo rm -rf /tmp/libtpu_lockfile && sudo rm -rf /tmp/tpu_logs') 311 | 312 | 313 | def main(args): 314 | if args.config_file != '': 315 | with mlxu.open_file(args.config_file, 'r') as f: 316 | __file__ = os.path.abspath(args.config_file) 317 | exec(f.read()) 318 | 319 | if FLAGS.launch_script_path is not None: 320 | with mlxu.open_file(FLAGS.launch_script_path, 'r') as f: 321 | FLAGS.launch_script = f.read() 322 | 323 | # Finalize config with defaults 324 | if FLAGS.reserved is None: 325 | FLAGS.reserved = False 326 | if FLAGS.spot is None: 327 | FLAGS.spot = False 328 | if FLAGS.tpu_user is None: 329 | FLAGS.tpu_user = os.environ['USER'] 330 | if FLAGS.upload_remove_remote is None: 331 | FLAGS.upload_remove_remote = True 332 | if FLAGS.tmux_session_name is None: 333 | FLAGS.tmux_session_name = 'tpc' 334 | if FLAGS.show_command is None: 335 | FLAGS.show_command = True 336 | if FLAGS.launch_script_remote_path is None: 337 | FLAGS.launch_script_remote_path = f'/home/{FLAGS.tpu_user}/tpc_launch_script.sh' 338 | 339 | 340 | match args.action: 341 | case 'list': 342 | _subcommand_list() 343 | case 'create': 344 | _subcommand_create() 345 | case 'delete': 346 | _subcommand_delete() 347 | case 'queue': 348 | _subcommand_queue() 349 | case 'ls_queue': 350 | _subcommand_ls_queue() 351 | case 'cancel_queue': 352 | _subcommand_cancel_queue() 353 | case 'describe': 354 | _subcommand_describe() 355 | case 'ips': 356 | _subcommand_ips() 357 | case 'upload': 358 | _subcommand_upload() 359 | case 'run': 360 | _subcommand_run() 361 | case 'launch': 362 | _subcommand_launch() 363 | case 'check': 364 | _subcommand_check() 365 | case 'stop': 366 | _subcommand_stop() 367 | case 'reboot': 368 | _subcommand_reboot() 369 | case 'unlock': 370 | _subcommand_unlock() 371 | case 'relaunch': 372 | _subcommand_stop() 373 | time.sleep(1) 374 | _subcommand_unlock() 375 | time.sleep(1) 376 | _subcommand_launch() 377 | case 'stop+unlock': 378 | _subcommand_stop() 379 | time.sleep(1) 380 | _subcommand_unlock() 381 | case 'upload+launch': 382 | _subcommand_upload() 383 | time.sleep(1) 384 | _subcommand_launch() 385 | 386 | 387 | 388 | def _parse_flags(argv): 389 | parser = argparse_flags.ArgumentParser( 390 | description="TPU pod commander", 391 | inherited_absl_flags=FLAGS, 392 | ) 393 | parser.add_argument( 394 | "action", 395 | type=str, 396 | choices=[ 397 | 'list', 398 | 'create', 399 | 'delete', 400 | 'queue', 401 | 'ls_queue', 402 | 'cancel_queue', 403 | 'describe', 404 | 'ips', 405 | 'upload', 406 | 'run', 407 | 'launch', 408 | 'check', 409 | 'stop', 410 | 'reboot', 411 | 'unlock', 412 | 'relaunch', 413 | 'stop+unlock', 414 | 'upload+launch', 415 | ], 416 | help='Action to execute', 417 | ) 418 | parser.add_argument( 419 | 'config_file', 420 | type=str, 421 | default='', 422 | nargs='?', 423 | help='Config file to load', 424 | ) 425 | 426 | return parser.parse_args(argv[1:]) 427 | 428 | 429 | def run_cli(): 430 | mlxu.run(main, flags_parser=_parse_flags) 431 | 432 | 433 | if __name__ == '__main__': 434 | run_cli() 435 | 436 | --------------------------------------------------------------------------------