├── .gitignore ├── requirements.txt ├── run-venv ├── run-local ├── run-ray ├── convert-imagenet.py ├── README.md ├── ssh-demo.ipynb ├── ray-demo.ipynb ├── README.ipynb ├── utils.py ├── imagenet.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.tar 2 | .bash_history 3 | 1 4 | __pycache__ 5 | _cache 6 | lightning_logs 7 | shards 8 | typescript 9 | venv 10 | work 11 | old 12 | OLD 13 | *.old 14 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | setuptools 2 | webdataset 3 | pytorch-lightning 4 | tensorboard 5 | typer 6 | psutil 7 | wandb 8 | webdataset 9 | ray[default] 10 | ray[air] 11 | ipython 12 | jupyterlab 13 | -------------------------------------------------------------------------------- /run-venv: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | test -d venv || python3 -m venv venv 4 | source venv/bin/activate 5 | pip3 install -U pip 6 | pip3 install -U numpy scipy 7 | pip3 install -U torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113 8 | pip3 install -U -r requirements.txt 9 | -------------------------------------------------------------------------------- /run-local: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | die() { 4 | echo "$@" >&2 5 | exit 1 6 | } 7 | 8 | test -d ./shards/. || die "./shards directory not found, create with convert-imagenet.py" 9 | test -f ./shards/imagenet-train-000000.tar || die "./shards/imagenet-train-000000.tar not found" 10 | 11 | . ./venv/bin/activate 12 | set -x 13 | python3 imagenet.py train --bucket=./shards/ --verbose 14 | -------------------------------------------------------------------------------- /run-ray: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | die() { 4 | echo "$@" >&2 5 | exit 1 6 | } 7 | 8 | test -d ./shards/. || die "./shards directory not found, create with convert-imagenet.py" 9 | test -f ./shards/imagenet-train-000000.tar || die "./shards/imagenet-train-000000.tar not found" 10 | 11 | . ./venv/bin/activate 12 | set -x 13 | 14 | # start up a web server serving the shards 15 | docker ps | awk '$2=="nginx"{print $1}' | xargs -r docker kill 16 | docker run -it --rm -d -p 8080:80 --name web -v $(/bin/pwd)/shards/.:/usr/share/nginx/html nginx 17 | 18 | # make sure Ray is running 19 | ray status > /dev/null 2>&1 || die "Ray is not running" 20 | 21 | # run training using the given number of GPUs 22 | python3 imagenet.py raytrain --bucket=http://$(hostname -i):8080/ --verbose "$@" 23 | -------------------------------------------------------------------------------- /convert-imagenet.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from torchvision.datasets import ImageNet 4 | import webdataset as wds 5 | import typer 6 | 7 | app = typer.Typer() 8 | 9 | 10 | @app.command() 11 | def convert(root: str, odir: str = "./shards"): 12 | assert os.path.isdir(root) 13 | assert os.path.isdir(os.path.join(root, "train")) 14 | assert os.path.isdir(os.path.join(root, "val")) 15 | assert os.path.isdir(odir) 16 | 17 | assert not os.path.exists(os.path.join(odir, "imagenet-train-000000.tar")) 18 | assert not os.path.exists(os.path.join(odir, "imagenet-val-000000.tar")) 19 | 20 | dataset = ImageNet(root="/fast1tb/imagenet-data", split="val") 21 | opat = os.path.join(odir, "imagenet-val-%06d.tar") 22 | output = wds.ShardWriter(opat, maxcount=1000) 23 | for i in range(len(dataset)): 24 | if i % 1000 == 0: 25 | print(i, file=sys.stderr) 26 | img, label = dataset[i] 27 | output.write({"__key__": "%08d" % i, "jpg": img, "cls": label}) 28 | output.close() 29 | 30 | dataset = ImageNet(root="/fast1tb/imagenet-data", split="train") 31 | opat = os.path.join(odir, "imagenet-train-%06d.tar") 32 | output = wds.ShardWriter(opat, maxcount=1000) 33 | for i in range(len(dataset)): 34 | if i % 1000 == 0: 35 | print(i, file=sys.stderr) 36 | img, label = dataset[i] 37 | output.write({"__key__": "%08d" % i, "jpg": img, "cls": label}) 38 | output.close() 39 | 40 | 41 | if __name__ == "__main__": 42 | app() 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ``` 2 | 3 | 4 | ############################################################################################## 5 | This repository has been archived. Please see the main webdataset repository for examples. 6 | ############################################################################################## 7 | 8 | 9 | 10 | ``` 11 | 12 | # Imagenet Training 13 | 14 | ## Setup 15 | 16 | This is a small repository showing the use of the webdataset library for training models on the Imagenet dataset. 17 | 18 | To start, you need to convert the Imagenet dataset to shards: 19 | 20 | ``` 21 | $ mkdir shards 22 | $ python3 convert-image.py /.../imagenet-data 23 | ``` 24 | 25 | This should generate a large number of shards in the `./shards` subdirectory. 26 | 27 | 28 | 29 | ```python 30 | !ls shards | shardsum 31 | ``` 32 | 33 | imagenet-train-{000000..001281}.tar 34 | imagenet-val-{000000..000049}.tar 35 | 36 | 37 | You first need to install a virtual environment: 38 | 39 | ``` 40 | $ ./run-venv 41 | ... 42 | $ . ./venv/bin/activate 43 | $ 44 | ``` 45 | 46 | You can then run `jupyter lab` and explore the notebooks or run command line programs. 47 | 48 | You have several ways of running Imagenet training: 49 | 50 | - `./run-local` will run single GPU training 51 | - `ray-demo.ipynb` shows how to use Ray for multinode training 52 | - `ssh-demo.ipynb` shows how to run distributed multinode training directly 53 | - `./run-ray` runs multinode training using Ray from the command line 54 | 55 | ## Data Serving 56 | 57 | In order to avoid having to distribute the data, the scripts will start up an nginx-based web server serving the data shards using `docker run`. You need to have `docker` installed for this to work. 58 | 59 | ## Ray-Based Training 60 | 61 | Ray is a convenient Python-based distributed computing platform. It is probably less common for starting up multi-node training jobs, but it is very convenient and it's the easiest of the different systems to package. 62 | 63 | For the Ray demos, you need to start up Ray. You can do that from the command line: 64 | 65 | ``` 66 | $ ray start --head 67 | ... 68 | $ ssh host1 "cd /some/dir && . ./venv/bin/activate && ray start --address=http://$(hostname -i):6379" 69 | $ ... 70 | ``` 71 | 72 | This creates a compute cluster on a local network of machines. Note that this repository needs to be installed on all machines. 73 | 74 | You can check the cluster status with: 75 | 76 | ``` 77 | $ ray status 78 | ``` 79 | 80 | Once the cluster is up and running, all the Ray-based training will run automatically and you can just start up, say, `./run-ray`. It will query the cluster for available GPUs and start training automatically. 81 | 82 | ## SSH-Based Training 83 | 84 | There are a couple of examples of SSH-based startup of the distributed training jobs. This is fairly cumbersome to do manually, but you can obviously automate it for your environment. 85 | 86 | The more usual way of performing this kind of training is using a container management system like Kubernetes or NGC, in combination with `torchrun`. The command line program is identical to the command line program using ssh-based training, but the environment variables are set for you automatically. 87 | 88 | ## Distributed Training Modes 89 | 90 | A fundamental problem with multinode distributed training is that it is difficult for multiple nodes to have exactly the same number of training batches, since the number of shards may not be evenly divisible by the number of nodes and workers, and since shards may not all contain the same number of samples. 91 | 92 | There are two common ways of dealing with this: 93 | 94 | 1. resampling: each worker picks one of the shards at random and returns samples from this; this leads to some samples being duplicated during each epoch, but is still statistically sound. This is the default. It works well for large datasets and large numbers of shards. 95 | 2. exact epochs with `Join`: the shards are split between all the compute nodes and workers and each worker iterates through its data until it runs out; at the end of training, batches become smaller as some of the GPUs have run out of training data. This ensures that each training sample is presented exactly once during each epoch. It differs from "traditional" single GPU training in that batch size is slightly variable. This mode can be enabled with the `--splitshards` argument. 96 | 97 | Please see the code for how these different modes are enabled. The command line interface and data loaders are defined in `imagenet.py`, and the training loop itself is in `utils.py`. 98 | 99 | 100 | -------------------------------------------------------------------------------- /ssh-demo.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "vscode": { 8 | "languageId": "shellscript" 9 | } 10 | }, 11 | "outputs": [], 12 | "source": [ 13 | "import os\n", 14 | "import multiprocessing as mp\n", 15 | "import time\n", 16 | "\n", 17 | "all_procs = []\n", 18 | "\n", 19 | "def background(command):\n", 20 | " proc = mp.Process(target=os.system, args=(command,))\n", 21 | " all_procs.append(proc)\n", 22 | " proc.start()\n", 23 | " \n", 24 | "def kill_all():\n", 25 | " for proc in all_procs:\n", 26 | " proc.terminate()" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "# Sharded Dataset\n", 34 | "\n", 35 | "For the subsequent code, we assume that the Imagenet shards are stored in ./shards.\n", 36 | "\n", 37 | "If the shards do not exist, we generate them directly from the original Imagenet data using a small script." 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": { 44 | "vscode": { 45 | "languageId": "shellscript" 46 | } 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "%%bash\n", 51 | "test -f shards/imagenet-train-000000.tar || {\n", 52 | " mkdir shards\n", 53 | " python3 ./convert-imagenet.py ./imagenet-data ./shards\n", 54 | "}" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "# Data Server\n", 62 | "\n", 63 | "Since we are implementing distributed training, we need to be able to retrieve shards over the network.\n", 64 | "\n", 65 | "Here, we use a small web server to serve the shards; the web server is simply nginx running in a Docker container.\n", 66 | "\n", 67 | "In practice, you would use some kind of permanently installed web server, or even better the AIStore object store." 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": { 74 | "vscode": { 75 | "languageId": "shellscript" 76 | } 77 | }, 78 | "outputs": [], 79 | "source": [ 80 | "%%bash\n", 81 | "docker ps | awk '$2==\"nginx\"{print $1}' | xargs docker kill" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "metadata": { 88 | "vscode": { 89 | "languageId": "shellscript" 90 | } 91 | }, 92 | "outputs": [], 93 | "source": [ 94 | "%%bash\n", 95 | "imagenetdir=/media/tmb/data1/gs/nvdata-imagenet\n", 96 | "docker run -it --rm -d -p 8080:80 --name web -v $imagenetdir:/usr/share/nginx/html nginx" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "metadata": { 103 | "vscode": { 104 | "languageId": "shellscript" 105 | } 106 | }, 107 | "outputs": [], 108 | "source": [ 109 | "!curl http://$(hostname -i):8080/imagenet-train-000000.tar | tar tvf - | tail" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": {}, 115 | "source": [ 116 | "# Training Jobs\n", 117 | "\n", 118 | "here, we are just starting up the distributed training jobs using ssh.\n", 119 | "This requires setting environment variables MASTER_ADDR, MASTER_PORT, RANK, and WORLD_SIZE.\n", 120 | "We put RANK=0 on the local machine." 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": { 127 | "vscode": { 128 | "languageId": "shellscript" 129 | } 130 | }, 131 | "outputs": [], 132 | "source": [ 133 | "%%bash\n", 134 | ". ./venv/bin/activate" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": null, 140 | "metadata": { 141 | "vscode": { 142 | "languageId": "shellscript" 143 | } 144 | }, 145 | "outputs": [], 146 | "source": [ 147 | "background(\"\"\"\n", 148 | "ssh sedna \"cd $(/bin/pwd) && . ./venv/bin/activate && env MASTER_ADDR=$(hostname -i) MASTER_PORT=29500 RANK=1 WORLD_SIZE=2 python3 imagenet.py train --verbose --bucket=http://$(hostname -i):8080/ --mname=resnet18 --backend=gloo\"\n", 149 | "\"\"\")" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "metadata": { 156 | "vscode": { 157 | "languageId": "shellscript" 158 | } 159 | }, 160 | "outputs": [], 161 | "source": [ 162 | "%%bash \n", 163 | "env MASTER_ADDR=$(hostname -i) MASTER_PORT=29500 RANK=0 WORLD_SIZE=2 \\\n", 164 | "python3 imagenet.py train --verbose --bucket=http://$(hostname -i):8080/ --mname=resnet18 --backend=gloo" 165 | ] 166 | } 167 | ], 168 | "metadata": { 169 | "kernelspec": { 170 | "display_name": "Python 3.10.6 ('venv': venv)", 171 | "language": "python", 172 | "name": "python3" 173 | }, 174 | "language_info": { 175 | "codemirror_mode": { 176 | "name": "ipython", 177 | "version": 3 178 | }, 179 | "file_extension": ".py", 180 | "mimetype": "text/x-python", 181 | "name": "python", 182 | "nbconvert_exporter": "python", 183 | "pygments_lexer": "ipython3", 184 | "version": "3.10.6" 185 | }, 186 | "orig_nbformat": 4, 187 | "vscode": { 188 | "interpreter": { 189 | "hash": "e4bcf1c9b208164f37ac7931ad36e4bb0817a209136db5032682a51fb7927afc" 190 | } 191 | } 192 | }, 193 | "nbformat": 4, 194 | "nbformat_minor": 2 195 | } 196 | -------------------------------------------------------------------------------- /ray-demo.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "vscode": { 8 | "languageId": "shellscript" 9 | } 10 | }, 11 | "outputs": [], 12 | "source": [ 13 | "import os\n", 14 | "import multiprocessing as mp\n", 15 | "import time\n", 16 | "\n", 17 | "all_procs = []\n", 18 | "\n", 19 | "def background(command):\n", 20 | " proc = mp.Process(target=os.system, args=(command,))\n", 21 | " all_procs.append(proc)\n", 22 | " proc.start()\n", 23 | " \n", 24 | "def kill_all():\n", 25 | " for proc in all_procs:\n", 26 | " proc.terminate()" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "# Sharded Dataset\n", 34 | "\n", 35 | "For the subsequent code, we assume that the Imagenet shards are stored in ./shards.\n", 36 | "\n", 37 | "If the shards do not exist, we generate them directly from the original Imagenet data using a small script." 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": { 44 | "vscode": { 45 | "languageId": "shellscript" 46 | } 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "%%bash\n", 51 | "test -f shards/imagenet-train-000000.tar || {\n", 52 | " python3 ./convert-imagenet.py ./imagenet-data ./shards\n", 53 | "}" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "# Data Server\n", 61 | "\n", 62 | "Since we are implementing distributed training, we need to be able to retrieve shards over the network.\n", 63 | "\n", 64 | "Here, we use a small web server to serve the shards; the web server is simply nginx running in a Docker container.\n", 65 | "\n", 66 | "In practice, you would use some kind of permanently installed web server, or even better the AIStore object store." 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": { 73 | "vscode": { 74 | "languageId": "shellscript" 75 | } 76 | }, 77 | "outputs": [], 78 | "source": [ 79 | "%%bash\n", 80 | "docker ps | awk '$2==\"nginx\"{print $1}' | xargs docker kill" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": { 87 | "vscode": { 88 | "languageId": "shellscript" 89 | } 90 | }, 91 | "outputs": [], 92 | "source": [ 93 | "%%bash\n", 94 | "imagenetdir=/media/tmb/data1/gs/nvdata-imagenet\n", 95 | "docker run -it --rm -d -p 8080:80 --name web -v $imagenetdir:/usr/share/nginx/html nginx" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": { 102 | "vscode": { 103 | "languageId": "shellscript" 104 | } 105 | }, 106 | "outputs": [], 107 | "source": [ 108 | "!curl http://$(hostname -i):8080/imagenet-train-000000.tar | tar tvf - | tail" 109 | ] 110 | }, 111 | { 112 | "cell_type": "markdown", 113 | "metadata": {}, 114 | "source": [ 115 | "# Ray Cluster\n", 116 | "\n", 117 | "In this example, we use Ray for starting up distributed training. Ray is a distributed processing system for Python. We start a two node Ray cluster. Of course, you can start up as many nodes as you like, with as many GPUs as you like." 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": { 124 | "vscode": { 125 | "languageId": "shellscript" 126 | } 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "%%bash\n", 131 | ". ./venv/bin/activate" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "metadata": { 138 | "vscode": { 139 | "languageId": "shellscript" 140 | } 141 | }, 142 | "outputs": [], 143 | "source": [ 144 | "%%bash\n", 145 | "ray stop > /dev/null 2>&1 || true" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": { 152 | "vscode": { 153 | "languageId": "shellscript" 154 | } 155 | }, 156 | "outputs": [], 157 | "source": [ 158 | "%%bash\n", 159 | "ray start --head" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": { 166 | "vscode": { 167 | "languageId": "shellscript" 168 | } 169 | }, 170 | "outputs": [], 171 | "source": [ 172 | "%%bash\n", 173 | "ssh sedna \"cd $(/bin/pwd) && . ./venv/bin/activate && ray start --address=$(hostname -i):6379\"" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": { 180 | "vscode": { 181 | "languageId": "shellscript" 182 | } 183 | }, 184 | "outputs": [], 185 | "source": [ 186 | "%%bash\n", 187 | "ray status" 188 | ] 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "metadata": {}, 193 | "source": [ 194 | "# Training Jobs\n", 195 | "\n", 196 | "Since Ray manages the cluster and handles the distributed computing aspect, starting up a multi-GPU distributed job is particularly simple and can be done with just a single command." 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": null, 202 | "metadata": { 203 | "vscode": { 204 | "languageId": "shellscript" 205 | } 206 | }, 207 | "outputs": [], 208 | "source": [ 209 | "%%bash\n", 210 | "python3 imagenet.py raytrain --verbose --bucket=http://$(hostname -i):8080/ --backend=gloo --mname=resnet18" 211 | ] 212 | } 213 | ], 214 | "metadata": { 215 | "kernelspec": { 216 | "display_name": "Python 3.10.6 ('venv': venv)", 217 | "language": "python", 218 | "name": "python3" 219 | }, 220 | "language_info": { 221 | "codemirror_mode": { 222 | "name": "ipython", 223 | "version": 3 224 | }, 225 | "file_extension": ".py", 226 | "mimetype": "text/x-python", 227 | "name": "python", 228 | "nbconvert_exporter": "python", 229 | "pygments_lexer": "ipython3", 230 | "version": "3.10.6" 231 | }, 232 | "orig_nbformat": 4, 233 | "vscode": { 234 | "interpreter": { 235 | "hash": "e4bcf1c9b208164f37ac7931ad36e4bb0817a209136db5032682a51fb7927afc" 236 | } 237 | } 238 | }, 239 | "nbformat": 4, 240 | "nbformat_minor": 2 241 | } 242 | -------------------------------------------------------------------------------- /README.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Imagenet Training\n", 9 | "\n", 10 | "## Setup\n", 11 | "\n", 12 | "This is a small repository showing the use of the webdataset library for training models on the Imagenet dataset.\n", 13 | "\n", 14 | "To start, you need to convert the Imagenet dataset to shards:\n", 15 | "\n", 16 | "```\n", 17 | "$ mkdir shards\n", 18 | "$ python3 convert-image.py /.../imagenet-data\n", 19 | "```\n", 20 | "\n", 21 | "This should generate a large number of shards in the `./shards` subdirectory.\n" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 4, 27 | "metadata": {}, 28 | "outputs": [ 29 | { 30 | "name": "stdout", 31 | "output_type": "stream", 32 | "text": [ 33 | "imagenet-train-{000000..001281}.tar\n", 34 | "imagenet-val-{000000..000049}.tar\n" 35 | ] 36 | } 37 | ], 38 | "source": [ 39 | "!ls shards | shardsum" 40 | ] 41 | }, 42 | { 43 | "attachments": {}, 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | "You first need to install a virtual environment:\n", 48 | "\n", 49 | "```\n", 50 | "$ ./run-venv\n", 51 | "...\n", 52 | "$ . ./venv/bin/activate\n", 53 | "$ \n", 54 | "```\n", 55 | "\n", 56 | "You can then run `jupyter lab` and explore the notebooks or run command line programs.\n", 57 | "\n", 58 | "You have several ways of running Imagenet training:\n", 59 | "\n", 60 | "- `./run-local` will run single GPU training\n", 61 | "- `ray-demo.ipynb` shows how to use Ray for multinode training\n", 62 | "- `ssh-demo.ipynb` shows how to run distributed multinode training directly\n", 63 | "- `./run-ray` runs multinode training using Ray from the command line" 64 | ] 65 | }, 66 | { 67 | "attachments": {}, 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "## Data Serving\n", 72 | "\n", 73 | "In order to avoid having to distribute the data, the scripts will start up an nginx-based web server serving the data shards using `docker run`. You need to have `docker` installed for this to work." 74 | ] 75 | }, 76 | { 77 | "attachments": {}, 78 | "cell_type": "markdown", 79 | "metadata": {}, 80 | "source": [ 81 | "## Ray-Based Training\n", 82 | "\n", 83 | "Ray is a convenient Python-based distributed computing platform. It is probably less common for starting up multi-node training jobs, but it is very convenient and it's the easiest of the different systems to package.\n", 84 | "\n", 85 | "For the Ray demos, you need to start up Ray. You can do that from the command line:\n", 86 | "\n", 87 | "```\n", 88 | "$ ray start --head\n", 89 | "...\n", 90 | "$ ssh host1 \"cd /some/dir && . ./venv/bin/activate && ray start --address=http://$(hostname -i):6379\"\n", 91 | "$ ...\n", 92 | "```\n", 93 | "\n", 94 | "This creates a compute cluster on a local network of machines. Note that this repository needs to be installed on all machines.\n", 95 | "\n", 96 | "You can check the cluster status with:\n", 97 | "\n", 98 | "```\n", 99 | "$ ray status\n", 100 | "```\n", 101 | "\n", 102 | "Once the cluster is up and running, all the Ray-based training will run automatically and you can just start up, say, `./run-ray`. It will query the cluster for available GPUs and start training automatically." 103 | ] 104 | }, 105 | { 106 | "attachments": {}, 107 | "cell_type": "markdown", 108 | "metadata": {}, 109 | "source": [ 110 | "## SSH-Based Training\n", 111 | "\n", 112 | "There are a couple of examples of SSH-based startup of the distributed training jobs. This is fairly cumbersome to do manually, but you can obviously automate it for your environment.\n", 113 | "\n", 114 | "The more usual way of performing this kind of training is using a container management system like Kubernetes or NGC, in combination with `torchrun`. The command line program is identical to the command line program using ssh-based training, but the environment variables are set for you automatically." 115 | ] 116 | }, 117 | { 118 | "attachments": {}, 119 | "cell_type": "markdown", 120 | "metadata": {}, 121 | "source": [ 122 | "## Distributed Training Modes\n", 123 | "\n", 124 | "A fundamental problem with multinode distributed training is that it is difficult for multiple nodes to have exactly the same number of training batches, since the number of shards may not be evenly divisible by the number of nodes and workers, and since shards may not all contain the same number of samples.\n", 125 | "\n", 126 | "There are two common ways of dealing with this:\n", 127 | "\n", 128 | "1. resampling: each worker picks one of the shards at random and returns samples from this; this leads to some samples being duplicated during each epoch, but is still statistically sound. This is the default. It works well for large datasets and large numbers of shards.\n", 129 | "2. exact epochs with `Join`: the shards are split between all the compute nodes and workers and each worker iterates through its data until it runs out; at the end of training, batches become smaller as some of the GPUs have run out of training data. This ensures that each training sample is presented exactly once during each epoch. It differs from \"traditional\" single GPU training in that batch size is slightly variable. This mode can be enabled with the `--splitshards` argument.\n", 130 | "\n", 131 | "Please see the code for how these different modes are enabled. The command line interface and data loaders are defined in `imagenet.py`, and the training loop itself is in `utils.py`." 132 | ] 133 | }, 134 | { 135 | "cell_type": "markdown", 136 | "metadata": {}, 137 | "source": [] 138 | } 139 | ], 140 | "metadata": { 141 | "kernelspec": { 142 | "display_name": "venv", 143 | "language": "python", 144 | "name": "python3" 145 | }, 146 | "language_info": { 147 | "codemirror_mode": { 148 | "name": "ipython", 149 | "version": 3 150 | }, 151 | "file_extension": ".py", 152 | "mimetype": "text/x-python", 153 | "name": "python", 154 | "nbconvert_exporter": "python", 155 | "pygments_lexer": "ipython3", 156 | "version": "3.10.6" 157 | }, 158 | "orig_nbformat": 4, 159 | "vscode": { 160 | "interpreter": { 161 | "hash": "a5b3a2b03d8d54c67e0d63d67d774e2648cc65039d8e8571334bfe0264e04b6b" 162 | } 163 | } 164 | }, 165 | "nbformat": 4, 166 | "nbformat_minor": 2 167 | } 168 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # -*- Python -*- 2 | 3 | import os 4 | import time 5 | import torch 6 | from torch import nn 7 | from torchvision import transforms 8 | import torchvision 9 | from torch.nn import functional as F 10 | from torch.optim import lr_scheduler 11 | import webdataset as wds 12 | import typer 13 | import numpy as np 14 | from itertools import islice 15 | import braceexpand 16 | import sys 17 | from torch.nn.parallel import DistributedDataParallel 18 | from torch.distributed.algorithms.join import Join 19 | import contextlib 20 | 21 | 22 | try: 23 | from apex.parallel import DistributedDataParallel as ApexDistributedDataParallel 24 | except ImportError: 25 | class ApexDistributedDataParallel: 26 | pass 27 | 28 | 29 | def identity(x): 30 | """Identity function.""" 31 | return x 32 | 33 | 34 | def fmt(v): 35 | """Generic number format.""" 36 | if isinstance(v, int): 37 | return "%9d" % v 38 | elif isinstance(v, float): 39 | return "%10.4g" % v 40 | else: 41 | return str(v)[:20] 42 | 43 | 44 | class TextLogger: 45 | def rank(self): 46 | if torch.distributed.is_initialized(): 47 | return f"[rank:{torch.distributed.get_rank()}] " 48 | else: 49 | return "" 50 | 51 | def message(self, *args): 52 | """Log a message.""" 53 | msg = " ".join([str(x) for x in args]) 54 | print(self.rank(), msg, file=sys.stderr) 55 | 56 | def __bool__(self): 57 | """Check whether the logger is active.""" 58 | return True 59 | 60 | def params(self, **kw): 61 | """Log a parameter.""" 62 | print(self.rank(), kw, file=sys.stderr) 63 | 64 | def log(self, prefix="train/", step=None, **kw): 65 | """Log to a time series.""" 66 | st = "@" + str(step) if isinstance(step, int) else "" 67 | st = (" " * 10 + st)[-10:] 68 | print(self.rank(), prefix, st, " ".join([f"{k}:{fmt(v)}" for k, v in kw.items()]), file=sys.stderr) 69 | 70 | def upload(self, name, object, step=None): 71 | """Upload an object.""" 72 | pass 73 | 74 | 75 | class TensorboardLogger: 76 | def __init__(self, log_dir=None, comment=None): 77 | from torch.utils.tensorboard import SummaryWriter 78 | self.writer = SummaryWriter(log_dir=log_dir, comment=comment) 79 | 80 | def message(self, *args): 81 | """Log a message.""" 82 | pass 83 | 84 | def params(self, **kw): 85 | """Log a parameter.""" 86 | # FIXME -- change to self.hparams(kw) interface 87 | pass 88 | 89 | def log(self, prefix="train/", step=None, **kw): 90 | """Log to a time series.""" 91 | for k, v in kw.items(): 92 | self.writer.add(prefix+k, v, step) 93 | 94 | def upload(self, name, object, step=None): 95 | """Upload an object.""" 96 | pass 97 | 98 | class Loggers: 99 | """A logging class that forwards to other loggers.""" 100 | def __init__(self, loggers=None, enable=True): 101 | """Initialize.""" 102 | if loggers is None: 103 | loggers = [TextLogger()] 104 | self.loggers = loggers if enable else [] 105 | 106 | def message(self, *args): 107 | """Log a message.""" 108 | for logger in self.loggers: 109 | if logger: 110 | logger.message(*args) 111 | 112 | def params(self, **kw): 113 | """Log a parameter.""" 114 | for logger in self.loggers: 115 | if logger: 116 | logger.params(**kw) 117 | 118 | def log(self, **kw): 119 | """Log to a time series.""" 120 | for logger in self.loggers: 121 | if logger: 122 | logger.log(**kw) 123 | 124 | def upload(self, name, obj, step=None): 125 | """Upload an object.""" 126 | for logger in self.loggers: 127 | if logger: 128 | logger.upload(name, obj, step=step) 129 | 130 | 131 | def schedule(epoch): 132 | """A simple learning rate schedule.""" 133 | return 0.1 ** (epoch // 30) 134 | 135 | 136 | def train_classifier( 137 | model, 138 | loader, 139 | step=0, 140 | lossfn=F.cross_entropy, 141 | optimizer=None, 142 | scheduler=None, 143 | logger=None, 144 | loginterval=10.0, 145 | amplevel="", 146 | join=False, 147 | ): 148 | """Train for one epoch. Handles DDP and logging.""" 149 | world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1 150 | optimizer = optimizer or torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4,) 151 | scheduler = scheduler or lr_scheduler.MultiStepLR(optimizer, milestones=[], gamma=0.1) 152 | device = next(model.parameters()).device 153 | model.train() 154 | last, last_step = time.time(), 0 155 | context = Join([model]) if join else contextlib.nullcontext() 156 | with context: 157 | for images, target in loader: 158 | images, target = images.to(device), target.to(device) 159 | optimizer.zero_grad() 160 | output = model(images) 161 | loss = lossfn(output, target) 162 | if amplevel != "": 163 | from apex import amp 164 | with amp.scale_loss(loss, optimizer) as scaled_loss: 165 | scaled_loss.backward() 166 | else: 167 | loss.backward() 168 | optimizer.step() 169 | step += len(images) * world_size 170 | lr = scheduler.get_last_lr()[-1] 171 | err = float((output.argmax(1) != target).sum() / float(len(target))) 172 | now = time.time() 173 | if logger is not None and now - last > loginterval: 174 | rate = (step - last_step) / (now - last) 175 | last, last_step = now, step 176 | logger.log( 177 | prefix="train/", step=step, loss=float(loss), err=err, lr=lr, rate=rate, 178 | ) 179 | return step 180 | 181 | 182 | def evaluate_classifier(model, loader, lossfn=F.cross_entropy, logger=None, prefix="val/", step=None): 183 | if isinstance(model, (DistributedDataParallel, ApexDistributedDataParallel)): 184 | # for evaluation, we use the model independently 185 | model = model.module 186 | device = next(model.parameters()).device 187 | losses = [] 188 | errs = [] 189 | model.eval() 190 | for images, target in loader: 191 | images = images.to(device) 192 | target = target.to(device) 193 | with torch.no_grad(): 194 | output = model(images) 195 | loss = lossfn(output, target) 196 | err = float((output.argmax(1) != target).sum() / float(len(target))) 197 | losses.append(float(loss)) 198 | errs.append(err) 199 | total, loss, err = len(losses), np.sum(losses), np.sum(errs) 200 | if torch.distributed.is_initialized(): 201 | torch.distributed.barrier() 202 | result = torch.tensor([total, loss, err]).to(device) 203 | torch.distributed.all_reduce(result, op=torch.distributed.ReduceOp.SUM) 204 | total, loss, err = result.tolist() 205 | loss, err = loss / total, err / total 206 | if logger is not None: 207 | logger.log(prefix=prefix, step=step, loss=loss, err=err) 208 | return loss, err 209 | -------------------------------------------------------------------------------- /imagenet.py: -------------------------------------------------------------------------------- 1 | # -*- Python -*- 2 | 3 | import os 4 | import time 5 | import warnings 6 | import torch 7 | from torch import nn 8 | from torchvision import transforms 9 | import torchvision 10 | from torch.nn import functional as F 11 | from torch.optim import lr_scheduler 12 | import webdataset as wds 13 | import typer 14 | import numpy as np 15 | from itertools import islice 16 | import braceexpand 17 | import sys 18 | from torch.nn.parallel import DistributedDataParallel 19 | import socket 20 | import pprint 21 | 22 | import ray 23 | 24 | import utils 25 | 26 | torchvision 27 | app = typer.Typer() 28 | 29 | default_train = "imagenet-train-{000000..001281}.tar" 30 | default_val = "imagenet-val-{000000..000049}.tar" 31 | 32 | 33 | def make_model(mname): 34 | if mname == "trivial": 35 | model1 = nn.Sequential(nn.Flatten(), nn.Linear(224 * 224 * 3, 1000)) 36 | else: 37 | import torchvision.models 38 | model1 = eval(f"torchvision.models.{mname}")() 39 | return model1 40 | 41 | 42 | normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) 43 | 44 | 45 | def make_transform(mode="train"): 46 | if mode == "train": 47 | return transforms.Compose( 48 | [ 49 | transforms.RandomResizedCrop(224), 50 | transforms.RandomHorizontalFlip(), 51 | transforms.ToTensor(), 52 | normalize, 53 | ] 54 | ) 55 | elif mode == "val": 56 | return transforms.Compose( 57 | [ 58 | transforms.Resize(256), 59 | transforms.CenterCrop(224), 60 | transforms.ToTensor(), 61 | normalize, 62 | ] 63 | ) 64 | 65 | def nodesplitter(src, group=None): 66 | if torch.distributed.is_initialized(): 67 | if group is None: 68 | group = torch.distributed.group.WORLD 69 | rank = torch.distributed.get_rank(group=group) 70 | size = torch.distributed.get_world_size(group=group) 71 | print(f"nodesplitter: rank={rank} size={size}") 72 | count = 0 73 | for i, item in enumerate(src): 74 | if i % size == rank: 75 | yield item 76 | count += 1 77 | print(f"nodesplitter: rank={rank} size={size} count={count} DONE") 78 | else: 79 | yield from src 80 | 81 | 82 | def make_loader(urls, mode="train", batch_size=64, num_workers=4, cache_dir=None, resampled=True): 83 | 84 | training = mode == "train" 85 | 86 | transform = make_transform(mode=mode) 87 | 88 | # repeat dataset infinitely for training mode 89 | repeat = training 90 | 91 | dataset = ( 92 | wds.WebDataset( 93 | urls, 94 | repeat=training, 95 | cache_dir=cache_dir, 96 | shardshuffle=1000 if training else False, 97 | resampled=resampled if training else False, 98 | handler=wds.ignore_and_continue, 99 | nodesplitter=None if (training and resampled) else nodesplitter, 100 | ) 101 | .shuffle(5000 if training else 0) 102 | .decode("pil") 103 | .to_tuple("jpg;png;jpeg cls", handler=wds.ignore_and_continue) 104 | .map_tuple(transform) 105 | .batched(batch_size, partial=False) 106 | ) 107 | 108 | loader = wds.WebLoader(dataset, batch_size=None, shuffle=False, num_workers=num_workers) 109 | return loader 110 | 111 | def print_distributed_info(): 112 | keys = "MASTER_ADDR MASTER_PORT WORLD_SIZE RANK LOCAL_RANK".split() 113 | for k in keys: 114 | print(f"{k}={os.environ.get(k)}") 115 | 116 | @app.command() 117 | def train( 118 | bucket: str = "./shards/", 119 | shards: str = default_train, 120 | valshards: str = default_val, 121 | batchsize: int = 32, 122 | mname: str = "resnet18", 123 | nepochs: int = 300, 124 | workers: int = 4, 125 | ntrain: int = 1281167, 126 | nval: int = 50000, 127 | device: str = "cuda", 128 | loginterval: float = 10.0, 129 | cache_dir: str = None, 130 | backend: str = "nccl", 131 | onelog: bool = False, 132 | showopen: bool = False, 133 | amplevel: str = "", 134 | apexddp: bool = False, 135 | verbose: bool = False, 136 | distributed: str = "", 137 | splitshards: bool = False, 138 | ): 139 | 140 | parameters = dict(locals()) 141 | 142 | resampled = not splitshards 143 | print("*** resampled", resampled) 144 | 145 | if showopen: 146 | os.environ["GOPEN_VERBOSE"] = "1" 147 | 148 | if bucket == "gs:": 149 | bucket = "pipe:curl -s -L http://storage.googleapis.com/nvdata-imagenet/{}" 150 | elif bucket == "ais:": 151 | os.environ["AIS_ENDPOINT"] = "http://ais.dynalias.net:51080" 152 | bucket = "pipe:ais get gs://nvdata-imagenet/{} - || true" 153 | 154 | if os.environ.get("WORLD_SIZE") is not None: 155 | print_distributed_info() 156 | print("init_process_group...") 157 | torch.distributed.init_process_group(backend=backend, init_method="env://") 158 | time.sleep(1) 159 | print("init_process_group done") 160 | local_rank = int(os.environ.get("LOCAL_RANK", -1)) 161 | if local_rank >= 0: 162 | torch.cuda.set_device(local_rank) 163 | device = torch.cuda.current_device() 164 | print("device", device) 165 | world_size = torch.distributed.get_world_size() 166 | multinode = True 167 | print( 168 | f"starting rank={torch.distributed.get_rank()} world_size={world_size} device={device}", 169 | file=sys.stderr, 170 | ) 171 | print("barrier...") 172 | torch.distributed.barrier() 173 | print( 174 | f"done rank={torch.distributed.get_rank()} world_size={world_size} device={device}", 175 | file=sys.stderr, 176 | ) 177 | print("barrier done") 178 | else: 179 | if os.getenv("NGC_ARRAY_SIZE") is not None: 180 | warnings.warn("NGC_ARRAY_SIZE is set but WORLD_SIZE is not") 181 | multinode = False 182 | world_size = 1 183 | 184 | if verbose: 185 | print("logger") 186 | 187 | if multinode and onelog: 188 | rank0 = (torch.distributed.get_rank() == 0) 189 | logger = utils.Loggers(enable=rank0) 190 | else: 191 | logger = utils.Loggers(enable=True) 192 | logger.params(**parameters) 193 | 194 | 195 | if verbose: 196 | print("loader") 197 | 198 | bucket = bucket if "{}" in bucket else bucket + "{}" 199 | shards = bucket.format(shards) 200 | valshards = bucket.format(valshards) 201 | logger.message(f"inputs: {shards}") 202 | logger.message(f"validation: {valshards}") 203 | 204 | loader = make_loader(shards, mode="train", batch_size=batchsize, num_workers=workers, cache_dir=cache_dir, resampled=resampled) 205 | nbatches = max(1, ntrain // (batchsize * world_size)) 206 | loader = loader.with_epoch(nbatches) 207 | 208 | valloader = make_loader( 209 | valshards, mode="val", batch_size=batchsize, num_workers=workers, cache_dir=cache_dir 210 | ) 211 | inputs, targets = next(iter(loader)) 212 | logger.message( 213 | f"inputs: {tuple(inputs.shape)} {inputs.dtype} {inputs.device} {float(inputs.min())} {float(inputs.max())}" 214 | ) 215 | logger.message(f"validation: {tuple(targets.shape)}") 216 | 217 | if verbose: 218 | print("model") 219 | 220 | model = make_model(mname) 221 | model.to(device) 222 | 223 | optimizer = torch.optim.SGD( 224 | model.parameters(), 225 | lr=0.1, 226 | momentum=0.9, 227 | weight_decay=1e-4, 228 | ) 229 | scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=[30, 60, 90, 120], gamma=0.1) 230 | 231 | if amplevel != "": 232 | from apex import amp 233 | logger.message(f"using amp level {amplevel}") 234 | model, optimizer = amp.initialize(model, optimizer, opt_level=amplevel) 235 | 236 | if multinode: 237 | if apexddp: 238 | from apex.parallel import DistributedDataParallel as ApexDistributedDataParallel 239 | logger.message(f"using apex ddp") 240 | model = ApexDistributedDataParallel(model) 241 | else: 242 | model = DistributedDataParallel(model, device_ids=[device]) 243 | 244 | if verbose: 245 | print("starting") 246 | 247 | step = 0 248 | for epoch in range(nepochs): 249 | logger.message("===", epoch, "===") 250 | step = utils.train_classifier( 251 | model, 252 | loader, 253 | optimizer=optimizer, 254 | scheduler=scheduler, 255 | logger=logger, 256 | step=step, 257 | loginterval=loginterval, 258 | amplevel=amplevel, 259 | join=resampled, 260 | ) 261 | utils.evaluate_classifier(model, valloader.slice(nval // batchsize), logger=logger, step=step) 262 | scheduler.step() 263 | 264 | 265 | @ray.remote(num_gpus=1) 266 | class TrainingWorker: 267 | def __init__(self, rank: int, wsize: int, backend: str = "gloo"): 268 | self.rank = rank 269 | self.wsize = wsize 270 | self.backend = backend 271 | 272 | def get_ip(self): 273 | return socket.gethostbyname(socket.gethostname()) 274 | 275 | def setup_distributed(self, master): 276 | self.master = master 277 | os.environ.update(master) 278 | os.environ.update(RANK=str(self.rank), WORLD_SIZE=str(self.wsize), BACKEND=self.backend) 279 | # torch.distributed.init_process_group(backend=self.backend, init_method="env://") 280 | 281 | def train(self, **kw): 282 | time.sleep(1) 283 | print("running", self.rank) 284 | train(**kw) 285 | print("done", self.rank) 286 | 287 | 288 | @app.command() 289 | def raytrain( 290 | bucket: str = "./shards/", 291 | shards: str = default_train, 292 | valshards: str = default_val, 293 | batchsize: int = 32, 294 | mname: str = "resnet18", 295 | nepochs: int = 300, 296 | workers: int = 4, 297 | ntrain: int = 1281167, 298 | nval: int = 50000, 299 | device: str = "cuda:0", 300 | loginterval: float = 10.0, 301 | cache_dir: str = None, 302 | backend: str = "gloo", 303 | onelog: bool = False, 304 | showopen: bool = False, 305 | amplevel: str = "", 306 | apexddp: bool = False, 307 | verbose: bool = False, 308 | wsize: int = 0, 309 | splitshards: bool = False, 310 | ): 311 | """Train a model on multiple GPUs using Ray. 312 | 313 | You need to start up a ray cluster first, e.g.: 314 | 315 | ray start --head 316 | 317 | You can add additional nodes as specified in the Ray output. 318 | 319 | By default, this will use as many GPUs as are available on 320 | the cluster. You can override this with the --wsize option. 321 | """ 322 | 323 | parameters = dict(locals()) 324 | del parameters["wsize"] 325 | 326 | ray.init() 327 | if wsize == 0: 328 | wsize = int(ray.available_resources()["GPU"]) 329 | elif wsize == -1: 330 | wsize = int(ray.cluster_resources()["GPU"]) 331 | 332 | print("world size:", wsize) 333 | 334 | print("starting workers") 335 | workers = [TrainingWorker.remote(i, wsize) for i in range(wsize)] 336 | 337 | print("getting master") 338 | addr = ray.get(workers[0].get_ip.remote()) 339 | master = dict(MASTER_ADDR=addr, MASTER_PORT="29500") 340 | print("master", master) 341 | 342 | results = [w.setup_distributed.remote(master) for w in workers] 343 | ray.get(results) 344 | 345 | print("running") 346 | results = [w.train.remote(**parameters) for w in workers] 347 | ray.get(results) 348 | print("done") 349 | 350 | if __name__ == "__main__": 351 | app() 352 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------