├── benchmark ├── __init__.py ├── results.txt ├── pod_template.yml ├── gen_pod.py ├── benchmark.sh ├── README.md ├── utils.py └── benchmark.py ├── pipeline_tool ├── __init__.py ├── blacklist.txt ├── constant.py ├── gpu_alloc.py ├── whitelist.txt ├── class_impl │ ├── PropagationLayer.py │ ├── CallModule.py │ ├── CallFunction.py │ ├── GetAttrModule.py │ ├── GetAttr.py │ └── LayerClass.py ├── evaluate_mem.py ├── dataset.py ├── pipeline_config.py ├── function_parser.py └── pipeline_tool.py ├── requirements.txt ├── img ├── 01_simple_model_input.png ├── 03_simple_model_dep.png ├── 02_simple_model_output.png └── Pipeline_tool_flowchart.png ├── .gitignore ├── tests ├── test_import.py ├── test_config_creation.py ├── test_trace_complex.py └── test_trace_simple.py ├── CODE_OWNERS.rst ├── CODE_AUTHORS.rst ├── CONTRIBUTING.rst ├── GOVERNANCE.rst ├── pyproject.toml ├── .github └── workflows │ ├── python-publish.yml │ └── python-package.yml ├── RELEASE_README.md ├── CODE_OF_CONDUCT.rst ├── examples ├── 00_Basic_usage.py └── 01_Multihead_handling.py ├── DEED_OF_CONTRIBUTION.rst ├── README.md └── LICENSE /benchmark/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pipeline_tool/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pipeline_tool/blacklist.txt: -------------------------------------------------------------------------------- 1 | assert -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch<=1.13.1 2 | numpy>=1.23.3 3 | torchvision<=0.14.1 4 | -------------------------------------------------------------------------------- /img/01_simple_model_input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/pipeline-tools/main/img/01_simple_model_input.png -------------------------------------------------------------------------------- /img/03_simple_model_dep.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/pipeline-tools/main/img/03_simple_model_dep.png -------------------------------------------------------------------------------- /img/02_simple_model_output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/pipeline-tools/main/img/02_simple_model_output.png -------------------------------------------------------------------------------- /img/Pipeline_tool_flowchart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/pipeline-tools/main/img/Pipeline_tool_flowchart.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **__pycache__* 2 | **log* 3 | benchmark/**data* 4 | examples/**data* 5 | **import_utils* 6 | **.idea* 7 | **pipelinecache* 8 | *venv* 9 | Dockerfile 10 | **.pth* 11 | dist/* -------------------------------------------------------------------------------- /tests/test_import.py: -------------------------------------------------------------------------------- 1 | from pipeline_tool.pipeline_tool import SkippableTracing 2 | from pipeline_tool.pipeline_config import PipelineConfig 3 | 4 | 5 | def test_import(): 6 | print("All user import needed are working !") 7 | -------------------------------------------------------------------------------- /CODE_OWNERS.rst: -------------------------------------------------------------------------------- 1 | The following is the list of code owners of the ``pipeline-tools`` Python package: 2 | 3 | - L2F SA 4 | - EPFL - Ecole Polytechnique Fédérale de Lausanne 5 | - REDS Institute of the Haut Ecole d'Ingénierie et Gestion du canton Vaud 6 | -------------------------------------------------------------------------------- /CODE_AUTHORS.rst: -------------------------------------------------------------------------------- 1 | The following is the list of code authors of the ``pipeline-tool`` python package. 2 | 3 | Where component authors are known, add them here. 4 | 5 | - Bruno Da Rocha Carvalho, bruno.darochacarvalho@heig-vd.ch 6 | - Gabriel Catel Torres Arzur, arzur.cateltorres@heig-vd.ch 7 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing guidelines 2 | ======================= 3 | 4 | This document only redirects to more `detailed instructions `_, 5 | which consist of: 6 | 7 | - a pull request checklist, 8 | - a Contributor License Agreement, 9 | - contributing guidelines and standards, including coding style guides. 10 | -------------------------------------------------------------------------------- /tests/test_config_creation.py: -------------------------------------------------------------------------------- 1 | from pipeline_tool.pipeline_config import PipelineConfig 2 | 3 | def test_config(): 4 | config = PipelineConfig(input_shape=[1,2], output_shape=[12], data_type="long") 5 | 6 | print("A simple config as been created") 7 | 8 | config.create_mha_conf_equal(nb_mha=2, num_heads=12, embed_dim=3, dropout=0.0, batch_first=True) 9 | 10 | print("An MHA config as been added") 11 | -------------------------------------------------------------------------------- /GOVERNANCE.rst: -------------------------------------------------------------------------------- 1 | This file describe the governance of the ``giotto-deep`` project. 2 | 3 | Project owner: 4 | -------------- 5 | 6 | - L2F SA 7 | 8 | Authors: 9 | -------- 10 | 11 | - Please refer to the `authors `_ file 12 | 13 | Pipeline-tool Project Team: 14 | ------------------------ 15 | 16 | - Bruno Da Rocha Carvalho, bruno.darochacarvalho@heig-vd.ch (Developer) 17 | - Gabriel Catel Torres Arzur, arzur.cateltorres@heig-vd.ch (Developer) 18 | - Matteo Caorsi m.caorsi@l2f.ch (Project Leader) 19 | 20 | Former Project Team Members: 21 | ---------------------------- 22 | -------------------------------------------------------------------------------- /pipeline_tool/constant.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | TAB = {1: " ", 17 | 2: " ", 18 | 3: " "} -------------------------------------------------------------------------------- /benchmark/results.txt: -------------------------------------------------------------------------------- 1 | Framework;Model;Number of GPUs;Number of Chunks;Time 1 [s];Time 2 [s];Time 3 [s];Time 4 [s];Alloc 1 [MB];Alloc 2 [MB];Alloc 3 [MB];Alloc 4 [MB] 2 | API torch;CNN;1;0;2.3584954738616943;0.4620656967163086;0.45350098609924316;0.446514368057251;[747];[625];[625];[625] 3 | API torch;FFNET;1;0;0.6421031951904297;0.174668550491333;0.1769857406616211;0.15308761596679688;[676];[520];[520];[520] 4 | Pipeline;CNN;1;2;2.887887954711914;0.9743552207946777;0.943678617477417;0.9702959060668945;[774];[628];[628];[628] 5 | Pipeline;CNN;2;2;4.311769485473633;1.5424797534942627;1.4045016765594482;1.494065761566162;[706, 537];[582, 514];[582, 514];[582, 514] 6 | Pipeline;FFNET;1;2;0.9374241828918457;0.4668889045715332;0.45452380180358887;0.45163583755493164;[830];[668];[668];[668] 7 | Pipeline;FFNET;2;2;1.803046464920044;0.9651117324829102;0.9729149341583252;0.946465015411377;[681, 517];[522, 514];[522, 514];[522, 514] 8 | Pipeline;CNN;2;2;4.222788572311401;1.4674599170684814;[706, 537];[582, 514] 9 | -------------------------------------------------------------------------------- /benchmark/pod_template.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: pipeline-benchmark 5 | namespace: default 6 | annotations: 7 | gke-gcsfuse/volumes: "true" 8 | spec: 9 | terminationGracePeriodSeconds: 60 10 | volumes: 11 | - name: gcs-fuse-csi-ephemeral 12 | csi: 13 | driver: gcsfuse.csi.storage.gke.io 14 | volumeAttributes: 15 | bucketName: $bucket 16 | - name: shared-memory 17 | emptyDir: 18 | medium: Memory 19 | sizeLimit: 16Gi 20 | containers: 21 | - name: pipeline-benchmark 22 | image: $image 23 | args: ["$gpu_count"] 24 | resources: 25 | limits: 26 | nvidia.com/gpu: $gpu_count 27 | volumeMounts: 28 | - mountPath: "/var/lib/data" 29 | name: gcs-fuse-csi-ephemeral 30 | - mountPath: /dev/shm 31 | name: shared-memory 32 | imagePullPolicy: Always 33 | serviceAccountName: $ksa 34 | restartPolicy: Never 35 | nodeSelector: 36 | cloud.google.com/gke-accelerator: $gpu_model -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [tool.hatch.build] 6 | include = [ 7 | "pipeline_tool/", 8 | ] 9 | exclude = [ 10 | "pipeline_tool/pipelinecache/", 11 | ] 12 | 13 | [project] 14 | name = "pipeline_tool" 15 | 16 | version = "0.0.2" 17 | 18 | authors = [ 19 | {name="Bruno Da Rocha Carvalho", email="bruno.darochacarvalho@heig-vd.ch"}, 20 | {name="Gabriel Catel Torres Arzur", email="arzur.cateltorres@heig-vd.ch"} 21 | ] 22 | 23 | description = "Alow splitting of big model in multiple GPU for training" 24 | 25 | readme = "README.md" 26 | 27 | license = {file = "LICENSE"} 28 | 29 | requires-python = ">=3.8" 30 | 31 | classifiers = [ 32 | "Programming Language :: Python :: 3", 33 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 34 | "Environment :: GPU :: NVIDIA CUDA :: 12", 35 | "Natural Language :: English", 36 | "Operating System :: Unix", 37 | ] 38 | 39 | dependencies = [ 40 | "torch<=1.13.1", 41 | "numpy<=1.23.3", 42 | "torchvision<=0.14.1", 43 | ] 44 | 45 | 46 | -------------------------------------------------------------------------------- /tests/test_trace_complex.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import os 5 | 6 | from pipeline_tool.pipeline_config import PipelineConfig 7 | from pipeline_tool.pipeline_tool import SkippableTracing 8 | 9 | # Define the Vision Transformer model 10 | from torchvision.models import vit_h_14 11 | class VisionTransformer(nn.Module): 12 | def __init__(self) -> None: 13 | super().__init__() 14 | self.model = vit_h_14(weights='DEFAULT') 15 | 16 | def forward(self, image): 17 | return self.model(image) 18 | 19 | 20 | model = VisionTransformer() 21 | batch_size = 4 22 | config_pipeline = PipelineConfig(input_shape=[batch_size, 3, 518, 518], 23 | output_shape=[batch_size, 1000], 24 | data_type="float") 25 | 26 | nb_mha = 33 27 | num_heads = 16 28 | embed_dim = 1280 29 | dropout = 0.0 30 | batch_first = True 31 | 32 | config_pipeline.create_mha_conf_equal(nb_mha, num_heads, embed_dim, dropout, batch_first) 33 | 34 | def test_trace(): 35 | trace = SkippableTracing(nb_gpus=0, model=model, config=config_pipeline) 36 | -------------------------------------------------------------------------------- /tests/test_trace_simple.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import os 5 | 6 | from pipeline_tool.pipeline_config import PipelineConfig 7 | from pipeline_tool.pipeline_tool import SkippableTracing 8 | 9 | class CNN(nn.Module): 10 | def __init__(self): 11 | super().__init__() 12 | self.conv1 = nn.Conv2d(3, 6, 5) 13 | self.pool = nn.MaxPool2d(2, 2) 14 | self.conv2 = nn.Conv2d(6, 16, 5) 15 | self.fc1 = nn.Linear(16 * 5 * 5, 120) 16 | self.fc2 = nn.Linear(120, 84) 17 | self.fc3 = nn.Linear(84, 10) 18 | 19 | def forward(self, x): 20 | x = self.pool(F.relu(self.conv1(x))) 21 | x = self.pool(F.relu(self.conv2(x))) 22 | x = torch.flatten(x, 1) 23 | x = F.relu(self.fc1(x)) 24 | x = F.relu(self.fc2(x)) 25 | x = self.fc3(x) 26 | return x 27 | 28 | model = CNN() 29 | 30 | 31 | 32 | batch_size = 4 33 | 34 | config_pipeline = PipelineConfig(input_shape=[batch_size, 3, 32, 32], 35 | output_shape=[batch_size], 36 | data_type="long") 37 | def test_trace_simple(): 38 | trace = SkippableTracing(nb_gpus=0, model=model, config=config_pipeline) 39 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: [workflow_dispatch] 12 | 13 | permissions: 14 | contents: read 15 | 16 | jobs: 17 | deploy: 18 | 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - uses: actions/checkout@v3 23 | - name: Set up Python 24 | uses: actions/setup-python@v3 25 | with: 26 | python-version: '<=3.10' 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | pip install build twine 31 | - name: Build package 32 | run: python -m build 33 | - name: Publish package 34 | env: 35 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 36 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 37 | run: | 38 | twine check dist/* 39 | twine upload dist/* 40 | -------------------------------------------------------------------------------- /.github/workflows/python-package.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Python package 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.8", "3.9", "3.10"] 20 | 21 | steps: 22 | - uses: actions/checkout@v3 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v3 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | python -m pip install flake8 build twine pytest 31 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 32 | - name: Lint with flake8 33 | run: | 34 | # stop the build if there are Python syntax errors or undefined names 35 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 36 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 37 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 38 | - name: Build 39 | run: | 40 | python -m build 41 | pip install dist/*.whl 42 | - name: Unit tests 43 | run: pytest . 44 | -------------------------------------------------------------------------------- /RELEASE_README.md: -------------------------------------------------------------------------------- 1 | # Release Readme 2 | 3 | ## Who can do it 4 | 5 | Maintainers or above can create releases. 6 | 7 | Pleas make sure to properly use the version numbers according to [these standards](https://semver.org/#:~:text=A%20normal%20version%20number%20MUST,0%20%2D%3E%201.11.0.). 8 | 9 | ## How to do it 10 | 11 | These are the steps to follow to make a new release of this package, in this order. Of course, you have to make sure that all CI tests are passing that you have also manually tested that everything works. 12 | 13 | ### Step 1: 14 | 15 | Change the version in the [pyproject.toml](./pyproject.toml) file 16 | 17 | ### Step 2: 18 | 19 | Draft a new release [here](https://github.com/giotto-ai/pipeline-tools/releases/new). Feel free to fill it in with the aoutomated button. 20 | 21 | In the release view, create a new tag called `vX.y.Z`, with `X`, `Y`, and `Z` the major, minor and patch version. 22 | Leave the main ranch as target. 23 | 24 | Once you are done, please make sure to click on the "Save draft". Do not publish yet! 25 | 26 | ### Step 3: 27 | 28 | Run this [action job](https://github.com/giotto-ai/pipeline-tools/actions/workflows/python-publish.yml) manually, by clicking the "Run workflow" button on the top right. 29 | This job, if successful, will deploy the package to `pypi` directly. You can check it online and `pip install` it. 30 | 31 | If the job fails, it means that there are probably issues in packaging and building the project: analyse the CI and fix all that is needed. 32 | 33 | ### Step 4: 34 | 35 | Once published on pypi via the action job of the previous step, complete, if needed, the new release you saved as draft at step 2. 36 | 37 | Once you are happy with the text, publish it (click the green button)! 38 | 39 | -------------------------------------------------------------------------------- /benchmark/gen_pod.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import enum 3 | import string 4 | 5 | class GPUs(enum.Enum): 6 | a100 = enum.auto() 7 | v100 = enum.auto() 8 | t4 = enum.auto() 9 | 10 | def __str__(self) -> str: 11 | return self.name 12 | 13 | @staticmethod 14 | def from_string(s): 15 | try: 16 | return GPUs[s] 17 | except KeyError: 18 | raise ValueError() 19 | 20 | def fullname(self) -> str: 21 | if self is GPUs.a100: 22 | return "nvidia-tesla-a100" 23 | elif self is GPUs.v100: 24 | return "nvidia-tesla-v100" 25 | elif self is GPUs.t4: 26 | return "nvidia-tesla-t4" 27 | else: 28 | raise Exception(f"Fullname missing for {self.name}") 29 | 30 | def run(args): 31 | values = { 32 | "image": args.image, 33 | "bucket": args.bucket, 34 | "ksa": args.ksa, 35 | "gpu_count": args.gpu_count, 36 | "gpu_model": args.gpu_model.fullname(), 37 | } 38 | 39 | with open("pod_template.yml", "r") as f: 40 | ymlt = string.Template(f.read()) 41 | 42 | ymlv = ymlt.substitute(values) 43 | filename = f"pod-{args.gpu_model}-{args.gpu_count}.yml" 44 | with open(filename, "w") as f: 45 | f.write(ymlv) 46 | 47 | print(f"kubectl apply -f {filename}") 48 | 49 | parser = argparse.ArgumentParser() 50 | 51 | parser.add_argument("-i", "--image", required=True, help="Container image") 52 | parser.add_argument("-b", "--bucket", required=True, help="Storage bucket") 53 | parser.add_argument("-k", "--ksa", required=True, help="Kubernetes Service Account") 54 | parser.add_argument("-c", "--gpu-count", required=True, type=int, help="GPU count") 55 | parser.add_argument("-g", "--gpu-model", required=True, type=GPUs.from_string, choices=[x for x in GPUs], help="GPU model") 56 | 57 | args = parser.parse_args() 58 | run(args) 59 | -------------------------------------------------------------------------------- /pipeline_tool/gpu_alloc.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | import torch 17 | 18 | def BToMb(x): 19 | """Convert bytes to megabytes. 20 | 21 | :param x: Value in bytes. 22 | :type x: int 23 | :return: Value in megabytes. 24 | :rtype: int 25 | """ 26 | return (x // (2 * 1024)) 27 | 28 | class TraceMalloc(): 29 | def __init__(self, nb_gpu): 30 | """Initialize a TraceMalloc object. 31 | 32 | :param nb_gpu: Number of GPUs. 33 | :type nb_gpu: int 34 | """ 35 | self.nb_gpu = nb_gpu 36 | self.begin = [0] * nb_gpu 37 | self.end = [0] * nb_gpu 38 | self.peak = [0] * nb_gpu 39 | self.peaked = [0] * nb_gpu 40 | 41 | def __enter__(self): 42 | """Enter the context manager. 43 | 44 | Save the current memory allocated to all GPUs. 45 | 46 | :return: The TraceMalloc object. 47 | :rtype: TraceMalloc 48 | """ 49 | for device in range(self.nb_gpu): 50 | self.begin[device] = torch.cuda.memory_allocated(device) 51 | 52 | return self 53 | 54 | def __exit__(self, *exc): 55 | """Exit the context manager. 56 | 57 | Get all the memory information, allocated and peak, to calculate the true peak between the enter and exit call. 58 | """ 59 | for device in range(self.nb_gpu): 60 | self.end[device] = torch.cuda.memory_allocated(device) 61 | self.peak[device] = torch.cuda.max_memory_allocated(device) 62 | self.peaked[device] = BToMb(self.peak[device] - self.begin[device]) 63 | torch.cuda.reset_peak_memory_stats(device) -------------------------------------------------------------------------------- /benchmark/benchmark.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e "------------------------------------ 4 | LAUNCHING BENCHMARK OF PIPELINE TOOL 5 | Multiple models will be injected into 6 | the tool and will be profiled to see 7 | memory usage and execution time. 8 | ------------------------------------\n" 9 | 10 | echo "All the benchmark output will be written into a txt file." 11 | 12 | nb_gpus="$1" 13 | 14 | nb_epochs=4 15 | models=("CNN" "FFNET" "BigModel") 16 | chunks=("2") 17 | 18 | if [ -d "/var/lib/data/" ]; then 19 | data_dir="/var/lib/data" 20 | work_dir="/pipeline_tool/benchmark/benchmark.py" 21 | else 22 | data_dir="." 23 | work_dir="benchmark.py" 24 | fi 25 | 26 | rm -f "$data_dir/results.txt" 27 | 28 | time_sequence=$(seq -s ";" -f "Time %g [s]" $nb_epochs) 29 | alloc_sequence=$(seq -s ";" -f "Alloc %g [MB]" $nb_epochs) 30 | 31 | echo "Framework;Model;Number of GPUs;Number of Chunks;$time_sequence;$alloc_sequence" >> $data_dir/results.txt 32 | 33 | echo "------------------------------------" 34 | echo "Starting benchmarking refs with API Torch" 35 | echo " Benchmarking memory consumption and execution time with CNN..." 36 | output=$(python3 $work_dir CNN "API torch" --gpu 1 --chunk 0 --epochs $nb_epochs --dir $data_dir) 37 | printf " Task ended \e[32m[OK]\e[0m \n" 38 | echo "------------------------------------" 39 | echo " Benchmarking memory consumption and execution time with FFNET..." 40 | output=$(python3 $work_dir FFNET "API torch" --gpu 1 --chunk 0 --epochs $nb_epochs --dir $data_dir) 41 | printf " Task ended \e[32m[OK]\e[0m \n" 42 | echo -e "------------------------------------\n" 43 | echo " Benchmarking memory consumption and execution time with Vision Transformer..." 44 | output=$(python3 $work_dir BigModel "API torch" --gpu 1 --chunk 0 --epochs $nb_epochs --dir $data_dir) 45 | printf " Task ended \e[32m[OK]\e[0m \n" 46 | echo -e "------------------------------------\n" 47 | 48 | echo "Starting benchmarking Pipeline Tool" 49 | for model in "${models[@]}"; do 50 | for ((i = 1; i <= nb_gpus; i++)); do 51 | for chunk in "${chunks[@]}"; do 52 | echo "------------------------------------" 53 | echo " Benchmarking memory consumption and execution time with $model on $i GPUs and $chunk chunks..." 54 | output=$(python3 $work_dir $model "Pipeline" --gpu $i --chunk $chunk --epochs $nb_epochs --dir $data_dir) 55 | printf " Task ended \e[32m[OK]\e[0m \n" 56 | done 57 | done 58 | done 59 | 60 | echo "------------------------------------" 61 | -------------------------------------------------------------------------------- /pipeline_tool/whitelist.txt: -------------------------------------------------------------------------------- 1 | Conv1d 2 | Conv2d 3 | Conv3d 4 | ConvTranpose1d 5 | ConvTranpose2d 6 | ConvTranpose3d 7 | LazyConv1d 8 | LazyConv2d 9 | LazyConv3d 10 | LazyConvTranspose1d 11 | LazyConvTranspose2d 12 | LazyConvTranspose3d 13 | Unfold 14 | Fold 15 | MaxPool1d 16 | MaxPool2d 17 | MaxPool3d 18 | MaxUnPool1d 19 | MaxUnPool2d 20 | MaxUnPool3d 21 | AvgPool1d 22 | AvgPool2d 23 | AvgPool3d 24 | FractionalMaxPool2d 25 | FractionalMaxPool3d 26 | LPPool1d 27 | LPPool2d 28 | AdaptiveMaxPool1d 29 | AdaptiveMaxPool2d 30 | AdaptiveMaxPool3d 31 | AdaptiveAvgPool1d 32 | AdaptiveAvgPool2d 33 | AdaptiveAvgPool3d 34 | ReflectionPad1d 35 | ReflectionPad2d 36 | ReflectionPad3d 37 | ReplicationPad1d 38 | ReplicationPad2d 39 | ReplicationPad3d 40 | ZeroPad2d 41 | ConstantPad1d 42 | ConstantPad2d 43 | ConstantPad3d 44 | MultiheadAttention 45 | ELU 46 | Hardshrink 47 | Hardsigmoid 48 | Hardtanh 49 | Hardswish 50 | LeakyReLU 51 | LogSigmoid 52 | PReLU 53 | ReLU 54 | ReLU6 55 | RReLU 56 | SELU 57 | CELU 58 | GELU 59 | Sigmoid 60 | SiLU 61 | Mish 62 | Softplus 63 | Softshrink 64 | Softsign 65 | Tanh 66 | Tanhshrink 67 | Threshold 68 | GLU 69 | Softmin 70 | Softmax 71 | Softmax2d 72 | LogSoftmax 73 | AdaptiveLogSoftmaxWithLoss 74 | BatchNorm1d 75 | BatchNorm2d 76 | BatchNorm3d 77 | LazyBatchNorm1d 78 | LazyBatchNorm2d 79 | LazyBatchNorm3d 80 | GroupNorm 81 | SyncBatchNorm 82 | InstanceNorm1d 83 | InstanceNorm2d 84 | InstanceNorm3d 85 | LazyInstanceNorm1d 86 | LazyInstanceNorm2d 87 | LazyInstanceNorm3d 88 | LayerNorm 89 | LocalResponseNorm 90 | RNNBase 91 | RNN 92 | LSTM 93 | GRU 94 | RNNCell 95 | LSTMCell 96 | GRUCell 97 | Transformer 98 | TransformerEncoder 99 | TransformerDecoder 100 | TransformerEncoderLayer 101 | TransformerDecoderLayer 102 | Identity 103 | Linear 104 | Bilinear 105 | LazyLinear 106 | Dropout 107 | Dropout1d 108 | Dropout2d 109 | Dropout3d 110 | AlphaDropout 111 | FeatureAlphaDropout 112 | Embedding 113 | EmbeddingBag 114 | CosineSimilarity 115 | PairwiseDistance 116 | L1Loss 117 | MSELoss 118 | CrossEntropyLoss 119 | CTCLoss 120 | NLLLoss 121 | PoissonNLLLoss 122 | GaussianNLLLoss 123 | KLDivLoss 124 | BCELoss 125 | BCEWithLogitsLoss 126 | MarginRankingLoss 127 | HingeEmbeddingLoss 128 | MultiLabelMarginLoss 129 | HuberLoss 130 | SmoothL1Loss 131 | SoftMarginLoss 132 | MultiLabelSoftMarginLoss 133 | CosineEmbeddingLoss 134 | MultiMarginLoss 135 | TripletMarginLoss 136 | TripletMarginWithDistanceLoss 137 | PixelShuffle 138 | PixelUnshuffle 139 | Upsample 140 | UpsamplingNearest2d 141 | UpsamplingBilinear2d 142 | ChannelShuffle 143 | DataParallel 144 | parallel.DistributedDataParallel 145 | Flatten 146 | Unflatten 147 | parameter.Parameter -------------------------------------------------------------------------------- /benchmark/README.md: -------------------------------------------------------------------------------- 1 | # Benchmark of Pipeline Tool 2 | 3 | ## In local 4 | The benchmark of the pipeline tool allows for checking the proper operation of the module in the environment, as well as verifying its execution speed and memory distribution on various GPUs. To obtain meaningful results, benchmarking is conducted on three different models: 5 | 6 | - A FFNET 7 | - A CNN 8 | - A Vision Transformer 9 | 10 | It involves running a complete model parsing, assessing its distribution, and conducting a training trial to verify the time and resources involved under real-world conditions. 11 | 12 | To initiate the benchmark, a script is provided: [benchmark.sh](benchmark.sh), which takes as its sole parameter the desired maximum number of GPUs. It will then run a trial for each model using the standard torch API to establish a baseline and subsequently run the pipeline tool for the three models on 1 to N GPUs, where N is the maximum specified in the script. 13 | 14 | The results will be stored in a text file in the following format: 15 | 16 | ```txt 17 | Framework;Model;Number of GPUs;Number of Chunks;Time 1 [s];Time 2 [s];Time 3 [s];Time 4 [s];Alloc 1 [MB];Alloc 2 [MB];Alloc 3 [MB];Alloc 4 [MB] 18 | API torch;CNN;1;0;2.3584954738616943;0.4620656967163086;0.45350098609924316;0.446514368057251;[747];[625];[625];[625] 19 | [...] 20 | Pipeline;CNN;1;2;2.887887954711914;0.9743552207946777;0.943678617477417;0.9702959060668945;[774];[628];[628];[628] 21 | [...] 22 | ``` 23 | ## On GKE 24 | To configure the command of this section, populate the variables below: 25 | ```bash 26 | PROJECT_ID="" 27 | CLUSTER_ZONE="" 28 | BUCKET="" 29 | SA_KUBE="" 30 | ARTIFACT_REGISTRY="" 31 | IMAGE_NAME="pipeline-benchmark:latest" 32 | IMAGE_FULLPATH="${CLUSTER_ZONE}-docker.pkg.dev/${PROJECT_ID}/${ARTIFACT_REGISTRY}/${IMAGE_NAME}" 33 | ``` 34 | 35 | ### Build Benchmark image 36 | The Docker image is build on nvidia/cuda runtime image. 37 | 38 | Execute this steps from the root of the project. 39 | ```bash 40 | cp benchmark/Dokerfile . 41 | docker builder build -t ${IMAGE_FULLPATH} . 42 | docker push ${IMAGE_FULLPATH} 43 | rm -f Dockerfile 44 | ``` 45 | 46 | ### Run deployment on GKE 47 | 48 | To simplify the creation of a Kubernetes pod, a script is provided, `gen_pod.py.` This script will enable the population of a template `pod_template.yml` and create a pod ready to be applied to a Kubernetes cluster. 49 | 50 | Here is how to use `gen_pod.py`: 51 | ```bash 52 | python3 gen_pod.py -i $IMAGE_FULLPATH -b $BUCKET -k $SA_KUBE -c 4 -g a100 53 | ``` 54 | Important thing to know is that the number of GPU set with -c will be passed to the script [benchmark.sh](benchmark.sh) 55 | And then apply the pod to the kubernets with : 56 | ```bash 57 | kubectl apply -f pod-a100-4.yml 58 | ``` 59 | -------------------------------------------------------------------------------- /pipeline_tool/class_impl/PropagationLayer.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | from .LayerClass import Layer 17 | 18 | class PropagationLayer(Layer): 19 | """Handle all the traced layer non define as call_module or call_function/method. 20 | 21 | :param node: Is the actual traced node from torch.fx. 22 | :type node: torch.fx.node.Node 23 | :param trace: Is the complete trace of torch.fx of the model. 24 | :type trace: torch.fx.graph._node_list 25 | :param prev_node: Is the just previous node in the trace before the actual traced node. 26 | :type node: torch.fx.node.Node 27 | """ 28 | 29 | def __init__(self, node, trace, prev_node): 30 | """Constructor.""" 31 | super().__init__(node, trace, prev_node) 32 | 33 | def get_declaration(self) -> str: 34 | """Generate and return the full class generated for a propagation layer. 35 | 36 | What we call a propagation layer, is a layer who do no direct action on the data but propagate it further. 37 | 38 | Sometimes this layer have a special argument to propagate but have to return the input for the next layers. 39 | 40 | :return: The full declaration of a Layer containing a CallFunction 41 | :rtype: str 42 | """ 43 | string = self.generate_class() 44 | 45 | task = "" 46 | if len(self.node.args) > 0 and self.node.op == "placeholder": 47 | task = str(self.node.args[0]) 48 | else: 49 | task = "input" 50 | 51 | string += self.generate_forward(task) 52 | 53 | return string 54 | 55 | def __str__(self) -> str: 56 | """Allow to print easily all the information of a layer. 57 | 58 | It adds a print to inform that it is a propagation layer. 59 | :return: String to print 60 | :rtype: str 61 | """ 62 | print_str = super().__str__() 63 | print_str += " This layer is just a propagation one\n\n" 64 | return print_str 65 | -------------------------------------------------------------------------------- /pipeline_tool/class_impl/CallModule.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | from .LayerClass import Layer 17 | 18 | class CallModule(Layer): 19 | """Handle all the traced layer define as "call_module". 20 | 21 | Modules are all the torch Module present in the file "whitelist.txt", we do not guaranty the handle of custom module. 22 | 23 | :param node: Is the actual traced node from torch.fx. 24 | :type node: torch.fx.node.Node 25 | :param trace: Is the complete trace of torch.fx of the model. 26 | :type trace: torch.fx.graph._node_list 27 | :param prev_node: Is the just previous node in the trace before the actual traced node. 28 | :type node: torch.fx.node.Node 29 | """ 30 | 31 | def __init__(self, node, trace, prev_node, module_desc): 32 | """Constructor.""" 33 | super().__init__(node, trace, prev_node) 34 | self.module_desc = module_desc 35 | 36 | def get_declaration(self) -> str: 37 | """Generate and return the full class generate for a layer containing a call method or call function. 38 | 39 | For example : 40 | .. code-block:: python 41 | @skippable... 42 | class {self.name}_layer(nn.Module): 43 | def __init__(self) -> None: 44 | super().__init__() 45 | self.fc = nn.call_module 46 | def forward(self, input): 47 | ... = yield pop... 48 | ret = call module (self.fc(input)) 49 | yield stash ... 50 | return ret 51 | 52 | :return: The full declaration of a Layer containing a CallModule 53 | :rtype: str 54 | """ 55 | string = self.generate_class() 56 | string += self.generate_init(str(self.module_desc)) 57 | 58 | task = f"self.fc(" 59 | for arg in self.args: 60 | # This is for handle the kwargs (i.e. dim=1) 61 | if isinstance(arg, tuple): 62 | task += f"{arg[0]}={arg[1]}, " 63 | else: 64 | task += f"{arg}, " 65 | task = task[:-2] 66 | task += ")" 67 | 68 | string += self.generate_forward(task) 69 | 70 | return string 71 | 72 | def __str__(self) -> str: 73 | """Allow to print easily all the information of a layer. 74 | 75 | It adds a print of the torch module executed. 76 | :return: String to print 77 | :rtype: str 78 | """ 79 | print_str = super().__str__() 80 | print_str += f" The module description is {self.module_desc}\n\n" 81 | return print_str 82 | -------------------------------------------------------------------------------- /pipeline_tool/evaluate_mem.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | from gpu_alloc import TraceMalloc 17 | from dataset import PipelineDataset 18 | from pipelinecache.layered_model import PipelinedModel 19 | import os 20 | import time 21 | import torch 22 | import argparse 23 | os.environ['MASTER_ADDR'] = 'localhost' 24 | os.environ['MASTER_PORT'] = '29600' 25 | 26 | parser = argparse.ArgumentParser() 27 | parser.add_argument('--input_shape', type=str, help='Input shape as a list') 28 | parser.add_argument('--output_shape', type=str, help='Output shape as a list') 29 | parser.add_argument('--number_gpu', type=int, help='Number of GPU') 30 | parser.add_argument('--number_chunks', type=int, help='Number of chunks') 31 | parser.add_argument('--dtype', type=str, help='Type of output\'s tensor (long, float32...)') 32 | args = parser.parse_args() 33 | 34 | input_shape = args.input_shape.replace("[", "").replace("]", "") 35 | input_shape = input_shape.split(",") 36 | input_shape = [int(x.strip()) for x in input_shape] 37 | 38 | output_shape = args.output_shape.replace("[", "").replace("]", "") 39 | output_shape = output_shape.split(",") 40 | output_shape = [int(x.strip()) for x in output_shape] 41 | 42 | number_gpus = args.number_gpu 43 | number_chunks = args.number_chunks 44 | 45 | 46 | trace_gpu_alloc = TraceMalloc(number_gpus) 47 | criterion = torch.nn.CrossEntropyLoss() 48 | 49 | torch.cuda.init() 50 | torch.distributed.rpc.init_rpc('worker', rank=0, world_size=1) 51 | 52 | with trace_gpu_alloc: 53 | 54 | model = PipelinedModel() 55 | dataset = PipelineDataset(1024, input_shape[1:], [1] if len(output_shape) == 1 else output_shape[1:], args.dtype) 56 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=input_shape[0], shuffle=True) 57 | 58 | model = model.get_modules() 59 | model = torch.distributed.pipeline.sync.Pipe(model, number_chunks) 60 | optimizer = torch.optim.SGD(model.parameters(), lr=0.001) 61 | 62 | for i in range(3): 63 | start_time = time.time() 64 | for inputs, labels in dataloader: 65 | optimizer.zero_grad() 66 | inputs = inputs.to(0) 67 | labels = labels.to(number_gpus- 1) 68 | 69 | try: 70 | outputs = model(inputs).local_value() 71 | except Exception as e: 72 | print(e) 73 | exit() 74 | 75 | labels_tmp = labels.squeeze() 76 | 77 | loss = criterion(outputs, labels.squeeze()) 78 | 79 | loss.backward() 80 | end_time = time.time() 81 | execution_time = end_time - start_time 82 | 83 | print(trace_gpu_alloc.peaked) 84 | 85 | 86 | -------------------------------------------------------------------------------- /pipeline_tool/class_impl/CallFunction.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | from .LayerClass import Layer 17 | from ..function_parser import _parse_func 18 | 19 | 20 | class CallFunction(Layer): 21 | """Handle all the traced layer define as "call_function". 22 | 23 | A call function is a layer with no init, he just executes a function or method on tensors. 24 | For example a torch.add or a call to the method expand. 25 | 26 | :param node: Is the actual traced node from torch.fx. 27 | :type node: torch.fx.node.Node 28 | :param trace: Is the complete trace of torch.fx of the model. 29 | :type trace: torch.fx.graph._node_list 30 | :param prev_node: Is the just previous node in the trace before the actual traced node. 31 | :type node: torch.fx.node.Node 32 | """ 33 | 34 | def __init__(self, node, trace, prev_node): 35 | """Constructor.""" 36 | super().__init__(node, trace, prev_node) 37 | # This call will return the exact function or method call 38 | self.function_call = _parse_func(node, self.args) 39 | 40 | def update_arg_by_attr(self, new_arg, position): 41 | """Allow to update argument with a specific attribute. 42 | 43 | For example t.shape. We need to reset the function call as we change the args. 44 | 45 | :param old_arg: Old argument to replace. 46 | :type old_arg: torch.fx.node.Node 47 | :param new_arg: New arg containing the attribute. (For ex .shape) 48 | :type new_arg: str 49 | """ 50 | super().update_arg_by_attr(new_arg, position) 51 | self.function_call = _parse_func(self.node, self.args) 52 | 53 | def get_declaration(self) -> str: 54 | """Generate and return the full class generate for a layer containing a call method or call function. 55 | 56 | For example : 57 | .. code-block:: python 58 | @skippable... 59 | class {self.name}_layer(nn.Module): 60 | def forward(self, input): 61 | ... = yield pop... 62 | ret = call function or call method (input.expand(16, -1, -1)) 63 | yield stash ... 64 | return ret 65 | 66 | :return: The full declaration of a Layer containing a CallFunction 67 | :rtype: str 68 | """ 69 | string = self.generate_class() 70 | string += self.generate_forward(self.function_call) 71 | 72 | return string 73 | 74 | def __str__(self) -> str: 75 | """Allow to print easily all the information of a layer. 76 | 77 | It adds a print of the function executed at the overload of the Layer class. 78 | 79 | :return: String to print 80 | :rtype: str 81 | """ 82 | print_str = super().__str__() 83 | print_str += f" The function call is {self.function_call}\n\n" 84 | return print_str 85 | -------------------------------------------------------------------------------- /pipeline_tool/dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | import torch 17 | 18 | class PipelineDataset(torch.utils.data.Dataset): 19 | def __init__(self, size, input_shape, output_shape, dtype="long"): 20 | """Initialize a PipelineDataset object. 21 | 22 | :param size: Size of the dataset. 23 | :type size: int 24 | :param input_shape: Shape of the input data. 25 | :type input_shape: tuple 26 | :param output_shape: Shape of the output data. 27 | :type output_shape: tuple 28 | """ 29 | self.size = size 30 | self.input_shape = input_shape 31 | self.output_shape = output_shape 32 | self.dtype = self.parse_dtype(dtype) 33 | 34 | def parse_dtype(self, dtype): 35 | """Map data type in string format to return data type of API torch 36 | 37 | :param dtype: Data type 38 | :type dtype: str 39 | :return: Data type of API torch 40 | :rtype: dtype 41 | """ 42 | data_type_mapping = { 43 | 'float32': torch.float32, 44 | 'float': torch.float32, 45 | 'float64': torch.float64, 46 | 'double': torch.float64, 47 | 'float16': torch.float16, 48 | 'half': torch.float16, 49 | 'bfloat16': torch.bfloat16, 50 | 'complex32': torch.complex32, 51 | 'chalf': torch.complex32, 52 | 'complex64': torch.complex64, 53 | 'cfloat': torch.complex64, 54 | 'complex128': torch.complex128, 55 | 'cdouble': torch.complex128, 56 | 'uint8': torch.uint8, 57 | 'byte': torch.uint8, 58 | 'int8': torch.int8, 59 | 'char': torch.int8, 60 | 'int16': torch.int16, 61 | 'short': torch.int16, 62 | 'int32': torch.int32, 63 | 'int': torch.int32, 64 | 'int64': torch.int64, 65 | 'long': torch.int64, 66 | 'bool': torch.bool, 67 | 'quint8': torch.quint8, 68 | 'qint8': torch.qint8, 69 | 'qint32': torch.qint32, 70 | 'quint4x2': torch.quint4x2 71 | } 72 | data_type_str = dtype.lower() # Convertir en minuscules pour être insensible à la casse 73 | return data_type_mapping.get(dtype, None) 74 | 75 | def __len__(self): 76 | """Return the length of the dataset. 77 | 78 | :return: Length of the dataset. 79 | :rtype: int 80 | """ 81 | return self.size 82 | 83 | def __getitem__(self, idx): 84 | """Get an item from the dataset at the given index. 85 | 86 | :param idx: Index of the item. 87 | :type idx: int 88 | :return: Tuple of input data and target data. 89 | :rtype: tuple 90 | """ 91 | data = torch.randn(*self.input_shape) 92 | target = torch.randint(0, 2, self.output_shape, dtype=self.dtype) 93 | return data, target 94 | 95 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.rst: -------------------------------------------------------------------------------- 1 | CONTRIBUTOR CODE OF CONDUCT 2 | =========================== 3 | (Code of Conduct) 4 | ----------------- 5 | 6 | 7 | Our Pledge 8 | ---------- 9 | 10 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 11 | 12 | Our Standards 13 | ------------- 14 | 15 | Examples of behavior that contributes to creating a positive environment include: 16 | 17 | * Using welcoming and inclusive language; 18 | * Being respectful of differing viewpoints and experiences; 19 | * Gracefully accepting constructive criticism; 20 | * Focusing on what is best for the community; 21 | * Showing empathy towards other community members. 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or advances; 26 | * Trolling, insulting/derogatory comments, and personal or political attacks; 27 | * Public or private harassment; 28 | * Publishing others’ private information, such as a physical or electronic address, without explicit permission; 29 | * Other conduct which could reasonably be considered inappropriate in a professional setting. 30 | 31 | Our Responsibilities 32 | -------------------- 33 | 34 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 35 | 36 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 37 | 38 | Scope 39 | ----- 40 | 41 | This Code of Conduct applies within all Giotto’s project spaces, to all content on , Giotto’s GitHub organization, or any other official Giotto web presence allowing for community interactions, and it also applies when an individual is representing the project or its community in public spaces. 42 | 43 | Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 44 | 45 | Enforcement 46 | ----------- 47 | 48 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances, Sanctions may include written warnings, expulsions from the project, project sponsored spaces, or project forums, or any other sanction which is deemed appropriate. [The project team] is obligated to maintain confidentiality with regard to the reporter of an incident. If the act is ongoing (such as someone engaging in harassment) or involves a threat to anyone's safety (e.g. threats of violence), the the project team may issue sanctions without notice. Further details of specific enforcement policies may be posted separately. 49 | 50 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by the project leader. 51 | 52 | Attribution 53 | ----------- 54 | 55 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at , and includes some aspects of the TensorFlow Code of Conduct, available at 56 | -------------------------------------------------------------------------------- /pipeline_tool/class_impl/GetAttrModule.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | from .LayerClass import Layer 17 | import torch 18 | 19 | 20 | class GetAttrModule(Layer): 21 | """Handle all the traced layer define as "getattr". 22 | 23 | If a special self is used in the module traced, torch fx mark it as an getattr layer. 24 | So we have to recreate the self object used and propagate it. 25 | 26 | For the moment only nn.parameter.Parameter are handled. 27 | 28 | :param node: Is the actual traced node from torch.fx. 29 | :type node: torch.fx.node.Node 30 | :param trace: Is the complete trace of torch.fx of the model. 31 | :type trace: torch.fx.graph._node_list 32 | :param prev_node: Is the just previous node in the trace before the actual traced node. 33 | :type node: torch.fx.node.Node 34 | :param net: The network given to the pipeline tool. 35 | :type net: Non-specific, could be a module or a set of module. 36 | """ 37 | 38 | def __init__(self, node, trace, prev_node, net): 39 | """Constructor.""" 40 | super().__init__(node, trace, prev_node) 41 | # We have to split the node.target because he contains the name of the attribute used. 42 | # For example "model.pooling.layer.query" the name of the attribute is the last word, query. 43 | module_tmp = str(node.target).split('.') 44 | tmp = "" 45 | for name in module_tmp[0:-1]: 46 | tmp += f"{name}." 47 | tmp = tmp[:-1] 48 | attr_parsed = module_tmp[len(module_tmp) - 1:] 49 | 50 | # Once we have the attribute to found we will search in the network given by the user 51 | for name, module in net.named_modules(): 52 | if str(name) == tmp: 53 | attr = getattr(module, attr_parsed[0]) 54 | 55 | if isinstance(attr, torch.nn.parameter.Parameter): 56 | self.module_attr_desc = "parameter.Parameter(torch.Tensor(" 57 | 58 | for shape in attr.shape: 59 | self.module_attr_desc += f"{shape}, " 60 | 61 | self.module_attr_desc = self.module_attr_desc[:-2] 62 | 63 | requires_grad = getattr(attr, "requires_grad") 64 | 65 | self.module_attr_desc += f"), requires_grad={requires_grad})" 66 | 67 | def get_declaration(self) -> str: 68 | """Generate and return the full class generate for a layer containing a gettatr of a module. 69 | 70 | For example : 71 | .. code-block:: python 72 | @skippable... 73 | class {self.name}_layer(nn.Module): 74 | def __init__(self) -> None: 75 | super().__init__() 76 | self.fc = nn.parameter.Parameter(torch.Tensor(1, 16), requires_grad=True) 77 | def forward(self, input): 78 | ret = self.fc 79 | yield stash ... 80 | return ret 81 | :return: The full class generated for a getattr layer 82 | :rtype: str 83 | """ 84 | string = self.generate_class() 85 | string += self.generate_init(str(self.module_attr_desc)) 86 | string += self.generate_forward("self.fc") 87 | 88 | return string 89 | 90 | def __str__(self) -> str: 91 | """Allow to print easily all the information of a layer. 92 | 93 | It adds a print of the parameter created in the layer. 94 | :return: String to print 95 | :rtype: str 96 | """ 97 | print_str = super().__str__() 98 | print_str += f" The parameter description is {self.module_attr_desc}\n\n" 99 | return print_str 100 | -------------------------------------------------------------------------------- /examples/00_Basic_usage.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import os 5 | import sys 6 | 7 | # Define the project root and add it to the sys path 8 | # project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) 9 | # sys.path.append(project_root) 10 | 11 | # Define the CNN model 12 | class CNN(nn.Module): 13 | def __init__(self): 14 | super().__init__() 15 | self.conv1 = nn.Conv2d(3, 6, 5) 16 | self.pool = nn.MaxPool2d(2, 2) 17 | self.conv2 = nn.Conv2d(6, 16, 5) 18 | self.fc1 = nn.Linear(16 * 5 * 5, 120) 19 | self.fc2 = nn.Linear(120, 84) 20 | self.fc3 = nn.Linear(84, 10) 21 | 22 | def forward(self, x): 23 | x = self.pool(F.relu(self.conv1(x))) 24 | x = self.pool(F.relu(self.conv2(x))) 25 | x = torch.flatten(x, 1) 26 | x = F.relu(self.fc1(x)) 27 | x = F.relu(self.fc2(x)) 28 | x = self.fc3(x) 29 | return x 30 | 31 | # Create the CNN model and save a reference to it 32 | model = CNN() 33 | model_saved = model 34 | 35 | # Prepare configuration 36 | from pipeline_tool.pipeline_config import PipelineConfig 37 | # from pipeline_config import PipelineConfig 38 | batch_size = 4 39 | 40 | # Define the input and output shapes and data type 41 | config_pipeline = PipelineConfig(input_shape=[batch_size, 3, 32, 32], 42 | output_shape=[batch_size], 43 | data_type="long") 44 | 45 | # Prepare pipelined model with skippable tracing 46 | from pipeline_tool.pipeline_tool import SkippableTracing 47 | 48 | nb_gpu = torch.cuda.device_count() 49 | trace = SkippableTracing(nb_gpus=nb_gpu, model=model, config=config_pipeline) 50 | 51 | # Get modules from tracing 52 | model = trace.get_modules() 53 | 54 | # Prepare Pipe from API torch 55 | from torch.distributed.pipeline.sync import Pipe 56 | nb_chunk = 2 57 | 58 | # Initialize RPC 59 | os.environ['MASTER_ADDR'] = 'localhost' 60 | os.environ['MASTER_PORT'] = '29600' 61 | torch.distributed.rpc.init_rpc('worker', rank=0, world_size=1) 62 | 63 | # Create a pipelined model 64 | model = Pipe(module=model, chunks=nb_chunk) 65 | 66 | # Download the CIFAR-10 dataset 67 | import torchvision 68 | import torchvision.transforms as transforms 69 | 70 | # Define data transformations 71 | transform = transforms.Compose( 72 | [transforms.ToTensor(), 73 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) 74 | 75 | # Load the training dataset 76 | trainset = torchvision.datasets.CIFAR10(root='./data', train=True, 77 | download=True, transform=transform) 78 | trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, 79 | shuffle=True, num_workers=2) 80 | 81 | # Load the test dataset 82 | testset = torchvision.datasets.CIFAR10(root='./data', train=False, 83 | download=True, transform=transform) 84 | testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, 85 | shuffle=False, num_workers=2) 86 | 87 | # Train the model 88 | optimizer = torch.optim.SGD(model.parameters(), lr=0.01) 89 | loss_fn = nn.CrossEntropyLoss() 90 | 91 | for epoch in range(1): 92 | running_loss = 0.0 93 | 94 | for i, data in enumerate(trainloader, 0): 95 | input, label = data 96 | 97 | input = input.to(0) 98 | label = label.to(nb_gpu - 1) 99 | 100 | optimizer.zero_grad() 101 | 102 | output = model(input).local_value() 103 | 104 | loss = loss_fn(output, label) 105 | 106 | loss.backward() 107 | optimizer.step() 108 | 109 | running_loss += loss.item() 110 | if i % 2000 == 1999: 111 | print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}') 112 | running_loss = 0.0 113 | 114 | print('Finished Training') 115 | 116 | # Validate the model 117 | correct = 0 118 | total = 0 119 | 120 | # Since we're not training, we don't need to calculate gradients for outputs 121 | with torch.no_grad(): 122 | for data in testloader: 123 | images, labels = data 124 | images = images.to(0) 125 | labels = labels.to(nb_gpu - 1) 126 | # Calculate outputs by running images through the network 127 | outputs = model(images).local_value() 128 | # The class with the highest energy is the prediction 129 | _, predicted = torch.max(outputs.data, 1) 130 | total += labels.size(0) 131 | correct += (predicted == labels).sum().item() 132 | 133 | print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %') 134 | 135 | # Save the model 136 | trained_weights = {} 137 | for (_, value_src), (key, _) in zip(model.state_dict().items(), model_saved.state_dict().items()): 138 | trained_weights[key] = value_src 139 | 140 | model_saved.load_state_dict(trained_weights) 141 | 142 | # Define the path to save the model 143 | PATH = './cifar_net.pth' 144 | torch.save(model_saved.state_dict(), PATH) 145 | -------------------------------------------------------------------------------- /pipeline_tool/class_impl/GetAttr.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | import torch 17 | from ..function_parser import _parse_func 18 | 19 | class GetAttr: 20 | """Handle all the getattr. 21 | 22 | A getattr cannot be a layer because the result of a getattr is not a tensor. 23 | So we have to attach the getattr with the Layer who need to use a getattr on his attribute. 24 | For that we create an object who save all the information, parent, child and attribute for the getattr. 25 | :param node: The actual getattr node 26 | :type node: torch.fx.node.Node 27 | :param trace: The trace of the model generated by torch fx 28 | :type trace: torch.fx.graph._node_list 29 | """ 30 | 31 | def __init__(self, node, trace, child = None): 32 | """Constructor.""" 33 | self.getitem_idx = None 34 | self.parent = node.args[0] 35 | self.attr = node.args[1] 36 | self.stash_needed = False 37 | self.node = node 38 | self.position = 0 39 | 40 | self.child = child 41 | if self.child is None: 42 | for _node in trace: 43 | if node in _node.args: 44 | if str(_node).find("getitem") >= 0: 45 | node = _node 46 | else: 47 | self.child = _node 48 | self.position = _node.args.index(node) 49 | break 50 | # Verifiy if the result of the getattr need to be stashed. 51 | prev_node = None 52 | for _node in trace: 53 | if _node == self.child: 54 | if prev_node != self.parent: 55 | self.stash_needed = True 56 | self.getattr_string = f"{self.parent}.{self.attr}" 57 | else: 58 | self.getattr_string = f"input.{self.attr}" 59 | 60 | if not str(_node).find("getitem") >= 0 and self.node != _node: 61 | prev_node = _node 62 | 63 | def get_position(self) -> int: 64 | """Return the position of the attribute in the list of param during the call 65 | 66 | :return: Return the position of the attribute in the list of param during the call 67 | :rtype: int 68 | """ 69 | return self.position 70 | 71 | def get_attr_name(self) -> str: 72 | """Return the name of the attribute used. 73 | 74 | :return: Return the name of the attribute used 75 | :rtype: str 76 | """ 77 | return self.getattr_string 78 | 79 | def get_child(self) -> torch.fx.node.Node: 80 | """Return the node in which the getattr will be done. 81 | 82 | :return: Return the child node of the getattr 83 | :rtype: torch.fx.node.Node 84 | """ 85 | return self.child 86 | 87 | def get_parent(self) -> torch.fx.node.Node: 88 | """Return the node of the ret value on which will be done the getattr. 89 | 90 | :return: Return the parent node of the getattr 91 | :rtype: torch.fx.node.Node 92 | """ 93 | if self.stash_needed: 94 | return self.parent 95 | else: 96 | return 'input' 97 | 98 | def add_getitem(self, idx): 99 | """Allow to add a getitem on a getattr call. 100 | 101 | For example : input.shape[0] 102 | 103 | :param idx: The index of the getitem 104 | :type idx: int 105 | """ 106 | self.getitem_idx = idx 107 | self.getattr_string += f"[{self.getitem_idx}]" 108 | 109 | def is_stash_needed(self) -> bool: 110 | """Return True if the getattr need to be stashed, else False. 111 | 112 | :return: If stash is needed 113 | :rtype: bool 114 | """ 115 | return self.stash_needed 116 | 117 | def __str__(self) -> str: 118 | """Allow to print easily all the information of a Getattr. 119 | 120 | :return: String to print 121 | :rtype: str 122 | """ 123 | print_str = "GetAttr info : \n" 124 | print_str += f" Attribute {self.attr} of ret of node {self.parent}\n" 125 | print_str += f" This getattr is needed in {self.child}\n" 126 | print_str += f" If not empty use those specific idx of the result {self.getitem_idx}\n" 127 | if self.stash_needed: 128 | print_str += f" A new stash have to be add on {self.parent} for {self.child}\n" 129 | else: 130 | print_str += f" No new stash need to be added on {self.parent}, the dest is directly connected\n" 131 | 132 | return print_str 133 | -------------------------------------------------------------------------------- /examples/01_Multihead_handling.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import os 5 | import sys 6 | 7 | # Define the project root and add it to the sys path 8 | project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) 9 | sys.path.append(project_root) 10 | 11 | # Define the Vision Transformer model 12 | from torchvision.models import vit_h_14 13 | class VisionTransformer(nn.Module): 14 | def __init__(self) -> None: 15 | super().__init__() 16 | self.model = vit_h_14(weights='DEFAULT') 17 | 18 | def forward(self, image): 19 | return self.model(image) 20 | 21 | # Create the Vision Tranformer model and save a reference to it 22 | model = VisionTransformer() 23 | model_saved = model 24 | 25 | # Prepare configuration 26 | from pipeline_tool.pipeline_config import PipelineConfig 27 | batch_size = 4 28 | 29 | # Define the input and output shapes and data type 30 | config_pipeline = PipelineConfig(input_shape=[batch_size, 3, 518, 518], 31 | output_shape=[batch_size, 1000], 32 | data_type="float") 33 | 34 | # Add Multihead configuration to PipelineConfig 35 | nb_mha = 33 36 | num_heads = 16 37 | embed_dim = 1280 38 | dropout = 0.0 39 | batch_first = True 40 | 41 | config_pipeline.create_mha_conf_equal(nb_mha, num_heads, embed_dim, dropout, batch_first) 42 | 43 | # Prepare pipelined model with skippable tracing 44 | from pipeline_tool.pipeline_tool import SkippableTracing 45 | 46 | # Here it should end if you have not enough space on your GPU to handle it by an error CUDA OOM. 47 | nb_gpu = 1 48 | try: 49 | trace = SkippableTracing(nb_gpus=nb_gpu, model=model, config=config_pipeline) 50 | except Exception as e: 51 | print(e) 52 | # Change to two or more GPU to be able to use this model 53 | nb_gpu = 2 54 | try: 55 | trace = SkippableTracing(nb_gpus=nb_gpu, model=model, config=config_pipeline) 56 | except Exception as e: 57 | print(e) 58 | 59 | # Get modules from tracing 60 | model = trace.get_modules() 61 | 62 | # Prepare Pipe from API torch 63 | from torch.distributed.pipeline.sync import Pipe 64 | nb_chunk = 2 65 | 66 | # Initialize RPC 67 | os.environ['MASTER_ADDR'] = 'localhost' 68 | os.environ['MASTER_PORT'] = '29600' 69 | torch.distributed.rpc.init_rpc('worker', rank=0, world_size=1) 70 | 71 | # Create a pipelined model 72 | model = Pipe(module=model, chunks=nb_chunk) 73 | 74 | # Download the CIFAR-10 dataset 75 | import torchvision 76 | import torchvision.transforms as transforms 77 | 78 | # Define data transformations 79 | from torchvision import transforms 80 | transform = transforms.Compose([ 81 | transforms.RandomResizedCrop(518), 82 | transforms.RandomHorizontalFlip(), 83 | transforms.ToTensor(), 84 | transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.299, 0.224, 0.225]) 85 | ]) 86 | 87 | # Load the training dataset 88 | trainset = torchvision.datasets.CIFAR10(root='./data', train=True, 89 | download=True, transform=transform) 90 | 91 | train, val = torch.utils.data.random_split(trainset, [0.1, 0.9]) 92 | 93 | trainloader = torch.utils.data.DataLoader(train, batch_size=batch_size, 94 | shuffle=True) 95 | 96 | 97 | # Load the test dataset 98 | testset = torchvision.datasets.CIFAR10(root='./data', train=False, 99 | download=True, transform=transform) 100 | test, val = torch.utils.data.random_split(testset, [0.1, 0.9]) 101 | 102 | testloader = torch.utils.data.DataLoader(test, batch_size=batch_size, 103 | shuffle=False) 104 | 105 | # Train the model with not enough space 106 | optimizer = torch.optim.SGD(model.parameters(), lr=0.01) 107 | loss_fn = nn.CrossEntropyLoss() 108 | 109 | for epoch in range(1): 110 | running_loss = 0.0 111 | 112 | for i, data in enumerate(trainloader, 0): 113 | input, label = data 114 | 115 | input = input.to(0) 116 | label = label.to(nb_gpu - 1) 117 | 118 | optimizer.zero_grad() 119 | 120 | output = model(input).local_value() 121 | 122 | loss = loss_fn(output, label) 123 | 124 | loss.backward() 125 | optimizer.step() 126 | 127 | running_loss += loss.item() 128 | if i % 2000 == 1999: 129 | print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}') 130 | running_loss = 0.0 131 | 132 | print('Finished Training') 133 | 134 | # Validate the model 135 | correct = 0 136 | total = 0 137 | 138 | # Since we're not training, we don't need to calculate gradients for outputs 139 | with torch.no_grad(): 140 | for data in testloader: 141 | images, labels = data 142 | images = images.to(0) 143 | labels = labels.to(nb_gpu - 1) 144 | # Calculate outputs by running images through the network 145 | outputs = model(images).local_value() 146 | # The class with the highest energy is the prediction 147 | _, predicted = torch.max(outputs.data, 1) 148 | total += labels.size(0) 149 | correct += (predicted == labels).sum().item() 150 | 151 | print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %') 152 | 153 | # Save the model 154 | trained_weights = {} 155 | for (_, value_src), (key, _) in zip(model.state_dict().items(), model_saved.state_dict().items()): 156 | trained_weights[key] = value_src 157 | 158 | model_saved.load_state_dict(trained_weights) 159 | 160 | # Define the path to save the model 161 | PATH = './cifar_net.pth' 162 | torch.save(model_saved.state_dict(), PATH) -------------------------------------------------------------------------------- /benchmark/utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | import torch.nn as nn 4 | from torchvision.models import vit_h_14 5 | from torchvision import transforms, datasets 6 | from torch.utils.data import DataLoader 7 | import os 8 | import sys 9 | import logging 10 | 11 | project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) 12 | sys.path.append(project_root) 13 | 14 | from pipeline_tool.dataset import PipelineDataset 15 | 16 | class CNN(nn.Module): 17 | def __init__(self): 18 | super().__init__() 19 | self.conv1 = nn.Conv2d(3, 6, 5) 20 | self.pool = nn.MaxPool2d(2, 2) 21 | self.conv2 = nn.Conv2d(6, 16, 5) 22 | self.fc1 = nn.Linear(16 * 5 * 5, 120) 23 | self.fc2 = nn.Linear(120, 84) 24 | self.fc3 = nn.Linear(84, 10) 25 | 26 | def forward(self, x): 27 | x = self.pool(F.relu(self.conv1(x))) 28 | x = self.pool(F.relu(self.conv2(x))) 29 | x = torch.flatten(x, 1) 30 | x = F.relu(self.fc1(x)) 31 | x = F.relu(self.fc2(x)) 32 | x = self.fc3(x) 33 | return x 34 | 35 | def get_input_shape(self): 36 | return [4, 3, 32, 32] 37 | 38 | def get_output_shape(self): 39 | return [4] 40 | 41 | def get_dtype(self): 42 | return "long" 43 | 44 | def get_trainloader(self): 45 | dataset = PipelineDataset(1024, self.get_input_shape()[1:], [1] if len(self.get_output_shape()) == 1 else self.get_output_shape()[1:], "long") 46 | return torch.utils.data.DataLoader(dataset, batch_size=self.get_input_shape()[0], shuffle=True) 47 | 48 | class FFNET(nn.Module): 49 | def __init__(self) -> None: 50 | super().__init__() 51 | self.fc1 = nn.Linear(28*28, 100) 52 | self.sigmoid = nn.Sigmoid() 53 | self.fc2 = nn.Linear(100, 10) 54 | 55 | def forward(self, x): 56 | out = self.fc1(x) 57 | out = self.sigmoid(out) 58 | out = self.fc2(out) 59 | return out 60 | 61 | def get_input_shape(self): 62 | return [4, 28*28] 63 | 64 | def get_output_shape(self): 65 | return [4] 66 | 67 | def get_dtype(self): 68 | return "long" 69 | 70 | def get_trainloader(self): 71 | dataset = PipelineDataset(1024, self.get_input_shape()[1:], [1] if len(self.get_output_shape()) == 1 else self.get_output_shape()[1:], self.get_dtype()) 72 | return torch.utils.data.DataLoader(dataset, batch_size=self.get_input_shape()[0], shuffle=True) 73 | 74 | class Debug(nn.Module): 75 | def __init__(self, n) -> None: 76 | super().__init__() 77 | self.fc1 = nn.Linear(28*28, 100) 78 | self.sigmoid = nn.Sigmoid() 79 | self.fc2 = nn.Linear(100, 10) 80 | 81 | def forward(self, x): 82 | out = self.fc1(x) 83 | out = self.sigmoid(out) 84 | out = self.fc2(out) 85 | return out 86 | 87 | def get_input_shape(self): 88 | return [2, 4] 89 | 90 | def get_output_shape(self): 91 | return [2] 92 | 93 | def get_dtype(self): 94 | return "long" 95 | 96 | def get_trainloader(self): 97 | dataset = PipelineDataset(1024, self.get_input_shape()[1:], [1] if len(self.get_output_shape()) == 1 else self.get_output_shape()[1:], self.get_dtype()) 98 | return torch.utils.data.DataLoader(dataset, batch_size=self.get_input_shape()[0], shuffle=True) 99 | 100 | class BigModel(nn.Module): 101 | def __init__(self) -> None: 102 | super().__init__() 103 | self.model = vit_h_14(weights='DEFAULT') 104 | 105 | def forward(self, image): 106 | return self.model(image) 107 | 108 | def get_input_shape(self): 109 | return [4, 3, 518, 518] 110 | 111 | def get_output_shape(self): 112 | return [4, 1000] 113 | 114 | def get_dtype(self): 115 | return "float" 116 | 117 | def get_trainloader(self): 118 | 119 | transform = transforms.Compose([ 120 | transforms.RandomResizedCrop(518), 121 | transforms.RandomHorizontalFlip(), 122 | transforms.ToTensor(), 123 | transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.299, 0.224, 0.225]) 124 | ]) 125 | trainset = datasets.CIFAR10(root="./data", 126 | train=True, 127 | download=True, 128 | transform=transform) 129 | 130 | train, val = torch.utils.data.random_split(trainset, [0.1, 0.9]) 131 | 132 | train_loader = DataLoader(train, batch_size=4, shuffle=True) 133 | return train_loader 134 | 135 | def get_mha_num_heads(self): 136 | return 16 137 | 138 | def get_mha_embed_dim(self): 139 | return 1280 140 | 141 | def get_dropout(self): 142 | return 0.0 143 | 144 | def get_batch_frist(self): 145 | return True 146 | 147 | 148 | def training_normal(model, trainloader, device, optimizer, loss_fn): 149 | running_loss = 0.0 150 | 151 | for i, data in enumerate(trainloader, 0): 152 | input, label = data 153 | input, label = input.to(device), label.to(device) 154 | 155 | optimizer.zero_grad() 156 | 157 | output = model(input) 158 | loss = loss_fn(output, label.squeeze()) 159 | loss.backward() 160 | optimizer.step() 161 | 162 | running_loss += loss.item() 163 | 164 | 165 | def training_pipeline(model, trainloader, nb_gpu, optimizer, loss_fn): 166 | running_loss = 0.0 167 | 168 | for i, data in enumerate(trainloader, 0): 169 | input, label = data 170 | 171 | input = input.to(0) 172 | label = label.to(nb_gpu - 1) 173 | 174 | optimizer.zero_grad() 175 | 176 | output = model(input).local_value() 177 | loss = loss_fn(output, label.squeeze()) 178 | loss.backward() 179 | optimizer.step() 180 | 181 | running_loss += loss.item() 182 | 183 | -------------------------------------------------------------------------------- /benchmark/benchmark.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import torch 3 | import torch.nn as nn 4 | import utils 5 | import os 6 | import sys 7 | import time 8 | from pipeline_tool.pipeline_config import PipelineConfig 9 | from pipeline_tool.pipeline_tool import SkippableTracing 10 | 11 | os.environ['MASTER_ADDR'] = 'localhost' 12 | os.environ['MASTER_PORT'] = '29600' 13 | 14 | project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) 15 | sys.path.append(project_root) 16 | 17 | from torch.distributed.pipeline.sync import Pipe 18 | 19 | nb_epochs = 2 20 | 21 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 22 | 23 | class Mode: 24 | def __init__(self, model, chunk, framework, gpu, epochs): 25 | self.model = model 26 | self.chunk = chunk 27 | self.framework = framework 28 | self.gpu = gpu 29 | self.epochs = epochs 30 | 31 | def set_model(self, model): 32 | self.model = model 33 | 34 | def set_chunk(self, chunk): 35 | self.chunk = chunk 36 | 37 | def set_gpu(self, gpu): 38 | self.gpu = gpu 39 | 40 | def set_framework(self, framework): 41 | self.framework = framework 42 | 43 | 44 | class BenchmarkMode: 45 | def __init__(self, args): 46 | self.args = args 47 | self.mem_alloc = [] 48 | self.exec_time = [] 49 | self.setup_model() 50 | self.setup_optimizer() 51 | self.setup_loss_fn() 52 | 53 | def setup_model(self): 54 | count_mha = 1 55 | if self.args.model == "CNN": 56 | self.model = utils.CNN() 57 | elif self.args.model == "FFNET": 58 | self.model = utils.FFNET() 59 | elif self.args.model == "Transformers": 60 | self.model = utils.Transformers() 61 | elif self.args.model == "Basic": 62 | self.model = None 63 | elif self.args.model == "Debug": 64 | self.model = utils.Debug() 65 | elif self.args.model == "BigModel": 66 | self.model = utils.BigModel() 67 | for name, module in self.model.named_modules(): 68 | if str(module).split('(', 1)[0].find('Multi') >= 0: 69 | count_mha += 1 70 | else: 71 | raise ValueError("Given model is not known.") 72 | 73 | input_shape = self.model.get_input_shape() 74 | output_shape = self.model.get_output_shape() 75 | 76 | self.trainloader = self.model.get_trainloader() 77 | if count_mha > 1: 78 | config = PipelineConfig.video_transform(PipelineConfig) 79 | else: 80 | config = PipelineConfig(input_shape, output_shape, self.model.get_dtype()) 81 | 82 | if self.args.framework == "Pipeline": 83 | trace = SkippableTracing(self.args.gpu, self.model, config) 84 | torch.distributed.rpc.init_rpc('worker', rank=0, world_size=1) 85 | self.model = trace.get_modules() 86 | self.model = Pipe(self.model, chunks=self.args.chunk) 87 | 88 | elif self.args.framework == "API torch": 89 | self.model.to(device) 90 | 91 | def setup_optimizer(self): 92 | self.optimizer = torch.optim.SGD(self.model.parameters(), lr=0.01) 93 | 94 | def setup_loss_fn(self): 95 | self.loss_fn = nn.CrossEntropyLoss() 96 | 97 | def run(self): 98 | for epoch in range(self.args.epochs): 99 | start = [0] * self.args.gpu 100 | peaked = [0] * self.args.gpu 101 | 102 | for gpu in range(self.args.gpu): 103 | start[gpu] = torch.cuda.memory_allocated(gpu) 104 | 105 | start_time = time.time() 106 | 107 | if self.args.framework == "Pipeline": 108 | utils.training_pipeline(self.model, self.trainloader, self.args.gpu, self.optimizer, self.loss_fn) 109 | 110 | elif self.args.framework == "API torch": 111 | utils.training_normal(self.model, self.trainloader, device, self.optimizer, self.loss_fn) 112 | 113 | end_time = time.time() 114 | 115 | execution_time = end_time - start_time 116 | 117 | for gpu in range(self.args.gpu): 118 | peaked[gpu] = (torch.cuda.max_memory_allocated(gpu) - start[gpu]) // (2 * 1024) 119 | 120 | self.mem_alloc.append(peaked) 121 | self.exec_time.append(execution_time) 122 | 123 | def generate_stats_string(self): 124 | string = f"{self.args.framework};{self.args.model};{self.args.gpu};{self.args.chunk};" 125 | 126 | for time in self.exec_time: 127 | string += f"{time};" 128 | 129 | for alloc in self.mem_alloc: 130 | string += f"{alloc};" 131 | 132 | string = string[:-1] 133 | string += "\n" 134 | return string 135 | 136 | def main(): 137 | parser = argparse.ArgumentParser(description="Script d'analyse avec différentes options") 138 | 139 | parser.add_argument( 140 | "model", 141 | choices=["CNN", "FFNET", "Basic", "Transformers", "Debug", "BigModel"], 142 | help="Modèle à utiliser (CNN, FFNET, Basic, Transformers)" 143 | ) 144 | parser.add_argument( 145 | "framework", 146 | choices=["Pipeline", "API torch"], 147 | help="Choix du framework (Pipeline, API torch)" 148 | ) 149 | parser.add_argument( 150 | "--gpu", 151 | type=int, 152 | default=1, 153 | help="Nombre de GPU à utiliser (par défaut 1)" 154 | ) 155 | parser.add_argument( 156 | "--chunk", 157 | type=int, 158 | default=2, 159 | help="Nombre de chunks (par défaut 2)" 160 | ) 161 | parser.add_argument( 162 | "--epochs", 163 | type=int, 164 | default=10, 165 | help="Nombre d'époques (par défaut 10)" 166 | ) 167 | parser.add_argument( 168 | "--dir", 169 | type=str, 170 | default=".", 171 | help="Result directory" 172 | ) 173 | 174 | args = parser.parse_args() 175 | 176 | mode = Mode(args.model, args.chunk, args.framework, args.gpu, args.epochs) 177 | 178 | bench = BenchmarkMode(mode) 179 | 180 | bench.run() 181 | 182 | with open(f"{args.dir}/results.txt", "a") as f: 183 | f.write(bench.generate_stats_string()) 184 | 185 | if __name__ == "__main__": 186 | main() -------------------------------------------------------------------------------- /pipeline_tool/pipeline_config.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | class PipelineConfig: 17 | """Create a configuration object for pipeline tool. 18 | 19 | :param input_shape: Input shape of the model 20 | :type input_shape: list of int 21 | :param output_shape: Output shape of the model 22 | :type output_shape: list of int 23 | :param data_type: Data type given to the model 24 | :type data_type: str 25 | :param config_mha: Multihead Attention configuration, allow reconstituion 26 | :type config_mha: dict 27 | """ 28 | def __init__(self, input_shape, output_shape, data_type, config_mha = []) -> None: 29 | """Constructor.""" 30 | self.input_shape = input_shape 31 | self.output_shape = output_shape 32 | self.data_type = data_type 33 | self.config_mha = config_mha 34 | 35 | def create_mha_conf_equal(self, nb_mha, num_heads, embed_dim, dropout, batch_first): 36 | """Allow to easily create Multihead configuration if all are equals. 37 | 38 | :param nb_mha: Number of multihead in the model 39 | :type nb_mha: int 40 | :param num_heads: Number of parallel attention heads. 41 | :type num_heads: int 42 | :param embed_dim: Total dimension of the Multihead. 43 | :type embed_dim: int 44 | :param dropout: Dropout probability 45 | :type dropout: float 46 | :param batch_first: Define if yes or not the batch is first in the input and output tensor. 47 | :type batch_first: bool 48 | """ 49 | self.config_mha = [] 50 | for i in range(nb_mha): 51 | self.config_mha.append({'embed_dim': embed_dim, 'num_heads': num_heads, 'dropout': dropout, 'batch_first': batch_first}) 52 | 53 | 54 | @classmethod 55 | def orbit5k(cls): 56 | config_mha = [{'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 57 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 58 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 59 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 60 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}] 61 | return cls([4, 1290, 4], [4], "long", config_mha) 62 | 63 | @classmethod 64 | def orbit5kbig(cls): 65 | config_mha = [{'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 66 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 67 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 68 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 69 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 70 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 71 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 72 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}, 73 | {'embed_dim': 128, 'num_heads': 32, 'dropout': 0.1, 'batch_first': True}] 74 | return cls([4, 1309, 4], [4], "long", config_mha) 75 | 76 | def video_transform(cls): 77 | config_mha = [{'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}, {'embed_dim': 1280, 'num_heads': 16, 'dropout': 0.0, 'batch_first': True}] 78 | return cls([4, 3, 518, 518], [4, 1000], "float", config_mha) 79 | 80 | -------------------------------------------------------------------------------- /DEED_OF_CONTRIBUTION.rst: -------------------------------------------------------------------------------- 1 | L2F – Contributor License Agreement 2 | =================================== 3 | 4 | In order to clarify the intellectual property license granted with Contributions from any person or entity, Giotto.ai SA, Place de la Gare 4, 1003 Lausanne, Switzerland (**L2F**) must have a Contributor License Agreement on file that has been signed by each Contributor, indicating agreement to the terms below. This agreement (the **Agreement**) is for Your protection as a contributor as well as the protection of L2F. 5 | 6 | You accept and agree to the following terms and conditions for Your present and future Contributions submitted to L2F. Except for the rights granted herein to L2F, and (at L2F’s discretion) recipients of software made available by L2F, You reserve all right, title, and interest in and to Your Contributions. 7 | 8 | 1. Definitions 9 | --------------- 10 | 11 | **You** (or **Your**) shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with L2F. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 12 | 13 | **Contribution** shall mean the code, documentation, or any other original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to L2F for inclusion in, or documentation of, any of the products owned or managed by L2F (the **Work**). For the purposes of this definition, **submitted** means any form of electronic, verbal, or written communication sent to L2F or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, L2F for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution". 14 | 15 | **Your Essential Patent Claims** shall mean all patent claims owned or controlled by You, whether already acquired or hereafter acquired, that would be infringed by some manner of making, using, or selling Your Contribution, but do not include claims that would be infringed only as a consequence of further modification of Your Contribution. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this Agreement. 16 | 17 | 2. Copyrights 18 | -------------- 19 | 20 | Subject to the terms and conditions of this Agreement, You hereby grant to L2F and to recipients of software distributed by L2F (at L2F’s discretion) a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, modify, prepare derivative works of, publicly display, publicly perform, propagate, sublicense, and distribute Your Contributions and such derivative works. 21 | To the extent that any of such rights cannot be licensed by You to L2F, You irrevocably waive and agree never to assert such rights against L2F, any of L2F’s successors in interest, or any of L2F’s licensees, either direct or indirect. 22 | 23 | 3. Patents 24 | ----------- 25 | 26 | Subject to the terms and conditions of this Agreement, You hereby grant to L2F, and (at L2F’s discretion) to recipients of software distributed by L2F, a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable patent license under Your Essential Patent Claims to make, have made, use, offer to sell, sell, import, and otherwise run, modify, transfer or propagate the content of Your Contribution and the Work to which You have contributed. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that Your Contribution, or the Work to which You have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity on the basis of this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed. 27 | 28 | 4. Representations 29 | ------------------- 30 | 31 | You represent that: 32 | 1. You are legally entitled to enter into this Agreement and grant the above rights. If You sign this Agreement as an individual and Your employer(s) has rights to intellectual property that You create that includes Your Contributions, You represent that You have received permission to make Contributions on behalf of that employer, that Your employer has waived such rights for Your Contributions to L2F, or that Your employer has executed a separate version of this Agreement with L2F. Respectively, if You sign this Agreement as an entity, You represent that each of Your employees is authorized to submit Contributions on Your behalf; and 33 | 2. each of Your Contributions is Your original creation (see Section 9 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which You are personally aware and which are associated with any part of Your Contributions. 34 | You agree to notify L2F of any facts or circumstances of which You become aware that would make these representations inaccurate in any respect. 35 | 36 | 5. Support/Warranty 37 | -------------------- 38 | 39 | You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. 40 | 41 | 6. Submissions on behalf of others 42 | ----------------------------------- 43 | 44 | Should You wish to submit work that is not Your original creation, You may submit it to L2F separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which You are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]". 45 | 46 | 7. L2F’s Rights 47 | ---------------- 48 | 49 | (a) No Duty to Use. You acknowledge that L2F is not obligated to use Your Contribution as part of a Work and may decide to include any Contribution it considers appropriate. 50 | (b) Outbound License. If L2F includes Your Contribution in a Work, it may license Your Contribution under any license, including copyleft, permissive, commercial, or proprietary licenses. 51 | 52 | 8. Miscellaneous 53 | ----------------- 54 | 55 | (a) *Severability*. If any provision of this Agreement is held to be invalid or unenforceable for any reason, the parties hereto shall replace it by a substitute provision that achieves to the fullest extent possible the same legal and economic purposes as those of the invalid or unenforceable provision. In any event, the remainder of this Agreement shall remain in full force and effect between the parties, 56 | (b) *Entire Agreement/Assignment*. This Agreement constitutes the entire agreement between the Parties with respect to its subject matter and supersedes all prior agreements between the parties with respect to its subject matter. This Agreement may be assigned by L2F. 57 | (c) *Governing Law/Jurisdiction*. This Agreement shall be governed by and construed in accordance with Swiss substantive law, without reference to its conflict of laws provisions. Any dispute or difference arising out of or in relation to this Agreement shall be subject to the exclusive jurisdiction of the competent courts at the registered office of L2F, subject to the right of appeal to the Swiss Federal Tribunal. 58 | -------------------------------------------------------------------------------- /pipeline_tool/function_parser.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | def _generate_function(var_names, func) -> str: 17 | """Return a string containg a call to a torch function. 18 | 19 | :param var_names: All the var that will be passed to the torch function 20 | :type var_names: list 21 | :param func: Name of the torch function to call 22 | :type func: str 23 | """ 24 | string = f"torch.{func}(" 25 | for var in var_names: 26 | if isinstance(var, tuple): 27 | string += f"{var[0]}={var[1]}, " 28 | 29 | else: 30 | if isinstance(var, list): 31 | string += f"[" 32 | for elem in var: 33 | string += f"{elem}, " 34 | string = string[:-2] 35 | string += f"], " 36 | else: 37 | string += f"{var}, " 38 | string = string[:-2] 39 | string += ")" 40 | return string 41 | 42 | def _generate_method(var_names, meth) -> str: 43 | """Return a string containg a call to a tensor method. 44 | 45 | :param var_names: All the var that will be passed to the tensor method 46 | :type var_names: list 47 | :param func: Name of the tensor method 48 | :type func: str 49 | """ 50 | string = f"{var_names[0]}.{meth}(" 51 | if len(var_names) > 1: 52 | for var in var_names[1:]: 53 | if isinstance(var, tuple): 54 | string += f"{var[0]}={var[1]}, " 55 | else: 56 | if isinstance(var, list): 57 | string += f"[" 58 | for elem in var: 59 | string += f"{elem}, " 60 | string = string[:-2] 61 | string += f"], " 62 | else: 63 | string += f"{var}, " 64 | string = string[:-2] 65 | string += ")" 66 | return string 67 | 68 | def gen_var_names(var_names, scheme, has_kwargs) -> list: 69 | """Return the modify arg list with the specified scheme. 70 | 71 | :param var_names: List of argument. 72 | :type var_names: list of list, tuple, torch.fx.Node.node, int and string 73 | :param scheme: Description of argument repartition by group. 74 | :type scheme: list of int 75 | :param has_kwargs: Number of kwargs in var_names 76 | :type has_kwargs: int 77 | :return: List of grouped var_names with the description of scheme 78 | :rtype: list of list, tuple, torch.fx.Node.node, int and string 79 | """ 80 | arg_cnt = 0 81 | new_var_names = [] 82 | for n in scheme: 83 | if n > 1: 84 | new_var_names.append(var_names[arg_cnt:arg_cnt+n]) 85 | else: 86 | new_var_names.append(var_names[arg_cnt]) 87 | arg_cnt += n 88 | if has_kwargs: 89 | new_var_names.extend(var_names[-has_kwargs:]) 90 | 91 | return new_var_names 92 | 93 | def _parse_func(key, var_names) -> str: 94 | """Return a string containg the full call to a method or function for torch tensor. 95 | 96 | :param key: Node that have his op call_method or call_function 97 | :type key: torch.fx.Node.node 98 | :param var_names: All the var that will be passed to the torch function 99 | :type var_names: list 100 | """ 101 | name = str(key) 102 | try: 103 | if name.find("add") >= 0: 104 | return _generate_function(var_names, "add") 105 | 106 | elif name.find("sub") >= 0: 107 | return _generate_function(var_names, "sub") 108 | 109 | elif name.find("mul") >= 0 and name.find("matmul") < 0: 110 | return _generate_function(var_names, "mul") 111 | 112 | elif name.find("floordiv") >= 0 or name.find("floor_divide") >= 0: 113 | return _generate_function(var_names, "floor_divide") 114 | 115 | elif name.find("truediv") >= 0 or name.find("true_divide") >= 0: 116 | return _generate_function(var_names, "true_divide") 117 | 118 | elif name.find("cat") >= 0: 119 | tmp_var = var_names 120 | has_kwargs = 0 121 | 122 | while isinstance(tmp_var[-1], tuple): 123 | tmp_var = tmp_var[:-1] 124 | has_kwargs += 1 125 | 126 | if isinstance(tmp_var[-1], int): 127 | scheme = [len(tmp_var[:-1]), 1] 128 | else: 129 | scheme = [len(tmp_var)] 130 | 131 | var_names = gen_var_names(var_names, scheme, has_kwargs) 132 | 133 | return _generate_function(var_names, "cat") 134 | 135 | elif name.find("split") >= 0: 136 | tmp_var = var_names 137 | has_kwargs = 0 138 | 139 | while isinstance(tmp_var[-1], tuple): 140 | tmp_var = tmp_var[:-1] 141 | has_kwargs += 1 142 | 143 | scheme = [1, len(tmp_var[1:])] 144 | 145 | var_names = gen_var_names(var_names, scheme, has_kwargs) 146 | 147 | return _generate_function(var_names, "split") 148 | 149 | elif name.find("flatten") >= 0: 150 | return _generate_function(var_names, "flatten") 151 | 152 | elif name.find("relu") >= 0: 153 | return _generate_function(var_names, "nn.functional.relu") 154 | 155 | elif name.find("matmul") >= 0: 156 | return _generate_function(var_names, "matmul") 157 | 158 | elif name.find("transpose") >= 0: 159 | return _generate_function(var_names, "transpose") 160 | 161 | elif name.find("expand") >= 0: 162 | return _generate_method(var_names, "expand") 163 | 164 | elif name.find("reshape") >= 0: 165 | tmp_var = var_names 166 | 167 | has_kwargs = 0 168 | 169 | while isinstance(tmp_var[-1], tuple): 170 | tmp_var = tmp_var[:-1] 171 | has_kwargs += 1 172 | 173 | scheme = [1, len(tmp_var[1:])] 174 | 175 | var_names = gen_var_names(var_names, scheme, 0) 176 | 177 | return _generate_function(var_names, "reshape") 178 | 179 | elif name.find("permute") >= 0: 180 | tmp_var = var_names 181 | has_kwargs = 0 182 | 183 | while isinstance(tmp_var[-1], tuple): 184 | tmp_var = tmp_var[:-1] 185 | has_kwargs += 1 186 | 187 | scheme = [1, len(tmp_var[1:])] 188 | 189 | var_names = gen_var_names(var_names, scheme, 0) 190 | 191 | return _generate_function(var_names, "permute") 192 | 193 | elif name.find("softmax") >= 0: 194 | return _generate_function(var_names, "nn.functional.softmax") 195 | 196 | elif name.find("view") >= 0: 197 | return _generate_method(var_names, "view") 198 | 199 | elif name.find("to") >= 0: 200 | return _generate_method(var_names, "to") 201 | 202 | elif name.find("pow") >= 0: 203 | return _generate_function(var_names, "pow") 204 | 205 | elif name.find("mean") >= 0: 206 | return _generate_function(var_names, "mean") 207 | 208 | elif name.find("rsqrt") >= 0: 209 | return _generate_function(var_names, "rsqrt") 210 | 211 | elif name.find("unsqueeze") >= 0: 212 | return _generate_function(var_names, "unsqueeze") 213 | 214 | elif name.find("squeeze") >= 0: 215 | return _generate_method(var_names, "squeeze") 216 | 217 | elif name.find("float") >= 0: 218 | raise AssertionError(f"Function not handled: {name}") 219 | 220 | elif name.find("type_as") >= 0: 221 | raise AssertionError(f"Function not handled: {name}") 222 | 223 | elif name.find("dropout") >= 0: 224 | return _generate_function(var_names, "nn.functional.dropout") 225 | 226 | elif name.find("contiguous") >= 0: 227 | raise AssertionError(f"Function not handled: {name}") 228 | 229 | elif name.find("tanh") >= 0: 230 | return _generate_function(var_names, "nn.functional.tanh") 231 | 232 | elif name.find("gelu") >= 0: 233 | return _generate_function(var_names, "nn.functional.gelu") 234 | 235 | elif name.find("size") >= 0: 236 | return _generate_method(var_names, "size") 237 | 238 | else: 239 | raise AssertionError(f"Unknown function or method: {name}") 240 | 241 | except AssertionError as e: 242 | print(f"Error : {e}") 243 | exit() -------------------------------------------------------------------------------- /pipeline_tool/class_impl/LayerClass.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 2 | # 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | 16 | import torch 17 | from ..constant import TAB 18 | 19 | class Layer: 20 | """Set up of the Layer to manage every thing for creating a layer with the init and forward functions. 21 | 22 | This class is the base class for CallFunction, CallModule, GetAttrModule and PropagationLayer. Thus, 23 | this should never have called. 24 | 25 | :param node: Is the actual traced node from torch.fx. 26 | :type node: torch.fx.node.Node 27 | :param trace: Is the complete trace of torch.fx of the model. 28 | :type trace: torch.fx.graph._node_list 29 | :param prev_node: Is the just previous node in the trace before the actual traced node. 30 | :type node: torch.fx.node.Node 31 | """ 32 | 33 | def __init__(self, node, trace, prev_node): 34 | """Constructor.""" 35 | self.node = node 36 | self.name = str(node) 37 | self.args = [] 38 | self.kwargs = [] 39 | self.pop_list = [] 40 | self.stash_list = [] 41 | 42 | self.getitem_idx = None 43 | # True if there is a change of CPU at this specific layer 44 | self.separation_layer = False 45 | 46 | # Call function to handle correctly all information about the node. 47 | self._args_handler(trace, prev_node) 48 | self._kwargs_handler(trace, prev_node) 49 | self._pop_handler(prev_node) 50 | 51 | def get_node(self) -> torch.fx.node.Node: 52 | """Getter for the node treated. 53 | 54 | :return: Node of the layer 55 | :rtype: torch.fx.node.Node 56 | """ 57 | return self.node 58 | 59 | def get_name(self) -> str: 60 | """Getter for the name of the node, just is string format. 61 | 62 | :return: Name of the node. 63 | :rtype: str 64 | """ 65 | return self.name 66 | 67 | def set_stash(self, target_node): 68 | """Update the stash_list, i.e. the list of layers to which it must send the result of its forward. 69 | 70 | :param target_node: Node for which the result should be saved. 71 | :type target_node: torch.fx.node.Node 72 | """ 73 | tmp = self.name + "_to_" + str(target_node) 74 | if tmp not in self.stash_list: 75 | self.stash_list.append(tmp) 76 | 77 | def _get_handler(self, arg, trace) -> torch.fx.node.Node: 78 | """Exist in the only objective to handler successive getattr and getitem call. 79 | 80 | Because those traced node should not be considered as Layer, and we have to search for the last node before them. 81 | :param arg: The arg to check 82 | :type arg: torch.fx.node.Node 83 | :param trace: Is the complete trace of torch.fx of the model. 84 | :type trace: torch.fx.graph._node_list 85 | :return: The last parent of the chained getitem and getattr call (if there is no chain just their direct parent) 86 | :rtype: torch.fx.node.Node 87 | """ 88 | _arg = arg 89 | while str(_arg).find("getitem") >= 0 or str(_arg).find("getattr") >= 0: 90 | for node in trace: 91 | if node == _arg: 92 | _arg = node.args[0] 93 | break 94 | return _arg 95 | 96 | def update_arg_by_attr(self, new_arg, position): 97 | """Allow to update argument with a specific attribute. 98 | 99 | For example t.shape 100 | :param new_arg: New arg containing the attribute. (For ex .shape) 101 | :type new_arg: str 102 | :param position: Position of the argument in the arg list 103 | :type position: int 104 | """ 105 | self.args[position] = new_arg 106 | 107 | 108 | def get_pop_parent(self) -> list: 109 | """Getter for the pop_list, the list of the layer who the actual layers need stashed value. 110 | 111 | :return: The pop list 112 | :rtype: list 113 | """ 114 | return self.pop_list 115 | 116 | def _pop_handler(self, prev_node): 117 | """Handle the creation of the pop list. 118 | 119 | This function will go throw the args of the treated node and found if in his param he have a layer who is not directly connected to him. 120 | :param prev_node: The node directly before the treated node 121 | :type prev_node: torch.fx.node.Node 122 | """ 123 | for arg in self.args: 124 | if isinstance(arg, tuple): 125 | tmp = arg[1] 126 | else: 127 | tmp = arg 128 | # If the node is not instance of torch.fx, then it's a param numeric or other.. 129 | if isinstance(tmp, torch.fx.node.Node) and tmp != prev_node: 130 | # ocmon avoid to have multiple time the same pop in the pop list. Because we can have several time 131 | # the same value in the params. 132 | ocmon = False 133 | for pop in self.pop_list: 134 | if str(pop[0]) == str(tmp): 135 | ocmon = True 136 | break 137 | if not ocmon: 138 | self.pop_list.append([tmp, str(tmp) + '_to_' + self.name]) 139 | 140 | def _kwargs_handler(self, trace, prev_node): 141 | """Handle the kwargs. 142 | 143 | The kwargs are specific and need to be writen as "dim=1". 144 | In this this function save the name of the parameter and his value in the list of args. 145 | """ 146 | for key, kwarg in self.node.kwargs.items(): 147 | kwarg = self._get_handler(kwarg, trace) 148 | 149 | if kwarg == prev_node: 150 | self.args.append((key, "input")) 151 | else: 152 | self.args.append((key, kwarg)) 153 | 154 | 155 | def _args_handler(self, trace, prev_node): 156 | """Handle the args. 157 | 158 | Args can be values but also the returned value of a past layer, so we have tocheck if the args is older than the direct previous or not. 159 | Also if in the args there is a getattr or getitem we have to delete it with a call to _get_handler() 160 | :param trace: Is the complete trace of torch.fx of the model. 161 | :type trace: torch.fx.graph._node_list 162 | :param prev_node: The node directly before the treated node 163 | :type prev_node: torch.fx.node.Node 164 | """ 165 | def process_argument(obj, arg, trace): 166 | if isinstance(arg, list): 167 | for item in arg: 168 | process_argument(obj, item, trace) 169 | else: 170 | arg = self._get_handler(arg, trace) 171 | if arg == prev_node: 172 | obj.args.append("input") 173 | else: 174 | obj.args.append(arg) 175 | 176 | for arg in self.node.args: 177 | process_argument(self, arg, trace) 178 | 179 | def generate_class(self) -> str: 180 | """Create a string containing the full class declaration for a layer. 181 | 182 | For example if there is any pop or stash to make : 183 | .. code-block:: python 184 | @skippable(stash=[..], pop=[..]) 185 | And then the class : 186 | .. code-block:: python 187 | class self.name_layer(nn.Module) 188 | 189 | :return: Return the class declaration 190 | :rtype: str 191 | """ 192 | string = "" 193 | if len(self.stash_list) > 0 or len(self.pop_list) > 0: 194 | string += f"@skippable(" 195 | 196 | if len(self.stash_list) > 0: 197 | string += "stash=[" 198 | for stash in self.stash_list: 199 | string += f"'{stash}', " 200 | string = string[:-2] 201 | string += "], " 202 | 203 | if len(self.pop_list) > 0: 204 | string += "pop=[" 205 | for pop in self.pop_list: 206 | string += f"'{pop[1]}', " 207 | string = string[:-2] 208 | string += "], " 209 | 210 | string = string[:-2] 211 | string += ")\n" 212 | 213 | string += f"class {self.name}_layer(nn.Module):\n" 214 | return string 215 | 216 | def generate_init(self, declaration) -> str: 217 | """Create a string containing the full __init__ function of the layer. 218 | 219 | For example : 220 | .. code-block:: python 221 | def __init__(self) -> None: 222 | super().__init__() 223 | self.fc = nn.DECLARATION 224 | 225 | The declaration can be for example nn.Linear(in_features=4, out_features=16, bias=True) or nn.parameter.Parameter(1, 16, requires_grad=True) 226 | 227 | :param declaration: Is the module or parameter to initialize 228 | :type declaration: str 229 | :return: Return the class __init__ 230 | :rtype: str 231 | """ 232 | string = TAB[1] + "def __init__(self) -> None:\n" 233 | string += TAB[2] + "super().__init__()\n" 234 | string += TAB[2] + f"self.fc = nn.{declaration}\n" 235 | 236 | return string 237 | 238 | def reset_separation_layer(self): 239 | self.separation_layer = False 240 | 241 | def set_separation_layer(self): 242 | """Set the layer as a separation layer. 243 | 244 | This is needed because when the data change from a GPU to another he needs to be cloned. 245 | 246 | So this adds to the forward declaration : input = input.clone() 247 | """ 248 | self.separation_layer = True 249 | 250 | def get_separation_layer(self) -> bool: 251 | """Return the separation status of the layer. 252 | 253 | :return: True if the layer is a separation layer, else False 254 | :rtype: bool 255 | """ 256 | return self.separation_layer 257 | 258 | def generate_forward(self, task) -> str: 259 | """Create the full forward definition. 260 | 261 | He has to first, if needed, pop all the params sent from older layer. 262 | Secondly clone the input if it is a separation layer. 263 | Thirdly do his task and affect it to the ret variable. A task can be some different thing, for example the execution of the Module declarated in the __init__ (self.fc) or simply a function call (torch.add). 264 | Fourthly it will add, if defined, a getitem to the executed task. So if the task return Tuple and only the first one is used it will add at the end a [0]. 265 | Fifthly he have to stash is ret value if anyone need it further. 266 | And finaly return is value for the next layer. 267 | 268 | A full forward can look as : 269 | .. code-block:: python 270 | def forward(self, input): 271 | add = yield pop('add_to_{self.name}') 272 | input = input.clone() 273 | ret = torch.add(input, add) 274 | yield stash('{self.name}_to_another', ret) 275 | return ret 276 | 277 | :param task: Task to be done in the forward 278 | :type task: str 279 | :return: Return the full forward declaration 280 | :rtype: str 281 | """ 282 | string = TAB[1] + "def forward(self, input):\n" 283 | 284 | # # TO REMOVE !!!!! 285 | # string += TAB[2] + f"with open(\"f.txt\", \"a\") as f:\n" 286 | # string += TAB[3] + f"f.write(f\"{self.node} - \")\n" 287 | # # --------------- 288 | 289 | for pop in self.pop_list: 290 | string += TAB[2] + f"{pop[0]} = yield pop('{pop[1]}')\n" 291 | 292 | if self.separation_layer: 293 | string += TAB[2] + "input = input.clone()\n" 294 | 295 | string += TAB[2] + f"ret = {task}" 296 | 297 | if self.getitem_idx is not None: 298 | string += f"[{self.getitem_idx}]" 299 | 300 | string += "\n" 301 | 302 | for stash in self.stash_list: 303 | string += TAB[2] + f"yield stash('{stash}', ret)\n" 304 | 305 | if self.node.op == "placeholder": 306 | string += TAB[2] + f"return input\n\n" 307 | else: 308 | string += TAB[2] + f"return ret\n\n" 309 | 310 | return string 311 | 312 | def add_stash(self, node_to): 313 | """Add stash information for special layer. 314 | 315 | The getattr are ignore during the parsing, so if one of those depend on layer we have to add their parent to the stash list to not lose the connection. 316 | :param node_to: Parent of a getattr 317 | :type node_to: torch.fx.node.Node 318 | """ 319 | self.stash_list.append(self.name + "_to_" + str(node_to)) 320 | 321 | def add_getitem(self, idx): 322 | """Allow to add a getitem to the task of the layer. 323 | 324 | Because the getitem cannot be considered as layer, we have to link the getitem to the layer with who he is linked. 325 | :param idx: Index of the getitem 326 | :type idx: int 327 | """ 328 | self.getitem_idx = idx 329 | 330 | def __str__(self) -> str: 331 | """Allow to print easily all the information of a layer. 332 | 333 | :return: String to print 334 | :rtype: str 335 | """ 336 | print_str = "---- Layer information ----\n" 337 | print_str += f" Name : {self.name}\n" 338 | print_str += f" Argument : {self.args}\n" 339 | 340 | if len(self.pop_list) > 0: 341 | print_str += f" Pop info :\n" 342 | 343 | for pop, stashed_from in self.pop_list: 344 | print_str += f" Argument {pop}, Stashed from {stashed_from}\n" 345 | 346 | if len(self.stash_list) > 0: 347 | print_str += " Stash info : \n" 348 | 349 | for stash in self.stash_list: 350 | print_str += f" ret is stashed for {stash}\n" 351 | if self.getitem_idx is not None: 352 | print_str += f" This node will access the result of ret with [{self.getitem_idx}]\n" 353 | return print_str 354 | -------------------------------------------------------------------------------- /pipeline_tool/pipeline_tool.py: -------------------------------------------------------------------------------- 1 | # The Pipeline tool allows you to create a new model, split across multiple GPUs, 2 | # from a PyTorch module. This enables the training of large models that do not fit on a single GPU. 3 | # Copyright (C) 2023 Bruno Da Rocha Carvalho, Gabriel Catel Torres Arzur 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | from torch.fx import symbolic_trace 19 | import torch 20 | from pathlib import Path 21 | from .constant import TAB 22 | import subprocess 23 | import sys 24 | from .class_impl.CallModule import CallModule 25 | from .class_impl.CallFunction import CallFunction 26 | from .class_impl.PropagationLayer import PropagationLayer 27 | from .class_impl.GetAttr import GetAttr 28 | from .class_impl.GetAttrModule import GetAttrModule 29 | import logging 30 | 31 | class SkippableTracing: 32 | """Create and sequence the model parallelism. 33 | 34 | He will parsed the model given by the user and generate a file that contain all the splitted Layer and divide them on the gpus. 35 | 36 | Example of use : 37 | .. code-block:: python 38 | trace = SkippableTracing(2, model) 39 | # Then just get the generated splitted model 40 | model = trace.get_modules() 41 | 42 | :param nb_gpus: Nb of gpus of work, if none given max gpus will be taken. 43 | :type nb_gpus: int 44 | :param model: Model to parsed 45 | :type model: a model extended of nn.Module. 46 | """ 47 | def __init__(self, nb_gpus, model, config): 48 | """Constructor.""" 49 | self.module_desc = {} 50 | self.file = "" 51 | self.net = None 52 | self.LayerLists = {} 53 | self.GetattrLists = {} 54 | self.nb_gpu = nb_gpus if nb_gpus is not None else torch.cuda.device_count() 55 | self.file_name = "layered_model.py" 56 | self.directory_name = "pipelinecache" 57 | self.configs_mha = config.config_mha 58 | self.mha_number = len(self.configs_mha) 59 | self.mha_count = 0 60 | self.input_shape = config.input_shape 61 | self.output_shape = config.output_shape 62 | self.dtype = config.data_type 63 | 64 | # logging.basicConfig(filename='pipelinecache/debug.log', encoding='utf-8', level=logging.DEBUG) 65 | 66 | self._verfiy_config_mha() 67 | 68 | self._tracer(model) 69 | 70 | def _verfiy_config_mha(self): 71 | """Verify if at least embed_dim and num_heads are present in the configuration given by the user. 72 | 73 | This two parameters are mandatory to create a MHA. 74 | """ 75 | for config in self.configs_mha: 76 | try: 77 | config['embed_dim'] 78 | except KeyError as e: 79 | raise KeyError("You didn't provide embed_dim in one of your MHA config") 80 | 81 | try: 82 | config['num_heads'] 83 | except KeyError as e: 84 | raise KeyError("You didn't provide num_heads in one of your MHA config") 85 | 86 | def _write_in_file(self): 87 | """Write to the output file the generated Layers to use it from other files.""" 88 | dir_path = Path(__file__).resolve().parent / self.directory_name 89 | 90 | if not dir_path.exists(): 91 | dir_path.mkdir(parents=True) 92 | 93 | file_path = dir_path / self.file_name 94 | 95 | with open(file_path, "w") as f: 96 | f.write(self.file) 97 | f.close() 98 | 99 | def get_modules(self) -> torch.nn.Sequential: 100 | """Allow the user to get the generated Sequential model for each GPU.""" 101 | from .pipelinecache.layered_model import PipelinedModel 102 | 103 | model = PipelinedModel() 104 | return model.get_modules() 105 | 106 | def _init_file(self): 107 | """Add all necessary import to the file.""" 108 | self.file += "import torch\n" 109 | self.file += "import torch.nn.functional as F\n" 110 | self.file += "import torch.nn as nn\n" 111 | self.file += "from torch.distributed.pipeline.sync.skip import stash, pop, skippable \n\n" 112 | 113 | def _generate_end_class(self): 114 | """Add a class at the end of the generated file to get simply the pipelined model.""" 115 | self.file += f"class PipelinedModel(nn.Module):\n" 116 | self.file += TAB[1] + "def __init__(self) -> None:\n" 117 | self.file += TAB[2] + "super().__init__()\n" 118 | 119 | gpu_index = 0 120 | self.file += TAB[2] + f"self.s{gpu_index} = nn.Sequential(" 121 | 122 | for layer in self.LayerLists.values(): 123 | self.file += f"{layer.get_name()}_layer(), " 124 | 125 | if layer.get_separation_layer(): 126 | self.file = self.file[:-2] 127 | self.file += f").cuda({gpu_index})\n" 128 | gpu_index = gpu_index + 1 129 | self.file += TAB[2] + f"self.s{gpu_index} = nn.Sequential(" 130 | 131 | self.file = self.file[:-2] 132 | self.file += f").cuda({gpu_index})\n" 133 | 134 | self.file += TAB[1] + "def forward(self, input):\n" 135 | self.file += TAB[2] + f"ret = input\n" 136 | for gpu in range(self.nb_gpu): 137 | self.file += TAB[2] + f"ret = self.s{gpu}(ret.to({gpu}))\n" 138 | 139 | self.file += TAB[2] + "return ret\n" 140 | 141 | self.file += TAB[1] + "def get_modules(self):\n" 142 | self.file += TAB[2] + "return nn.Sequential(*[" 143 | for gpu in range(self.nb_gpu): 144 | self.file += f"nn.Sequential(*self.s{gpu})," 145 | self.file = self.file[:-1] 146 | self.file += "])\n" 147 | 148 | def _create_mha(self): 149 | """Create MHA string declaration.""" 150 | config = self.configs_mha[self.mha_count] 151 | 152 | decl = f"MultiheadAttention(" 153 | 154 | for key, param in config.items(): 155 | decl += f"{key}={param}, " 156 | 157 | decl = decl[:-2] 158 | decl += ")" 159 | self.mha_count = self.mha_count + 1 160 | 161 | return decl 162 | 163 | def _catch_module_desc(self): 164 | """Create a look-up dictionary to match target names with their declaration. 165 | 166 | We use the withelist.txt to know which module name we have to keep as "core" module. 167 | All the modules not present in the whitelist willbe digged to found their composition. 168 | 169 | MultiheadAttention are not parsed, so we have to do a little trick to found how is it configured, only based on giotto_deep implementation. 170 | """ 171 | filename = Path(__file__).resolve().parent / 'whitelist.txt' 172 | whitelist = open(filename).readlines() 173 | whitelist = [line.strip() for line in whitelist] 174 | 175 | for name, module in self.net.named_modules(): 176 | if str(module).split('(', 1)[0] in whitelist: 177 | if str(module).split('(', 1)[0].find('Multi') >= 0: 178 | # try: 179 | if self.mha_number >= 1: 180 | self.module_desc[name] = self._create_mha() 181 | else: 182 | raise UserWarning(f"Error: You didn't specified any MHA config, but at least one exist.") 183 | # except UserWarning as e: 184 | # raise Exception(f"Error : {e}") 185 | else: 186 | self.module_desc[name] = module 187 | 188 | def _balancing(self, layers, memory): 189 | """Balance the distribution of layers across GPUs based on memory usage. 190 | 191 | :param layers: Current distribution of layers across GPUs. 192 | :type layers: list 193 | :param memory: Memory usage for each GPU. 194 | :type memory: list 195 | :return: New balanced distribution of layers across GPUs. 196 | :rtype: list 197 | """ 198 | repartition = layers.copy() 199 | memory_tmp = memory.copy() 200 | 201 | # We couldn't have only 1 layer on first or last GPU, so we remove it to avoid 202 | # this case. 203 | repartition[0] -= 1 204 | repartition[-1] -= 1 205 | 206 | n = len(layers) 207 | 208 | lower_idx = min(range(n), key=lambda i: memory_tmp[i]) 209 | 210 | while True: 211 | upper_idx = max(range(n), key=lambda i: memory_tmp[i]) 212 | memory_tmp[upper_idx] = 0 213 | if repartition[upper_idx] > 1: 214 | break 215 | 216 | repartition[lower_idx] += 1 217 | repartition[upper_idx] -= 1 218 | 219 | # We restablish the two deleted layers. 220 | repartition[0] += 1 221 | repartition[-1] += 1 222 | 223 | 224 | return repartition 225 | 226 | def reset_repartition(self, layer_per_gpu): 227 | """Reset the distribution of layers based on the number of layers per GPU. 228 | 229 | :param layer_per_gpu: Number of layers per GPU. 230 | :type layer_per_gpu: list 231 | """ 232 | current_layer = 0 233 | gpu_index = 0 234 | separation_layer_index = layer_per_gpu[gpu_index] - 1 235 | 236 | for _, layer in self.LayerLists.items(): 237 | if current_layer >= len(self.LayerLists.items()) - 1: 238 | break 239 | 240 | if separation_layer_index == current_layer: 241 | layer.reset_separation_layer() 242 | gpu_index += 1 243 | separation_layer_index += layer_per_gpu[gpu_index] 244 | 245 | current_layer += 1 246 | 247 | def set_repartition(self, layer_per_gpu): 248 | """Set the distribution of layers across GPUs based on the number of layers per GPU. 249 | 250 | :param layer_per_gpu: Number of layers per GPU. 251 | :type layer_per_gpu: list 252 | """ 253 | current_layer = 0 254 | gpu_index = 0 255 | separation_layer_index = layer_per_gpu[gpu_index] - 1 256 | 257 | for _, layer in self.LayerLists.items(): 258 | 259 | if current_layer >= len(self.LayerLists.items()) - 1: 260 | self.file += layer.get_declaration() 261 | break 262 | 263 | if separation_layer_index == current_layer: 264 | layer.set_separation_layer() 265 | gpu_index += 1 266 | separation_layer_index += layer_per_gpu[gpu_index] 267 | 268 | self.file += layer.get_declaration() 269 | current_layer += 1 270 | 271 | self._generate_end_class() 272 | 273 | def _check_memory_peak(self, memory_peak): 274 | """Check if the memory peaks are balanced across GPUs. 275 | 276 | :param memory_peak: Memory peaks for each GPU. 277 | :type memory_peak: list 278 | :return: True if memory peaks are balanced, False otherwise. 279 | :rtype: bool 280 | """ 281 | threshold = 0.2 282 | reference_value = memory_peak[0] 283 | return all(abs(value - reference_value) <= reference_value * threshold for value in memory_peak[1:]) 284 | 285 | 286 | def _repartition(self): 287 | """Perform the distribution of layers across GPUs in a balanced manner based on memory usage.""" 288 | self._init_file() 289 | # Save self var for remake 290 | file = self.file 291 | # Calculate first naive repartition on gpus 292 | clone_step = len(self.LayerLists.items()) // self.nb_gpu 293 | remainder = len(self.LayerLists.items()) % self.nb_gpu 294 | layer_per_gpu = [clone_step] * self.nb_gpu 295 | 296 | # Distribute remainder layer to the GPU 297 | for i in range(remainder): 298 | layer_per_gpu[i] += 1 299 | 300 | # Initialise cloned layers 301 | self.set_repartition(layer_per_gpu) 302 | 303 | # Write in file the naive repartition 304 | self._write_in_file() 305 | 306 | dir_path = Path(__file__).resolve().parent / "evaluate_mem.py" 307 | 308 | previous_repartitions = [] 309 | 310 | while True: 311 | if layer_per_gpu[0] == 1 or layer_per_gpu[:-1] == 1: 312 | raise Exception(f"The model is not separable in {self.nb_gpu} GPU, first or last GPU contain only 1 layer. {layer_per_gpu}") 313 | 314 | if 0 in layer_per_gpu: 315 | raise Exception(f"At least one GPU have 0 layer, please allocate less GPU. {layer_per_gpu}") 316 | 317 | p = subprocess.run([sys.executable, dir_path, 318 | '--input_shape', str(list(self.input_shape)), 319 | '--output_shape', str(list(self.output_shape)), 320 | '--number_gpu', str(int(self.nb_gpu)), 321 | '--number_chunks', str(2), 322 | '--dtype', str(self.dtype)], capture_output=True, text=True) 323 | 324 | result = p.stdout 325 | if "CUDA" in result: 326 | raise Exception(f"The model is too big for the number of GPU given. CUDA OOM") 327 | 328 | elif result == '': 329 | raise Exception(f"An error occured during training. The repartition tried was {layer_per_gpu}.") 330 | 331 | result = result.replace("[", "").replace("]", "") 332 | result = result.split(",") 333 | memory_peak = [int(x.strip()) for x in result] 334 | 335 | if not self._check_memory_peak(memory_peak): 336 | new_layer_per_gpu = self._balancing(layer_per_gpu, memory_peak) 337 | if new_layer_per_gpu in previous_repartitions: 338 | break 339 | 340 | previous_repartitions.append(new_layer_per_gpu) 341 | 342 | self.file = file 343 | self.reset_repartition(layer_per_gpu) 344 | self.set_repartition(new_layer_per_gpu) 345 | self._write_in_file() 346 | layer_per_gpu = new_layer_per_gpu 347 | 348 | else: 349 | break 350 | 351 | 352 | 353 | def _filter_trace(self, trace): 354 | """Filter trace by removing blacklisted layers and un-propaged layers. 355 | 356 | :param trace: Trace of the model 357 | :type trace: torch.fx.graph._node_list 358 | """ 359 | to_remove = [] 360 | filename = Path(__file__).resolve().parent / 'blacklist.txt' 361 | blacklist = open(filename).readlines() 362 | blacklist = [line.strip() for line in blacklist] 363 | 364 | for node in trace.graph.nodes: 365 | if any(item in node.name for item in blacklist): 366 | to_remove.append(node) 367 | 368 | for node in to_remove[::-1]: 369 | trace.graph.erase_node(node) 370 | 371 | all_unused_deleted = True 372 | while all_unused_deleted == True: 373 | all_unused_deleted = False 374 | for node in trace.graph.nodes: 375 | if node.name == "output": 376 | break 377 | try: 378 | trace.graph.erase_node(node) 379 | all_unused_deleted = True 380 | except: 381 | continue 382 | 383 | 384 | def _tracer(self, net): 385 | """Trace and create all the composite needed to describe correctly the models given. 386 | 387 | It will call the class of class_impl folder to generate at the end the correct file of the model splited between GPUs. 388 | :param net: Model to trace. 389 | :type net: a model extended of nn.Module. 390 | """ 391 | self.net = net 392 | 393 | try: 394 | trace = symbolic_trace(net) 395 | except Exception as e: 396 | raise Exception(f"The model given cannot be traced by torch.fx. Error : {e}") 397 | 398 | self._filter_trace(trace) 399 | 400 | self._catch_module_desc() 401 | 402 | prev_node = None 403 | 404 | # Iter through each node traced by torch.fx 405 | for node in trace.graph.nodes: 406 | if str(node).find("getitem") >= 0: 407 | for _node in trace.graph.nodes: 408 | if node in _node.args: 409 | if str(node.args[0]).find("getattr") >= 0: 410 | if self.GetattrLists[node.args[0]].getitem_idx is None: 411 | self.GetattrLists[node.args[0]].add_getitem(node.args[1]) 412 | else: 413 | self.GetattrLists[node] = GetAttr(node.args[0], trace.graph.nodes, _node) 414 | self.GetattrLists[node].add_getitem(node.args[1]) 415 | 416 | else: 417 | self.LayerLists[node.args[0]].add_getitem(node.args[1]) 418 | 419 | elif str(node).find("getattr") >= 0: 420 | self.GetattrLists[node] = GetAttr(node, trace.graph.nodes) 421 | 422 | else: 423 | if node.op == "call_module": 424 | self.LayerLists[node] = CallModule(node, trace.graph.nodes, prev_node, 425 | self.module_desc[node.target]) 426 | 427 | elif node.op == "call_function" or node.op == "call_method": 428 | self.LayerLists[node] = CallFunction(node, trace.graph.nodes, prev_node) 429 | elif node.op == "get_attr": 430 | self.LayerLists[node] = GetAttrModule(node, trace.graph.nodes, prev_node, net) 431 | pass 432 | 433 | else: 434 | self.LayerLists[node] = PropagationLayer(node, trace.graph.nodes, prev_node) 435 | prev_node = node 436 | 437 | # For each getattr, we will update the Layer who are linked to it. If the value of the getattr need to be 438 | # stashed we will update the stash list of the parent of the getattr. And by default update all the argument 439 | # to have the correct declaration with the getattr. 440 | for _, getattr_item in self.GetattrLists.items(): 441 | # if getattr_item.get_child() is not None: 442 | if getattr_item.is_stash_needed(): 443 | self.LayerLists[getattr_item.get_parent()].add_stash(getattr_item.get_child()) 444 | 445 | self.LayerLists[getattr_item.get_child()].update_arg_by_attr(getattr_item.get_attr_name(), getattr_item.get_position()) 446 | 447 | # As it is complicated to trace efficiently the stash we updated it with the poplist of each node. 448 | # So for each "pop parent" we set a stash for the current node. 449 | for layer in self.LayerLists.values(): 450 | for pop_parent in layer.get_pop_parent(): 451 | self.LayerLists[pop_parent[0]].set_stash(layer.get_node()) 452 | 453 | 454 | # Test mode without GPUs 455 | if self.nb_gpu == 0: 456 | print("Pipeline tool as performed a full tracing, but is not allowed to use GPU.") 457 | else: 458 | self._repartition() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pipeline tool 2 | 3 | ## Table of contents 4 | 5 | [toc] 6 | 7 | ## Introduction 8 | 9 | The field of machine learning is constantly evolving, with increasingly sophisticated models and ever-expanding datasets. Professionals in the field can face significant challenges, especially when it comes to training models that are too large to fit into the memory of a single GPU. 10 | 11 | In this context, developers have created a tool for distributing a PyTorch machine learning model across multiple GPUs without altering the training process. The tool takes the PyTorch model description as input, interprets each layer independently, and rewrites the model to handle the operations' interdependencies. The result is a new model that can be automatically distributed (creating a pipeline) across multiple GPUs without affecting the quality of the results. 12 | 13 | In the following, we will present this tool in detail, along with the benefits it can offer to machine learning professionals seeking to train large and complex models 14 | 15 | ## How it works 16 | 17 | ### First step 18 | 19 | To run the tool, you need to provide some parameters: 20 | 21 | - Number of GPUs: If the user doesn't specify the number of GPUs to use, the tool will automatically detect the available GPUs on the machine running the command. In this case, the model will be trained using all detected GPUs to improve performance. 22 | - PyTorch Model: The user must provide a PyTorch model that only uses functions and modules from the PyTorch API. In other words, the model should not incorporate custom functions unknown to the PyTorch API. However, you can create custom layers using combinations of functions (always from the PyTorch API). 23 | - Shapes of the input and output: You will need to provide these to profile[memory usage](#model-splitting). 24 | - Data type that will be passed into the model, for example, float. 25 | 26 | The first step is to add the following imports to your project: 27 | 28 | ```python 29 | from torch.distributed.pipeline.sync import Pipe 30 | from pipeline_tool.pipeline_tool import SkippableTracing 31 | from pipeline_tool.pipeline_config import PipelineConfig 32 | ``` 33 | 34 | Next, you should use the PipelineConfig class, which enables you to prepare the necessary parameters (input and output shape, data type). 35 | 36 | ```python 37 | config = PipelineConfig([X, Y, Z], [X, Y], "dtype") 38 | ``` 39 | > *One important thing to know is that the first number given in input/output shape is your batch size.* 40 | 41 | Once you have defined your config and created your model, you can process it as shown in the example below. 42 | 43 | ```python 44 | N_GPUs = 2 45 | trace = SkippableTracing(N_GPUs, model, config) 46 | graph_model = trace.get_modules() 47 | ``` 48 | 49 | Here, we trace the model using [torch.fx](https://pytorch.org/docs/stable/fx.html) to obtain the GraphModule. This allows us to determine, for each module, its type, parameters, functions (e.g., convolution, activation, multiplication), and their links to other modules. 50 | 51 | Below is an example of how a simple model is treated: 52 | 53 | ![03_simple_model_dep](img/03_simple_model_dep.png) 54 | 55 | In this basic example, we have a model composed exclusively of PyTorch modules. To describe them accurately, we utilize the trace generated by torch fx. 56 | 57 | The generated trace appears as follows: 58 | 59 | ```bash 60 | Opcode Name Target 61 | placeholder x x 62 | call_module linear1 linear1 63 | call_module activation activation 64 | call_module linear2 linear2 65 | call_module softmax softmax 66 | output output output 67 | ``` 68 | 69 | This trace allows us to identify each generated layer and provides the following information: 70 | 71 | - Opcode: Indicates the type of operation performed by the layer. 72 | - Name: Corresponds to the name of the function or operation performed by the layer. 73 | - Target: Represents the name of the layer as it appears in the description of the PyTorch model. 74 | 75 | Thus, the trace provides a detailed view of the operations performed by each layer, making it easier to understand and analyze the model. 76 | 77 | ```bash 78 | Name Module declaration 79 | linear1 Linear(in_features=100, out_features=200, bias=True) 80 | activation ReLU() 81 | linear2 Linear(in_features=200, out_features=10, bias=True) 82 | softmax Softmax(dim=None) 83 | ``` 84 | 85 | The retrieval, analysis, and management of all this information enable the generation of a file containing a new model ready for pipelined training on N GPUs. 86 | 87 | ### Model splitting 88 | 89 | Now that we can create a model that can be distributed across multiple GPUs, the question arises: how do we split it intelligently? Currently, the tool proceeds with a somewhat naive approach. We create a dummy dataset to pass through the model and perform a training run. This allows us to measure the memory loads on all GPUs. 90 | 91 | Initially, the tool divides the layers into two equal parts (in terms of the number of layers) and conducts these memory load measurements. 92 | If the load is not evenly distributed, we rewrite the model (moving layers around) and iterate the dummy run until we achieve uniform distribution on N GPUs. 93 | 94 | ## Pipeline Tool Example 95 | Two examples are provided in [examples/](./examples/). They demonstrate how to: 96 | 97 | 1. Use the pipeline_tool 98 | 2. Train a pipelined model 99 | 3. Evaluating a pipelined model 100 | 4. Save the trained model. 101 | 102 | 103 | ## Pipeline Tool in Giotto Deep 104 | The Pipeline tool is seamlessly integrated into Giotto-Deep's trainer, requiring no changes to its API. 105 | 106 | Here's an example of what you need to do: 107 | 108 | ```python 109 | # New import 110 | from gdeep.trainer.trainer import Parallelism, ParallelismType 111 | 112 | # Create the trainer as before 113 | trainer = Trainer(wrapped_model, [dl_train, dl_train], loss_function, writer) 114 | 115 | # Prepare the config of the MHA 116 | configs = [{'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 117 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 118 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 119 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}, 120 | {'embed_dim': 16, 'num_heads': 8, 'dropout': 0.1, 'batch_first': True}] 121 | 122 | # List of device 123 | devices = list(range(torch.cuda.device_count())) 124 | 125 | # Use the Parallelism class created to prepare the trainer for a pipeline run 126 | parallel = Parallelism(ParallelismType.PIPELINE, 127 | devices, 128 | len(devices), 129 | pipeline_chunks=2, 130 | config_mha=configs) 131 | 132 | # Call the train function with the new parameter 133 | trainer.train(Adam, 2, parallel=parallel) 134 | ``` 135 | 136 | ### Example 137 | To experiment with Giotto Deep training using the Pipeline tool in your environment, we have provided two example scripts. Navigate to Giotto's examples folder and run either [pipeline_basic_image.py](TODO) or [pipeline_orbit5k.py](TODO) with the --pipeline argument to enable the pipeline mode, or without it for regular training. 138 | 139 | ## Installation 140 | 141 | 142 | ### Install from sources 143 | Launch from the root of the project: 144 | 145 | ```bash 146 | pip install . 147 | ``` 148 | This will install pipeline_tool on your Python environment. 149 | 150 | The necessary imports are: 151 | ```python3 152 | from pipeline_tool.pipeline_config import PipelineConfig 153 | from pipeline_tool.pipeline_tool import SkippableTracing 154 | ``` 155 | 156 | ## Benchmarking 157 | 158 | A benchmarking tool is available. This script will test the pipeline_tool on 3 different models: 159 | 160 | 1. A FFNET 161 | 2. A CNN 162 | 3. One VisionTransformer 163 | 164 | With these 3 models, we cover the majority of cases that the tool has to deal with. "The CNN and FFNET are two small models and quickly become unable to be split too much, while the VisionTransformer is very large and may not necessarily fit on 1 GPU, and it also contains MultiHeads. 165 | 166 | This is how we proceed: 167 | 168 | When you launch the script, set the maximum number of GPUs in the environment (in the example below, 8), then run the first execution with the torch API to create a repository before launching the analyses with the pipeline_tool. 169 | 170 | The results are as follows: 171 | 172 | |Framework|Model |Number of GPUs|Number of Chunks|Time [s] | Alloc [MB] | 173 | |---------|--------|--------------|----------------|------------------|------------------| 174 | |API torch|CNN |1 |0 |0.53|[625]| 175 | |API torch|FFNET |1 |0 |0.25|[520]| 176 | |Pipeline |CNN |1 |2 |1.16|[698]| 177 | |Pipeline |CNN |2 |2 |2.03|[582, 514]| 178 | |Pipeline |CNN |3 |2 |2.22|[582, 0, 514]| 179 | |Pipeline |CNN |4 |2 |3.31|[69, 514, 513, 514]| 180 | |Pipeline |CNN |5 |2 |3.97|[79, 45, 514, 513, 513]| 181 | |Pipeline |CNN |6 |2 |5.427|[79, 51, 0, 514, 513, 513]| 182 | |Pipeline |CNN |7 |2 |5.97|[54, 68, 0, 514, 513, 0, 513]| 183 | |Pipeline |FFNET |1 |2 |0.67|[668]| 184 | |Pipeline |FFNET |2 |2 |1.4|[522, 514]| 185 | |Pipeline |VisionTransformer|2 |2 |2269.89|[3979519, 3958031]| 186 | |Pipeline |VisionTransformer|3 |2 |2014.98|[2574197, 3021793, 2635734]| 187 | |Pipeline |VisionTransformer|4 |2 |1861.44|[2119623, 2228904, 2145561, 2112281]| 188 | |Pipeline |VisionTransformer|5 |2 |1786.39|[1706017, 1918617, 1732474, 1925785, 1657517]| 189 | |Pipeline |VisionTransformer|6 |2 |1715.75|[1478507, 1691115, 1546192, 1664987, 1546192, 1430453]| 190 | |Pipeline |VisionTransformer|7 |2 |1676.8 |[1437800, 1277582, 1436969, 1498672, 1277582, 1477999, 1229807]| 191 | |Pipeline |VisionTransformer|8 |2 |1631.67|[1210541, 1278218, 1277900, 1312002, 1276935, 1209459, 1209459, 1195574]| 192 | 193 | 194 | ### Result analysis 195 | Firstly, we notice that some results are missing; for example, for the FFNET, we only have results on 1 or 2 GPUs, etc. It's simply because when an error occurs, we don't store the result in the benchmark. But there are 4 possible types of error: 196 | 197 | 1. If the first/last GPU in the chain has only one layer, it cannot be executed. 198 | 2. One of the GPUs has 0 layers. 199 | 3. Cuda Out of Memory, at least 1 of the GPUs can't handle the amount of layers and data given to it. 200 | 4. Finally, an error occurs during training. 201 | 202 | If none of these errors occur, we store the results. 203 | 204 | So, based on this, we can see right away that no input is available with the torch API for the VisionTransformer, simply because it doesn't fit on a single GPU. As a result, the pipeline tool allows the model to be separated on multiple GPUs; we can see that with the VisionTransformers that can only be run on more than 1 GPU. Another point to note is that the tool slows down execution time anyway, due to the added communication between GPUs; execution time between the torch API and runs of the Pipeline in 1 GPU show it clearly. So you can't use it routinely and should only use it in really useful cases, i.e., when the model can't fit on a single GPU. 205 | 206 | 207 | ## Visual explaination of the Pipeline Tool 208 | A [flowchart](./img/Pipeline_tool_flowchart.png) explain all the process made by the tool for generating a complete model. 209 | 210 | ## Complex Models 211 | 212 | Unfortunately, a model is never limited to a simple linear sequence of modules taking the output of the previous operation as input... More complex models exist, and it is necessary to handle all possible cases, to trace the model correctly so that it is faithfully reproduced without omitting certain operations. 213 | 214 | As a result, it is necessary to distinguish PyTorch modules from other elements. 215 | 216 | We analyze the model received as a parameter and store the elements by their names in a dictionary, which we use to create a correspondence table with the names given by the trace. 217 | 218 | We can then iterate over the generated trace to differentiate five types of layers: 219 | 220 | 1. **Module**: These need to be initialized and thus require their description to be retrieved from the original model. 221 | 2. **Function**: These correspond to simple PyTorch functions executed between tensors or on a tensor (e.g., additions, dimension reductions, etc.). 222 | 3. **Getitem**: These appear in the trace when only a portion of a result in the form of a list needs to be retrieved (e.g., index 1 of a list or the first return value of a function). 223 | 4. **Getattr**: These correspond to retrieving an attribute of a tensor. 224 | 5. **Propagation**: These appear in the trace to propagate tensors to other layers. 225 | 226 | ### call_function 227 | 228 | Let's explore the concept of call_function with the widely known ResNet model. 229 | 230 | When we examine the generated trace, we notice a new opcode, distinct from the one we previously discussed in the [first step](#first-step) : 231 | 232 | ```bash 233 | Opcode Name Arguments 234 | placeholder x () 235 | call_module flow_0_conv1 (x,) 236 | [...] 237 | call_module flow_0_avgpool (flow_0_layer4_1_relu_1,) 238 | # ############################################################################################ 239 | call_function flatten (flow_0_avgpool, 1) 240 | # ############################################################################################ 241 | call_module flow_0_fc (flatten,) 242 | call_module flow_1 (flow_0_fc,) 243 | output output (flow_1,) 244 | ``` 245 | *Notice that we also have access to the input arguments of each layer.* 246 | 247 | call_functions are treated differently from call_modules and consequently generate distinct code. Therefore, each call_function is declared as a Torch module that exclusively performs the necessary operation. In the case of the previous trace, let's consider the declaration of the call_function `flatten`: 248 | 249 | ```python 250 | class flatten_layer(nn.Module): 251 | def forward(self, input): 252 | ret = torch.flatten(input, 1) 253 | return ret 254 | ``` 255 | 256 | Functions do not necessitate an initialization function. Instead, our tool seeks out the appropriate Torch function based on the name provided in the trace. For instance, when working with the instantiated ResNet18 model, the function "flatten" already exists within the Torch API. 257 | 258 | The trace allows us to identify the arguments passed to this function. In the case above, the inputs are the output of the previous layer and the integer "1". 259 | 260 | ### Propagation 261 | 262 | As discussed in the section on [complex models](#complex-models) there are instances where we need to transmit the output of one layer to others that are not inherently connected to it. To facilitate this process, PyTorch provides a useful decorator called "skippable." This decorator introduces two key features: 263 | 264 | 1. `stash`: This feature permits us to store a specific value with an associated name, allowing for convenient retrieval later. 265 | 266 | 2. `pop`: With this functionality, 267 | 268 | Let's get a look into an example trace to have a better understanding:: 269 | 270 | ```bash 271 | Opcode Name Arguments 272 | placeholder x () 273 | call_module flow_0_conv1 (x,) 274 | [...] 275 | call_module flow_0_maxpool (flow_0_relu,) 276 | call_module flow_0_layer1_0_conv1 (flow_0_maxpool,) 277 | call_module flow_0_layer1_0_bn1 (flow_0_layer1_0_conv1,) 278 | call_module flow_0_layer1_0_relu (flow_0_layer1_0_bn1,) 279 | call_module flow_0_layer1_0_conv2 (flow_0_layer1_0_relu,) 280 | call_module flow_0_layer1_0_bn2 (flow_0_layer1_0_conv2,) 281 | ############################################################################################# 282 | call_function add (flow_0_layer1_0_bn2, flow_0_maxpool) 283 | ############################################################################################# 284 | call_module flow_0_layer1_0_relu_1 (add,) 285 | [...] 286 | call_module flow_0_fc (flatten,) 287 | call_module flow_1 (flow_0_fc,) 288 | output output (flow_1,) 289 | ``` 290 | 291 | The call_function surrounded have two name in input : 292 | - flow_0_layer1_0_bn2, which directly stems from the previous layer. 293 | - flow_0_maxpool, originating from an earlier layer in the model. 294 | 295 | Our tool is designed to establish connections between layers and retain information about the arguments derived from prior layers. 296 | 297 | Consequently, when utilizing the skippable decorator in the generated code: 298 | 299 | ```python 300 | [...] 301 | 302 | @skippable(stash=['flow_0_maxpool_to_add']) 303 | class flow_0_maxpool_layer(nn.Module): 304 | def __init__(self) -> None: 305 | super().__init__() 306 | self.fc = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) 307 | def forward(self, input): 308 | ret = self.fc(input) 309 | yield stash('flow_0_maxpool_to_add', ret) 310 | return ret 311 | 312 | [...] 313 | 314 | class flow_0_layer1_0_bn2_layer(nn.Module): 315 | def __init__(self) -> None: 316 | super().__init__() 317 | self.fc = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) 318 | def forward(self, input): 319 | ret = self.fc(input) 320 | return ret 321 | 322 | @skippable(pop=['flow_0_maxpool_to_add']) 323 | class add_layer(nn.Module): 324 | def forward(self, input): 325 | flow_0_maxpool = yield pop('flow_0_maxpool_to_add') 326 | ret = torch.add(input, flow_0_maxpool) 327 | return ret 328 | 329 | [...] 330 | ``` 331 | We ensure that the dependencies between layers are properly preserved. 332 | 333 | 334 | ### Getitem 335 | 336 | Within the trace, certain call_function entries contain the term "getitem" in their names. This indicates that these are not conventional functions but rather indicate the need to access a specific index within a result. Consider the following trace as an example: 337 | 338 | ```bash 339 | [...] 340 | call_function getattr_1 (add_3, 'shape') 341 | call_function getitem_4 (getattr_1, 0) 342 | [...] 343 | ``` 344 | 345 | Here, we notice the presence of a getitem operation, which is applied to the result of the previous layer. If we were to translate this trace, it would resemble something like add_3.shape[0] (for an explanation of getattr, please refer to the [next point](#getattr)). 346 | 347 | The challenge with getitem lies in the limitation of the Torch API, which does not allow the propagation of non-tensor values. Consequently, we must concatenate the getitem operation to the layer from which we require the value, rather than creating an independent layer that cannot effectively transmit its output. 348 | 349 | ### GetAttr 350 | 351 | There are two distinct types of `getattr` operations: 352 | 353 | 1. **call_function with the Name "getattr"**: These instances occur when an attribute of modules needs to be accessed.. 354 | 355 | In the provided trace: 356 | 357 | ```bash 358 | [...] 359 | call_function getattr_1 (add_3, 'shape') 360 | [...] 361 | call_module model_pooling_layer_scaled_dot_product_attention (expand, add_3, add_3) 362 | ``` 363 | 364 | As previously mentioned, we cannot propagate non-tensor values. The presence of getattr indicates the need to access a specific attribute within a module. In the trace above, the tensor add_3 possesses an attribute "shape" that will be utilized. In such cases, we refrain from creating new modules; instead, we reference the relevant attribute of the tensor when it is passed as a parameter. 365 | 366 | Here's an illustrative example of generated code to elucidate this approach: 367 | 368 | ```python 369 | [...] 370 | @skippable(stash=['add_3_to_expand', 'add_3_to_model_pooling_layer_scaled_dot_product_attention'], pop=['add_2_to_add_3']) 371 | class add_3_layer(nn.Module): 372 | def forward(self, input): 373 | add_2 = yield pop('add_2_to_add_3') 374 | ret = torch.add(input, add_2) 375 | yield stash('add_3_to_expand', ret) 376 | yield stash('add_3_to_model_pooling_layer_scaled_dot_product_attention', ret) 377 | return ret 378 | [...] 379 | @skippable(pop=['add_3_to_expand']) 380 | class expand_layer(nn.Module): 381 | def forward(self, input): 382 | add_3 = yield pop('add_3_to_expand') 383 | ret = input.expand(add_3.shape[0], -1, -1) 384 | return ret 385 | ``` 386 | 387 | 388 | 2. **get_attr with the Opcode "get_attr"**: These occurrences arise when a private attribute of a user-created class is requested. 389 | 390 | In the provided trace: 391 | ```bash 392 | get_attr model_pooling_layer_query () 393 | ``` 394 | 395 | We only have the name of the attribute, and it needs to be initialized to propagate or utilize it, we create a module that initializes the attribute based on the provided information. We search for the attribute on the given model and recreate it identically. 396 | 397 | Here's an example of code to illustrate this process: 398 | 399 | ```python 400 | class model_pooling_layer_query_layer(nn.Module): 401 | def __init__(self) -> None: 402 | super().__init__() 403 | self.fc = nn.parameter.Parameter(torch.Tensor(1, 16), requires_grad=True) 404 | def forward(self, input): 405 | ret = self.fc 406 | return ret 407 | ``` 408 | 409 | ### MultiHeadAttention processing 410 | 411 | Unpredictable management is, however, necessary for MultiHeadAttention. During the module declaration retrieval phase, it is impossible to retrieve those of the MultiHeadAttention. Therefore, the user must provide a dictionary containing the description of all the parameters and their values for the MultiHeadAttention of their model during the tool's initialization. 412 | 413 | At a minimum, the following parameters must be provided for a MultiHead: 414 | 415 | - embed_dim 416 | - num_heads 417 | 418 | And the initialization would be changed to three alternative: 419 | 420 | 1. Give your hand made dictionnary describing all your MHA 421 | 422 | ```python 423 | mha_config = [{'embed_dim': hidden_val, 'num_heads': heads_val, 'dropout': 0.1, 'batch_first': True}, 424 | {'embed_dim': hidden_val, 'num_heads': heads_val, 'dropout': 0.1, 'batch_first': True}, 425 | {'embed_dim': hidden_val, 'num_heads': heads_val, 'dropout': 0.1, 'batch_first': True}, 426 | {'embed_dim': hidden_val, 'num_heads': heads_val, 'dropout': 0.1, 'batch_first': True}, 427 | {'embed_dim': hidden_val, 'num_heads': heads_val, 'dropout': 0.1, 'batch_first': True}] 428 | config = PipelineConfig([X, Y, Z], [X, Y], "dtype", mha_config) 429 | nb_gpus = 2 430 | trace = SkippableTracing(nb_gpus, model, config) 431 | model_pipe = trace.get_modules() 432 | ``` 433 | 2. Use MHA dictionnary generator in PipelineConfig class. If you know that all your MHA are identical, you can use this function to create N dictionnary entry identical. 434 | ```python 435 | config = PipelineConfig([X, Y, Z], [X, Y], "dtype") 436 | config.create_mha_conf_equal(embed_dim, num_heads, dropout, batch_first) 437 | nb_gpus = 2 438 | trace = SkippableTracing(nb_gpus, model, config) 439 | model_pipe = trace.get_modules() 440 | ``` 441 | 3. Finaly some default model are setup with classmethod, Persformer, one bigger Persformer and VideoTransformer. 442 | ```python 443 | # TODO EXPLAINATION 444 | ``` 445 | 446 | 447 | ## Improvements 448 | In its current state, the tool works, but it hasn't been designed for performance yet. That's why the following points for improvement are important: 449 | 450 | 1. Although repartition is currently performed, it is unnecessary when the model fits within a single GPU. The process should automatically avoid splitting when feasible, requiring an initial run on the largest GPU and an error-handling mechanism. 451 | 2. Replace the rudimentary repartition method with a more efficient approach, such as employing a dichotomous search. 452 | 3. Actually, the tool is searching for the best memory balancing between GPUs. But after some execution time analysis, this solution is not the best concerning execution time. One improvement should be to search for the best execution time instead of the best memory balancing. To put this solution in place: 453 | 1. Change the analysis returned by the script [evaluate_mem.py](./pipeline_tool/evaluate_mem.py) to return time and not memory balancing. 454 | 2. Find a way to preprocess and create all potential best repartition to avoid testing all possibilities that could be exponential in process time depending on the number of layers. 455 | 3. Change the behavior to test all pre-calculated possibilities and not stop, keeping the fastest one. 456 | 457 | Here is the time analysis made, in italic are the chosen repartition, and in bold, the minimal execution time: 458 | 459 | | **Model** | **Nb GPU** | **Repartition** | **Epoch 1** | **Epoch 2** | **Epoch 3** | **Minimal Epoch time** | 460 | | ----------------- | ---------- | -------------------------------- | ----------- | ----------- | ----------- | ---------------------- | 461 | | CNN | 2 | [7, 7] | 3.85 | 1.84 | **1.79** | | 462 | | CNN | 2 | [8, 6] | 3.81 | 1.91 | 1.85 | | 463 | | *CNN* | *2* | *[9, 5]* | *4.02* | *1.89* | *1.84* | 1.79 | 464 | | | | | | | | | 465 | | CNN | 3 | [5, 5, 4] | 5.08 | 2.49 | 2.55 | | 466 | | CNN | 3 | [6, 4, 4] | 5.05 | 2.65 | 2.66 | | 467 | | CNN | 3 | [7, 3, 4] | 4.95 | 2.62 | 2.51 | | 468 | | CNN | 3 | [8, 2, 4] | 5.13 | 2.54 | 2.62 | | 469 | | *CNN* | *3* | *[9, 1, 4]* | *4.20* | *2.21* | **2.21** | 2.21 | 470 | | | | | | | | | 471 | | CNN | 4 | [4, 4, 3, 3] | 6.66 | 3.20 | 3.32 | | 472 | | CNN | 4 | [4, 5, 2, 3] | 6.65 | 3.36 | 3.40 | | 473 | | CNN | 4 | [5, 4, 2, 3] | 6.20 | 3.32 | 3.25 | | 474 | | CNN | 4 | [6, 3, 2, 3] | 6.14 | 3.21 | 3.16 | | 475 | | CNN | 4 | [7, 2, 2, 3] | 6.07 | 3.23 | 3.28 | | 476 | | *CNN* | *4* | *[8, 1, 2, 3]* | *6.08* | *3.31* | *3.35* | | 477 | | CNN | 4 | [9, 1, 1, 3] | 5.39 | 2.88 | **2.88** | 2.88 | 478 | | | | | | | | | 479 | | CNN | 5 | [3, 3, 3, 3, 2] | 7.96 | 3.96 | 3.85 | | 480 | | CNN | 5 | [3, 4, 2, 3, 2] | 7.81 | 3.87 | 3.73 | | 481 | | CNN | 5 | [3, 5, 1, 3, 2] | 7.86 | 3.85 | 4.05 | | 482 | | CNN | 5 | [3, 6, 1, 2, 2] | 7.05 | 3.61 | **3.53** | | 483 | | *CNN* | *5* | *[3, 5, 2, 2, 2]* | *7.87* | *3.81* | *3.91* | 3.53 | 484 | | | | | | | | | 485 | | *CNN* | *6* | *[3, 3, 2, 2, 2, 2]* | *8.95* | *4.98* | *4.79* | | 486 | | CNN | 6 | [3, 3, 3, 1, 2, 2] | 8.10 | **4.07** | 4.19 | 4.07 | 487 | | | | | | | | | 488 | | CNN | 7 | [2, 2, 2, 2, 2, 2, 2] | 8.55 | 4.60 | 4.64 | | 489 | | CNN | 7 | [2, 3, 2, 2, 1, 2, 2] | 9.59 | 5.69 | 5.53 | | 490 | | *CNN* | *7* | *[2, 3, 3, 1, 1, 2, 2]* | *9.26* | *5.71* | *5.69* | | 491 | | CNN | 7 | [2, 3, 4, 1, 1, 1, 2] | 8.44 | 4.56 | **4.42** | 4.42 | 492 | | | | | | | | | 493 | | *FFNET* | *2* | *[3, 2]* | *2.39* | *1.32* | **1.27** | | 494 | | FFNET | 2 | [2, 3] | 2.41 | 1.39 | 1.34 | 1.27 | 495 | | | | | | | | | 496 | | *VisionTransformer* | *2* | *[184, 184]* | *471.70* | *470.42* | *470.53* | | 497 | | | | | | | | | 498 | | *VisionTransformer* | *3* | *[123, 123, 122]* | *418.28* | *416.19* | *416.29* | | 499 | | | | | | | | | 500 | | *VisionTransformer* | *4* | *[92, 92, 92, 92]* | *385.19* | *382.62* | *383.39* | | 501 | | | | | | | | | 502 | | *VisionTransformer* | *5* | *[74, 74, 74, 73, 73]* | *370.09* | *367.58* | *367.66* | | 503 | | | | | | | | | 504 | | VisionTransformer | 6 | [62, 62, 61, 61, 61, 61] | 356.13 | **353.30** | 353.54 | | 505 | | *VisionTransformer* | *6* | *[63, 62, 61, 60, 61, 61]* | *357.41* | *354.58* | *354.84* | 353.30 | 506 | | | | | | | | | 507 | | VisionTransformer | 7 | [53, 53, 53, 53, 52, 52, 52] | 347.54 | **345.12** | 345.18 | | 508 | | VisionTransformer | 7 | [54, 53, 52, 53, 52, 52, 52] | 351.04 | 347.78 | 347.89 | | 509 | | VisionTransformer | 7 | [55, 52, 52, 53, 52, 52, 52] | 349.60 | 346.24 | 346.29 | | 510 | | VisionTransformer | 7 | [56, 52, 51, 53, 52, 52, 52] | 349.48 | 346.58 | 346.45 | | 511 | | VisionTransformer | 7 | [57, 52, 50, 53, 52, 52, 52] | 349.51 | 346.42 | 346.55 | | 512 | | VisionTransformer | 7 | [58, 52, 49, 53, 52, 52, 52] | 348.30 | 345.28 | 345.35 | | 513 | | *VisionTransformer* | *7* | *[59, 52, 49, 53, 52, 51, 52]* | *348.69* | *345.15* | *345.28* | 345.12 | 514 | | | | | | | | | 515 | | VisionTransformer | 8 | [46, 46, 46, 46, 46, 46, 46, 46] | 342.10 | 338.47 | 338.73 | | 516 | | VisionTransformer | 8 | [47, 45, 46, 46, 46, 46, 46, 46] | 342.17 | 338.51 | 338.44 | | 517 | | *VisionTransformer* | *8* | *[48, 44, 46, 46, 46, 46, 46, 46]* | *339.99* | *336.45* | **336.44** | 336.44 | 518 | 519 | ## Known issue 520 | 1. The pipeline of Persformers in more than 2 GPU have backward process problem for an unknow reason and no error is throw. 521 | 2. Actually when a CUDA error OOM is throw we admit that the envrionement don't have enough GPU. In the futur we will implement logic test to see if yes or not the model can be split on the desired config before telling that it is impossible. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------