add resources for pytorch 2 intro

This commit is contained in:
Daniel Bourke committed 2023-03-23 12:56:39 +10:00
1 parent 8e59ca153a
commit 4db7d3cc5c
4 files changed
+331 -54

No files matched your search

+331 -54
View File
@@ -5,51 +5,274 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# WIP: A Quick PyTorch 2.0 Tutorial\n",
"# WIP: A Quick PyTorch 2.0 Tutorial\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Notebook last updated: 2023-03-23 12:41:18.916374\n"
]
}
],
"source": [
"import datetime\n",
"print(f\"Notebook last updated: {datetime.datetime.now()}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"In short:\n",
"## 30-second intro\n",
"\n",
"If you have a new GPU (NVIDIA 40XX or A100, A10G etc), you can \"compile\" your models and often see speed ups.\n",
"PyTorch 2.0 is out!\n",
"\n",
"**Before PyTorch 2.0:**\n",
"With the main improvement being speed.\n",
"\n",
"This comes via a single backwards-compatible line.\n",
"\n",
"```python\n",
"import torch\n",
"\n",
"model = create_model()\n",
"\n",
"### Train model ###\n",
"\n",
"### Test model ###\n",
"torch.compile()\n",
"```\n",
"\n",
"**After PyTorch 2.0:**\n",
"In other words, after you create your model, you can pass it to `torch.compile()` and in turn expect speedups in training and inference on newer GPUs (e.g. NVIDIA RTX 40 series, A100, H100, the newer the GPU the more noticeable the speedups).\n",
"\n",
"```python\n",
"import torch\n",
"\n",
"model = create_model()\n",
"compiled_model = torch.compile(model) # <- new!\n",
"\n",
"### Train model ### <- faster!\n",
"\n",
"### Test model ### <- faster!\n",
"```\n",
"\n",
"Things to note:\n",
"* TK - add where it doesn't work\n",
"\n",
"## TK - Resources to learn more\n",
"* PyTorch 2.0 launch blog post - https://pytorch.org/get-started/pytorch-2.0/ \n",
"* PyTorch 2.0 release notes - https://pytorch.org/blog/pytorch-2.0-release/ \n",
" * GitHub release notes - https://github.com/pytorch/pytorch/releases/tag/v2.0.0 (lots of info here!)\n",
"* PyTorch default device context manager - https://github.com/pytorch/tutorials/pull/2220/files "
"> **Note:** Backwards-compatible means that if you already know PyTorch, such as via the [learnpytorch.io](https://learnpytorch.io) course, you can start using PyTorch 2.0 straight away."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code examples"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Before PyTorch 2.0"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torchvision\n",
"\n",
"model = torchvision.models.resnet50() # note: this could be any model\n",
"\n",
"### Train model ###\n",
"\n",
"### Test model ###"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### After PyTorch 2.0"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torchvision\n",
"\n",
"model = torchvision.models.resnet50() # note: this could be any model\n",
"compiled_model = torch.compile(model) # <- magic happens!\n",
"\n",
"### Train model ### <- faster!\n",
"\n",
"### Test model ### <- faster!"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Speedups\n",
"\n",
"Ok so the focus of PyTorch 2.0 is speed, how much faster is it actually?\n",
"\n",
"The PyTorch team ran tests across 163 open-source models from [Hugging Face Transformers](https://huggingface.co/docs/transformers/index), [timm](https://github.com/huggingface/pytorch-image-models) (PyTorch Image Models) and [TorchBench](https://github.com/pytorch/benchmark) (a curated set of popular code bases from across GitHub).\n",
"\n",
"This is important because unless PyTorch 2.0 is faster on models people actually use, it’s not faster.\n",
"\n",
"Using a mixture of AMP (automatic mixed precision or float16) training and float32 precision (higher precision requires more compute) the PyTorch team found that `torch.compile()` provides an average speedup of 43% in training on a NVIDIA A100 GPU.\n",
"\n",
"Or 38% on timm, 76% on TorchBench and 52% on Hugging Face Transformers.\n",
"\n",
"TK - image of speedups"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3-minute overview\n",
"\n",
"> **Note:** The following is adapted from [*A Quick Introduction to PyTorch 2.0*](https://www.mrdbourke.com/pytorch-2/) on mrdbourke.com.\n",
"\n",
"What's happening behind the scenes of `torch.compile()`?\n",
"\n",
"`torch.compile()` is designed to \"just work\" but there are a few technologies behind it:\n",
"* TorchDynamo\n",
"* AOTAutograd\n",
"* PrimTorch\n",
"* TorchInductor\n",
"\n",
"The [PyTorch 2.0 getting started notes](https://pytorch.org/get-started/pytorch-2.0/) explain these in more detail but from a high level the two main improvements `torch.compile()` offers are:\n",
"* Fusion (or operator fusion)\n",
"* Graph capture (or graph tracing)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Fusion\n",
"\n",
"Fusion, also known as **operator fusion** is one of the best ways to make deep learning models go brrrrrr (brrrrrr is the sound your GPUs fan make when your models are training).\n",
"\n",
"Operator fusion condenses (like Dragon Ball Z) many operations into one (or many to less).\n",
"\n",
"Why?\n",
"\n",
"Modern GPUs have so much compute power they are often not compute limited, as in, the main bottleneck to training models is how fast can you get data from your CPU to your GPU.\n",
"This is known as bandwidth or memory bandwidth.\n",
"\n",
"You want to reduce your bandwidth costs as much as possible.\n",
"\n",
"And feed the data hungry GPUs with as much data as possible.\n",
"\n",
"TK - image of fusion\n",
"\n",
"So instead of performing an operation on a piece of data and then saving the result to memory (increased bandwidth costs), you chain together as many operations as possible via fusion.\n",
"\n",
"A rough analogy would be using a blender to make a smoothie.\n",
"\n",
"Most blenders are good at blending things (like GPUs are good at performing matrix multiplications).\n",
"\n",
"Using a blender **without operator fusion** would be like adding each ingredient one by one and blending each time a new ingredient is added.\n",
"Not only is this insane, it increases your bandwidth cost.\n",
"\n",
"The actual blending is fast each time (like GPU computations generally are) but you lose a bunch of time adding each ingredient one by one.\n",
"\n",
"Using a blender **with operator fusion** is akin to using a blender by adding all the ingredients at the start (operator fusion) and then performing the blend once.\n",
"\n",
"You lose a little time adding at the start but you gain all of the lost memory bandwidth time back."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Graph capture\n",
"\n",
"Graph capture I’m less confident explaining.\n",
"\n",
"But the way I think about is that graph capture or graph tracing is:\n",
"\n",
"* Going through a series of operations that need to happen, such as the operations in a neural network.\n",
"* And capturing or tracing what needs to happen ahead of time.\n",
"\n",
"Computing **without graph capture** is like going to a new area and following GPS directions turn by turn.\n",
"\n",
"As a good human driver, you can follow the turns quite easily but you still have to think about each turn you take.\n",
"\n",
"This is the equivalent to PyTorch having to look up what each operation does as it does it.\n",
"\n",
"As in, to perform an addition, it has to look up what an addition does before it can perform it.\n",
"\n",
"It does this quickly but there’s still non-zero overhead.\n",
"\n",
"TK - image of graph capture\n",
"\n",
"Computing **with graph capture** is like driving through your own neighbourhood.\n",
"\n",
"You barely think about what turns to make.\n",
"\n",
"Sometimes you get out of the car and realise you can’t remember the last 5 minutes of the drive.\n",
"\n",
"Your brain was functioning on autopilot, minimal overhead.\n",
"\n",
"However, it took you some time upfront to remember how to drive to your house.\n",
"\n",
"This is a caveat of graph capture, it takes a little time upfront to memorize the operations that need to happen but subsequent computations should be faster.\n",
"\n",
"Of course, this is a quick high-level overview of what’s happening behind the scenes of torch.compile()but it's how I understand it.\n",
"\n",
"For more on fusion and graph tracing, I’d recommend Horace He’s [*Making Deep Learning Go Brrrr From First Principles*](https://horace.io/brrr_intro.html) blog post."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Things to note\n",
"\n",
"Since PyTorch 2.0 was just released, there are a few limitations with some of the features.\n",
"\n",
"One of the main ones being with exporting models.\n",
"\n",
"TK - image of where it doesn't work\n",
"\n",
"However, these will likely be fixed in future releases.\n",
"\n",
"Another main limitation is that because the features of PyTorch 2.0 are designed for newer hardware, old GPUs and desktop-class GPUs (e.g. NVIDIA RTX 30 series) will likely see less speedups than newer hardware."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## TK - Resources to learn more\n",
"\n",
"The following resources are helpful \n",
"* PyTorch 2.0 launch blog post - https://pytorch.org/get-started/pytorch-2.0/ \n",
"* PyTorch 2.0 release notes - https://pytorch.org/blog/pytorch-2.0-release/ \n",
" * GitHub release notes - https://github.com/pytorch/pytorch/releases/tag/v2.0.0 (lots of info here!)\n",
"* PyTorch default device context manager - https://github.com/pytorch/tutorials/pull/2220/files \n",
"* PyTorch 2.0 video introduction - https://youtu.be/WqLKfta5Ijw"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## TK - 0. Getting setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
@@ -109,28 +332,6 @@
" print(mod(torch.randn(128, 20)).device)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11.8\n",
"True\n",
"8700\n"
]
}
],
"source": [
"import torch\n",
"print(torch.version.cuda)\n",
"print(torch.cuda.is_available())\n",
"print(torch.backends.cudnn.version())"
]
},
{
"attachments": {},
"cell_type": "markdown",
@@ -209,7 +410,9 @@
"\n",
" # Get GPU capability score\n",
" gpu_score = torch.cuda.get_device_capability()\n",
" print(f\"GPU capability score: {gpu_score}\")"
" print(f\"GPU capability score: {gpu_score}\")\n",
"\n",
" # TK - print out if GPU score is capable of getting the best speedups "
]
},
{
@@ -759,6 +962,13 @@
"model, transforms = create_model()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 19,
@@ -954,6 +1164,73 @@
"model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"\n",
"model = create_model()\n",
"compiled_model = torch.compile(model) # <- magic happens!\n",
"\n",
"### Train model ### <- faster!\n",
"\n",
"### Test model ### <- faster!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from torch import nn\n",
"\n",
"class YourModel(nn.Module):\n",
" cos = torch.cos()\n",
" sin = torch.sin()\n",
"\n",
" def forward(self, x):\n",
" # Without operator fusion\n",
" x = self.cos(x)\n",
" x = self.sin(x)\n",
" return x"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from torch import nn\n",
"\n",
"class YourModel(nn.Module):\n",
" cos = torch.cos()\n",
" sin = torch.sin()\n",
"\n",
" def forward(self, x):\n",
" # With operator fusion\n",
" return self.cos(self.sin(x))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"\n",
"model = create_model()\n",
"\n",
"### Train model ###\n",
"\n",
"### Test model ###"
]
},
{
"cell_type": "code",
"execution_count": 21,
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB