", "metadata": {"source": "https://pytorch.org/blog/a-contributor-license-agreement-for-pytorch/", "category": "pytorch blogs"}}
{"page_content": "
\n

\n
\n\nIf you're contributing as an individual, meaning the code is not something you worked on as part of your job, you should sign the individual contributor agreement. This agreement associates your GitHub username with future contributions and only needs to be signed once.\n\nIf you're contributing as part of your employment, you may need to sign the [corporate contributor agreement](https://code.facebook.com/cla/corporate). Check with your legal team on filling this out. Also you will include a list of github ids from your company.\n\nAs always, we continue to be humbled and grateful for all your support, and we look forward to scaling PyTorch together to even greater heights in the years to come.\n\nThank you!\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/a-contributor-license-agreement-for-pytorch/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'Feature Extraction in TorchVision using Torch FX'\nauthor: Alexander Soare and Francisco Massa\nfeatured-img: 'assets/images/fx-image2.png'\n---\n\n\n\n# Introduction\n\n[FX](https://pytorch.org/docs/stable/fx.html) based feature extraction is a new [TorchVision utility](https://pytorch.org/vision/stable/feature_extraction.html) that lets us access intermediate transformations of an input during the forward pass of a PyTorch Module. It does so by symbolically tracing the forward method to produce a graph where each node represents a single operation. Nodes are named in a human-readable manner such that one may easily specify which nodes they want to access.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "Did that all sound a little complicated? Not to worry as there\u2019s a little in this article for everyone. Whether you\u2019re a beginner or an advanced deep-vision practitioner, chances are you will want to know about FX feature extraction. If you still want more background on feature extraction in general, read on. If you\u2019re already comfortable with that and want to know how to do it in PyTorch, skim ahead to Existing Methods in PyTorch: Pros and Cons. And if you already know about the challenges of doing feature extraction in PyTorch, feel free to skim forward to FX to The Rescue.\n\n\n## A Recap On Feature Extraction\n\nWe\u2019re all used to the idea of having a deep neural network (DNN) that takes inputs and produces outputs, and we don\u2019t necessarily think of what happens in between. Let\u2019s just consider a ResNet-50 classification model as an example:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "
\n\t
\n\t
\n\t\tFigure 1: ResNet-50 takes an image of a bird and transforms that into the abstract concept \"bird\". Source: Bird image from ImageNet.\n
\n\nWe know though, that there are many sequential \u201clayers\u201d within the ResNet-50 architecture that transform the input step-by-step. In Figure 2 below, we peek under the hood to show the layers within ResNet-50, and we also show the intermediate transformations of the input as it passes through those layers.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "
\n\t
\n\t
\n\t\tFigure 2: ResNet-50 transforms the input image in multiple steps. Conceptually, we may access the intermediate transformation of the image after each one of these steps. Source: Bird image from ImageNet.\n
\n\n\n## Existing Methods In PyTorch: Pros and Cons\n\nThere were already a few ways of doing feature extraction in PyTorch prior to FX based feature extraction being introduced.\n\nTo illustrate these, let\u2019s consider a simple convolutional neural network that does the following\n\n* Applies several \u201cblocks\u201d each with several convolution layers within.\n* After several blocks, it uses a global average pool and flatten operation.\n* Finally it uses a single output classification layer.\n\n```python\nimport torch\nfrom torch import nn", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "```python\nimport torch\nfrom torch import nn\n\n\nclass ConvBlock(nn.Module):\n \"\"\"\n Applies `num_layers` 3x3 convolutions each followed by ReLU then downsamples\n via 2x2 max pool.\n \"\"\"\n\n def __init__(self, num_layers, in_channels, out_channels):\n super().__init__()\n self.convs = nn.ModuleList(\n [nn.Sequential(\n nn.Conv2d(in_channels if i==0 else out_channels, out_channels, 3, padding=1),\n nn.ReLU()\n )\n for i in range(num_layers)]\n )\n self.downsample = nn.MaxPool2d(kernel_size=2, stride=2)\n \n def forward(self, x):\n for conv in self.convs:\n x = conv(x)\n x = self.downsample(x)\n return x\n \n\nclass CNN(nn.Module):\n \"\"\"\n Applies several ConvBlocks each doubling the number of channels, and\n halving the feature map size, before taking a global average and classifying.\n \"\"\"", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "def __init__(self, in_channels, num_blocks, num_classes):\n super().__init__()\n first_channels = 64\n self.blocks = nn.ModuleList(\n [ConvBlock(\n 2 if i==0 else 3,\n in_channels=(in_channels if i == 0 else first_channels*(2**(i-1))),\n out_channels=first_channels*(2**i))\n for i in range(num_blocks)]\n )\n self.global_pool = nn.AdaptiveAvgPool2d((1, 1))\n self.cls = nn.Linear(first_channels*(2**(num_blocks-1)), num_classes)\n\n def forward(self, x):\n for block in self.blocks:\n x = block(x)\n x = self.global_pool(x)\n x = x.flatten(1)\n x = self.cls(x)\n return x\n\n\nmodel = CNN(3, 4, 10)\nout = model(torch.zeros(1, 3, 32, 32)) # This will be the final logits over classes\n\n```\n\nLet\u2019s say we want to get the final feature map before global average pooling. We could do the following:\n\n### Modify the forward method", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "### Modify the forward method\n\n```python\ndef forward(self, x):\n for block in self.blocks:\n x = block(x)\n self.final_feature_map = x\n x = self.global_pool(x)\n x = x.flatten(1)\n x = self.cls(x)\n return x\n```\n\nOr return it directly:\n\n```python\ndef forward(self, x):\n for block in self.blocks:\n x = block(x)\n final_feature_map = x\n x = self.global_pool(x)\n x = x.flatten(1)\n x = self.cls(x)\n return x, final_feature_map\n```\nThat looks pretty easy. But there are some downsides here which all stem from the same underlying issue: that is, modifying the source code is not ideal:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "* It\u2019s not always easy to access and change given the practical considerations of a project.\n* If we want flexibility (switching feature extraction on or off, or having variations on it), we need to further adapt the source code to support that.\n* It\u2019s not always just a question of inserting a single line of code. Think about how you would go about getting the feature map from one of the intermediate blocks with the way I\u2019ve written this module.\n* Overall, we\u2019d rather avoid the overhead of maintaining source code for a model, when we actually don\u2019t need to change anything about how it works.\n\nOne can see how this downside can start to get a lot more thorny when dealing with larger, more complicated models, and trying to get at features from within nested submodules.\n\n### Write a new module using the parameters from the original one\n\nFollowing on the example from above, say we want to get a feature map from each block. We could write a new module like so:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "```python\nclass CNNFeatures(nn.Module):\n def __init__(self, backbone):\n super().__init__()\n self.blocks = backbone.blocks\n\n def forward(self, x):\n feature_maps = []\n for block in self.blocks:\n x = block(x)\n feature_maps.append(x)\n return feature_maps\n\n\nbackbone = CNN(3, 4, 10)\nmodel = CNNFeatures(backbone)\nout = model(torch.zeros(1, 3, 32, 32)) # This is now a list of Tensors, each representing a feature map\n```\n\nIn fact, this is much like the method that TorchVision used internally to make many of its detection models. \n\nAlthough this approach solves some of the issues with modifying the source code directly, there are still some major downsides:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "* It\u2019s only really straight-forward to access the outputs of top-level submodules. Dealing with nested submodules rapidly becomes complicated.\n* We have to be careful not to miss any important operations in between the input and the output. We introduce potential for errors in transcribing the exact functionality of the original module to the new module.\n\nOverall, this method and the last both have the complication of tying in feature extraction with the model\u2019s source code itself. Indeed, if we examine the source code for TorchVision models we might suspect that some of the design choices were influenced by the desire to use them in this way for downstream tasks.\n\n### Use hooks\n\nHooks move us away from the paradigm of writing source code, towards one of specifying outputs. Considering our toy CNN example above, and the goal of getting feature maps for each layer, we could use hooks like this:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "Did that all sound a little complicated? Not to worry as there\u2019s a little in this article for everyone. Whether you\u2019re a beginner or an advanced deep-vision practitioner, chances are you will want to know about FX feature extraction. If you still want more background on feature extraction in general, read on. If you\u2019re already comfortable with that and want to know how to do it in PyTorch, skim ahead to Existing Methods in PyTorch: Pros and Cons. And if you already know about the challenges of doing feature extraction in PyTorch, feel free to skim forward to FX to The Rescue.\n\n\n## A Recap On Feature Extraction\n\nWe\u2019re all used to the idea of having a deep neural network (DNN) that takes inputs and produces outputs, and we don\u2019t necessarily think of what happens in between. Let\u2019s just consider a ResNet-50 classification model as an example:\n\n
", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "
\n\t
\n\t
\n\t\tFigure 1: ResNet-50 takes an image of a bird and transforms that into the abstract concept \"bird\". Source: Bird image from ImageNet.\n
\n\nWe know though, that there are many sequential \u201clayers\u201d within the ResNet-50 architecture that transform the input step-by-step. In Figure 2 below, we peek under the hood to show the layers within ResNet-50, and we also show the intermediate transformations of the input as it passes through those layers.\n\n
\n\t
\n\t
", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "
\n\t\tFigure 2: ResNet-50 transforms the input image in multiple steps. Conceptually, we may access the intermediate transformation of the image after each one of these steps. Source: Bird image from ImageNet.\n
\n\n\n## Existing Methods In PyTorch: Pros and Cons\n\nThere were already a few ways of doing feature extraction in PyTorch prior to FX based feature extraction being introduced.\n\nTo illustrate these, let\u2019s consider a simple convolutional neural network that does the following\n\n* Applies several \u201cblocks\u201d each with several convolution layers within.\n* After several blocks, it uses a global average pool and flatten operation.\n* Finally it uses a single output classification layer.\n\n```python\nimport torch\nfrom torch import nn\n\n\nclass ConvBlock(nn.Module):\n \"\"\"\n Applies `num_layers` 3x3 convolutions each followed by ReLU then downsamples\n via 2x2 max pool.\n \"\"\"\n\n def __init__(self, num_layers, in_channels, out_channels):\n super().__init__()\n self.convs = nn.ModuleList(", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "self.convs = nn.ModuleList(\n [nn.Sequential(\n nn.Conv2d(in_channels if i==0 else out_channels, out_channels, 3, padding=1),\n nn.ReLU()\n )\n for i in range(num_layers)]\n )\n self.downsample = nn.MaxPool2d(kernel_size=2, stride=2)\n \n def forward(self, x):\n for conv in self.convs:\n x = conv(x)\n x = self.downsample(x)\n return x\n \n\nclass CNN(nn.Module):\n \"\"\"\n Applies several ConvBlocks each doubling the number of channels, and\n halving the feature map size, before taking a global average and classifying.\n \"\"\"\n\n def __init__(self, in_channels, num_blocks, num_classes):\n super().__init__()\n first_channels = 64\n self.blocks = nn.ModuleList(\n [ConvBlock(\n 2 if i==0 else 3,\n in_channels=(in_channels if i == 0 else first_channels*(2**(i-1))),\n out_channels=first_channels*(2**i))\n for i in range(num_blocks)]\n )", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "for i in range(num_blocks)]\n )\n self.global_pool = nn.AdaptiveAvgPool2d((1, 1))\n self.cls = nn.Linear(first_channels*(2**(num_blocks-1)), num_classes)\n\n def forward(self, x):\n for block in self.blocks:\n x = block(x)\n x = self.global_pool(x)\n x = x.flatten(1)\n x = self.cls(x)\n return x\n\n\nmodel = CNN(3, 4, 10)\nout = model(torch.zeros(1, 3, 32, 32)) # This will be the final logits over classes\n\n```\n\nLet\u2019s say we want to get the final feature map before global average pooling. We could do the following:\n\n### Modify the forward method\n\n```python\ndef forward(self, x):\n for block in self.blocks:\n x = block(x)\n self.final_feature_map = x\n x = self.global_pool(x)\n x = x.flatten(1)\n x = self.cls(x)\n return x\n```\n\nOr return it directly:\n\n```python\ndef forward(self, x):\n for block in self.blocks:\n x = block(x)\n final_feature_map = x\n x = self.global_pool(x)\n x = x.flatten(1)\n x = self.cls(x)", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "x = x.flatten(1)\n x = self.cls(x)\n return x, final_feature_map\n```\nThat looks pretty easy. But there are some downsides here which all stem from the same underlying issue: that is, modifying the source code is not ideal:\n\n* It\u2019s not always easy to access and change given the practical considerations of a project.\n* If we want flexibility (switching feature extraction on or off, or having variations on it), we need to further adapt the source code to support that.\n* It\u2019s not always just a question of inserting a single line of code. Think about how you would go about getting the feature map from one of the intermediate blocks with the way I\u2019ve written this module.\n* Overall, we\u2019d rather avoid the overhead of maintaining source code for a model, when we actually don\u2019t need to change anything about how it works.\n\nOne can see how this downside can start to get a lot more thorny when dealing with larger, more complicated models, and trying to get at features from within nested submodules.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "### Write a new module using the parameters from the original one\n\nFollowing on the example from above, say we want to get a feature map from each block. We could write a new module like so:\n\n```python\nclass CNNFeatures(nn.Module):\n def __init__(self, backbone):\n super().__init__()\n self.blocks = backbone.blocks\n\n def forward(self, x):\n feature_maps = []\n for block in self.blocks:\n x = block(x)\n feature_maps.append(x)\n return feature_maps\n\n\nbackbone = CNN(3, 4, 10)\nmodel = CNNFeatures(backbone)\nout = model(torch.zeros(1, 3, 32, 32)) # This is now a list of Tensors, each representing a feature map\n```\n\nIn fact, this is much like the method that TorchVision used internally to make many of its detection models. \n\nAlthough this approach solves some of the issues with modifying the source code directly, there are still some major downsides:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "* It\u2019s only really straight-forward to access the outputs of top-level submodules. Dealing with nested submodules rapidly becomes complicated.\n* We have to be careful not to miss any important operations in between the input and the output. We introduce potential for errors in transcribing the exact functionality of the original module to the new module.\n\nOverall, this method and the last both have the complication of tying in feature extraction with the model\u2019s source code itself. Indeed, if we examine the source code for TorchVision models we might suspect that some of the design choices were influenced by the desire to use them in this way for downstream tasks.\n\n### Use hooks\n\nHooks move us away from the paradigm of writing source code, towards one of specifying outputs. Considering our toy CNN example above, and the goal of getting feature maps for each layer, we could use hooks like this:\n\n\n```python\nmodel = CNN(3, 4, 10)", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
{"page_content": "```python\nmodel = CNN(3, 4, 10)\nfeature_maps = [] # This will be a list of Tensors, each representing a feature map\n\ndef hook_feat_map(mod, inp, out):\n\tfeature_maps.append(out)\n\nfor block in model.blocks:\n\tblock.register_forward_hook(hook_feat_map)\n\nout = model(torch.zeros(1, 3, 32, 32)) # This will be the final logits over classes\n```\n\nNow we have full flexibility in terms of accessing nested submodules, and we free ourselves of the responsibilities of fiddling with the source code. But this approach comes with its own downsides:\n\n* We can only apply hooks to modules. If we have functional operations (reshape, view, functional non-linearities, etc) for which we want the outputs, hooks won\u2019t work directly on them.\n* We have not modified anything about the source code, so the whole forward pass is executed, regardless of the hooks. If we only need to access early features without any need for the final output, this could result in a lot of useless computation.\n* Hooks are not TorchScript friendly.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "Here\u2019s a summary of the different methods and their pros/cons:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "| | Can use source code as is without any modifications or rewriting | Full flexibility in accessing features | Drops unnecessary computational steps | TorchScript friendly |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| Modify forward method | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES | \n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| New module that reuses submodules / parameters of original module | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| Hooks | YES | Mostly YES. Only outputs of submodules | NO | NO |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "Table 1: The pros (or cons) of some of the existing methods for feature extraction with PyTorch\n\nIn the next section of this article, let\u2019s see how we can get YES across the board.\n\n\n## FX to The Rescue\n\nThe natural question for some new-starters in Python and coding at this point might be: *\u201cCan\u2019t we just point to a line of code and tell Python or PyTorch that we want the result of that line?\u201d* For those who have spent more time coding, the reason this can\u2019t be done is clear: multiple operations can happen in one line of code, whether they are explicitly written there, or they are implicit as sub-operations. Just take this simple module as an example:\n\n```python\nclass MyModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.param = torch.nn.Parameter(torch.rand(3, 4))\n self.submodule = MySubModule()\n\n def forward(self, x):\n return self.submodule(x + self.param).clamp(min=0.0, max=1.0)\n```\n\nThe forward method has a single line of code which we can unravel as:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "1. Add `self.param` to `x`\n2. Pass x through self.submodule. Here we would need to consider the steps happening in that submodule. I\u2019m just going to use dummy operation names for illustration:\n\tI. submodule.op_1\n\tII. submodule.op_2\n3. Apply the clamp operation\n\nSo even if we point at this one line, the question then is: \u201cFor which step do we want to extract the output?\u201d.\n\n[FX](https://pytorch.org/docs/stable/fx.html) is a core PyTorch toolkit that (oversimplifying) does the unravelling I just mentioned. It does something called \u201csymbolic tracing\u201d, which means the Python code is interpreted and stepped through, operation-by-operation, using some dummy proxy for a real input. Introducing some nomenclature, each step as described above is considered a **\u201cnode\u201d**, and consecutive nodes are connected to one another to form a **\u201cgraph\u201d** (not unlike the common mathematical notion of a graph). Here are the \u201csteps\u201d above translated to this concept of a graph.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "
\n\t
\n\t
\n\t\tFigure 3: Graphical representation of the result of symbolically tracing our example of a simple forward method.\n
\n\nNote that we call this a graph, and not just a set of steps, because it\u2019s possible for the graph to branch off and recombine. Think of the skip connection in a residual block. This would look something like:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "
\n\t
\n\t
\n\t\tFigure 4: Graphical representation of a residual skip connection. The middle node is like the main branch of a residual block, and the final node represents the sum of the input and output of the main branch.\n
\n\nNow, TorchVision\u2019s **[get_graph_node_names](https://pytorch.org/vision/stable/feature_extraction.html#torchvision.models.feature_extraction.get_graph_node_names)** function applies FX as described above, and in the process of doing so, tags each node with a human readable name. Let\u2019s try this with our toy CNN model from the previous section:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "```python\nmodel = CNN(3, 4, 10)\nfrom torchvision.models.feature_extraction import get_graph_node_names\nnodes, _ = get_graph_node_names(model)\nprint(nodes)\n```\nwhich will result in:\n```python\n['x', 'blocks.0.convs.0.0', 'blocks.0.convs.0.1', 'blocks.0.convs.1.0', 'blocks.0.convs.1.1', 'blocks.0.downsample', 'blocks.1.convs.0.0', 'blocks.1.convs.0.1', 'blocks.1.convs.1.0', 'blocks.1.convs.1.1', 'blocks.1.convs.2.0', 'blocks.1.convs.2.1', 'blocks.1.downsample', 'blocks.2.convs.0.0', 'blocks.2.convs.0.1', 'blocks.2.convs.1.0', 'blocks.2.convs.1.1', 'blocks.2.convs.2.0', 'blocks.2.convs.2.1', 'blocks.2.downsample', 'blocks.3.convs.0.0', 'blocks.3.convs.0.1', 'blocks.3.convs.1.0', 'blocks.3.convs.1.1', 'blocks.3.convs.2.0', 'blocks.3.convs.2.1', 'blocks.3.downsample', 'global_pool', 'flatten', 'cls']\n```\n\nWe can read these node names as hierarchically organised \u201caddresses\u201d for the operations of interest. For example 'blocks.1.downsample' refers to the MaxPool2d layer in the second `ConvBlock`.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "[`create_feature_extractor`](https://pytorch.org/vision/stable/feature_extraction.html#torchvision.models.feature_extraction.create_feature_extractor), which is where all the magic happens, goes a few steps further than **`get_graph_node_names`**. It takes desired node names as one of the input arguments, and then uses more FX core functionality to:\n\n1. Assign the desired nodes as outputs.\n2. Prune unnecessary downstream nodes and their associated parameters.\n3. Translate the resulting graph back into Python code.\n4. Return another PyTorch Module to the user. This has the python code from step 3 as the forward method.\n\nAs a demonstration, here\u2019s how we would apply `create_feature_extractor` to get the 4 feature maps from our toy CNN model", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "```python\nfrom torchvision.models.feature_extraction import create_feature_extractor\n# Confused about the node specification here?\n# We are allowed to provide truncated node names, and `create_feature_extractor`\n# will choose the last node with that prefix.\nfeature_extractor = create_feature_extractor(\n\tmodel, return_nodes=['blocks.0', 'blocks.1', 'blocks.2', 'blocks.3'])\n# `out` will be a dict of Tensors, each representing a feature map\nout = feature_extractor(torch.zeros(1, 3, 32, 32))\n```\n\nIt\u2019s as simple as that. When it comes down to it, FX feature extraction is just a way of making it possible to do what some of us would have naively hoped for when we first started programming: *\u201cjust give me the output of this code (*points finger at screen)\u201d*.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "- [ ] \u2026 does not require us to fiddle with source code.\n- [ ] \u2026 provides full flexibility in terms of accessing any intermediate transformation of our inputs, whether they are the results of a module or a functional operation\n- [ ] \u2026 does drop unnecessary computations steps once features have been extracted\n- [ ] \u2026 and I didn\u2019t mention this before, but it\u2019s also TorchScript friendly!\n\nHere\u2019s that table again with another row added for FX feature extraction", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "| | Can use source code as is without any modifications or rewriting | Full flexibility in accessing features | Drops unnecessary computational steps | TorchScript friendly |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| Modify forward method | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES | \n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| New module that reuses submodules / parameters of original module | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| Hooks | YES | Mostly YES. Only outputs of submodules | NO | NO |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| FX | YES | YES | YES | YES |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "Table 2: A copy of Table 1 with an added row for FX feature extraction. FX feature extraction gets YES across the board!\n\n\n## Current FX Limitations\n\nAlthough I would have loved to end the post there, FX does have some of its own limitations which boil down to:\n\n1. There may be some Python code that isn\u2019t yet handled by FX when it comes to the step of interpretation and translation into a graph.\n2. Dynamic control flow can\u2019t be represented in terms of a static graph.\n\nThe easiest thing to do when these problems crop up is to bundle the underlying code into a \u201cleaf node\u201d. Recall the example graph from Figure 3? Conceptually, we may agree that the `submodule` should be treated as a node in itself rather than a set of nodes representing the underlying operations. If we do so, we can redraw the graph as:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "
\n\t
\n\t
\n\t\tFigure 5: The individual operations within `submodule` may (left - within red box), may be consolidated into one node (right - node #2) if we consider the `submodule` as a \"leaf\" node.\n
\n\n\nWe would want to do so if there is some problematic code within the submodule, but we don\u2019t have any need for extracting any intermediate transformations from within it. In practice, this is easily achievable by providing a keyword argument to create_feature_extractor or get_graph_node_names.\n\n\n```python\nmodel = CNN(3, 4, 10)\nnodes, _ = get_graph_node_names(model, tracer_kwargs={'leaf_modules': [ConvBlock]})\nprint(nodes)\n```\n\nfor which the output will be:", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "for which the output will be:\n\n```python\n['x', 'blocks.0', 'blocks.1', 'blocks.2', 'blocks.3', 'global_pool', 'flatten', 'cls']\n```\n\nNotice how, as compared to previously, all the nodes for any given `ConvBlock` are consolidated into a single node.\n\nWe could do something similar with functions. For example, Python\u2019s inbuilt `len` needs to be wrapped and the result should be treated as a leaf node. Here\u2019s how you can do that with core FX functionality:\n\n```python\ntorch.fx.wrap('len')\n\nclass MyModule(nn.Module):\n def forward(self, x):\n x += 1\n len(x)\n\nmodel = MyModule()\nfeature_extractor = create_feature_extractor(model, return_nodes=['add'])\n```\n\nFor functions you define, you may instead use another keyword argument to `create_feature_extractor` (minor detail: here\u2019s[ why you might want to do it this way instead](https://github.com/pytorch/pytorch/issues/62021#issue-950458396)):\n\n\n```python\ndef myfunc(x):\n return len(x)", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "```python\ndef myfunc(x):\n return len(x)\n\nclass MyModule(nn.Module):\n def forward(self, x):\n x += 1\n myfunc(x)\n\nmodel = MyModule()\nfeature_extractor = create_feature_extractor(\n model, return_nodes=['add'], tracer_kwargs={'autowrap_functions': [myfunc]})\n```\n\nNotice that none of the fixes above involved modifying source code.\n\nOf course, there may be times when the very intermediate transformation one is trying to get access to is within the same forward method or function that is causing problems. Here, we can\u2019t just treat that module or function as a leaf node, because then we can\u2019t access the intermediate transformations within. In these cases, some rewriting of the source code will be needed. Here are some examples (not exhaustive)", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "- FX will raise an error when trying to trace through code with an `assert` statement. In this case you may need to remove that assertion or switch it with [`torch._assert`](https://pytorch.org/docs/stable/generated/torch._assert.html) (this is not a public function - so consider it a bandaid and use with caution).\n- Symbolically tracing in-place changes to slices of tensors is not supported. You will need to make a new variable for the slice, apply the operation, then reconstruct the original tensor using concatenation or stacking.\n- Representing dynamic control flow in a static graph is just not logically possible. See if you can distill the coded logic down to something that is not dynamic - see FX documentation for tips.\n\nIn general, you may consult the FX documentation for more detail on the [limitations of symbolic tracing](https://pytorch.org/docs/stable/fx.html#limitations-of-symbolic-tracing) and the possible workarounds.\n\n## Conclusion", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "* Hooks are not TorchScript friendly.\n\nHere\u2019s a summary of the different methods and their pros/cons:\n\n\n| | Can use source code as is without any modifications or rewriting | Full flexibility in accessing features | Drops unnecessary computational steps | TorchScript friendly |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| Modify forward method | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES |", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| New module that reuses submodules / parameters of original module | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "| Hooks | YES | Mostly YES. Only outputs of submodules | NO | NO |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n\nTable 1: The pros (or cons) of some of the existing methods for feature extraction with PyTorch\n\nIn the next section of this article, let\u2019s see how we can get YES across the board.\n\n\n## FX to The Rescue", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "## FX to The Rescue\n\nThe natural question for some new-starters in Python and coding at this point might be: *\u201cCan\u2019t we just point to a line of code and tell Python or PyTorch that we want the result of that line?\u201d* For those who have spent more time coding, the reason this can\u2019t be done is clear: multiple operations can happen in one line of code, whether they are explicitly written there, or they are implicit as sub-operations. Just take this simple module as an example:\n\n```python\nclass MyModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.param = torch.nn.Parameter(torch.rand(3, 4))\n self.submodule = MySubModule()\n\n def forward(self, x):\n return self.submodule(x + self.param).clamp(min=0.0, max=1.0)\n```\n\nThe forward method has a single line of code which we can unravel as:\n\n1. Add `self.param` to `x`", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "1. Add `self.param` to `x`\n2. Pass x through self.submodule. Here we would need to consider the steps happening in that submodule. I\u2019m just going to use dummy operation names for illustration:\n\tI. submodule.op_1\n\tII. submodule.op_2\n3. Apply the clamp operation\n\nSo even if we point at this one line, the question then is: \u201cFor which step do we want to extract the output?\u201d.\n\n[FX](https://pytorch.org/docs/stable/fx.html) is a core PyTorch toolkit that (oversimplifying) does the unravelling I just mentioned. It does something called \u201csymbolic tracing\u201d, which means the Python code is interpreted and stepped through, operation-by-operation, using some dummy proxy for a real input. Introducing some nomenclature, each step as described above is considered a **\u201cnode\u201d**, and consecutive nodes are connected to one another to form a **\u201cgraph\u201d** (not unlike the common mathematical notion of a graph). Here are the \u201csteps\u201d above translated to this concept of a graph.\n\n
", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "
\n\t
\n\t
\n\t\tFigure 3: Graphical representation of the result of symbolically tracing our example of a simple forward method.\n
\n\nNote that we call this a graph, and not just a set of steps, because it\u2019s possible for the graph to branch off and recombine. Think of the skip connection in a residual block. This would look something like:\n\n
\n\t
\n\t
", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "
\n\t\tFigure 4: Graphical representation of a residual skip connection. The middle node is like the main branch of a residual block, and the final node represents the sum of the input and output of the main branch.\n
\n\nNow, TorchVision\u2019s **[get_graph_node_names](https://pytorch.org/vision/stable/feature_extraction.html#torchvision.models.feature_extraction.get_graph_node_names)** function applies FX as described above, and in the process of doing so, tags each node with a human readable name. Let\u2019s try this with our toy CNN model from the previous section:\n\n```python\nmodel = CNN(3, 4, 10)\nfrom torchvision.models.feature_extraction import get_graph_node_names\nnodes, _ = get_graph_node_names(model)\nprint(nodes)\n```\nwhich will result in:\n```python", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "print(nodes)\n```\nwhich will result in:\n```python\n['x', 'blocks.0.convs.0.0', 'blocks.0.convs.0.1', 'blocks.0.convs.1.0', 'blocks.0.convs.1.1', 'blocks.0.downsample', 'blocks.1.convs.0.0', 'blocks.1.convs.0.1', 'blocks.1.convs.1.0', 'blocks.1.convs.1.1', 'blocks.1.convs.2.0', 'blocks.1.convs.2.1', 'blocks.1.downsample', 'blocks.2.convs.0.0', 'blocks.2.convs.0.1', 'blocks.2.convs.1.0', 'blocks.2.convs.1.1', 'blocks.2.convs.2.0', 'blocks.2.convs.2.1', 'blocks.2.downsample', 'blocks.3.convs.0.0', 'blocks.3.convs.0.1', 'blocks.3.convs.1.0', 'blocks.3.convs.1.1', 'blocks.3.convs.2.0', 'blocks.3.convs.2.1', 'blocks.3.downsample', 'global_pool', 'flatten', 'cls']\n```\n\nWe can read these node names as hierarchically organised \u201caddresses\u201d for the operations of interest. For example 'blocks.1.downsample' refers to the MaxPool2d layer in the second `ConvBlock`.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "[`create_feature_extractor`](https://pytorch.org/vision/stable/feature_extraction.html#torchvision.models.feature_extraction.create_feature_extractor), which is where all the magic happens, goes a few steps further than **`get_graph_node_names`**. It takes desired node names as one of the input arguments, and then uses more FX core functionality to:\n\n1. Assign the desired nodes as outputs.\n2. Prune unnecessary downstream nodes and their associated parameters.\n3. Translate the resulting graph back into Python code.\n4. Return another PyTorch Module to the user. This has the python code from step 3 as the forward method.\n\nAs a demonstration, here\u2019s how we would apply `create_feature_extractor` to get the 4 feature maps from our toy CNN model\n\n```python\nfrom torchvision.models.feature_extraction import create_feature_extractor\n# Confused about the node specification here?\n# We are allowed to provide truncated node names, and `create_feature_extractor`\n# will choose the last node with that prefix.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "# will choose the last node with that prefix.\nfeature_extractor = create_feature_extractor(\n\tmodel, return_nodes=['blocks.0', 'blocks.1', 'blocks.2', 'blocks.3'])\n# `out` will be a dict of Tensors, each representing a feature map\nout = feature_extractor(torch.zeros(1, 3, 32, 32))\n```\n\nIt\u2019s as simple as that. When it comes down to it, FX feature extraction is just a way of making it possible to do what some of us would have naively hoped for when we first started programming: *\u201cjust give me the output of this code (*points finger at screen)\u201d*.\n\n- [ ] \u2026 does not require us to fiddle with source code.\n- [ ] \u2026 provides full flexibility in terms of accessing any intermediate transformation of our inputs, whether they are the results of a module or a functional operation\n- [ ] \u2026 does drop unnecessary computations steps once features have been extracted\n- [ ] \u2026 and I didn\u2019t mention this before, but it\u2019s also TorchScript friendly!\n\nHere\u2019s that table again with another row added for FX feature extraction", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "| | Can use source code as is without any modifications or rewriting | Full flexibility in accessing features | Drops unnecessary computational steps | TorchScript friendly |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| Modify forward method | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES |", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| New module that reuses submodules / parameters of original module | NO | Technically yes. Depends on how much code you\u2019re willing to write. So in practice, NO. | YES | YES |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "| Hooks | YES | Mostly YES. Only outputs of submodules | NO | NO |\n|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n| FX | YES | YES | YES | YES |", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "|-------------------------------------------------------------------|:-----------------------------------------------------------------:|:--------------------------------------------------------------------------------------:|:--------------------------------------:|:--------------------:|\n\nTable 2: A copy of Table 1 with an added row for FX feature extraction. FX feature extraction gets YES across the board!\n\n\n## Current FX Limitations\n\nAlthough I would have loved to end the post there, FX does have some of its own limitations which boil down to:\n\n1. There may be some Python code that isn\u2019t yet handled by FX when it comes to the step of interpretation and translation into a graph.\n2. Dynamic control flow can\u2019t be represented in terms of a static graph.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "The easiest thing to do when these problems crop up is to bundle the underlying code into a \u201cleaf node\u201d. Recall the example graph from Figure 3? Conceptually, we may agree that the `submodule` should be treated as a node in itself rather than a set of nodes representing the underlying operations. If we do so, we can redraw the graph as:\n\n
\n\t
\n\t
\n\t\tFigure 5: The individual operations within `submodule` may (left - within red box), may be consolidated into one node (right - node #2) if we consider the `submodule` as a \"leaf\" node.\n
", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "\n\n\nWe would want to do so if there is some problematic code within the submodule, but we don\u2019t have any need for extracting any intermediate transformations from within it. In practice, this is easily achievable by providing a keyword argument to create_feature_extractor or get_graph_node_names.\n\n\n```python\nmodel = CNN(3, 4, 10)\nnodes, _ = get_graph_node_names(model, tracer_kwargs={'leaf_modules': [ConvBlock]})\nprint(nodes)\n```\n\nfor which the output will be:\n\n```python\n['x', 'blocks.0', 'blocks.1', 'blocks.2', 'blocks.3', 'global_pool', 'flatten', 'cls']\n```\n\nNotice how, as compared to previously, all the nodes for any given `ConvBlock` are consolidated into a single node.\n\nWe could do something similar with functions. For example, Python\u2019s inbuilt `len` needs to be wrapped and the result should be treated as a leaf node. Here\u2019s how you can do that with core FX functionality:\n\n```python\ntorch.fx.wrap('len')\n\nclass MyModule(nn.Module):\n def forward(self, x):\n x += 1\n len(x)", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "x += 1\n len(x)\n\nmodel = MyModule()\nfeature_extractor = create_feature_extractor(model, return_nodes=['add'])\n```\n\nFor functions you define, you may instead use another keyword argument to `create_feature_extractor` (minor detail: here\u2019s[ why you might want to do it this way instead](https://github.com/pytorch/pytorch/issues/62021#issue-950458396)):\n\n\n```python\ndef myfunc(x):\n return len(x)\n\nclass MyModule(nn.Module):\n def forward(self, x):\n x += 1\n myfunc(x)\n\nmodel = MyModule()\nfeature_extractor = create_feature_extractor(\n model, return_nodes=['add'], tracer_kwargs={'autowrap_functions': [myfunc]})\n```\n\nNotice that none of the fixes above involved modifying source code.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "Of course, there may be times when the very intermediate transformation one is trying to get access to is within the same forward method or function that is causing problems. Here, we can\u2019t just treat that module or function as a leaf node, because then we can\u2019t access the intermediate transformations within. In these cases, some rewriting of the source code will be needed. Here are some examples (not exhaustive)\n\n- FX will raise an error when trying to trace through code with an `assert` statement. In this case you may need to remove that assertion or switch it with [`torch._assert`](https://pytorch.org/docs/stable/generated/torch._assert.html) (this is not a public function - so consider it a bandaid and use with caution).\n- Symbolically tracing in-place changes to slices of tensors is not supported. You will need to make a new variable for the slice, apply the operation, then reconstruct the original tensor using concatenation or stacking.", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
+{"page_content": "- Representing dynamic control flow in a static graph is just not logically possible. See if you can distill the coded logic down to something that is not dynamic - see FX documentation for tips.\n\nIn general, you may consult the FX documentation for more detail on the [limitations of symbolic tracing](https://pytorch.org/docs/stable/fx.html#limitations-of-symbolic-tracing) and the possible workarounds.\n\n## Conclusion", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
{"page_content": "## Conclusion\n\nWe did a quick recap on feature extraction and why one might want to do it. Although there are existing methods for doing feature extraction in PyTorch they all have rather significant shortcomings. We learned how TorchVision\u2019s FX feature extraction utility works and what makes it so versatile compared to the existing methods. While there are still some minor kinks to iron out for the latter, we understand the limitations, and can trade them off against the limitations of other methods depending on our use case. Hopefully by adding this new utility to your PyTorch toolkit, you\u2019re now equipped to handle the vast majority of feature extraction requirements you may come across.\n\nHappy coding!", "metadata": {"source": "https://pytorch.org/blog/FX-feature-extraction-torchvision/", "category": "pytorch blogs"}}
-{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch Ecosystem Day 2021 Recap and New Contributor Resources'\nauthor: Team PyTorch\n---\n\nThank you to our incredible community for making the first ever PyTorch Ecosystem Day a success! The day was filled with discussions on new developments, trends and challenges showcased through 71 posters, 32 breakout sessions and 6 keynote speakers. \n\n
\n

\n
\n\nSpecial thanks to our keynote speakers: Piotr Bialecki, Ritchie Ng, Miquel Farr\u00e9, Joe Spisak, Geeta Chauhan, and Suraj Subramanian who shared updates from the latest release of PyTorch, exciting work being done with partners, use case example from Disney, the growth and development of the PyTorch community in Asia Pacific, and latest contributor highlights.", "metadata": {"source": "https://pytorch.org/blog/ecosystem-day-2021-recap/", "category": "pytorch blogs"}}
-{"page_content": "If you missed the opening talks, you rewatch them here:\n* [Morning/EMEA Opening Talks](https://www.youtube.com/watch?v=MYE01-XaSZA)\n* [Evening/APAC Opening Talks](https://www.youtube.com/watch?v=CjU_6OaYKpw)\n\nIn addition to the talks, we had 71 posters covering various topics such as multimodal, NLP, compiler, distributed training, researcher productivity tools, AI accelerators, and more. From the event, it was clear that an underlying thread that ties all of these different projects together is the cross-collaboration of the PyTorch community. Thank you for continuing to push the state of the art with PyTorch! \n\nTo view the full catalogue of poster, please visit **[PyTorch Ecosystem Day 2021 Event Page](https://pytorch.org/ecosystem/pted/2021)**.", "metadata": {"source": "https://pytorch.org/blog/ecosystem-day-2021-recap/", "category": "pytorch blogs"}}
-{"page_content": "### New Contributor Resources \nToday, we are also sharing new contributor resources that we are trying out to give you the most access to up-to-date news, networking opportunities and more. \n* [Contributor Newsletter](https://pytorch.org/resources/contributors/) - Includes curated news including RFCs, feature roadmaps, notable PRs, editorials from developers, and more to support keeping track of everything that\u2019s happening in our community. \n* [Contributors Discussion Forum](https://dev-discuss.pytorch.org/) - Designed for contributors to learn and collaborate on the latest development across PyTorch. \n* [PyTorch Developer Podcast (Beta)](https://pytorch-dev-podcast.simplecast.com/) - Edward Yang, PyTorch Research Scientist, at Facebook AI shares bite-sized (10 to 20 mins) podcast episodes discussing topics about all sorts of internal development topics in PyTorch.\n\nThank you,\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/ecosystem-day-2021-recap/", "category": "pytorch blogs"}}
+{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch Ecosystem Day 2021 Recap and New Contributor Resources'\nauthor: Team PyTorch\n---\n\nThank you to our incredible community for making the first ever PyTorch Ecosystem Day a success! The day was filled with discussions on new developments, trends and challenges showcased through 71 posters, 32 breakout sessions and 6 keynote speakers. \n\n
\n

\n
\n\nSpecial thanks to our keynote speakers: Piotr Bialecki, Ritchie Ng, Miquel Farr\u00e9, Joe Spisak, Geeta Chauhan, and Suraj Subramanian who shared updates from the latest release of PyTorch, exciting work being done with partners, use case example from Disney, the growth and development of the PyTorch community in Asia Pacific, and latest contributor highlights.\n\nIf you missed the opening talks, you rewatch them here:\n* [Morning/EMEA Opening Talks](https://www.youtube.com/watch?v=MYE01-XaSZA)", "metadata": {"source": "https://pytorch.org/blog/ecosystem-day-2021-recap/", "category": "pytorch blogs"}}
+{"page_content": "* [Evening/APAC Opening Talks](https://www.youtube.com/watch?v=CjU_6OaYKpw)\n\nIn addition to the talks, we had 71 posters covering various topics such as multimodal, NLP, compiler, distributed training, researcher productivity tools, AI accelerators, and more. From the event, it was clear that an underlying thread that ties all of these different projects together is the cross-collaboration of the PyTorch community. Thank you for continuing to push the state of the art with PyTorch! \n\nTo view the full catalogue of poster, please visit **[PyTorch Ecosystem Day 2021 Event Page](https://pytorch.org/ecosystem/pted/2021)**. \n\n### New Contributor Resources \nToday, we are also sharing new contributor resources that we are trying out to give you the most access to up-to-date news, networking opportunities and more.", "metadata": {"source": "https://pytorch.org/blog/ecosystem-day-2021-recap/", "category": "pytorch blogs"}}
+{"page_content": "* [Contributor Newsletter](https://pytorch.org/resources/contributors/) - Includes curated news including RFCs, feature roadmaps, notable PRs, editorials from developers, and more to support keeping track of everything that\u2019s happening in our community. \n* [Contributors Discussion Forum](https://dev-discuss.pytorch.org/) - Designed for contributors to learn and collaborate on the latest development across PyTorch. \n* [PyTorch Developer Podcast (Beta)](https://pytorch-dev-podcast.simplecast.com/) - Edward Yang, PyTorch Research Scientist, at Facebook AI shares bite-sized (10 to 20 mins) podcast episodes discussing topics about all sorts of internal development topics in PyTorch.\n\nThank you,\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/ecosystem-day-2021-recap/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Geospatial deep learning with TorchGeo\"\nauthor: Adam Stewart (University of Illinois at Urbana-Champaign), Caleb Robinson (Microsoft AI for Good Research Lab), Isaac Corley (University of Texas at San Antonio)\nfeatured-img: 'assets/images/torchgeo-hurricane.jpg'\n---\n\nTorchGeo is a PyTorch domain library providing datasets, samplers, transforms, and pre-trained models specific to geospatial data.\n\n
\n
\n
\n\n
\n https://github.com/microsoft/torchgeo\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "For decades, Earth observation satellites, aircraft, and more recently UAV platforms have been collecting increasing amounts of imagery of the Earth\u2019s surface. With information about seasonal and long-term trends, remotely sensed imagery can be invaluable for solving some of the greatest challenges to humanity, including climate change adaptation, natural disaster monitoring, water resource management, and food security for a growing global population. From a computer vision perspective, this includes applications like land cover mapping (semantic segmentation), deforestation and flood monitoring (change detection), glacial flow (pixel tracking), hurricane tracking and intensity estimation (regression), and building and road detection (object detection, instance segmentation). By leveraging recent advancements in deep learning architectures, cheaper and more powerful GPUs, and petabytes of freely available satellite imagery datasets, we can come closer to solving these important problems.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "\n\nFor decades, Earth observation satellites, aircraft, and more recently UAV platforms have been collecting increasing amounts of imagery of the Earth\u2019s surface. With information about seasonal and long-term trends, remotely sensed imagery can be invaluable for solving some of the greatest challenges to humanity, including climate change adaptation, natural disaster monitoring, water resource management, and food security for a growing global population. From a computer vision perspective, this includes applications like land cover mapping (semantic segmentation), deforestation and flood monitoring (change detection), glacial flow (pixel tracking), hurricane tracking and intensity estimation (regression), and building and road detection (object detection, instance segmentation). By leveraging recent advancements in deep learning architectures, cheaper and more powerful GPUs, and petabytes of freely available satellite imagery datasets, we can come closer to solving these important problems.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\n\n
\nNational Oceanic and Atmospheric Administration satellite image of Hurricane Katrina, taken on August 28, 2005 (source). Geospatial machine learning libraries like TorchGeo can be used to detect, track, and predict future trajectories of hurricanes and other natural disasters.\n
\n\n# The challenges", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "In traditional computer vision datasets, such as ImageNet, the image files themselves tend to be rather simple and easy to work with. Most images have 3 spectral bands (RGB), are stored in common file formats like PNG or JPEG, and can be easily loaded with popular software libraries like [PIL](https://pillow.readthedocs.io/en/stable/) or [OpenCV](https://opencv.org/). Each image in these datasets is usually small enough to pass directly into a neural network. Furthermore, most of these datasets contain a finite number of well-curated images that are assumed to be independent and identically distributed, making train-val-test splits straightforward. As a result of this relative homogeneity, the same pre-trained models (e.g., CNNs pretrained on ImageNet) have shown to be effective across a wide range of vision tasks using transfer learning methods. Existing libraries, such as [torchvision](https://github.com/pytorch/vision), handle these simple cases well, and have been used to make large advances in vision tasks over the past decade.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "Remote sensing imagery is not so uniform. Instead of simple RGB images, satellites tend to capture images that are multispectral ([Landsat 8](https://www.usgs.gov/landsat-missions) has 11 spectral bands) or even hyperspectral ([Hyperion](https://www.usgs.gov/centers/eros/science/usgs-eros-archive-earth-observing-one-eo-1-hyperion) has 242 spectral bands). These images capture information at a wider range of wavelengths (400 nm\u201315 \u00b5m), far outside of the visible spectrum. Different satellites also have very different spatial resolutions\u2014[GOES](https://www.goes.noaa.gov/) has a resolution of 4 km/px, [Maxar](https://www.maxar.com/products/satellite-imagery) imagery is 30 cm/px, and drone imagery resolution can be as high as 7 mm/px. These datasets almost always have a temporal component, with satellite revisists that are daily, weekly, or biweekly. Images often have overlap with other images in the dataset, and need to be stitched together based on geographic metadata. These images tend to be very large (e.g., 10K x 10K pixels), so it isn't possible to pass an entire image through a neural network. This data is distributed in hundreds of different raster and vector file formats like GeoTIFF and ESRI Shapefile, requiring specialty libraries like [GDAL](https://gdal.org/) to load.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\n\n\n
\nFrom left to right: Mercator, Albers Equal Area, and Interrupted Goode Homolosine projections (source). Geospatial data is associated with one of many different types of reference systems that project the 3D Earth onto a 2D representation. Combining data from different sources often involves re-projecting to a common reference system in order to ensure that all layers are aligned.\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "Although each image is 2D, the Earth itself is 3D. In order to stitch together images, they first need to be projected onto a 2D representation of the Earth, called a coordinate reference system (CRS). Most people are familiar with equal angle representations like Mercator that distort the size of regions (Greenland looks larger than Africa even though Africa is 15x larger), but there are many other CRSs that are commonly used. Each dataset may use a different CRS, and each image within a single dataset may also be in a unique CRS. In order to use data from multiple layers, they must all share a common CRS, otherwise the data won't be properly aligned. For those who aren't familiar with remote sensing data, this can be a daunting task.\n\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "
\nEven if you correctly georeference images during indexing, if you don't project them to a common CRS, you'll end up with rotated images with nodata values around them, and the images won't be pixel-aligned.\n
\n\n# The solution\n\nAt the moment, it can be quite challenging to work with both deep learning models and geospatial data without having expertise in both of these very different fields. To address these challenges, we've built TorchGeo, a PyTorch domain library for working with geospatial data. TorchGeo is designed to make it simple:\n\n1. for machine learning experts to work with geospatial data, and\n2. for remote sensing experts to explore machine learning solutions.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "TorchGeo is not just a research project, but a production-quality library that uses continuous integration to test every commit with a range of Python versions on a range of platforms (Linux, macOS, Windows). It can be easily installed with any of your favorite package managers, including pip, conda, and [spack](https://spack.io):\n\n```\n$ pip install torchgeo\n```\n\nTorchGeo is designed to have the same API as other PyTorch domain libraries like torchvision, torchtext, and torchaudio. If you already use torchvision in your workflow for computer vision datasets, you can switch to TorchGeo by changing only a few lines of code. All TorchGeo datasets and samplers are compatible with the PyTorch ``DataLoader`` class, meaning that you can take advantage of wrapper libraries like [PyTorch Lightning](https://www.pytorchlightning.ai/) for distributed training. In the following sections, we'll explore possible use cases for TorchGeo to show how simple it is to use.\n\n# Geospatial datasets and samplers", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "# Geospatial datasets and samplers\n\n
\n
\n
\n\n
\nExample application in which we combine A) a scene from Landsat 8 and B) Cropland Data Layer labels, even though these files are in different EPSG projections. We want to sample patches C) and D) from these datasets using a geospatial bounding box as an index.\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "Many remote sensing applications involve working with [*geospatial datasets*](https://torchgeo.readthedocs.io/en/latest/api/datasets.html#geospatial-datasets) \u2014datasets with geographic metadata. In TorchGeo, we define a ``GeoDataset`` class to represent these kinds of datasets. Instead of being indexed by an integer, each ``GeoDataset`` is indexed by a spatiotemporal bounding box, meaning that two or more datasets covering a different geographic extent can be intelligently combined.\n\nIn this example, we show how easy it is to work with geospatial data and to sample small image patches from a combination of Landsat and Cropland Data Layer (CDL) data using TorchGeo. First, we assume that the user has Landsat 7 and 8 imagery downloaded. Since Landsat 8 has more spectral bands than Landsat 7, we'll only use the bands that both satellites have in common. We'll create a single dataset including all images from both Landsat 7 and 8 data by taking the union between these two datasets.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "```c++\nfrom torch.utils.data import DataLoader\nfrom torchgeo.datasets import CDL, Landsat7, Landsat8, stack_samples\nfrom torchgeo.samplers import RandomGeoSampler\n\nlandsat7 = Landsat7(root=\"...\")\nlandsat8 = Landsat8(root=\"...\", bands=Landsat8.all_bands[1:-2])\nlandsat = landsat7 | landsat8\n```\n\nNext, we take the intersection between this dataset and the CDL dataset. We want to take the intersection instead of the union to ensure that we only sample from regions where we have both Landsat and CDL data. Note that we can automatically download and checksum CDL data. Also note that each of these datasets may contain files in different CRSs or resolutions, but TorchGeo automatically ensures that a matching CRS and resolution is used.\n\n```c++\ncdl = CDL(root=\"...\", download=True, checksum=True)\ndataset = landsat & cdl\n```", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "This dataset can now be used with a PyTorch data loader. Unlike benchmark datasets, geospatial datasets often include very large images. For example, the CDL dataset consists of a single image covering the entire contiguous United States. In order to sample from these datasets using geospatial coordinates, TorchGeo defines a number of [*samplers*](https://torchgeo.readthedocs.io/en/latest/api/samplers.html). In this example, we'll use a random sampler that returns 256 x 256 pixel images and 10,000 samples per epoch. We'll also use a custom collation function to combine each sample dictionary into a mini-batch of samples.\n\n```c++\nsampler = RandomGeoSampler(dataset, size=256, length=10000)\ndataloader = DataLoader(dataset, batch_size=128, sampler=sampler, collate_fn=stack_samples)\n```\n\nThis data loader can now be used in your normal training/evaluation pipeline.\n\n```c++\nfor batch in dataloader:\n image = batch[\"image\"]\n mask = batch[\"mask\"]", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "# train a model, or make predictions using a pre-trained model\n```\n\nMany applications involve intelligently composing datasets based on geospatial metadata like this. For example, users may want to:\n\n- Combine datasets for multiple image sources and treat them as equivalent (e.g., Landsat 7 and 8)\n- Combine datasets for disparate geospatial locations (e.g., Chesapeake NY and PA)\n\nThese combinations require that all queries are present in *at least one* dataset, and can be created using a ``UnionDataset``. Similarly, users may want to:\n\n- Combine image and target labels and sample from both simultaneously (e.g., Landsat and CDL)\n- Combine datasets for multiple image sources for multimodal learning or data fusion (e.g., Landsat and Sentinel)\n\nThese combinations require that all queries are present in *both* datasets, and can be created using an ``IntersectionDataset``. TorchGeo automatically composes these datasets for you when you use the intersection (``&``) and union \\(``|``\\) operators.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "# Multispectral and geospatial transforms\n\nIn deep learning, it's common to augment and transform the data so that models are robust to variations in the input space. Geospatial data can have variations such as seasonal changes and warping effects, as well as image processing and capture issues like cloud cover and atmospheric distortion. TorchGeo utilizes augmentations and transforms from the [Kornia](https://kornia.github.io/) library, which supports GPU acceleration and supports multispectral imagery with more than 3 channels.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "\n\nAlthough each image is 2D, the Earth itself is 3D. In order to stitch together images, they first need to be projected onto a 2D representation of the Earth, called a coordinate reference system (CRS). Most people are familiar with equal angle representations like Mercator that distort the size of regions (Greenland looks larger than Africa even though Africa is 15x larger), but there are many other CRSs that are commonly used. Each dataset may use a different CRS, and each image within a single dataset may also be in a unique CRS. In order to use data from multiple layers, they must all share a common CRS, otherwise the data won't be properly aligned. For those who aren't familiar with remote sensing data, this can be a daunting task.\n\n
\n
\n
\n\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n
\nEven if you correctly georeference images during indexing, if you don't project them to a common CRS, you'll end up with rotated images with nodata values around them, and the images won't be pixel-aligned.\n
\n\n# The solution\n\nAt the moment, it can be quite challenging to work with both deep learning models and geospatial data without having expertise in both of these very different fields. To address these challenges, we've built TorchGeo, a PyTorch domain library for working with geospatial data. TorchGeo is designed to make it simple:\n\n1. for machine learning experts to work with geospatial data, and\n2. for remote sensing experts to explore machine learning solutions.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "TorchGeo is not just a research project, but a production-quality library that uses continuous integration to test every commit with a range of Python versions on a range of platforms (Linux, macOS, Windows). It can be easily installed with any of your favorite package managers, including pip, conda, and [spack](https://spack.io):\n\n```\n$ pip install torchgeo\n```\n\nTorchGeo is designed to have the same API as other PyTorch domain libraries like torchvision, torchtext, and torchaudio. If you already use torchvision in your workflow for computer vision datasets, you can switch to TorchGeo by changing only a few lines of code. All TorchGeo datasets and samplers are compatible with the PyTorch ``DataLoader`` class, meaning that you can take advantage of wrapper libraries like [PyTorch Lightning](https://www.pytorchlightning.ai/) for distributed training. In the following sections, we'll explore possible use cases for TorchGeo to show how simple it is to use.\n\n# Geospatial datasets and samplers\n\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "
\n
\n
\n\n
\nExample application in which we combine A) a scene from Landsat 8 and B) Cropland Data Layer labels, even though these files are in different EPSG projections. We want to sample patches C) and D) from these datasets using a geospatial bounding box as an index.\n
\n\nMany remote sensing applications involve working with [*geospatial datasets*](https://torchgeo.readthedocs.io/en/latest/api/datasets.html#geospatial-datasets) \u2014datasets with geographic metadata. In TorchGeo, we define a ``GeoDataset`` class to represent these kinds of datasets. Instead of being indexed by an integer, each ``GeoDataset`` is indexed by a spatiotemporal bounding box, meaning that two or more datasets covering a different geographic extent can be intelligently combined.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "In this example, we show how easy it is to work with geospatial data and to sample small image patches from a combination of Landsat and Cropland Data Layer (CDL) data using TorchGeo. First, we assume that the user has Landsat 7 and 8 imagery downloaded. Since Landsat 8 has more spectral bands than Landsat 7, we'll only use the bands that both satellites have in common. We'll create a single dataset including all images from both Landsat 7 and 8 data by taking the union between these two datasets.\n\n```c++\nfrom torch.utils.data import DataLoader\nfrom torchgeo.datasets import CDL, Landsat7, Landsat8, stack_samples\nfrom torchgeo.samplers import RandomGeoSampler\n\nlandsat7 = Landsat7(root=\"...\")\nlandsat8 = Landsat8(root=\"...\", bands=Landsat8.all_bands[1:-2])\nlandsat = landsat7 | landsat8\n```", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "landsat = landsat7 | landsat8\n```\n\nNext, we take the intersection between this dataset and the CDL dataset. We want to take the intersection instead of the union to ensure that we only sample from regions where we have both Landsat and CDL data. Note that we can automatically download and checksum CDL data. Also note that each of these datasets may contain files in different CRSs or resolutions, but TorchGeo automatically ensures that a matching CRS and resolution is used.\n\n```c++\ncdl = CDL(root=\"...\", download=True, checksum=True)\ndataset = landsat & cdl\n```", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "dataset = landsat & cdl\n```\n\nThis dataset can now be used with a PyTorch data loader. Unlike benchmark datasets, geospatial datasets often include very large images. For example, the CDL dataset consists of a single image covering the entire contiguous United States. In order to sample from these datasets using geospatial coordinates, TorchGeo defines a number of [*samplers*](https://torchgeo.readthedocs.io/en/latest/api/samplers.html). In this example, we'll use a random sampler that returns 256 x 256 pixel images and 10,000 samples per epoch. We'll also use a custom collation function to combine each sample dictionary into a mini-batch of samples.\n\n```c++\nsampler = RandomGeoSampler(dataset, size=256, length=10000)\ndataloader = DataLoader(dataset, batch_size=128, sampler=sampler, collate_fn=stack_samples)\n```\n\nThis data loader can now be used in your normal training/evaluation pipeline.\n\n```c++\nfor batch in dataloader:\n image = batch[\"image\"]\n mask = batch[\"mask\"]", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "mask = batch[\"mask\"]\n\n # train a model, or make predictions using a pre-trained model\n```\n\nMany applications involve intelligently composing datasets based on geospatial metadata like this. For example, users may want to:\n\n- Combine datasets for multiple image sources and treat them as equivalent (e.g., Landsat 7 and 8)\n- Combine datasets for disparate geospatial locations (e.g., Chesapeake NY and PA)\n\nThese combinations require that all queries are present in *at least one* dataset, and can be created using a ``UnionDataset``. Similarly, users may want to:\n\n- Combine image and target labels and sample from both simultaneously (e.g., Landsat and CDL)\n- Combine datasets for multiple image sources for multimodal learning or data fusion (e.g., Landsat and Sentinel)", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "These combinations require that all queries are present in *both* datasets, and can be created using an ``IntersectionDataset``. TorchGeo automatically composes these datasets for you when you use the intersection (``&``) and union \\(``|``\\) operators.\n\n# Multispectral and geospatial transforms\n\nIn deep learning, it's common to augment and transform the data so that models are robust to variations in the input space. Geospatial data can have variations such as seasonal changes and warping effects, as well as image processing and capture issues like cloud cover and atmospheric distortion. TorchGeo utilizes augmentations and transforms from the [Kornia](https://kornia.github.io/) library, which supports GPU acceleration and supports multispectral imagery with more than 3 channels.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "Traditional geospatial analyses compute and visualize spectral indices which are combinations of multispectral bands. Spectral indices are designed to highlight areas of interest in a multispectral image relevant to some application, such as vegetation health, areas of man-made change or increasing urbanization, or snow cover. TorchGeo supports numerous [*transforms*](https://torchgeo.readthedocs.io/en/latest/api/transforms.html), which can compute common spectral indices and append them as additional bands to a multispectral image tensor.\n\nBelow, we show a simple example where we compute the Normalized Difference Vegetation Index (NDVI) on a Sentinel-2 image. NDVI measures the presence of vegetation and vegetation health and is computed as the normalized difference between the red and near-infrared (NIR) spectral bands. Spectral index transforms operate on sample dictionaries returned from TorchGeo datasets and append the resulting spectral index to the image channel dimension.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "First, we instantiate a Sentinel-2 dataset and load a sample image. Then, we plot the true color (RGB) representation of this data to see the region we are looking at.\n\n```c++\nimport matplotlib.pyplot as plt\nfrom torchgeo.datasets import Sentinel2\nfrom torchgeo.transforms import AppendNDVI\n\ndataset = Sentinel2(root=\"...\")\nsample = dataset[...]\nfig = dataset.plot(sample)\nplt.show()\n```\n\nNext, we instantiate and compute an NDVI transform, appending this new channel to the end of the image. Sentinel-2 imagery uses index 0 for its red band and index 3 for its NIR band. In order to visualize the data, we also normalize the image. NDVI values can range from -1 to 1, but we want to use the range 0 to 1 for plotting.\n\n```c++\ntransform = AppendNDVI(index_red=0, index_nir=3)\nsample = transform(sample)\nsample[\"image\"][-1] = (sample[\"image\"][-1] + 1) / 2\nplt.imshow(sample[\"image\"][-1], cmap=\"RdYlGn_r\")\nplt.show()\n```\n\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "
\nTrue color (left) and NDVI (right) of the Texas Hill Region, taken on November 16, 2018 by the Sentinel-2 satellite. In the NDVI image, red indicates water bodies, yellow indicates barren soil, light green indicates unhealthy vegetation, and dark green indicates healthy vegetation.\n
\n\n# Benchmark datasets\n\nOne of the driving factors behind progress in computer vision is the existence of standardized benchmark datasets like ImageNet and MNIST. Using these datasets, researchers can directly compare the performance of different models and training procedures to determine which perform the best. In the remote sensing domain, there are many such datasets, but due to the aforementioned difficulties of working with this data and the lack of existing libraries for loading these datasets, many researchers opt to use their own custom datasets.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "One of the goals of TorchGeo is to provide easy-to-use data loaders for these existing datasets. TorchGeo includes a number of [*benchmark datasets*](https://torchgeo.readthedocs.io/en/latest/api/datasets.html#non-geospatial-datasets) \u2014datasets that include both input images and target labels. This includes datasets for tasks like image classification, regression, semantic segmentation, object detection, instance segmentation, change detection, and more.\n\nIf you've used torchvision before, these types of datasets should be familiar. In this example, we'll create a dataset for the Northwestern Polytechnical University (NWPU) very-high-resolution ten-class (VHR-10) geospatial object detection dataset. This dataset can be automatically downloaded, checksummed, and extracted, just like with torchvision.\n\n```c++\nfrom torch.utils.data import DataLoader\nfrom torchgeo.datasets import VHR10", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "dataset = VHR10(root=\"...\", download=True, checksum=True)\ndataloader = DataLoader(dataset, batch_size=128, shuffle=True, num_workers=4)\n\nfor batch in dataloader:\n image = batch[\"image\"]\n label = batch[\"label\"]\n\n # train a model, or make predictions using a pre-trained model\n```\n\nAll TorchGeo datasets are compatible with PyTorch data loaders, making them easy to integrate into existing training workflows. The only difference between a benchmark dataset in TorchGeo and a similar dataset in torchvision is that each dataset returns a dictionary with keys for each PyTorch ``Tensor``.\n\n
\n
\n
\n\n
\nExample predictions from a Mask R-CNN model trained on the NWPU VHR-10 dataset. The model predicts sharp bounding boxes and masks for all objects with high confidence scores.\n
\n\n# Reproducibility with PyTorch Lightning", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "# Reproducibility with PyTorch Lightning\n\nAnother key goal of TorchGeo is reproducibility. For many of these benchmark datasets, there is no predefined train-val-test split, or the predefined split has issues with class imbalance or geographic distribution. As a result, the performance metrics reported in the literature either can't be reproduced, or aren't indicative of how well a pre-trained model would work in a different geographic location.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "In order to facilitate direct comparisons between results published in the literature and further reduce the boilerplate code needed to run experiments with datasets in TorchGeo, we have created PyTorch Lightning [*datamodules*](https://torchgeo.readthedocs.io/en/latest/api/datamodules.html) with well-defined train-val-test splits and [*trainers*](https://torchgeo.readthedocs.io/en/latest/api/trainers.html) for various tasks like classification, regression, and semantic segmentation. These datamodules show how to incorporate augmentations from the kornia library, include preprocessing transforms (with pre-calculated channel statistics), and let users easily experiment with hyperparameters related to the data itself (as opposed to the modeling process). Training a semantic segmentation model on the Inria Aerial Image Labeling dataset is as easy as a few imports and four lines of code.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "```c++\nfrom pytorch_lightning import Trainer\nfrom torchgeo.datamodules import InriaAerialImageLabelingDataModule\nfrom torchgeo.trainers import SemanticSegmentationTask\n\ndatamodule = InriaAerialImageLabelingDataModule(root_dir=\"...\", batch_size=64, num_workers=6)\ntask = SemanticSegmentationTask(segmentation_model=\"unet\", encoder_weights=\"imagenet\", learning_rate=0.1)\ntrainer = Trainer(gpus=1, default_root_dir=\"...\")\n\ntrainer.fit(model=task, datamodule=datamodule)\n```\n\n
\n
\n
\n\n
\nBuilding segmentations produced by a U-Net model trained on the Inria Aerial Image Labeling dataset. Reproducing these results is as simple as a few imports and four lines of code, making comparison of different models and training techniques simple and easy.\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
-{"page_content": "In our [preprint](https://arxiv.org/abs/2111.08872) we show a set of results that use the aforementioned datamodules and trainers to benchmark simple modeling approaches for several of the datasets in TorchGeo. For example, we find that a simple ResNet-50 can achieve state-of-the-art performance on the [So2Sat](https://ieeexplore.ieee.org/document/9014553) dataset. These types of baseline results are important for evaluating the contribution of different modeling choices when tackling problems with remotely sensed data.\n\n# Future work and contributing\n\nThere is still a lot of remaining work to be done in order to make TorchGeo as easy to use as possible, especially for users without prior deep learning experience. One of the ways in which we plan to achieve this is by expanding our tutorials to include subjects like \"writing a custom dataset\" and \"transfer learning\", or tasks like \"land cover mapping\" and \"object detection\".", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "\n\n
\nTrue color (left) and NDVI (right) of the Texas Hill Region, taken on November 16, 2018 by the Sentinel-2 satellite. In the NDVI image, red indicates water bodies, yellow indicates barren soil, light green indicates unhealthy vegetation, and dark green indicates healthy vegetation.\n
\n\n# Benchmark datasets\n\nOne of the driving factors behind progress in computer vision is the existence of standardized benchmark datasets like ImageNet and MNIST. Using these datasets, researchers can directly compare the performance of different models and training procedures to determine which perform the best. In the remote sensing domain, there are many such datasets, but due to the aforementioned difficulties of working with this data and the lack of existing libraries for loading these datasets, many researchers opt to use their own custom datasets.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "One of the goals of TorchGeo is to provide easy-to-use data loaders for these existing datasets. TorchGeo includes a number of [*benchmark datasets*](https://torchgeo.readthedocs.io/en/latest/api/datasets.html#non-geospatial-datasets) \u2014datasets that include both input images and target labels. This includes datasets for tasks like image classification, regression, semantic segmentation, object detection, instance segmentation, change detection, and more.\n\nIf you've used torchvision before, these types of datasets should be familiar. In this example, we'll create a dataset for the Northwestern Polytechnical University (NWPU) very-high-resolution ten-class (VHR-10) geospatial object detection dataset. This dataset can be automatically downloaded, checksummed, and extracted, just like with torchvision.\n\n```c++\nfrom torch.utils.data import DataLoader\nfrom torchgeo.datasets import VHR10\n\ndataset = VHR10(root=\"...\", download=True, checksum=True)", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "dataloader = DataLoader(dataset, batch_size=128, shuffle=True, num_workers=4)\n\nfor batch in dataloader:\n image = batch[\"image\"]\n label = batch[\"label\"]\n\n # train a model, or make predictions using a pre-trained model\n```\n\nAll TorchGeo datasets are compatible with PyTorch data loaders, making them easy to integrate into existing training workflows. The only difference between a benchmark dataset in TorchGeo and a similar dataset in torchvision is that each dataset returns a dictionary with keys for each PyTorch ``Tensor``.\n\n
\n
\n
\n\n
\nExample predictions from a Mask R-CNN model trained on the NWPU VHR-10 dataset. The model predicts sharp bounding boxes and masks for all objects with high confidence scores.\n
\n\n# Reproducibility with PyTorch Lightning", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "\n\n# Reproducibility with PyTorch Lightning\n\nAnother key goal of TorchGeo is reproducibility. For many of these benchmark datasets, there is no predefined train-val-test split, or the predefined split has issues with class imbalance or geographic distribution. As a result, the performance metrics reported in the literature either can't be reproduced, or aren't indicative of how well a pre-trained model would work in a different geographic location.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "In order to facilitate direct comparisons between results published in the literature and further reduce the boilerplate code needed to run experiments with datasets in TorchGeo, we have created PyTorch Lightning [*datamodules*](https://torchgeo.readthedocs.io/en/latest/api/datamodules.html) with well-defined train-val-test splits and [*trainers*](https://torchgeo.readthedocs.io/en/latest/api/trainers.html) for various tasks like classification, regression, and semantic segmentation. These datamodules show how to incorporate augmentations from the kornia library, include preprocessing transforms (with pre-calculated channel statistics), and let users easily experiment with hyperparameters related to the data itself (as opposed to the modeling process). Training a semantic segmentation model on the Inria Aerial Image Labeling dataset is as easy as a few imports and four lines of code.\n\n```c++\nfrom pytorch_lightning import Trainer\nfrom torchgeo.datamodules import InriaAerialImageLabelingDataModule", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "from torchgeo.trainers import SemanticSegmentationTask\n\ndatamodule = InriaAerialImageLabelingDataModule(root_dir=\"...\", batch_size=64, num_workers=6)\ntask = SemanticSegmentationTask(segmentation_model=\"unet\", encoder_weights=\"imagenet\", learning_rate=0.1)\ntrainer = Trainer(gpus=1, default_root_dir=\"...\")\n\ntrainer.fit(model=task, datamodule=datamodule)\n```\n\n
\n
\n
\n\n
\nBuilding segmentations produced by a U-Net model trained on the Inria Aerial Image Labeling dataset. Reproducing these results is as simple as a few imports and four lines of code, making comparison of different models and training techniques simple and easy.\n
", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
+{"page_content": "\n\nIn our [preprint](https://arxiv.org/abs/2111.08872) we show a set of results that use the aforementioned datamodules and trainers to benchmark simple modeling approaches for several of the datasets in TorchGeo. For example, we find that a simple ResNet-50 can achieve state-of-the-art performance on the [So2Sat](https://ieeexplore.ieee.org/document/9014553) dataset. These types of baseline results are important for evaluating the contribution of different modeling choices when tackling problems with remotely sensed data.\n\n# Future work and contributing\n\nThere is still a lot of remaining work to be done in order to make TorchGeo as easy to use as possible, especially for users without prior deep learning experience. One of the ways in which we plan to achieve this is by expanding our tutorials to include subjects like \"writing a custom dataset\" and \"transfer learning\", or tasks like \"land cover mapping\" and \"object detection\".", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "Another important project we are working on is pre-training models. Most remote sensing researchers work with very small labeled datasets, and could benefit from pre-trained models and transfer learning approaches. TorchGeo is the first deep learning library to provide models pre-trained on multispectral imagery. Our goal is to provide models for different image modalities (optical, SAR, multispectral) and specific platforms (Landsat, Sentinel, MODIS) as well as benchmark results showing their performance with different amounts of training data. Self-supervised learning is a promising method for training such models. Satellite imagery datasets often contain petabytes of imagery, but accurately labeled datasets are much harder to come by. Self-supervised learning methods will allow us to train directly on the raw imagery without needing large labeled datasets.", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "Aside from these larger projects, we're always looking to add new datasets, data augmentation transforms, and sampling strategies. If you're Python savvy and interested in contributing to TorchGeo, we would love to see contributions! TorchGeo is open source under an MIT license, so you can use it in almost any project.\n\nExternal links:\n\n- **Homepage**: [https://github.com/microsoft/torchgeo](https://github.com/microsoft/torchgeo)\n- **Documentation**: [https://torchgeo.readthedocs.io/](https://torchgeo.readthedocs.io/)\n- **PyPI**: [https://pypi.org/project/torchgeo/](https://pypi.org/project/torchgeo/)\n- **Paper**: [https://arxiv.org/abs/2111.08872](https://arxiv.org/abs/2111.08872)\n\nIf you like TorchGeo, give us a star on GitHub! And if you use TorchGeo in your work, please cite our paper.\n\n# Acknowledgments", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "# Acknowledgments\n\n*We would like to thank all TorchGeo contributors for their efforts in creating the library, the Microsoft AI for Good program for support, and the PyTorch Team for their guidance. This research is part of the Blue Waters sustained-petascale computing project, which is supported by the National Science Foundation (awards OCI-0725070 and ACI-1238993), the State of Illinois, and as of December, 2019, the National Geospatial-Intelligence Agency. Blue Waters is a joint effort of the University of Illinois at Urbana-Champaign and its National Center for Supercomputing Applications. The research was supported in part by NSF grants IIS-1908104, OAC-1934634, and DBI-2021898.*", "metadata": {"source": "https://pytorch.org/blog/geospatial-deep-learning-with-torchgeo/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'What\u2019s New in PyTorch Profiler 1.9?'\nauthor: Sabrina Smai, Program Manager on the AI Framework team at Microsoft\n---\n\nPyTorch Profiler v1.9 has been released! The goal of this new release (previous [PyTorch Profiler release](https://pytorch.org/blog/introducing-pytorch-profiler-the-new-and-improved-performance-tool/)) is to provide you with new state-of-the-art tools to help diagnose and fix machine learning performance issues regardless of whether you are working on one or numerous machines. The objective is to target the execution steps that are the most costly in time and/or memory, and visualize the work load distribution between GPUs and CPUs. \n\nHere is a summary of the five major features being released:", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "1.\t**Distributed Training View**: This helps you understand how much time and memory is consumed in your distributed training job. Many issues occur when you take a training model and split the load into worker nodes to be run in parallel as it can be a black box. The overall model goal is to speed up model training. This distributed training view will help you diagnose and debug issues within individual nodes. \n2.\t**Memory View**: This view allows you to understand your memory usage better. This tool will help you avoid the famously pesky Out of Memory error by showing active memory allocations at various points of your program run. \n3.\t**GPU Utilization Visualization**: This tool helps you make sure that your GPU is being fully utilized. \n4.\t**Cloud Storage Support**: Tensorboard plugin can now read profiling data from Azure Blob Storage, Amazon S3, and Google Cloud Platform. \n5.\t**Jump to Source Code**: This feature allows you to visualize stack tracing information and jump directly into the source code. This helps you quickly optimize and iterate on your code based on your profiling results.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "## Getting Started with PyTorch Profiling Tool\nPyTorch includes a profiling functionality called \u00ab PyTorch Profiler \u00bb. The PyTorch Profiler tutorial can be found [here](https://pytorch.org/tutorials/intermediate/tensorboard_profiler_tutorial.html).\n\nTo instrument your PyTorch code for profiling, you must:\n\n$ pip install torch-tb-profiler\n\n```python\nimport torch.profiler as profiler\nWith profiler.profile(XXXX)\n```\n\n**Comments**:\n\n\u2022 For CUDA and CPU profiling, see [below](https://github.com/pytorch/kineto/blob/master/tb_plugin/examples/resnet50_profiler_api.py): \n```\nwith torch.profiler.profile( \nactivities=[ \ntorch.profiler.ProfilerActivity.CPU, \ntorch.profiler.ProfilerActivity.CUDA], \n```\n\n\u2022\tWith profiler.record_function(\u201c$NAME\u201d): allows putting a decorator (a tag associated to a name) for a block of function\n\n\u2022\tProfile_memory=True parameter under profiler.profile allows you to profile CPU and GPU memory footprint\n\n## Visualizing PyTorch Model Performance using PyTorch Profiler\n\n### Distributed Training", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "### Distributed Training \n\nRecent advances in deep learning argue for the value of large datasets and large models, which requires you to scale out model training to more computational resources. Distributed Data Parallel (DDP) and NVIDIA Collective Communications Library (NCCL) are the widely adopted paradigms in PyTorch for accelerating your deep learning training. \n\nIn this release of PyTorch Profiler, DDP with NCCL backend is now supported.\n\n
\n

\n
\n\n### Computation/Communication Overview\n\nIn the Computation/Communication overview under the Distributed training view, you can observe the computation-to-communication ratio of each worker and [load balancer](https://en.wikipedia.org/wiki/Load_balancing_(computing) nodes between worker as measured by granularity. \n\n**Scenario 1**:", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "**Scenario 1**:\n\nIf the computation and overlapping time of one worker is much larger than the others, this may suggest an issue in the workload balance or worker being a straggler. Computation is the sum of kernel time on GPU minus the overlapping time. The overlapping time is the time saved by interleaving communications during computation. The more overlapping time represents better parallelism between computation and communication. Ideally the computation and communication completely overlap with each other. Communication is the total communication time minus the overlapping time. The example image below displays how this scenario appears on Tensorboard. \n\n
\n

\n
Figure: A straggler example
\n
\n\n**Scenario 2**:", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "**Scenario 2**:\n\nIf there is a small batch size (i.e. less computation on each worker) or the data to be transferred is large, the computation-to-communication may also be small and be seen in the profiler with low GPU utilization and long waiting times. This computation/communication view will allow you to diagnose your code to reduce communication by adopting gradient accumulation, or to decrease the communication proportion by increasing batch size. DDP communication time depends on model size. Batch size has no relationship with model size. So increasing batch size could make computation time longer and make computation-to-communication ratio bigger. \n\n### Synchronizing/Communication Overview", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "### Synchronizing/Communication Overview\n\nIn the Synchronizing/Communication view, you can observe the efficiency of communication. This is done by taking the step time minus computation and communication time. Synchronizing time is part of the total communication time for waiting and synchronizing with other workers. The Synchronizing/Communication view includes initialization, data loader, CPU computation, and so on Insights like what is the ratio of total communication is really used for exchanging data and what is the idle time of waiting for data from other workers can be drawn from this view. \n\n
\n

\n
\n\nFor example, if there is an inefficient workload balance or straggler issue, you\u2019ll be able to identify it in this Synchronizing/Communication view. This view will show several workers\u2019 waiting time being longer than others.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "1.\t**Distributed Training View**: This helps you understand how much time and memory is consumed in your distributed training job. Many issues occur when you take a training model and split the load into worker nodes to be run in parallel as it can be a black box. The overall model goal is to speed up model training. This distributed training view will help you diagnose and debug issues within individual nodes. \n2.\t**Memory View**: This view allows you to understand your memory usage better. This tool will help you avoid the famously pesky Out of Memory error by showing active memory allocations at various points of your program run. \n3.\t**GPU Utilization Visualization**: This tool helps you make sure that your GPU is being fully utilized. \n4.\t**Cloud Storage Support**: Tensorboard plugin can now read profiling data from Azure Blob Storage, Amazon S3, and Google Cloud Platform.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "5.\t**Jump to Source Code**: This feature allows you to visualize stack tracing information and jump directly into the source code. This helps you quickly optimize and iterate on your code based on your profiling results. \n\n## Getting Started with PyTorch Profiling Tool\nPyTorch includes a profiling functionality called \u00ab PyTorch Profiler \u00bb. The PyTorch Profiler tutorial can be found [here](https://pytorch.org/tutorials/intermediate/tensorboard_profiler_tutorial.html).\n\nTo instrument your PyTorch code for profiling, you must:\n\n$ pip install torch-tb-profiler\n\n```python\nimport torch.profiler as profiler\nWith profiler.profile(XXXX)\n```\n\n**Comments**:\n\n\u2022 For CUDA and CPU profiling, see [below](https://github.com/pytorch/kineto/blob/master/tb_plugin/examples/resnet50_profiler_api.py): \n```\nwith torch.profiler.profile( \nactivities=[ \ntorch.profiler.ProfilerActivity.CPU, \ntorch.profiler.ProfilerActivity.CUDA], \n```", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "torch.profiler.ProfilerActivity.CUDA], \n```\n\n\u2022\tWith profiler.record_function(\u201c$NAME\u201d): allows putting a decorator (a tag associated to a name) for a block of function\n\n\u2022\tProfile_memory=True parameter under profiler.profile allows you to profile CPU and GPU memory footprint\n\n## Visualizing PyTorch Model Performance using PyTorch Profiler\n\n### Distributed Training \n\nRecent advances in deep learning argue for the value of large datasets and large models, which requires you to scale out model training to more computational resources. Distributed Data Parallel (DDP) and NVIDIA Collective Communications Library (NCCL) are the widely adopted paradigms in PyTorch for accelerating your deep learning training. \n\nIn this release of PyTorch Profiler, DDP with NCCL backend is now supported.\n\n
\n

\n
\n\n### Computation/Communication Overview", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n### Computation/Communication Overview\n\nIn the Computation/Communication overview under the Distributed training view, you can observe the computation-to-communication ratio of each worker and [load balancer](https://en.wikipedia.org/wiki/Load_balancing_(computing) nodes between worker as measured by granularity. \n\n**Scenario 1**:\n\nIf the computation and overlapping time of one worker is much larger than the others, this may suggest an issue in the workload balance or worker being a straggler. Computation is the sum of kernel time on GPU minus the overlapping time. The overlapping time is the time saved by interleaving communications during computation. The more overlapping time represents better parallelism between computation and communication. Ideally the computation and communication completely overlap with each other. Communication is the total communication time minus the overlapping time. The example image below displays how this scenario appears on Tensorboard. \n\n", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "
\n

\n
Figure: A straggler example
\n
\n\n**Scenario 2**:\n\nIf there is a small batch size (i.e. less computation on each worker) or the data to be transferred is large, the computation-to-communication may also be small and be seen in the profiler with low GPU utilization and long waiting times. This computation/communication view will allow you to diagnose your code to reduce communication by adopting gradient accumulation, or to decrease the communication proportion by increasing batch size. DDP communication time depends on model size. Batch size has no relationship with model size. So increasing batch size could make computation time longer and make computation-to-communication ratio bigger. \n\n### Synchronizing/Communication Overview", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "### Synchronizing/Communication Overview\n\nIn the Synchronizing/Communication view, you can observe the efficiency of communication. This is done by taking the step time minus computation and communication time. Synchronizing time is part of the total communication time for waiting and synchronizing with other workers. The Synchronizing/Communication view includes initialization, data loader, CPU computation, and so on Insights like what is the ratio of total communication is really used for exchanging data and what is the idle time of waiting for data from other workers can be drawn from this view. \n\n
\n

\n
\n\nFor example, if there is an inefficient workload balance or straggler issue, you\u2019ll be able to identify it in this Synchronizing/Communication view. This view will show several workers\u2019 waiting time being longer than others. \n\n
", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "
\n

\n
\n\nThis table view above allows you to see the detailed statistics of all communication ops in each node. This allows you to see what operation types are being called, how many times each op is called, what is the size of the data being transferred by each op, etc. \n\n### Memory View:\n\nThis memory view tool helps you understand the hardware resource consumption of the operators in your model. Understanding the time and memory consumption on the operator-level allows you to resolve performance bottlenecks and in turn, allow your model to execute faster. Given limited GPU memory size, optimizing the memory usage can: \n\n1. Allow bigger model which can potentially generalize better on end level tasks.\n2. Allow bigger batch size. Bigger batch sizes increase the training speed.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "The profiler records all the memory allocation during the profiler interval. Selecting the \u201cDevice\u201d will allow you to see each operator\u2019s memory usage on the GPU side or host side. You must enable ```profile_memory=True``` to generate the below memory data as shown [here](https://github.com/pytorch/kineto/blob/master/tb_plugin/examples/resnet50_profiler_api.py#L39). \n\n```\nWith torch.profiler.profile(\nProfiler_memory=True # this will take 1 \u2013 2 minutes to complete. \n)\n```\n\n**Important Definitions**:\n\n\u2022\t\u201cSize Increase\u201d displays the sum of all allocation bytes and minus all the memory release bytes.\n\n\u2022\t\u201cAllocation Size\u201d shows the sum of all allocation bytes without considering the memory release.\n\n\u2022\t\u201cSelf\u201d means the allocated memory is not from any child operators, instead by the operator itself.\n\n
\n

\n
\n\n\n### GPU Metric on Timeline:", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "### GPU Metric on Timeline:\n\nThis feature will help you debug performance issues when one or more GPU are underutilized. Ideally, your program should have high GPU utilization (aiming for 100% GPU utilization), minimal CPU to GPU communication, and no overhead. \n\n**Overview**:\nThe overview page highlights the results of three important GPU usage metrics at different levels (i.e. GPU Utilization, Est. SM Efficiency, and Est. Achieved Occupancy). Essentially, each GPU has a bunch of SM each with a bunch of warps that can execute a bunch of threads concurrently. Warps execute a bunch because the amount depends on the GPU. But at a high level, this GPU Metric on Timeline tool allows you can see the whole stack, which is useful. \n\nIf the GPU utilization result is low, this suggests a potential bottleneck is present in your model. Common reasons: \n\n\u2022Insufficient parallelism in kernels (i.e., low batch size) \n\n\u2022Small kernels called in a loop. This is to say the launch overheads are not amortized", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\n### GPU Metric on Timeline:\n\nThis feature will help you debug performance issues when one or more GPU are underutilized. Ideally, your program should have high GPU utilization (aiming for 100% GPU utilization), minimal CPU to GPU communication, and no overhead. \n\n**Overview**:\nThe overview page highlights the results of three important GPU usage metrics at different levels (i.e. GPU Utilization, Est. SM Efficiency, and Est. Achieved Occupancy). Essentially, each GPU has a bunch of SM each with a bunch of warps that can execute a bunch of threads concurrently. Warps execute a bunch because the amount depends on the GPU. But at a high level, this GPU Metric on Timeline tool allows you can see the whole stack, which is useful. \n\nIf the GPU utilization result is low, this suggests a potential bottleneck is present in your model. Common reasons: \n\n\u2022Insufficient parallelism in kernels (i.e., low batch size) \n\n\u2022Small kernels called in a loop. This is to say the launch overheads are not amortized", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "\u2022CPU or I/O bottlenecks lead to the GPU not receiving enough work to keep busy \n\nLooking of the overview page where the performance recommendation section is where you\u2019ll find potential suggestions on how to increase that GPU utilization. In this example, GPU utilization is low so the performance recommendation was to increase batch size. Increasing batch size 4 to 32, as per the performance recommendation, increased the GPU Utilization by 60.68%.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "GPU Utilization: the step interval time in the profiler when a GPU engine was executing a workload. The high the utilization %, the better. The drawback of using GPU utilization solely to diagnose performance bottlenecks is it is too high-level and coarse. It won\u2019t be able to tell you how many Streaming Multiprocessors are in use. Note that while this metric is useful for detecting periods of idleness, a high value does not indicate efficient use of the GPU, only that it is doing anything at all. For instance, a kernel with a single thread running continuously will get a GPU Utilization of 100%", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "Estimated Stream Multiprocessor Efficiency (Est. SM Efficiency) is a finer grained metric, it indicates what percentage of SMs are in use at any point in the trace This metric reports the percentage of time where there is at least one active warp on a SM and those that are stalled (NVIDIA [doc](https://forums.developer.nvidia.com/t/nvprof-question-about-the-sm-efficiency-metric/72640#:~:text=My%20understanding%20from%20the%20profiler%20documentation%20is%20that,that%20%E2%80%9Cactive%20warps%E2%80%9D%20include%20warps%20that%20are%20stalled.)). Est. SM Efficiency also has it\u2019s limitation. For instance, a kernel with only one thread per block can\u2019t fully use each SM. SM Efficiency does not tell us how busy each SM is, only that they are doing anything at all, which can include stalling while waiting on the result of a memory load. To keep an SM busy, it is necessary to have a sufficient number of ready warps that can be run whenever a stall occurs", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "Estimated Achieved Occupancy (Est. Achieved Occupancy) is a layer deeper than Est. SM Efficiency and GPU Utilization for diagnosing performance issues. Estimated Achieved Occupancy indicates how many warps can be active at once per SMs. Having a sufficient number of active warps is usually key to achieving good throughput. Unlike GPU Utilization and SM Efficiency, it is not a goal to make this value as high as possible. As a rule of thumb, good throughput gains can be had by improving this metric to 15% and above. But at some point you will hit diminishing returns. If the value is already at 30% for example, further gains will be uncertain. This metric reports the average values of all warp schedulers for the kernel execution period (NVIDIA [doc](https://docs.nvidia.com/gameworks/content/developertools/desktop/analysis/report/cudaexperiments/kernellevel/achievedoccupancy.htm)). The larger the Est. Achieve Occupancy value is the better.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "
\n

\n
Overview details: Resnet50_batchsize4
\n
\n\n
\n

\n
Overview details: Resnet50_batchsize32
\n
\n\n_Kernel View_\nThe kernel has \u201cBlocks per SM\u201d and \u201cEst. Achieved Occupancy\u201d which is a great tool to compare model runs. \n\n
\n

\n
\n\nMean Blocks per SM: \nBlocks per SM = Blocks of this kernel / SM number of this GPU. If this number is less than 1, it indicates the GPU multiprocessors are not fully utilized. \u201cMean Blocks per SM\u201d is weighted average of all runs of this kernel name, using each run\u2019s duration as weight.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "Estimated Achieved Occupancy (Est. Achieved Occupancy) is a layer deeper than Est. SM Efficiency and GPU Utilization for diagnosing performance issues. Estimated Achieved Occupancy indicates how many warps can be active at once per SMs. Having a sufficient number of active warps is usually key to achieving good throughput. Unlike GPU Utilization and SM Efficiency, it is not a goal to make this value as high as possible. As a rule of thumb, good throughput gains can be had by improving this metric to 15% and above. But at some point you will hit diminishing returns. If the value is already at 30% for example, further gains will be uncertain. This metric reports the average values of all warp schedulers for the kernel execution period (NVIDIA [doc](https://docs.nvidia.com/gameworks/content/developertools/desktop/analysis/report/cudaexperiments/kernellevel/achievedoccupancy.htm)). The larger the Est. Achieve Occupancy value is the better. \n\n
", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "
\n

\n
Overview details: Resnet50_batchsize4
\n
\n\n
\n

\n
Overview details: Resnet50_batchsize32
\n
\n\n_Kernel View_\nThe kernel has \u201cBlocks per SM\u201d and \u201cEst. Achieved Occupancy\u201d which is a great tool to compare model runs. \n\n
\n

\n
\n\nMean Blocks per SM: \nBlocks per SM = Blocks of this kernel / SM number of this GPU. If this number is less than 1, it indicates the GPU multiprocessors are not fully utilized. \u201cMean Blocks per SM\u201d is weighted average of all runs of this kernel name, using each run\u2019s duration as weight. \n\nMean Est. Achieved Occupancy:", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "Mean Est. Achieved Occupancy: \nEst. Achieved Occupancy is defined as above in overview. \u201cMean Est. Achieved Occupancy\u201d is weighted average of all runs of this kernel name, using each run\u2019s duration as weight. \n\n_Trace View_\nThis trace view displays a timeline that shows the duration of operators in your model and which system executed the operation. This view can help you identify whether the high consumption and long execution is because of input or model training. Currently, this trace view shows GPU Utilization and Est. SM Efficiency on a timeline. \n\n
\n

\n
", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "GPU utilization is calculated independently and divided into multiple 10 millisecond buckets. The buckets\u2019 GPU utilization values are drawn alongside the timeline between 0 \u2013 100%. In the above example, the \u201cProfilerStep5\u201d GPU utilization during thread 28022\u2019s busy time is higher than the following the one during \u201cOptimizer.step\u201d. This is where you can zoom-in to investigate why that is. \n\n
\n

\n
\n\nFrom above, we can see the former\u2019s kernels are longer than the later\u2019s kernels. The later\u2019s kernels are too short in execution, which results in lower GPU utilization. \n\nEst. SM Efficiency: Each kernel has a calculated est. SM efficiency between 0 \u2013 100%. For example, the below kernel has only 64 blocks, while the SMs in this GPU is 80. Then its \u201cEst. SM Efficiency\u201d is 64/80, which is 0.8.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "
\n\nGPU utilization is calculated independently and divided into multiple 10 millisecond buckets. The buckets\u2019 GPU utilization values are drawn alongside the timeline between 0 \u2013 100%. In the above example, the \u201cProfilerStep5\u201d GPU utilization during thread 28022\u2019s busy time is higher than the following the one during \u201cOptimizer.step\u201d. This is where you can zoom-in to investigate why that is. \n\n
\n

\n
\n\nFrom above, we can see the former\u2019s kernels are longer than the later\u2019s kernels. The later\u2019s kernels are too short in execution, which results in lower GPU utilization. \n\nEst. SM Efficiency: Each kernel has a calculated est. SM efficiency between 0 \u2013 100%. For example, the below kernel has only 64 blocks, while the SMs in this GPU is 80. Then its \u201cEst. SM Efficiency\u201d is 64/80, which is 0.8. \n\n
", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "
\n

\n
\n\n### Cloud Storage Support\n\nAfter running pip install tensorboard, to have data be read through these cloud providers, you can now run: \n\n``` sh \ntorch-tb-profiler[blob] \ntorch-tb-profiler[gs] \ntorch-tb-profiler[s3] \n``` \n```pip install torch-tb-profiler[blob]```, ```pip install torch-tb-profiler[gs]```, or ```pip install torch-tb-profiler[S3]``` to have data be read through these cloud providers. For more information, please refer to this [README](https://github.com/pytorch/kineto/tree/main/tb_plugin). \n\n### Jump to Source Code:", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "### Jump to Source Code:\n\nOne of the great benefits of having both TensorBoard and the PyTorch Profiler being integrated directly in Visual Studio Code (VS Code) is the ability to directly jump to the source code (file and line) from the profiler stack traces. VS Code Python Extension now [supports TensorBoard Integration](https://devblogs.microsoft.com/python/python-in-visual-studio-code-february-2021-release/).\n\nJump to source is ONLY available when Tensorboard is launched within VS Code. Stack tracing will appear on the plugin UI if the profiling with_stack=True. When you click on a stack trace from the PyTorch Profiler, VS Code will automatically open the corresponding file side by side and jump directly to the line of code of interest for you to debug. This allows you to quickly make actionable optimizations and changes to your code based on the profiling results and suggestions.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
-{"page_content": "
\n

\n
Gify: Jump to Source using Visual Studio Code Plug In UI
\n
\n\nFor how to optimize batch size performance, check out the step-by-step tutorial [here](https://opendatascience.com/optimizing-pytorch-performance-batch-size-with-pytorch-profiler/). PyTorch Profiler is also integrated with [PyTorch Lightning](https://pytorch-lightning.readthedocs.io/en/stable/advanced/profiler.html#pytorch-profiling) and you can simply launch your lightning training jobs with --```trainer.profiler=pytorch``` flag to generate the traces. Check out an example [here](https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/basic_examples/profiler_example.py). \n\n## What\u2019s Next for the PyTorch Profiler?\nYou just saw how PyTorch Profiler can help optimize a model. You can now try the Profiler by ```pip install torch-tb-profiler``` to optimize your PyTorch model.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "### Jump to Source Code:\n\nOne of the great benefits of having both TensorBoard and the PyTorch Profiler being integrated directly in Visual Studio Code (VS Code) is the ability to directly jump to the source code (file and line) from the profiler stack traces. VS Code Python Extension now [supports TensorBoard Integration](https://devblogs.microsoft.com/python/python-in-visual-studio-code-february-2021-release/).\n\nJump to source is ONLY available when Tensorboard is launched within VS Code. Stack tracing will appear on the plugin UI if the profiling with_stack=True. When you click on a stack trace from the PyTorch Profiler, VS Code will automatically open the corresponding file side by side and jump directly to the line of code of interest for you to debug. This allows you to quickly make actionable optimizations and changes to your code based on the profiling results and suggestions. \n\n
\n

", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
+{"page_content": "
Gify: Jump to Source using Visual Studio Code Plug In UI
\n
\n\nFor how to optimize batch size performance, check out the step-by-step tutorial [here](https://opendatascience.com/optimizing-pytorch-performance-batch-size-with-pytorch-profiler/). PyTorch Profiler is also integrated with [PyTorch Lightning](https://pytorch-lightning.readthedocs.io/en/stable/advanced/profiler.html#pytorch-profiling) and you can simply launch your lightning training jobs with --```trainer.profiler=pytorch``` flag to generate the traces. Check out an example [here](https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/basic_examples/profiler_example.py). \n\n## What\u2019s Next for the PyTorch Profiler?\nYou just saw how PyTorch Profiler can help optimize a model. You can now try the Profiler by ```pip install torch-tb-profiler``` to optimize your PyTorch model.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "Look out for an advanced version of this tutorial in the future. We are also thrilled to continue to bring state-of-the-art tool to PyTorch users to improve ML performance. We'd love to hear from you. Feel free to open an issue [here](https://github.com/pytorch/kineto/issues). \n\nFor new and exciting features coming up with PyTorch Profiler, follow @PyTorch on Twitter and check us out on pytorch.org. \n\n## Acknowledgements\n\nThe author would like to thank the contributions of the following individuals to this piece. From the Facebook side: Geeta Chauhan, Gisle Dankel, Woo Kim, Sam Farahzad, and Mark Saroufim. On the Microsoft side: AI Framework engineers (Teng Gao, Mike Guo, and Yang Gu), Guoliang Hua, and Thuy Nguyen.", "metadata": {"source": "https://pytorch.org/blog/pytorch-profiler-1.9-released/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'Announcing the Winners of the 2020 Global PyTorch Summer Hackathon'\nauthor: Team PyTorch\n---\n\nMore than 2,500 participants in this year\u2019s Global PyTorch Summer Hackathon pushed the envelope to create unique new tools and applications for PyTorch developers and researchers.\n\n
\n

\n
\n\n***Notice**: None of the projects submitted to the hackathon are associated with or offered by Facebook, Inc.* \n\nThis year\u2019s projects fell into three categories:\n\n* **PyTorch Developer Tools:** a tool or library for improving productivity and efficiency for PyTorch researchers and developers.\n\n* **Web/Mobile Applications Powered by PyTorch:** a web or mobile interface and/or an embedded device built using PyTorch.", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
{"page_content": "* **PyTorch Responsible AI Development Tools:** a tool, library, or web/mobile app to support researchers and developers in creating responsible AI that factors in fairness, security, privacy, and more throughout its entire development process.\n\nThe virtual hackathon ran from June 22 to August 25, with more than 2,500 registered participants, representing 114 countries from Republic of Azerbaijan, to Zimbabwe, to Japan, submitting a total of 106 projects. Entrants were judged on their idea\u2019s quality, originality, potential impact, and how well they implemented it.\n\nMeet the winners of each category below. \n\n## PyTorch Developer Tools\n\n**1st place** - [DeMask](https://devpost.com/software/asteroid-the-pytorch-based-source-separation-toolkit)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
-{"page_content": "DeMask is an end-to-end model for enhancing speech while wearing face masks \u2014 offering a clear benefit during times when face masks are mandatory in many spaces and for workers who wear face masks on the job. Built with [Asteroid](https://github.com/mpariente/asteroid), a PyTorch-based audio source separation toolkit, DeMask is trained to recognize distortions in speech created by the muffling from face masks and to adjust the speech to make it sound clearer. \n\nThis submission stood out in particular because it represents both a high-quality idea and an implementation that can be reproduced by other researchers.\n\nHere is an example on how to train a speech separation model in less than 20 lines:\n\n```python\nfrom torch import optim\nfrom pytorch_lightning import Trainer\n\nfrom asteroid import ConvTasNet\nfrom asteroid.losses import PITLossWrapper\nfrom asteroid.data import LibriMix\nfrom asteroid.engine import System", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
-{"page_content": "train_loader, val_loader = LibriMix.loaders_from_mini(task='sep_clean', batch_size=4)\nmodel = ConvTasNet(n_src=2)\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\nloss = PITLossWrapper(\n lambda x, y: (x - y).pow(2).mean(-1), # MSE\n pit_from=\"pw_pt\", # Point in the pairwise matrix.\n)\n\nsystem = System(model, optimizer, loss, train_loader, val_loader)\n\ntrainer = Trainer(fast_dev_run=True)\ntrainer.fit(system)\n```\n\n**2nd place** - [carefree-learn](https://devpost.com/software/carefree-learn)\n\nA PyTorch-based automated machine learning (AutoML) solution, carefree-learn provides high-level APIs to make training models using tabular data sets simpler. It features an interface similar to [scikit-learn](https://scikit-learn.org/stable/) and functions as an end-to-end end pipeline for tabular data sets. It automatically detects feature column types and redundant feature columns, imputes missing values, encodes string columns and categorical columns, and preprocesses numerical columns, among other features.", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
-{"page_content": "**3rd Place** - [TorchExpo](https://devpost.com/software/torchexpo)\n\nTorchExpo is a collection of models and extensions that simplifies taking PyTorch from research to production in mobile devices. This library is more than a web and mobile application, and also comes with a Python library. The Python library is available via pip install and it helps researchers convert a state-of-the-art model in TorchScript and ONNX format in just one line. Detailed docs are available [here](https://torchexpo.readthedocs.io/en/latest/).\n\n## Web/Mobile Applications Powered by PyTorch\n\n**1st place** - [Q&Aid](https://devpost.com/software/pytorchxai)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
+{"page_content": "DeMask is an end-to-end model for enhancing speech while wearing face masks \u2014 offering a clear benefit during times when face masks are mandatory in many spaces and for workers who wear face masks on the job. Built with [Asteroid](https://github.com/mpariente/asteroid), a PyTorch-based audio source separation toolkit, DeMask is trained to recognize distortions in speech created by the muffling from face masks and to adjust the speech to make it sound clearer. \n\nThis submission stood out in particular because it represents both a high-quality idea and an implementation that can be reproduced by other researchers.\n\nHere is an example on how to train a speech separation model in less than 20 lines:\n\n```python\nfrom torch import optim\nfrom pytorch_lightning import Trainer\n\nfrom asteroid import ConvTasNet\nfrom asteroid.losses import PITLossWrapper\nfrom asteroid.data import LibriMix\nfrom asteroid.engine import System\n\ntrain_loader, val_loader = LibriMix.loaders_from_mini(task='sep_clean', batch_size=4)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
+{"page_content": "model = ConvTasNet(n_src=2)\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\nloss = PITLossWrapper(\n lambda x, y: (x - y).pow(2).mean(-1), # MSE\n pit_from=\"pw_pt\", # Point in the pairwise matrix.\n)\n\nsystem = System(model, optimizer, loss, train_loader, val_loader)\n\ntrainer = Trainer(fast_dev_run=True)\ntrainer.fit(system)\n```\n\n**2nd place** - [carefree-learn](https://devpost.com/software/carefree-learn)\n\nA PyTorch-based automated machine learning (AutoML) solution, carefree-learn provides high-level APIs to make training models using tabular data sets simpler. It features an interface similar to [scikit-learn](https://scikit-learn.org/stable/) and functions as an end-to-end end pipeline for tabular data sets. It automatically detects feature column types and redundant feature columns, imputes missing values, encodes string columns and categorical columns, and preprocesses numerical columns, among other features. \n\n**3rd Place** - [TorchExpo](https://devpost.com/software/torchexpo)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
+{"page_content": "TorchExpo is a collection of models and extensions that simplifies taking PyTorch from research to production in mobile devices. This library is more than a web and mobile application, and also comes with a Python library. The Python library is available via pip install and it helps researchers convert a state-of-the-art model in TorchScript and ONNX format in just one line. Detailed docs are available [here](https://torchexpo.readthedocs.io/en/latest/).\n\n## Web/Mobile Applications Powered by PyTorch\n\n**1st place** - [Q&Aid](https://devpost.com/software/pytorchxai)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
{"page_content": "Q&Aid is a conceptual health-care chatbot aimed at making health-care diagnoses and facilitating communication between patients and doctors. It relies on a series of machine learning models to filter, label, and answer medical questions, based on a medical image and/or questions in text provided by a patient. The transcripts from the chat app then can be forwarded to the local hospitals and the patient will be contacted by one of them to make an appointment to determine proper diagnosis and care. The team hopes that this concept application helps hospitals to work with patients more efficiently and provide proper care. \n\n
\n

\n
\n\n**2nd place** - [Rasoee](https://devpost.com/software/groundwav)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
{"page_content": "Rasoee is an application that can take images as input and output the name of the dish. It also lists the ingredients and recipe, along with the link to the original recipe online. Additionally, users can choose a cuisine from the list of cuisines in the drop menu, and describe the taste and/or method of preparation in text. Then the application will return matching dishes from the [list of 308 identifiable dishes](https://github.com/arijitgupta42/Rasoee/blob/master/Dishes.txt). The team has put a significant amount of effort gathering and cleaning various datasets to build more accurate and comprehensive models. You can check out the application [here](https://rasoee.herokuapp.com).\n\n**3rd place** - [Rexana the Robot \u2014 PyTorch](https://devpost.com/software/rexana-the-robot)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
{"page_content": "Rexana is an AI voice assistant meant to lay the foundation for a physical robot that can complete basic tasks around the house. The system is capable of autonomous navigation (knowing its position around the house relative to landmarks), recognizing voice commands, and object detection and recognition \u2014 meaning it can be commanded to perform various household tasks (e.g., \"Rexana, water the potted plant in the lounge room.\u201d). Rexana can be controlled remotely via a mobile device, and the robot itself features customizable hands (magnets, grippers, etc.) for taking on different jobs.\n\n## PyTorch Responsible AI Development Tools\n\n**1st place**: [FairTorch](https://devpost.com/software/a-qeysp1)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
@@ -283,48 +283,51 @@
{"page_content": "Fluence is a PyTorch-based deep learning library for language research. It specifically addresses the large compute demands of natural language processing (NLP) research. Fluence aims to provide low-resource and computationally efficient algorithms for NLP, giving researchers algorithms that can enhance current NLP methods or help discover where current methods fall short.\n\n**3rd place**: [Causing: CAUSal INterpretation using Graphs](https://devpost.com/software/realrate-explainable-ai-for-company-ratings)", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
{"page_content": "Causing (CAUSal INterpretation using Graphs) is a multivariate graphic analysis tool for bringing transparency to neural networks. It explains causality and helps researchers and developers interpret the causal effects of a given equation system to ensure fairness. Developers can input data and a model describing the dependencies between the variables within the data set into Causing, and Causing will output a colored graph of quantified effects acting between the model\u2019s variables. In addition, it also allows developers to estimate these effects to validate whether data fits a model.\n\nThank you,\n\n**The PyTorch team**", "metadata": {"source": "https://pytorch.org/blog/announcing-the-winners-of-the-2020-global-pytorch-summer-hackathon/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"PyTorch\u2019s Tracing Based Selective Build\"\nauthor: Dhruv Matani, Suraj Subramanian\nfeatured-img: \"/assets/images/pytorchs-tracing-based-selective-build_Figure_4.png\"\n---\n\n## Introduction\n\n**TL;DR**: It can be challenging to run PyTorch on mobile devices, SBCs (Single Board Computers), and IOT devices. When compiled, the PyTorch library is huge and includes dependencies that might not be needed for the on-device use case. \n\nTo run a specific set of models on-device, we actually require only a small subset of the features in the PyTorch library. We found that using a PyTorch runtime generated using **selective build** can achieve up to 90% reduction in binary size (for the CPU and QuantizedCPU backends on an x86-64 build on Linux). In this blog, we share our experience of generating model-specific minimal runtimes using Selective Build and show you how to do the same.\n\n## Why is this important for app developers?", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "## Why is this important for app developers?\n\nUsing a PyTorch runtime generated by **selective build** can reduce the size of AI-powered apps by 30+ MB - a significant reduction for a typical mobile app! Making mobile applications more lightweight has many benefits - they are runnable on a wider variety of devices, consume less cellular data, and can be downloaded and updated faster on user\u2019s devices.\n\n## What does the Developer Experience look like?\n\nThis method can work seamlessly with any existing PyTorch Mobile deployment workflows. All you need to do is replace the general PyTorch runtime library with a runtime customized for the specific models you wish to use in your application. The general steps in this process are:", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "1. Build the PyTorch Runtime in **instrumentation mode** (this is called an **instrumentation build** of PyTorch). This will record the used operators, kernels and features.\n2. Run your models through this instrumentation build by using the provided **model_tracer** binary. This will generate a single YAML file that stores all the features used by your model. These features will be preserved in the minimal runtime.\n3. Build PyTorch using this YAML file as input. This is the **selective build** technique, and it greatly reduces the size of the final PyTorch binary.\n4. Use this selectively-built PyTorch library to reduce the size of your mobile application!\n\n\nBuilding the PyTorch Runtime in a special **\u201cinstrumentation\u201d mode** ( by passing the `TRACING_BASED=1` build option) generates an **instrumentation build** runtime of PyTorch, along with a **model_tracer** binary. Running a model with this build allows us to trace the parts of PyTorch used by the model.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "
\n
\n
\n\n
\n Figure 1: Instrumentation build of PyTorch\n
\n\n```python\n# Clone the PyTorch repo\ngit clone https://github.com/pytorch/pytorch.git\ncd pytorch\n\n# Build the model_tracer\nUSE_NUMPY=0 USE_DISTRIBUTED=0 USE_CUDA=0 TRACING_BASED=1 \\\n python setup.py develop\n```\n\nNow this instrumentation build is used to run a model inference with representative inputs. The **model_tracer** binary observes parts of the instrumentation build that were activated during the inference run, and dumps it to a YAML file.\n\n
\n
\n
\n\n
\n Figure 2: YAML file generated by running model(s) on an instrumentation build\n
", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "```python\n# Generate YAML file\n./build/bin/model_tracer \\\n --model_input_path /tmp/path_to_model.ptl \\\n --build_yaml_path /tmp/selected_ops.yaml\n```\n\nNow we build the PyTorch Runtime again, but this time using the YAML file generated by the tracer. The runtime now only includes those parts that are needed for this model. This is called **\u201cSelectively built PyTorch runtime\u201d** in the diagram below.\n\n```python\n# Clean out cached configuration\nmake clean\n\n# Build PyTorch using Selected Operators (from the YAML file)\n# using the host toolchain, and use this generated library\nBUILD_PYTORCH_MOBILE_WITH_HOST_TOOLCHAIN=1 \\\nUSE_LIGHTWEIGHT_DISPATCH=0 \\\nBUILD_LITE_INTERPRETER=1 \\\nSELECTED_OP_LIST=/tmp/selected_ops.yaml \\\nTRACING_BASED=1 \\\n ./scripts/build_mobile.sh\n```\n\n
\n
\n
\n\n
\n Figure 3: Selective Build of PyTorch and model execution on a selectively built PyTorch runtime\n
", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "### Show me the code!\n\nWe\u2019ve put together a [notebook](https://gist.github.com/dhruvbird/65fd800983f362a72d78afe68031568c) to illustrate what the process above looks like in code using a simple PyTorch model. \n\nFor a more hands-on tutorial to deploy this on Android/iOS [this tutorial](https://pytorch.org/tutorials/prototype/tracing_based_selective_build.html) should be helpful.\n\n## Technical FAQs\n\n### Why is Tracing needed for a Selective Build of PyTorch?\n\nIn PyTorch, CPU kernels can call other operators via the [PyTorch Dispatcher](http://blog.ezyang.com/2020/09/lets-talk-about-the-pytorch-dispatcher/). Simply including the set of root operators called directly by the model is not sufficient as there might be many more being called under-the-hood transitively. Running the model on representative inputs and observing the actual list of operators called (aka \u201ctracing\u201d) is the most accurate way of determining what parts of PyTorch are used.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "Additionally, factors such as which dtypes a kernel should handle are also runtime features that depend on actual input provided to the model. Hence, the tracing mechanism is extremely suitable for this purpose.\n\n### Which features can be selected (in or out) by using Tracing Based Selective Build?\n\nThe following features can be selected for the PyTorch runtime during the tracing based selective build process:", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "1. [CPU/QuantizedCPU](https://codebrowser.bddppq.com/pytorch/pytorch/build/aten/src/ATen/) kernels for [PyTorch\u2019s ATen Operators](https://pytorch.org/cppdocs/): If a PyTorch Operator is not needed by a model targeted at a selectively built runtime, then the registration of that CPU kernel is omitted in the runtime. This is controlled via [Torchgen code-gen](https://github.com/pytorch/pytorch/blob/master/torchgen/gen.py).\n2. [Primary Operators](https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/runtime/register_prim_ops.cpp): This is controlled by a macro named [TORCH_SELECTIVE_SCHEMA](https://codebrowser.bddppq.com/pytorch/pytorch/torch/library.h.html) (via templated selective build) that either selects a primary operator or de-selects it based on information in a generated header file.\n3. Code that handles [specific dtypes](https://codebrowser.bddppq.com/pytorch/pytorch/aten/src/ATen/Dispatch.h.html) in CPU kernels: This is performed by generating exception throws in specific case statements in the switch case generated by the macro [AT_PRIVATE_CHECK_SELECTIVE_BUILD](https://codebrowser.bddppq.com/pytorch/pytorch/aten/src/ATen/Dispatch.h.html#_M/AT_PRIVATE_CHECK_SELECTIVE_BUILD).\n4. Registration of [Custom C++ Classes](https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html) that extend PyTorch: This is controlled by the macro [TORCH_SELECTIVE_CLASS](https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/quantized/cpu/fbgemm_utils.cpp#L385-L386), which can be used when registering Custom C++ Classes. The [torch::selective_class_<>](https://github.com/pytorch/pytorch/blob/master/torch/custom_class.h#L443-L460) helper is to be used in conjunction with the macro [TORCH_SELECTIVE_CLASS](https://codebrowser.bddppq.com/pytorch/pytorch/torch/library.h.html#_M/TORCH_SELECTIVE_CLASS).", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "### What is the structure of the YAML file used during the build?\n\nThe YAML file generated after tracing looks like the example below. It encodes all the elements of the \u201cselectable\u201d build feature as specified above.\n\n```python\ninclude_all_non_op_selectives: false\nbuild_features: []\noperators:\n aten::add.Tensor:\n is_used_for_training: false\n is_root_operator: true\n include_all_overloads: false\n aten::len.t:\n is_used_for_training: false\n is_root_operator: true\n include_all_overloads: false\nkernel_metadata:\n _local_scalar_dense_cpu:\n - Float\n add_stub:\n - Float\n copy_:\n - Bool\n - Byte\n mul_cpu:\n - Float\ncustom_classes: []\n```\n\n### How exactly is code eliminated from the generated binary?\n\nDepending on the specific scenario, there are 2 main techniques that are used to hint the compiler and linker about unused and unreachable code. This code is then cleaned up by the compiler or linker as unreachable code.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "#### [1] Unreferenced functions removed by the Linker\n\nWhen a function that isn\u2019t transitively referenced from any visible function is present in the compiled object files that are being linked together, the linker will remove it (if the right build flags are provided). This is leveraged in 2 scenarios by the selective build system.\n\n##### Kernel Registration in the Dispatcher\n\nIf an operator\u2019s kernel isn\u2019t needed, then it isn\u2019t registered with the dispatcher. An unregistered kernel means that the function is unreachable, and it will be removed by the linker.\n\n##### Templated Selective Build\n\nThe general idea here is that a class template specialization is used to select a class that either captures a reference to a function or not (depending on whether it\u2019s used) and the linker can come along and clean out the unreferenced function.\n\nFor example, in the code below, there\u2019s no reference to the function \u201c`fn2`\u201d, so it will be cleaned up by the linker since it\u2019s not referenced anywhere.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "```python\n#include
\n#include \n\ntemplate \nstruct FunctionSelector {\n T fn_;\n FunctionSelector(T fn): fn_(fn) {}\n T get() { return this->fn_; }\n};\n\n// The \"false\" specialization of this class does NOT retain the argument passed\n// to the class constructor, which means that the function pointer passed in\n// is considered to be unreferenced in the program (unless it is referenced\n// elsewhere).\ntemplate \nstruct FunctionSelector {\n FunctionSelector(T) {}\n};\n\ntemplate \nFunctionSelector make_function_selector_true(T fn) {\n return FunctionSelector(fn);\n}\n\ntemplate \nFunctionSelector make_function_selector_false(T fn) {\n return FunctionSelector(fn);\n}\n\ntypedef void(*fn_ptr_type)();\n\nstd::vector fns;\n\ntemplate \nvoid add_fn(FunctionSelector fs) {\n fns.push_back(fs.get());\n}", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "template \nvoid add_fn(FunctionSelector) {\n // Do nothing.\n}\n\n// fn1 will be kept by the linker since it is added to the vector \"fns\" at\n// runtime.\nvoid fn1() {\n printf(\"fn1\\n\");\n}\n\n// fn2 will be removed by the linker since it isn't referenced at all.\nvoid fn2() {\n printf(\"fn2\\n\");\n}\n\nint main() {\n add_fn(make_function_selector_true(fn1));\n add_fn(make_function_selector_false(fn2));\n}\n```\n\n#### [2] Dead Code Eliminated by the Compiler\n\nC++ Compilers can detect dead ([unreachable](https://en.wikipedia.org/wiki/Unreachable_code)) code by analyzing the code\u2019s control flow statically. For example, if there\u2019s a code-path that comes after an **unconditional exception throw**, then all the code after it will be marked as dead code and not converted to object code by the compiler. Typically, compilers require the use of the `-fdce` flag to eliminate dead code.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "In the example below, you can see that the C++ code on the left (in the red boxes) doesn\u2019t have any corresponding generated object code on the right.\n\n\n
\n
\n\n\n Figure 4: Dead Code Elimination by C++ Compilers\n
\n\nThis property is leveraged in the bodies of PyTorch kernel implementations that have a lot of repeated code to handle multiple dtypes of a Tensor. A [dtype](https://pytorch.org/docs/stable/tensor_attributes.html) is the underlying data-type that the Tensor stores elements of. This can be one of float, double, int64, bool, int8, etc\u2026\n\nAlmost every PyTorch CPU kernel uses a macro of the form AT_DISPATCH_ALL_TYPES* that is used to substitute some code specialized for every dtype that the kernel needs to handle. For example:", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "```python\nAT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(\n kBool, kHalf, kBFloat16, dtype, \"copy_kernel\", [&] {\n cpu_kernel_vec(\n iter,\n [=](scalar_t a) -> scalar_t { return a; },\n [=](Vectorized a) -> Vectorized { return a; });\n});\n```\n\nThe macro `AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3` internally has a switch-case statement that looks like the code in Figure-4 above. The tracing process records the dtypes triggered for the kernel tag \"`copy_kernel`\" and the build process processes these tags and inserts `throw` statements in every `case` statement that is handling the dtype that isn\u2019t required for this kernel tag.\n\nThis is how dtype selectivity is implemented in PyTorch\u2019s Tracing Based Selective Build.\n\n## Conclusion\n\nTracing Based Selective Build is a practical and scalable approach to selecting only the used parts of an application to retain code that static analysis can not detect. This code is usually extremely data/input dependent in nature.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
-{"page_content": "This article provides detailed insights into how Tracing Based Selective Build works under the hood, and the technical details related to its implementation. These techniques can also be applied to other applications and situations that can benefit from reduced binary size.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "## Why is this important for app developers?\n\nUsing a PyTorch runtime generated by **selective build** can reduce the size of AI-powered apps by 30+ MB - a significant reduction for a typical mobile app! Making mobile applications more lightweight has many benefits - they are runnable on a wider variety of devices, consume less cellular data, and can be downloaded and updated faster on user\u2019s devices.\n\n## What does the Developer Experience look like?\n\nThis method can work seamlessly with any existing PyTorch Mobile deployment workflows. All you need to do is replace the general PyTorch runtime library with a runtime customized for the specific models you wish to use in your application. The general steps in this process are:\n\n1. Build the PyTorch Runtime in **instrumentation mode** (this is called an **instrumentation build** of PyTorch). This will record the used operators, kernels and features.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "2. Run your models through this instrumentation build by using the provided **model_tracer** binary. This will generate a single YAML file that stores all the features used by your model. These features will be preserved in the minimal runtime.\n3. Build PyTorch using this YAML file as input. This is the **selective build** technique, and it greatly reduces the size of the final PyTorch binary.\n4. Use this selectively-built PyTorch library to reduce the size of your mobile application!\n\n\nBuilding the PyTorch Runtime in a special **\u201cinstrumentation\u201d mode** ( by passing the `TRACING_BASED=1` build option) generates an **instrumentation build** runtime of PyTorch, along with a **model_tracer** binary. Running a model with this build allows us to trace the parts of PyTorch used by the model.\n\n\n
\n
\n\n\n Figure 1: Instrumentation build of PyTorch\n
\n\n```python", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "\n\n```python\n# Clone the PyTorch repo\ngit clone https://github.com/pytorch/pytorch.git\ncd pytorch\n\n# Build the model_tracer\nUSE_NUMPY=0 USE_DISTRIBUTED=0 USE_CUDA=0 TRACING_BASED=1 \\\n python setup.py develop\n```\n\nNow this instrumentation build is used to run a model inference with representative inputs. The **model_tracer** binary observes parts of the instrumentation build that were activated during the inference run, and dumps it to a YAML file.\n\n\n
\n
\n\n\n Figure 2: YAML file generated by running model(s) on an instrumentation build\n
\n\n```python\n# Generate YAML file\n./build/bin/model_tracer \\\n --model_input_path /tmp/path_to_model.ptl \\\n --build_yaml_path /tmp/selected_ops.yaml\n```", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "--build_yaml_path /tmp/selected_ops.yaml\n```\n\nNow we build the PyTorch Runtime again, but this time using the YAML file generated by the tracer. The runtime now only includes those parts that are needed for this model. This is called **\u201cSelectively built PyTorch runtime\u201d** in the diagram below.\n\n```python\n# Clean out cached configuration\nmake clean\n\n# Build PyTorch using Selected Operators (from the YAML file)\n# using the host toolchain, and use this generated library\nBUILD_PYTORCH_MOBILE_WITH_HOST_TOOLCHAIN=1 \\\nUSE_LIGHTWEIGHT_DISPATCH=0 \\\nBUILD_LITE_INTERPRETER=1 \\\nSELECTED_OP_LIST=/tmp/selected_ops.yaml \\\nTRACING_BASED=1 \\\n ./scripts/build_mobile.sh\n```\n\n\n
\n
\n\n\n Figure 3: Selective Build of PyTorch and model execution on a selectively built PyTorch runtime\n
\n\n### Show me the code!", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "\n\n### Show me the code!\n\nWe\u2019ve put together a [notebook](https://gist.github.com/dhruvbird/65fd800983f362a72d78afe68031568c) to illustrate what the process above looks like in code using a simple PyTorch model. \n\nFor a more hands-on tutorial to deploy this on Android/iOS [this tutorial](https://pytorch.org/tutorials/prototype/tracing_based_selective_build.html) should be helpful.\n\n## Technical FAQs\n\n### Why is Tracing needed for a Selective Build of PyTorch?\n\nIn PyTorch, CPU kernels can call other operators via the [PyTorch Dispatcher](http://blog.ezyang.com/2020/09/lets-talk-about-the-pytorch-dispatcher/). Simply including the set of root operators called directly by the model is not sufficient as there might be many more being called under-the-hood transitively. Running the model on representative inputs and observing the actual list of operators called (aka \u201ctracing\u201d) is the most accurate way of determining what parts of PyTorch are used.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "Additionally, factors such as which dtypes a kernel should handle are also runtime features that depend on actual input provided to the model. Hence, the tracing mechanism is extremely suitable for this purpose.\n\n### Which features can be selected (in or out) by using Tracing Based Selective Build?\n\nThe following features can be selected for the PyTorch runtime during the tracing based selective build process:\n\n1. [CPU/QuantizedCPU](https://codebrowser.bddppq.com/pytorch/pytorch/build/aten/src/ATen/) kernels for [PyTorch\u2019s ATen Operators](https://pytorch.org/cppdocs/): If a PyTorch Operator is not needed by a model targeted at a selectively built runtime, then the registration of that CPU kernel is omitted in the runtime. This is controlled via [Torchgen code-gen](https://github.com/pytorch/pytorch/blob/master/torchgen/gen.py).", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "2. [Primary Operators](https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/runtime/register_prim_ops.cpp): This is controlled by a macro named [TORCH_SELECTIVE_SCHEMA](https://codebrowser.bddppq.com/pytorch/pytorch/torch/library.h.html) (via templated selective build) that either selects a primary operator or de-selects it based on information in a generated header file.\n3. Code that handles [specific dtypes](https://codebrowser.bddppq.com/pytorch/pytorch/aten/src/ATen/Dispatch.h.html) in CPU kernels: This is performed by generating exception throws in specific case statements in the switch case generated by the macro [AT_PRIVATE_CHECK_SELECTIVE_BUILD](https://codebrowser.bddppq.com/pytorch/pytorch/aten/src/ATen/Dispatch.h.html#_M/AT_PRIVATE_CHECK_SELECTIVE_BUILD).", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "4. Registration of [Custom C++ Classes](https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html) that extend PyTorch: This is controlled by the macro [TORCH_SELECTIVE_CLASS](https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/quantized/cpu/fbgemm_utils.cpp#L385-L386), which can be used when registering Custom C++ Classes. The [torch::selective_class_<>](https://github.com/pytorch/pytorch/blob/master/torch/custom_class.h#L443-L460) helper is to be used in conjunction with the macro [TORCH_SELECTIVE_CLASS](https://codebrowser.bddppq.com/pytorch/pytorch/torch/library.h.html#_M/TORCH_SELECTIVE_CLASS).\n\n### What is the structure of the YAML file used during the build?\n\nThe YAML file generated after tracing looks like the example below. It encodes all the elements of the \u201cselectable\u201d build feature as specified above.\n\n```python\ninclude_all_non_op_selectives: false\nbuild_features: []\noperators:\n aten::add.Tensor:\n is_used_for_training: false\n is_root_operator: true", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "is_root_operator: true\n include_all_overloads: false\n aten::len.t:\n is_used_for_training: false\n is_root_operator: true\n include_all_overloads: false\nkernel_metadata:\n _local_scalar_dense_cpu:\n - Float\n add_stub:\n - Float\n copy_:\n - Bool\n - Byte\n mul_cpu:\n - Float\ncustom_classes: []\n```\n\n### How exactly is code eliminated from the generated binary?\n\nDepending on the specific scenario, there are 2 main techniques that are used to hint the compiler and linker about unused and unreachable code. This code is then cleaned up by the compiler or linker as unreachable code.\n\n#### [1] Unreferenced functions removed by the Linker\n\nWhen a function that isn\u2019t transitively referenced from any visible function is present in the compiled object files that are being linked together, the linker will remove it (if the right build flags are provided). This is leveraged in 2 scenarios by the selective build system.\n\n##### Kernel Registration in the Dispatcher", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "##### Kernel Registration in the Dispatcher\n\nIf an operator\u2019s kernel isn\u2019t needed, then it isn\u2019t registered with the dispatcher. An unregistered kernel means that the function is unreachable, and it will be removed by the linker.\n\n##### Templated Selective Build\n\nThe general idea here is that a class template specialization is used to select a class that either captures a reference to a function or not (depending on whether it\u2019s used) and the linker can come along and clean out the unreferenced function.\n\nFor example, in the code below, there\u2019s no reference to the function \u201c`fn2`\u201d, so it will be cleaned up by the linker since it\u2019s not referenced anywhere.\n\n```python\n#include \n#include \n\ntemplate \nstruct FunctionSelector {\n T fn_;\n FunctionSelector(T fn): fn_(fn) {}\n T get() { return this->fn_; }\n};\n\n// The \"false\" specialization of this class does NOT retain the argument passed\n// to the class constructor, which means that the function pointer passed in", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "// is considered to be unreferenced in the program (unless it is referenced\n// elsewhere).\ntemplate \nstruct FunctionSelector {\n FunctionSelector(T) {}\n};\n\ntemplate \nFunctionSelector make_function_selector_true(T fn) {\n return FunctionSelector(fn);\n}\n\ntemplate \nFunctionSelector make_function_selector_false(T fn) {\n return FunctionSelector(fn);\n}\n\ntypedef void(*fn_ptr_type)();\n\nstd::vector fns;\n\ntemplate \nvoid add_fn(FunctionSelector fs) {\n fns.push_back(fs.get());\n}\n\ntemplate \nvoid add_fn(FunctionSelector) {\n // Do nothing.\n}\n\n// fn1 will be kept by the linker since it is added to the vector \"fns\" at\n// runtime.\nvoid fn1() {\n printf(\"fn1\\n\");\n}\n\n// fn2 will be removed by the linker since it isn't referenced at all.\nvoid fn2() {\n printf(\"fn2\\n\");\n}\n\nint main() {\n add_fn(make_function_selector_true(fn1));\n add_fn(make_function_selector_false(fn2));", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "add_fn(make_function_selector_false(fn2));\n}\n```\n\n#### [2] Dead Code Eliminated by the Compiler\n\nC++ Compilers can detect dead ([unreachable](https://en.wikipedia.org/wiki/Unreachable_code)) code by analyzing the code\u2019s control flow statically. For example, if there\u2019s a code-path that comes after an **unconditional exception throw**, then all the code after it will be marked as dead code and not converted to object code by the compiler. Typically, compilers require the use of the `-fdce` flag to eliminate dead code.\n\nIn the example below, you can see that the C++ code on the left (in the red boxes) doesn\u2019t have any corresponding generated object code on the right.\n\n\n
\n
\n\n\n Figure 4: Dead Code Elimination by C++ Compilers\n
", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "\n\nThis property is leveraged in the bodies of PyTorch kernel implementations that have a lot of repeated code to handle multiple dtypes of a Tensor. A [dtype](https://pytorch.org/docs/stable/tensor_attributes.html) is the underlying data-type that the Tensor stores elements of. This can be one of float, double, int64, bool, int8, etc\u2026\n\nAlmost every PyTorch CPU kernel uses a macro of the form AT_DISPATCH_ALL_TYPES* that is used to substitute some code specialized for every dtype that the kernel needs to handle. For example:\n\n```python\nAT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(\n kBool, kHalf, kBFloat16, dtype, \"copy_kernel\", [&] {\n cpu_kernel_vec(\n iter,\n [=](scalar_t a) -> scalar_t { return a; },\n [=](Vectorized a) -> Vectorized { return a; });\n});\n```", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
+{"page_content": "});\n```\n\nThe macro `AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3` internally has a switch-case statement that looks like the code in Figure-4 above. The tracing process records the dtypes triggered for the kernel tag \"`copy_kernel`\" and the build process processes these tags and inserts `throw` statements in every `case` statement that is handling the dtype that isn\u2019t required for this kernel tag.\n\nThis is how dtype selectivity is implemented in PyTorch\u2019s Tracing Based Selective Build.\n\n## Conclusion\n\nTracing Based Selective Build is a practical and scalable approach to selecting only the used parts of an application to retain code that static analysis can not detect. This code is usually extremely data/input dependent in nature.\n\nThis article provides detailed insights into how Tracing Based Selective Build works under the hood, and the technical details related to its implementation. These techniques can also be applied to other applications and situations that can benefit from reduced binary size.", "metadata": {"source": "https://pytorch.org/blog/pytorchs-tracing-based-selective-build/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"PyTorch & OpenXLA: The Path Forward\"\nauthor: Milad Mohammadi, Jack Cao, Shauheen Zahirazami, Joe Spisak, and Jiewen Tan \n---\n\nAs we celebrate the release of [OpenXLA](https://opensource.googleblog.com/2023/03/openxla-is-ready-to-accelerate-and-simplify-ml-development.html), [PyTorch 2.0](https://pytorch.org/blog/pytorch-2.0-release/), and [PyTorch/XLA 2.0](https://pytorch.org/blog/pytorch-2.0-xla/), it\u2019s worth taking a step back and sharing where we see it all going in the short to medium term. With PyTorch adoption leading in the AI space and XLA supporting best-in-class compiler features, PyTorch/XLA is well positioned to provide a cutting edge development stack for both model training and inference. To achieve this, we see investments in three main areas:", "metadata": {"source": "https://pytorch.org/blog/pytorch-2.0-xla-path-forward/", "category": "pytorch blogs"}}
-{"page_content": "* **Training Large Models** - Large language models (LLM) and diffusion models have quickly risen in popularity and many cutting edge applications today are built on them. Further to this, training these models requires scale and more specifically the ability to train across thousands of accelerators. To achieve this we are investing in features such as AMP for mixed precision training, PjRt for increased runtime performance, SPMD / FSDP for efficient model sharding, Dynamic Shapes to enable new research approaches, faster data loading through Ray and tf.data, and a toolchain that packages all of these features together into a seamless workflow. Some of these features are already available in experimental or beta stages, and others are coming up this year with many heavily leveraging the underlying OpenXLA compiler stack.\n* **Model Inference** - With large models continuing to grow in size and computational cost, deployment becomes the next challenge as these models continue to find their way into applications. With the introduction of Dynamo in the PyTorch 2.0 release, PyTorch/XLA delivers performance competitive inference. We are, however, incorporating additional inference-oriented including model serving support, Dynamo for sharded large models, quantization via Torch.Export and StableHLO.\n* **Ecosystem integration** - We are expanding integration with [Hugging Face](https://huggingface.co/) and [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/) so users can take advantage of upcoming PyTorch/XLA cutting edge features (e.g. FSDP support in Hugging Face) and the downstream OpenXLA features (e.g. Quantization) through familiar APIs.", "metadata": {"source": "https://pytorch.org/blog/pytorch-2.0-xla-path-forward/", "category": "pytorch blogs"}}
+{"page_content": "* **Training Large Models** - Large language models (LLM) and diffusion models have quickly risen in popularity and many cutting edge applications today are built on them. Further to this, training these models requires scale and more specifically the ability to train across thousands of accelerators. To achieve this we are investing in features such as AMP for mixed precision training, PjRt for increased runtime performance, SPMD / FSDP for efficient model sharding, Dynamic Shapes to enable new research approaches, faster data loading through Ray and tf.data, and a toolchain that packages all of these features together into a seamless workflow. Some of these features are already available in experimental or beta stages, and others are coming up this year with many heavily leveraging the underlying OpenXLA compiler stack.", "metadata": {"source": "https://pytorch.org/blog/pytorch-2.0-xla-path-forward/", "category": "pytorch blogs"}}
+{"page_content": "* **Model Inference** - With large models continuing to grow in size and computational cost, deployment becomes the next challenge as these models continue to find their way into applications. With the introduction of Dynamo in the PyTorch 2.0 release, PyTorch/XLA delivers performance competitive inference. We are, however, incorporating additional inference-oriented including model serving support, Dynamo for sharded large models, quantization via Torch.Export and StableHLO.\n* **Ecosystem integration** - We are expanding integration with [Hugging Face](https://huggingface.co/) and [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/) so users can take advantage of upcoming PyTorch/XLA cutting edge features (e.g. FSDP support in Hugging Face) and the downstream OpenXLA features (e.g. Quantization) through familiar APIs.", "metadata": {"source": "https://pytorch.org/blog/pytorch-2.0-xla-path-forward/", "category": "pytorch blogs"}}
{"page_content": "Additionally, PyTorch/XLA is set to migrate to the open source [OpenXLA](https://github.com/openxla) as its default downstream compiler; allowing the PyTorch community to gain access to a leading, framework-agnostic compiler stack that enjoys industry-wide contribution and innovation. To achieve this, we will begin supporting StableHLO. As a result, OpenXLA will replace the existing TF:XLA dependency, overall streamlining the dependencies and creating leverage from the broader compiler ecosystem. PyTorch/XLA will also sunset the XRT runtime after migration. You can see the resulting high level stack below with the TensorFlow dependency stricken out:\n\n{:style=\"max-height:800px; width:100%\"} \n\n**Figure:** the upcoming PyTorch/XLA features and integrations are illustrated here", "metadata": {"source": "https://pytorch.org/blog/pytorch-2.0-xla-path-forward/", "category": "pytorch blogs"}}
{"page_content": "We cannot be more excited about what\u2019s ahead for PyTorch/XLA and invite the community to join us. PyTorch/XLA is developed fully in open source so please file issues, submit pull requests, and send RFCs to [GitHub](https://github.com/pytorch/xla) such that we can openly collaborate. You can also [try out](https://colab.sandbox.google.com/github/pytorch/xla/blob/master/contrib/colab/getting-started.ipynb) PyTorch/XLA for yourself on various XLA devices including TPUs and GPUs.\n\nCheers, \nThe PyTorch/XLA Team at Google", "metadata": {"source": "https://pytorch.org/blog/pytorch-2.0-xla-path-forward/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Scaling Multimodal Foundation Models in TorchMultimodal with Pytorch Distributed\"\nauthor: Ankita De, Edward Wang (EcoF), Rohan Varma, Anjali Sridhar, Kartikay Khandelwal\nfeatured-img: \"/assets/images/scaling-multimodal-image1-diagram-of-multimodal-flava-new.png\"\n---\n\n## Introduction", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "## Introduction\n\nIn recent years, scaling model sizes has become a promising area of research. In the field of NLP, language models have gone from hundreds of millions of parameters (BERT) to hundreds of billions of parameters (GPT-3) demonstrating significant improvements on downstream tasks. The [scaling laws](https://arxiv.org/pdf/2001.08361.pdf) for large scale language models have also been studied extensively in the industry. A similar trend can be observed in the vision field, with the community moving to transformer based models (like [Vision Transformer](https://arxiv.org/pdf/2010.11929.pdf), [Masked Auto Encoders](https://arxiv.org/pdf/2111.06377.pdf)) as well. It is clear that individual modalities - text, image, video - have benefited massively from recent advancements in scale, and frameworks have quickly adapted to accommodate larger models.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "---\n\n## Introduction\n\nIn recent years, scaling model sizes has become a promising area of research. In the field of NLP, language models have gone from hundreds of millions of parameters (BERT) to hundreds of billions of parameters (GPT-3) demonstrating significant improvements on downstream tasks. The [scaling laws](https://arxiv.org/pdf/2001.08361.pdf) for large scale language models have also been studied extensively in the industry. A similar trend can be observed in the vision field, with the community moving to transformer based models (like [Vision Transformer](https://arxiv.org/pdf/2010.11929.pdf), [Masked Auto Encoders](https://arxiv.org/pdf/2111.06377.pdf)) as well. It is clear that individual modalities - text, image, video - have benefited massively from recent advancements in scale, and frameworks have quickly adapted to accommodate larger models.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "At the same time, multimodality is becoming increasingly important in research with tasks like image-text retrieval, visual question-answering, visual dialog and text to image generation gaining traction in real world applications. Training large scale multimodal models is the natural next step and we already see several efforts in this area like [CLIP](https://openai.com/blog/clip/) from OpenAI, [Parti](https://parti.research.google/) from Google and [CM3](https://arxiv.org/pdf/2201.07520.pdf) from Meta.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "In this blog, we present a case study demonstrating the scaling of [FLAVA](https://flava-model.github.io/) to 10B params using techniques from PyTorch Distributed. FLAVA is a vision and language foundation model, available in [TorchMultimodal](https://github.com/facebookresearch/multimodal/tree/main/torchmultimodal/models/flava), which has shown competitive performance on both unimodal and multimodal benchmarks. We also give the relevant code pointers in this blog. The instructions for running an example script to scale FLAVA can be found [here](https://github.com/facebookresearch/multimodal/tree/main/examples/flava/native).\n\n## Scaling FLAVA Overview", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "## Scaling FLAVA Overview\n\nFLAVA is a foundation multimodal model which consists of transformer based image and text encoders followed by a transformer-based multimodal fusion module. It is pretrained on both unimodal and multimodal data with a diverse set of losses. This includes masked language, image and multimodal modeling losses that require the model to reconstruct the original input from its context (self-supervised learning). It also uses image text matching loss over positive and negative examples of aligned image-text pairs as well as CLIP style contrastive loss. In addition to multimodal tasks (like image-text retrieval), FLAVA demonstrated competitive performance on unimodal benchmarks as well (GLUE tasks for NLP and image classification for vision).\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "The original FLAVA model has ~350M parameters and uses ViT-B16 configurations (from the [Vision Transformer paper](https://arxiv.org/pdf/2010.11929.pdf)) for image and text encoders. The multimodal fusion transformer follows the unimodal encoders but with half the number of layers. We explore increasing the size of each encoder to larger ViT variants. \n\nAnother aspect of scaling is adding the ability to increase the batch size. FLAVA makes use of contrastive loss over in-batch negatives, which typically benefits from large batch size (as studied [here](https://openreview.net/pdf?id=U2exBrf_SJh)). The largest training efficiency or throughput is also generally achieved when operating near maximum possible batch sizes as determined by the amount of GPU memory available (also see the experiments section). \n\nThe following table displays the different model configurations we experimented with. We also determine the maximum batch size that was able to fit in memory for each configuration in the experiments section.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "| Approx Model params | Hidden size | MLP size | Heads | Unimodal layers | Multimodal layers | Model size (fp32) |\n|-----------------------|---------------|----------|---------|-------------------|---------------------|---------------------|\n| 350M (original) | 768 | 3072 | 12 | 12 | 6 | 1.33GB |\n| 900M | 1024 | 4096 | 16 | 24 | 12 | 3.48GB |\n| 1.8B | 1280 | 5120 | 16 | 32 | 16 | 6.66GB |\n| 2.7B | 1408 | 6144 | 16 | 40 | 20 | 10.3GB |\n| 4.8B | 1664 | 8192 | 16 | 48 | 24 | 18.1GB |\n| 10B | 2048 | 10240 | 16 | 64 | 40 | 38GB |", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "## Optimization overview\n\nPyTorch offers several native techniques to efficiently scale models. In the following sections, we go over some of these techniques and show how they can be applied to scale up a FLAVA model to 10 billion parameters.\n\n## Distributed Data Parallel\n\nA common starting point for distributed training is data parallelism. Data parallelism replicates the model across each worker (GPU), and partitions the dataset across the workers. Different workers process different data partitions in parallel and synchronize their gradients (via all reduce) before model weights are updated. The figure below showcases the flow (forward, backward, and weight update steps) for processing a single example for data parallelism:\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "\n Source: https://engineering.fb.com/2021/07/15/open-source/fsdp/\n
\n\nPyTorch provides a native API, [DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) (DDP) to enable data parallelism which can be used as a module wrapper as showcased below. Please see PyTorch Distributed [documentation](https://pytorch.org/docs/stable/distributed.html#) for more details.\n\n```Python\nfrom torchmultimodal.models.flava.model import flava_model_for_pretraining\nimport torch\nimport torch.distributed as dist\n\nmodel = flava_model_for_pretraining().cuda()\n# Initialize PyTorch Distributed process groups\n# Please see https://pytorch.org/tutorials/intermediate/dist_tuto.html for details\ndist.init_process_group(backend=\u201dnccl\u201d)\n# Wrap model in DDP\nmodel = torch.nn.parallel.DistributedDataParallel(model, device_ids=[torch.cuda.current_device()])\n```\n\n## Fully Sharded Data Parallel", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "## Fully Sharded Data Parallel\n\nGPU memory usage of a training application can roughly be broken down into model inputs, intermediate activations (needed for gradient computation), model parameters, gradients, and optimizer states. Scaling a model will typically increase each of these elements. Scaling a model with DDP can eventually result in out-of-memory issues when a single GPU's memory becomes insufficient since it replicates the parameters, gradients, and optimizer states on all workers.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "To reduce this replication and save GPU memory, we can shard the model parameters, gradients, and optimizer states across all workers with each worker only managing a single shard. This technique was popularized by the [ZeRO-3](https://arxiv.org/abs/1910.02054) approach developed by Microsoft. A PyTorch-native implementation of this approach is available as [FullyShardedDataParallel](https://pytorch.org/docs/stable/fsdp.html) (FSDP) API, released as a beta feature in PyTorch 1.12. During a module\u2019s forward and backward passes, FSDP unshards the model parameters as needed for computation (using all-gather) and reshards them after computation. It synchronizes gradients using the reduce-scatter collective to ensure sharded gradients are globally averaged. The forward and backward pass flow of a model wrapped in FSDP are detailed below:\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "\n Source: https://engineering.fb.com/2021/07/15/open-source/fsdp/\n
\n\nTo use FSDP, the submodules of a model need to be wrapped with the API to control when specific submodules are sharded or unsharded. FSDP provides an auto-wrapping API (see the [auto_wrap_policy](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel) argument) that can be used out of the box as well as several [wrapping policies](https://github.com/pytorch/pytorch/blob/master/torch/distributed/fsdp/wrap.py) and the ability to [write your own policy](https://github.com/pytorch/pytorch/blob/75c0e3a471c19b883feca15fd4ecfabedf746691/torch/distributed/fsdp/fully_sharded_data_parallel.py#L858).", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "\n\nThe original FLAVA model has ~350M parameters and uses ViT-B16 configurations (from the [Vision Transformer paper](https://arxiv.org/pdf/2010.11929.pdf)) for image and text encoders. The multimodal fusion transformer follows the unimodal encoders but with half the number of layers. We explore increasing the size of each encoder to larger ViT variants. \n\nAnother aspect of scaling is adding the ability to increase the batch size. FLAVA makes use of contrastive loss over in-batch negatives, which typically benefits from large batch size (as studied [here](https://openreview.net/pdf?id=U2exBrf_SJh)). The largest training efficiency or throughput is also generally achieved when operating near maximum possible batch sizes as determined by the amount of GPU memory available (also see the experiments section).", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "The following table displays the different model configurations we experimented with. We also determine the maximum batch size that was able to fit in memory for each configuration in the experiments section.\n\n| Approx Model params | Hidden size | MLP size | Heads | Unimodal layers | Multimodal layers | Model size (fp32) |\n|-----------------------|---------------|----------|---------|-------------------|---------------------|---------------------|\n| 350M (original) | 768 | 3072 | 12 | 12 | 6 | 1.33GB |\n| 900M | 1024 | 4096 | 16 | 24 | 12 | 3.48GB |\n| 1.8B | 1280 | 5120 | 16 | 32 | 16 | 6.66GB |\n| 2.7B | 1408 | 6144 | 16 | 40 | 20 | 10.3GB |", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "| 4.8B | 1664 | 8192 | 16 | 48 | 24 | 18.1GB |\n| 10B | 2048 | 10240 | 16 | 64 | 40 | 38GB |\n\n## Optimization overview\n\nPyTorch offers several native techniques to efficiently scale models. In the following sections, we go over some of these techniques and show how they can be applied to scale up a FLAVA model to 10 billion parameters.\n\n## Distributed Data Parallel\n\nA common starting point for distributed training is data parallelism. Data parallelism replicates the model across each worker (GPU), and partitions the dataset across the workers. Different workers process different data partitions in parallel and synchronize their gradients (via all reduce) before model weights are updated. The figure below showcases the flow (forward, backward, and weight update steps) for processing a single example for data parallelism:\n\n", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "
\n
\n
\n\n\n Source: https://engineering.fb.com/2021/07/15/open-source/fsdp/\n
\n\nPyTorch provides a native API, [DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) (DDP) to enable data parallelism which can be used as a module wrapper as showcased below. Please see PyTorch Distributed [documentation](https://pytorch.org/docs/stable/distributed.html#) for more details.\n\n```Python\nfrom torchmultimodal.models.flava.model import flava_model_for_pretraining\nimport torch\nimport torch.distributed as dist\n\nmodel = flava_model_for_pretraining().cuda()\n# Initialize PyTorch Distributed process groups\n# Please see https://pytorch.org/tutorials/intermediate/dist_tuto.html for details\ndist.init_process_group(backend=\u201dnccl\u201d)\n# Wrap model in DDP", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "# Wrap model in DDP\nmodel = torch.nn.parallel.DistributedDataParallel(model, device_ids=[torch.cuda.current_device()])\n```\n\n## Fully Sharded Data Parallel\n\nGPU memory usage of a training application can roughly be broken down into model inputs, intermediate activations (needed for gradient computation), model parameters, gradients, and optimizer states. Scaling a model will typically increase each of these elements. Scaling a model with DDP can eventually result in out-of-memory issues when a single GPU's memory becomes insufficient since it replicates the parameters, gradients, and optimizer states on all workers.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "To reduce this replication and save GPU memory, we can shard the model parameters, gradients, and optimizer states across all workers with each worker only managing a single shard. This technique was popularized by the [ZeRO-3](https://arxiv.org/abs/1910.02054) approach developed by Microsoft. A PyTorch-native implementation of this approach is available as [FullyShardedDataParallel](https://pytorch.org/docs/stable/fsdp.html) (FSDP) API, released as a beta feature in PyTorch 1.12. During a module\u2019s forward and backward passes, FSDP unshards the model parameters as needed for computation (using all-gather) and reshards them after computation. It synchronizes gradients using the reduce-scatter collective to ensure sharded gradients are globally averaged. The forward and backward pass flow of a model wrapped in FSDP are detailed below:\n\n\n
\n
\n\n", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\n Source: https://engineering.fb.com/2021/07/15/open-source/fsdp/\n
\n\nTo use FSDP, the submodules of a model need to be wrapped with the API to control when specific submodules are sharded or unsharded. FSDP provides an auto-wrapping API (see the [auto_wrap_policy](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel) argument) that can be used out of the box as well as several [wrapping policies](https://github.com/pytorch/pytorch/blob/master/torch/distributed/fsdp/wrap.py) and the ability to [write your own policy](https://github.com/pytorch/pytorch/blob/75c0e3a471c19b883feca15fd4ecfabedf746691/torch/distributed/fsdp/fully_sharded_data_parallel.py#L858).", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "The following example demonstrates wrapping the FLAVA model with FSDP. We specify the auto-wrapping policy as `transformer_auto_wrap_policy`. This will wrap individual transformer layers (`TransformerEncoderLayer`), the image transformer (`ImageTransformer`), text encoder (`BERTTextEncoder`) and multimodal encoder (`FLAVATransformerWithoutEmbeddings`) as individual FSDP units. This uses a recursive wrapping approach for efficient memory management. For example, after an individual transformer layer\u2019s forward or backward pass is finished, its parameters are discarded, freeing up memory thereby reducing peak memory usage.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "FSDP also provides a number of configurable options to tune the performance of applications. For example, in our use case, we illustrate the use of the new `limit_all_gathers` flag, which prevents all-gathering model parameters too early thereby alleviating memory pressure on the application. We encourage users to experiment with this flag which can potentially improve the performance of applications with high active memory usage.\n\n```Python\nimport torch\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\nfrom torch.distributed.fsdp.wrap import transformer_auto_wrap_policy\nfrom torchmultimodal.models.flava.model import flava_model_for_pretraining\nfrom torchmultimodal.models.flava.text_encoder import BertTextEncoder\nfrom torchmultimodal.models.flava.image_encoder import ImageTransformer\nfrom torchmultimodal.models.flava.transformer import FLAVATransformerWithoutEmbeddings\nfrom torchmultimodal.modules.layers.transformer import TransformerEncoderLayer", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "model = flava_model_for_pretraining().cuda()\ndist.init_process_group(backend=\u201dnccl\u201d)\n\nmodel = FSDP(\n model,\n device_id=torch.cuda.current_device(),\n auto_wrap_policy=partial(\n transformer_auto_wrap_policy,\n transformer_layer_cls={\n TransformerEncoderLayer,\n ImageTransformer,\n BERTTextEncoder,\n FLAVATransformerWithoutEmbeddings\n },\n ),\n limit_all_gathers=True,\n )\n```\n\n## Activation Checkpointing", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "## Activation Checkpointing\n\nAs discussed above, intermediate activations, model parameters, gradients, and optimizer states contribute to the overall GPU memory usage. FSDP can reduce memory consumption due to the latter three but does not reduce memory consumed by activations. Memory used by activations increases with increase in batch size or number of hidden layers. Activation checkpointing is a technique to decrease this memory usage by recomputing the activations during the backward pass instead of holding them in memory for a specific checkpointed module. For example, we observed ~4x reduction in the peak active memory after forward pass by applying activation checkpointing to the 2.7B parameter model.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": ")\n```\n\n## Activation Checkpointing\n\nAs discussed above, intermediate activations, model parameters, gradients, and optimizer states contribute to the overall GPU memory usage. FSDP can reduce memory consumption due to the latter three but does not reduce memory consumed by activations. Memory used by activations increases with increase in batch size or number of hidden layers. Activation checkpointing is a technique to decrease this memory usage by recomputing the activations during the backward pass instead of holding them in memory for a specific checkpointed module. For example, we observed ~4x reduction in the peak active memory after forward pass by applying activation checkpointing to the 2.7B parameter model.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "PyTorch offers a wrapper based activation checkpointing API. In particular, `checkpoint_wrapper` allows users to wrap an individual module with checkpointing, and `apply_activation_checkpointing` allows users to specify a policy with which to wrap modules within an overall module with checkpointing. Both these APIs can be applied to most models as they do not require any modifications to the model definition code. However, if more granular control over checkpointed segments, such as checkpointing specific functions within a module, is required, the functional `torch.utils.checkpoint` [API](https://pytorch.org/docs/stable/checkpoint.html) can be leveraged, although this requires modification to the model code. The application of the activation checkpointing wrapper to individual FLAVA transformer layers (denoted by `TransformerEncoderLayer`) is shown below. For a thorough description of activation checkpointing, please see the description in the [PyTorch documentation](https://pytorch.org/docs/stable/checkpoint.html).", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "```Python\nfrom torchmultimodal.models.flava.model import flava_model_for_pretraining\nfrom torch.distributed.algorithms._checkpoint.checkpoint_wrapper import apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl\nfrom torchmultimodal.modules.layers.transformer import TransformerEncoderLayer\n\nmodel = flava_model_for_pretraining()\ncheckpoint_tformer_layers_policy = lambda submodule: isinstance(submodule, TransformerEncoderLayer)\n\napply_activation_checkpointing(\n model,\n checkpoint_wrapper_fn=checkpoint_wrapper,\n check_fn=checkpoint_tformer_layers_policy,\n )\n```\nUsed together, wrapping FLAVA transformer layers with activation checkpointing and wrapping the overall model with FSDP as demonstrated above, we are able to scale FLAVA to 10B parameters.\n\n## Experiments", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "## Experiments\n\nWe conduct an empirical study about the impact of the different optimizations from the previous section on system performance. For all our experiments, we use a single node with 8 A100 40GB GPUs and run the pretraining for 1000 iterations. All runs also used PyTorch\u2019s [automatic mixed precision](https://pytorch.org/docs/stable/amp.html) with the bfloat16 data type. [TensorFloat32](https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) format is also enabled to improve matmul performance on the A100. We define throughput as the average number of items (text or image) processed per second (we ignore the first 100 iterations while measuring throughput to account for warmup). We leave training to convergence and its impact on downstream task metrics as an area for future study.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "Figure 1 plots the throughput for each model configuration and optimization, both with a local batch size of 8 and then with the maximum batch size possible on 1 node. Absence of a data point for a model variant for an optimization indicates that the model could not be trained on a single node.\n\nFigure 2 plots the maximum possible batch size per worker for each optimization. We observe a few things:", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "1. Scaling model size: DDP is only able to fit the 350M and 900M model on a node. With FSDP, due to memory savings, we are able to train ~3x bigger models compared to DDP (i.e. the 1.8B and 2.7B variants). Combining activation checkpointing (AC) with FSDP enables training even bigger models, on the order of ~10x compared to DDP (i.e. 4.8B and 10B variants)\n2. Throughput:\n - For smaller model sizes, at a constant batch size of 8, the throughput for DDP is slightly higher than or equal to FSDP, explainable by the additional communication required by FSDP. It is lowest for FSDP and AC combined together. This is because AC re-runs checkpointed forward passes during the backwards pass, trading off additional computation for memory savings. However, in the case of the 2.7B model, FSDP + AC actually has higher throughput compared to FSDP alone. This is because the 2.7B model with FSDP is operating close to the memory limit even at batch size 8 triggering CUDA malloc retries which tend to slow down training. AC helps with reducing the memory pressure and leads to no retries.\n - For DDP and FSDP + AC, the throughput increases with an increase in batch size for each model. For FSDP alone, this is true for smaller variants. However, with the 1.8B and 2.7B parameter models, we observe throughput degradation when increasing batch size. A potential reason for this, as noted above also, is that at the memory limit, PyTorch\u2019s CUDA memory management may have to retry cudaMalloc calls and/or run expensive defragmentation steps to find free memory blocks to handle the workload\u2019s memory requirements which can result in training slowdown.\n - For larger models that can only be trained with FSDP (1.8B, 2.7B, 4.8B) the setting with highest throughput achieved is with FSDP + AC scaling to the maximum batch size. For 10B, we observe nearly equal throughput for smaller and maximum batch size. This might be counterintuitive as AC results in increased computation and maxing out batch size potentially leads to expensive defragmentation operations due to operating at CUDA memory limit. However, for these large models, the increase in batch size is large enough to mask this overhead.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "\n
\n
\n\n\n Figure 1: Training throughput for different configurations\n
\n\n\n - Batch size: FSDP alone enables slightly higher batch sizes compared to DDP. Using FSDP + AC enables ~3x batch size compared to DDP for the 350M param model and ~5.5x for 900M param model. Even for 10B, a max batch size of ~20 which is fairly decent. This essentially enables larger global batch size using fewer GPUs which is especially useful for contrastive learning tasks.
\n
\n\n\n
\n
\n\n\n Figure 2: Max local batchsize possible for different configurations\n
\n\n## Conclusion", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "## Conclusion\n\nAs the world moves towards multimodal foundation models, scaling model parameters and efficient training is becoming an area of focus. The PyTorch ecosystem aims to accelerate innovation in this field by providing different tools to the research community, both for training and scaling multimodal models. With FLAVA, we laid out an example of scaling a model for multimodal understanding. In the future, we plan to add support for other kinds of models like the ones for multimodal generation and demonstrate their scaling factors. We also hope to automate many of these scaling and memory saving techniques (such as sharding and activation checkpointing) to reduce the amount of user experimentation needed to achieve the desired scale and maximum training throughput.\n\n## References", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
-{"page_content": "## References\n\n- [Introducing TorchMultimodal - a library for accelerating exploration in Multimodal AI](https://pytorch.org/blog/introducing-torchmultimodal/)\n- [FLAVA paper](https://deploy-preview-1186--pytorch-dot-org-preview.netlify.app/blog/introducing-torchmultimodal/)\n- [Introducing Pytorch FSDP](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/)", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "Figure 1 plots the throughput for each model configuration and optimization, both with a local batch size of 8 and then with the maximum batch size possible on 1 node. Absence of a data point for a model variant for an optimization indicates that the model could not be trained on a single node.\n\nFigure 2 plots the maximum possible batch size per worker for each optimization. We observe a few things:\n\n1. Scaling model size: DDP is only able to fit the 350M and 900M model on a node. With FSDP, due to memory savings, we are able to train ~3x bigger models compared to DDP (i.e. the 1.8B and 2.7B variants). Combining activation checkpointing (AC) with FSDP enables training even bigger models, on the order of ~10x compared to DDP (i.e. 4.8B and 10B variants)\n2. Throughput:", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "2. Throughput:\n - For smaller model sizes, at a constant batch size of 8, the throughput for DDP is slightly higher than or equal to FSDP, explainable by the additional communication required by FSDP. It is lowest for FSDP and AC combined together. This is because AC re-runs checkpointed forward passes during the backwards pass, trading off additional computation for memory savings. However, in the case of the 2.7B model, FSDP + AC actually has higher throughput compared to FSDP alone. This is because the 2.7B model with FSDP is operating close to the memory limit even at batch size 8 triggering CUDA malloc retries which tend to slow down training. AC helps with reducing the memory pressure and leads to no retries.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "- For DDP and FSDP + AC, the throughput increases with an increase in batch size for each model. For FSDP alone, this is true for smaller variants. However, with the 1.8B and 2.7B parameter models, we observe throughput degradation when increasing batch size. A potential reason for this, as noted above also, is that at the memory limit, PyTorch\u2019s CUDA memory management may have to retry cudaMalloc calls and/or run expensive defragmentation steps to find free memory blocks to handle the workload\u2019s memory requirements which can result in training slowdown.", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "- For larger models that can only be trained with FSDP (1.8B, 2.7B, 4.8B) the setting with highest throughput achieved is with FSDP + AC scaling to the maximum batch size. For 10B, we observe nearly equal throughput for smaller and maximum batch size. This might be counterintuitive as AC results in increased computation and maxing out batch size potentially leads to expensive defragmentation operations due to operating at CUDA memory limit. However, for these large models, the increase in batch size is large enough to mask this overhead.\n\n\n
\n
\n\n\n Figure 1: Training throughput for different configurations\n
\n\n", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "\n\n\n - Batch size: FSDP alone enables slightly higher batch sizes compared to DDP. Using FSDP + AC enables ~3x batch size compared to DDP for the 350M param model and ~5.5x for 900M param model. Even for 10B, a max batch size of ~20 which is fairly decent. This essentially enables larger global batch size using fewer GPUs which is especially useful for contrastive learning tasks.
\n
\n\n\n
\n
\n\n\n Figure 2: Max local batchsize possible for different configurations\n
\n\n## Conclusion", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "\n\n## Conclusion\n\nAs the world moves towards multimodal foundation models, scaling model parameters and efficient training is becoming an area of focus. The PyTorch ecosystem aims to accelerate innovation in this field by providing different tools to the research community, both for training and scaling multimodal models. With FLAVA, we laid out an example of scaling a model for multimodal understanding. In the future, we plan to add support for other kinds of models like the ones for multimodal generation and demonstrate their scaling factors. We also hope to automate many of these scaling and memory saving techniques (such as sharding and activation checkpointing) to reduce the amount of user experimentation needed to achieve the desired scale and maximum training throughput.\n\n## References\n\n- [Introducing TorchMultimodal - a library for accelerating exploration in Multimodal AI](https://pytorch.org/blog/introducing-torchmultimodal/)", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
+{"page_content": "- [FLAVA paper](https://deploy-preview-1186--pytorch-dot-org-preview.netlify.app/blog/introducing-torchmultimodal/)\n- [Introducing Pytorch FSDP](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/)", "metadata": {"source": "https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"A BetterTransformer for Fast Transformer Inference\"\nauthor: Michael Gschwind, Eric Han, Scott Wolchok, Rui Zhu, Christian Puhrsch\nfeatured-img: \"/assets/images/2022-7-12-a-better-transformer-for-fast-transformer-encoder-inference-3.png\"\n---\n\n**tl;dr** Transformers achieve state-of-the-art performance for NLP, and are becoming popular for a myriad of other tasks. They are computationally expensive which has been a blocker to their widespread productionisation. Launching with PyTorch 1.12, BetterTransformer implements a backwards-compatible fast path of `torch.nn.TransformerEncoder` for Transformer Encoder Inference and does not require model authors to modify their models. BetterTransformer improvements can exceed 2x in speedup and throughput for many common execution scenarios. To use BetterTransformer, [install](https://pytorch.org/get-started/locally/) PyTorch 1.12 and start using high-quality, high-performance Transformer models with the PyTorch API today.", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
{"page_content": "\n
\n
\n\n\nDiagram of the Transformer Encoder Architecture (from \"Attention Is All You Need\"). During Inference, the entire module will execute as a single PyTorch-native function.\n
\n\nIn this blog post, we share the following topics \u2014 Performance Improvements, Backwards compatibility, and Taking advantage of the FastPath. Learn more about these topics below. \n\n## Performance Improvements", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
{"page_content": "## Performance Improvements\n\nBetterTransformer launches with accelerated native implementations of MultiHeadAttention and TransformerEncoderLayer for CPUs and GPUs. These fast paths are integrated in the standard PyTorch Transformer APIs, and will accelerate [TransformerEncoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html), [TransformerEncoderLayer](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html) and [MultiHeadAttention](https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html) nn.modules. These new modules implement two types of optimizations: (1) fused kernels combine multiple individual operators normally used to implement Transformers to provide a more efficient implementation, and (2) take advantage of sparsity in the inputs to avoid performing unnecessary operations on padding tokens. Padding tokens frequently account for a large fraction of input batches in many Transformer models used for Natural Language Processing.", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
@@ -333,9 +336,9 @@
{"page_content": "2. Torchtext library acceleration: As part of this project, we have optimized Torchtext to build on the PyTorch core API to benefit from BetterTransformer enhancements while maintaining strict and transparent compatibility with previous library versions and models trained with previous Torchtext versions. Using PyTorch Transformers in Torchtext also ensures that Torchtext will benefit from expected future enhancements to the PyTorch Transformer implementation.\n\n## Taking advantage of the Fastpath\n\nBetterTransformer is a fastpath for the PyTorch Transformer API. The fastpath is a native, specialized implementation of key Transformer functions for CPU and GPU that applies to common Transformer use cases.", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
{"page_content": "To take advantage of input sparsity (i.e. padding) in accelerating your model (see Figure 2), set the keyword argument `enable_nested_tensor=True` when instantiating a [TransformerEncoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html) and pass in the `src_key_padding_mask` argument (which denotes padding tokens) during inference. This requires the padding mask to be contiguous, which is the typical case.", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
{"page_content": "Currently, the BetterTransformer speedup only applies to transformer encoder models used in inference. To benefit from fastpath execution, models must be composed of any of the following components: [TransformerEncoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html), [TransformerEncoderLayer](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html) or [MultiheadAttention](https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html) (MHA). Fastpath execution is also subject to some criteria. Most importantly, the model must be executed in inference mode and operate on input tensors that do not collect gradient tape information (e.g., running with torch.no_grad). The full list of conditions can be found at these links for [nn.MultiHeadAttention](https://github.com/pytorch/pytorch/blob/29189d2ba8e583b2355cd0e9517a1ee742ba12cf/torch/nn/modules/activation.py#L1060) and [nn.TransformerEncoder](https://github.com/pytorch/pytorch/blob/29189d2ba8e583b2355cd0e9517a1ee742ba12cf/torch/nn/modules/transformer.py#L206), respectively. If the criteria are not met, control flows to the legacy PyTorch 1.11 Transformer implementation which has the same API, but lacks the fastpath performance boost.", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
-{"page_content": "Other transformer models (such as decoder models) which use the PyTorch MultiheadAttention module will benefit from the BetterTransformer fastpath. Planned future work is to expand the end-to-end BetterTransformer fastpath to models based on [TransformerDecoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerDecoder.html) to support popular seq2seq and decoder-only (e.g., [OPT](https://ai.facebook.com/blog/democratizing-access-to-large-scale-language-models-with-opt-175b/)) model architectures, and to training.\n\n## Speedups\n\nThe following graphs show the performance achieved for the [BERT](https://arxiv.org/abs/1810.04805)-base model with small and large-scale inputs:\n\n\n
\n
\n\n\nFigure 1: PyTorch 1.12 Improvements with BetterTransformer fastpath execution\n
", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
-{"page_content": "\n
\n
\n\n\nFigure 2: PyTorch 1.12 Improvements with BetterTransformer fastpath execution
\nwith sparsity optimization enabled by enable_nested_tensor=True\n
", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
-{"page_content": "BetterTransformer includes two types of optimization: (1) fused kernels implementing multiple operations more efficiently in a single kernel, and (2) exploiting sparsity by avoiding unnecessary processing on padding tokens. Enhanced performance for small input sizes benefits primarily from the fused kernel implementations, and shows a constant performance improvement regardless of padding amount. While large inputs still benefit from fused kernels, the computation heavy processing limits the benefits that may be obtained by the fused kernels as baseline performance is already closer to the theoretical peak. However, as we increase the amount of padding, performance increases dramatically as increasingly large amounts of computation can be avoided by exploiting the sparsity introduced by padding in NLP workloads.\n\n## Future Work", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
+{"page_content": "Other transformer models (such as decoder models) which use the PyTorch MultiheadAttention module will benefit from the BetterTransformer fastpath. Planned future work is to expand the end-to-end BetterTransformer fastpath to models based on [TransformerDecoder](https://pytorch.org/docs/stable/generated/torch.nn.TransformerDecoder.html) to support popular seq2seq and decoder-only (e.g., [OPT](https://ai.facebook.com/blog/democratizing-access-to-large-scale-language-models-with-opt-175b/)) model architectures, and to training.\n\n## Speedups\n\nThe following graphs show the performance achieved for the [BERT](https://arxiv.org/abs/1810.04805)-base model with small and large-scale inputs:\n\n\n
\n
\n\n\nFigure 1: PyTorch 1.12 Improvements with BetterTransformer fastpath execution\n
\n\n", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\n
\n
\n\n\nFigure 2: PyTorch 1.12 Improvements with BetterTransformer fastpath execution
\nwith sparsity optimization enabled by enable_nested_tensor=True\n
", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
+{"page_content": "\n\n\nBetterTransformer includes two types of optimization: (1) fused kernels implementing multiple operations more efficiently in a single kernel, and (2) exploiting sparsity by avoiding unnecessary processing on padding tokens. Enhanced performance for small input sizes benefits primarily from the fused kernel implementations, and shows a constant performance improvement regardless of padding amount. While large inputs still benefit from fused kernels, the computation heavy processing limits the benefits that may be obtained by the fused kernels as baseline performance is already closer to the theoretical peak. However, as we increase the amount of padding, performance increases dramatically as increasingly large amounts of computation can be avoided by exploiting the sparsity introduced by padding in NLP workloads.\n\n## Future Work", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
{"page_content": "## Future Work\n\nAs part of our ongoing work on PyTorch BetterTransformer, we are working on extending BetterTransformer improvements to Transformer Decoders. We aim to expand beyond inference to training as well.\n\nWe are partnering to enable BetterTransformer on additional libraries such as FairSeq, MetaSeq, and HuggingFace to benefit all Transformer-based PyTorch models. We\u2019ll provide future updates on the progress of BetterTransformer accelerations for the larger PyTorch ecosystem as part of this blog series.\n\nAcknowledgements: The authors would like to thank Lin Qiao, Ajit Mathews, Andrew Tulloch, Dmytro Dzhulgakov, Natalia Gimelshein, Emad El-Haraty, Mark Saroufim, Adnan Aziz, Geeta Chauhan, and Hamid Shojanazeri for their support, contributions and many helpful suggestions throughout the course of this project, and in the preparation of this blog.", "metadata": {"source": "https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Experience the power of PyTorch 2.0 on AMD Solutions\"\nauthor: AMD\n---\n\nPyTorch 2.0 represents a significant step forward for the PyTorch machine learning framework. The stable release of PyTorch 2.0 brings new features that unlock even higher performance, while remaining backward compatible with prior releases and retaining the Pythonic focus which has helped to make PyTorch so enthusiastically adopted by the AI/ML community. AMD has long been a strong proponent of PyTorch, and we are delighted that the PyTorch 2.0 stable release includes support for AMD Instinct\u2122 and Radeon\u2122 GPUs that are supported by the ROCm\u2122 software platform.", "metadata": {"source": "https://pytorch.org/blog/experience-power-pytorch-2.0/", "category": "pytorch blogs"}}
{"page_content": "With the stable PyTorch 2.0 release, PyTorch 2.0 introduces torch.compile as a beta feature underpinned by TorchInductor with support for AMD Instinct and Radeon GPUs through OpenAI Triton deep learning compiler. Through TorchInductor, developers can now generate low level kernels using Triton that are portable and performant to hand-written kernels on native hardware centric kernel programming models.\n\nOpenAI Triton is a language and compiler for blocked algorithms, which aims to provide an abstraction layer between CUDA/HIP and Torch at which developers can write efficient kernels more productively. We have written a new backend which interfaces Triton's custom MLIR dialects with our ROCm compiler stack.", "metadata": {"source": "https://pytorch.org/blog/experience-power-pytorch-2.0/", "category": "pytorch blogs"}}
@@ -348,22 +351,20 @@
{"page_content": "---\nlayout: blog_detail\ntitle: 'Announcing PyTorch Developer Day 2021'\nauthor: Team PyTorch\nfeatured-img: 'assets/images/ptdevday21.gif'\n---\n\nWe are excited to announce PyTorch Developer Day (#PTD2), taking place virtually from December 1 & 2, 2021. Developer Day is designed for developers and users to discuss core technical developments, ideas, and roadmaps. \n\n\n

\n
\n\n## Event Details \n**Technical Talks Live Stream - December 1, 2021**\n\nJoin us for technical talks on a variety of topics, including updates to the core framework, new tools and libraries to support development across a variety of domains, responsible AI and industry use cases. All talks will take place on December 1 and will be live streamed on PyTorch channels.", "metadata": {"source": "https://pytorch.org/blog/pytorch-developer-day-2021/", "category": "pytorch blogs"}}
{"page_content": "Stay up to date by following us on our social channels: [Twitter](https://twitter.com/PyTorch), [Facebook](https://facebook.com/PyTorch), or [LinkedIn](https://www.linkedin.com/company/pytorch).\n\n**Poster Exhibition & Networking - December 2, 2021**\n\nOn the second day, we\u2019ll be hosting an online poster exhibition on Gather.Town. There will be opportunities to meet the authors and learn more about their PyTorch projects as well as network with the community. This poster and networking event is limited to people composed of PyTorch maintainers and contributors, long-time stakeholders and experts in areas relevant to PyTorch\u2019s future. Conversations from the networking event will strongly shape the future of PyTorch. As such, invitations are required to attend the networking event. \n\nApply for an invitation to the networking event by clicking [here](https://pytorchdeveloperday.fbreg.com/).\n\n## Call for Content Now Open", "metadata": {"source": "https://pytorch.org/blog/pytorch-developer-day-2021/", "category": "pytorch blogs"}}
{"page_content": "## Call for Content Now Open\n\nSubmit your poster abstracts today! Please send us the title and brief summary of your project, tools and libraries that could benefit PyTorch researchers in academia and industry, application developers, and ML engineers for consideration. The focus must be on academic papers, machine learning research, or open-source projects related to PyTorch development, Responsible AI or Mobile. Please no sales pitches. **Deadline for submission is September 24, 2021**. \n\nYou can submit your poster abstract during your application & registration process [here](https://pytorchdeveloperday.fbreg.com/apply).\n\nVisit the [event website](https://pytorchdeveloperday.fbreg.com/) for more information and we look forward to having you at PyTorch Developer Day. For any questions about the event, contact [pytorch@fbreg.com](mailto:pytorch@fbreg.com).", "metadata": {"source": "https://pytorch.org/blog/pytorch-developer-day-2021/", "category": "pytorch blogs"}}
-{"page_content": "---\nlayout: blog_detail\ntitle: 'Efficient PyTorch: Tensor Memory Format Matters'\nauthor: 'Dhruv Matani, Suraj Subramanian'\nfeatured-img: ''\n---\n\nEnsuring the right memory format for your inputs can significantly impact the running time of your PyTorch vision models. When in doubt, choose a Channels Last memory format.\n\nWhen dealing with vision models in PyTorch that accept multimedia (for example image Tensorts) as input, the Tensor\u2019s memory format can significantly impact **the inference execution speed of your model on mobile platforms when using the CPU backend along with XNNPACK**. This holds true for training and inference on server platforms as well, but latency is particularly critical for mobile devices and users.\n\n", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "## Outline of this article\n1. Deep Dive into matrix storage/memory representation in C++. Introduction to [Row and Column major order](https://en.wikipedia.org/wiki/Row-_and_column-major_order).\n2. Impact of looping over a matrix in the same or different order as the storage representation, along with an example.\n3. Introduction to Cachegrind; a tool to inspect the cache friendliness of your code.\n4. Memory formats supported by PyTorch Operators.\n5. Best practices example to ensure efficient model execution with XNNPACK optimizations\n\n## Matrix Storage Representation in C++\n\nImages are fed into PyTorch ML models as multi-dimensional Tensors. These Tensors have specific memory formats. To understand this concept better, let\u2019s take a look at how a 2-d matrix may be stored in memory.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "Broadly speaking, there are 2 main ways of efficiently storing multi-dimensional data in memory.\n1. **Row Major Order:** In this format, the matrix is stored in row order, with each row stored before the next row in memory. I.e. row N comes before row N+1.\n2. **Column Major Order:** In this format, the matrix is stored in column-order, with each column stored before the next column in memory. I.e. column N comes before column N+1.\n\nYou can see the differences graphically below.\n\n\n
\n
\nC++ stores multi-dimensional data in row-major format.\n
\n\n## Efficiently accessing elements of a 2d matrix\n\nSimilar to the storage format, there are 2 ways to access data in a 2d matrix.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "1. **Loop Over Rows first:** All elements of a row are processed before any element of the next row.\n2. **Loop Over Columns first:** All elements of a column are processed before any element of the next column.\n\nFor maximum efficiency, one should always access data in the same format in which it is stored. I.e. if the data is stored in row-major order, then one should try to access it in that order.\n\nThe code below (main.cpp) shows [2 ways](https://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra) of accessing all the elements of a 2d 4000x4000 matrix.\n\n```python\n#include \n#include \n\n// loop1 accesses data in matrix 'a' in row major order,\n// since i is the outer loop variable, and j is the\n// inner loop variable.\nint loop1(int a[4000][4000]) {\n int s = 0;\n for (int i = 0; i < 4000; ++i) {\n for (int j = 0; j < 4000; ++j) {\n s += a[i][j];\n }\n }\n return s;\n}", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "// loop2 accesses data in matrix 'a' in column major order\n// since j is the outer loop variable, and i is the\n// inner loop variable.\nint loop2(int a[4000][4000]) {\n int s = 0;\n for (int j = 0; j < 4000; ++j) {\n for (int i = 0; i < 4000; ++i) {\n s += a[i][j];\n }\n }\n return s;\n}\n\nint main() {\n static int a[4000][4000] = {0};\n for (int i = 0; i < 100; ++i) {\n int x = rand() % 4000;\n int y = rand() % 4000;\n a[x][y] = rand() % 1000;\n }\n\n auto start = std::chrono::high_resolution_clock::now();\n auto end = start;\n int s = 0;\n\n#if defined RUN_LOOP1\n start = std::chrono::high_resolution_clock::now();\n\n s = 0;\n for (int i = 0; i < 10; ++i) {\n s += loop1(a);\n s = s % 100;\n }\n end = std::chrono::high_resolution_clock::now();\n\n std::cout << \"s = \" << s << std::endl;\n std::cout << \"Time for loop1: \"\n << std::chrono::duration(end - start).count()\n << \"ms\" << std::endl;\n#endif", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "#if defined RUN_LOOP2\n start = std::chrono::high_resolution_clock::now();\n s = 0;\n for (int i = 0; i < 10; ++i) {\n s += loop2(a);\n s = s % 100;\n }\n end = std::chrono::high_resolution_clock::now();\n\n std::cout << \"s = \" << s << std::endl;\n std::cout << \"Time for loop2: \"\n << std::chrono::duration(end - start).count()\n << \"ms\" << std::endl;\n#endif\n}\n\n\nLet\u2019s build and run this program and see what it prints.\n\ng++ -O2 main.cpp -DRUN_LOOP1 -DRUN_LOOP2\n./a.out\n\n\nPrints the following:\n\ns = 70\nTime for loop1: 77.0687ms\ns = 70\nTime for loop2: 1219.49ms\n```\n\nloop1() is **15x faster** than loop2(). Why is that? Let\u2019s find out below!\n\n## Measure cache misses using Cachegrind\n\n[Cachegrind](https://courses.cs.washington.edu/courses/cse326/05wi/valgrind-doc/cg_main.html) is a cache profiling tool used to see how many I1 (first level instruction), D1 (first level data), and LL (last level) cache misses your program caused.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "Let\u2019s build our program with just loop1() and just loop2() to see how cache friendly each of these functions is.\n\n### Build and run/profile just loop1()\n\n```python\ng++ -O2 main.cpp -DRUN_LOOP1\nvalgrind --tool=cachegrind ./a.out\n```\n\n#### Prints:", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "#### Prints:\n\n```python\n==3299700==\n==3299700== I refs: 643,156,721\n==3299700== I1 misses: 2,077\n==3299700== LLi misses: 2,021\n==3299700== I1 miss rate: 0.00%\n==3299700== LLi miss rate: 0.00%\n==3299700==\n==3299700== D refs: 160,952,192 (160,695,444 rd + 256,748 wr)\n==3299700== D1 misses: 10,021,300 ( 10,018,723 rd + 2,577 wr)\n==3299700== LLd misses: 10,010,916 ( 10,009,147 rd + 1,769 wr)\n==3299700== D1 miss rate: 6.2% ( 6.2% + 1.0% )\n==3299700== LLd miss rate: 6.2% ( 6.2% + 0.7% )\n==3299700==\n==3299700== LL refs: 10,023,377 ( 10,020,800 rd + 2,577 wr)\n==3299700== LL misses: 10,012,937 ( 10,011,168 rd + 1,769 wr)\n==3299700== LL miss rate: 1.2% ( 1.2% + 0.7% )\n```\n\n### Build and run/profile just loop2()\n\n\n```python\ng++ -O2 main.cpp -DRUN_LOOP2\nvalgrind --tool=cachegrind ./a.out\n```\n\n#### Prints:", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "#### Prints:\n\n```python\n==3300389==\n==3300389== I refs: 643,156,726\n==3300389== I1 misses: 2,075\n==3300389== LLi misses: 2,018\n==3300389== I1 miss rate: 0.00%\n==3300389== LLi miss rate: 0.00%\n==3300389==\n==3300389== D refs: 160,952,196 (160,695,447 rd + 256,749 wr)\n==3300389== D1 misses: 160,021,290 (160,018,713 rd + 2,577 wr)\n==3300389== LLd misses: 10,014,907 ( 10,013,138 rd + 1,769 wr)\n==3300389== D1 miss rate: 99.4% ( 99.6% + 1.0% )\n==3300389== LLd miss rate: 6.2% ( 6.2% + 0.7% )\n==3300389==\n==3300389== LL refs: 160,023,365 (160,020,788 rd + 2,577 wr)\n==3300389== LL misses: 10,016,925 ( 10,015,156 rd + 1,769 wr)\n==3300389== LL miss rate: 1.2% ( 1.2% + 0.7% )\n```\n\nThe main differences between the 2 runs are:\n1. **D1 misses:** 10M v/s 160M\n2. **D1 miss rate:** 6.2% v/s 99.4%", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "As you can see, `loop2()` causes many many more (**~16x more**) L1 data cache misses than loop1(). This is why `loop1()` is ~15x faster than loop2().\n\n## Memory Formats supported by PyTorch Operators\n\nWhile PyTorch operators expect all tensors to be in [Channels First (NCHW) dimension format](https://discuss.pytorch.org/t/why-does-pytorch-prefer-using-nchw/83637/4), PyTorch operators support 3 output [memory formats](https://github.com/pytorch/pytorch/blob/master/c10/core/MemoryFormat.h).", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "1. **Contiguous:** Tensor memory is in the same order as the tensor\u2019s dimensions.\n2. **ChannelsLast:** Irrespective of the dimension order, the 2d (image) tensor is laid out as an HWC or [NHWC](https://oneapi-src.github.io/oneDNN/dev_guide_understanding_memory_formats.html) (N: batch, H: height, W: width, C: channels) tensor in memory. The dimensions could be permuted in any order.\n3. **ChannelsLast3d:** For 3d tensors (video tensors), the memory is laid out in THWC (Time, Height, Width, Channels) or NTHWC (N: batch, T: time, H: height, W: width, C: channels) format. The dimensions could be permuted in any order.\n\nThe reason that ChannelsLast is preferred for vision models is because [XNNPACK](https://github.com/google/XNNPACK) (kernel acceleration library) used by PyTorch expects all inputs to be in **Channels Last** format, so if the input to the model isn\u2019t channels last, then it must first be converted to channels last, which is an additional operation.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "Additionally, most PyTorch operators preserve the input tensor\u2019s memory format, so if the input is Channels First, then the operator needs to first convert to Channels Last, then perform the operation, and then convert back to Channels First.\n\nWhen you combine it with the fact that accelerated operators work better with a channels last memory format, you\u2019ll notice that having the operator return back a channels-last memory format is better for subsequent operator calls or you\u2019ll end up having every operator convert to channels-last (should it be more efficient for that specific operator).\n\nFrom the XNNPACK home page:\n\n> \u201cAll operators in XNNPACK support NHWC layout, but additionally allow custom stride along the Channel dimension\".\n\n## PyTorch Best Practice\n\nThe best way to get the most performance from your PyTorch vision models is to ensure that your input tensor is in a **Channels Last** [memory format](https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html) before it is fed into the model.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "You can get even more speedups by optimizing your model to use the XNNPACK backend (by simply calling `optimize_for_mobile()` on your torchscripted model). Note that XNNPACK models will run slower if the inputs are contiguous, so definitely make sure it is in Channels-Last format.\n\n## Working example showing speedup\n\nRun this example on [Google Colab](https://colab.research.google.com/gist/suraj813/ad9aebcbffbdd6d02b23ca7231130a30/channels-last-with-xnnpack.ipynb#scrollTo=xvJN73YWXgDF) - note that runtimes on colab CPUs might not reflect accurate performance; it is recommended to run this code on your local machine.\n\n```python\nimport torch\nfrom torch.utils.mobile_optimizer import optimize_for_mobile\nimport torch.backends.xnnpack\nimport time\n\nprint(\"XNNPACK is enabled: \", torch.backends.xnnpack.enabled, \"\\n\")\n\nN, C, H, W = 1, 3, 200, 200\nx = torch.rand(N, C, H, W)\nprint(\"Contiguous shape: \", x.shape)\nprint(\"Contiguous stride: \", x.stride())\nprint()", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "xcl = x.to(memory_format=torch.channels_last)\nprint(\"Channels-Last shape: \", xcl.shape)\nprint(\"Channels-Last stride: \", xcl.stride())\n\n## Outputs:\n \n# XNNPACK is enabled: True\n \n# Contiguous shape: torch.Size([1, 3, 200, 200])\n# Contiguous stride: (120000, 40000, 200, 1)\n \n# Channels-Last shape: torch.Size([1, 3, 200, 200])\n# Channels-Last stride: (120000, 1, 600, 3)\n\n```\n\nThe input shape stays the same for contiguous and channels-last formats. Internally however, the tensor's layout has changed as you can see in the strides. Now, the number of jumps required to go across channels is only 1 (instead of 40000 in the contiguous tensor).\nThis better data locality means convolution layers can access all the channels for a given pixel much faster. Let's see now how the memory format affects runtime:\n\n```python\nfrom torchvision.models import resnet34, resnet50, resnet101\n\nm = resnet34(pretrained=False)\n# m = resnet50(pretrained=False)\n# m = resnet101(pretrained=False)", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "def get_optimized_model(mm):\n mm = mm.eval()\n scripted = torch.jit.script(mm)\n optimized = optimize_for_mobile(scripted) # explicitly call the xnnpack rewrite \n return scripted, optimized\n\n\ndef compare_contiguous_CL(mm):\n # inference on contiguous\n start = time.perf_counter()\n for i in range(20):\n mm(x)\n end = time.perf_counter()\n print(\"Contiguous: \", end-start)\n\n # inference on channels-last\n start = time.perf_counter()\n for i in range(20):\n mm(xcl)\n end = time.perf_counter()\n print(\"Channels-Last: \", end-start)\n\nwith torch.inference_mode():\n scripted, optimized = get_optimized_model(m)\n\n print(\"Runtimes for torchscripted model: \")\n compare_contiguous_CL(scripted.eval())\n print()\n print(\"Runtimes for mobile-optimized model: \")\n compare_contiguous_CL(optimized.eval())", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
-{"page_content": "## Outputs (on an Intel Core i9 CPU):\n \n# Runtimes for torchscripted model:\n# Contiguous: 1.6711160129999598\n# Channels-Last: 1.6678222839999535\n \n# Runtimes for mobile-optimized model:\n# Contiguous: 0.5712863490000473\n# Channels-Last: 0.46113000699995155\n\n```\n\n## Conclusion\n\nThe Memory Layout of an input tensor can significantly impact a model\u2019s running time. For Vision Models, prefer a **Channels Last** memory format to get the most out of your PyTorch models.\n\n## References", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "---\nlayout: blog_detail\ntitle: 'Efficient PyTorch: Tensor Memory Format Matters'\nauthor: 'Dhruv Matani, Suraj Subramanian'\nfeatured-img: ''\n---\n\nEnsuring the right memory format for your inputs can significantly impact the running time of your PyTorch vision models. When in doubt, choose a Channels Last memory format.\n\nWhen dealing with vision models in PyTorch that accept multimedia (for example image Tensorts) as input, the Tensor\u2019s memory format can significantly impact **the inference execution speed of your model on mobile platforms when using the CPU backend along with XNNPACK**. This holds true for training and inference on server platforms as well, but latency is particularly critical for mobile devices and users.\n\n\n\n## Outline of this article", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "\n\n## Outline of this article\n1. Deep Dive into matrix storage/memory representation in C++. Introduction to [Row and Column major order](https://en.wikipedia.org/wiki/Row-_and_column-major_order).\n2. Impact of looping over a matrix in the same or different order as the storage representation, along with an example.\n3. Introduction to Cachegrind; a tool to inspect the cache friendliness of your code.\n4. Memory formats supported by PyTorch Operators.\n5. Best practices example to ensure efficient model execution with XNNPACK optimizations\n\n## Matrix Storage Representation in C++\n\nImages are fed into PyTorch ML models as multi-dimensional Tensors. These Tensors have specific memory formats. To understand this concept better, let\u2019s take a look at how a 2-d matrix may be stored in memory.\n\nBroadly speaking, there are 2 main ways of efficiently storing multi-dimensional data in memory.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "1. **Row Major Order:** In this format, the matrix is stored in row order, with each row stored before the next row in memory. I.e. row N comes before row N+1.\n2. **Column Major Order:** In this format, the matrix is stored in column-order, with each column stored before the next column in memory. I.e. column N comes before column N+1.\n\nYou can see the differences graphically below.\n\n\n
\n
\nC++ stores multi-dimensional data in row-major format.\n
\n\n## Efficiently accessing elements of a 2d matrix\n\nSimilar to the storage format, there are 2 ways to access data in a 2d matrix.\n\n1. **Loop Over Rows first:** All elements of a row are processed before any element of the next row.\n2. **Loop Over Columns first:** All elements of a column are processed before any element of the next column.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "For maximum efficiency, one should always access data in the same format in which it is stored. I.e. if the data is stored in row-major order, then one should try to access it in that order.\n\nThe code below (main.cpp) shows [2 ways](https://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra) of accessing all the elements of a 2d 4000x4000 matrix.\n\n```python\n#include \n#include \n\n// loop1 accesses data in matrix 'a' in row major order,\n// since i is the outer loop variable, and j is the\n// inner loop variable.\nint loop1(int a[4000][4000]) {\n int s = 0;\n for (int i = 0; i < 4000; ++i) {\n for (int j = 0; j < 4000; ++j) {\n s += a[i][j];\n }\n }\n return s;\n}\n\n// loop2 accesses data in matrix 'a' in column major order\n// since j is the outer loop variable, and i is the\n// inner loop variable.\nint loop2(int a[4000][4000]) {\n int s = 0;\n for (int j = 0; j < 4000; ++j) {\n for (int i = 0; i < 4000; ++i) {\n s += a[i][j];\n }", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "s += a[i][j];\n }\n }\n return s;\n}\n\nint main() {\n static int a[4000][4000] = {0};\n for (int i = 0; i < 100; ++i) {\n int x = rand() % 4000;\n int y = rand() % 4000;\n a[x][y] = rand() % 1000;\n }\n\n auto start = std::chrono::high_resolution_clock::now();\n auto end = start;\n int s = 0;\n\n#if defined RUN_LOOP1\n start = std::chrono::high_resolution_clock::now();\n\n s = 0;\n for (int i = 0; i < 10; ++i) {\n s += loop1(a);\n s = s % 100;\n }\n end = std::chrono::high_resolution_clock::now();\n\n std::cout << \"s = \" << s << std::endl;\n std::cout << \"Time for loop1: \"\n << std::chrono::duration(end - start).count()\n << \"ms\" << std::endl;\n#endif\n\n#if defined RUN_LOOP2\n start = std::chrono::high_resolution_clock::now();\n s = 0;\n for (int i = 0; i < 10; ++i) {\n s += loop2(a);\n s = s % 100;\n }\n end = std::chrono::high_resolution_clock::now();\n\n std::cout << \"s = \" << s << std::endl;\n std::cout << \"Time for loop2: \"\n << std::chrono::duration(end - start).count()", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "<< \"ms\" << std::endl;\n#endif\n}\n\n\nLet\u2019s build and run this program and see what it prints.\n\ng++ -O2 main.cpp -DRUN_LOOP1 -DRUN_LOOP2\n./a.out\n\n\nPrints the following:\n\ns = 70\nTime for loop1: 77.0687ms\ns = 70\nTime for loop2: 1219.49ms\n```\n\nloop1() is **15x faster** than loop2(). Why is that? Let\u2019s find out below!\n\n## Measure cache misses using Cachegrind\n\n[Cachegrind](https://courses.cs.washington.edu/courses/cse326/05wi/valgrind-doc/cg_main.html) is a cache profiling tool used to see how many I1 (first level instruction), D1 (first level data), and LL (last level) cache misses your program caused.\n\nLet\u2019s build our program with just loop1() and just loop2() to see how cache friendly each of these functions is.\n\n### Build and run/profile just loop1()\n\n```python\ng++ -O2 main.cpp -DRUN_LOOP1\nvalgrind --tool=cachegrind ./a.out\n```\n\n#### Prints:\n\n```python\n==3299700==\n==3299700== I refs: 643,156,721\n==3299700== I1 misses: 2,077\n==3299700== LLi misses: 2,021", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "==3299700== LLi misses: 2,021\n==3299700== I1 miss rate: 0.00%\n==3299700== LLi miss rate: 0.00%\n==3299700==\n==3299700== D refs: 160,952,192 (160,695,444 rd + 256,748 wr)\n==3299700== D1 misses: 10,021,300 ( 10,018,723 rd + 2,577 wr)\n==3299700== LLd misses: 10,010,916 ( 10,009,147 rd + 1,769 wr)\n==3299700== D1 miss rate: 6.2% ( 6.2% + 1.0% )\n==3299700== LLd miss rate: 6.2% ( 6.2% + 0.7% )\n==3299700==\n==3299700== LL refs: 10,023,377 ( 10,020,800 rd + 2,577 wr)\n==3299700== LL misses: 10,012,937 ( 10,011,168 rd + 1,769 wr)\n==3299700== LL miss rate: 1.2% ( 1.2% + 0.7% )\n```\n\n### Build and run/profile just loop2()\n\n\n```python\ng++ -O2 main.cpp -DRUN_LOOP2\nvalgrind --tool=cachegrind ./a.out\n```\n\n#### Prints:\n\n```python\n==3300389==\n==3300389== I refs: 643,156,726\n==3300389== I1 misses: 2,075\n==3300389== LLi misses: 2,018", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "==3300389== LLi misses: 2,018\n==3300389== I1 miss rate: 0.00%\n==3300389== LLi miss rate: 0.00%\n==3300389==\n==3300389== D refs: 160,952,196 (160,695,447 rd + 256,749 wr)\n==3300389== D1 misses: 160,021,290 (160,018,713 rd + 2,577 wr)\n==3300389== LLd misses: 10,014,907 ( 10,013,138 rd + 1,769 wr)\n==3300389== D1 miss rate: 99.4% ( 99.6% + 1.0% )\n==3300389== LLd miss rate: 6.2% ( 6.2% + 0.7% )\n==3300389==\n==3300389== LL refs: 160,023,365 (160,020,788 rd + 2,577 wr)\n==3300389== LL misses: 10,016,925 ( 10,015,156 rd + 1,769 wr)\n==3300389== LL miss rate: 1.2% ( 1.2% + 0.7% )\n```\n\nThe main differences between the 2 runs are:\n1. **D1 misses:** 10M v/s 160M\n2. **D1 miss rate:** 6.2% v/s 99.4%\n\nAs you can see, `loop2()` causes many many more (**~16x more**) L1 data cache misses than loop1(). This is why `loop1()` is ~15x faster than loop2().", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "## Memory Formats supported by PyTorch Operators\n\nWhile PyTorch operators expect all tensors to be in [Channels First (NCHW) dimension format](https://discuss.pytorch.org/t/why-does-pytorch-prefer-using-nchw/83637/4), PyTorch operators support 3 output [memory formats](https://github.com/pytorch/pytorch/blob/master/c10/core/MemoryFormat.h).\n\n1. **Contiguous:** Tensor memory is in the same order as the tensor\u2019s dimensions.\n2. **ChannelsLast:** Irrespective of the dimension order, the 2d (image) tensor is laid out as an HWC or [NHWC](https://oneapi-src.github.io/oneDNN/dev_guide_understanding_memory_formats.html) (N: batch, H: height, W: width, C: channels) tensor in memory. The dimensions could be permuted in any order.\n3. **ChannelsLast3d:** For 3d tensors (video tensors), the memory is laid out in THWC (Time, Height, Width, Channels) or NTHWC (N: batch, T: time, H: height, W: width, C: channels) format. The dimensions could be permuted in any order.", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "The reason that ChannelsLast is preferred for vision models is because [XNNPACK](https://github.com/google/XNNPACK) (kernel acceleration library) used by PyTorch expects all inputs to be in **Channels Last** format, so if the input to the model isn\u2019t channels last, then it must first be converted to channels last, which is an additional operation.\n\nAdditionally, most PyTorch operators preserve the input tensor\u2019s memory format, so if the input is Channels First, then the operator needs to first convert to Channels Last, then perform the operation, and then convert back to Channels First.\n\nWhen you combine it with the fact that accelerated operators work better with a channels last memory format, you\u2019ll notice that having the operator return back a channels-last memory format is better for subsequent operator calls or you\u2019ll end up having every operator convert to channels-last (should it be more efficient for that specific operator).\n\nFrom the XNNPACK home page:", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "From the XNNPACK home page:\n\n> \u201cAll operators in XNNPACK support NHWC layout, but additionally allow custom stride along the Channel dimension\".\n\n## PyTorch Best Practice\n\nThe best way to get the most performance from your PyTorch vision models is to ensure that your input tensor is in a **Channels Last** [memory format](https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html) before it is fed into the model.\n\nYou can get even more speedups by optimizing your model to use the XNNPACK backend (by simply calling `optimize_for_mobile()` on your torchscripted model). Note that XNNPACK models will run slower if the inputs are contiguous, so definitely make sure it is in Channels-Last format.\n\n## Working example showing speedup", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "## Working example showing speedup\n\nRun this example on [Google Colab](https://colab.research.google.com/gist/suraj813/ad9aebcbffbdd6d02b23ca7231130a30/channels-last-with-xnnpack.ipynb#scrollTo=xvJN73YWXgDF) - note that runtimes on colab CPUs might not reflect accurate performance; it is recommended to run this code on your local machine.\n\n```python\nimport torch\nfrom torch.utils.mobile_optimizer import optimize_for_mobile\nimport torch.backends.xnnpack\nimport time\n\nprint(\"XNNPACK is enabled: \", torch.backends.xnnpack.enabled, \"\\n\")\n\nN, C, H, W = 1, 3, 200, 200\nx = torch.rand(N, C, H, W)\nprint(\"Contiguous shape: \", x.shape)\nprint(\"Contiguous stride: \", x.stride())\nprint()\n\nxcl = x.to(memory_format=torch.channels_last)\nprint(\"Channels-Last shape: \", xcl.shape)\nprint(\"Channels-Last stride: \", xcl.stride())\n\n## Outputs:\n \n# XNNPACK is enabled: True\n \n# Contiguous shape: torch.Size([1, 3, 200, 200])\n# Contiguous stride: (120000, 40000, 200, 1)\n \n# Channels-Last shape: torch.Size([1, 3, 200, 200])", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "# Channels-Last stride: (120000, 1, 600, 3)\n\n```\n\nThe input shape stays the same for contiguous and channels-last formats. Internally however, the tensor's layout has changed as you can see in the strides. Now, the number of jumps required to go across channels is only 1 (instead of 40000 in the contiguous tensor).\nThis better data locality means convolution layers can access all the channels for a given pixel much faster. Let's see now how the memory format affects runtime:\n\n```python\nfrom torchvision.models import resnet34, resnet50, resnet101\n\nm = resnet34(pretrained=False)\n# m = resnet50(pretrained=False)\n# m = resnet101(pretrained=False)\n\ndef get_optimized_model(mm):\n mm = mm.eval()\n scripted = torch.jit.script(mm)\n optimized = optimize_for_mobile(scripted) # explicitly call the xnnpack rewrite \n return scripted, optimized\n\n\ndef compare_contiguous_CL(mm):\n # inference on contiguous\n start = time.perf_counter()\n for i in range(20):\n mm(x)\n end = time.perf_counter()", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
+{"page_content": "mm(x)\n end = time.perf_counter()\n print(\"Contiguous: \", end-start)\n\n # inference on channels-last\n start = time.perf_counter()\n for i in range(20):\n mm(xcl)\n end = time.perf_counter()\n print(\"Channels-Last: \", end-start)\n\nwith torch.inference_mode():\n scripted, optimized = get_optimized_model(m)\n\n print(\"Runtimes for torchscripted model: \")\n compare_contiguous_CL(scripted.eval())\n print()\n print(\"Runtimes for mobile-optimized model: \")\n compare_contiguous_CL(optimized.eval())\n\n \n## Outputs (on an Intel Core i9 CPU):\n \n# Runtimes for torchscripted model:\n# Contiguous: 1.6711160129999598\n# Channels-Last: 1.6678222839999535\n \n# Runtimes for mobile-optimized model:\n# Contiguous: 0.5712863490000473\n# Channels-Last: 0.46113000699995155\n\n```\n\n## Conclusion\n\nThe Memory Layout of an input tensor can significantly impact a model\u2019s running time. For Vision Models, prefer a **Channels Last** memory format to get the most out of your PyTorch models.\n\n## References", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
{"page_content": "## References\n\n- [Row/Column Major matrix storage order](https://en.wikipedia.org/wiki/Row-_and_column-major_order)\n- [Loop order impact on performance](https://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra)\n- [Cachegrind: a cache-miss profiler](https://courses.cs.washington.edu/courses/cse326/05wi/valgrind-doc/cg_main.html)\n- [NHWC format explained](https://oneapi-src.github.io/oneDNN/dev_guide_understanding_memory_formats.html)\n- [Why does PyTorch prefer NCHW?](https://discuss.pytorch.org/t/why-does-pytorch-prefer-using-nchw/83637/4)\n- [XNNPACK](https://github.com/google/XNNPACK)\n- [PyTorch memory format tutorial](https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html)\n- [Supported operators](https://github.com/pytorch/pytorch/wiki/Operators-with-Channels-Last-support)", "metadata": {"source": "https://pytorch.org/blog/tensor-memory-format-matters/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch framework for cryptographically secure random number generation, torchcsprng, now available'\nauthor: Team PyTorch\n---\n\nOne of the key components of modern cryptography is the pseudorandom number generator. Katz and Lindell stated, \"The use of badly designed or inappropriate random number generators can often leave a good cryptosystem vulnerable to attack. Particular care must be taken to use a random number generator that is designed for cryptographic use, rather than a 'general-purpose' random number generator which may be fine for some applications but not ones that are required to be cryptographically secure.\"[1] Additionally, most pseudorandom number generators scale poorly to massively parallel high-performance computation because of their sequential nature. Others don\u2019t satisfy cryptographically secure properties.", "metadata": {"source": "https://pytorch.org/blog/torchcsprng-release-blog/", "category": "pytorch blogs"}}
{"page_content": "[torchcsprng](https://github.com/pytorch/csprng) is a PyTorch [C++/CUDA extension](https://pytorch.org/tutorials/advanced/cpp_extension.html) that provides [cryptographically secure pseudorandom number generators](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) for PyTorch.\n\n## torchcsprng overview \n\nHistorically, PyTorch had only two pseudorandom number generator implementations: Mersenne Twister for CPU and Nvidia\u2019s cuRAND Philox for CUDA. Despite good performance properties, neither of them are suitable for cryptographic applications. Over the course of the past several months, the PyTorch team developed the torchcsprng extension API. Based on PyTorch dispatch mechanism and operator registration, it allows the users to extend c10::GeneratorImpl and implement their own custom pseudorandom number generator.", "metadata": {"source": "https://pytorch.org/blog/torchcsprng-release-blog/", "category": "pytorch blogs"}}
@@ -373,87 +374,90 @@
{"page_content": "---\nlayout: blog_detail\ntitle: \"Optimizing Production PyTorch Models\u2019 Performance with Graph Transformations\"\nauthor: Jade Nie, CK Luk, Xiaodong Wang, Jackie (Jiaqi) Xu\nfeatured-img: \"assets/images/blog1-3b.png\"\n---\n\n## 1. Introduction\n\nPyTorch supports two execution modes [1]: eager mode and graph mode. In eager mode, operators in a model are immediately executed as they are encountered. In contrast, in graph mode, operators are first synthesized into a graph, which will then be compiled and executed as a whole. Eager mode is easier to use, more suitable for ML researchers, and hence is the default mode of execution. On the other hand, graph mode typically delivers higher performance and hence is heavily used in production.", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "Specifically, graph mode enables operator fusion [2], wherein one operator is merged with another to reduce/localize memory reads as well as total kernel launch overhead. Fusion can be horizontal\u2014taking a single operation (e.g., BatchNorm) that is independently applied to many operands and merging those operands into an array; and vertical\u2014merging a kernel with another kernel that consumes the output of the first kernel (e.g., Convolution followed by ReLU).\n\nTorch.FX [3, 4] (abbreviated as FX) is a publicly available toolkit as part of the PyTorch package that supports graph mode execution. In particular, it (1) captures the graph from a PyTorch program and (2) allows developers to write transformations on the captured graph. It is used inside Meta to optimize the training throughput of production models. By introducing a number of FX-based optimizations developed at Meta, we demonstrate the approach of using graph transformation to optimize PyTorch\u2019s performance for production.\n\n## 2. Background", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "## 2. Background\n\nEmbedding tables are ubiquitous in recommendation systems. Section 3 will discuss three FX transformations that optimize accesses to embedding tables. In this section, we provide some background on FX (Section 2.1) and embedding tables (Section 2.2).\n\n### 2.1 FX\n\nFigure 1 is a simple example adopted from [3] which illustrates using FX to transform a PyTorch program. It contains three steps: (1) capturing the graph from a program, (2) modifying the graph (in this example, all uses of RELU are replaced by GELU), and (3) generating a new program from the modified graph.\n\n\n
\n
\n\n**Figure 1: A FX example which replaces all uses of RELU by GELU in a PyTorch module.**\n\nThe FX API [4] provides many more functionalities for inspecting and transforming PyTorch program graphs.\n\n### 2.2 Embedding Tables\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
-{"page_content": "**Figure 2: Illustration of an embedding table for a sparse feature with batch size = 1**\n\nIn a recommendation system, sparse features (e.g., User ID, Story ID) are represented by embedding tables. An embedding table E is an HxD matrix, where H is the hash size, D is the embedding dimension. Each row of E is a vector of floats. Feature hashing [5] is used to map a sparse feature to a list of indices to E, say [S1,S2, \u2026, Sk], where 0<=Si<H. Its output value is computed as f(E[S1], E[S2], \u2026, E[Sk]), where E[Si] is the vector at row Si, and f is called the pooling function, which is typically one of the following functions: sum, average, maximum. See Figure 2 for an illustration.", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
+{"page_content": "\n\n**Figure 2: Illustration of an embedding table for a sparse feature with batch size = 1**\n\nIn a recommendation system, sparse features (e.g., User ID, Story ID) are represented by embedding tables. An embedding table E is an HxD matrix, where H is the hash size, D is the embedding dimension. Each row of E is a vector of floats. Feature hashing [5] is used to map a sparse feature to a list of indices to E, say [S1,S2, \u2026, Sk], where 0<=Si<H. Its output value is computed as f(E[S1], E[S2], \u2026, E[Sk]), where E[Si] is the vector at row Si, and f is called the pooling function, which is typically one of the following functions: sum, average, maximum. See Figure 2 for an illustration.", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "To fully utilize the GPU, sparse features are usually processed in a batch. Each entity in a batch has its own list of indices. If a batch has B entities, a naive representation has B lists of indices. A more compact representation is to combine the B lists of indices into a single list of indices and add a list of the lengths of indices (one length for each entity in the batch). For example, if a batch has 3 entities whose lists of indices are as follows:\n\n- Entity 1: indices = [10, 20]\n- Entity 2: indices = [5, 9, 77, 81]\n- Entity 3: indices = [15, 20, 45]\n\nThen the indices and lengths for the entire batch will be:\n\n- Indices = [10, 20, 5, 9, 77, 81, 15, 20, 45]\n- Lengths = [2, 4, 3]\n\nAnd the output of the embedding table lookup for the whole batch is a BxD matrix.\n\n## 3. Three FX Transformations", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "## 3. Three FX Transformations\n\nWe have developed three FX transformations that accelerate accesses to embedding tables. Section 3.1 discusses a transformation that combines multiple small input tensors into a single big tensor; Section 3.2 a transformation that fuses multiple, parallel compute chains into a single compute chain; and Section 3.3 a transformation that overlaps communication with computation.\n\n### 3.1 Combining Input Sparse Features", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "### 3.1 Combining Input Sparse Features\n\nRecall that an input sparse feature in a batch is represented by two lists: a list of indices and a list of B lengths, where B is the batch size. In PyTorch, these two lists are implemented as two tensors. When a PyTorch model is run on a GPU, embedding tables are commonly stored in the GPU memory (which is closer to the GPU and has much higher read/write bandwidth than the CPU memory). To use an input sparse feature, its two tensors need to be first copied from CPU to GPU. Nevertheless, per host-to-device memory copying requires a kernel launch, which is relatively expensive compared to the actual data transfer time. If a model uses many input sparse features, this copying could become a performance bottleneck (e.g., 1000 input sparse features would require copying 2000 tensors from host to device).", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
-{"page_content": "An optimization that reduces the number of host-to-device memcpy is to combine multiple input sparse features before sending them to the device. For instance, given the following three input features:\n\n- Feature_A: indices = [106, 211, 7], lengths = [2, 1]\n- Feature_B: indices = [52, 498, 616, 870, 1013], lengths = [3, 2]\n- Feature_C: indices = [2011, 19, 351, 790], lengths = [1, 3]\n\nThe combined form is:\n\n- Features_A_B_C: indices = [106, 211, 7, 52, 498, 616, 870, 1013, 2011, 19, 351, 790], lengths = [2, 1, 3, 2, 1, 3]\n\nSo, instead of copying 3x2=6 tensors from host to device, we only need to copy 2 tensors.\n\nFigure 3(b) describes an implementation of this optimization, which has two components:", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
-{"page_content": "- On the CPU side: The input pipeline is modified to combine all the indices of sparse features into a single tensor and similarly all the lengths into another tensor. Then the two tensors are copied to the GPU.\n- On the GPU side: Using FX, we insert a Permute_and_Split op into the model graph to recover the indices and lengths tensors of individual features from the combined tensors, and route them to the corresponding nodes downstream.\n\n\n
\n
\n\n(a). **Without the optimization**\n\n\n
\n
\n\n(b). **With the optimization**\n\n**Figure 3: Combining input sparse features**\n\n### 3.2 Horizontal fusion of computation chains started with accesses to embedding tables", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
+{"page_content": "An optimization that reduces the number of host-to-device memcpy is to combine multiple input sparse features before sending them to the device. For instance, given the following three input features:\n\n- Feature_A: indices = [106, 211, 7], lengths = [2, 1]\n- Feature_B: indices = [52, 498, 616, 870, 1013], lengths = [3, 2]\n- Feature_C: indices = [2011, 19, 351, 790], lengths = [1, 3]\n\nThe combined form is:\n\n- Features_A_B_C: indices = [106, 211, 7, 52, 498, 616, 870, 1013, 2011, 19, 351, 790], lengths = [2, 1, 3, 2, 1, 3]\n\nSo, instead of copying 3x2=6 tensors from host to device, we only need to copy 2 tensors.\n\nFigure 3(b) describes an implementation of this optimization, which has two components:\n\n- On the CPU side: The input pipeline is modified to combine all the indices of sparse features into a single tensor and similarly all the lengths into another tensor. Then the two tensors are copied to the GPU.", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
+{"page_content": "- On the GPU side: Using FX, we insert a Permute_and_Split op into the model graph to recover the indices and lengths tensors of individual features from the combined tensors, and route them to the corresponding nodes downstream.\n\n\n
\n
\n\n(a). **Without the optimization**\n\n\n
\n
\n\n(b). **With the optimization**\n\n**Figure 3: Combining input sparse features**\n\n### 3.2 Horizontal fusion of computation chains started with accesses to embedding tables", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "In a production model, it is fairly common to have 10s of embedding tables residing on each GPU. For performance reasons, lookups to these tables are grouped together so that their outputs are concatenated in a single big tensor (see the red part in Figure 4(a)). To apply computations to individual feature outputs, a Split op is used to divide the big tensors into N smaller tensors (where N is the number of features) and then the desired computations are applied to each tensor. This is shown in Figure 4(a), where the computation applied to each feature output O is Tanh(LayerNorm(O)). All the computation results are concatenated back to a big tensor, which is then passed to downstream ops (Op1 in Figure 4(a)).", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "The main runtime cost here is the GPU kernel launch overhead. For instance, the number of GPU kernel launches in Figure 4(a) is 2\\*N + 3 (each oval in the figure is a GPU kernel). This could become a performance issue because execution times of LayerNorm and Tanh on the GPU are short compared to their kernel launch times. In addition, the Split op may create an extra copy of the embedding output tensor, consuming additional GPU memory.", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "We use FX to implement an optimization called horizontal fusion which dramatically reduces the number of GPU kernel launches (in this example, the optimized number of GPU kernel launches is 5, see Figure 4(b)). Instead of doing an explicit Split, we use the Add_middle_dim op to reshape the 2D embedding tensor of shape (B, NxD) to a 3D tensor of shape (B, N, D). Then a single LayerNorm is applied to the last dimension of it. Then a single Tanh is applied to the result of the LayerNorm. At the end, we use the Remove_middle_dim op to reshape the Tanh\u2019s result back to a 2D tensor. In addition, since Add_middle_dim and Remove_middle_dim only reshape the tensor without creating an extra copy, the amount of GPU memory consumption could be reduced as well.\n\n\n
\n
\n\n(a). **Without the optimization**\n\n\n
\n
\n\n(b). **With the optimization**\n\n**Figure 4: Horizontal fusion**", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
-{"page_content": "**Figure 4: Horizontal fusion**\n\n### 3.3 Overlapping Computation with Communication\n\nTraining of a production recommendation model is typically done on a distributed GPU system. Since the capacity of the device memory per GPU is not big enough to hold all the embedding tables in the model, they need to be distributed among the GPUs.\n\nWithin a training step, a GPU needs to read/write feature values from/to the embedding tables on the other GPUs. This is known as all-to-all communication [6] and can be a major performance bottleneck.\n\nWe use FX to implement a transformation that can overlap computation with all-to-all communication. Figure 5(a) shows the example of a model graph which has embedding table accesses (EmbeddingAllToAll) and other ops. Without any optimization, they are sequentially executed on a GPU stream, as shown in Figure 5(b). Using FX, we break EmbeddingAllToAll into EmbeddingAllToAll_Request and EmbeddingAllToAll_Wait, and schedule independent ops in between them.", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
+{"page_content": "**Figure 4: Horizontal fusion**\n\n### 3.3 Overlapping Computation with Communication\n\nTraining of a production recommendation model is typically done on a distributed GPU system. Since the capacity of the device memory per GPU is not big enough to hold all the embedding tables in the model, they need to be distributed among the GPUs.\n\nWithin a training step, a GPU needs to read/write feature values from/to the embedding tables on the other GPUs. This is known as all-to-all communication [6] and can be a major performance bottleneck.\n\nWe use FX to implement a transformation that can overlap computation with all-to-all communication. Figure 5(a) shows the example of a model graph which has embedding table accesses (EmbeddingAllToAll) and other ops. Without any optimization, they are sequentially executed on a GPU stream, as shown in Figure 5(b). Using FX, we break EmbeddingAllToAll into EmbeddingAllToAll_Request and EmbeddingAllToAll_Wait, and schedule independent ops in between them.\n\n", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\n\n**(a) Model graph**\n\n\n
\n
\n\n**(b) Original execution order**\n\n\n
\n
\n\n**(c)Optimized execution order**\n\n**Figure 5: Overlapping Computation with Communication**\n\n### 3.4 Summary\n\nTable 1 summarizes the optimizations discussed in this section and the corresponding performance bottlenecks addressed.\n\n\n \n Optimization\n | \n Performance Bottleneck Addressed\n | \n
\n \n Combining Input Sparse Features\n | \n Host-to-device memory copy\n | \n
\n \n Horizontal fusion\n | \n GPU kernel launch overhead\n | \n
\n \n Overlapping Computation with Communication\n | \n Embedding all-to-all access time\n | \n
\n
", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
-{"page_content": "**Table 1: Summary of the optimizations and the performance bottlenecks addressed**\n\nWe have also developed other FX transformations which are not discussed in this section due to space limitations.\n\nTo discover which models would benefit from these transformations, we analyzed the performance data collected by MAIProf [7] from the models that run at Meta\u2019s data centers. Altogether, these transformations provide up to 2-3x of speedups compared to eager mode on a set of production models.\n\n## 4. Concluding Remarks\n\nThe graph mode in PyTorch is preferred over the eager mode for production use for performance reasons. FX is a powerful tool for capturing and optimizing the graph of a PyTorch program. We demonstrate three FX transformations that are used to optimize production recommendation models inside Meta. We hope that this blog can motivate other PyTorch model developers to use graph transformations to boost their models\u2019 performance.\n\nReferences", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
+{"page_content": "\n \n\n\n**Table 1: Summary of the optimizations and the performance bottlenecks addressed**\n\nWe have also developed other FX transformations which are not discussed in this section due to space limitations.\n\nTo discover which models would benefit from these transformations, we analyzed the performance data collected by MAIProf [7] from the models that run at Meta\u2019s data centers. Altogether, these transformations provide up to 2-3x of speedups compared to eager mode on a set of production models.\n\n## 4. Concluding Remarks\n\nThe graph mode in PyTorch is preferred over the eager mode for production use for performance reasons. FX is a powerful tool for capturing and optimizing the graph of a PyTorch program. We demonstrate three FX transformations that are used to optimize production recommendation models inside Meta. We hope that this blog can motivate other PyTorch model developers to use graph transformations to boost their models\u2019 performance.\n\nReferences", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "References\n\n[1] [End-to-end Machine Learning Framework](https://pytorch.org/features/)\n\n[2] [DNNFusion: Accelerating Deep Neural Networks Execution with Advanced Operator Fusion](https://arxiv.org/abs/2108.13342)\n\n[3] [Torch.FX: Practical Program Capture and Transformation for Deep Learning In Python](https://arxiv.org/pdf/2112.08429.pdf), MLSys 2022.\n\n[4] [Torch.fx\u2014PyTorch 1.12 documentation](https://pytorch.org/docs/stable/fx.html)\n\n[5] [Feature Hashing for Large Scale Multitask Learning](https://alex.smola.org/papers/2009/Weinbergeretal09.pdf)\n\n[6] [NVIDIA Collective Communication Library Documentation](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/)\n\n[7] [Performance Debugging of Production PyTorch Models at Meta](https://pytorch.org/blog/performance-debugging-of-production-pytorch-models-at-meta/)", "metadata": {"source": "https://pytorch.org/blog/optimizing-production-pytorch-performance-with-graph-transformations/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch 1.3 adds mobile, privacy, quantization, and named tensors'\nauthor: Team PyTorch\n---\n\nPyTorch continues to gain momentum because of its focus on meeting the needs of researchers, its streamlined workflow for production use, and most of all because of the enthusiastic support it has received from the AI community. PyTorch citations in papers on ArXiv [grew 194 percent in the first half of 2019 alone, as noted by O\u2019Reilly](https://www.oreilly.com/ideas/one-simple-graphic-researchers-love-pytorch-and-tensorflow?fbclid=IwAR3kYmlyD7zky37IYFu0cafQn7yemhl8P-7MNyB30z0q5RDzxcTOrP8kxDk), and the number of contributors to the platform has grown more than 50 percent over the last year, to nearly 1,200. Facebook, Microsoft, Uber, and other organizations across industries are increasingly using it as the foundation for their most important machine learning (ML) research and production workloads.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "We are now advancing the platform further with the release of PyTorch 1.3, which includes experimental support for features such as seamless model deployment to mobile devices, model quantization for better performance at inference time, and front-end improvements, like the ability to name tensors and create clearer code with less need for inline comments. We\u2019re also launching a number of additional tools and libraries to support model interpretability and bringing multimodal research to production.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "Additionally, we\u2019ve collaborated with Google and Salesforce to add broad support for Cloud Tensor Processing Units, providing a significantly accelerated option for training large-scale deep neural networks. [Alibaba Cloud](https://data.aliyun.com/bigdata/pai-pytorch?spm=5176.12825654.a9ylfrljh.d112.7b652c4ayuOO4M&scm=20140722.1068.1.1098&aly_as=-PvJ5e4c) also joins Amazon Web Services, Microsoft Azure, and Google Cloud as supported cloud platforms for PyTorch users. You can get started now at [pytorch.org](https://pytorch.org/get-started/locally/).\n\n# PyTorch 1.3\n\nThe 1.3 release of PyTorch brings significant new features, including experimental support for mobile device deployment, eager mode quantization at 8-bit integer, and the ability to name tensors. With each of these enhancements, we look forward to additional contributions and improvements from the PyTorch community.\n\n## Named tensors (experimental)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "## Named tensors (experimental)\n\nCornell University\u2019s [Sasha Rush has argued](http://nlp.seas.harvard.edu/NamedTensor) that, despite its ubiquity in deep learning, the traditional implementation of tensors has significant shortcomings, such as exposing private dimensions, broadcasting based on absolute position, and keeping type information in documentation. He proposed named tensors as an alternative approach.\n\nToday, we name and access dimensions by comment:\n\n```python\n# Tensor[N, C, H, W]\n images = torch.randn(32, 3, 56, 56)\n images.sum(dim=1)\n images.select(dim=1, index=0)\n```\n\nBut naming explicitly leads to more readable and maintainable code:\n\n```python\nNCHW = [\u2018N\u2019, \u2018C\u2019, \u2018H\u2019, \u2018W\u2019]\n images = torch.randn(32, 3, 56, 56, names=NCHW)\n images.sum('C')\n images.select('C', index=0)\n```\n\n## Quantization (experimental)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "## Quantization (experimental)\n\nIt\u2019s important to make efficient use of both server-side and on-device compute resources when developing ML applications. To support more efficient deployment on servers and edge devices, PyTorch 1.3 now supports 8-bit model quantization using the familiar eager mode Python API. Quantization refers to techniques used to perform computation and storage at reduced precision, such as 8-bit integer. This currently experimental feature includes support for post-training quantization, dynamic quantization, and quantization-aware training. It leverages the [FBGEMM](https://github.com/pytorch/FBGEMM) and [QNNPACK](https://github.com/pytorch/QNNPACK) state-of-the-art quantized kernel back ends, for x86 and ARM CPUs, respectively, which are integrated with PyTorch and now share a common API.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "To learn more about the design and architecture, check out the API docs [here](https://pytorch.org/docs/master/quantization.html), and get started with any of the supported techniques using the tutorials available [here](https://pytorch.org/tutorials/).\n\n## PyTorch mobile (experimental)\n\nRunning ML on edge devices is growing in importance as applications continue to demand lower latency. It is also a foundational element for privacy-preserving techniques such as federated learning. To enable more efficient on-device ML, PyTorch 1.3 now supports an end-to-end workflow from Python to deployment on iOS and Android.\n\nThis is an early, experimental release, optimized for end-to-end development. Coming releases will focus on:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "* Optimization for size: Build level optimization and selective compilation depending on the operators needed for user applications (i.e., you pay binary size for only the operators you need)\n* Performance: Further improvements to performance and coverage on mobile CPUs and GPUs\n* High level API: Extend mobile native APIs to cover common preprocessing and integration tasks needed for incorporating ML in mobile applications. e.g. Computer vision and NLP\n\nLearn more or get started on Android or iOS [here](http://pytorch.org/mobile).\n\n# New tools for model interpretability and privacy\n\n## Captum", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "## Captum\n\nAs models become ever more complex, it is increasingly important to develop new methods for model interpretability. To help address this need, we\u2019re launching Captum, a tool to help developers working in PyTorch understand why their model generates a specific output. Captum provides state-of-the-art tools to understand how the importance of specific neurons and layers and affect predictions made by the models. Captum\u2019s algorithms include integrated gradients, conductance, SmoothGrad and VarGrad, and DeepLift.\n\nThe example below shows how to apply model interpretability algorithms on a pretrained ResNet model and then visualize the attributions for each pixel by overlaying them on the image.\n\n```python\nnoise_tunnel = NoiseTunnel(integrated_gradients)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "attributions_ig_nt, delta = noise_tunnel.attribute(input, n_samples=10, nt_type='smoothgrad_sq', target=pred_label_idx)\n_ = viz.visualize_image_attr_multiple([\"original_image\", \"heat_map\"],\n [\"all\", \"positive\"],\n np.transpose(attributions_ig_nt.squeeze().cpu().detach().numpy(), (1,2,0)),\n np.transpose(transformed_img.squeeze().cpu().detach().numpy(), (1,2,0)),\n cmap=default_cmap,\n show_colorbar=True)\n```\n\n\n

\n
\n\n

\n
\n\nLearn more about Captum at [captum.ai](https://www.captum.ai/).\n\n## CrypTen", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "```\n\n## Quantization (experimental)\n\nIt\u2019s important to make efficient use of both server-side and on-device compute resources when developing ML applications. To support more efficient deployment on servers and edge devices, PyTorch 1.3 now supports 8-bit model quantization using the familiar eager mode Python API. Quantization refers to techniques used to perform computation and storage at reduced precision, such as 8-bit integer. This currently experimental feature includes support for post-training quantization, dynamic quantization, and quantization-aware training. It leverages the [FBGEMM](https://github.com/pytorch/FBGEMM) and [QNNPACK](https://github.com/pytorch/QNNPACK) state-of-the-art quantized kernel back ends, for x86 and ARM CPUs, respectively, which are integrated with PyTorch and now share a common API.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "To learn more about the design and architecture, check out the API docs [here](https://pytorch.org/docs/master/quantization.html), and get started with any of the supported techniques using the tutorials available [here](https://pytorch.org/tutorials/).\n\n## PyTorch mobile (experimental)\n\nRunning ML on edge devices is growing in importance as applications continue to demand lower latency. It is also a foundational element for privacy-preserving techniques such as federated learning. To enable more efficient on-device ML, PyTorch 1.3 now supports an end-to-end workflow from Python to deployment on iOS and Android.\n\nThis is an early, experimental release, optimized for end-to-end development. Coming releases will focus on:\n\n* Optimization for size: Build level optimization and selective compilation depending on the operators needed for user applications (i.e., you pay binary size for only the operators you need)\n* Performance: Further improvements to performance and coverage on mobile CPUs and GPUs", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "* High level API: Extend mobile native APIs to cover common preprocessing and integration tasks needed for incorporating ML in mobile applications. e.g. Computer vision and NLP\n\nLearn more or get started on Android or iOS [here](http://pytorch.org/mobile).\n\n# New tools for model interpretability and privacy\n\n## Captum\n\nAs models become ever more complex, it is increasingly important to develop new methods for model interpretability. To help address this need, we\u2019re launching Captum, a tool to help developers working in PyTorch understand why their model generates a specific output. Captum provides state-of-the-art tools to understand how the importance of specific neurons and layers and affect predictions made by the models. Captum\u2019s algorithms include integrated gradients, conductance, SmoothGrad and VarGrad, and DeepLift.\n\nThe example below shows how to apply model interpretability algorithms on a pretrained ResNet model and then visualize the attributions for each pixel by overlaying them on the image.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "```python\nnoise_tunnel = NoiseTunnel(integrated_gradients)\n\nattributions_ig_nt, delta = noise_tunnel.attribute(input, n_samples=10, nt_type='smoothgrad_sq', target=pred_label_idx)\n_ = viz.visualize_image_attr_multiple([\"original_image\", \"heat_map\"],\n [\"all\", \"positive\"],\n np.transpose(attributions_ig_nt.squeeze().cpu().detach().numpy(), (1,2,0)),\n np.transpose(transformed_img.squeeze().cpu().detach().numpy(), (1,2,0)),\n cmap=default_cmap,\n show_colorbar=True)\n```\n\n\n

\n
\n\n

\n
\n\nLearn more about Captum at [captum.ai](https://www.captum.ai/).\n\n## CrypTen", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "## CrypTen\n\nPractical applications of ML via cloud-based or machine-learning-as-a-service (MLaaS) platforms pose a range of security and privacy challenges. In particular, users of these platforms may not want or be able to share unencrypted data, which prevents them from taking full advantage of ML tools. To address these challenges, the ML community is exploring a number of technical approaches, at various levels of maturity. These include homomorphic encryption, secure multiparty computation, trusted execution environments, on-device computation, and differential privacy.\n\nTo provide a better understanding of how some of these technologies can be applied, we are releasing CrypTen, a new community-based research platform for taking the field of privacy-preserving ML forward. Learn more about CrypTen [here](https://ai.facebook.com/blog/crypten-a-new-research-tool-for-secure-machine-learning-with-pytorch). It is available on GitHub [here](https://github.com/facebookresearch/CrypTen).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "# Tools for multimodal AI systems\n\nDigital content is often made up of several modalities, such as text, images, audio, and video. For example, a single public post might contain an image, body text, a title, a video, and a landing page. Even one particular component may have more than one modality, such as a video that contains both visual and audio signals, or a landing page that is composed of images, text, and HTML sources.\n\nThe ecosystem of tools and libraries that work with PyTorch offer enhanced ways to address the challenges of building multimodal ML systems. Here are some of the latest libraries launching today:\n\n## Detectron2", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "## Detectron2\n\nObject detection and segmentation are used for tasks ranging from autonomous vehicles to content understanding for platform integrity. To advance this work, Facebook AI Research (FAIR) is releasing Detectron2, an object detection library now implemented in PyTorch. Detectron2 provides support for the latest models and tasks, increased flexibility to aid computer vision research, and improvements in maintainability and scalability to support production use cases.\n\nDetectron2 is available [here](https://github.com/facebookresearch/detectron2) and you can learn more [here](https://ai.facebook.com/blog/-detectron2-a-pytorch-based-modular-object-detection-library-).\n\n## Speech extensions to fairseq", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "## Speech extensions to fairseq\n\nLanguage translation and audio processing are critical components in systems and applications such as search, translation, speech, and assistants. There has been tremendous progress in these fields recently thanks to the development of new architectures like transformers, as well as large-scale pretraining methods. We\u2019ve extended fairseq, a framework for sequence-to-sequence applications such as language translation, to include support for end-to-end learning for speech and audio recognition tasks.These extensions to fairseq enable faster exploration and prototyping of new speech research ideas while offering a clear path to production.\n\nGet started with fairseq [here](https://github.com/pytorch/fairseq/tree/master/examples/speech_recognition).\n\n# Cloud provider and hardware ecosystem support", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "# Cloud provider and hardware ecosystem support\n\nCloud providers such as Amazon Web Services, Microsoft Azure, and Google Cloud provide extensive support for anyone looking to develop ML on PyTorch and deploy in production. We\u2019re excited to share the general availability of Google Cloud TPU support and a newly launched integration with Alibaba Cloud. We\u2019re also expanding hardware ecosystem support.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "* Google Cloud TPU support now broadly available. To accelerate the largest-scale machine learning (ML) applications deployed today and enable rapid development of the ML applications of tomorrow, Google created custom silicon chips called Tensor Processing Units ([TPUs](https://cloud.google.com/tpu/)). When assembled into multi-rack ML supercomputers called [Cloud TPU Pods](https://cloud.google.com/blog/products/ai-machine-learning/cloud-tpu-pods-break-ai-training-records), these TPUs can complete ML workloads in minutes or hours that previously took days or weeks on other systems. Engineers from Facebook, Google, and Salesforce worked together to enable and pilot Cloud TPU support in PyTorch, including experimental support for Cloud TPU Pods. PyTorch support for Cloud TPUs is also available in Colab. Learn more about how to get started with PyTorch on Cloud TPUs [here](https://github.com/pytorch/xla).\n* Alibaba adds support for PyTorch in Alibaba Cloud. The initial integration involves a one-click solution for PyTorch 1.x, Data Science Workshop notebook service, distributed training with Gloo/NCCL, as well as seamless integration with Alibaba IaaS such as OSS, ODPS, and NAS. Together with the toolchain provided by Alibaba, we look forward to significantly reducing the overhead necessary for adoption, as well as helping Alibaba Cloud\u2019s global customer base leverage PyTorch to develop new AI applications.\n* ML hardware ecosystem expands. In addition to key GPU and CPU partners, the PyTorch ecosystem has also enabled support for dedicated ML accelerators. Updates from [Intel](https://www.intel.ai/nnpi-glow-pytorch/) and [Habana](https://medium.com/@HabanaLabs/unlocking-ai-scaling-through-software-and-hardware-interface-standardization-77561cb7598b) showcase how PyTorch, connected to the Glow optimizing compiler, enables developers to utilize these market-specific solutions.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "# Growth in the PyTorch community\n\nAs an open source, community-driven project, PyTorch benefits from wide range of contributors bringing new capabilities to the ecosystem. Here are some recent examples:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "* Mila SpeechBrain aims to provide an open source, all-in-one speech toolkit based on PyTorch. The goal is to develop a single, flexible, user-friendly toolkit that can be used to easily develop state-of-the-art systems for speech recognition (both end to end and HMM-DNN), speaker recognition, speech separation, multi-microphone signal processing (e.g., beamforming), self-supervised learning, and many others. [Learn more](https://speechbrain.github.io/)\n* SpaCy is a new wrapping library with consistent and easy-to-use interfaces to several models, in order to extract features to power NLP pipelines. Support is provided for via spaCy\u2019s standard training API. The library also calculates an alignment so the transformer features can be related back to actual words instead of just wordpieces. [Learn more](https://explosion.ai/blog/spacy-pytorch-transformers)\n* HuggingFace PyTorch-Transformers (formerly known as pytorch-pretrained-bert is a library of state-of-the-art pretrained models for Natural Language Processing (NLP). The library currently contains PyTorch implementations, pretrained model weights, usage scripts, and conversion utilities for models such as BERT, GPT-2, RoBERTa, and DistilBERT. It has also grown quickly, with more than 13,000 GitHub stars and a broad set of users. [Learn more](https://github.com/huggingface/transformers)\n* PyTorch Lightning is a Keras-like ML library for PyTorch. It leaves core training and validation logic to you and automates the rest. Reproducibility is a crucial requirement for many fields of research, including those based on ML techniques. As the number of research papers submitted to arXiv and conferences skyrockets into the tens of thousands, scaling reproducibility becomes difficult. [Learn more](https://github.com/williamFalcon/pytorch-lightning).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "We recently held the first online Global PyTorch Summer Hackathon, where researchers and developers around the world were invited to build innovative new projects with PyTorch. Nearly 1,500 developers participated, submitting projects ranging from livestock disease detection to AI-powered financial assistants. The winning projects were:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "* Google Cloud TPU support now broadly available. To accelerate the largest-scale machine learning (ML) applications deployed today and enable rapid development of the ML applications of tomorrow, Google created custom silicon chips called Tensor Processing Units ([TPUs](https://cloud.google.com/tpu/)). When assembled into multi-rack ML supercomputers called [Cloud TPU Pods](https://cloud.google.com/blog/products/ai-machine-learning/cloud-tpu-pods-break-ai-training-records), these TPUs can complete ML workloads in minutes or hours that previously took days or weeks on other systems. Engineers from Facebook, Google, and Salesforce worked together to enable and pilot Cloud TPU support in PyTorch, including experimental support for Cloud TPU Pods. PyTorch support for Cloud TPUs is also available in Colab. Learn more about how to get started with PyTorch on Cloud TPUs [here](https://github.com/pytorch/xla).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "* Alibaba adds support for PyTorch in Alibaba Cloud. The initial integration involves a one-click solution for PyTorch 1.x, Data Science Workshop notebook service, distributed training with Gloo/NCCL, as well as seamless integration with Alibaba IaaS such as OSS, ODPS, and NAS. Together with the toolchain provided by Alibaba, we look forward to significantly reducing the overhead necessary for adoption, as well as helping Alibaba Cloud\u2019s global customer base leverage PyTorch to develop new AI applications.\n* ML hardware ecosystem expands. In addition to key GPU and CPU partners, the PyTorch ecosystem has also enabled support for dedicated ML accelerators. Updates from [Intel](https://www.intel.ai/nnpi-glow-pytorch/) and [Habana](https://medium.com/@HabanaLabs/unlocking-ai-scaling-through-software-and-hardware-interface-standardization-77561cb7598b) showcase how PyTorch, connected to the Glow optimizing compiler, enables developers to utilize these market-specific solutions.\n\n# Growth in the PyTorch community", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "# Growth in the PyTorch community\n\nAs an open source, community-driven project, PyTorch benefits from wide range of contributors bringing new capabilities to the ecosystem. Here are some recent examples:\n\n* Mila SpeechBrain aims to provide an open source, all-in-one speech toolkit based on PyTorch. The goal is to develop a single, flexible, user-friendly toolkit that can be used to easily develop state-of-the-art systems for speech recognition (both end to end and HMM-DNN), speaker recognition, speech separation, multi-microphone signal processing (e.g., beamforming), self-supervised learning, and many others. [Learn more](https://speechbrain.github.io/)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "* SpaCy is a new wrapping library with consistent and easy-to-use interfaces to several models, in order to extract features to power NLP pipelines. Support is provided for via spaCy\u2019s standard training API. The library also calculates an alignment so the transformer features can be related back to actual words instead of just wordpieces. [Learn more](https://explosion.ai/blog/spacy-pytorch-transformers)\n* HuggingFace PyTorch-Transformers (formerly known as pytorch-pretrained-bert is a library of state-of-the-art pretrained models for Natural Language Processing (NLP). The library currently contains PyTorch implementations, pretrained model weights, usage scripts, and conversion utilities for models such as BERT, GPT-2, RoBERTa, and DistilBERT. It has also grown quickly, with more than 13,000 GitHub stars and a broad set of users. [Learn more](https://github.com/huggingface/transformers)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
+{"page_content": "* PyTorch Lightning is a Keras-like ML library for PyTorch. It leaves core training and validation logic to you and automates the rest. Reproducibility is a crucial requirement for many fields of research, including those based on ML techniques. As the number of research papers submitted to arXiv and conferences skyrockets into the tens of thousands, scaling reproducibility becomes difficult. [Learn more](https://github.com/williamFalcon/pytorch-lightning).\n\nWe recently held the first online Global PyTorch Summer Hackathon, where researchers and developers around the world were invited to build innovative new projects with PyTorch. Nearly 1,500 developers participated, submitting projects ranging from livestock disease detection to AI-powered financial assistants. The winning projects were:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "* Torchmeta, which provides extensions for PyTorch to simplify the development of meta-learning algorithms in PyTorch. It features a unified interface inspired by TorchVision for both few-shot classification and regression problems, to allow easy benchmarking on multiple data sets to aid with reproducibility.\n* Open-Unmix, a system for end-to-end music demixing with PyTorch. Demixing separates the individual instruments or vocal track from any stereo recording.\n* Endless AI-Generated Tees, a store featuring AI-generated T-shirt designs that can be purchased and delivered worldwide. The system uses a state-of-the-art generative model (StyleGAN) that was built with PyTorch and then trained on modern art.\n\nVisit [pytorch.org](https://pytorch.org/) to learn more and get started with PyTorch 1.3 and the latest libraries and ecosystem projects. We look forward to the contributions, exciting research advancements, and real-world applications that the community builds with PyTorch.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
{"page_content": "*We\u2019d like to thank the entire PyTorch team and the community for all their contributions to this work.*", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-3-adds-mobile-privacy-quantization-and-named-tensors/", "category": "pytorch blogs"}}
-{"page_content": "---\nlayout: blog_detail\ntitle: \"New library updates in PyTorch 1.12\"\nauthor: Team PyTorch\nfeatured-img: ''\n---\n\nWe are bringing a number of improvements to the current PyTorch libraries, alongside the [PyTorch 1.12 release](https://github.com/pytorch/pytorch/releases/tag/v1.12.0). These updates demonstrate our focus on developing common and extensible APIs across all domains to make it easier for our community to build ecosystem projects on PyTorch.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "Summary:\n- **TorchVision** - Added multi-weight support API, new architectures, model variants, and pretrained weight. See the release notes [here](https://github.com/pytorch/vision/releases).\n- **TorchAudio** - Introduced beta features including a streaming API, a CTC beam search decoder, and new beamforming modules and methods. See the release notes [here](https://github.com/pytorch/audio/releases).\n- **TorchText** - Extended support for scriptable BERT tokenizer and added datasets for GLUE benchmark. See the release notes [here](https://github.com/pytorch/text/releases).\n- **TorchRec** - Added EmbeddingModule benchmarks, examples for TwoTower Retrieval, inference and sequential embeddings, metrics, improved planner and demonstrated integration with production components. See the release notes [here](https://github.com/pytorch/torchrec/releases).\n- **TorchX** - Launch PyTorch trainers developed on local workspaces onto five different types of schedulers. See the release notes [here](https://github.com/pytorch/torchx/blob/main/CHANGELOG.md?plain=1#L3).\n- **FBGemm** - Added and improved kernels for Recommendation Systems inference workloads, including table batched embedding bag, jagged tensor operations, and other special-case optimizations.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "## TorchVision v0.13\n\n### Multi-weight support API\n\nTorchVision v0.13 offers a new [Multi-weight support API](https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/) for loading different weights to the existing model builder methods:\n\n```python\nfrom torchvision.models import *\n\n# Old weights with accuracy 76.130%\nresnet50(weights=ResNet50_Weights.IMAGENET1K_V1)\n\n# New weights with accuracy 80.858%\nresnet50(weights=ResNet50_Weights.IMAGENET1K_V2)\n\n# Best available weights (currently alias for IMAGENET1K_V2)\n# Note that these weights may change across versions\nresnet50(weights=ResNet50_Weights.DEFAULT)\n\n# Strings are also supported\nresnet50(weights=\"IMAGENET1K_V2\")\n\n# No weights - random initialization\nresnet50(weights=None)\n```\n\nThe new API bundles along with the weights important details such as the preprocessing transforms and meta-data such as labels. Here is how to make the most out of it:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "```python\nfrom torchvision.io import read_image\nfrom torchvision.models import resnet50, ResNet50_Weights\n\nimg = read_image(\"test/assets/encode_jpeg/grace_hopper_517x606.jpg\")\n\n# Step 1: Initialize model with the best available weights\nweights = ResNet50_Weights.DEFAULT\nmodel = resnet50(weights=weights)\nmodel.eval()\n\n# Step 2: Initialize the inference transforms\npreprocess = weights.transforms()\n\n# Step 3: Apply inference preprocessing transforms\nbatch = preprocess(img).unsqueeze(0)\n\n# Step 4: Use the model and print the predicted category\nprediction = model(batch).squeeze(0).softmax(0)\nclass_id = prediction.argmax().item()\nscore = prediction[class_id].item()\ncategory_name = weights.meta[\"categories\"][class_id]\nprint(f\"{category_name}: {100 * score:.1f}%\")\n```\n\nYou can read more about the new API in the [docs](https://pytorch.org/vision/0.13/models.html). To provide your feedback, please use this dedicated [Github issue](https://github.com/pytorch/vision/issues/5088).\n\n### New architectures and model variants", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### New architectures and model variants\n\n#### Classification\n\nThe [Swin Transformer](https://arxiv.org/abs/2103.14030) and [EfficienetNetV2](https://arxiv.org/abs/2104.00298) are two popular classification models which are often used for downstream vision tasks. This release includes 6 pre-trained weights for their classification variants. Here is how to use the new models:\n\n```python\nimport torch\nfrom torchvision.models import *\n\nimage = torch.rand(1, 3, 224, 224)\nmodel = swin_t(weights=\"DEFAULT\").eval()\nprediction = model(image)\n\nimage = torch.rand(1, 3, 384, 384)\nmodel = efficientnet_v2_s(weights=\"DEFAULT\").eval()\nprediction = model(image)\n```\n\nIn addition to the above, we also provide new variants for existing architectures such as ShuffleNetV2, ResNeXt and MNASNet. The accuracies of all the new pre-trained models obtained on ImageNet-1K are seen below:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "| **Model** | **Acc@1** | **Acc@5** |\n|--------------------------------|-----------|-----------|\n| swin_t | 81.474 | 95.776 |\n| swin_s | 83.196 | 96.36 |\n| swin_b | 83.582 | 96.64 |\n| efficientnet_v2_s | 84.228 | 96.878 |\n| efficientnet_v2_m | 85.112 | 97.156 |\n| efficientnet_v2_l | 85.808 | 97.788 |\n| resnext101_64x4d | 83.246 | 96.454 |\n| resnext101_64x4d (quantized) | 82.898 | 96.326 |\n| shufflenet_v2_x1_5 | 72.996 | 91.086 |\n| shufflenet_v2_x1_5 (quantized) | 72.052 | 0.700 |\n| shufflenet_v2_x2_0 | 76.230 | 93.006 |\n| shufflenet_v2_x2_0 (quantized) | 75.354 | 92.488 |\n| mnasnet0_75 | 71.180 | 90.496 |\n| mnas1_3 | 76.506 | 93.522 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "We would like to thank Hu Ye for contributing to TorchVision the Swin Transformer implementation.\n\n#### (BETA) Object Detection and Instance Segmentation\n\nWe have introduced 3 new model variants for RetinaNet, FasterRCNN and MaskRCNN that include several [post-paper architectural optimizations](https://github.com/pytorch/vision/pull/5444) and improved training recipes. All models can be used similarly:\n\n```python\nimport torch\nfrom torchvision.models.detection import *\n\nimages = [torch.rand(3, 800, 600)]\nmodel = retinanet_resnet50_fpn_v2(weights=\"DEFAULT\")\n# model = fasterrcnn_resnet50_fpn_v2(weights=\"DEFAULT\")\n# model = maskrcnn_resnet50_fpn_v2(weights=\"DEFAULT\")\nmodel.eval()\nprediction = model(images)\n```\n\nBelow we present the metrics of the new variants on COCO val2017. In parenthesis we denote the improvement over the old variants:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "| **Model** | **Box mAP** | **Mask mAP** |\n|----------------------------|-------------|--------------|\n| retinanet_resnet50_fpn_v2 | 41.5 (+5.1) | - |\n| fasterrcnn_resnet50_fpn_v2 | 46.7 (+9.7) | - |\n| maskrcnn_resnet50_fpn_v2 | 47.4 (+9.5) | 41.8 (+7.2) |\n\nWe would like to thank Ross Girshick, Piotr Dollar, Vaibhav Aggarwal, Francisco Massa and Hu Ye for their past research and contributions to this work.\n\n### New pre-trained weights \n\n#### SWAG weights\n\nThe ViT and RegNet model variants offer new pre-trained [SWAG](https://arxiv.org/abs/2201.08371) (\u200b\u200bSupervised Weakly from hashtAGs) weights. One of the biggest of these models achieves a whopping 88.6% accuracy on ImageNet-1K. We currently offer two versions of the weights: 1) fine-tuned end-to-end weights on ImageNet-1K (highest accuracy) and 2) frozen trunk weights with a linear classifier fit on ImageNet-1K (great for transfer learning). Below we see the detailed accuracies of each model variant:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "| **Model Weights** | **Acc@1** | **Acc@5** |\n|--------------------------------------------------|-----------|-----------|\n| RegNet_Y_16GF_Weights.IMAGENET1K_SWAG_E2E_V1 | 86.012 | 98.054 |\n| RegNet_Y_16GF_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 83.976 | 97.244 |\n| RegNet_Y_32GF_Weights.IMAGENET1K_SWAG_E2E_V1 | 86.838 | 98.362 |\n| RegNet_Y_32GF_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 84.622 | 97.48 |\n| RegNet_Y_128GF_Weights.IMAGENET1K_SWAG_E2E_V1 | 88.228 | 98.682 |\n| RegNet_Y_128GF_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 86.068 | 97.844 |\n| ViT_B_16_Weights.IMAGENET1K_SWAG_E2E_V1 | 85.304 | 97.65 |\n| ViT_B_16_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 81.886 | 96.18 |\n| ViT_L_16_Weights.IMAGENET1K_SWAG_E2E_V1 | 88.064 | 98.512 |\n| ViT_L_16_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 85.146 | 97.422 |\n| ViT_H_14_Weights.IMAGENET1K_SWAG_E2E_V1 | 88.552 | 98.694 |\n| ViT_H_14_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 85.708 | 97.73 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "The SWAG weights are released under the [Attribution-NonCommercial 4.0 International](https://github.com/facebookresearch/SWAG/blob/main/LICENSE) license. We would like to thank Laura Gustafson, Mannat Singh and Aaron Adcock for their work and support in making the weights available to TorchVision.\n\n#### Model Refresh\n\nThe release of the Multi-weight support API enabled us to refresh the most popular models and offer more accurate weights. We improved on average each model by ~3 points. The new recipe used was learned on top of ResNet50 and its details were covered on a [previous blog post](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "| **Model** | **Old weights** | **New weights** |\n|------------------------------|-----------------|-----------------|\n| efficientnet_b1 | 78.642 | 79.838 |\n| mobilenet_v2 | 71.878 | 72.154 |\n| mobilenet_v3_large | 74.042 | 75.274 |\n| regnet_y_400mf | 74.046 | 75.804 |\n| regnet_y_800mf | 76.42 | 78.828 |\n| regnet_y_1_6gf | 77.95 | 80.876 |\n| regnet_y_3_2gf | 78.948 | 81.982 |\n| regnet_y_8gf | 80.032 | 82.828 |\n| regnet_y_16gf | 80.424 | 82.886 |\n| regnet_y_32gf | 80.878 | 83.368 |\n| regnet_x_400mf | 72.834 | 74.864 |\n| regnet_x_800mf | 75.212 | 77.522 |\n| regnet_x_1_6gf | 77.04 | 79.668 |\n| regnet_x_3_2gf | 78.364 | 81.196 |\n| regnet_x_8gf | 79.344 | 81.682 |\n| regnet_x_16gf | 80.058 | 82.716 |\n| regnet_x_32gf | 80.622 | 83.014 |\n| resnet50 | 76.13 | 80.858 |\n| resnet50 (quantized) | 75.92 | 80.282 |\n| resnet101 | 77.374 | 81.886 |\n| resnet152 | 78.312 | 82.284 |\n| resnext50_32x4d | 77.618 | 81.198 |\n| resnext101_32x8d | 79.312 | 82.834 |\n| resnext101_32x8d (quantized) | 78.986 | 82.574 |\n| wide_resnet50_2 | 78.468 | 81.602 |\n| wide_resnet101_2 | 78.848 | 82.51 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "We would like to thank Piotr Dollar, Mannat Singh and Hugo Touvron for their past research and contributions to this work.\n\n### New Augmentations, Layers and Losses\n\nThis release brings a bunch of new primitives which can be used to produce SOTA models. Some highlights include the addition of [AugMix](https://arxiv.org/abs/1912.02781) data-augmentation method, the [DropBlock](https://arxiv.org/abs/1810.12890) layer, the [cIoU/dIoU](https://arxiv.org/abs/1911.08287) loss and [many more](https://github.com/pytorch/vision/issues/5410). We would like to thank Aditya Oke, Abhijit Deo, Yassine Alouini and Hu Ye for contributing to the project and for helping us maintain TorchVision relevant and fresh.\n\n### Documentation", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "---\nlayout: blog_detail\ntitle: \"New library updates in PyTorch 1.12\"\nauthor: Team PyTorch\nfeatured-img: ''\n---\n\nWe are bringing a number of improvements to the current PyTorch libraries, alongside the [PyTorch 1.12 release](https://github.com/pytorch/pytorch/releases/tag/v1.12.0). These updates demonstrate our focus on developing common and extensible APIs across all domains to make it easier for our community to build ecosystem projects on PyTorch. \n\nSummary:\n- **TorchVision** - Added multi-weight support API, new architectures, model variants, and pretrained weight. See the release notes [here](https://github.com/pytorch/vision/releases).\n- **TorchAudio** - Introduced beta features including a streaming API, a CTC beam search decoder, and new beamforming modules and methods. See the release notes [here](https://github.com/pytorch/audio/releases).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- **TorchText** - Extended support for scriptable BERT tokenizer and added datasets for GLUE benchmark. See the release notes [here](https://github.com/pytorch/text/releases).\n- **TorchRec** - Added EmbeddingModule benchmarks, examples for TwoTower Retrieval, inference and sequential embeddings, metrics, improved planner and demonstrated integration with production components. See the release notes [here](https://github.com/pytorch/torchrec/releases).\n- **TorchX** - Launch PyTorch trainers developed on local workspaces onto five different types of schedulers. See the release notes [here](https://github.com/pytorch/torchx/blob/main/CHANGELOG.md?plain=1#L3).\n- **FBGemm** - Added and improved kernels for Recommendation Systems inference workloads, including table batched embedding bag, jagged tensor operations, and other special-case optimizations.\n\n## TorchVision v0.13\n\n### Multi-weight support API", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### Multi-weight support API\n\nTorchVision v0.13 offers a new [Multi-weight support API](https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/) for loading different weights to the existing model builder methods:\n\n```python\nfrom torchvision.models import *\n\n# Old weights with accuracy 76.130%\nresnet50(weights=ResNet50_Weights.IMAGENET1K_V1)\n\n# New weights with accuracy 80.858%\nresnet50(weights=ResNet50_Weights.IMAGENET1K_V2)\n\n# Best available weights (currently alias for IMAGENET1K_V2)\n# Note that these weights may change across versions\nresnet50(weights=ResNet50_Weights.DEFAULT)\n\n# Strings are also supported\nresnet50(weights=\"IMAGENET1K_V2\")\n\n# No weights - random initialization\nresnet50(weights=None)\n```\n\nThe new API bundles along with the weights important details such as the preprocessing transforms and meta-data such as labels. Here is how to make the most out of it:\n\n```python\nfrom torchvision.io import read_image\nfrom torchvision.models import resnet50, ResNet50_Weights", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "img = read_image(\"test/assets/encode_jpeg/grace_hopper_517x606.jpg\")\n\n# Step 1: Initialize model with the best available weights\nweights = ResNet50_Weights.DEFAULT\nmodel = resnet50(weights=weights)\nmodel.eval()\n\n# Step 2: Initialize the inference transforms\npreprocess = weights.transforms()\n\n# Step 3: Apply inference preprocessing transforms\nbatch = preprocess(img).unsqueeze(0)\n\n# Step 4: Use the model and print the predicted category\nprediction = model(batch).squeeze(0).softmax(0)\nclass_id = prediction.argmax().item()\nscore = prediction[class_id].item()\ncategory_name = weights.meta[\"categories\"][class_id]\nprint(f\"{category_name}: {100 * score:.1f}%\")\n```\n\nYou can read more about the new API in the [docs](https://pytorch.org/vision/0.13/models.html). To provide your feedback, please use this dedicated [Github issue](https://github.com/pytorch/vision/issues/5088).\n\n### New architectures and model variants\n\n#### Classification", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "#### Classification\n\nThe [Swin Transformer](https://arxiv.org/abs/2103.14030) and [EfficienetNetV2](https://arxiv.org/abs/2104.00298) are two popular classification models which are often used for downstream vision tasks. This release includes 6 pre-trained weights for their classification variants. Here is how to use the new models:\n\n```python\nimport torch\nfrom torchvision.models import *\n\nimage = torch.rand(1, 3, 224, 224)\nmodel = swin_t(weights=\"DEFAULT\").eval()\nprediction = model(image)\n\nimage = torch.rand(1, 3, 384, 384)\nmodel = efficientnet_v2_s(weights=\"DEFAULT\").eval()\nprediction = model(image)\n```\n\nIn addition to the above, we also provide new variants for existing architectures such as ShuffleNetV2, ResNeXt and MNASNet. The accuracies of all the new pre-trained models obtained on ImageNet-1K are seen below:\n\n| **Model** | **Acc@1** | **Acc@5** |\n|--------------------------------|-----------|-----------|\n| swin_t | 81.474 | 95.776 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "| swin_s | 83.196 | 96.36 |\n| swin_b | 83.582 | 96.64 |\n| efficientnet_v2_s | 84.228 | 96.878 |\n| efficientnet_v2_m | 85.112 | 97.156 |\n| efficientnet_v2_l | 85.808 | 97.788 |\n| resnext101_64x4d | 83.246 | 96.454 |\n| resnext101_64x4d (quantized) | 82.898 | 96.326 |\n| shufflenet_v2_x1_5 | 72.996 | 91.086 |\n| shufflenet_v2_x1_5 (quantized) | 72.052 | 0.700 |\n| shufflenet_v2_x2_0 | 76.230 | 93.006 |\n| shufflenet_v2_x2_0 (quantized) | 75.354 | 92.488 |\n| mnasnet0_75 | 71.180 | 90.496 |\n| mnas1_3 | 76.506 | 93.522 |\n\nWe would like to thank Hu Ye for contributing to TorchVision the Swin Transformer implementation.\n\n#### (BETA) Object Detection and Instance Segmentation", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "We have introduced 3 new model variants for RetinaNet, FasterRCNN and MaskRCNN that include several [post-paper architectural optimizations](https://github.com/pytorch/vision/pull/5444) and improved training recipes. All models can be used similarly:\n\n```python\nimport torch\nfrom torchvision.models.detection import *\n\nimages = [torch.rand(3, 800, 600)]\nmodel = retinanet_resnet50_fpn_v2(weights=\"DEFAULT\")\n# model = fasterrcnn_resnet50_fpn_v2(weights=\"DEFAULT\")\n# model = maskrcnn_resnet50_fpn_v2(weights=\"DEFAULT\")\nmodel.eval()\nprediction = model(images)\n```\n\nBelow we present the metrics of the new variants on COCO val2017. In parenthesis we denote the improvement over the old variants:\n\n| **Model** | **Box mAP** | **Mask mAP** |\n|----------------------------|-------------|--------------|\n| retinanet_resnet50_fpn_v2 | 41.5 (+5.1) | - |\n| fasterrcnn_resnet50_fpn_v2 | 46.7 (+9.7) | - |\n| maskrcnn_resnet50_fpn_v2 | 47.4 (+9.5) | 41.8 (+7.2) |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "We would like to thank Ross Girshick, Piotr Dollar, Vaibhav Aggarwal, Francisco Massa and Hu Ye for their past research and contributions to this work.\n\n### New pre-trained weights \n\n#### SWAG weights\n\nThe ViT and RegNet model variants offer new pre-trained [SWAG](https://arxiv.org/abs/2201.08371) (\u200b\u200bSupervised Weakly from hashtAGs) weights. One of the biggest of these models achieves a whopping 88.6% accuracy on ImageNet-1K. We currently offer two versions of the weights: 1) fine-tuned end-to-end weights on ImageNet-1K (highest accuracy) and 2) frozen trunk weights with a linear classifier fit on ImageNet-1K (great for transfer learning). Below we see the detailed accuracies of each model variant:\n\n| **Model Weights** | **Acc@1** | **Acc@5** |\n|--------------------------------------------------|-----------|-----------|\n| RegNet_Y_16GF_Weights.IMAGENET1K_SWAG_E2E_V1 | 86.012 | 98.054 |\n| RegNet_Y_16GF_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 83.976 | 97.244 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "| RegNet_Y_32GF_Weights.IMAGENET1K_SWAG_E2E_V1 | 86.838 | 98.362 |\n| RegNet_Y_32GF_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 84.622 | 97.48 |\n| RegNet_Y_128GF_Weights.IMAGENET1K_SWAG_E2E_V1 | 88.228 | 98.682 |\n| RegNet_Y_128GF_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 86.068 | 97.844 |\n| ViT_B_16_Weights.IMAGENET1K_SWAG_E2E_V1 | 85.304 | 97.65 |\n| ViT_B_16_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 81.886 | 96.18 |\n| ViT_L_16_Weights.IMAGENET1K_SWAG_E2E_V1 | 88.064 | 98.512 |\n| ViT_L_16_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 85.146 | 97.422 |\n| ViT_H_14_Weights.IMAGENET1K_SWAG_E2E_V1 | 88.552 | 98.694 |\n| ViT_H_14_Weights.IMAGENET1K_SWAG_LINEAR_V1 | 85.708 | 97.73 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "The SWAG weights are released under the [Attribution-NonCommercial 4.0 International](https://github.com/facebookresearch/SWAG/blob/main/LICENSE) license. We would like to thank Laura Gustafson, Mannat Singh and Aaron Adcock for their work and support in making the weights available to TorchVision.\n\n#### Model Refresh\n\nThe release of the Multi-weight support API enabled us to refresh the most popular models and offer more accurate weights. We improved on average each model by ~3 points. The new recipe used was learned on top of ResNet50 and its details were covered on a [previous blog post](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/). \n\n| **Model** | **Old weights** | **New weights** |\n|------------------------------|-----------------|-----------------|\n| efficientnet_b1 | 78.642 | 79.838 |\n| mobilenet_v2 | 71.878 | 72.154 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "| mobilenet_v3_large | 74.042 | 75.274 |\n| regnet_y_400mf | 74.046 | 75.804 |\n| regnet_y_800mf | 76.42 | 78.828 |\n| regnet_y_1_6gf | 77.95 | 80.876 |\n| regnet_y_3_2gf | 78.948 | 81.982 |\n| regnet_y_8gf | 80.032 | 82.828 |\n| regnet_y_16gf | 80.424 | 82.886 |\n| regnet_y_32gf | 80.878 | 83.368 |\n| regnet_x_400mf | 72.834 | 74.864 |\n| regnet_x_800mf | 75.212 | 77.522 |\n| regnet_x_1_6gf | 77.04 | 79.668 |\n| regnet_x_3_2gf | 78.364 | 81.196 |\n| regnet_x_8gf | 79.344 | 81.682 |\n| regnet_x_16gf | 80.058 | 82.716 |", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "| regnet_x_32gf | 80.622 | 83.014 |\n| resnet50 | 76.13 | 80.858 |\n| resnet50 (quantized) | 75.92 | 80.282 |\n| resnet101 | 77.374 | 81.886 |\n| resnet152 | 78.312 | 82.284 |\n| resnext50_32x4d | 77.618 | 81.198 |\n| resnext101_32x8d | 79.312 | 82.834 |\n| resnext101_32x8d (quantized) | 78.986 | 82.574 |\n| wide_resnet50_2 | 78.468 | 81.602 |\n| wide_resnet101_2 | 78.848 | 82.51 |\n\nWe would like to thank Piotr Dollar, Mannat Singh and Hugo Touvron for their past research and contributions to this work.\n\n### New Augmentations, Layers and Losses", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### New Augmentations, Layers and Losses\n\nThis release brings a bunch of new primitives which can be used to produce SOTA models. Some highlights include the addition of [AugMix](https://arxiv.org/abs/1912.02781) data-augmentation method, the [DropBlock](https://arxiv.org/abs/1810.12890) layer, the [cIoU/dIoU](https://arxiv.org/abs/1911.08287) loss and [many more](https://github.com/pytorch/vision/issues/5410). We would like to thank Aditya Oke, Abhijit Deo, Yassine Alouini and Hu Ye for contributing to the project and for helping us maintain TorchVision relevant and fresh.\n\n### Documentation", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "We completely revamped our models documentation to make them easier to browse, and added various key information such as supported image sizes, or image pre-processing steps of pre-trained weights. We now have a [main model page](https://pytorch.org/vision/main/models.html) with various [summary tables](https://pytorch.org/vision/main/models.html#table-of-all-available-classification-weights) of available weights, and each model has a [dedicated page](https://pytorch.org/vision/main/models/resnet.html). Each model builder is also documented in their [own page](https://pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html#torchvision.models.resnet50), with more details about the available weights, including accuracy, minimal image size, link to training recipes, and other valuable info. For comparison, our previous models docs are [here](https://pytorch.org/vision/0.12/models.html). To provide feedback on the new documentation, please use the dedicated [Github issue](https://github.com/pytorch/vision/issues/5511).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "## TorchAudio v0.12\n\n### (BETA) Streaming API\n\n\n
\n
\n\n\nStreamReader is TorchAudio\u2019s new I/O API. It is backed by FFmpeg\u2020, and allows users to:\n- Decode audio and video formats, including MP4 and AAC\n- Handle input forms, such as local files, network protocols, microphones, webcams, screen captures and file-like objects\n- Iterate over and decode chunk-by-chunk, while changing the sample rate or frame rate\n- Apply audio and video filters, such as low-pass filter and image scaling\n- Decode video with Nvidia's hardware-based decoder (NVDEC)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "For usage details, please check out the [documentation](https://pytorch.org/audio/0.12.0/io.html#streamreader) and tutorials:\n- [Media Stream API - Pt.1](https://pytorch.org/audio/0.12.0/tutorials/streaming_api_tutorial.html)\n- [Media Stream API - Pt.2](https://pytorch.org/audio/0.12.0/tutorials/streaming_api2_tutorial.html)\n- [Online ASR with Emformer RNN-T](https://pytorch.org/audio/0.12.0/tutorials/online_asr_tutorial.html)\n- [Device ASR with Emformer RNN-T](https://pytorch.org/audio/0.12.0/tutorials/device_asr.html)\n- [Accelerated Video Decoding with NVDEC](https://pytorch.org/audio/0.12.0/hw_acceleration_tutorial.html)\n\n\u2020 To use StreamReader, FFmpeg libraries are required. Please install FFmpeg. The coverage of codecs depends on how these libraries are configured. TorchAudio official binaries are compiled to work with FFmpeg 4 libraries; FFmpeg 5 can be used if TorchAudio is built from source.\n\n### (BETA) CTC Beam Search Decoder", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### (BETA) CTC Beam Search Decoder\n\nTorchAudio integrates the wav2letter CTC beam search decoder from [Flashlight](https://arxiv.org/pdf/2201.12465.pdf) ([GitHub](https://github.com/flashlight/flashlight)). The addition of this inference time decoder enables running end-to-end CTC ASR evaluation using TorchAudio utils.\n\nCustomizable lexicon and lexicon-free decoders are supported, and both are compatible with KenLM n-gram language models or without using a language model. TorchAudio additionally supports downloading token, lexicon, and pretrained KenLM files for the LibriSpeech dataset.\n\nFor usage details, please check out the [documentation](https://pytorch.org/audio/0.12.0/models.decoder.html#ctcdecoder) and [ASR inference tutorial](https://pytorch.org/audio/0.12.0/tutorials/asr_inference_with_ctc_decoder_tutorial.html).\n\n### (BETA) New Beamforming Modules and Methods", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### (BETA) New Beamforming Modules and Methods\n\nTo improve flexibility in usage, the release adds two new beamforming modules under torchaudio.transforms: [SoudenMVDR](https://pytorch.org/audio/0.12.0/transforms.html#soudenmvdr) and [RTFMVDR](https://pytorch.org/audio/0.12.0/transforms.html#rtfmvdr). The main differences from [MVDR](https://pytorch.org/audio/0.11.0/transforms.html#mvdr) are:\n- Use power spectral density (PSD) and relative transfer function (RTF) matrices as inputs instead of time-frequency masks. The module can be integrated with neural networks that directly predict complex-valued STFT coefficients of speech and noise\n- Add \\'reference_channel\\' as an input argument in the forward method, to allow users to select the reference channel in model training or dynamically change the reference channel in inference", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "Besides the two modules, new function-level beamforming methods are added under torchaudio.functional. These include:\n- [psd](https://pytorch.org/audio/0.12.0/functional.html#psd)\n- [mvdr_weights_souden](https://pytorch.org/audio/0.12.0/functional.html#mvdr-weights-souden)\n- [mvdr_weights_rtf](https://pytorch.org/audio/0.12.0/functional.html#mvdr-weights-rtf)\n- [rtf_evd](https://pytorch.org/audio/0.12.0/functional.html#rtf-evd)\n- [rtf_power](https://pytorch.org/audio/0.12.0/functional.html#rtf-power)\n- [apply_beamforming](https://pytorch.org/audio/0.12.0/functional.html#apply-beamforming)\n\nFor usage details, please check out the documentation at [torchaudio.transforms](https://pytorch.org/audio/0.12.0/transforms.html#multi-channel) and [torchaudio.functional](https://pytorch.org/audio/0.12.0/functional.html#multi-channel) and the [Speech Enhancement with MVDR Beamforming tutorial](https://pytorch.org/audio/0.12.0/tutorials/mvdr_tutorial.html).\n\n## TorchText v0.13\n\n### Glue Datasets", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "We increased the number of datasets in TorchText from 22 to 30 by adding the remaining 8 datasets from the GLUE benchmark (SST-2 was already supported). The complete list of GLUE datasets is as follows:\n- [CoLA](https://nyu-mll.github.io/CoLA/) ([paper](https://arxiv.org/pdf/1805.12471.pdf)): Single sentence binary classification acceptability task\n- [SST-2](https://nlp.stanford.edu/sentiment/) ([paper](https://nlp.stanford.edu/~socherr/EMNLP2013_RNTN.pdf)): Single sentence binary classification sentiment task\n- [MRPC](https://nlp.stanford.edu/~socherr/EMNLP2013_RNTN.pdf) ([paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/I05-50025B15D.pdf)): Dual sentence binary classification paraphrase task\n- [QQP](https://quoradata.quora.com/First-Quora-Dataset-Release-Question-Pairs): Dual sentence binary classification paraphrase task\n- [STS-B](https://ixa2.si.ehu.eus/stswiki/index.php/STSbenchmark) ([paper](https://aclanthology.org/S17-2001.pdf)): Single sentence to float regression sentence similarity task\n- [MNLI](https://cims.nyu.edu/~sbowman/multinli/) ([paper](https://cims.nyu.edu/~sbowman/multinli/paper.pdf)): Sentence ternary classification NLI task\n- [QNLI](https://gluebenchmark.com/) ([paper](https://arxiv.org/pdf/1804.07461.pdf)): Sentence binary classification QA and NLI tasks\n- [RTE](https://aclweb.org/aclwiki/Recognizing_Textual_Entailment) ([paper](https://arxiv.org/pdf/2010.03061.pdf)): Dual sentence binary classification NLI task\n- [WNLI](https://cs.nyu.edu/~davise/papers/WinogradSchemas/WS.html) ([paper](http://commonsensereasoning.org/2011/papers/Levesque.pdf)): Dual sentence binary classification coreference and NLI tasks", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### Scriptable BERT Tokenizer\n\nTorchText has extended support for scriptable tokenizer by adding the WordPiece tokenizer used in BERT. It is one of the commonly used algorithms for splitting input text into sub-words units and was introduced in [Japanese and Korean Voice Search (Schuster et al., 2012)](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf). \n\nTorchScriptabilty support would allow users to embed the BERT text-preprocessing natively in C++ without needing the support of python runtime. As TorchText now supports the CMAKE build system to natively link torchtext binaries with application code, users can easily integrate BERT tokenizers for deployment needs.\n\nFor usage details, please refer to the corresponding [documentation](https://pytorch.org/text/main/transforms.html#torchtext.transforms.BERTTokenizer).\n\n## TorchRec v0.2.0\n\n### EmbeddingModule + DLRM benchmarks", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### EmbeddingModule + DLRM benchmarks\n\nA set of [benchmarking tests](https://github.com/pytorch/torchrec/tree/main/benchmarks), showing performance characteristics of TorchRec\u2019s base modules and research models built out of TorchRec.\n\n### TwoTower Retrieval Example, with FAISS\n\nWe provide an [example](https://github.com/pytorch/torchrec/tree/main/examples/retrieval) demonstrating training a distributed TwoTower (i.e. User-Item) Retrieval model that is sharded using TorchRec. The projected item embeddings are added to an IVFPQ FAISS index for candidate generation. The retrieval model and KNN lookup are bundled in a Pytorch model for efficient end-to-end retrieval.\n\n### Integrations", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### Integrations\n\nWe demonstrate that TorchRec works out of the box with many components commonly used alongside PyTorch models in production like systems, such as \n- [Training](https://github.com/pytorch/torchrec/tree/main/examples/ray) a TorchRec model on Ray Clusters utilizing the Torchx Ray scheduler\n- [Preprocessing](https://github.com/pytorch/torchrec/tree/main/torchrec/datasets/scripts/nvt) and DataLoading with NVTabular on DLRM\n- [Training](https://github.com/pytorch/torchrec/tree/main/examples/torcharrow) a TorchRec model with on-the-fly preprocessing with TorchArrow showcasing RecSys domain UDFs\n\n### Sequential Embeddings Example: Bert4Rec\n\nWe provide an [example](https://github.com/pytorch/torchrec/tree/main/examples/bert4rec), using TorchRec, that reimplements the [BERT4REC](https://arxiv.org/abs/1904.06690) paper, showcasing EmbeddingCollection for non-pooled embeddings. Using DistributedModelParallel we see a 35% QPS gain over conventional data parallelism.\n\n### (Beta) Planner", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "## TorchAudio v0.12\n\n### (BETA) Streaming API\n\n\n
\n
\n\n\nStreamReader is TorchAudio\u2019s new I/O API. It is backed by FFmpeg\u2020, and allows users to:\n- Decode audio and video formats, including MP4 and AAC\n- Handle input forms, such as local files, network protocols, microphones, webcams, screen captures and file-like objects\n- Iterate over and decode chunk-by-chunk, while changing the sample rate or frame rate\n- Apply audio and video filters, such as low-pass filter and image scaling\n- Decode video with Nvidia's hardware-based decoder (NVDEC)\n\nFor usage details, please check out the [documentation](https://pytorch.org/audio/0.12.0/io.html#streamreader) and tutorials:\n- [Media Stream API - Pt.1](https://pytorch.org/audio/0.12.0/tutorials/streaming_api_tutorial.html)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- [Media Stream API - Pt.2](https://pytorch.org/audio/0.12.0/tutorials/streaming_api2_tutorial.html)\n- [Online ASR with Emformer RNN-T](https://pytorch.org/audio/0.12.0/tutorials/online_asr_tutorial.html)\n- [Device ASR with Emformer RNN-T](https://pytorch.org/audio/0.12.0/tutorials/device_asr.html)\n- [Accelerated Video Decoding with NVDEC](https://pytorch.org/audio/0.12.0/hw_acceleration_tutorial.html)\n\n\u2020 To use StreamReader, FFmpeg libraries are required. Please install FFmpeg. The coverage of codecs depends on how these libraries are configured. TorchAudio official binaries are compiled to work with FFmpeg 4 libraries; FFmpeg 5 can be used if TorchAudio is built from source.\n\n### (BETA) CTC Beam Search Decoder\n\nTorchAudio integrates the wav2letter CTC beam search decoder from [Flashlight](https://arxiv.org/pdf/2201.12465.pdf) ([GitHub](https://github.com/flashlight/flashlight)). The addition of this inference time decoder enables running end-to-end CTC ASR evaluation using TorchAudio utils.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "Customizable lexicon and lexicon-free decoders are supported, and both are compatible with KenLM n-gram language models or without using a language model. TorchAudio additionally supports downloading token, lexicon, and pretrained KenLM files for the LibriSpeech dataset.\n\nFor usage details, please check out the [documentation](https://pytorch.org/audio/0.12.0/models.decoder.html#ctcdecoder) and [ASR inference tutorial](https://pytorch.org/audio/0.12.0/tutorials/asr_inference_with_ctc_decoder_tutorial.html).\n\n### (BETA) New Beamforming Modules and Methods\n\nTo improve flexibility in usage, the release adds two new beamforming modules under torchaudio.transforms: [SoudenMVDR](https://pytorch.org/audio/0.12.0/transforms.html#soudenmvdr) and [RTFMVDR](https://pytorch.org/audio/0.12.0/transforms.html#rtfmvdr). The main differences from [MVDR](https://pytorch.org/audio/0.11.0/transforms.html#mvdr) are:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- Use power spectral density (PSD) and relative transfer function (RTF) matrices as inputs instead of time-frequency masks. The module can be integrated with neural networks that directly predict complex-valued STFT coefficients of speech and noise\n- Add \\'reference_channel\\' as an input argument in the forward method, to allow users to select the reference channel in model training or dynamically change the reference channel in inference\n\nBesides the two modules, new function-level beamforming methods are added under torchaudio.functional. These include:\n- [psd](https://pytorch.org/audio/0.12.0/functional.html#psd)\n- [mvdr_weights_souden](https://pytorch.org/audio/0.12.0/functional.html#mvdr-weights-souden)\n- [mvdr_weights_rtf](https://pytorch.org/audio/0.12.0/functional.html#mvdr-weights-rtf)\n- [rtf_evd](https://pytorch.org/audio/0.12.0/functional.html#rtf-evd)\n- [rtf_power](https://pytorch.org/audio/0.12.0/functional.html#rtf-power)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- [apply_beamforming](https://pytorch.org/audio/0.12.0/functional.html#apply-beamforming)\n\nFor usage details, please check out the documentation at [torchaudio.transforms](https://pytorch.org/audio/0.12.0/transforms.html#multi-channel) and [torchaudio.functional](https://pytorch.org/audio/0.12.0/functional.html#multi-channel) and the [Speech Enhancement with MVDR Beamforming tutorial](https://pytorch.org/audio/0.12.0/tutorials/mvdr_tutorial.html).\n\n## TorchText v0.13\n\n### Glue Datasets\n\nWe increased the number of datasets in TorchText from 22 to 30 by adding the remaining 8 datasets from the GLUE benchmark (SST-2 was already supported). The complete list of GLUE datasets is as follows:\n- [CoLA](https://nyu-mll.github.io/CoLA/) ([paper](https://arxiv.org/pdf/1805.12471.pdf)): Single sentence binary classification acceptability task\n- [SST-2](https://nlp.stanford.edu/sentiment/) ([paper](https://nlp.stanford.edu/~socherr/EMNLP2013_RNTN.pdf)): Single sentence binary classification sentiment task", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- [MRPC](https://nlp.stanford.edu/~socherr/EMNLP2013_RNTN.pdf) ([paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/I05-50025B15D.pdf)): Dual sentence binary classification paraphrase task\n- [QQP](https://quoradata.quora.com/First-Quora-Dataset-Release-Question-Pairs): Dual sentence binary classification paraphrase task\n- [STS-B](https://ixa2.si.ehu.eus/stswiki/index.php/STSbenchmark) ([paper](https://aclanthology.org/S17-2001.pdf)): Single sentence to float regression sentence similarity task\n- [MNLI](https://cims.nyu.edu/~sbowman/multinli/) ([paper](https://cims.nyu.edu/~sbowman/multinli/paper.pdf)): Sentence ternary classification NLI task\n- [QNLI](https://gluebenchmark.com/) ([paper](https://arxiv.org/pdf/1804.07461.pdf)): Sentence binary classification QA and NLI tasks\n- [RTE](https://aclweb.org/aclwiki/Recognizing_Textual_Entailment) ([paper](https://arxiv.org/pdf/2010.03061.pdf)): Dual sentence binary classification NLI task", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- [WNLI](https://cs.nyu.edu/~davise/papers/WinogradSchemas/WS.html) ([paper](http://commonsensereasoning.org/2011/papers/Levesque.pdf)): Dual sentence binary classification coreference and NLI tasks\n\n### Scriptable BERT Tokenizer\n\nTorchText has extended support for scriptable tokenizer by adding the WordPiece tokenizer used in BERT. It is one of the commonly used algorithms for splitting input text into sub-words units and was introduced in [Japanese and Korean Voice Search (Schuster et al., 2012)](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf). \n\nTorchScriptabilty support would allow users to embed the BERT text-preprocessing natively in C++ without needing the support of python runtime. As TorchText now supports the CMAKE build system to natively link torchtext binaries with application code, users can easily integrate BERT tokenizers for deployment needs.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "For usage details, please refer to the corresponding [documentation](https://pytorch.org/text/main/transforms.html#torchtext.transforms.BERTTokenizer).\n\n## TorchRec v0.2.0\n\n### EmbeddingModule + DLRM benchmarks\n\nA set of [benchmarking tests](https://github.com/pytorch/torchrec/tree/main/benchmarks), showing performance characteristics of TorchRec\u2019s base modules and research models built out of TorchRec.\n\n### TwoTower Retrieval Example, with FAISS\n\nWe provide an [example](https://github.com/pytorch/torchrec/tree/main/examples/retrieval) demonstrating training a distributed TwoTower (i.e. User-Item) Retrieval model that is sharded using TorchRec. The projected item embeddings are added to an IVFPQ FAISS index for candidate generation. The retrieval model and KNN lookup are bundled in a Pytorch model for efficient end-to-end retrieval.\n\n### Integrations\n\nWe demonstrate that TorchRec works out of the box with many components commonly used alongside PyTorch models in production like systems, such as", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- [Training](https://github.com/pytorch/torchrec/tree/main/examples/ray) a TorchRec model on Ray Clusters utilizing the Torchx Ray scheduler\n- [Preprocessing](https://github.com/pytorch/torchrec/tree/main/torchrec/datasets/scripts/nvt) and DataLoading with NVTabular on DLRM\n- [Training](https://github.com/pytorch/torchrec/tree/main/examples/torcharrow) a TorchRec model with on-the-fly preprocessing with TorchArrow showcasing RecSys domain UDFs\n\n### Sequential Embeddings Example: Bert4Rec\n\nWe provide an [example](https://github.com/pytorch/torchrec/tree/main/examples/bert4rec), using TorchRec, that reimplements the [BERT4REC](https://arxiv.org/abs/1904.06690) paper, showcasing EmbeddingCollection for non-pooled embeddings. Using DistributedModelParallel we see a 35% QPS gain over conventional data parallelism.\n\n### (Beta) Planner", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "### (Beta) Planner\n\nThe TorchRec library includes a built-in [planner](https://pytorch.org/torchrec/torchrec.distributed.planner.html) that selects near optimal sharding plan for a given model. The planner attempts to identify the best sharding plan by evaluating a series of proposals which are statically analyzed and fed into an integer partitioner. The planner is able to automatically adjust plans for a wide range of hardware setups, allowing users to scale performance seamlessly from local development environment to large scale production hardware. See this [notebook](https://github.com/pytorch/torchrec/blob/main/torchrec/distributed/planner/Planner_Introduction.ipynb) for a more detailed tutorial.\n\n### (Beta) Inference", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### (Beta) Inference\n\n[TorchRec Inference](https://github.com/pytorch/torchrec/tree/main/torchrec/inference) is a C++ library that supports multi-gpu inference. The TorchRec library is used to shard models written and packaged in Python via torch.package (an alternative to TorchScript). The torch.deploy library is used to serve inference from C++ by launching multiple Python interpreters carrying the packaged model, thus subverting the GIL. Two models are provided as examples: [DLRM multi-GPU](https://github.com/pytorch/torchrec/blob/main/examples/inference/dlrm_predict.py) (sharded via TorchRec) and [DLRM single-GPU](https://github.com/pytorch/torchrec/blob/main/examples/inference/dlrm_predict_single_gpu.py).\n\n### (Beta) RecMetrics", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### (Beta) RecMetrics\n\nRecMetrics is a [metrics](https://github.com/pytorch/torchrec/tree/main/torchrec/metrics) library that collects common utilities and optimizations for Recommendation models. It extends [torchmetrics](https://torchmetrics.readthedocs.io/en/stable/).\n- A centralized metrics module that allows users to add new metrics\n- Commonly used metrics, including AUC, Calibration, CTR, MSE/RMSE, NE & Throughput\n- Optimization for metrics related operations to reduce the overhead of metric computation\n- Checkpointing\n\n### (Prototype) Single process Batched + Fused Embeddings", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "Previously TorchRec\u2019s abstractions (EmbeddingBagCollection/EmbeddingCollection) over FBGEMM kernels, which provide benefits such as table batching, optimizer fusion, and UVM placement, could only be used in conjunction with DistributedModelParallel. We\u2019ve decoupled these notions from sharding, and introduced the [FusedEmbeddingBagCollection](https://github.com/pytorch/torchrec/blob/eb1247d8a2d16edc4952e5c2617e69acfe5477a5/torchrec/modules/fused_embedding_modules.py#L271), which can be used as a standalone module, with all of the above features, and can also be sharded.\n\n## TorchX v0.2.0\n\nTorchX is a job launcher that makes it easier to run PyTorch in distributed training clusters with many scheduler integrations including Kubernetes and Slurm. We're excited to release TorchX 0.2.0 with a number of improvements. TorchX is currently being used in production in both on-premise and cloud environments.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "Check out the [quickstart](https://pytorch.org/torchx/main/quickstart.html) to start launching local and remote jobs.\n\n### Workspaces\n\nTorchX [now supports workspaces](https://pytorch.org/torchx/main/workspace.html) which allows users to easily launch training jobs using their local workspace. TorchX can automatically build a patch with your local training code on top of a base image to minimize iteration time and time to training.\n\n### .torchxconfig\n\nSpecifying options in [.torchxconfig](https://pytorch.org/torchx/latest/runner.config.html) saves you from having to type long CLI commands each time you launch a job. You can also define project level generic configs and drop a config file in your home directory for user-level overrides.\n\n### Expanded Scheduler Support\n\nTorchX now supports [AWS Batch](https://pytorch.org/torchx/main/schedulers/aws_batch.html) and [Ray (experimental)](https://pytorch.org/torchx/main/schedulers/ray.html) schedulers in addition to our existing integrations.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "### Distributed Training On All Schedulers\n\nThe TorchX dist.ddp component now works on all schedulers without any configuration. Distributed training workers will automatically discover each other when using [torchelastic](https://pytorch.org/docs/stable/distributed.elastic.html) via [the builtin dist.ddp component](https://pytorch.org/torchx/main/components/distributed.html).\n\n### Hyper Parameter Optimization\n\nTorchX [integrates with Ax](https://ax.dev/versions/latest/api/runners.html#module-ax.runners.torchx) to let you scale hyper-parameter optimizations (HPO) by launching the search trials onto remote clusters.\n\n### File and Device Mounts\n\nTorchX now supports [remote filesystem mounts and custom devices](https://pytorch.org/torchx/main/specs.html#mounts). This enables your PyTorch jobs to efficiently access cloud storage such as NFS or Lustre. The device mounts enables usage of network accelerators like Infiniband and custom inference/training accelerators.\n\n## FBGemm v0.2.0", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "## FBGemm v0.2.0\n\nThe FBGEMM library contains optimized kernels meant to improve the performance of PyTorch workloads. We\u2019ve added a number of new features and optimizations over the last few months that we are excited to report.\n\n### Inference Table Batched Embedding (TBE)\n\nThe [table batched embedding bag](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py#L1541) (TBE) operator is an important base operation for embedding lookup for recommendation system inference on GPU. We added the following enhancements for performance and flexibility:\n\nAlignment restriction removed\n- Embedding dimension \\* data type size had to be multiple of 4B before and now, it is 1B.\n\nUnified Virtual Memory (UVM) caching kernel optimizations\n- UVM caching kernels now scale linearly with # of tables using UVM caching. Previously, it was having similar overhead as all tables using UVM caching\n- UVM caching kernel overhead is much smaller than before", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### (Beta) Inference\n\n[TorchRec Inference](https://github.com/pytorch/torchrec/tree/main/torchrec/inference) is a C++ library that supports multi-gpu inference. The TorchRec library is used to shard models written and packaged in Python via torch.package (an alternative to TorchScript). The torch.deploy library is used to serve inference from C++ by launching multiple Python interpreters carrying the packaged model, thus subverting the GIL. Two models are provided as examples: [DLRM multi-GPU](https://github.com/pytorch/torchrec/blob/main/examples/inference/dlrm_predict.py) (sharded via TorchRec) and [DLRM single-GPU](https://github.com/pytorch/torchrec/blob/main/examples/inference/dlrm_predict_single_gpu.py).\n\n### (Beta) RecMetrics\n\nRecMetrics is a [metrics](https://github.com/pytorch/torchrec/tree/main/torchrec/metrics) library that collects common utilities and optimizations for Recommendation models. It extends [torchmetrics](https://torchmetrics.readthedocs.io/en/stable/).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "- A centralized metrics module that allows users to add new metrics\n- Commonly used metrics, including AUC, Calibration, CTR, MSE/RMSE, NE & Throughput\n- Optimization for metrics related operations to reduce the overhead of metric computation\n- Checkpointing\n\n### (Prototype) Single process Batched + Fused Embeddings\n\nPreviously TorchRec\u2019s abstractions (EmbeddingBagCollection/EmbeddingCollection) over FBGEMM kernels, which provide benefits such as table batching, optimizer fusion, and UVM placement, could only be used in conjunction with DistributedModelParallel. We\u2019ve decoupled these notions from sharding, and introduced the [FusedEmbeddingBagCollection](https://github.com/pytorch/torchrec/blob/eb1247d8a2d16edc4952e5c2617e69acfe5477a5/torchrec/modules/fused_embedding_modules.py#L271), which can be used as a standalone module, with all of the above features, and can also be sharded.\n\n## TorchX v0.2.0", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "## TorchX v0.2.0\n\nTorchX is a job launcher that makes it easier to run PyTorch in distributed training clusters with many scheduler integrations including Kubernetes and Slurm. We're excited to release TorchX 0.2.0 with a number of improvements. TorchX is currently being used in production in both on-premise and cloud environments.\n\nCheck out the [quickstart](https://pytorch.org/torchx/main/quickstart.html) to start launching local and remote jobs.\n\n### Workspaces\n\nTorchX [now supports workspaces](https://pytorch.org/torchx/main/workspace.html) which allows users to easily launch training jobs using their local workspace. TorchX can automatically build a patch with your local training code on top of a base image to minimize iteration time and time to training.\n\n### .torchxconfig", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### .torchxconfig\n\nSpecifying options in [.torchxconfig](https://pytorch.org/torchx/latest/runner.config.html) saves you from having to type long CLI commands each time you launch a job. You can also define project level generic configs and drop a config file in your home directory for user-level overrides.\n\n### Expanded Scheduler Support\n\nTorchX now supports [AWS Batch](https://pytorch.org/torchx/main/schedulers/aws_batch.html) and [Ray (experimental)](https://pytorch.org/torchx/main/schedulers/ray.html) schedulers in addition to our existing integrations.\n\n### Distributed Training On All Schedulers\n\nThe TorchX dist.ddp component now works on all schedulers without any configuration. Distributed training workers will automatically discover each other when using [torchelastic](https://pytorch.org/docs/stable/distributed.elastic.html) via [the builtin dist.ddp component](https://pytorch.org/torchx/main/components/distributed.html).\n\n### Hyper Parameter Optimization", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### Hyper Parameter Optimization\n\nTorchX [integrates with Ax](https://ax.dev/versions/latest/api/runners.html#module-ax.runners.torchx) to let you scale hyper-parameter optimizations (HPO) by launching the search trials onto remote clusters.\n\n### File and Device Mounts\n\nTorchX now supports [remote filesystem mounts and custom devices](https://pytorch.org/torchx/main/specs.html#mounts). This enables your PyTorch jobs to efficiently access cloud storage such as NFS or Lustre. The device mounts enables usage of network accelerators like Infiniband and custom inference/training accelerators.\n\n## FBGemm v0.2.0\n\nThe FBGEMM library contains optimized kernels meant to improve the performance of PyTorch workloads. We\u2019ve added a number of new features and optimizations over the last few months that we are excited to report.\n\n### Inference Table Batched Embedding (TBE)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### Inference Table Batched Embedding (TBE)\n\nThe [table batched embedding bag](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py#L1541) (TBE) operator is an important base operation for embedding lookup for recommendation system inference on GPU. We added the following enhancements for performance and flexibility:\n\nAlignment restriction removed\n- Embedding dimension \\* data type size had to be multiple of 4B before and now, it is 1B.\n\nUnified Virtual Memory (UVM) caching kernel optimizations\n- UVM caching kernels now scale linearly with # of tables using UVM caching. Previously, it was having similar overhead as all tables using UVM caching\n- UVM caching kernel overhead is much smaller than before\n\n### Inference FP8 Table Batched Embedding (TBE)", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "### Inference FP8 Table Batched Embedding (TBE) \n\nThe [table batched embedding bag](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py#L1541) (TBE) previously supported FP32, FP16, INT8, INT4, and INT2 embedding weight types. While these weight types work well in many models, we integrate FP8 weight types (in both GPU and CPU operations) to allow for numerical and performance evaluations of FP8 in our models. Compared to INT8, FP8 does not require the additional bias and scale storage and calculations. Additionally, the next generation of H100 GPUs has the FP8 support on Tensor Core (mainly matmul ops).\n\n### Jagged Tensor Kernels", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "### Jagged Tensor Kernels\n\nWe added optimized kernels to speed up [TorchRec JaggedTensor](https://pytorch.org/torchrec/torchrec.sparse.html). The purpose of JaggedTensor is to handle the case where one dimension of the input data is \u201cjagged\u201d, meaning that each consecutive row in a given dimension may be a different length, which is often the case with sparse feature inputs in recommendation systems. The internal representation is shown below:\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "We added ops for [converting jagged tensors from sparse to dense formats](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L982) [and back](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L968), performing [matrix multiplications with jagged tensors](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L996), and [elementwise ops](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L995).\n \n### Optimized permute102-baddbmm-permute102", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
-{"page_content": "It is difficult to fuse various matrix multiplications where the batch size is not the batch size of the model, switching the batch dimension is a quick solution. We created the [permute102_baddbmm_permute102](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/sparse_ops_cpu.cpp#L2401) operation that switches the first and the second dimension, performs the batched matrix multiplication and then switches back. Currently we only support forward pass with FP16 data type and will support FP32 type and backward pass in the future.\n\n### Optimized index_select for dim 0 index selection", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "\n\nWe added ops for [converting jagged tensors from sparse to dense formats](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L982) [and back](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L968), performing [matrix multiplications with jagged tensors](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L996), and [elementwise ops](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/jagged_tensor_ops_cpu.cpp#L995).\n \n### Optimized permute102-baddbmm-permute102", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
+{"page_content": "### Optimized permute102-baddbmm-permute102\n\nIt is difficult to fuse various matrix multiplications where the batch size is not the batch size of the model, switching the batch dimension is a quick solution. We created the [permute102_baddbmm_permute102](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/sparse_ops_cpu.cpp#L2401) operation that switches the first and the second dimension, performs the batched matrix multiplication and then switches back. Currently we only support forward pass with FP16 data type and will support FP32 type and backward pass in the future.\n\n### Optimized index_select for dim 0 index selection", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "index_select is normally used as part of a sparse operation. While PyTorch supports a generic index_select for an arbitrary-dimension index selection, its performance for a special case like the dim 0 index selection is suboptimal. For this reason, we implement a [specialized index_select for dim 0](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/src/sparse_ops_cpu.cpp#L2421). In some cases, we have observed 1.4x performance gain from FBGEMM\u2019s index_select compared to the one from PyTorch (using uniform index distribution).\n\nMore about the implementation of influential instances can be found on our [GitHub](https://github.com/pytorch/captum/tree/master/captum/influence) page and [tutorials](https://captum.ai/tutorials/TracInCP_Tutorial).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "Thanks for reading, If you\u2019re interested in these updates and want to join the PyTorch community, we encourage you to join the [discussion forums](https://discuss.pytorch.org/) and [open GitHub issues](https://github.com/pytorch/pytorch/issues). To get the latest news from PyTorch, follow us on [Twitter](https://twitter.com/PyTorch), [Medium](https://medium.com/pytorch), [YouTube](https://www.youtube.com/pytorch), and [LinkedIn](https://www.linkedin.com/company/pytorch).\n\nCheers!\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.12-new-library-releases/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'The torch.linalg module: Accelerated Linear Algebra with Autograd in PyTorch'\nauthor: Mike Ruberry, Ivan Yashchuk, Xiao Wang, Mario Lezcano and Natalia Gimelshein\nfeatured-img: 'assets/images/cholesky-decomposition.png'\n---\n\nLinear algebra is essential to deep learning and scientific computing, and it\u2019s always been a core part of PyTorch. PyTorch 1.9 extends PyTorch\u2019s support for linear algebra operations with the ```torch.linalg``` module. This module, documented [here](https://pytorch.org/docs/master/linalg.html?highlight=linalg#module-torch.linalg), has 26 operators, including faster and easier to use versions of older PyTorch operators, every function from [NumPy\u2019s linear algebra module](https://numpy.org/doc/stable/reference/routines.linalg.html) extended with accelerator and autograd support, and a few operators that are completely new. This makes the ```torch.linalg``` immediately familiar to NumPy users and an exciting update to PyTorch\u2019s linear algebra support.", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
{"page_content": "# NumPy-like linear algebra in PyTorch\n\nIf you\u2019re familiar with NumPy\u2019s linear algebra module then it\u2019ll be easy to start using ```torch.linalg```. In most cases it\u2019s a drop-in replacement. Let\u2019s looking at drawing samples from a [multivariate normal distribution](https://en.wikipedia.org/wiki/Multivariate_normal_distribution) using the [Cholesky decomposition](https://en.wikipedia.org/wiki/Cholesky_decomposition) as a motivating example to demonstrate this:\n\n```python\nimport numpy as np\n\n# Creates inputs\nnp.random.seed(0)\nmu_np = np.random.rand(4)\nL = np.random.rand(4, 4)\n# Covariance matrix sigma is positive-definite\nsigma_np = L @ L.T + np.eye(4)\nnormal_noise_np = np.random.standard_normal(mu_np.size)\n\ndef multivariate_normal_sample_np(mu, sigma, normal_noise):\n return mu + np.linalg.cholesky(sigma) @ normal_noise\n\nprint(\"Random sample: \", \n multivariate_normal_sample_np(mu_np, sigma_np, normal_noise_np))\n: Random sample: [2.9502426 1.78518077 1.83168697 0.90798228]\n```", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
-{"page_content": "Now let\u2019s see the same sampler implemented in PyTorch:\n\n```python\nimport torch\n\ndef multivariate_normal_sample_torch(mu, sigma, normal_noise):\n return mu + torch.linalg.cholesky(sigma) @ normal_noise\n```\n\nThe two functions are identical, and we can validate their behavior by calling the function with the same arguments wrapped as PyTorch tensors:\n\n```python\n# NumPy arrays are wrapped as tensors and share their memory\nmu_torch = torch.from_numpy(mu_np)\nsigma_torch = torch.from_numpy(sigma_np)\nnormal_noise_torch = torch.from_numpy(normal_noise_np)\n\nmultivariate_normal_sample_torch(mu_torch, sigma_torch, normal_noise_torch)\n: tensor([2.9502, 1.7852, 1.8317, 0.9080], dtype=torch.float64)\n```\n\nThe only difference is in how PyTorch prints tensors by default.", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nNow let\u2019s see the same sampler implemented in PyTorch:\n\n```python\nimport torch\n\ndef multivariate_normal_sample_torch(mu, sigma, normal_noise):\n return mu + torch.linalg.cholesky(sigma) @ normal_noise\n```\n\nThe two functions are identical, and we can validate their behavior by calling the function with the same arguments wrapped as PyTorch tensors:\n\n```python\n# NumPy arrays are wrapped as tensors and share their memory\nmu_torch = torch.from_numpy(mu_np)\nsigma_torch = torch.from_numpy(sigma_np)\nnormal_noise_torch = torch.from_numpy(normal_noise_np)\n\nmultivariate_normal_sample_torch(mu_torch, sigma_torch, normal_noise_torch)\n: tensor([2.9502, 1.7852, 1.8317, 0.9080], dtype=torch.float64)\n```\n\nThe only difference is in how PyTorch prints tensors by default.", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
{"page_content": "The Cholesky decomposition can also help us quickly compute the probability density function of the non-degenerate multivariate normal distribution. One of the expensive terms in that computation is the square root of the determinant of the covariance matrix. Using [properties of the determinant](https://en.wikipedia.org/wiki/Determinant#Properties_of_the_determinant) and the Cholesky decomposition we can calculate the same result faster than the naive computation, however. Here\u2019s the NumPy program that demonstrates this:\n\n```python\nsqrt_sigma_det_np = np.sqrt(np.linalg.det(sigma_np))\nsqrt_L_det_np = np.prod(np.diag(np.linalg.cholesky(sigma_np)))\n\nprint(\"|sigma|^0.5 = \", sqrt_sigma_det_np)\n: |sigma|^0.5 = 4.237127491242027\n \nprint(\"|L| = \", sqrt_L_det_np)\n: |L| = 4.237127491242028\n```\n\nAnd here\u2019s the same validation in PyTorch:\n\n```python\nsqrt_sigma_det_torch = torch.sqrt(torch.linalg.det(sigma_torch))\nsqrt_L_det_torch = torch.prod(torch.diag(torch.linalg.cholesky(sigma_torch)))", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
-{"page_content": "print(\"|sigma|^0.5 = \", sqrt_sigma_det_torch)\n: |sigma|^0.5 = tensor(4.2371, dtype=torch.float64) \n\nprint(\"|L| = \", sqrt_L_det_torch)\n: |L| = tensor(4.2371, dtype=torch.float64)\n```\n\nWe can measure the difference in run time using PyTorch\u2019s built-in benchmark utility:\n\n```python\nimport torch.utils.benchmark as benchmark\n\nt0 = benchmark.Timer(\n stmt='torch.sqrt(torch.linalg.det(sigma))',\n globals={'sigma': sigma_torch})\n\nt1 = benchmark.Timer(\n stmt='torch.prod(torch.diag(torch.linalg.cholesky(sigma)))',\n globals={'sigma': sigma_torch})\n\nprint(t0.timeit(100))\n: torch.sqrt(torch.linalg.det(sigma))\n 80.80 us\n 1 measurement, 100 runs , 1 thread", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
-{"page_content": "print(t1.timeit(100))\n: torch.prod(torch.diag(torch.linalg.cholesky(sigma)))\n 11.56 us\n 1 measurement, 100 runs , 1 thread\n ```\n \nDemonstrating that the approach using the Cholesky decomposition can be significantly faster. Behind the scenes, PyTorch\u2019s linear algebra module uses OpenBLAS or MKL implementations of the LAPACK standard to maximize its CPU performance.\n\n# Autograd Support\n\nPyTorch\u2019s linear algebra module doesn\u2019t just implement the same functions as NumPy\u2019s linear algebra module (and a few more), it also extends them with autograd and CUDA support.\n\nLet\u2019s look at a very simple program that just computes an inverse and the gradient of that operation to show how autograd works:\n\n```python\nt = torch.tensor(((1, 2), (3, 4)), dtype=torch.float32, requires_grad=True)\n\ninv = torch.linalg.inv(t)\ninv.backward(torch.ones_like(inv))\n\nprint(t.grad)\n: tensor([[-0.5000, 0.5000],\n [ 0.5000, -0.5000]])\n```\n\nWe can mimic the same computation in NumPy by defining the autograd formula ourselves:", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
-{"page_content": "```python\na = np.array(((1, 2), (3, 4)), dtype=np.float32)\n\ninv_np = np.linalg.inv(a)\n\ndef inv_backward(result, grad):\n return -(result.transpose(-2, -1) @ (grad @ result.transpose(-2, -1)))\ngrad_np = inv_backward(inv_np, np.ones_like(inv_np))\n\nprint(grad_np)\n: [[-0.5 0.5]\n [ 0.5 -0.5]]\n```\n\nOf course, as programs become more complicated it\u2019s convenient to have builtin autograd support, and PyTorch\u2019s linear algebra module supports both real and complex autograd.\n\n# CUDA Support\n\nSupport for autograd and accelerators, like CUDA devices, is a core part of PyTorch. The ```torch.linalg``` module was developed with NVIDIA\u2019s PyTorch and cuSOLVER teams, who helped optimize its performance on CUDA devices with the cuSOLVER, cuBLAS, and MAGMA libraries. These improvements make PyTorch\u2019s CUDA linear algebra operations faster than ever. For example, let\u2019s look at the performance of PyTorch 1.9\u2019s ```torch.linalg.cholesky``` vs. PyTorch 1.8\u2019s (now deprecated) ```torch.cholesky```:", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
+{"page_content": "print(\"|sigma|^0.5 = \", sqrt_sigma_det_torch)\n: |sigma|^0.5 = tensor(4.2371, dtype=torch.float64) \n\nprint(\"|L| = \", sqrt_L_det_torch)\n: |L| = tensor(4.2371, dtype=torch.float64)\n```\n\nWe can measure the difference in run time using PyTorch\u2019s built-in benchmark utility:\n\n```python\nimport torch.utils.benchmark as benchmark\n\nt0 = benchmark.Timer(\n stmt='torch.sqrt(torch.linalg.det(sigma))',\n globals={'sigma': sigma_torch})\n\nt1 = benchmark.Timer(\n stmt='torch.prod(torch.diag(torch.linalg.cholesky(sigma)))',\n globals={'sigma': sigma_torch})\n\nprint(t0.timeit(100))\n: torch.sqrt(torch.linalg.det(sigma))\n 80.80 us\n 1 measurement, 100 runs , 1 thread\n\n\nprint(t1.timeit(100))\n: torch.prod(torch.diag(torch.linalg.cholesky(sigma)))\n 11.56 us\n 1 measurement, 100 runs , 1 thread\n ```", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
+{"page_content": "1 measurement, 100 runs , 1 thread\n ```\n \nDemonstrating that the approach using the Cholesky decomposition can be significantly faster. Behind the scenes, PyTorch\u2019s linear algebra module uses OpenBLAS or MKL implementations of the LAPACK standard to maximize its CPU performance.\n\n# Autograd Support\n\nPyTorch\u2019s linear algebra module doesn\u2019t just implement the same functions as NumPy\u2019s linear algebra module (and a few more), it also extends them with autograd and CUDA support.\n\nLet\u2019s look at a very simple program that just computes an inverse and the gradient of that operation to show how autograd works:\n\n```python\nt = torch.tensor(((1, 2), (3, 4)), dtype=torch.float32, requires_grad=True)\n\ninv = torch.linalg.inv(t)\ninv.backward(torch.ones_like(inv))\n\nprint(t.grad)\n: tensor([[-0.5000, 0.5000],\n [ 0.5000, -0.5000]])\n```\n\nWe can mimic the same computation in NumPy by defining the autograd formula ourselves:\n\n```python\na = np.array(((1, 2), (3, 4)), dtype=np.float32)\n\ninv_np = np.linalg.inv(a)", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
+{"page_content": "inv_np = np.linalg.inv(a)\n\ndef inv_backward(result, grad):\n return -(result.transpose(-2, -1) @ (grad @ result.transpose(-2, -1)))\ngrad_np = inv_backward(inv_np, np.ones_like(inv_np))\n\nprint(grad_np)\n: [[-0.5 0.5]\n [ 0.5 -0.5]]\n```\n\nOf course, as programs become more complicated it\u2019s convenient to have builtin autograd support, and PyTorch\u2019s linear algebra module supports both real and complex autograd.\n\n# CUDA Support\n\nSupport for autograd and accelerators, like CUDA devices, is a core part of PyTorch. The ```torch.linalg``` module was developed with NVIDIA\u2019s PyTorch and cuSOLVER teams, who helped optimize its performance on CUDA devices with the cuSOLVER, cuBLAS, and MAGMA libraries. These improvements make PyTorch\u2019s CUDA linear algebra operations faster than ever. For example, let\u2019s look at the performance of PyTorch 1.9\u2019s ```torch.linalg.cholesky``` vs. PyTorch 1.8\u2019s (now deprecated) ```torch.cholesky```:\n\n", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
{"page_content": "
\n

\n
\n\n(The above charts were created using an Ampere A100 GPU with CUDA 11.3, cuSOLVER 11.1.1.58, and MAGMA 2.5.2. Matrices are in double precision.)\n\nThese charts show that performance has increased significantly on larger matrices, and that batched performance is better across the board. Other linear algebra operations, including ```torch.linalg.qr``` and ```torch.linalg.lstsq```, have also had their CUDA performance improved.\n\n# Beyond NumPy", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
{"page_content": "# Beyond NumPy\n\nIn addition to offering all the functions in NumPy\u2019s linear algebra module with support for autograd and accelerators, ```torch.linalg``` has a few new functions of its own. NumPy\u2019s ```linalg.norm``` does not allow users to compute vector norms over arbitrary subsets of dimensions, so to enable this functionality we added ```torch.linalg.vector_norm```. We\u2019ve also started modernizing other linear algebra functionality in PyTorch, so we created ```torch.linalg.householder_product``` to replace the older ```torch.orgqr```, and we plan to continue adding more linear algebra functionality in the future, too.\n\n# The Future of Linear Algebra in PyTorch", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
{"page_content": "# The Future of Linear Algebra in PyTorch\n\nThe ```torch.linalg``` module is fast and familiar with great support for autograd and accelerators. It\u2019s already being used in libraries like [botorch](https://github.com/pytorch/botorch), too. But we\u2019re not stopping here. We plan to continue updating more of PyTorch\u2019s existing linear algebra functionality (like ```torch.lobpcg```) and offering more support for low rank and sparse linear algebra. We also want to hear your feedback on how we can improve, so start a conversation on the [forum](https://discuss.pytorch.org/) or file an issue on our [Github](https://github.com/pytorch/pytorch) and share your thoughts. \n\nWe look forward to hearing from you and seeing what the community does with PyTorch\u2019s new linear algebra functionality!", "metadata": {"source": "https://pytorch.org/blog/torch-linalg-autograd/", "category": "pytorch blogs"}}
-{"page_content": "---\nlayout: blog_detail\ntitle: \"Democratizing AI with PyTorch Foundation and ROCm\u2122 support for PyTorch\"\nauthor: AMD\n---\n\n{:width=\"50%\" style=\"display:block; margin-left:auto; margin-right:auto\"}\n\nLast year, Meta announced that [PyTorch](https://pytorch.org/) joined the Linux Foundation as a neutral home for growing the machine learning project and community with AMD representation as a part of the founding membership and governing board.\n\n[PyTorch Foundation\u2019s](https://pytorch.org/foundation) mission is to drive AI adoption by democratizing its software ecosystem through open source principles aligning with the AMD core principle of an Open software ecosystem. AMD strives to foster innovation through the support for latest generations of hardware, tools, libraries, and other components to simplify and accelerate adoption of AI across a broad range of scientific discoveries.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "
\n
\n
\nAMD, along with key PyTorch codebase developers (including those at Meta AI), delivered a set of updates to the ROCm\u2122 open software ecosystem that brings stable support for AMD Instinct\u2122 accelerators as well as many Radeon\u2122 GPUs. This now gives PyTorch developers the ability to build their next great AI solutions leveraging AMD GPU accelerators & ROCm. The support from PyTorch community in identifying gaps, prioritizing key updates, providing feedback for performance optimizing and supporting our journey from \u201cBeta\u201d to \u201cStable\u201d was immensely helpful and we deeply appreciate the strong collaboration between the two teams at AMD and PyTorch. The move for ROCm support from \u201cBeta\u201d to \u201cStable\u201d came in the PyTorch 1.12 release (June 2022) brings the added support to easily run PyTorch on native environment without having to configure custom dockers. This is a sign of confidence about the quality of support and performance of PyTorch using AMD Instinct and ROCm. The results of these collaborative efforts are evident in the performance measured on key industry benchmarks like Microsoft\u2019s SuperBench shown below in Graph 1.\n
\n
\n
\n
\n\u201cWe are excited to see the significant impact of developers at AMD to contribute to and extend features within PyTorch to make AI models run in a more performant, efficient, and scalable way. A great example of this is the thought-leadership around unified memory approaches between the framework and future hardware systems, and we look forward to seeing that feature progress.\u201d
\n- Soumith Chintala, PyTorch lead-maintainer and Director of Engineering, Meta AI\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "The progressive improvements on both the AMD CDNA\u2122 architecture as well as ROCm and PyTorch shows single GPU model throughput increase from AMD Instinct MI100 to the latest generation AMD Instinct MI200 family GPUs going from ROCm 4.2 to ROCm 5.3 and from PyTorch 1.7 to PyTorch 1.12.\n\n{:width=\"100%\"}\n\n
Graph 1: ML model performance over generation using Microsoft Superbench Suite 1, 2, 3\n\n\nBelow are a few of the key updates for ROCm support since the PyTorch 1.12 release\n\n \n\n## Full Continuous Integration (CI) for ROCm on PyTorch", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "---\nlayout: blog_detail\ntitle: \"Democratizing AI with PyTorch Foundation and ROCm\u2122 support for PyTorch\"\nauthor: AMD\n---\n\n{:width=\"50%\" style=\"display:block; margin-left:auto; margin-right:auto\"}\n\nLast year, Meta announced that [PyTorch](https://pytorch.org/) joined the Linux Foundation as a neutral home for growing the machine learning project and community with AMD representation as a part of the founding membership and governing board.\n\n[PyTorch Foundation\u2019s](https://pytorch.org/foundation) mission is to drive AI adoption by democratizing its software ecosystem through open source principles aligning with the AMD core principle of an Open software ecosystem. AMD strives to foster innovation through the support for latest generations of hardware, tools, libraries, and other components to simplify and accelerate adoption of AI across a broad range of scientific discoveries.\n\n
", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "AMD, along with key PyTorch codebase developers (including those at Meta AI), delivered a set of updates to the ROCm\u2122 open software ecosystem that brings stable support for AMD Instinct\u2122 accelerators as well as many Radeon\u2122 GPUs. This now gives PyTorch developers the ability to build their next great AI solutions leveraging AMD GPU accelerators & ROCm. The support from PyTorch community in identifying gaps, prioritizing key updates, providing feedback for performance optimizing and supporting our journey from \u201cBeta\u201d to \u201cStable\u201d was immensely helpful and we deeply appreciate the strong collaboration between the two teams at AMD and PyTorch. The move for ROCm support from \u201cBeta\u201d to \u201cStable\u201d came in the PyTorch 1.12 release (June 2022) brings the added support to easily run PyTorch on native environment without having to configure custom dockers. This is a sign of confidence about the quality of support and performance of PyTorch using AMD Instinct and ROCm. The results of these collaborative efforts are evident in the performance measured on key industry benchmarks like Microsoft\u2019s SuperBench shown below in Graph 1.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "
\n
\n
\n
\n\u201cWe are excited to see the significant impact of developers at AMD to contribute to and extend features within PyTorch to make AI models run in a more performant, efficient, and scalable way. A great example of this is the thought-leadership around unified memory approaches between the framework and future hardware systems, and we look forward to seeing that feature progress.\u201d
\n- Soumith Chintala, PyTorch lead-maintainer and Director of Engineering, Meta AI\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\n
\n
\n\n\nThe progressive improvements on both the AMD CDNA\u2122 architecture as well as ROCm and PyTorch shows single GPU model throughput increase from AMD Instinct MI100 to the latest generation AMD Instinct MI200 family GPUs going from ROCm 4.2 to ROCm 5.3 and from PyTorch 1.7 to PyTorch 1.12.\n\n{:width=\"100%\"}\n\nGraph 1: ML model performance over generation using Microsoft Superbench Suite 1, 2, 3\n\n\nBelow are a few of the key updates for ROCm support since the PyTorch 1.12 release\n\n \n\n## Full Continuous Integration (CI) for ROCm on PyTorch", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "With the ROCm support for PyTorch move from \u201cBeta\u201d to \u201cStable,\u201d all the functions and features commits are now verified through a full Continuous Integration (CI) process. The CI process helps ensure the proper build and test process ahead of an expected Docker and PIP wheel release with stable commits forthcoming.\n\n\n## Support for [Kineto Profiler](https://github.com/pytorch/kineto)\n\nThe addition of Kineto profiler support to ROCm now helps developers and users understand performance bottlenecks through effective diagnosis and profiling tools. The tool also provides recommendations to improve known issues and visualization through TensorBoard UI.\n\n## Key PyTorch Libraries support added", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "## Key PyTorch Libraries support added\n\nPyTorch ecosystem libraries like [TorchText](https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html) (Text classification), [TorchRec](https://pytorch.org/torchrec/) (libraries for recommender systems - RecSys), [TorchVision](https://pytorch.org/vision/stable/index.html) (Computer Vision), [TorchAudio](https://pytorch.org/audio/stable/index.html) (audio and signal processing) are fully supported since ROCm 5.1 and upstreamed with PyTorch 1.12.\n\nKey libraries provided with the ROCm software stack including [MIOpen](https://github.com/ROCmSoftwarePlatform/MIOpen) (Convolution models), [RCCL](https://github.com/ROCmSoftwarePlatform/rccl) (ROCm Collective Communications) and [rocBLAS](https://github.com/ROCmSoftwarePlatform/rocBLAS) (BLAS for transformers) were further optimized to offer new potential efficiencies and higher performance.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "MIOpen innovates on several fronts, such as implementing fusion to optimize for memory bandwidth and GPU launch overheads, providing an auto-tuning infrastructure to overcome the large design space of problem configurations, and implementing different algorithms to optimize convolutions for different filter and input sizes. MIOpen is one of the first libraries to publicly support the bfloat16 data-type for convolutions, allowing efficient training at lower precision maintaining expected accuracy.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
@@ -461,126 +465,124 @@
{"page_content": "Along with the above key highlights, over 50 features and functionality improvements were completed jointly between AMD and PyTorch to add stable support for ROCm. These include improvements to tools, compilers, runtime, graph optimizations through TorchScript, INT8 quant path usage, and [ONNX runtime integration](https://onnxruntime.ai/) including support for Navi 21 based Radeon\u2122 PRO datacenter graphics card to name a few.\n\n## [AITemplate](https://github.com/facebookincubator/AITemplate) Inference Engine", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "MetaAI recently published a blog announcing the release of its open source AITemplate ([link](https://ai.facebook.com/blog/gpu-inference-engine-nvidia-amd-open-source/)) for a unified inference system supporting AMD Instinct GPU accelerators using the AMD ROCm stack. This Python based framework can help significantly improve performance through increased utilization of AMD matrix cores for transformer blocks. This is achieved through the AMD [Composable Kernel (CK) library](https://github.com/ROCmSoftwarePlatform/composable_kernel) which provides performance critical Kernels for ML AI workloads across multiple architectures including GPUs and CPUs through HIP & C++.\n\nMoreover, the AITemplate also provides out-of-the-box support for widely used AI models like BERT, ResNET, Vision Transformer, Stable Diffusion etc. simplifying deployment process through these pretrained models.\n\n \n## What\u2019s coming with future ROCm releases?\n\n### Unified memory models for CPU + GPU", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "### Unified memory models for CPU + GPU\n\n \n\nAs system architecture evolves to address the complexity of large problem sizes and data sets, memory management becomes a key performance bottle neck that needs a cohesive strategy to be addressed through innovations at both hardware and software levels. AMD is uniquely positioned to address this problem with its effective data center solutions integrating AMD EPYC\u2122 CPU cores with its AMD Instinct GPU compute units in a truly unified datacenter APU (Accelerated Processing Unit) form factor set to be launched in 2H 2023.\n\nThe software work to leverage the unified CPU + GPU memory has already started in collaboration with the PyTorch team, to enable the usage of a fast, low latency, synchronized memory model that enables not only AMD but also other AI accelerators to address the complex memory management problem of today. We are looking forward to this joint effort and announcement soon.\n\n## Acknowledgement", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## Acknowledgement\n\nThe content in this blog highlights the joint work between AMD and key PyTorch contributors including Meta, working on many of the core features, as well as Microsoft enabling ONNX Runtime support. We are looking forward to working with the other founding members at the PyTorch Foundation on the next steps and improvements to democratize and grow adoption of PyTorch across the industry.\n\n## CAUTIONARY STATEMENT", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "\nThis blog contains forward-looking statements concerning Advanced Micro Devices, Inc. (AMD) such as the availability, timing and expected benefits of an AMD datacenter APU form factor, which are made pursuant to the Safe Harbor provisions of the Private Securities Litigation Reform Act of 1995. Forward-looking statements are commonly identified by words such as \"would,\" \"may,\" \"expects,\" \"believes,\" \"plans,\" \"intends,\" \"projects\" and other terms with similar meaning. Investors are cautioned that the forward-looking statements in this blog are based on current beliefs, assumptions and expectations, speak only as of the date of this blog and involve risks and uncertainties that could cause actual results to differ materially from current expectations. Such statements are subject to certain known and unknown risks and uncertainties, many of which are difficult to predict and generally beyond AMD's control, that could cause actual results and other future events to differ materially from those expressed in, or implied or projected by, the forward-looking information and statements. Investors are urged to review in detail the risks and uncertainties in AMD\u2019s Securities and Exchange Commission filings, including but not limited to AMD\u2019s most recent reports on Forms 10-K and 10-Q. AMD does not assume, and hereby disclaims, any obligation to update forward-looking statements made in this blog, except as may be required by law. \n", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## Endnotes", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "1. MI100D-01 SuperBench v0.5 model training results based on AMD internal testing as of 11/09/2022 measuring the total training throughput, at half precision, using a 2P AMD EPYC\u2122 7763 CPU server tested with 1x AMD Instinct\u2122 MI100 (32GB HBM2e) 300W GPU, SBIOS 2.2, Ubuntu\u00ae 20.04.5 LTS, host ROCm\u2122 5.2.0, guest ROCm 4.2, PyTorch 1.7.0. Server manufacturers may vary configurations, yielding different results. Performance may vary based factors including use of latest drivers and optimizations.\n2. MI200D-01 SuperBench v0.6 model training results based on AMD internal testing as of 11/09/2022 measuring the total training throughput, at half precision, using a 2P AMD EPYC\u2122 7763 CPU server tested with 1x AMD Instinct\u2122 MI210 (64GB HBM2e) 300W GPU, SBIOS 2.2, Ubuntu 20.04.5 LTS, host ROCm 5.3.0, guest ROCm 5.3, PyTorch 1.12. Server manufacturers may vary configurations, yielding different results. Performance may vary based factors including use of latest drivers and optimizations.\n3. MI200D-02: SuperBench v0.6 model training results based on AMD internal testing as of 11/09/2022 measuring the total training throughput, at half precision, using a 2P AMD EPYC\u2122\ufe0f 7763 CPU server tested with 1x AMD Instinct\u2122\ufe0f MI250 (128GB HBM2e) 560W GPU, SBIOS M12, Ubuntu 20.04 LTS, host ROCm 5.3.0, guest ROCm 5.3, PyTorch 1.12. Server manufacturers may vary configurations, yielding different results. Performance may vary based factors including use of latest drivers and optimizations.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "## Acknowledgement\n\nThe content in this blog highlights the joint work between AMD and key PyTorch contributors including Meta, working on many of the core features, as well as Microsoft enabling ONNX Runtime support. We are looking forward to working with the other founding members at the PyTorch Foundation on the next steps and improvements to democratize and grow adoption of PyTorch across the industry.\n\n## CAUTIONARY STATEMENT \n\n", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "This blog contains forward-looking statements concerning Advanced Micro Devices, Inc. (AMD) such as the availability, timing and expected benefits of an AMD datacenter APU form factor, which are made pursuant to the Safe Harbor provisions of the Private Securities Litigation Reform Act of 1995. Forward-looking statements are commonly identified by words such as \"would,\" \"may,\" \"expects,\" \"believes,\" \"plans,\" \"intends,\" \"projects\" and other terms with similar meaning. Investors are cautioned that the forward-looking statements in this blog are based on current beliefs, assumptions and expectations, speak only as of the date of this blog and involve risks and uncertainties that could cause actual results to differ materially from current expectations. Such statements are subject to certain known and unknown risks and uncertainties, many of which are difficult to predict and generally beyond AMD's control, that could cause actual results and other future events to differ materially from those expressed in, or implied or projected by, the forward-looking information and statements. Investors are urged to review in detail the risks and uncertainties in AMD\u2019s Securities and Exchange Commission filings, including but not limited to AMD\u2019s most recent reports on Forms 10-K and 10-Q. AMD does not assume, and hereby disclaims, any obligation to update forward-looking statements made in this blog, except as may be required by law.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\n \n\n## Endnotes\n\n\n1. MI100D-01 SuperBench v0.5 model training results based on AMD internal testing as of 11/09/2022 measuring the total training throughput, at half precision, using a 2P AMD EPYC\u2122 7763 CPU server tested with 1x AMD Instinct\u2122 MI100 (32GB HBM2e) 300W GPU, SBIOS 2.2, Ubuntu\u00ae 20.04.5 LTS, host ROCm\u2122 5.2.0, guest ROCm 4.2, PyTorch 1.7.0. Server manufacturers may vary configurations, yielding different results. Performance may vary based factors including use of latest drivers and optimizations.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "2. MI200D-01 SuperBench v0.6 model training results based on AMD internal testing as of 11/09/2022 measuring the total training throughput, at half precision, using a 2P AMD EPYC\u2122 7763 CPU server tested with 1x AMD Instinct\u2122 MI210 (64GB HBM2e) 300W GPU, SBIOS 2.2, Ubuntu 20.04.5 LTS, host ROCm 5.3.0, guest ROCm 5.3, PyTorch 1.12. Server manufacturers may vary configurations, yielding different results. Performance may vary based factors including use of latest drivers and optimizations.\n3. MI200D-02: SuperBench v0.6 model training results based on AMD internal testing as of 11/09/2022 measuring the total training throughput, at half precision, using a 2P AMD EPYC\u2122\ufe0f 7763 CPU server tested with 1x AMD Instinct\u2122\ufe0f MI250 (128GB HBM2e) 560W GPU, SBIOS M12, Ubuntu 20.04 LTS, host ROCm 5.3.0, guest ROCm 5.3, PyTorch 1.12. Server manufacturers may vary configurations, yielding different results. Performance may vary based factors including use of latest drivers and optimizations.", "metadata": {"source": "https://pytorch.org/blog/democratizing-ai-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Introducing PyTorch Fully Sharded Data Parallel (FSDP) API\"\nauthor: Yanli Zhao, Rohan Varma, Chien-Chin Huang, Shen Li, Min Xu, Alban Desmaison\nfeatured-img: \"assets/images/pytorch-logo.jpg\"\n---\n\nRecent studies have shown that large model training will be beneficial for improving model quality. During the last 3 years, model size grew 10,000 times from [BERT](https://arxiv.org/abs/1810.04805) with 110M parameters to [Megatron-2](https://arxiv.org/abs/2104.04473) with one trillion. However, training large AI models is not easy\u2014aside from the need for large amounts of computing resources, software engineering complexity is also challenging. PyTorch has been working on building tools and infrastructure to make it easier.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "PyTorch Distributed data parallelism is a staple of scalable deep learning because of its robustness and simplicity. It however requires the model to fit on one GPU. Recent approaches like DeepSpeed ZeRO and FairScale\u2019s Fully Sharded Data Parallel allow us to break this barrier by sharding a model\u2019s parameters, gradients and optimizer states across data parallel workers while still maintaining the simplicity of data parallelism.\n\nWith PyTorch 1.11 we\u2019re adding native support for Fully Sharded Data Parallel (FSDP), currently available as a prototype feature. Its implementation heavily borrows from FairScale\u2019s version while bringing more streamlined APIs and additional performance improvements.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "Scaling tests of PyTorch FSDP on AWS show it can scale up to train dense models with 1T parameters. Realized performance in our experiments reached 84 TFLOPS per A100 GPU for GPT 1T model and 159 TFLOPS per A100 GPU for GPT 175B model on AWS cluster. Native FSDP implementation also dramatically improved model initialization time compared to FairScale\u2019s original when CPU offloading was enabled.\n\nIn future PyTorch versions, we\u2019re going to enable users to seamlessly switch between DDP, ZeRO-1, ZeRO-2 and FSDP flavors of data parallelism, so that users can train different scales of models with simple configurations in the unified API.\n\n### How FSDP Works\n\nFSDP is a type of data-parallel training, but unlike traditional data-parallel, which maintains a per-GPU copy of a model\u2019s parameters, gradients and optimizer states, it shards all of these states across data-parallel workers and can optionally offload the sharded model parameters to CPUs. \n\nThe figure below shows how FSDP works for 2 data-parallel processes:", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "\n
\n
\n\n\nFigure 1. FSDP workflow\n
\n\nUsually, model layers are wrapped with FSDP in a nested way, so that only layers in a single FSDP instance need to gather the full parameters to a single device during forward or backward computations. The gathered full parameters will be freed immediately after computation, and the freed memory can be used for the next layer\u2019s computation. In this way, peak GPU memory could be saved and thus training can be scaled to use a larger model size or larger batch size. To further maximize memory efficiency, FSDP can offload the parameters, gradients and optimizer states to CPUs when the instance is not active in the computation.\n\n### Using FSDP in PyTorch\n\nThere are two ways to wrap a model with PyTorch FSDP. Auto wrapping is a drop-in replacement for DDP; manual wrapping needs minimal changes of model definition code with the ability to explore complex sharding strategies.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "#### Auto Wrapping\n\nModel layers should be wrapped in FSDP in a nested way to save peak memory and enable communication and computation overlapping. The simplest way to do it is auto wrapping, which can serve as a drop-in replacement for DDP without changing the rest of the code.\n\nfsdp_auto_wrap_policy argument allows specifying a callable function to recursively wrap layers with FSDP. default_auto_wrap_policy function provided by the PyTorch FSDP recursively wraps layers with the number of parameters larger than 100M. You can supply your own wrapping policy as needed. The example of writing a customized wrapping policy is shown in the [FSDP API doc](https://pytorch.org/docs/stable/fsdp.html).\n\nIn addition, cpu_offload could be configured optionally to offload wrapped parameters to CPUs when these parameters are not used in computation. This can further improve memory efficiency at the cost of data transfer overhead between host and device.\n\nThe example below shows how FSDP is wrapped using auto wrapping.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
-{"page_content": "```python\nfrom torch.distributed.fsdp import (\n FullyShardedDataParallel,\n CPUOffload,\n)\nfrom torch.distributed.fsdp.wrap import (\n default_auto_wrap_policy,\n)\nimport torch.nn as nn\n \nclass model(nn.Module):\n def __init__(self):\n super().__init__()\n self.layer1 = nn.Linear(8, 4)\n self.layer2 = nn.Linear(4, 16)\n self.layer3 = nn.Linear(16, 4)\n \nmodel = DistributedDataParallel(model())\nfsdp_model = FullyShardedDataParallel(\n model(),\n fsdp_auto_wrap_policy=default_auto_wrap_policy,\n cpu_offload=CPUOffload(offload_params=True),\n)\n```\n\n#### Manual Wrapping\n\nManual wrapping can be useful to explore complex sharding strategies by applying `wrap` selectively to some parts of the model. Overall settings can be passed to the enable_wrap() context manager.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
-{"page_content": "```python\nfrom torch.distributed.fsdp import (\n FullyShardedDataParallel,\n CPUOffload,\n)\nfrom torch.distributed.fsdp.wrap import (\n enable_wrap,\n wrap,\n)\nimport torch.nn as nn\nfrom typing import Dict\n \n \nclass model(nn.Module):\n def __init__(self):\n super().__init__()\n self.layer1 = wrap(nn.Linear(8, 4))\n self.layer2 = nn.Linear(4, 16)\n self.layer3 = wrap(nn.Linear(16, 4))\n \nwrapper_kwargs = Dict(cpu_offload=CPUOffload(offload_params=True))\nwith enable_wrap(wrapper_cls=FullyShardedDataParallel, **wrapper_kwargs):\n fsdp_model = wrap(model())\n```\n\nAfter wrapping the model with FSDP using one of the two above approaches, the model can be trained in a similar way as local training, like this:\n\n```python\noptim = torch.optim.Adam(fsdp_model.parameters(), lr=0.0001)\nfor sample, label in next_batch():\n out = fsdp_model(input)\n loss = criterion(out, label)\n loss.backward()\n optim.step()\n```\n\n### Benchmark Results", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
-{"page_content": "### Benchmark Results\n\nWe ran extensive scaling tests for 175B and 1T GPT models on AWS clusters using PyTorch FSDP. Each cluster node is an instance with 8 [NVIDIA A100-SXM4-40GB](https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf) GPUs, and inter-nodes are connected via AWS Elastic Fabric Adapter (EFA) with 400 Gbps network bandwidth.\n\nGPT models are implemented using [minGPT](https://github.com/karpathy/minGPT). A randomly generated input dataset is used for benchmarking purposes. All experiments ran with 50K vocabulary size, fp16 precision and [SGD](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html) optimizer.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
-{"page_content": "| Model | Number of layers | Hidden size | Attention heads | Model size, billions of parameters |\n|----------|------------------|-------------|-----------------|------------------------------------|\n| GPT 175B | 96 | 12288 | 96 | 175 |\n| GPT 1T | 128 | 25600 | 160 | 1008 |\n\nIn addition to using FSDP with parameters CPU offloading in the experiments, the [activation checkpointing feature](https://pytorch.org/docs/stable/checkpoint.html) in PyTorch is also applied in the tests.\n\nThe maximum per-GPU throughput of 159 teraFLOP/s (51% of NVIDIA A100 peak theoretical performance 312 teraFLOP/s/GPU) is achieved with batch size 20 and sequence length 512 on 128 GPUs for the GPT 175B model; further increase of the number of GPUs leads to per-GPU throughput degradation because of growing communication between the nodes.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
+{"page_content": "```python\nfrom torch.distributed.fsdp import (\n FullyShardedDataParallel,\n CPUOffload,\n)\nfrom torch.distributed.fsdp.wrap import (\n default_auto_wrap_policy,\n)\nimport torch.nn as nn\n \nclass model(nn.Module):\n def __init__(self):\n super().__init__()\n self.layer1 = nn.Linear(8, 4)\n self.layer2 = nn.Linear(4, 16)\n self.layer3 = nn.Linear(16, 4)\n \nmodel = DistributedDataParallel(model())\nfsdp_model = FullyShardedDataParallel(\n model(),\n fsdp_auto_wrap_policy=default_auto_wrap_policy,\n cpu_offload=CPUOffload(offload_params=True),\n)\n```\n\n#### Manual Wrapping\n\nManual wrapping can be useful to explore complex sharding strategies by applying `wrap` selectively to some parts of the model. Overall settings can be passed to the enable_wrap() context manager.\n\n```python\nfrom torch.distributed.fsdp import (\n FullyShardedDataParallel,\n CPUOffload,\n)\nfrom torch.distributed.fsdp.wrap import (\n enable_wrap,\n wrap,\n)\nimport torch.nn as nn\nfrom typing import Dict", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
+{"page_content": "import torch.nn as nn\nfrom typing import Dict\n \n \nclass model(nn.Module):\n def __init__(self):\n super().__init__()\n self.layer1 = wrap(nn.Linear(8, 4))\n self.layer2 = nn.Linear(4, 16)\n self.layer3 = wrap(nn.Linear(16, 4))\n \nwrapper_kwargs = Dict(cpu_offload=CPUOffload(offload_params=True))\nwith enable_wrap(wrapper_cls=FullyShardedDataParallel, **wrapper_kwargs):\n fsdp_model = wrap(model())\n```\n\nAfter wrapping the model with FSDP using one of the two above approaches, the model can be trained in a similar way as local training, like this:\n\n```python\noptim = torch.optim.Adam(fsdp_model.parameters(), lr=0.0001)\nfor sample, label in next_batch():\n out = fsdp_model(input)\n loss = criterion(out, label)\n loss.backward()\n optim.step()\n```\n\n### Benchmark Results", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
+{"page_content": "optim.step()\n```\n\n### Benchmark Results\n\nWe ran extensive scaling tests for 175B and 1T GPT models on AWS clusters using PyTorch FSDP. Each cluster node is an instance with 8 [NVIDIA A100-SXM4-40GB](https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf) GPUs, and inter-nodes are connected via AWS Elastic Fabric Adapter (EFA) with 400 Gbps network bandwidth.\n\nGPT models are implemented using [minGPT](https://github.com/karpathy/minGPT). A randomly generated input dataset is used for benchmarking purposes. All experiments ran with 50K vocabulary size, fp16 precision and [SGD](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html) optimizer.\n\n| Model | Number of layers | Hidden size | Attention heads | Model size, billions of parameters |\n|----------|------------------|-------------|-----------------|------------------------------------|", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
+{"page_content": "| GPT 175B | 96 | 12288 | 96 | 175 |\n| GPT 1T | 128 | 25600 | 160 | 1008 |\n\nIn addition to using FSDP with parameters CPU offloading in the experiments, the [activation checkpointing feature](https://pytorch.org/docs/stable/checkpoint.html) in PyTorch is also applied in the tests.\n\nThe maximum per-GPU throughput of 159 teraFLOP/s (51% of NVIDIA A100 peak theoretical performance 312 teraFLOP/s/GPU) is achieved with batch size 20 and sequence length 512 on 128 GPUs for the GPT 175B model; further increase of the number of GPUs leads to per-GPU throughput degradation because of growing communication between the nodes.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "For the GPT 1T model, the maximum per-GPU throughput of 84 teraFLOP/s (27% of the peak teraFLOP/s) is achieved with batch size 4 and sequence length 2048 on 128 GPUs. However, further increase of the number of GPUs doesn\u2019t affect the per-GPU throughput too much because we observed that the largest bottleneck in the 1T model training is not from communication but from the slow CUDA cache allocator when peak GPU memory is reaching the limit. The use of A100 80G GPUs with larger memory capacity will mostly resolve this issue and also help scale the batch size to achieve much larger throughput.\n\n\n
\n
\n\n\n
\n
\n\n### Future Work", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
-{"page_content": "### Future Work\n\nIn the next beta release, we are planning to add efficient distributed model/states checkpointing APIs, meta device support for large model materialization, and mixed-precision support inside FSDP computation and communication. We\u2019re also going to make it easier to switch between [DDP](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html), [ZeRO1, ZeRO2](https://arxiv.org/abs/1910.02054) and FSDP flavors of data parallelism in the new API. To further improve FSDP performance, memory fragmentation reduction and communication efficiency improvements are also planned.\n\n### A Bit of History of 2 Versions of FSDP", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
+{"page_content": "\n\n### Future Work\n\nIn the next beta release, we are planning to add efficient distributed model/states checkpointing APIs, meta device support for large model materialization, and mixed-precision support inside FSDP computation and communication. We\u2019re also going to make it easier to switch between [DDP](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html), [ZeRO1, ZeRO2](https://arxiv.org/abs/1910.02054) and FSDP flavors of data parallelism in the new API. To further improve FSDP performance, memory fragmentation reduction and communication efficiency improvements are also planned.\n\n### A Bit of History of 2 Versions of FSDP", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "### A Bit of History of 2 Versions of FSDP\n\n[FairScale FSDP](https://engineering.fb.com/2021/07/15/open-source/fsdp/) was released in early 2021 as part of the FairScale library. And then we started the effort to upstream FairScale FSDP to PyTorch in PT 1.11, making it production-ready. We have selectively upstreamed and refactored key features from FairScale FSDP, redesigned user interfaces and made performance improvements.\n\nIn the near future, FairScale FSDP will stay in the FairScale repository for research projects, while generic and widely adopted features will be upstreamed to PyTorch incrementally and hardened accordingly.\n\nMeanwhile, PyTorch FSDP will focus more on production readiness and long-term support. This includes better integration with ecosystems and improvements on performance, usability, reliability, debuggability and composability.\n\n### Acknowledgments", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "### Acknowledgments\n\nWe would like to thank the authors of FairScale FSDP: Myle Ott, Sam Shleifer, Min Xu, Priya Goyal, Quentin Duval, Vittorio Caggiano, Tingting Markstrum, Anjali Sridhar. Thanks to the Microsoft DeepSpeed ZeRO team for developing and popularizing sharded data parallel techniques. Thanks to Pavel Belevich, Jessica Choi, Sisil Mehta for running experiments using PyTorch FSDP on different clusters. Thanks to Geeta Chauhan, Mahesh Yadav, Pritam Damania, Dmytro Dzhulgakov for supporting this effort and insightful discussions.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch library updates including new model serving library '\nauthor: Team PyTorch\n---\n\n\nAlong with the PyTorch 1.5 release, we are announcing new libraries for high-performance PyTorch model serving and tight integration with TorchElastic and Kubernetes. Additionally, we are releasing updated packages for torch_xla (Google Cloud TPUs), torchaudio, torchvision, and torchtext. All of these new libraries and enhanced capabilities are available today and accompany all of the core features [released in PyTorch 1.5](https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis). \n\n## TorchServe (Experimental)", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
-{"page_content": "## TorchServe (Experimental)\n\nTorchServe is a flexible and easy to use library for serving PyTorch models in production performantly at scale. It is cloud and environment agnostic and supports features such as multi-model serving, logging, metrics, and the creation of RESTful endpoints for application integration. TorchServe was jointly developed by engineers from Facebook and AWS with feedback and engagement from the broader PyTorch community. The experimental release of TorchServe is available today. Some of the highlights include:", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
-{"page_content": "* Support for both Python-based and TorchScript-based models\n* Default handlers for common use cases (e.g., image segmentation, text classification) as well as the ability to write custom handlers for other use cases\n* Model versioning, the ability to run multiple versions of a model at the same time, and the ability to roll back to an earlier version\n* The ability to package a model, learning weights, and supporting files (e.g., class mappings, vocabularies) into a single, persistent artifact (a.k.a. the \u201cmodel archive\u201d)\n* Robust management capability, allowing full configuration of models, versions, and individual worker threads via command line, config file, or run-time API\n* Automatic batching of individual inferences across HTTP requests\n* Logging including common metrics, and the ability to incorporate custom metrics\n* Ready-made Dockerfile for easy deployment\n* HTTPS support for secure deployment", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
-{"page_content": "To learn more about the APIs and the design of this feature, see the links below:\n* See for a full multi-node deployment reference architecture.\n* The full documentation can be found [here](https://pytorch.org/serve).\n\n## TorchElastic integration with Kubernetes (Experimental)", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
+{"page_content": "## TorchServe (Experimental)\n\nTorchServe is a flexible and easy to use library for serving PyTorch models in production performantly at scale. It is cloud and environment agnostic and supports features such as multi-model serving, logging, metrics, and the creation of RESTful endpoints for application integration. TorchServe was jointly developed by engineers from Facebook and AWS with feedback and engagement from the broader PyTorch community. The experimental release of TorchServe is available today. Some of the highlights include:\n\n* Support for both Python-based and TorchScript-based models\n* Default handlers for common use cases (e.g., image segmentation, text classification) as well as the ability to write custom handlers for other use cases\n* Model versioning, the ability to run multiple versions of a model at the same time, and the ability to roll back to an earlier version", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
+{"page_content": "* The ability to package a model, learning weights, and supporting files (e.g., class mappings, vocabularies) into a single, persistent artifact (a.k.a. the \u201cmodel archive\u201d)\n* Robust management capability, allowing full configuration of models, versions, and individual worker threads via command line, config file, or run-time API\n* Automatic batching of individual inferences across HTTP requests\n* Logging including common metrics, and the ability to incorporate custom metrics\n* Ready-made Dockerfile for easy deployment\n* HTTPS support for secure deployment\n\nTo learn more about the APIs and the design of this feature, see the links below:\n* See for a full multi-node deployment reference architecture.\n* The full documentation can be found [here](https://pytorch.org/serve).\n\n## TorchElastic integration with Kubernetes (Experimental)", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
{"page_content": "[TorchElastic](https://github.com/pytorch/elastic) is a proven library for training large scale deep neural networks at scale within companies like Facebook, where having the ability to dynamically adapt to server availability and scale as new compute resources come online is critical. Kubernetes enables customers using machine learning frameworks like PyTorch to run training jobs distributed across fleets of powerful GPU instances like the Amazon EC2 P3. Distributed training jobs, however, are not fault-tolerant, and a job cannot continue if a node failure or reclamation interrupts training. Further, jobs cannot start without acquiring all required resources, or scale up and down without being restarted. This lack of resiliency and flexibility results in increased training time and costs from idle resources. TorchElastic addresses these limitations by enabling distributed training jobs to be executed in a fault-tolerant and elastic manner. Until today, Kubernetes users needed to manage Pods and Services required for TorchElastic training jobs manually.", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
{"page_content": "Through the joint collaboration of engineers at Facebook and AWS, TorchElastic, adding elasticity and fault tolerance, is now supported using vanilla Kubernetes and through the managed EKS service from AWS.\n\nTo learn more see the [TorchElastic repo](http://pytorch.org/elastic/0.2.0rc0/kubernetes.html) for the controller implementation and docs on how to use it.\n\n## torch_xla 1.5 now available", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
{"page_content": "## torch_xla 1.5 now available\n\n[torch_xla](http://pytorch.org/xla/) is a Python package that uses the [XLA linear algebra compiler](https://www.tensorflow.org/xla) to accelerate the [PyTorch deep learning framework](https://pytorch.org/) on [Cloud TPUs](https://cloud.google.com/tpu/) and [Cloud TPU Pods](https://cloud.google.com/tpu/docs/tutorials/pytorch-pod). torch_xla aims to give PyTorch users the ability to do everything they can do on GPUs on Cloud TPUs as well while minimizing changes to the user experience. The project began with a conversation at NeurIPS 2017 and gathered momentum in 2018 when teams from Facebook and Google came together to create a proof of concept. We announced this collaboration at PTDC 2018 and made the PyTorch/XLA integration broadly available at PTDC 2019. The project already has 28 contributors, nearly 2k commits, and a repo that has been forked more than 100 times.", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
{"page_content": "This release of [torch_xla](http://pytorch.org/xla/) is aligned and tested with PyTorch 1.5 to reduce friction for developers and to provide a stable and mature PyTorch/XLA stack for training models using Cloud TPU hardware. You can [try it for free](https://medium.com/pytorch/get-started-with-pytorch-cloud-tpus-and-colab-a24757b8f7fc) in your browser on an 8-core Cloud TPU device with [Google Colab](https://colab.research.google.com/), and you can use it at a much larger scaleon [Google Cloud](https://cloud.google.com/gcp).\n\nSee the full torch_xla release notes [here](https://github.com/pytorch/xla/releases). Full docs and tutorials can be found [here](https://pytorch.org/xla/) and [here](https://cloud.google.com/tpu/docs/tutorials).\n\n## PyTorch Domain Libraries", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
-{"page_content": "## PyTorch Domain Libraries\n\ntorchaudio, torchvision, and torchtext complement PyTorch with common datasets, models, and transforms in each domain area. We\u2019re excited to share new releases for all three domain libraries alongside PyTorch 1.5 and the rest of the library updates. For this release, all three domain libraries are removing support for Python2 and will support Python3 only.\n\n### torchaudio 0.5\nThe torchaudio 0.5 release includes new transforms, functionals, and datasets. Highlights for the release include:\n\n* Added the Griffin-Lim functional and transform, `InverseMelScale` and `Vol` transforms, and `DB_to_amplitude`. \n* Added support for `allpass`, `fade`, `bandpass`, `bandreject`, `band`, `treble`, `deemph`, and `riaa` filters and transformations.\n* New datasets added including `LJSpeech` and `SpeechCommands` datasets. \n\nSee the release full notes [here](https://github.com/pytorch/audio/releases) and full docs can be found [here](https://pytorch.org/audio/).", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
-{"page_content": "### torchvision 0.6\nThe torchvision 0.6 release includes updates to datasets, models and a significant number of bug fixes. Highlights include:\n\n* Faster R-CNN now supports negative samples which allows the feeding of images without annotations at training time.\n* Added `aligned` flag to `RoIAlign` to match Detectron2. \n* Refactored abstractions for C++ video decoder\n\nSee the release full notes [here](https://github.com/pytorch/vision/releases) and full docs can be found [here](https://pytorch.org/docs/stable/torchvision/index.html).\n\n### torchtext 0.6\nThe torchtext 0.6 release includes a number of bug fixes and improvements to documentation. Based on user's feedback, dataset abstractions are currently being redesigned also. Highlights for the release include:", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
-{"page_content": "* Fixed an issue related to the SentencePiece dependency in conda package.\n* Added support for the experimental IMDB dataset to allow a custom vocab.\n* A number of documentation updates including adding a code of conduct and a deduplication of the docs on the torchtext site. \n\nYour feedback and discussions on the experimental datasets API are welcomed. You can send them to [issue #664](https://github.com/pytorch/text/issues/664). We would also like to highlight the pull request [here](https://github.com/pytorch/text/pull/701) where the latest dataset abstraction is applied to the text classification datasets. The feedback can be beneficial to finalizing this abstraction. \n\nSee the release full notes [here](https://github.com/pytorch/text/releases) and full docs can be found [here](https://pytorch.org/text/).\n\n\n*We\u2019d like to thank the entire PyTorch team, the Amazon team and the community for all their contributions to this work.*\n\nCheers!\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
+{"page_content": "## PyTorch Domain Libraries\n\ntorchaudio, torchvision, and torchtext complement PyTorch with common datasets, models, and transforms in each domain area. We\u2019re excited to share new releases for all three domain libraries alongside PyTorch 1.5 and the rest of the library updates. For this release, all three domain libraries are removing support for Python2 and will support Python3 only.\n\n### torchaudio 0.5\nThe torchaudio 0.5 release includes new transforms, functionals, and datasets. Highlights for the release include:\n\n* Added the Griffin-Lim functional and transform, `InverseMelScale` and `Vol` transforms, and `DB_to_amplitude`. \n* Added support for `allpass`, `fade`, `bandpass`, `bandreject`, `band`, `treble`, `deemph`, and `riaa` filters and transformations.\n* New datasets added including `LJSpeech` and `SpeechCommands` datasets. \n\nSee the release full notes [here](https://github.com/pytorch/audio/releases) and full docs can be found [here](https://pytorch.org/audio/).\n\n### torchvision 0.6", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
+{"page_content": "### torchvision 0.6\nThe torchvision 0.6 release includes updates to datasets, models and a significant number of bug fixes. Highlights include:\n\n* Faster R-CNN now supports negative samples which allows the feeding of images without annotations at training time.\n* Added `aligned` flag to `RoIAlign` to match Detectron2. \n* Refactored abstractions for C++ video decoder\n\nSee the release full notes [here](https://github.com/pytorch/vision/releases) and full docs can be found [here](https://pytorch.org/docs/stable/torchvision/index.html).\n\n### torchtext 0.6\nThe torchtext 0.6 release includes a number of bug fixes and improvements to documentation. Based on user's feedback, dataset abstractions are currently being redesigned also. Highlights for the release include:\n\n* Fixed an issue related to the SentencePiece dependency in conda package.\n* Added support for the experimental IMDB dataset to allow a custom vocab.", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
+{"page_content": "* A number of documentation updates including adding a code of conduct and a deduplication of the docs on the torchtext site. \n\nYour feedback and discussions on the experimental datasets API are welcomed. You can send them to [issue #664](https://github.com/pytorch/text/issues/664). We would also like to highlight the pull request [here](https://github.com/pytorch/text/pull/701) where the latest dataset abstraction is applied to the text classification datasets. The feedback can be beneficial to finalizing this abstraction. \n\nSee the release full notes [here](https://github.com/pytorch/text/releases) and full docs can be found [here](https://pytorch.org/text/).\n\n\n*We\u2019d like to thank the entire PyTorch team, the Amazon team and the community for all their contributions to this work.*\n\nCheers!\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/pytorch-library-updates-new-model-serving-library/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Understanding LazyTensor System Performance with PyTorch/XLA on Cloud TPU\"\nauthor: Vaibhav Singh\nfeatured-img: \"\"\n---\n\n## Introduction\n\nEase of use, expressivity, and debuggability are among the core principles of PyTorch. One of the key drivers for the ease of use is that PyTorch execution is by default \u201ceager, i.e. op by op execution preserves the imperative nature of the program. However, eager execution does not offer the compiler based optimization, for example, the optimizations when the computation can be expressed as a graph.\n\nLazyTensor [[1]], first introduced with PyTorch/XLA, helps combine these seemingly disparate approaches. While PyTorch eager execution is widely used, intuitive, and well understood, lazy execution is not as prevalent yet.", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "In this post we will explore some of the basic concepts of the LazyTensor System with the goal of applying these concepts to understand and debug performance of LazyTensor based implementations in PyTorch. Although we will use PyTorch/XLA on Cloud TPU as the vehicle for exploring these concepts, we hope that these ideas will be useful to understand other system(s) built on LazyTensors.\n\n## LazyTensor\n\nAny operation performed on a PyTorch tensor is by default dispatched as a kernel or a composition of kernels to the underlying hardware. These kernels are executed asynchronously on the underlying hardware. The program execution is not blocked until the value of a tensor is fetched. This approach scales extremely well with massively parallel programmed hardware such as GPUs.", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "The starting point of a LazyTensor system is a custom tensor type. In PyTorch/XLA, this type is called XLA tensor. In contrast to PyTorch\u2019s native tensor type, operations performed on XLA tensors are recorded into an IR graph. Let\u2019s examine an example that sums the product of two tensors:\n\n```python\nimport torch\nimport torch_xla\nimport torch_xla.core.xla_model as xm\n\ndev = xm.xla_device()\n\nx1 = torch.rand((3, 3)).to(dev)\nx2 = torch.rand((3, 8)).to(dev)\n\ny1 = torch.einsum('bs,st->bt', x1, x2)\nprint(torch_xla._XLAC._get_xla_tensors_text([y1]))\n```\n\nYou can execute [this](https://github.com/ultrons/xla/blob/lazy-tensor-post/contrib/colab/LazyTensor_Basics.ipynb) colab notebook to examine the resulting graph for y1. Notice that no computation has been performed yet.\n\n```python\ny1 = y1 + x2\nprint(torch_xla._XLAC._get_xla_tensors_text([y1]))\n```", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "The operations will continue until PyTorch/XLA encounters a barrier. This barrier can either be a [mark step()](https://github.com/pytorch/xla/blob/ff079bb48744e5aa6696201ccf34057f15fc7cac/torch_xla/core/xla_model.py#L751) api call or any other event which forces the execution of the graph recorded so far.\n\n```python\nxm.mark_step()\nprint(torch_xla._XLAC._get_xla_tensors_text([y1]))\n```\n\nOnce the mark_step() is called, the graph is compiled and then executed on TPU, i.e. the tensors have been materialized. Therefore, the graph is now reduced to a single line y1 tensor which holds the result of the computation.\n\n### Compile Once, Execute Often", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nThe operations will continue until PyTorch/XLA encounters a barrier. This barrier can either be a [mark step()](https://github.com/pytorch/xla/blob/ff079bb48744e5aa6696201ccf34057f15fc7cac/torch_xla/core/xla_model.py#L751) api call or any other event which forces the execution of the graph recorded so far.\n\n```python\nxm.mark_step()\nprint(torch_xla._XLAC._get_xla_tensors_text([y1]))\n```\n\nOnce the mark_step() is called, the graph is compiled and then executed on TPU, i.e. the tensors have been materialized. Therefore, the graph is now reduced to a single line y1 tensor which holds the result of the computation.\n\n### Compile Once, Execute Often", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "### Compile Once, Execute Often\n\nXLA compilation passes offer optimizations (e.g. op-fusion, which reduces HBM pressure by using scratch-pad memory for multiple ops, [ref](https://arxiv.org/pdf/2004.13336.pdf) ) and leverages lower level XLA infrastructure to optimally use the underlying hardware. However, there is one caveat, compilation passes are expensive, i.e. can add to the training step time. Therefore, this approach scales well if and only if we can **compile once and execute often** (compilation cache helps, such that the same graph is not compiled more than once).\n\nIn the following example, we create a small computation graph and time the execution:\n\n```python\ny1 = torch.rand((3, 8)).to(dev)\ndef dummy_step() :\n y1 = torch.einsum('bs,st->bt', y1, x)\n xm.mark_step()\n return y1\n```\n\n```python\n%timeit dummy_step\n```\n\n```python\nThe slowest run took 29.74 times longer than the fastest. This could mean that an intermediate result is being cached.\n10000000 loops, best of 5: 34.2 ns per loop\n```", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "You notice that the slowest step is quite longer than the fastest. This is because of the graph compilation overhead which is incurred only once for a given shape of graph, input shape, and output shape. Subsequent steps are faster because no graph compilation is necessary.\n\nThis also implies that we expect to see performance cliffs when the \u201ccompile once and execute often\u201d assumption breaks. Understanding when this assumption breaks is the key to understanding and optimizing the performance of a LazyTensor system. Let\u2019s examine what triggers the compilation.\n\n### Graph Compilation and Execution and LazyTensor Barrier", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "10000000 loops, best of 5: 34.2 ns per loop\n```\n\nYou notice that the slowest step is quite longer than the fastest. This is because of the graph compilation overhead which is incurred only once for a given shape of graph, input shape, and output shape. Subsequent steps are faster because no graph compilation is necessary.\n\nThis also implies that we expect to see performance cliffs when the \u201ccompile once and execute often\u201d assumption breaks. Understanding when this assumption breaks is the key to understanding and optimizing the performance of a LazyTensor system. Let\u2019s examine what triggers the compilation.\n\n### Graph Compilation and Execution and LazyTensor Barrier", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "We saw that the computation graph is compiled and executed when a LazyTensor barrier is encountered. There are three scenarios when the LazyTensor barrier is automatically or manually introduced. The first is the explicit call of mark_step() api as shown in the preceding example. mark_step() is also called implicitly at every step when you wrap your dataloader with MpDeviceLoader (highly recommended to overlap compute and data upload to TPU device). The [Optimizer step](https://github.com/pytorch/xla/blob/master/torch_xla/core/xla_model.py#L804) method of xla_model also allows to implicitly call mark_step (when you set barrier=True).", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "The second scenario where a barrier is introduced is when PyTorch/XLA finds an op with no mapping (lowering) to equivalent XLA HLO ops. PyTorch has [2000+](https://dev-discuss.pytorch.org/t/where-do-the-2000-pytorch-operators-come-from-more-than-you-wanted-to-know/373) operations. Although most of these operations are composite (i.e. can be expressed in terms of other fundamental operations), some of these operations do not have corresponding lowering in XLA.\n\n\n
\n
\n\nWhat happens when an op with no XLA lowering is used? PyTorch XLA stops the operation recording and cuts the graph(s) leading to the input(s) of the unlowered op. This cut graph is then compiled and dispatched for execution. The results (materialized tensor) of execution are sent back from device to host, the unlowered op is then executed on the host (cpu), and then downstream LazyTensor operations creating a new graph(s) until a barrier is encountered again.", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "The third and final scenario which results in a LazyTensor barrier is when there is a control structure/statement or another method which requires the value of a tensor. This statement would at the minimum cause the execution of the computation graph leading to the tensor (if the graph has already been seen) or cause compilation and execution of both.\n\nOther examples of such methods include .item(), isEqual(). In general, any operation that maps Tensor -> Scalar will cause this behavior.\n\n### Dynamic Graph\n\nAs illustrated in the preceding section, graph compilation cost is amortized if the same shape of the graph is executed many times. It\u2019s because the compiled graph is cached with a hash derived from the graph shape, input shape, and the output shape. If these shapes change it will trigger compilation, and too frequent compilation will result in training time degradation.\n\nLet\u2019s consider the following example:", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "Let\u2019s consider the following example:\n\n```python\ndef dummy_step(x, y, loss, acc=False):\n z = torch.einsum('bs,st->bt', y, x)\n step_loss = z.sum().view(1,)\n if acc:\n loss = torch.cat((loss, step_loss))\n else:\n loss = step_loss\n xm.mark_step()\n return loss\n\n\nimport time\ndef measure_time(acc=False):\n exec_times = []\n iter_count = 100\n x = torch.rand((512, 8)).to(dev)\n y = torch.rand((512, 512)).to(dev)\n loss = torch.zeros(1).to(dev)\n for i in range(iter_count):\n tic = time.time()\n loss = dummy_step(x, y, loss, acc=acc)\n toc = time.time()\n exec_times.append(toc - tic)\n return exec_times\n\ndyn = measure_time(acc=True) # acc= True Results in dynamic graph\nst = measure_time(acc=False) # Static graph, computation shape, inputs and output shapes don't change\n\nimport matplotlib.pyplot as plt\nplt.plot(st, label = 'static graph')\nplt.plot(dyn, label = 'dynamic graph')\nplt.legend()\nplt.title('Execution time in seconds')\n```", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "\n
\n
\n\nNote that static and dynamic cases have the same computation but dynamic graph compiles every time, leading to the higher overall run-time. In practice, the training step with recompilation can sometimes be an order of magnitude or slower. In the next section we discuss some of the PyTorch/XLA tools to debug training degradation.\n\n### Profiling Training Performance with PyTorch/XLA", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "PyTorch/XLA profiling consists of two major components. First is the client side profiling. This feature is turned on by simply setting the environment variable PT_XLA_DEBUG to 1. Client side profiling points to unlowered ops or device-to-host transfer in your source code. Client side profiling also reports if there are too frequent compilations happening during the training. You can explore some metrics and counters provided by PyTorch/XLA in conjunction with the profiler in [this](https://github.com/ultrons/xla/blob/lazy-tensor-post/contrib/colab/Exploring_LazyTensor_with_Debug_Metrics.ipynb) notebook.\n\nThe second component offered by PyTorch/XLA profiler is the inline trace annotation. For example:\n\n```python\nimport torch_xla.debug.profiler as xp", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "```python\nimport torch_xla.debug.profiler as xp\n\ndef train_imagenet():\n print('==> Preparing data..')\n img_dim = get_model_property('img_dim')\n ....\n server = xp.start_server(3294)\n def train_loop_fn(loader, epoch):\n ....\n model.train()\n for step, (data, target) in enumerate(loader):\n with xp.StepTrace('Train_Step', step_num=step):\n ....\n if FLAGS.amp:\n ....\n else:\n with xp.Trace('build_graph'):\n output = model(data)\n loss = loss_fn(output, target)\n loss.backward()\n xm.optimizer_step(optimizer)\n```\n\nNotice the start_server api call. The port number that you have used here is the same port number you will use with the tensorboard profiler in order to view the op trace similar to:\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
-{"page_content": "Op trace along with the client-side debugging function is a powerful set of tools to debug and optimize your training performance with PyTorch/XLA. For more detailed instructions on the profiler usage, the reader is encouraged to explore blogs [part-1](https://cloud.google.com/blog/topics/developers-practitioners/pytorchxla-performance-debugging-tpu-vm-part-1), [part-2](https://cloud.google.com/blog/topics/developers-practitioners/pytorchxla-performance-debugging-cloud-tpu-vm-part-ii), and [part-3](https://cloud.google.com/blog/topics/developers-practitioners/pytorchxla-performance-debugging-cloud-tpu-vm-part-iii) of the blog series on PyTorch/XLA performance debugging.\n\n### Summary", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "The third and final scenario which results in a LazyTensor barrier is when there is a control structure/statement or another method which requires the value of a tensor. This statement would at the minimum cause the execution of the computation graph leading to the tensor (if the graph has already been seen) or cause compilation and execution of both.\n\nOther examples of such methods include .item(), isEqual(). In general, any operation that maps Tensor -> Scalar will cause this behavior.\n\n### Dynamic Graph\n\nAs illustrated in the preceding section, graph compilation cost is amortized if the same shape of the graph is executed many times. It\u2019s because the compiled graph is cached with a hash derived from the graph shape, input shape, and the output shape. If these shapes change it will trigger compilation, and too frequent compilation will result in training time degradation.\n\nLet\u2019s consider the following example:\n\n```python\ndef dummy_step(x, y, loss, acc=False):\n z = torch.einsum('bs,st->bt', y, x)", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "z = torch.einsum('bs,st->bt', y, x)\n step_loss = z.sum().view(1,)\n if acc:\n loss = torch.cat((loss, step_loss))\n else:\n loss = step_loss\n xm.mark_step()\n return loss\n\n\nimport time\ndef measure_time(acc=False):\n exec_times = []\n iter_count = 100\n x = torch.rand((512, 8)).to(dev)\n y = torch.rand((512, 512)).to(dev)\n loss = torch.zeros(1).to(dev)\n for i in range(iter_count):\n tic = time.time()\n loss = dummy_step(x, y, loss, acc=acc)\n toc = time.time()\n exec_times.append(toc - tic)\n return exec_times\n\ndyn = measure_time(acc=True) # acc= True Results in dynamic graph\nst = measure_time(acc=False) # Static graph, computation shape, inputs and output shapes don't change\n\nimport matplotlib.pyplot as plt\nplt.plot(st, label = 'static graph')\nplt.plot(dyn, label = 'dynamic graph')\nplt.legend()\nplt.title('Execution time in seconds')\n```\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "\n\nNote that static and dynamic cases have the same computation but dynamic graph compiles every time, leading to the higher overall run-time. In practice, the training step with recompilation can sometimes be an order of magnitude or slower. In the next section we discuss some of the PyTorch/XLA tools to debug training degradation.\n\n### Profiling Training Performance with PyTorch/XLA\n\nPyTorch/XLA profiling consists of two major components. First is the client side profiling. This feature is turned on by simply setting the environment variable PT_XLA_DEBUG to 1. Client side profiling points to unlowered ops or device-to-host transfer in your source code. Client side profiling also reports if there are too frequent compilations happening during the training. You can explore some metrics and counters provided by PyTorch/XLA in conjunction with the profiler in [this](https://github.com/ultrons/xla/blob/lazy-tensor-post/contrib/colab/Exploring_LazyTensor_with_Debug_Metrics.ipynb) notebook.", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "The second component offered by PyTorch/XLA profiler is the inline trace annotation. For example:\n\n```python\nimport torch_xla.debug.profiler as xp\n\ndef train_imagenet():\n print('==> Preparing data..')\n img_dim = get_model_property('img_dim')\n ....\n server = xp.start_server(3294)\n def train_loop_fn(loader, epoch):\n ....\n model.train()\n for step, (data, target) in enumerate(loader):\n with xp.StepTrace('Train_Step', step_num=step):\n ....\n if FLAGS.amp:\n ....\n else:\n with xp.Trace('build_graph'):\n output = model(data)\n loss = loss_fn(output, target)\n loss.backward()\n xm.optimizer_step(optimizer)\n```\n\nNotice the start_server api call. The port number that you have used here is the same port number you will use with the tensorboard profiler in order to view the op trace similar to:\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
+{"page_content": "\n\nOp trace along with the client-side debugging function is a powerful set of tools to debug and optimize your training performance with PyTorch/XLA. For more detailed instructions on the profiler usage, the reader is encouraged to explore blogs [part-1](https://cloud.google.com/blog/topics/developers-practitioners/pytorchxla-performance-debugging-tpu-vm-part-1), [part-2](https://cloud.google.com/blog/topics/developers-practitioners/pytorchxla-performance-debugging-cloud-tpu-vm-part-ii), and [part-3](https://cloud.google.com/blog/topics/developers-practitioners/pytorchxla-performance-debugging-cloud-tpu-vm-part-iii) of the blog series on PyTorch/XLA performance debugging.\n\n### Summary", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "### Summary\n\nIn this article we have reviewed the fundamentals of the LazyTensor system. We built on those fundamentals with PyTorch/XLA to understand the potential causes of training performance degradation. We discussed why \u201ccompile once and execute often\u201d helps to get the best performance on LazyTensor systems, and why training slows down when this assumption breaks.\n\nWe hope that PyTorch users will find these insights helpful for their novel works with LazyTensor systems.\n\n### Acknowledgements\n\nA big thank you to my outstanding colleagues Jack Cao, Milad Mohammedi, Karl Weinmeister, Rajesh Thallam, Jordan Tottan (Google) and Geeta Chauhan (Meta) for their meticulous reviews and feedback. And thanks to the extended PyTorch/XLA development team from Google, Meta, and the open source community to make PyTorch possible on TPUs. And finally, thanks to the authors of the [LazyTensor paper](https://arxiv.org/pdf/2102.13267.pdf) not only for developing LazyTensor but also for writing such an accessible paper.", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "## Refrences\n\n[[1]] LazyTensor: combining eager execution with domain-specific compilers\n\n[1]: https://arxiv.org/pdf/2102.13267.pdf", "metadata": {"source": "https://pytorch.org/blog/understanding-lazytensor-system-performance-with-pytorch-xla-on-cloud-tpu/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Extending TorchVision\u2019s Transforms to Object Detection, Segmentation & Video tasks\"\nauthor: Philip Meier, Victor Fomin, Vasilis Vryniotis, Nicolas Hug\nfeatured-img: \"assets/images/Transforms-v2-feature-image.png\"\n---\n\n**Note**: A previous version of this post was published in November 2022. We have updated this post with the most up-to-date info, in view of the upcoming 0.15 release of torchvision in March 2023, jointly with PyTorch 2.0.\n\nTorchVision is extending its Transforms API! Here is what\u2019s new:\n\n- You can use them not only for Image Classification but also for Object Detection, Instance & Semantic Segmentation and Video Classification.\n- You can use new functional transforms for transforming Videos, Bounding Boxes and Segmentation Masks.", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
{"page_content": "The API is completely backward compatible with the previous one, and remains the same to assist the migration and adoption. We are now releasing this new API as Beta in the torchvision.transforms.v2 namespace, and we would love to get early feedback from you to improve its functionality. Please [_reach out to us_](https://github.com/pytorch/vision/issues/6753) if you have any questions or suggestions.\n\n## Limitations of current Transforms\n\nThe existing Transforms API of TorchVision (aka V1) only supports single images. As a result it can only be used for classification tasks:\n\n```python\nfrom torchvision import transforms\ntrans = transforms.Compose([\n transforms.ColorJitter(contrast=0.5),\n transforms.RandomRotation(30),\n transforms.CenterCrop(480),\n])\nimgs = trans(imgs)\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "The above approach doesn\u2019t support Object Detection nor Segmentation. This limitation made any non-classification Computer Vision tasks second-class citizens as one couldn\u2019t use the Transforms API to perform the necessary augmentations. Historically this made it difficult to train high-accuracy models using TorchVision\u2019s primitives and thus our Model Zoo lagged by several points from SoTA.", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "To circumvent this limitation, TorchVision offered [_custom implementations_](https://github.com/pytorch/vision/blob/main/references/detection/transforms.py) in its reference scripts that show-cased how one could perform augmentations in each task. Though this practice enabled us to train high accuracy [_classification_](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/), [_object detection & segmentation_](https://pytorch.org/blog/pytorch-1.12-new-library-releases/#beta-object-detection-and-instance-segmentation) models, it was a hacky approach which made those transforms impossible to import from the TorchVision binary.\n\n## The new Transforms API\n\nThe Transforms V2 API supports videos, bounding boxes, and segmentation masks meaning that it offers native support for many Computer Vision tasks. The new solution is a drop-in replacement:\n\n```python\nimport torchvision.transforms.v2 as transforms", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "# Exactly the same interface as V1:\ntrans = transforms.Compose([\n transforms.ColorJitter(contrast=0.5),\n transforms.RandomRotation(30),\n transforms.CenterCrop(480),\n])\nimgs, bboxes, labels = trans(imgs, bboxes, labels)\n```\n\nThe new Transform Classes can receive any arbitrary number of inputs without enforcing specific order or structure:\n\n```python\n# Already supported:\ntrans(imgs) # Image Classification\ntrans(videos) # Video Tasks\ntrans(imgs, bboxes, labels) # Object Detection\ntrans(imgs, bboxes, masks, labels) # Instance Segmentation\ntrans(imgs, masks) # Semantic Segmentation\ntrans({\"image\": imgs, \"box\": bboxes, \"tag\": labels}) # Arbitrary Structure\n\n# Future support:\ntrans(imgs, bboxes, labels, keypoints) # Keypoint Detection\ntrans(stereo_images, disparities, masks) # Depth Perception\ntrans(image1, image2, optical_flows, masks) # Optical Flow\ntrans(imgs_or_videos, labels) # MixUp/CutMix-style Transforms\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "The Transform Classes make sure that they apply the same random transforms to all the inputs to ensure consistent results.\n\nThe functional API has been updated to support all necessary signal processing kernels (resizing, cropping, affine transforms, padding etc) for all inputs:\n\n```python\nfrom torchvision.transforms.v2 import functional as F\n\n\n# High-level dispatcher, accepts any supported input type, fully BC\nF.resize(inpt, size=[224, 224])\n# Image tensor kernel\nF.resize_image_tensor(img_tensor, size=[224, 224], antialias=True) \n# PIL image kernel\nF.resize_image_pil(img_pil, size=[224, 224], interpolation=BILINEAR)\n# Video kernel\nF.resize_video(video, size=[224, 224], antialias=True) \n# Mask kernel\nF.resize_mask(mask, size=[224, 224])\n# Bounding box kernel\nF.resize_bounding_box(bbox, size=[224, 224], spatial_size=[256, 256])\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "Under the hood, the API uses Tensor subclassing to wrap the input, attach useful meta-data and dispatch to the right kernel. For your data to be compatible with these new transforms, you can either use the provided dataset wrapper which should work with most of torchvision built-in datasets, or your can wrap your data manually into Datapoints:\n\n```python\nfrom torchvision.datasets import wrap_dataset_for_transforms_v2\nds = CocoDetection(..., transforms=v2_transforms)\nds = wrap_dataset_for_transforms_v2(ds) # data is now compatible with transforms v2!\n\n# Or wrap your data manually using the lower-level Datapoint classes:\nfrom torchvision import datapoints\n\nimgs = datapoints.Image(images)\nvids = datapoints.Video(videos)\nmasks = datapoints.Mask(target[\"masks\u201c])\nbboxes = datapoints.BoundingBox(target[\"boxes\u201c], format=\u201dXYXY\u201d, spatial_size=imgs.shape)\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "In addition to the new API, we now provide importable implementations for several data augmentations that are used in SoTA research such as [_Large Scale Jitter_](https://github.com/pytorch/vision/blob/928b05cad36eadb13e169f03028767c8bcd1f21d/torchvision/transforms/v2/_geometry.py#L1109), [_AutoAugmentation_](https://github.com/pytorch/vision/blob/main/torchvision/transforms/v2/_auto_augment.py) methods and [_several_](https://github.com/pytorch/vision/blob/main/torchvision/transforms/v2/__init__.py) new Geometric, Color and Type Conversion transforms.\n\nThe API continues to support both PIL and Tensor backends for Images, single or batched input and maintains JIT-scriptability on both the functional and class APIs.. The new API has been [_verified_](https://github.com/pytorch/vision/pull/6433#issuecomment-1256741233) to achieve the same accuracy as the previous implementation.\n\n## An end-to-end example", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "## An end-to-end example\n\n Here is an example of the new API using the following [_image_](https://user-images.githubusercontent.com/5347466/195350223-8683ef25-1367-4292-9174-c15f85c7358e.jpg). It works both with PIL images and Tensors. For more examples and tutorials, [_take a look at our gallery!_](https://pytorch.org/vision/0.15/auto_examples/index.html)\n\n\n```python\nfrom torchvision import io, utils\nfrom torchvision import datapoints\nfrom torchvision.transforms import v2 as T\nfrom torchvision.transforms.v2 import functional as F", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "# Defining and wrapping input to appropriate Tensor Subclasses\npath = \"COCO_val2014_000000418825.jpg\"\nimg = datapoints.Image(io.read_image(path))\n# img = PIL.Image.open(path)\nbboxes = datapoints.BoundingBox(\n [[2, 0, 206, 253], [396, 92, 479, 241], [328, 253, 417, 332],\n [148, 68, 256, 182], [93, 158, 170, 260], [432, 0, 438, 26],\n [422, 0, 480, 25], [419, 39, 424, 52], [448, 37, 456, 62],\n [435, 43, 437, 50], [461, 36, 469, 63], [461, 75, 469, 94],\n [469, 36, 480, 64], [440, 37, 446, 56], [398, 233, 480, 304],\n [452, 39, 463, 63], [424, 38, 429, 50]],\n format=datapoints.BoundingBoxFormat.XYXY,\n spatial_size=F.get_spatial_size(img),\n)\nlabels = [59, 58, 50, 64, 76, 74, 74, 74, 74, 74, 74, 74, 74, 74, 50, 74, 74]\n# Defining and applying Transforms V2\ntrans = T.Compose(\n [\n T.ColorJitter(contrast=0.5),\n T.RandomRotation(30),\n T.CenterCrop(480),\n ]\n)\nimg, bboxes, labels = trans(img, bboxes, labels)\n# Visualizing results\nviz = utils.draw_bounding_boxes(F.to_image_tensor(img), boxes=bboxes)\nF.to_pil_image(viz).show()\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
-{"page_content": "## Development milestones and future work\n\nHere is where we are in development:\n\n- [x] Design API\n- [x] Write Kernels for transforming Videos, Bounding Boxes, Masks and Labels\n- [x] Rewrite all existing Transform Classes (stable + references) on the new API:\n - [x] Image Classification\n - [x] Video Classification\n - [x] Object Detection\n - [x] Instance Segmentation\n - [x] Semantic Segmentation\n- [x] Verify the accuracy of the new API for all supported Tasks and Backends\n- [x] Speed Benchmarks and Performance Optimizations (in progress - planned for Dec)\n- [x] Graduate from Prototype (planned for Q1)\n- [ ] Add support of Depth Perception, Keypoint Detection, Optical Flow and more (future)\n- [ ] Add smooth support for batch-wise transforms like MixUp and CutMix\n\n\nWe would love to get [_feedback_](https://github.com/pytorch/vision/issues/6753) from you to improve its functionality. Please reach out to us if you have any questions or suggestions.", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "])\nimgs = trans(imgs)\n```\n\nThe above approach doesn\u2019t support Object Detection nor Segmentation. This limitation made any non-classification Computer Vision tasks second-class citizens as one couldn\u2019t use the Transforms API to perform the necessary augmentations. Historically this made it difficult to train high-accuracy models using TorchVision\u2019s primitives and thus our Model Zoo lagged by several points from SoTA.", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "To circumvent this limitation, TorchVision offered [_custom implementations_](https://github.com/pytorch/vision/blob/main/references/detection/transforms.py) in its reference scripts that show-cased how one could perform augmentations in each task. Though this practice enabled us to train high accuracy [_classification_](https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/), [_object detection & segmentation_](https://pytorch.org/blog/pytorch-1.12-new-library-releases/#beta-object-detection-and-instance-segmentation) models, it was a hacky approach which made those transforms impossible to import from the TorchVision binary.\n\n## The new Transforms API\n\nThe Transforms V2 API supports videos, bounding boxes, and segmentation masks meaning that it offers native support for many Computer Vision tasks. The new solution is a drop-in replacement:\n\n```python\nimport torchvision.transforms.v2 as transforms\n\n# Exactly the same interface as V1:\ntrans = transforms.Compose([", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "trans = transforms.Compose([\n transforms.ColorJitter(contrast=0.5),\n transforms.RandomRotation(30),\n transforms.CenterCrop(480),\n])\nimgs, bboxes, labels = trans(imgs, bboxes, labels)\n```\n\nThe new Transform Classes can receive any arbitrary number of inputs without enforcing specific order or structure:\n\n```python\n# Already supported:\ntrans(imgs) # Image Classification\ntrans(videos) # Video Tasks\ntrans(imgs, bboxes, labels) # Object Detection\ntrans(imgs, bboxes, masks, labels) # Instance Segmentation\ntrans(imgs, masks) # Semantic Segmentation\ntrans({\"image\": imgs, \"box\": bboxes, \"tag\": labels}) # Arbitrary Structure\n\n# Future support:\ntrans(imgs, bboxes, labels, keypoints) # Keypoint Detection\ntrans(stereo_images, disparities, masks) # Depth Perception\ntrans(image1, image2, optical_flows, masks) # Optical Flow\ntrans(imgs_or_videos, labels) # MixUp/CutMix-style Transforms\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nThe Transform Classes make sure that they apply the same random transforms to all the inputs to ensure consistent results.\n\nThe functional API has been updated to support all necessary signal processing kernels (resizing, cropping, affine transforms, padding etc) for all inputs:\n\n```python\nfrom torchvision.transforms.v2 import functional as F\n\n\n# High-level dispatcher, accepts any supported input type, fully BC\nF.resize(inpt, size=[224, 224])\n# Image tensor kernel\nF.resize_image_tensor(img_tensor, size=[224, 224], antialias=True) \n# PIL image kernel\nF.resize_image_pil(img_pil, size=[224, 224], interpolation=BILINEAR)\n# Video kernel\nF.resize_video(video, size=[224, 224], antialias=True) \n# Mask kernel\nF.resize_mask(mask, size=[224, 224])\n# Bounding box kernel\nF.resize_bounding_box(bbox, size=[224, 224], spatial_size=[256, 256])\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nUnder the hood, the API uses Tensor subclassing to wrap the input, attach useful meta-data and dispatch to the right kernel. For your data to be compatible with these new transforms, you can either use the provided dataset wrapper which should work with most of torchvision built-in datasets, or your can wrap your data manually into Datapoints:\n\n```python\nfrom torchvision.datasets import wrap_dataset_for_transforms_v2\nds = CocoDetection(..., transforms=v2_transforms)\nds = wrap_dataset_for_transforms_v2(ds) # data is now compatible with transforms v2!\n\n# Or wrap your data manually using the lower-level Datapoint classes:\nfrom torchvision import datapoints\n\nimgs = datapoints.Image(images)\nvids = datapoints.Video(videos)\nmasks = datapoints.Mask(target[\"masks\u201c])\nbboxes = datapoints.BoundingBox(target[\"boxes\u201c], format=\u201dXYXY\u201d, spatial_size=imgs.shape)\n```", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "```\n\n\nIn addition to the new API, we now provide importable implementations for several data augmentations that are used in SoTA research such as [_Large Scale Jitter_](https://github.com/pytorch/vision/blob/928b05cad36eadb13e169f03028767c8bcd1f21d/torchvision/transforms/v2/_geometry.py#L1109), [_AutoAugmentation_](https://github.com/pytorch/vision/blob/main/torchvision/transforms/v2/_auto_augment.py) methods and [_several_](https://github.com/pytorch/vision/blob/main/torchvision/transforms/v2/__init__.py) new Geometric, Color and Type Conversion transforms.\n\nThe API continues to support both PIL and Tensor backends for Images, single or batched input and maintains JIT-scriptability on both the functional and class APIs.. The new API has been [_verified_](https://github.com/pytorch/vision/pull/6433#issuecomment-1256741233) to achieve the same accuracy as the previous implementation.\n\n## An end-to-end example", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "## An end-to-end example\n\n Here is an example of the new API using the following [_image_](https://user-images.githubusercontent.com/5347466/195350223-8683ef25-1367-4292-9174-c15f85c7358e.jpg). It works both with PIL images and Tensors. For more examples and tutorials, [_take a look at our gallery!_](https://pytorch.org/vision/0.15/auto_examples/index.html)\n\n\n```python\nfrom torchvision import io, utils\nfrom torchvision import datapoints\nfrom torchvision.transforms import v2 as T\nfrom torchvision.transforms.v2 import functional as F\n\n# Defining and wrapping input to appropriate Tensor Subclasses\npath = \"COCO_val2014_000000418825.jpg\"\nimg = datapoints.Image(io.read_image(path))\n# img = PIL.Image.open(path)\nbboxes = datapoints.BoundingBox(\n [[2, 0, 206, 253], [396, 92, 479, 241], [328, 253, 417, 332],\n [148, 68, 256, 182], [93, 158, 170, 260], [432, 0, 438, 26],\n [422, 0, 480, 25], [419, 39, 424, 52], [448, 37, 456, 62],\n [435, 43, 437, 50], [461, 36, 469, 63], [461, 75, 469, 94],", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "[469, 36, 480, 64], [440, 37, 446, 56], [398, 233, 480, 304],\n [452, 39, 463, 63], [424, 38, 429, 50]],\n format=datapoints.BoundingBoxFormat.XYXY,\n spatial_size=F.get_spatial_size(img),\n)\nlabels = [59, 58, 50, 64, 76, 74, 74, 74, 74, 74, 74, 74, 74, 74, 50, 74, 74]\n# Defining and applying Transforms V2\ntrans = T.Compose(\n [\n T.ColorJitter(contrast=0.5),\n T.RandomRotation(30),\n T.CenterCrop(480),\n ]\n)\nimg, bboxes, labels = trans(img, bboxes, labels)\n# Visualizing results\nviz = utils.draw_bounding_boxes(F.to_image_tensor(img), boxes=bboxes)\nF.to_pil_image(viz).show()\n```\n\n## Development milestones and future work\n\nHere is where we are in development:\n\n- [x] Design API\n- [x] Write Kernels for transforming Videos, Bounding Boxes, Masks and Labels\n- [x] Rewrite all existing Transform Classes (stable + references) on the new API:\n - [x] Image Classification\n - [x] Video Classification\n - [x] Object Detection\n - [x] Instance Segmentation\n - [x] Semantic Segmentation", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
+{"page_content": "- [x] Semantic Segmentation\n- [x] Verify the accuracy of the new API for all supported Tasks and Backends\n- [x] Speed Benchmarks and Performance Optimizations (in progress - planned for Dec)\n- [x] Graduate from Prototype (planned for Q1)\n- [ ] Add support of Depth Perception, Keypoint Detection, Optical Flow and more (future)\n- [ ] Add smooth support for batch-wise transforms like MixUp and CutMix\n\n\nWe would love to get [_feedback_](https://github.com/pytorch/vision/issues/6753) from you to improve its functionality. Please reach out to us if you have any questions or suggestions.", "metadata": {"source": "https://pytorch.org/blog/extending-torchvisions-transforms-to-object-detection-segmentation-and-video-tasks/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"New Library Updates in PyTorch 1.13\"\nauthor: Team PyTorch\nfeatured-img: \"assets/images/new-library-updates-in-pytorch-1.13-2.jpg\"\n---\n\n## Summary\n\nWe are bringing a number of improvements to the current PyTorch libraries, alongside the PyTorch 1.13 [release](https://github.com/pytorch/pytorch/releases). These updates demonstrate our focus on developing common and extensible APIs across all domains to make it easier for our community to build ecosystem projects on PyTorch.\n\nAlong with **1.13**, we are releasing updates to the PyTorch Libraries, please find them below.\n\n### TorchAudio \n\n#### (Beta) Hybrid Demucs Model and Pipeline\n\nHybrid Demucs is a music source separation model that uses both spectrogram and time domain features. It has demonstrated state-of-the-art performance in the Sony\u00ae Music DeMixing Challenge. (citation: [https://arxiv.org/abs/2111.03600](https://arxiv.org/abs/2111.03600))\n\nThe TorchAudio v0.13 release includes the following features", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "- MUSDB_HQ Dataset, which is used in Hybrid Demucs training ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.MUSDB_HQ.html#torchaudio.datasets.MUSDB_HQ))\n- Hybrid Demucs model architecture ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.models.HDemucs.html#torchaudio.models.HDemucs))\n- Three factory functions suitable for different sample rate ranges\n- Pre-trained pipelines ([docs](https://pytorch.org/audio/0.13.0/pipelines.html#id46))\n- SDR Results of pre-trained pipelines on MUSDB_HQ test set\n- Tutorial that steps through music source separation using the pretrained pipeline ([docs](https://pytorch.org/audio/0.13.0/tutorials/hybrid_demucs_tutorial.html))", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "| Pipeline | All | Drums | Bass | Other | Vocals |\n|----------------------------------------|-------|-------|--------|-------|--------|\n| HDEMUCS_HIGH_MUSDB* | 6.42 | 7.76 | 6.51 | 4.47 | 6.93 |\n| HDEMUCS_HIGH_MUSDB_PLUS** | 9.37 | 11.38 | 10.53 | 7.24 | 8.32 |\n\n* Trained on the training data of MUSDB-HQ dataset.
** Trained on both training and test sets of MUSDB-HQ and 150 extra songs from an internal database that were specifically produced for Meta.
\n\n```python\nfrom torchaudio.pipelines import HDEMUCS_HIGH_MUSDB_PLUS\n\nbundle = HDEMUCS_HIGH_MUSDB_PLUS\nmodel = bundle.get_model()\nsources_list = model.sources\n\nmixture, samplerate = torchaudio.load(\"song.wav\")\nsources = model(mixture)\naudios = dict(zip(sources_list, sources)\n```\n\nSpecial thanks to Alexandre Defossez for the guidance.\n\n#### (Beta) Datasets and Metadata Mode for SUPERB Benchmark", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "TorchAudio adds support for various audio-related datasets used in downstream tasks for benchmarking self-supervised learning models. With the addition of several new datasets, there is now support for the downstream tasks in version 1 of the [SUPERB benchmark](https://superbbenchmark.org/), which can be found in the [s3prl repository](https://github.com/s3prl/s3prl/blob/master/s3prl/downstream/docs/superb.md).\n\nFor these datasets, we also add metadata support through a `get_metadata` function, enabling faster dataset iteration or preprocessing without the need to load waveforms. The function returns the same features as `__getitem__`, except it returns the relative waveform path rather than the loaded waveform.\n\nDatasets with metadata functionality", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "- LIBRISPEECH ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.LIBRISPEECH.html#torchaudio.datasets.LIBRISPEECH))\n- LibriMix ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.LibriMix.html#torchaudio.datasets.LibriMix))\n- QUESST14 ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.QUESST14.html#torchaudio.datasets.QUESST14))\n- SPEECHCOMMANDS ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.SPEECHCOMMANDS.html#torchaudio.datasets.SPEECHCOMMANDS))\n- (new) FluentSpeechCommands ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.FluentSpeechCommands.html#torchaudio.datasets.FluentSpeechCommands))\n- (new) Snips ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.Snips.html#torchaudio.datasets.Snips))\n- (new) IEMOCAP ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.IEMOCAP.html#torchaudio.datasets.IEMOCAP))\n- (new) VoxCeleb1 ([Identification](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.VoxCeleb1Identification.html#torchaudio.datasets.VoxCeleb1Identification), [Verification](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.VoxCeleb1Verification.html#torchaudio.datasets.VoxCeleb1Verification))", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "#### (Beta) Custom Language Model support in CTC Beam Search Decoding\n\nTorchAudio released a CTC beam search decoder in release 0.12, with KenLM language model support. This release, there is added functionality for creating custom Python language models that are compatible with the decoder, using the `torchaudio.models.decoder.CTCDecoderLM` wrapper.\n\nFor more information on using a custom language model, please refer to the [documentation](https://pytorch.org/audio/0.13.0/generated/torchaudio.models.decoder.CTCDecoder.html#ctcdecoderlm) and [tutorial](https://pytorch.org/audio/0.13.0/tutorials/asr_inference_with_ctc_decoder_tutorial.html#custom-language-model).\n\n#### (Beta) StreamWriter\n\ntorchaudio.io.StreamWriter is a class for encoding media including audio and video. This can handle a wide variety of codecs, chunk-by-chunk encoding and GPU encoding.", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "```python\nwriter = StreamWriter(\"example.mp4\")\nwriter.add_audio_stream(\n sample_rate=16_000,\n num_channels=2,\n)\nwriter.add_video_stream(\n frame_rate=30,\n height=96,\n width=128,\n format=\"rgb24\",\n)\nwith writer.open():\n writer.write_audio_chunk(0, audio)\n writer.write_video_chunk(1, video)\n```\n\nFor more information, refer to [the documentation](https://pytorch.org/audio/0.13.0/generated/torchaudio.io.StreamWriter.html) and the following tutorials\n- [StreamWriter Basic Usage](https://pytorch.org/audio/0.13.0/tutorials/streamwriter_basic_tutorial.html)\n- [StreamWriter Advanced Usage](https://pytorch.org/audio/0.13.0/tutorials/streamwriter_advanced.html)\n- [Hardware-Accelerated Video Decoding and Encoding](https://pytorch.org/audio/0.13.0/hw_acceleration_tutorial.html)\n\n### TorchData\n\nFor a complete list of changes and new features, please visit [our repository\u2019s 0.5.0 release note](https://github.com/pytorch/data/releases).\n\n#### (Prototype) DataLoader2", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "- MUSDB_HQ Dataset, which is used in Hybrid Demucs training ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.MUSDB_HQ.html#torchaudio.datasets.MUSDB_HQ))\n- Hybrid Demucs model architecture ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.models.HDemucs.html#torchaudio.models.HDemucs))\n- Three factory functions suitable for different sample rate ranges\n- Pre-trained pipelines ([docs](https://pytorch.org/audio/0.13.0/pipelines.html#id46))\n- SDR Results of pre-trained pipelines on MUSDB_HQ test set\n- Tutorial that steps through music source separation using the pretrained pipeline ([docs](https://pytorch.org/audio/0.13.0/tutorials/hybrid_demucs_tutorial.html))\n\n| Pipeline | All | Drums | Bass | Other | Vocals |\n|----------------------------------------|-------|-------|--------|-------|--------|\n| HDEMUCS_HIGH_MUSDB* | 6.42 | 7.76 | 6.51 | 4.47 | 6.93 |", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "| HDEMUCS_HIGH_MUSDB_PLUS** | 9.37 | 11.38 | 10.53 | 7.24 | 8.32 |\n\n* Trained on the training data of MUSDB-HQ dataset.
** Trained on both training and test sets of MUSDB-HQ and 150 extra songs from an internal database that were specifically produced for Meta.
\n\n```python\nfrom torchaudio.pipelines import HDEMUCS_HIGH_MUSDB_PLUS\n\nbundle = HDEMUCS_HIGH_MUSDB_PLUS\nmodel = bundle.get_model()\nsources_list = model.sources\n\nmixture, samplerate = torchaudio.load(\"song.wav\")\nsources = model(mixture)\naudios = dict(zip(sources_list, sources)\n```\n\nSpecial thanks to Alexandre Defossez for the guidance.\n\n#### (Beta) Datasets and Metadata Mode for SUPERB Benchmark", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "TorchAudio adds support for various audio-related datasets used in downstream tasks for benchmarking self-supervised learning models. With the addition of several new datasets, there is now support for the downstream tasks in version 1 of the [SUPERB benchmark](https://superbbenchmark.org/), which can be found in the [s3prl repository](https://github.com/s3prl/s3prl/blob/master/s3prl/downstream/docs/superb.md).\n\nFor these datasets, we also add metadata support through a `get_metadata` function, enabling faster dataset iteration or preprocessing without the need to load waveforms. The function returns the same features as `__getitem__`, except it returns the relative waveform path rather than the loaded waveform.\n\nDatasets with metadata functionality\n\n- LIBRISPEECH ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.LIBRISPEECH.html#torchaudio.datasets.LIBRISPEECH))\n- LibriMix ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.LibriMix.html#torchaudio.datasets.LibriMix))", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "- QUESST14 ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.QUESST14.html#torchaudio.datasets.QUESST14))\n- SPEECHCOMMANDS ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.SPEECHCOMMANDS.html#torchaudio.datasets.SPEECHCOMMANDS))\n- (new) FluentSpeechCommands ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.FluentSpeechCommands.html#torchaudio.datasets.FluentSpeechCommands))\n- (new) Snips ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.Snips.html#torchaudio.datasets.Snips))\n- (new) IEMOCAP ([docs](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.IEMOCAP.html#torchaudio.datasets.IEMOCAP))\n- (new) VoxCeleb1 ([Identification](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.VoxCeleb1Identification.html#torchaudio.datasets.VoxCeleb1Identification), [Verification](https://pytorch.org/audio/0.13.0/generated/torchaudio.datasets.VoxCeleb1Verification.html#torchaudio.datasets.VoxCeleb1Verification))", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "#### (Beta) Custom Language Model support in CTC Beam Search Decoding\n\nTorchAudio released a CTC beam search decoder in release 0.12, with KenLM language model support. This release, there is added functionality for creating custom Python language models that are compatible with the decoder, using the `torchaudio.models.decoder.CTCDecoderLM` wrapper.\n\nFor more information on using a custom language model, please refer to the [documentation](https://pytorch.org/audio/0.13.0/generated/torchaudio.models.decoder.CTCDecoder.html#ctcdecoderlm) and [tutorial](https://pytorch.org/audio/0.13.0/tutorials/asr_inference_with_ctc_decoder_tutorial.html#custom-language-model).\n\n#### (Beta) StreamWriter\n\ntorchaudio.io.StreamWriter is a class for encoding media including audio and video. This can handle a wide variety of codecs, chunk-by-chunk encoding and GPU encoding.\n\n```python\nwriter = StreamWriter(\"example.mp4\")\nwriter.add_audio_stream(\n sample_rate=16_000,\n num_channels=2,\n)\nwriter.add_video_stream(", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "num_channels=2,\n)\nwriter.add_video_stream(\n frame_rate=30,\n height=96,\n width=128,\n format=\"rgb24\",\n)\nwith writer.open():\n writer.write_audio_chunk(0, audio)\n writer.write_video_chunk(1, video)\n```\n\nFor more information, refer to [the documentation](https://pytorch.org/audio/0.13.0/generated/torchaudio.io.StreamWriter.html) and the following tutorials\n- [StreamWriter Basic Usage](https://pytorch.org/audio/0.13.0/tutorials/streamwriter_basic_tutorial.html)\n- [StreamWriter Advanced Usage](https://pytorch.org/audio/0.13.0/tutorials/streamwriter_advanced.html)\n- [Hardware-Accelerated Video Decoding and Encoding](https://pytorch.org/audio/0.13.0/hw_acceleration_tutorial.html)\n\n### TorchData\n\nFor a complete list of changes and new features, please visit [our repository\u2019s 0.5.0 release note](https://github.com/pytorch/data/releases).\n\n#### (Prototype) DataLoader2", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "#### (Prototype) DataLoader2\n\n`DataLoader2` was introduced in the last release to execute `DataPipe` graph, with support for dynamic sharding for multi-process/distributed data loading, multiple backend ReadingServices, and `DataPipe` graph in-place modification (e.g. shuffle control).\n\nIn this release, we further consolidated the API for `DataLoader2` and a [detailed documentation is now available here](https://pytorch.org/data/0.5/dataloader2.html). We continue to welcome early adopters and feedback, as well as potential contributors. If you are interested in trying it out, we encourage you to install the nightly version of TorchData.\n\n#### (Beta) Data Loading from Cloud Service Providers\n\nWe extended our support to load data from additional cloud storage providers via DataPipes, now covering AWS, Google Cloud Storage, and Azure. A [tutorial is also available](https://pytorch.org/data/0.5/tutorial.html#working-with-cloud-storage-providers). We are open to feedback and feature requests.", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "We also performed a simple benchmark, comparing the performance of data loading from AWS S3 and attached volume on an AWS EC2 instance. The results are [visible here](https://github.com/pytorch/data/blob/gh/NivekT/100/head/benchmarks/cloud/aws_s3_results.md).\n\n### torch::deploy (Beta)\n\ntorch::deploy is now in Beta! torch::deploy is a C++ library for Linux based operating systems that allows you to run multiple Python interpreters in a single process. You can run your existing eager PyTorch models without any changes for production inference use cases. Highlights include: \n\n- Existing models work out of the box\u2013no need to modify your python code to support tracing.\n- Full support for your existing Python environment including C extensions.\n- No need to cross process boundaries to load balance in multi-GPU serving environments.\n- Model weight can be shared between multiple Python interpreters.\n- A vastly improved installation and setup process.\n\n```Python\ntorch::deploy::InterpreterManager manager(4);", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "// access one of the 4 interpreters\nauto I = manager.acquireOne();\n\n// run infer from your_model.py\nI.global(\"your_model\", \"infer\")({at::randn({10, 240, 320})});\n```\n\nLearn more [here](https://github.com/pytorch/multipy).\n\n#### (Beta) CUDA/ROCm/CPU Backends\n\ntorch::deploy now links against standard PyTorch Python distributions so all accelerators that PyTorch core supports such as CUDA and AMD/HIP work out of the box.\n\n- Can install any device variant of PyTorch via pip/conda like normal.\n- [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)\n\n#### (Prototype) aarch64/arm64 support\n\ntorch::deploy now has basic support for aarch64 Linux systems.\n\n- We're looking to gather feedback on it and learn more about arm use cases for eager PyTorch models.\n- Learn more / share your use case at [https://github.com/pytorch/multipy/issues/64](https://github.com/pytorch/multipy/issues/64)\n\n### TorchEval\n\n#### (Prototype) Introducing Native Metrics Support for PyTorch", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "TorchEval is a library built for users who want highly performant implementations of common metrics to evaluate machine learning models. It also provides an easy to use interface for building custom metrics with the same toolkit. Building your metrics with TorchEval makes running distributed training loops with [torch.distributed](https://pytorch.org/docs/stable/distributed.html) a breeze.\n\nLearn more with our [docs](https://pytorch.org/torcheval), see our [examples](https://pytorch.org/torcheval/metric_example.html), or check out our [GitHub repo](http://github.com/pytorch/torcheval).\n\n### TorchMultimodal Release (Beta)\n\nPlease watch for upcoming blogs in early November that will introduce TorchMultimodal, a PyTorch domain library for training SoTA multi-task multimodal models at scale, in more details; in the meantime, play around with the library and models through our [tutorial](https://pytorch.org/tutorials/beginner/flava_finetuning_tutorial.html).\n\n### TorchRec", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "### TorchRec\n\n#### (Prototype) Simplified Optimizer Fusion APIs\n\nWe\u2019ve provided a simplified and more intuitive API for setting fused optimizer settings via apply_optimizer_in_backward. This new approach enables the ability to specify optimizer settings on a per-parameter basis and sharded modules will configure [FBGEMM\u2019s TableBatchedEmbedding modules accordingly](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py#L181). Additionally, this now let's TorchRec\u2019s planner account for optimizer memory usage. This should alleviate reports of sharding jobs OOMing after using Adam using a plan generated from planner.\n\n#### (Prototype) Simplified Sharding APIs", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "torch::deploy::InterpreterManager manager(4);\n\n// access one of the 4 interpreters\nauto I = manager.acquireOne();\n\n// run infer from your_model.py\nI.global(\"your_model\", \"infer\")({at::randn({10, 240, 320})});\n```\n\nLearn more [here](https://github.com/pytorch/multipy).\n\n#### (Beta) CUDA/ROCm/CPU Backends\n\ntorch::deploy now links against standard PyTorch Python distributions so all accelerators that PyTorch core supports such as CUDA and AMD/HIP work out of the box.\n\n- Can install any device variant of PyTorch via pip/conda like normal.\n- [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)\n\n#### (Prototype) aarch64/arm64 support\n\ntorch::deploy now has basic support for aarch64 Linux systems.\n\n- We're looking to gather feedback on it and learn more about arm use cases for eager PyTorch models.\n- Learn more / share your use case at [https://github.com/pytorch/multipy/issues/64](https://github.com/pytorch/multipy/issues/64)\n\n### TorchEval", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "### TorchEval\n\n#### (Prototype) Introducing Native Metrics Support for PyTorch\n\nTorchEval is a library built for users who want highly performant implementations of common metrics to evaluate machine learning models. It also provides an easy to use interface for building custom metrics with the same toolkit. Building your metrics with TorchEval makes running distributed training loops with [torch.distributed](https://pytorch.org/docs/stable/distributed.html) a breeze.\n\nLearn more with our [docs](https://pytorch.org/torcheval), see our [examples](https://pytorch.org/torcheval/metric_example.html), or check out our [GitHub repo](http://github.com/pytorch/torcheval).\n\n### TorchMultimodal Release (Beta)", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "### TorchMultimodal Release (Beta)\n\nPlease watch for upcoming blogs in early November that will introduce TorchMultimodal, a PyTorch domain library for training SoTA multi-task multimodal models at scale, in more details; in the meantime, play around with the library and models through our [tutorial](https://pytorch.org/tutorials/beginner/flava_finetuning_tutorial.html).\n\n### TorchRec\n\n#### (Prototype) Simplified Optimizer Fusion APIs", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "#### (Prototype) Simplified Optimizer Fusion APIs\n\nWe\u2019ve provided a simplified and more intuitive API for setting fused optimizer settings via apply_optimizer_in_backward. This new approach enables the ability to specify optimizer settings on a per-parameter basis and sharded modules will configure [FBGEMM\u2019s TableBatchedEmbedding modules accordingly](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/fbgemm_gpu/split_table_batched_embeddings_ops.py#L181). Additionally, this now let's TorchRec\u2019s planner account for optimizer memory usage. This should alleviate reports of sharding jobs OOMing after using Adam using a plan generated from planner.\n\n#### (Prototype) Simplified Sharding APIs", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "#### (Prototype) Simplified Sharding APIs\n\nWe\u2019re introducing the shard API, which now allows you to shard only the embedding modules within a model, and provides an alternative to the current main entry point - DistributedModelParallel. This lets you have a finer grained control over the rest of the model, which can be useful for customized parallelization logic, and inference use cases (which may not require any parallelization on the dense layers). We\u2019re also introducing construct_module_sharding_plan, providing a simpler interface to the TorchRec sharder.\n\n#### (Beta) Quantized Comms", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "#### (Beta) Quantized Comms\n\nApplying [quantization or mixed precision](https://dlp-kdd.github.io/assets/pdf/a11-yang.pdf) to tensors in a collective call during model parallel training greatly improves training efficiency, with little to no effect on model quality. TorchRec now integrates with the [quantized comms library provided by FBGEMM GPU](https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/fbgemm_gpu/quantize_comm.py) and provides an interface to construct encoders and decoders (codecs) that surround the all_to_all, and reduce_scatter collective calls in the output_dist of a sharded module. We also allow you to construct your own codecs to apply to your sharded module. The codces provided by FBGEMM allow FP16, BF16, FP8, and INT8 compressions, and you may use different quantizations for the forward pass and backward pass.\n\n### TorchSnapshot (Beta)", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "### TorchSnapshot (Beta)\n\nAlong with PyTorch 1.13, we are releasing the beta version of TorchSnapshot, which is a performant, memory-efficient checkpointing library for PyTorch applications, designed with large, complex distributed workloads in mind. Highlights include:\n\n- Performance: TorchSnapshot provides a fast checkpointing implementation employing various optimizations, including zero-copy serialization for most tensor types, overlapped device-to-host copy and storage I/O, parallelized storage I/O\n- Memory Use: TorchSnapshot's memory usage adapts to the host's available resources, greatly reducing the chance of out-of-memory issues when saving and loading checkpoints\n- Usability: Simple APIs that are consistent between distributed and non-distributed workloads\n\nLearn more with our [tutorial](https://pytorch.org/torchsnapshot/main/getting_started.html).\n\n### TorchVision", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "### TorchVision \n\nWe are happy to introduce torchvision v0.14 [(release note)](https://github.com/pytorch/vision/releases). This version introduces a new [model registration API](https://pytorch.org/blog/easily-list-and-initialize-models-with-new-apis-in-torchvision/) to help users retrieving and listing models and weights. It also includes new image and video classification models such as MViT, S3D, Swin Transformer V2, and MaxViT. Last but not least, we also have new primitives and augmentation such as PolynomicalLR scheduler and SimpleCopyPaste.\n\n#### (Beta) Model Registration API", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "#### (Beta) Model Registration API\n\nFollowing up on the [multi-weight support API](https://pytorch.org/blog/introducing-torchvision-new-multi-weight-support-api/) that was released on the previous version, we have added a new [model registration API](https://pytorch.org/blog/easily-list-and-initialize-models-with-new-apis-in-torchvision/) to help users retrieve models and weights. There are now 4 new methods under the torchvision.models module: get_model, get_model_weights, get_weight, and list_models. Here are examples of how we can use them:\n\n```Python\nimport torchvision\nfrom torchvision.models import get_model, get_model_weights, list_models\n\n\nmax_params = 5000000\n\ntiny_models = []\nfor model_name in list_models(module=torchvision.models):\n weights_enum = get_model_weights(model_name)\n if len([w for w in weights_enum if w.meta[\"num_params\"] <= max_params]) > 0:\n tiny_models.append(model_name)\n\nprint(tiny_models)\n# ['mnasnet0_5', 'mnasnet0_75', 'mnasnet1_0', 'mobilenet_v2', ...]", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "model = get_model(tiny_models[0], weights=\"DEFAULT\")\nprint(sum(x.numel() for x in model.state_dict().values()))\n# 2239188\n```\n\n#### (Beta) New Video Classification Models\n\nWe added two new video classification models, MViT and S3D. MViT is a state of the art video classification transformer model which has 80.757% accuracy on the Kinetics400 dataset, while S3D is a relatively small model with good accuracy for its size. These models can be used as follows:\n\n```Python\nimport torch\nfrom torchvision.models.video import *\n\nvideo = torch.rand(3, 32, 800, 600)\nmodel = mvit_v2_s(weights=\"DEFAULT\")\n# model = s3d(weights=\"DEFAULT\")\nmodel.eval()\nprediction = model(images)\n```\n\nHere is the table showing the accuracy of the new video classification models tested in the Kinetics400 dataset.", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "| **Model** | **Acc@1** | **Acc@5** |\n|--------------------------------|-----------|-----------|\n| mvit_v1_b | 81.474 | 95.776 |\n| mvit_v2_s | 83.196 | 96.36 |\n| s3d | 83.582 | 96.64 |\n\nWe would like to thank Haoqi Fan, Yanghao Li, Christoph Feichtenhofer and Wan-Yen Lo for their work on [PyTorchVideo](https://github.com/facebookresearch/pytorchvideo/) and their support during the development of the MViT model. We would like to thank Sophia Zhi for her contribution implementing the S3D model in torchvision.\n\n#### (Stable) New Architecture and Model Variants\n\nFor Classification Models, we\u2019ve added the Swin Transformer V2 architecture along with pre-trained weights for its tiny/small/base variants. In addition, we have added support for the MaxViT transformer. Here is an example on how to use the models:\n\n```Python\nimport torch\nfrom torchvision.models import *", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "image = torch.rand(1, 3, 224, 224)\nmodel = swin_v2_t(weights=\"DEFAULT\").eval()\n# model = maxvit_t(weights=\"DEFAULT\").eval()\nprediction = model(image)\n```\n\nHere is the table showing the accuracy of the models tested on ImageNet1K dataset.\n\n| **Model** | **Acc@1** | **Acc@1 change over V1** | **Acc@5** | **Acc@5 change over V1** |\n|---------------|-----------|--------------------------|-----------|--------------------------|\n| swin_v2_t | 82.072 | + 0.598 | 96.132 | + 0.356 |\n| swin_v2_s | 83.712 | + 0.516 | 96.816 | + 0.456 |\n| swin_v2_b | 84.112 | + 0.530 | 96.864 | + 0.224 |\n| maxvit_t | 83.700 | - | 96.722 | - |\n\nWe would like to thank [Ren Pang](https://github.com/ain-soph) and [Teodor Poncu](https://github.com/TeodorPoncu) for contributing the 2 models to torchvision.\n\n### (Stable) New Primitives & Augmentations", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "model = get_model(tiny_models[0], weights=\"DEFAULT\")\nprint(sum(x.numel() for x in model.state_dict().values()))\n# 2239188\n```\n\n#### (Beta) New Video Classification Models\n\nWe added two new video classification models, MViT and S3D. MViT is a state of the art video classification transformer model which has 80.757% accuracy on the Kinetics400 dataset, while S3D is a relatively small model with good accuracy for its size. These models can be used as follows:\n\n```Python\nimport torch\nfrom torchvision.models.video import *\n\nvideo = torch.rand(3, 32, 800, 600)\nmodel = mvit_v2_s(weights=\"DEFAULT\")\n# model = s3d(weights=\"DEFAULT\")\nmodel.eval()\nprediction = model(images)\n```\n\nHere is the table showing the accuracy of the new video classification models tested in the Kinetics400 dataset.\n\n| **Model** | **Acc@1** | **Acc@5** |\n|--------------------------------|-----------|-----------|\n| mvit_v1_b | 81.474 | 95.776 |", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "| mvit_v2_s | 83.196 | 96.36 |\n| s3d | 83.582 | 96.64 |\n\nWe would like to thank Haoqi Fan, Yanghao Li, Christoph Feichtenhofer and Wan-Yen Lo for their work on [PyTorchVideo](https://github.com/facebookresearch/pytorchvideo/) and their support during the development of the MViT model. We would like to thank Sophia Zhi for her contribution implementing the S3D model in torchvision.\n\n#### (Stable) New Architecture and Model Variants\n\nFor Classification Models, we\u2019ve added the Swin Transformer V2 architecture along with pre-trained weights for its tiny/small/base variants. In addition, we have added support for the MaxViT transformer. Here is an example on how to use the models:\n\n```Python\nimport torch\nfrom torchvision.models import *\n\nimage = torch.rand(1, 3, 224, 224)\nmodel = swin_v2_t(weights=\"DEFAULT\").eval()\n# model = maxvit_t(weights=\"DEFAULT\").eval()\nprediction = model(image)\n```", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "prediction = model(image)\n```\n\nHere is the table showing the accuracy of the models tested on ImageNet1K dataset.\n\n| **Model** | **Acc@1** | **Acc@1 change over V1** | **Acc@5** | **Acc@5 change over V1** |\n|---------------|-----------|--------------------------|-----------|--------------------------|\n| swin_v2_t | 82.072 | + 0.598 | 96.132 | + 0.356 |\n| swin_v2_s | 83.712 | + 0.516 | 96.816 | + 0.456 |\n| swin_v2_b | 84.112 | + 0.530 | 96.864 | + 0.224 |\n| maxvit_t | 83.700 | - | 96.722 | - |\n\nWe would like to thank [Ren Pang](https://github.com/ain-soph) and [Teodor Poncu](https://github.com/TeodorPoncu) for contributing the 2 models to torchvision.\n\n### (Stable) New Primitives & Augmentations", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "### (Stable) New Primitives & Augmentations\n\nIn this release we\u2019ve added the [SimpleCopyPaste](https://arxiv.org/abs/2012.07177) augmentation in our reference scripts and we up-streamed the PolynomialLR scheduler to PyTorch Core. We would like to thank [Lezwon Castelino](https://github.com/lezwon) and [Federico Pozzi](https://github.com/federicopozzi33) for their contributions. We are continuing our efforts to modernize TorchVision by adding more SoTA primitives, Augmentations and architectures with the help of our community. If you are interested in contributing, have a look at the following [issue](https://github.com/pytorch/vision/issues/6323).\n\n### Torch-TensorRT\n\n#### (Prototype) TensorRT with FX2TRT frontend\n\nTorch-TensorRT is the PyTorch integration for TensorRT, providing high performance inference on NVIDIA GPUs. Torch-TRT allows for optimizing models directly in PyTorch for deployment providing up to 6x performance improvement.", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "Torch-TRT is an AoT compiler which ingests an nn.Module or TorchScript module, optimizes compatible subgraphs in TensorRT & leaves the rest to run in PyTorch. This gives users the performance of TensorRT, but the usability and familiarity of Torch.\n\nTorch-TensorRT is part of the PyTorch ecosystem, and was released as v1.0 in November \u201821. There are currently two distinct front-ends: Torchscript & FX. Each provides the same value proposition and underlying operation with the primary difference being the input & output formats (TS vs FX / Python).\n\nThe Torchscript front-end was included in v1.0 and should be considered stable. The FX front-end is first released in v1.2 and should be considered a Beta.\n\nRelevant Links:", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "Relevant Links:\n\n- [Github](https://github.com/pytorch/TensorRT)\n- [Documentation](https://pytorch.org/TensorRT/)\n- [Generic (TS) getting started guide](https://pytorch.org/TensorRT/getting_started/getting_started_with_python_api.html)\n- [FX getting started guide](https://pytorch.org/TensorRT/tutorials/getting_started_with_fx_path.html)\n\n#### (Stable) Introducing Torch-TensorRT", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "#### (Stable) Introducing Torch-TensorRT\n\nTorch-TensorRT is an integration for PyTorch that leverages inference optimizations of TensorRT on NVIDIA GPUs. It takes advantage of TensorRT optimizations, such as FP16 and INT8 reduced precision, graph optimization, operation fusion, etc. while offering a fallback to native PyTorch when TensorRT does not support the model subgraphs. Currently, there are two frontend paths existing in the library that help to convert a PyTorch model to tensorRT engine. One path is through Torch Script (TS) and the other is through FX frontend. That being said, the models are traced by either TS or FX into their IR graph and then converted to TensorRT from it.\n\nLearn more with our [tutorial](https://pytorch.org/TensorRT/).\n\n### TorchX", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "Torch-TRT is an AoT compiler which ingests an nn.Module or TorchScript module, optimizes compatible subgraphs in TensorRT & leaves the rest to run in PyTorch. This gives users the performance of TensorRT, but the usability and familiarity of Torch.\n\nTorch-TensorRT is part of the PyTorch ecosystem, and was released as v1.0 in November \u201821. There are currently two distinct front-ends: Torchscript & FX. Each provides the same value proposition and underlying operation with the primary difference being the input & output formats (TS vs FX / Python).\n\nThe Torchscript front-end was included in v1.0 and should be considered stable. The FX front-end is first released in v1.2 and should be considered a Beta.\n\nRelevant Links:\n\n- [Github](https://github.com/pytorch/TensorRT)\n- [Documentation](https://pytorch.org/TensorRT/)\n- [Generic (TS) getting started guide](https://pytorch.org/TensorRT/getting_started/getting_started_with_python_api.html)", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "- [FX getting started guide](https://pytorch.org/TensorRT/tutorials/getting_started_with_fx_path.html)\n\n#### (Stable) Introducing Torch-TensorRT\n\nTorch-TensorRT is an integration for PyTorch that leverages inference optimizations of TensorRT on NVIDIA GPUs. It takes advantage of TensorRT optimizations, such as FP16 and INT8 reduced precision, graph optimization, operation fusion, etc. while offering a fallback to native PyTorch when TensorRT does not support the model subgraphs. Currently, there are two frontend paths existing in the library that help to convert a PyTorch model to tensorRT engine. One path is through Torch Script (TS) and the other is through FX frontend. That being said, the models are traced by either TS or FX into their IR graph and then converted to TensorRT from it.\n\nLearn more with our [tutorial](https://pytorch.org/TensorRT/).\n\n### TorchX", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "### TorchX\n\nTorchX 0.3 updates include a new list API, experiment tracking, elastic training and improved scheduler support. There\u2019s also a new Multi-Objective NAS [tutorial](https://pytorch.org/tutorials/intermediate/ax_multiobjective_nas_tutorial.html) using TorchX + Ax.\n\n#### (Prototype) List\n\nThe newly added list command and API allows you to list recently launched jobs and their statuses for a given scheduler directly from within TorchX.\n\n- This removes the need for using secondary tools to list the jobs.\n- Full programmatic access to recent jobs for integration with custom tools.\n\n```Python\n$ torchx list -s kubernetes\nAPP HANDLE APP STATUS\n----------------------------------------------- -----------------\nkubernetes://torchx/default:train-f2nx4459p5crr SUCCEEDED\n```\n\nLearn more with our [documentation](https://pytorch.org/torchx/main/schedulers.html#torchx.schedulers.Scheduler.list).\n\n#### (Prototype) Tracker", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "#### (Prototype) Tracker\n\nTorchX Tracker is a new prototype library that provides a flexible and customizable experiment and artifact tracking interface. This allows you to track inputs and outputs for jobs across multiple steps to make it easier to use TorchX with pipelines and other external systems.\n\n```Python\nfrom torchx import tracker\n\napp_run = tracker.app_run_from_env()\napp_run.add_metadata(lr=lr, gamma=gamma) # hyper parameters\napp_run.add_artifact(\"model\", \"storage://path/mnist_cnn.pt\") # logs / checkpoints\napp_run.add_source(parent_run_id, \"model\") # lineage\n```\n\nExample:\n\n- [https://github.com/pytorch/torchx/tree/main/torchx/examples/apps/tracker](https://github.com/pytorch/torchx/tree/main/torchx/examples/apps/tracker)\n- [https://pytorch.org/torchx/main/tracker.html](https://pytorch.org/torchx/main/tracker.html)\n\n#### (Prototype) Elastic Training and Autoscaling", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "#### (Prototype) Elastic Training and Autoscaling\n\nElasticity on Ray and Kubernetes \u2013 automatic scale up of distributed training jobs when using a supported scheduler. Learn more with our [documentation](https://pytorch.org/torchx/main/components/distributed.html).\n\n#### (Prototype) Scheduler Improvements: IBM\u00ae Spectrum LSF\n\nAdded prototype support for the IBM Spectrum LSF scheduler.\n\n#### (Beta) AWS Batch Scheduler\n\nThe AWS Batch scheduler integration is now in beta.\n\n- log fetching and listing jobs is now supported.\n- Added configs for job priorities and queue policies\n- Easily access job UI via ui_url\n[https://pytorch.org/torchx/main/schedulers/aws_batch.html](https://pytorch.org/torchx/main/schedulers/aws_batch.html)\n\n#### (Prototype) AnyPrecision Optimizer \n\nDrop in replacement for AdamW optimizer that reduces GPU memory, enables two main features:", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
-{"page_content": "- Ability to successfully train the entire model pipeline in full BFloat16.\nKahan summation ensures precision. This can improve training throughput, especially on huge models, by reduced memory and increased computation speed.\n- Ability to change the variance state to BFloat16. This can reduce overall memory required for model training with additional speed improvements.\n\nFind more information [here](https://github.com/pytorch/torchdistx/pull/52).", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "#### (Prototype) Elastic Training and Autoscaling\n\nElasticity on Ray and Kubernetes \u2013 automatic scale up of distributed training jobs when using a supported scheduler. Learn more with our [documentation](https://pytorch.org/torchx/main/components/distributed.html).\n\n#### (Prototype) Scheduler Improvements: IBM\u00ae Spectrum LSF\n\nAdded prototype support for the IBM Spectrum LSF scheduler.\n\n#### (Beta) AWS Batch Scheduler\n\nThe AWS Batch scheduler integration is now in beta.\n\n- log fetching and listing jobs is now supported.\n- Added configs for job priorities and queue policies\n- Easily access job UI via ui_url\n[https://pytorch.org/torchx/main/schedulers/aws_batch.html](https://pytorch.org/torchx/main/schedulers/aws_batch.html)\n\n#### (Prototype) AnyPrecision Optimizer \n\nDrop in replacement for AdamW optimizer that reduces GPU memory, enables two main features:\n\n- Ability to successfully train the entire model pipeline in full BFloat16.", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
+{"page_content": "Kahan summation ensures precision. This can improve training throughput, especially on huge models, by reduced memory and increased computation speed.\n- Ability to change the variance state to BFloat16. This can reduce overall memory required for model training with additional speed improvements.\n\nFind more information [here](https://github.com/pytorch/torchdistx/pull/52).", "metadata": {"source": "https://pytorch.org/blog/new-library-updates-in-pytorch-1.13/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"PyTorch 1.11, TorchData, and functorch are now available\"\nauthor: Team PyTorch\nfeatured-img: \"assets/images/pytorch-logo.jpg\"\n---\n\nWe are excited to announce the release of PyTorch 1.11 ([release notes](https://github.com/pytorch/pytorch/releases/tag/v1.11.0)). This release is composed of over 3,300 commits since 1.10, made by 434 contributors. Along with 1.11, we are releasing beta versions of TorchData and functorch.\n\nSummary:\n\n* **TorchData** is a new library for common modular data loading primitives for easily constructing flexible and performant data pipelines. [View it on GitHub](https://github.com/pytorch/data).\n* **functorch**, a library that adds composable function transforms to PyTorch, is now available in beta. [View it on GitHub](https://github.com/pytorch/functorch).\n* Distributed Data Parallel (DDP) static graph optimizations available in stable.\n\n## Introducing TorchData", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "## Introducing TorchData\n\nWe are delighted to present the Beta release of [TorchData](https://github.com/pytorch/data). This is a library of common modular data loading primitives for easily constructing flexible and performant data pipelines. Based on community feedback, we have found that the existing DataLoader bundled too many features together and can be difficult to extend. Moreover, different use cases often have to rewrite the same data loading utilities over and over again. The goal here is to enable composable data loading through Iterable-style and Map-style building blocks called \u201c[DataPipes](https://github.com/pytorch/data#what-are-datapipes)\u201d that work well out of the box with the [PyTorch\u2019s DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "A `DataPipe` takes in some access function over Python data structures, `__iter__` for `IterDataPipe` and `__getitem__` for `MapDataPipe`, and returns a new access function with a slight transformation applied. You can chain multiple DataPipes together to form a data pipeline that performs all the necessary data transformation.\n\nWe have implemented over 50 DataPipes that provide different core functionalities, such as opening files, parsing texts, transforming samples, caching, shuffling, and batching. For users who are interested in connecting to cloud providers (such as Google Drive or AWS S3), the [fsspec](https://pytorch.org/data/0.3.0/torchdata.datapipes.iter.html#io-datapipes) and iopath DataPipes will allow you to do so. The documentation provides detailed explanations and usage examples of each [IterDataPipe](https://pytorch.org/data/0.3.0/torchdata.datapipes.iter.html) and [MapDataPipe](https://pytorch.org/data/0.3.0/torchdata.datapipes.map.html).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "In this release, some of the PyTorch domain libraries have migrated their datasets to use DataPipes. In TorchText, the [popular datasets provided by the library](https://github.com/pytorch/text/tree/release/0.12/torchtext/datasets) are implemented using DataPipes and a [section of its SST-2 binary text classification tutorial](https://pytorch.org/text/0.12.0/tutorials/sst2_classification_non_distributed.html#dataset) demonstrates how you can use DataPipes to preprocess data for your model. There also are other prototype implementations of datasets with DataPipes in [TorchVision (available in nightly releases)](https://github.com/pytorch/vision/tree/main/torchvision/prototype/datasets/_builtin) and in [TorchRec](https://pytorch.org/torchrec/torchrec.datasets.html). You can find more [specific examples here](https://pytorch.org/data/0.3.0/examples.html).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "The [documentation for TorchData](https://pytorch.org/data) is now live. It contains a tutorial that covers [how to use DataPipes](https://pytorch.org/data/0.3.0/tutorial.html#using-datapipes), [use them with DataLoader](https://pytorch.org/data/0.3.0/tutorial.html#working-with-dataloader), and [implement custom ones](https://pytorch.org/data/0.3.0/tutorial.html#implementing-a-custom-datapipe). FAQs and future plans related to DataLoader are described in [our project\u2019s README file](https://github.com/pytorch/data#readme).\n\n## Introducing functorch\n\nWe\u2019re excited to announce the first beta release of [functorch](https://github.com/pytorch/functorch). Heavily inspired by [Google JAX](https://github.com/google/jax), functorch is a library that adds composable function transforms to PyTorch. It aims to provide composable vmap (vectorization) and autodiff transforms that work with PyTorch modules and PyTorch autograd with good eager-mode performance.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "Composable function transforms can help with a number of use cases that are tricky to do in PyTorch today:\n\n* computing per-sample-gradients (or other per-sample quantities)\n* running ensembles of models on a single machine\n* efficiently batching together tasks in the inner-loop of MAML\n* efficiently computing Jacobians and Hessians as well as batched ones\n\nComposing vmap (vectorization), vjp (reverse-mode AD), and jvp (forward-mode AD) transforms allows us to effortlessly express the above without designing a separate library for each.\n\nFor more details, please see our [documentation](https://pytorch.org/functorch/), [tutorials](https://pytorch.org/functorch), and [installation instructions](https://pytorch.org/functorch/stable/install.html).\n\n## Distributed Training\n\n### (Stable) DDP static graph", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
-{"page_content": "### (Stable) DDP static graph\n\nDDP static graph assumes that your model employs the same set of used/unused parameters in every iteration, so that it can deterministically know states like which hooks will fire, how many times the hooks will fire and gradients computation ready order after the first iteration. Static graph caches these states in the first iteration, and thus it could support features that DDP can not support in previous releases, e.g., support multiple activation checkpoints on the same parameters regardless of whether there are unused parameters or not. The static graph feature also applies performance optimizations when there are unused parameters, e.g., it avoids traversing graphs to search unused parameters every iteration, and enables dynamic bucketing order. These optimizations in the DDP static graph brought 10% QPS gain for some recommendation models.\n\nTo enable static graph, just simply set static_graph=True in the DDP API like this:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
+{"page_content": "### (Stable) DDP static graph\n\nDDP static graph assumes that your model employs the same set of used/unused parameters in every iteration, so that it can deterministically know states like which hooks will fire, how many times the hooks will fire and gradients computation ready order after the first iteration. Static graph caches these states in the first iteration, and thus it could support features that DDP can not support in previous releases, e.g., support multiple activation checkpoints on the same parameters regardless of whether there are unused parameters or not. The static graph feature also applies performance optimizations when there are unused parameters, e.g., it avoids traversing graphs to search unused parameters every iteration, and enables dynamic bucketing order. These optimizations in the DDP static graph brought 10% QPS gain for some recommendation models.\n\nTo enable static graph, just simply set static_graph=True in the DDP API like this:\n\n```", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "```\nddp_model = DistributedDataParallel(model, static_graph=True)\n```\n\nFor more details, please see our [documentation](https://pytorch.org/docs/master/generated/torch.nn.parallel.DistributedDataParallel.html) and [tutorials](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html).\n\nThanks for reading, If you\u2019re interested in these updates and want to join the PyTorch community, we encourage you to join the [discussion forums](https://discuss.pytorch.org/) and [open GitHub issues](https://github.com/pytorch/pytorch/issues). To get the latest news from PyTorch, follow us on [Twitter](https://twitter.com/PyTorch), [Medium](https://medium.com/pytorch), [YouTube](https://www.youtube.com/pytorch), and [LinkedIn](https://www.linkedin.com/company/pytorch).\n\nCheers!\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.11-released/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Torchserve Performance Tuning, Animated Drawings Case-Study\"\nauthor: Hamid Shojanazeri, Geeta Chauhan, Mark Saroufim, Jesse Smith\nfeatured-img: \"assets/images/sketch_animator.png\"\n---", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "In this post we discuss performance tuning of Torchserve for serving your models in production. One of the biggest challenges in the life cycle of a ML project is deploying models in production. This requires a reliable serving solution along with solutions that address the MLOps needs. A robust serving solution needs to provide support for multi model serving, model versioning, metric logging, monitoring and scaling to serve the peak traffic. In this post, we will have an overview of Torchserve and how to tune its performance for production use-cases. We discuss the [Animated Drawings app](https://ai.facebook.com/blog/using-ai-to-bring-childrens-drawings-to-life/) from Meta that can turn your human figure sketches to animations and how it could serve the peak traffic with Torchserve. The Animated Drawing\u2019s workflow is below.\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "[https://ai.facebook.com/blog/using-ai-to-bring-childrens-drawings-to-life/](https://ai.facebook.com/blog/using-ai-to-bring-childrens-drawings-to-life/)\n\nMany AI systems and tools are designed to handle realistic images of humans, children's drawings add a level of complexity and unpredictability as they are often constructed in abstract, fanciful ways. These types of morphological and stylistic variations can confuse even state-of-the-art AI systems that excel at spotting objects in photorealistic images and drawings.\nMeta AI researchers are working to overcome this challenge so that AI systems will be better able to recognize drawings of human figures in the wildly varied ways that children create them. This great blog post provides more details about the Animated Drawings and the approach taken.\n\n## Torchserve\n\n\n
\n
Fig1. Overall flow of Torchserve performance tuning \n", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "Once you have trained your model, it needs to be integrated into a larger system to have a full-fledged application, we use the term \u201cmodel serving\u201d to refer to this integration. Basically model serving is making your trained model available to run inferences and subsequent use of the model. \n\nTorchserve is the Pytorch preferred solution for serving models in production. It is a performant and scalable tool that wraps your model in a HTTP or HTTPS API. It has a frontend implemented in Java that handles multiple tasks from assigning workers for serving models to handling the connection between client and server. Torchserve has a Python backend that is responsible for handling the inference service.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "---\n\nIn this post we discuss performance tuning of Torchserve for serving your models in production. One of the biggest challenges in the life cycle of a ML project is deploying models in production. This requires a reliable serving solution along with solutions that address the MLOps needs. A robust serving solution needs to provide support for multi model serving, model versioning, metric logging, monitoring and scaling to serve the peak traffic. In this post, we will have an overview of Torchserve and how to tune its performance for production use-cases. We discuss the [Animated Drawings app](https://ai.facebook.com/blog/using-ai-to-bring-childrens-drawings-to-life/) from Meta that can turn your human figure sketches to animations and how it could serve the peak traffic with Torchserve. The Animated Drawing\u2019s workflow is below.\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "\n\n[https://ai.facebook.com/blog/using-ai-to-bring-childrens-drawings-to-life/](https://ai.facebook.com/blog/using-ai-to-bring-childrens-drawings-to-life/)\n\nMany AI systems and tools are designed to handle realistic images of humans, children's drawings add a level of complexity and unpredictability as they are often constructed in abstract, fanciful ways. These types of morphological and stylistic variations can confuse even state-of-the-art AI systems that excel at spotting objects in photorealistic images and drawings.\nMeta AI researchers are working to overcome this challenge so that AI systems will be better able to recognize drawings of human figures in the wildly varied ways that children create them. This great blog post provides more details about the Animated Drawings and the approach taken.\n\n## Torchserve\n\n\n
\n
Fig1. Overall flow of Torchserve performance tuning \n", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "\n\nOnce you have trained your model, it needs to be integrated into a larger system to have a full-fledged application, we use the term \u201cmodel serving\u201d to refer to this integration. Basically model serving is making your trained model available to run inferences and subsequent use of the model. \n\nTorchserve is the Pytorch preferred solution for serving models in production. It is a performant and scalable tool that wraps your model in a HTTP or HTTPS API. It has a frontend implemented in Java that handles multiple tasks from assigning workers for serving models to handling the connection between client and server. Torchserve has a Python backend that is responsible for handling the inference service.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "Torchserve supports multi model serving and versioning for AB test, dynamic batching, logging and metrics. It exposes four APIs for [inference](https://github.com/pytorch/serve/blob/master/docs/inference_api.md), [explanations](https://github.com/pytorch/serve/blob/master/docs/inference_api.md#explanations-api), [management](https://github.com/pytorch/serve/blob/master/docs/management_api.md) and [metrics](https://github.com/pytorch/serve/blob/master/docs/metrics_api.md). \n\n[Inference](https://github.com/pytorch/serve/blob/master/docs/inference_api.md) API is listening on port 8080 and accessible through localhost by default, this can be configured in [Torchserve configuration](https://github.com/pytorch/serve/blob/master/docs/configuration.md) and enable getting predictions from the model.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "[Explanation](https://github.com/pytorch/serve/blob/master/docs/inference_api.md#explanations-api) API uses Captum under the hood to provide explanations of the model that is being served and listens to the port 8080 as well.\n\n[Management](https://github.com/pytorch/serve/blob/master/docs/management_api.md#management-api) API allows to register or unregister and describe a model. It also enables users to scale up or down the number of workers that serve the model. \n\n[Metric](https://github.com/pytorch/serve/blob/master/docs/metrics_api.md) API by default listens to port 8082 and enables us to monitor the model that is being served.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "Torchserve let you scale your model serving and handle the peak traffic by supporting [batch inference](https://github.com/pytorch/serve/blob/master/docs/batch_inference_with_ts.md) and multiple workers that serve your model. Scaling can be done through [management](https://github.com/pytorch/serve/blob/master/docs/management_api.md) API and settings through a [configuration](https://github.com/pytorch/serve/blob/master/docs/configuration.md) file. Also, metric API helps you to monitor your model serving through default and customizable metrics.\n\nOther advanced settings such as the length of the queue for the received requests, maximum wait time for a batch of inputs and many other properties are configurable through a[ config file](https://github.com/pytorch/serve/blob/master/docs/configuration.md) that can be passed to Torchserve when it is started.\n\n\n**Steps to serve your model with Torchserve**", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "1. [Install Torchserve, model archiver](https://github.com/pytorch/serve/blob/master/docs/getting_started.md#install-torchserve-and-torch-model-archiver) and its requirements.\n2. Choose a default handler that fits your task (e.g image classification, etc) or author a [custom handler](https://github.com/pytorch/serve/blob/master/docs/custom_service.md#custom-handlers).\n3. [Package your model](https://github.com/pytorch/serve/tree/master/examples/Huggingface_Transformers#create-model-archive-eager-mode) artifacts (trained model checkpoint and all other necessary files for loading and running your model) and the handler into a \u201c.mar\u201d file using [Torcharchive](https://github.com/pytorch/serve/blob/master/model-archiver/README.md) and place it in the model store.\n4. [Start serving your model](https://github.com/pytorch/serve/blob/master/docs/getting_started.md).\n5. [Run inference](https://github.com/pytorch/serve/blob/master/docs/getting_started.md#get-predictions-from-a-model).\nWe will discuss model handlers and metrics in more detail here.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "## Model handlers\n\nTorchserve uses a handler in the backend to load the models, preprocess the received data, run inference and post-process the response. Handler in torchserve is a **python script** that all the model initialization, preprocessing, inference and post processing logic goes into.\n\nTorchserve provides an out of the box handler for a number of applications like image classification, segmentation, object detection and text classification. It also supports custom handlers, in case your use case is not supported in default handlers. \n\nIt provides a great flexibility in custom handlers, this potentially make Torchserve as **multi-framework** serving tool. Custom handlers let you define your custom logic to initialize a model that can be used also to load models from other frameworks such as ONNX.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "Torchserve **handler** is made of four main **functions**, **initialize**, **preprocess**, **inference** and **postprocess** that each return a list. The code snippet below shows an example of a custom handler.**Custom handlers inherit** from **BaseHandler** in Torchserve and can **overwrite** any of the **main** **functions**. Here is an example of the handler used for loading the [Detectron2](https://github.com/facebookresearch/detectron2) model for figure detection, this model has been exported to Torchscript and uses model.half() to run the inference with FP16, details are explained in another [section]() in this post.\n\n```python\n\nclass MyModelHandler(BaseHandler):\n def initialize(self, context):\n self.manifest = ctx.manifest\n properties = ctx.system_properties\n model_dir = properties.get(\"model_dir\")\n serialized_file = self.manifest[\"model\"][\"serializedFile\"]\n model_pt_path = os.path.join(model_dir, serialized_file)", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "self.device = torch.device(\n \"cuda:\" + str(properties.get(\"gpu_id\"))\n if torch.cuda.is_available() and properties.get(\"gpu_id\") is not None\n else \"cpu\"\n )\n self.model = torch.jit.load(model_pt_path, map_location=self.device)\n\n self.model = self.model.half()\n\n def preprocess(self, data):\n\n inputs = []\n for request in batch:\n\n request_body = request.get(\"body\")\n\n input_ = io.BytesIO(request_body)\n image = cv2.imdecode(np.fromstring(input_.read(), np.uint8), 1)\n input = torch.Tensor(image).permute(2, 0, 1)\n input = input.to(self.device)\n input = input.half()\n inputs.append({\"image\": input})\n\n return inputs\n\n def inference(self,inputs):\n predictions = self.model(**inputs)\n return predictions", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "def postprocess(self, output):\n responses = []\n for inference_output in inference_outputs:\n responses_json = {\n 'classes': inference_output['pred_classes'].tolist(),\n 'scores': inference_output['scores'].tolist(),\n \"boxes\": inference_output['pred_boxes'].tolist()\n }\n responses.append(json.dumps(responses_json))\n\n return responses\n```\n\n## Metrics\n\nAn essential component in serving models in production is the ability to monitor them. **Torchserve** **collects** **system level** [metrics](https://github.com/pytorch/serve/blob/master/docs/metrics.md) regularly and **allows** adding **custom metrics** as well.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "**Steps to serve your model with Torchserve**\n\n1. [Install Torchserve, model archiver](https://github.com/pytorch/serve/blob/master/docs/getting_started.md#install-torchserve-and-torch-model-archiver) and its requirements.\n2. Choose a default handler that fits your task (e.g image classification, etc) or author a [custom handler](https://github.com/pytorch/serve/blob/master/docs/custom_service.md#custom-handlers).\n3. [Package your model](https://github.com/pytorch/serve/tree/master/examples/Huggingface_Transformers#create-model-archive-eager-mode) artifacts (trained model checkpoint and all other necessary files for loading and running your model) and the handler into a \u201c.mar\u201d file using [Torcharchive](https://github.com/pytorch/serve/blob/master/model-archiver/README.md) and place it in the model store.\n4. [Start serving your model](https://github.com/pytorch/serve/blob/master/docs/getting_started.md).", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "5. [Run inference](https://github.com/pytorch/serve/blob/master/docs/getting_started.md#get-predictions-from-a-model).\nWe will discuss model handlers and metrics in more detail here.\n\n## Model handlers\n\nTorchserve uses a handler in the backend to load the models, preprocess the received data, run inference and post-process the response. Handler in torchserve is a **python script** that all the model initialization, preprocessing, inference and post processing logic goes into.\n\nTorchserve provides an out of the box handler for a number of applications like image classification, segmentation, object detection and text classification. It also supports custom handlers, in case your use case is not supported in default handlers. \n\nIt provides a great flexibility in custom handlers, this potentially make Torchserve as **multi-framework** serving tool. Custom handlers let you define your custom logic to initialize a model that can be used also to load models from other frameworks such as ONNX.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "Torchserve **handler** is made of four main **functions**, **initialize**, **preprocess**, **inference** and **postprocess** that each return a list. The code snippet below shows an example of a custom handler.**Custom handlers inherit** from **BaseHandler** in Torchserve and can **overwrite** any of the **main** **functions**. Here is an example of the handler used for loading the [Detectron2](https://github.com/facebookresearch/detectron2) model for figure detection, this model has been exported to Torchscript and uses model.half() to run the inference with FP16, details are explained in another [section]() in this post.\n\n```python\n\nclass MyModelHandler(BaseHandler):\n def initialize(self, context):\n self.manifest = ctx.manifest\n properties = ctx.system_properties\n model_dir = properties.get(\"model_dir\")\n serialized_file = self.manifest[\"model\"][\"serializedFile\"]\n model_pt_path = os.path.join(model_dir, serialized_file)\n\n self.device = torch.device(", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "self.device = torch.device(\n \"cuda:\" + str(properties.get(\"gpu_id\"))\n if torch.cuda.is_available() and properties.get(\"gpu_id\") is not None\n else \"cpu\"\n )\n self.model = torch.jit.load(model_pt_path, map_location=self.device)\n\n self.model = self.model.half()\n\n def preprocess(self, data):\n\n inputs = []\n for request in batch:\n\n request_body = request.get(\"body\")\n\n input_ = io.BytesIO(request_body)\n image = cv2.imdecode(np.fromstring(input_.read(), np.uint8), 1)\n input = torch.Tensor(image).permute(2, 0, 1)\n input = input.to(self.device)\n input = input.half()\n inputs.append({\"image\": input})\n\n return inputs\n\n def inference(self,inputs):\n predictions = self.model(**inputs)\n return predictions\n\n def postprocess(self, output):\n responses = []\n for inference_output in inference_outputs:\n responses_json = {", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "responses_json = {\n 'classes': inference_output['pred_classes'].tolist(),\n 'scores': inference_output['scores'].tolist(),\n \"boxes\": inference_output['pred_boxes'].tolist()\n }\n responses.append(json.dumps(responses_json))\n\n return responses\n```\n\n## Metrics\n\nAn essential component in serving models in production is the ability to monitor them. **Torchserve** **collects** **system level** [metrics](https://github.com/pytorch/serve/blob/master/docs/metrics.md) regularly and **allows** adding **custom metrics** as well.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "**[System level metrics](https://github.com/pytorch/serve/blob/master/docs/metrics.md#system-metrics)** consist of CPU utilization, available and used disk space and memory on the host machine along with number of requests with different response codes (e.g 200-300, 400-500 and above 500). **Custom metrics** can be **added** to the metrics as explained [here](https://github.com/pytorch/serve/blob/master/docs/metrics.md#custom-metrics-api). TorchServe logs these two sets of metrics to different log files. Metrics are collected by default at:\n\n* System metrics - log_directory/ts_metrics.log\n* Custom metrics - log directory/model_metrics.log", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "As mentioned before, Torchserve also exposes [metric API](https://github.com/pytorch/serve/blob/master/docs/metrics_api.md), that by default listens to port 8082 and enables users to query and monitor the collected metrics. The default metrics endpoint returns Prometheus formatted metrics. You can query metrics using curl requests or point a [Prometheus Server](https://github.com/pytorch/serve/blob/master/docs/metrics_api.md#prometheus-server) to the endpoint and use [Grafana](https://github.com/pytorch/serve/blob/master/docs/metrics_api.md#grafana) for dashboards. \n\nWhile serving a model you can query metrics using curl request as follows:\n\n```\ncurl http://127.0.0.1:8082/metrics\n```", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "```\ncurl http://127.0.0.1:8082/metrics\n```\n\nIn case you are looking into exporting the logged metrics, please refer to this [example](https://github.com/google/mtail) that uses mtail to export metrics to Prometheus. Tracking these metrics in a dashboard allows you to monitor performance regressions that may have been sporadic or hard to spot during an offline benchmark run.\n\n## What to consider for tuning performance of a model in production\n\nThe workflow suggested in Fig 1, is the general idea on how to approach model deployment in production with Torchserve.\n\nIn many cases serving models in production is **optimized** **based** on **throughput** or **latency** service level agreement (**SLA)s**. Usually **real-time** **applications** are more concerned about **latency** whereas **off-line applications** may care more about higher **throughput**.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "There are a number of main factors contributing to the performance of a serving model in production. In particular, we are focusing on serving Pytorch models with Torchserve here, however most of these factors generalize to all models from other frameworks as well.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "* **Model optimizations**: this is a pre-step for deploying models into production. This is a very broad discussion that we will get into in a series of future blogs. This includes techniques like quantization, pruning to decrease the size of the model, using Intermediate representations (IR graphs) such as Torchscript in Pytorch, fusing kernels and many others. Currently [torchprep](https://github.com/msaroufim/torchprep) provides many of these techniques as a CLI tool. \n* **Batch inference:** it refers to feeding multiple inputs into a model, while it is essential during training, it can be very helpful to manage the cost at inference time as well. Hardware accelerators are optimized for parallelism and batching helps to saturate the compute capacity and often leads to higher throughput. The main difference in inference is you can\u2019t wait too long to get a batch filled from clients, something we call dynamic batching\n* **Number of Workers :** Torchserve uses workers to serve models. Torchserve workers are Python processes that hold a copy of the model weights for running inference. Too few workers means you\u2019re not benefitting from enough parallelism but too many can cause worker contention and degrade end to end performance.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "There are a number of main factors contributing to the performance of a serving model in production. In particular, we are focusing on serving Pytorch models with Torchserve here, however most of these factors generalize to all models from other frameworks as well.\n\n* **Model optimizations**: this is a pre-step for deploying models into production. This is a very broad discussion that we will get into in a series of future blogs. This includes techniques like quantization, pruning to decrease the size of the model, using Intermediate representations (IR graphs) such as Torchscript in Pytorch, fusing kernels and many others. Currently [torchprep](https://github.com/msaroufim/torchprep) provides many of these techniques as a CLI tool.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "* **Batch inference:** it refers to feeding multiple inputs into a model, while it is essential during training, it can be very helpful to manage the cost at inference time as well. Hardware accelerators are optimized for parallelism and batching helps to saturate the compute capacity and often leads to higher throughput. The main difference in inference is you can\u2019t wait too long to get a batch filled from clients, something we call dynamic batching\n* **Number of Workers :** Torchserve uses workers to serve models. Torchserve workers are Python processes that hold a copy of the model weights for running inference. Too few workers means you\u2019re not benefitting from enough parallelism but too many can cause worker contention and degrade end to end performance.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "- **Hardware :** choosing the appropriate hardware based on the model, application and latency, throughput budget. This could be one of the **supported** hardwares in Torchserve, **CPU, GPU, AWS Inferentia**. Some hardware configurations are intended for best in class performance and others are better suited for cost effective inference. From our experiments we\u2019ve found that GPUs shine best at larger batch sizes whereas the right CPUs and AWS Inferentia can be far more cost effective for lower batch sizes and low latency.\n\n## Best Practices for Performance tuning on Torchserve\n\nTo get the best performance out of your model while serving it with Torchserve, we are sharing some of the best practices here. Torchserve provides a [benchmark](https://github.com/pytorch/serve/tree/c87bfec8916d340de5de5810b14a016049b0e395/benchmarks#benchmarking-with-apache-bench) suite that provides helpful insight to make informed decisions on different choices as detailed below.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "* **Optimize your model** as the first step, Pytorch model optimization [tutorials](https://pytorch.org/tutorials/). **Model optimization** choices are also closely **tied** to the **hardware** of choice. We will discuss it in more detail in another blog post.\n* **Deciding** the **hardware** for model deployment can be closely related to the latency and throughput budget and cost per inference. Depending on the size of model and application it can vary, for some models like computer vision models it has been historically not affordable to run in production on CPU. However, by having optimizations such [IPEX](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/examples/intel_extension_for_pytorch/README.md) as recently added to Torchserve this has been much more affordable and cost beneficial and you can learn more in this investigative [case study](https://pytorch.org/tutorials/intermediate/torchserve_with_ipex.html) \n* **Workers** in Torchserve are Python processes that provide parallelism, setting the number of workers should be done carefully. By default Torchserve launch number of workers equal to VCPUs or available GPUs on the host, this can add a considerable amount of time to the Torchserve start.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "Torchserve exposes a [config property](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/docs/configuration.md#config-model) to set the number of workers. To provide an **efficient parallelism** through **multiple workers** and avoiding them to compete over resources, as a baseline we **recommend** following setting on CPU and GPU:\n\n\n **CPU** : In the handler, `torch.set_num_threads(1) `then set the number of workers to `num physical cores / 2. `But the the best threading configurations can be achieved by leveraging the Intel CPU launcher script.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "* **Optimize your model** as the first step, Pytorch model optimization [tutorials](https://pytorch.org/tutorials/). **Model optimization** choices are also closely **tied** to the **hardware** of choice. We will discuss it in more detail in another blog post.\n* **Deciding** the **hardware** for model deployment can be closely related to the latency and throughput budget and cost per inference. Depending on the size of model and application it can vary, for some models like computer vision models it has been historically not affordable to run in production on CPU. However, by having optimizations such [IPEX](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/examples/intel_extension_for_pytorch/README.md) as recently added to Torchserve this has been much more affordable and cost beneficial and you can learn more in this investigative [case study](https://pytorch.org/tutorials/intermediate/torchserve_with_ipex.html)", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "* **Workers** in Torchserve are Python processes that provide parallelism, setting the number of workers should be done carefully. By default Torchserve launch number of workers equal to VCPUs or available GPUs on the host, this can add a considerable amount of time to the Torchserve start. \n\n Torchserve exposes a [config property](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/docs/configuration.md#config-model) to set the number of workers. To provide an **efficient parallelism** through **multiple workers** and avoiding them to compete over resources, as a baseline we **recommend** following setting on CPU and GPU:\n\n\n **CPU** : In the handler, `torch.set_num_threads(1) `then set the number of workers to `num physical cores / 2. `But the the best threading configurations can be achieved by leveraging the Intel CPU launcher script.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "**GPU**: number of available GPUs can be set through[ number_gpus](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/docs/configuration.md#limit-gpu-usage) in config.properties. Torchserve uses round robin to assign workers to GPUs. We recommend setting the number of workers as follows. `Number of worker = (Number of available GPUs) / (Number of Unique Models). `Note that GPUs that are pre-Ampere do not provide any resource isolation with Multi Instance GPUs.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "* **Batch size** can directly affect the latency and the throughput. To better utilize the compute resources batch size needs to be increased. However, there is a tradeoff between latency and throughput. **Larger batch sizes** can **increase** the **throughput but results in a higher latency** as well. Batch size can be set in Torchserve in two ways, either through[ model config](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/docs/configuration.md#config-model) in config.properties or while registering the model using [Management API](https://github.com/pytorch/serve/blob/c87bfec8916d340de5de5810b14a016049b0e395/docs/management_api.md#scale-workers). \n\nIn the next section, we are going to use Torchserve benchmark suite to decide the best combination of model optimization, hardware, workers, and batch size. \n\n## Animated Drawings Performance Tuning", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "## Animated Drawings Performance Tuning \n\nTo use the Torchserve benchmark suite, first we need to have an archived file, \u201c.mar\u201d file as discussed above, that contains the model, handler and all other artifacts to load and run inference. Animated Drawings uses Detectron2\u2019s implementation of Mask-RCNN for an object detection model. \n\n### How to run benchmark suite \n\nThe [Automated benchmark suite](https://github.com/pytorch/serve/tree/master/benchmarks#auto-benchmarking-with-apache-bench) in Torchserve let you benchmark multiple models with different setting including batch size and number of worker and finally generate a report for you. To get started:\n\n```\ngit clone https://github.com/pytorch/serve.git\n\ncd serve/benchmarks\n\npip install -r requirements-ab.txt\n\napt-get install apache2-utils\n```\n\nModel level settings can be configured in a yaml file similar to \n\n```yaml", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "```yaml\n\nModel_name:\n eager_mode:\n benchmark_engine: \"ab\"\n url: \"Path to .mar file\"\n workers:\n - 1\n - 4\n batch_delay: 100\n batch_size:\n - 1\n - 2\n - 4\n - 8\n requests: 10000\n concurrency: 10\n input: \"Path to model input\"\n backend_profiling: False\n exec_env: \"local\"\n processors:\n - \"cpu\"\n - \"gpus\": \"all\"\n\n```\n\nThis yaml file will be referenced in the [benchmark_config_template](https://github.com/pytorch/serve/blob/master/benchmarks/benchmark_config_template.yaml#L12).yaml file that includes other settings for generating reports, this can optionally work with AWS cloud watch for logs as well.\n\n```\npython benchmarks/auto_benchmark.py --input benchmark_config_template.yaml\n```", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "Running the **benchmarks**, results will be written in \u201ccsv\u201d file that can be found in \u201c_ /tmp/benchmark/ab_report.csv_\u201d and full report \u201c/tmp/ts_benchmark/report.md\". It will include items such as Torchserve average latency, model P99 latency, throughput, number of concurrency, number of requests, handler time, and some other metrics. Here we focus on some of the important ones that we track to tune the performance which are, **concurrency**, **model P99** latency, **throughput**. We look at these numbers specifically in **combination** with **batch size**, the used **device, number of workers** and if any **model optimization** has been done.\n\n\nThe **latency SLA** for this model has been set to **100 ms,** this is real-time application and as we discussed earlier, latency is more of a concern and **throughput** ideally should be as high as possible while it does **not violate** the **latency SLA.**", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "Through searching the space, over different batch sizes (1-32), number of workers (1-16) and devices (CPU,GPU), we have run a set of experiments that summarized the best ones in the table below.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "\n \n Device \n | \n Concurrency \n | \n # Requests\n | \n #workers\n | \n Batch size\n | \n Payload/image\n | \n Optimization \n | \n Throughput \n | \n Latency P99\n | \n
\n \n CPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 3.45\n | \n 305.3 ms\n | \n
\n \n CPU\n | \n 1\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 3.45\n | \n 291.8 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 41.05\n | \n 25.48 ms\n | \n
\n \n GPU\n | \n 1\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 42.21\n | \n 23.6 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 4\n | \n small\n | \n N/A\n | \n 54.78\n | \n 73.62 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 4\n | \n small\n | \n model.half()\n | \n 78.62\n | \n 50.69 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 8\n | \n small\n | \n model.half()\n | \n 85.29\n | \n 94.4 ms\n | \n
\n
", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "The latency of this model on CPU with all of the tried settings in terms of batch size, concurrency and number of workers did not meet the SLA, in fact ~13x higher.\n\n**Moving** the model serving **to GPU**, immediately could **improve** the **latency** ~**13x **from 305 ms down to 23.6 ms. \n\nOne of the **simplest** **optimizations** that we could do for the model was lowering its precision to **fp16**, it is one liner (**model.half()**) and could reduce the **model P99 latency **by **32%** and increase the throughput by almost the same amount.\n\nThere could be other optimization done by Torchscripting the model and using [optimize_for_inference](https://github.com/pytorch/pytorch/blob/master/torch/jit/_freeze.py#L168) or other tricks including onnx or tensorrt runtime optimizations which leverage aggressive fusions are out of the scope of this post. We will discuss model optimizations in a separate post.\n\nWe found both on CPU and GPU , setting **number of workers=1 **worked the best in this case.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
-{"page_content": "* Moving the model to GPU, using **number of workers = 1**, and **batch size = 1** increased the **Throughput ~12x compared** to **CPU and latency ~13x.**\n* Moving the model to GPU, using **model.half()**, **number of workers = 1**, and **batch size = 8** yielded **best** results in terms of **Throughput** and tolerable latency. **Throughput** increased **~25x compared** to **CPU with latency still meeting the SLA (94.4ms).**\n \n_Note: if you are running the benchmark suite, make sure you are setting a proper `batch_delay` and set the concurrency of the request to a number proportional to your batch size. Concurrency here means the number of concurrent requests being sent to the server._\n\n## Conclusion", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "## Animated Drawings Performance Tuning \n\nTo use the Torchserve benchmark suite, first we need to have an archived file, \u201c.mar\u201d file as discussed above, that contains the model, handler and all other artifacts to load and run inference. Animated Drawings uses Detectron2\u2019s implementation of Mask-RCNN for an object detection model. \n\n### How to run benchmark suite \n\nThe [Automated benchmark suite](https://github.com/pytorch/serve/tree/master/benchmarks#auto-benchmarking-with-apache-bench) in Torchserve let you benchmark multiple models with different setting including batch size and number of worker and finally generate a report for you. To get started:\n\n```\ngit clone https://github.com/pytorch/serve.git\n\ncd serve/benchmarks\n\npip install -r requirements-ab.txt\n\napt-get install apache2-utils\n```\n\nModel level settings can be configured in a yaml file similar to \n\n```yaml\n\nModel_name:\n eager_mode:\n benchmark_engine: \"ab\"\n url: \"Path to .mar file\"\n workers:\n - 1\n - 4", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "workers:\n - 1\n - 4\n batch_delay: 100\n batch_size:\n - 1\n - 2\n - 4\n - 8\n requests: 10000\n concurrency: 10\n input: \"Path to model input\"\n backend_profiling: False\n exec_env: \"local\"\n processors:\n - \"cpu\"\n - \"gpus\": \"all\"\n\n```\n\nThis yaml file will be referenced in the [benchmark_config_template](https://github.com/pytorch/serve/blob/master/benchmarks/benchmark_config_template.yaml#L12).yaml file that includes other settings for generating reports, this can optionally work with AWS cloud watch for logs as well.\n\n```\npython benchmarks/auto_benchmark.py --input benchmark_config_template.yaml\n```", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nRunning the **benchmarks**, results will be written in \u201ccsv\u201d file that can be found in \u201c_ /tmp/benchmark/ab_report.csv_\u201d and full report \u201c/tmp/ts_benchmark/report.md\". It will include items such as Torchserve average latency, model P99 latency, throughput, number of concurrency, number of requests, handler time, and some other metrics. Here we focus on some of the important ones that we track to tune the performance which are, **concurrency**, **model P99** latency, **throughput**. We look at these numbers specifically in **combination** with **batch size**, the used **device, number of workers** and if any **model optimization** has been done.\n\n\nThe **latency SLA** for this model has been set to **100 ms,** this is real-time application and as we discussed earlier, latency is more of a concern and **throughput** ideally should be as high as possible while it does **not violate** the **latency SLA.**", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "Through searching the space, over different batch sizes (1-32), number of workers (1-16) and devices (CPU,GPU), we have run a set of experiments that summarized the best ones in the table below.\n\n\n \n Device \n | \n Concurrency \n | \n # Requests\n | \n #workers\n | \n Batch size\n | \n Payload/image\n | \n Optimization \n | \n Throughput \n | \n Latency P99\n | \n
\n \n CPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 3.45\n | \n 305.3 ms\n | \n
\n \n CPU\n | \n 1\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 3.45\n | \n 291.8 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 41.05", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": " | \n N/A\n | \n 41.05\n | \n 25.48 ms\n | \n
\n \n GPU\n | \n 1\n | \n 1000\n | \n 1\n | \n 1\n | \n small\n | \n N/A\n | \n 42.21\n | \n 23.6 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 4\n | \n small\n | \n N/A\n | \n 54.78\n | \n 73.62 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 4\n | \n small\n | \n model.half()\n | \n 78.62\n | \n 50.69 ms\n | \n
\n \n GPU\n | \n 10\n | \n 1000\n | \n 1\n | \n 8\n | \n small\n | \n model.half()\n | \n 85.29\n | \n 94.4 ms\n | \n
\n
", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "\n 94.4 ms\n | \n \n\n\nThe latency of this model on CPU with all of the tried settings in terms of batch size, concurrency and number of workers did not meet the SLA, in fact ~13x higher.\n\n**Moving** the model serving **to GPU**, immediately could **improve** the **latency** ~**13x **from 305 ms down to 23.6 ms. \n\nOne of the **simplest** **optimizations** that we could do for the model was lowering its precision to **fp16**, it is one liner (**model.half()**) and could reduce the **model P99 latency **by **32%** and increase the throughput by almost the same amount.\n\nThere could be other optimization done by Torchscripting the model and using [optimize_for_inference](https://github.com/pytorch/pytorch/blob/master/torch/jit/_freeze.py#L168) or other tricks including onnx or tensorrt runtime optimizations which leverage aggressive fusions are out of the scope of this post. We will discuss model optimizations in a separate post.", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
+{"page_content": "We found both on CPU and GPU , setting **number of workers=1 **worked the best in this case. \n\n* Moving the model to GPU, using **number of workers = 1**, and **batch size = 1** increased the **Throughput ~12x compared** to **CPU and latency ~13x.**\n* Moving the model to GPU, using **model.half()**, **number of workers = 1**, and **batch size = 8** yielded **best** results in terms of **Throughput** and tolerable latency. **Throughput** increased **~25x compared** to **CPU with latency still meeting the SLA (94.4ms).**\n \n_Note: if you are running the benchmark suite, make sure you are setting a proper `batch_delay` and set the concurrency of the request to a number proportional to your batch size. Concurrency here means the number of concurrent requests being sent to the server._\n\n## Conclusion", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "## Conclusion\n\nIn this post, we have discussed the considerations and knobs that Torchserve expose to tune the performance in production. We have discussed the Torchserve benchmark suite as a means to tune the performance and get insights on possible choices for model optimizations, hardware choice and cost in general. We used Animated Drawings app which uses Detectron2\u2019s Mask-RCNN model as a case-study to showcase the performance tuning with benchmark suite. \n\nFor more details on Performance tuning in Torchserve please refer to our documentation [here](https://github.com/pytorch/serve/blob/master/docs/performance_guide.md).\nAlso feel free to open a ticket on [Torchserve repo](https://github.com/pytorch/serve/issues) for any further questions and feedback. \n\n### Acknowledgement", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "### Acknowledgement\n\nWe would like to thank Somya Jain (Meta), Christopher Gustave (Meta) for their great support and guidance throughout many steps of this blog and providing insights to Sketch Animator workflow. Also, special thanks to[ Li Ning](https://www.linkedin.com/in/li-ning-7274604/) from AWS for the great efforts to make performance tuning much easier on Torchserve with automated benchmark suite.\n\n\n", "metadata": {"source": "https://pytorch.org/blog/torchserve-performance-tuning/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Scaling Vision Model Training Platforms with PyTorch\"\nauthor: Vaibhav Aggarwal, Mannat Singh, Anjali Sridhar, Yanghao Li, Shoubhik Debnath, Ronghang Hu, Will Feng, Xinlei Chen, Tingting Markstrum, Diana Liskovich, Anupam Bhatnagar, Chay Ryali, Haoqi Fan, Tete Xiao, Min Xu, Rahul Iyer, Christoph Feichtenhofer, Ross Girshick, Piotr Dollar, Aaron Adcock, Wan-Yen Lo, CK Luk\nfeatured-img: \"/assets/images/scaling-vision-figure_1-solutions-to-the-challenges.png\"\n---\n\n*TL;DR: We demonstrate the use of PyTorch with FairScale\u2019s FullyShardedDataParallel (FSDP) API in writing large vision transformer models. We discuss our techniques for scaling and optimizing these models on a GPU cluster. The goal of this platform scaling effort is to enable research at scale. This blog does not discuss model accuracy, new model architectures, or new training recipes.*\n\n## 1. Introduction", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
@@ -591,23 +593,22 @@
{"page_content": "We apply various forms of data and model parallelism to enable fitting very large models in GPU memory.\n\nWe use FairScale\u2019s *FullyShardedDataParallel (FSDP)* API [4], based on PyTorch, to shard parameters, gradients, and optimizer state across multiple GPUs, thereby reducing the memory footprint per GPU. This process consists of the following three steps:\n\n- Step 1: We wrapped the entire model in a single FSDP instance. This shards the model parameters at the end of a forward pass and gathers parameters at the beginning of a forward pass. This enabled us to scale ~3x from 1.5B to 4.5B parameters. \n\n- Step 2: We experimented with wrapping individual model layers in separate FSDP instances. This nested wrapping further reduced the memory footprint by sharding and gathering parameters of individual model layers instead of an entire model. The peak memory is then determined by an individually wrapped transformer block in GPU memory in this mode instead of the entire model.", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "- Step 3: We used *activation-checkpoint* to reduce the memory consumption by activations. It saves the input tensors and discards the intermediate activation tensors during the forward pass. These are recomputed during the backward pass.\n\nIn addition, we experimented with model-parallelism techniques such as pipeline parallelism [5], which allow us to scale to more GPUs without increasing the batch size.\n\n### 3.2 Addressing optimization challenges with advanced AMP and kernel fusion\n\n#### Advanced AMP\n\nAutomatic Mixed Precision (AMP) [6] training refers to training models using a lower precision of bits than FP32 or the default but still maintaining accuracy. We experimented with three levels of AMP as described below:\n\n- AMP O1: This refers to training in mixed precision where weights are in FP32 and some operations are in FP16. With AMP O1, the ops that might impact accuracy remain in FP32 and are not autocasted to FP16.", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "- AMP O2: This refers to training in mixed precision but with more weights and ops in FP16 than in O1. Weights do not implicitly remain in FP32 and are cast to FP16. A copy of the master weights is maintained in the FP32 precision that is used by the optimizer. If we want the normalization layer weights in FP32 then we need to explicitly use layer wrapping to ensure that.\n\n- Full FP16: This refers to training in full FP16 where weights and operations are in FP16. FP16 is challenging to enable for training due to convergence issues.\n\nWe found that AMP O2 with LayerNorm wrapping in FP32 leads to the best performance without sacrificing accuracy.\n\n#### Kernel Fusion\n\n- To reduce GPU kernel launch overhead and increase GPU work granularity, we experimented with kernel fusions, including fused dropout and fused layer-norm, using the [xformers library](https://github.com/facebookresearch/xformers) [7].\n\n### 3.3 Addressing stability challenges by studying ops numerical stability and training recipes", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "#### BFloat16 in general but with LayerNorm in FP32\n\nThe [bfloat16](https://cloud.google.com/tpu/docs/bfloat16) (BF16) [8] floating-point format provides the same dynamic range as FP32 with a memory footprint identical to FP16. We found that we could train models in the BF16 format using the same set of hyperparameters as in FP32, without special parameter tuning. Nevertheless, we found that we need to keep LayerNorm in FP32 mode in order for the training to converge.\n\n### 3.4 Final training recipe\n\nA summary of the final training recipe.", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "A summary of the final training recipe.\n\n1. Wrap the outer model in an FSDP instance. Enable parameter sharding after the forward pass.\n2. Wrap individual ViT blocks with activation checkpointing, nested FSDP wrapping, and parameter flattening.\n3. Enable mixed precision mode (AMP O2) with bfloat16 representation. Maintain the optimizer state in FP32 precision to enhance numerical stability.\n4. Wrap normalization layers like LayerNorm in FP32 for better numerical stability.\n5. Maximize the Nvidia TensorCore utilization by keeping matrix dimensions to be multiple of 8. For More details check [Nvidia Tensor Core Performance Guide](https://developer.download.nvidia.com/video/gputechconf/gtc/2019/presentation/s9926-tensor-core-performance-the-ultimate-guide.pdf).\n\n## 4. Results", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## 4. Results\n\nIn this section, we show the scaling results of ViT on three types of tasks: (1) image classification, (2) object detection (3) video understanding. **Our key result is that we are able to train massive ViT backbones across these vision tasks after applying the discussed scaling and optimization techniques. This enables vision research at a much larger scale.** We trained the models to convergence to verify that we maintain the current baselines even with all the optimizations. A common trend in Figures 2, 3, 4 is that we are able to train up to 25B-param models with an epoch time of less than 4 hours on 128 A100 GPUs. The 60B and 120B models are relatively slower to train.\n\n**Figure 2** shows the *image-classification* scaling result. It plots the epoch time for training ViTs on ImageNet using 128 A100-80GB GPUs with different model sizes.\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "\nFigure 2: Image-classification scaling result.\n
\n\n**Figure 3** shows the *object-detection* scaling result. It plots the epoch time for training [ViTDet](https://arxiv.org/abs/2203.16527) [9] with different ViT backbones on COCO using 128 A100-80GB GPUs.\n\n\n
\n
\n\n\nFigure 3: Object-detection scaling result.\n
\n\n**Figure 4** shows the *video-understanding* scaling result. It plots the epoch time for training [MViTv2](https://arxiv.org/abs/2112.01526) [10] models on [Kinetics 400](https://www.deepmind.com/open-source/kinetics) [11] using 128 V100 (32 GB) GPUs in FP32.\n\n\n
\n
\n\n\nFigure 4: Video-understanding scaling result.\n
", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "**Figure 5** shows the optimization result with the ViT-H model in Figure 2 on 8 A100-40GB GPUs.\nThree versions are used: (1) the baseline uses PyTorch\u2019s DDP [12] with AMP O1, (2) FSDP + AMP-O2 + other optimizations, and (3) FSDP + FP16 + other optimizations. These optimizations altogether speed up the training by up to 2.2x.\n\n\n
\n
\n\n\nFigure 5: Training speedups from various optimizations.\n
\n\n## 5. Concluding Remarks\n\nWe have demonstrated the use of PyTorch with FairScale\u2019s FullyShardedDataParallel (FSDP) API in writing large vision transformer models. We discuss our techniques for scaling and optimizing these models on a GPU cluster. We hope that this article can motivate others to develop large-scale ML models with PyTorch and its ecosystem.\n\n## References\n\n[1] [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377)", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "[2] [Revisiting Weakly Supervised Pre-Training of Visual Perception Models](https://arxiv.org/abs/2201.08371)\n\n[3] [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929v2)\n\n[4] [fairscale.nn.FullyShardedDataParallel](https://fairscale.readthedocs.io/en/stable/api/nn/fsdp.html)\n\n[5] [Pipeline parallelism in PyTorch](https://pytorch.org/docs/stable/pipeline.html)\n\n[6] [Automatic Mixed Precision (AMP) in PyTorch](https://pytorch.org/docs/stable/amp.html#module-torch.amp)\n\n[7] [xformers](https://github.com/facebookresearch/xformers)\n\n[8] [The bfloat16 numerical format](https://cloud.google.com/tpu/docs/bfloat16)\n\n[9] [Exploring Plain Vision Transformer Backbones for Object Detection](https://arxiv.org/abs/2203.16527)\n\n[10] [MViTv2: Improved Multiscale Vision Transformers for Classification and Detection](https://arxiv.org/abs/2112.01526)\n\n[11] [https://www.deepmind.com/open-source/kinetics](https://www.deepmind.com/open-source/kinetics)", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "[12] [Getting Started with Distributed Data Parallel (DDP)](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html)", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "---\nlayout: blog_detail\ntitle: 'Announcing PyTorch Ecosystem Day'\nauthor: Team PyTorch\n---\n\nWe\u2019re proud to announce our first PyTorch Ecosystem Day. The virtual, one-day event will focus completely on our Ecosystem and Industry PyTorch communities!\n\n\nPyTorch is a deep learning framework of choice for academics and companies, all thanks to its rich ecosystem of tools and strong community. As with our developers, our ecosystem partners play a pivotal role in the development and growth of the community.\n\n\n

\n
", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
-{"page_content": "We will be hosting our first PyTorch Ecosystem Day, a virtual event designed for our ecosystem and industry communities to showcase their work and discover new opportunities to collaborate. \n \nPyTorch Ecosystem Day will be held on April 21, with both a morning and evening session, to ensure we reach our global community. Join us virtually for a day filled with discussions on new developments, trends, challenges, and best practices through keynotes, breakout sessions, and a unique networking opportunity hosted through Gather.Town . \n\n## Event Details\nApril 21, 2021 (Pacific Time)\nFully digital experience \n \n* Morning Session: (EMEA)\nOpening Talks - 8:00 am-9:00 am PT\nPoster Exhibition & Breakout Sessions - 9:00 am-12:00 pm PT \n\n* Evening Session (APAC/US)\nOpening Talks - 3:00 pm-4:00 pm PT\nPoster Exhibition & Breakout Sessions - 3:00 pm-6:00 pm PT \n\n* Networking - 9:00 am-7:00 pm PT", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
-{"page_content": "* Networking - 9:00 am-7:00 pm PT\n\n### There are two ways to participate in PyTorch Ecosystem Day:\n \n1. **Poster Exhibition** from the PyTorch ecosystem and industry communities covering a variety of topics. Posters are available for viewing throughout the duration of the event. To be part of the poster exhibition, please see below for submission details. If your poster is accepted, we highly recommend tending your poster during one of the morning or evening sessions or both!\n \n2. **Breakout Sessions** are 40-min sessions freely designed by the community. The breakouts can be talks, demos, tutorials or discussions. Note: you must have an accepted poster to apply for the breakout sessions.", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
+{"page_content": "#### BFloat16 in general but with LayerNorm in FP32\n\nThe [bfloat16](https://cloud.google.com/tpu/docs/bfloat16) (BF16) [8] floating-point format provides the same dynamic range as FP32 with a memory footprint identical to FP16. We found that we could train models in the BF16 format using the same set of hyperparameters as in FP32, without special parameter tuning. Nevertheless, we found that we need to keep LayerNorm in FP32 mode in order for the training to converge.\n\n### 3.4 Final training recipe\n\nA summary of the final training recipe.\n\n1. Wrap the outer model in an FSDP instance. Enable parameter sharding after the forward pass.\n2. Wrap individual ViT blocks with activation checkpointing, nested FSDP wrapping, and parameter flattening.\n3. Enable mixed precision mode (AMP O2) with bfloat16 representation. Maintain the optimizer state in FP32 precision to enhance numerical stability.\n4. Wrap normalization layers like LayerNorm in FP32 for better numerical stability.", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "5. Maximize the Nvidia TensorCore utilization by keeping matrix dimensions to be multiple of 8. For More details check [Nvidia Tensor Core Performance Guide](https://developer.download.nvidia.com/video/gputechconf/gtc/2019/presentation/s9926-tensor-core-performance-the-ultimate-guide.pdf).\n\n## 4. Results\n\nIn this section, we show the scaling results of ViT on three types of tasks: (1) image classification, (2) object detection (3) video understanding. **Our key result is that we are able to train massive ViT backbones across these vision tasks after applying the discussed scaling and optimization techniques. This enables vision research at a much larger scale.** We trained the models to convergence to verify that we maintain the current baselines even with all the optimizations. A common trend in Figures 2, 3, 4 is that we are able to train up to 25B-param models with an epoch time of less than 4 hours on 128 A100 GPUs. The 60B and 120B models are relatively slower to train.", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "**Figure 2** shows the *image-classification* scaling result. It plots the epoch time for training ViTs on ImageNet using 128 A100-80GB GPUs with different model sizes.\n\n\n
\n
\n\n\nFigure 2: Image-classification scaling result.\n
\n\n**Figure 3** shows the *object-detection* scaling result. It plots the epoch time for training [ViTDet](https://arxiv.org/abs/2203.16527) [9] with different ViT backbones on COCO using 128 A100-80GB GPUs.\n\n\n
\n
\n\n\nFigure 3: Object-detection scaling result.\n
", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\n\n**Figure 4** shows the *video-understanding* scaling result. It plots the epoch time for training [MViTv2](https://arxiv.org/abs/2112.01526) [10] models on [Kinetics 400](https://www.deepmind.com/open-source/kinetics) [11] using 128 V100 (32 GB) GPUs in FP32.\n\n\n
\n
\n\n\nFigure 4: Video-understanding scaling result.\n
\n\n**Figure 5** shows the optimization result with the ViT-H model in Figure 2 on 8 A100-40GB GPUs.\nThree versions are used: (1) the baseline uses PyTorch\u2019s DDP [12] with AMP O1, (2) FSDP + AMP-O2 + other optimizations, and (3) FSDP + FP16 + other optimizations. These optimizations altogether speed up the training by up to 2.2x.\n\n\n
\n
\n\n\nFigure 5: Training speedups from various optimizations.", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n## 5. Concluding Remarks\n\nWe have demonstrated the use of PyTorch with FairScale\u2019s FullyShardedDataParallel (FSDP) API in writing large vision transformer models. We discuss our techniques for scaling and optimizing these models on a GPU cluster. We hope that this article can motivate others to develop large-scale ML models with PyTorch and its ecosystem.\n\n## References\n\n[1] [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377)\n\n[2] [Revisiting Weakly Supervised Pre-Training of Visual Perception Models](https://arxiv.org/abs/2201.08371)\n\n[3] [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929v2)\n\n[4] [fairscale.nn.FullyShardedDataParallel](https://fairscale.readthedocs.io/en/stable/api/nn/fsdp.html)\n\n[5] [Pipeline parallelism in PyTorch](https://pytorch.org/docs/stable/pipeline.html)\n\n[6] [Automatic Mixed Precision (AMP) in PyTorch](https://pytorch.org/docs/stable/amp.html#module-torch.amp)", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "[7] [xformers](https://github.com/facebookresearch/xformers)\n\n[8] [The bfloat16 numerical format](https://cloud.google.com/tpu/docs/bfloat16)\n\n[9] [Exploring Plain Vision Transformer Backbones for Object Detection](https://arxiv.org/abs/2203.16527)\n\n[10] [MViTv2: Improved Multiscale Vision Transformers for Classification and Detection](https://arxiv.org/abs/2112.01526)\n\n[11] [https://www.deepmind.com/open-source/kinetics](https://www.deepmind.com/open-source/kinetics)\n\n[12] [Getting Started with Distributed Data Parallel (DDP)](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html)", "metadata": {"source": "https://pytorch.org/blog/scaling-vision-model-training-platforms-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "---\nlayout: blog_detail\ntitle: 'Announcing PyTorch Ecosystem Day'\nauthor: Team PyTorch\n---\n\nWe\u2019re proud to announce our first PyTorch Ecosystem Day. The virtual, one-day event will focus completely on our Ecosystem and Industry PyTorch communities!\n\n\nPyTorch is a deep learning framework of choice for academics and companies, all thanks to its rich ecosystem of tools and strong community. As with our developers, our ecosystem partners play a pivotal role in the development and growth of the community.\n\n\n

\n
\n\nWe will be hosting our first PyTorch Ecosystem Day, a virtual event designed for our ecosystem and industry communities to showcase their work and discover new opportunities to collaborate.", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
+{"page_content": "PyTorch Ecosystem Day will be held on April 21, with both a morning and evening session, to ensure we reach our global community. Join us virtually for a day filled with discussions on new developments, trends, challenges, and best practices through keynotes, breakout sessions, and a unique networking opportunity hosted through Gather.Town . \n\n## Event Details\nApril 21, 2021 (Pacific Time)\nFully digital experience \n \n* Morning Session: (EMEA)\nOpening Talks - 8:00 am-9:00 am PT\nPoster Exhibition & Breakout Sessions - 9:00 am-12:00 pm PT \n\n* Evening Session (APAC/US)\nOpening Talks - 3:00 pm-4:00 pm PT\nPoster Exhibition & Breakout Sessions - 3:00 pm-6:00 pm PT \n\n* Networking - 9:00 am-7:00 pm PT\n\n### There are two ways to participate in PyTorch Ecosystem Day:", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
+{"page_content": "1. **Poster Exhibition** from the PyTorch ecosystem and industry communities covering a variety of topics. Posters are available for viewing throughout the duration of the event. To be part of the poster exhibition, please see below for submission details. If your poster is accepted, we highly recommend tending your poster during one of the morning or evening sessions or both!\n \n2. **Breakout Sessions** are 40-min sessions freely designed by the community. The breakouts can be talks, demos, tutorials or discussions. Note: you must have an accepted poster to apply for the breakout sessions.", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
{"page_content": "Call for posters now open! [Submit your proposal](https://pytorchecosystemday.fbreg.com/posters) today! Please send us the **title** and **summary** of your projects, tools, and libraries that could benefit PyTorch researchers in academia and industry, application developers, and ML engineers for consideration. The focus must be on academic papers, machine learning research, or open-source projects. Please no sales pitches. **Deadline for submission is March 18, 2021.** \n\nVisit [pytorchecosystemday.fbreg.com](http://pytorchecosystemday.fbreg.com) for more information and we look forward to welcoming you to PyTorch Ecosystem Day on April 21st!", "metadata": {"source": "https://pytorch.org/blog/ecosystem_day_2021/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch 1.5 released, new and updated APIs including C++ frontend API parity with Python'\nauthor: Team PyTorch\n---\n\n\nToday, we\u2019re announcing the availability of PyTorch 1.5, along with new and updated libraries. This release includes several major new API additions and improvements. PyTorch now includes a significant update to the C++ frontend, \u2018channels last\u2019 memory format for computer vision models, and a stable release of the distributed RPC framework used for model-parallel training. The release also has new APIs for autograd for hessians and jacobians, and an API that allows the creation of Custom C++ Classes that was inspired by pybind.\n\nYou can find the detailed release notes [here](https://github.com/pytorch/pytorch/releases).\n\n## C++ Frontend API (Stable)\n\nThe C++ frontend API is now at parity with Python, and the features overall have been moved to \u2018stable\u2019 (previously tagged as experimental). Some of the major highlights include:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
{"page_content": "* Now with ~100% coverage and docs for C++ torch::nn module/functional, users can easily translate their model from Python API to C++ API, making the model authoring experience much smoother.\n* Optimizers in C++ had deviated from the Python equivalent: C++ optimizers can\u2019t take parameter groups as input while the Python ones can. Additionally, step function implementations were not exactly the same. With the 1.5 release, C++ optimizers will always behave the same as the Python equivalent.\n* The lack of tensor multi-dim indexing API in C++ is a well-known issue and had resulted in many posts in PyTorch Github issue tracker and forum. The previous workaround was to use a combination of `narrow` / `select` / `index_select` / `masked_select`, which was clunky and error-prone compared to the Python API\u2019s elegant `tensor[:, 0, ..., mask]` syntax. With the 1.5 release, users can use `tensor.index({Slice(), 0, \"...\", mask})` to achieve the same purpose.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
-{"page_content": "## \u2018Channels last\u2019 memory format for Computer Vision models (Experimental)\n\n\u2018Channels last\u2019 memory layout unlocks ability to use performance efficient convolution algorithms and hardware (NVIDIA\u2019s Tensor Cores, FBGEMM, QNNPACK). Additionally, it is designed to automatically propagate through the operators, which allows easy switching between memory layouts.\n\nLearn more [here](https://github.com/pytorch/pytorch/wiki/Writing-memory-format-aware-operators) on how to write memory format aware operators.\n\n## Custom C++ Classes (Experimental)\n\nThis release adds a new API, `torch::class_`, for binding custom C++ classes into TorchScript and Python simultaneously. This API is almost identical in syntax to [pybind11](https://pybind11.readthedocs.io/en/stable/). It allows users to expose their C++ class and its methods to the TorchScript type system and runtime system such that they can instantiate and manipulate arbitrary C++ objects from TorchScript and Python. An example C++ binding:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
+{"page_content": "## \u2018Channels last\u2019 memory format for Computer Vision models (Experimental)\n\n\u2018Channels last\u2019 memory layout unlocks ability to use performance efficient convolution algorithms and hardware (NVIDIA\u2019s Tensor Cores, FBGEMM, QNNPACK). Additionally, it is designed to automatically propagate through the operators, which allows easy switching between memory layouts.\n\nLearn more [here](https://github.com/pytorch/pytorch/wiki/Writing-memory-format-aware-operators) on how to write memory format aware operators.\n\n## Custom C++ Classes (Experimental)\n\nThis release adds a new API, `torch::class_`, for binding custom C++ classes into TorchScript and Python simultaneously. This API is almost identical in syntax to [pybind11](https://pybind11.readthedocs.io/en/stable/). It allows users to expose their C++ class and its methods to the TorchScript type system and runtime system such that they can instantiate and manipulate arbitrary C++ objects from TorchScript and Python. An example C++ binding:\n\n```python\ntemplate ", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
{"page_content": "```python\ntemplate \nstruct MyStackClass : torch::CustomClassHolder {\n std::vector stack_;\n MyStackClass(std::vector init) : stack_(std::move(init)) {}\n\n void push(T x) {\n stack_.push_back(x);\n }\n T pop() {\n auto val = stack_.back();\n stack_.pop_back();\n return val;\n }\n};\n\nstatic auto testStack =\n torch::class_>(\"myclasses\", \"MyStackClass\")\n .def(torch::init>())\n .def(\"push\", &MyStackClass::push)\n .def(\"pop\", &MyStackClass::pop)\n .def(\"size\", [](const c10::intrusive_ptr& self) {\n return self->stack_.size();\n });\n```\n\n Which exposes a class you can use in Python and TorchScript like so:\n\n```python\n@torch.jit.script\ndef do_stacks(s : torch.classes.myclasses.MyStackClass):\n s2 = torch.classes.myclasses.MyStackClass([\"hi\", \"mom\"])\n print(s2.pop()) # \"mom\"\n s2.push(\"foobar\")\n return s2 # [\"hi\", \"foobar\"]\n```", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
-{"page_content": "You can try it out in the tutorial [here](https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html).\n\n\n## Distributed RPC framework APIs (Now Stable)\n\nThe Distributed [RPC framework](https://pytorch.org/docs/stable/rpc.html) was launched as experimental in the 1.4 release and the proposal is to mark Distributed RPC framework as stable and no longer experimental. This work involves a lot of enhancements and bug fixes to make the distributed RPC framework more reliable and robust overall, as well as adding a couple of new features, including profiling support, using TorchScript functions in RPC, and several enhancements for ease of use. Below is an overview of the various APIs within the framework:\n\n### RPC API\nThe RPC API allows users to specify functions to run and objects to be instantiated on remote nodes. These functions are transparently recorded so that gradients can backpropagate through remote nodes using Distributed Autograd.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
-{"page_content": "### Distributed Autograd\nDistributed Autograd connects the autograd graph across several nodes and allows gradients to flow through during the backwards pass. Gradients are accumulated into a context (as opposed to the .grad field as with Autograd) and users must specify their model\u2019s forward pass under a with `dist_autograd.context()` manager in order to ensure that all RPC communication is recorded properly. Currently, only FAST mode is implemented (see [here](https://pytorch.org/docs/stable/rpc/distributed_autograd.html#distributed-autograd-design) for the difference between FAST and SMART modes).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
+{"page_content": "return s2 # [\"hi\", \"foobar\"]\n```\n\nYou can try it out in the tutorial [here](https://pytorch.org/tutorials/advanced/torch_script_custom_classes.html).\n\n\n## Distributed RPC framework APIs (Now Stable)\n\nThe Distributed [RPC framework](https://pytorch.org/docs/stable/rpc.html) was launched as experimental in the 1.4 release and the proposal is to mark Distributed RPC framework as stable and no longer experimental. This work involves a lot of enhancements and bug fixes to make the distributed RPC framework more reliable and robust overall, as well as adding a couple of new features, including profiling support, using TorchScript functions in RPC, and several enhancements for ease of use. Below is an overview of the various APIs within the framework:\n\n### RPC API\nThe RPC API allows users to specify functions to run and objects to be instantiated on remote nodes. These functions are transparently recorded so that gradients can backpropagate through remote nodes using Distributed Autograd.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
+{"page_content": "### Distributed Autograd\nDistributed Autograd connects the autograd graph across several nodes and allows gradients to flow through during the backwards pass. Gradients are accumulated into a context (as opposed to the .grad field as with Autograd) and users must specify their model\u2019s forward pass under a with `dist_autograd.context()` manager in order to ensure that all RPC communication is recorded properly. Currently, only FAST mode is implemented (see [here](https://pytorch.org/docs/stable/rpc/distributed_autograd.html#distributed-autograd-design) for the difference between FAST and SMART modes).\n\n### Distributed Optimizer", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
{"page_content": "### Distributed Optimizer\nThe distributed optimizer creates RRefs to optimizers on each worker with parameters that require gradients, and then uses the RPC API to run the optimizer remotely. The user must collect all remote parameters and wrap them in an `RRef`, as this is required input to the distributed optimizer. The user must also specify the distributed autograd `context_id` so that the optimizer knows in which context to look for gradients.\n\nLearn more about distributed RPC framework APIs [here](https://pytorch.org/docs/stable/rpc.html).\n\n## New High level autograd API (Experimental)\n\nPyTorch 1.5 brings new functions including jacobian, hessian, jvp, vjp, hvp and vhp to the `torch.autograd.functional` submodule. This feature builds on the current API and allows the user to easily perform these functions.\n\nDetailed design discussion on GitHub can be found [here](https://github.com/pytorch/pytorch/issues/30632).\n\n## Python 2 no longer supported", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
{"page_content": "## Python 2 no longer supported\n\nStarting PyTorch 1.5.0, we will no longer support Python 2, specifically version 2.7. Going forward support for Python will be limited to Python 3, specifically Python 3.5, 3.6, 3.7 and 3.8 (first enabled in PyTorch 1.4.0).\n\n\n*We\u2019d like to thank the entire PyTorch team and the community for all their contributions to this work.*\n\nCheers!\n\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/pytorch-1-dot-5-released-with-new-and-updated-apis/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'OpenMined and PyTorch partner to launch fellowship funding for privacy-preserving ML community'\nauthor: Andrew Trask (OpenMined/U.Oxford), Shubho Sengupta, Laurens van der Maaten, Joe Spisak\nexcerpt: Many applications of machine learning (ML) pose a range of security and privacy challenges.\n---\n\n\n

\n
\n\nMany applications of machine learning (ML) pose a range of security and privacy challenges. In particular, users may not be willing or allowed to share their data, which prevents them from taking full advantage of ML platforms like PyTorch. To take the field of privacy-preserving ML (PPML) forward, OpenMined and PyTorch are announcing plans to jointly develop a combined platform to accelerate PPML research as well as new funding for fellowships.", "metadata": {"source": "https://pytorch.org/blog/openmined-and-pytorch-launch-fellowship-funding-for-privacy-preserving-ml/", "category": "pytorch blogs"}}
@@ -622,36 +623,32 @@
{"page_content": "### Development Challenges\n\nOver the coming months, we will issue regular open competitions for increasing the performance and security of the PySyft and PyGrid codebases. For performance-related challenges, contestants will compete (for a cash prize) to make a specific PySyft demo (such as federated learning) as fast as possible. For security-related challenges, contestants will compete to hack into a PyGrid server. The first to demonstrate their ability will win the cash bounty! For more information on the challenges and to sign up to receive emails when each challenge is opened, [sign up here](http://blog.openmined.org/announcing-the-openmined-pytorch-development-challenges).\n\nTo apply, select one of the above projects and identify a role that matches your strengths!\n\nCheers,\n\nAndrew, Laurens, Joe, and Shubho", "metadata": {"source": "https://pytorch.org/blog/openmined-and-pytorch-launch-fellowship-funding-for-privacy-preserving-ml/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'How Computational Graphs are Constructed in PyTorch'\nauthor: Preferred Networks\nfeatured-img: 'assets/images/augmented_computational_graph.png'\n---\n\nIn the previous [post](https://pytorch.org/blog/overview-of-pytorch-autograd-engine/) we went over the theoretical foundations of automatic differentiation and reviewed the implementation in PyTorch. In this post, we will be showing the parts of PyTorch involved in creating the graph and executing it. In order to understand the following contents, please read @ezyang\u2019s wonderful [blog post](http://blog.ezyang.com/2019/05/pytorch-internals/) about PyTorch internals.\n\n# Autograd components\n\nFirst of all, let\u2019s look at where the different components of autograd live:", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
{"page_content": "[tools/autograd](https://github.com/pytorch/pytorch/tree/release/1.9/tools/autograd): Here we can find the definition of the derivatives as we saw in the previous post [derivatives.yaml](https://github.com/pytorch/pytorch/blob/release/1.9/tools/autograd/derivatives.yaml), several python scripts and a folder called [templates](https://github.com/pytorch/pytorch/tree/release/1.9/tools/autograd/templates). These scripts and the templates are used at building time to generate the C++ code for the derivatives as specified in the yaml file. Also, the scripts here generate wrappers for the regular ATen functions so that the computational graph can be constructed.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "[torch/autograd](https://github.com/pytorch/pytorch/tree/release/1.9/torch/autograd): This folder is where the autograd components that can be used directly from python are located. In [function.py](https://github.com/pytorch/pytorch/blob/release/1.9/torch/autograd/function.py) we find the actual definition of `torch.autograd.Function`, a class used by users to write their own differentiable functions in python as per the documentation. [functional.py](https://github.com/pytorch/pytorch/blob/release/1.9/torch/autograd/functional.py) holds components for functionally computing the jacobian vector product, hessian, and other gradient related computations of a given function.\nThe rest of the files have additional components such as gradient checkers, anomaly detection, and the autograd profiler.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "[torch/csrc/autograd](https://github.com/pytorch/pytorch/tree/release/1.9/torch/csrc/autograd): This is where the graph creation and execution-related code lives.\nAll this code is written in C++, since it is a critical part that is required to be extremely performant. Here we have several files that implement the engine, metadata storage, and all the needed components. Alongside this, we have several files whose names start with `python_`, and their main responsibility is to allow python objects to be used in the autograd engine.\n\n# Graph Creation\n\n[Previously](https://pytorch.org/blog/overview-of-pytorch-autograd-engine/), we described the creation of a computational graph. Now, we will see how PyTorch creates these graphs with references to the actual codebase.\n\n\n
\n
\nFigure 1: Example of an augmented computational graph\n
", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "It all starts when in our python code, where we request a tensor to require the gradient.\n\n```py\n>>> x = torch.tensor([0.5, 0.75], requires_grad=True)\n```\n\nWhen the `required_grad` flag is set in tensor creation, c10 will [allocate](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/c10/core/TensorImpl.cpp#L382-L406) an `AutogradMeta` object that is used to hold the graph information.\n\n```c++\n\nvoid TensorImpl::set_requires_grad(bool requires_grad) {\n ...\n if (!autograd_meta_)\n autograd_meta_ = impl::GetAutogradMetaFactory()->make();\n autograd_meta_->set_requires_grad(requires_grad, this);\n}\n```\n\n\nThe `AutogradMeta` object is defined in [torch/csrc/autograd/variable.h](https://github.com/pytorch/pytorch/blob/release/1.9/torch/csrc/autograd/variable.h#L190-L286) as follows:\n\n```c++\n\nstruct TORCH_API AutogradMeta : public c10::AutogradMetaInterface {\n std::string name_;", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Variable grad_;\n std::shared_ptr grad_fn_;\n std::weak_ptr grad_accumulator_;\n // other fields and methods\n ...\n};\n```\n\nThe most important fields in this structure are the computed gradient in `grad_` and a pointer to the function `grad_fn` that will be called by the engine to produce the actual gradient. Also, there is a gradient accumulator object that is used to add together all the different gradients where this tensor is involved as we will see in the graph execution.\n\n### Graphs, Nodes and Edges.\n\nNow, when we call a differentiable function that takes this tensor as an argument, the associated metadata will be populated. Let\u2019s suppose that we call a regular torch function that is implemented in ATen. Let it be the multiplication as in our previous blog post example. The resulting tensor has a field called `grad_fn` that is essentially a pointer to the function that will be used to compute the gradient of that operation.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```py\n>>> x = torch.tensor([0.5, 0.75], requires_grad=True)\n>>> v = x[0] * x[1]\n>>> v\ntensor(0.3750, grad_fn=)\n```\n\nHere we see that the tensors\u2019 `grad_fn` has a `MulBackward0` value. This function is the same that was written in the [derivatives.yaml](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/tools/autograd/derivatives.yaml#L840-L843) file, and its C++ code was generated automatically by all the scripts in `tools/autograd`. It\u2019s auto-generated source code can be seen in `torch/csrc/autograd/generated/Functions.cpp`.\n\n```c++\nvariable_list MulBackward0::apply(variable_list&& grads) {\n std::lock_guard lock(mutex_);", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "IndexRangeGenerator gen;\n auto self_ix = gen.range(1);\n auto other_ix = gen.range(1);\n variable_list grad_inputs(gen.size());\n auto& grad = grads[0];\n auto self = self_.unpack();\n auto other = other_.unpack();\n bool any_grad_defined = any_variable_defined(grads);\n if (should_compute_output({ other_ix })) {\n auto grad_result = any_grad_defined ? (mul_tensor_backward(grad, self, other_scalar_type)) : Tensor();\n copy_range(grad_inputs, other_ix, grad_result);\n }\n if (should_compute_output({ self_ix })) {\n auto grad_result = any_grad_defined ? (mul_tensor_backward(grad, other, self_scalar_type)) : Tensor();\n copy_range(grad_inputs, self_ix, grad_result);\n }\n return grad_inputs;\n}\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "The `grad_fn` objects inherit from the [`TraceableFunction`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L535-L541) class, a descendant of `Node` with just a property set to enable tracing for debugging and optimization purposes. A graph by definition has nodes and edges, so these functions are indeed the nodes of the computational graph that are linked together by using `Edge` objects to enable the graph traversal later on.\n\nThe `Node` definition can be found in the [torch/csrc/autograd/function.h](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L50-L533) file.\n\n```c++\nstruct TORCH_API Node : std::enable_shared_from_this {\n ...\n /// Evaluates the function on the given inputs and returns the result of the\n /// function call.\n variable_list operator()(variable_list&& inputs) {\n ...\n }", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "protected:\n /// Performs the `Node`'s actual operation.\n virtual variable_list apply(variable_list&& inputs) = 0;\n \u2026\n edge_list next_edges_;\n```\n\nEssentially we see that it has an override of the `operator ()` that performs the call to the actual function, and a pure virtual function called `apply`. The automatically generated functions override this `apply` method as we saw in the `MulBackward0` example above. Finally, the node also has a list of edges to enable graph connectivity.\n\nThe [Edge](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/edge.h#L14-L39) object is used to link `Node`s together and its implementation is straightforward.\n\n```c++\nstruct Edge {\n ...\n /// The function this `Edge` points to.\n std::shared_ptr function;\n /// The identifier of a particular input to the function.\n uint32_t input_nr;\n};\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "It only requires a function pointer (the actual `grad_fn` objects that the edges link together), and an input number that acts as an id for the edge.\n\n### Linking nodes together\n\nWhen we invoke the product operation of two tensors, we enter into the realm of autogenerated code. All the scripts that we saw in `tools/autograd` fill a series of templates that wrap the differentiable functions in ATen. These functions have code to construct the backward graph during the forward pass.\n\nThe [gen_variable_type.py](https://github.com/pytorch/pytorch/blob/release/1.9/tools/autograd/gen_variable_type.py) script is in charge of writing all this wrapping code. This script is called from the [tools/autograd/gen_autograd.py](https://github.com/pytorch/pytorch/blob/release/1.9/tools/autograd/gen_autograd.py) during the pytorch build process and it will output the automatically generated function wrappers to `torch/csrc/autograd/generated/`.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Let\u2019s take a look at how the tensor multiplication generated function looks like. The code has been simplified, but it can be found in the `torch/csrc/autograd/generated/VariableType_4.cpp` file when compiling pytorch from source.\n\n```c++\nat::Tensor mul_Tensor(c10::DispatchKeySet ks, const at::Tensor & self, const at::Tensor & other) {\n ...\n auto _any_requires_grad = compute_requires_grad( self, other );\n std::shared_ptr grad_fn;\n if (_any_requires_grad) {\n // Creates the link to the actual grad_fn and links the graph for backward traversal\n grad_fn = std::shared_ptr(new MulBackward0(), deleteNode);\n grad_fn->set_next_edges(collect_next_edges( self, other ));\n ...\n }\n \u2026\n // Does the actual function call to ATen\n auto _tmp = ([&]() {\n at::AutoDispatchBelowADInplaceOrView guard;\n return at::redispatch::mul(ks & c10::after_autograd_keyset, self_, other_);\n })();", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "auto result = std::move(_tmp);\n if (grad_fn) {\n // Connects the result to the graph\n set_history(flatten_tensor_args( result ), grad_fn);\n }\n ...\n return result;\n}\n```\n\nLet\u2019s walk through the most important lines of this code.\nFirst of all, the `grad_fn` object is created with: ` grad_fn = std::shared_ptr(new MulBackward0(), deleteNode);`.\n\nAfter the `grad_fn` object is created, the edges used to link the nodes together are created by using the `grad_fn->set_next_edges(collect_next_edges( self, other ));` calls.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```c++\nstruct MakeNextFunctionList : IterArgs {\n edge_list next_edges;\n using IterArgs::operator();\n void operator()(const Variable& variable) {\n if (variable.defined()) {\n next_edges.push_back(impl::gradient_edge(variable));\n } else {\n next_edges.emplace_back();\n }\n }\n void operator()(const c10::optional& variable) {\n if (variable.has_value() && variable->defined()) {\n next_edges.push_back(impl::gradient_edge(*variable));\n } else {\n next_edges.emplace_back();\n }\n }\n};\n\ntemplate \nedge_list collect_next_edges(Variables&&... variables) {\n detail::MakeNextFunctionList make;\n make.apply(std::forward(variables)...);\n return std::move(make.next_edges);\n}\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Given an input variable (it\u2019s just a regular tensor), [`collect_next_edges`](\nhttps://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L597-L603)\n will create an `Edge` object by calling [`impl::gradient_edge`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/variable.cpp#L228-L240.)", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```c++\n Edge gradient_edge(const Variable& self) {\n // If grad_fn is null (as is the case for a leaf node), we instead\n // interpret the gradient function to be a gradient accumulator, which will\n // accumulate its inputs into the grad property of the variable. These\n // nodes get suppressed in some situations, see \"suppress gradient\n // accumulation\" below. Note that only variables which have `requires_grad =\n // True` can have gradient accumulators.\n if (const auto& gradient = self.grad_fn()) {\n return Edge(gradient, self.output_nr());\n } else {\n return Edge(grad_accumulator(self), 0);\n }\n }\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "To understand how edges work, let\u2019s assume that an early executed function produced two output tensors, both with their `grad_fn` set, each tensor also has an `output_nr` property with the order in which they were returned. When creating the edges for the current `grad_fn`, an `Edge` object per input variable will be created. The edges will point to the variable\u2019s grad_fn and will also track the `output_nr` to establish ids used when traversing the graph. In the case that the input variables are \u201cleaf\u201d, i.e. they were not produced by any differentiable function, they don\u2019t have a `grad_fn` attribute set. A special function called a gradient accumulator is set by default as seen in the above code snippet.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "After the edges are created, the `grad_fn` graph Node object that is being currently created will hold them using the [`set_next_edges`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L258-L263) function. This is what connects `grad_fn`s together, producing the computational graph.\n\n```c++\n void set_next_edges(edge_list&& next_edges) {\n next_edges_ = std::move(next_edges);\n for(const auto& next_edge : next_edges_) {\n update_topological_nr(next_edge);\n }\n }\n```\n\nNow, the forward pass of the function will execute, and after the execution `set_history` will connect the output tensors to the `grad_fn` Node.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```c++\ninline void set_history(\n at::Tensor& variable,\n const std::shared_ptr& grad_fn) {\n AT_ASSERT(grad_fn);\n if (variable.defined()) {\n // If the codegen triggers this, you most likely want to add your newly added function\n // to the DONT_REQUIRE_DERIVATIVE list in tools/autograd/gen_variable_type.py\n TORCH_INTERNAL_ASSERT(isDifferentiableType(variable.scalar_type()));\n auto output_nr =\n grad_fn->add_input_metadata(variable);\n impl::set_gradient_edge(variable, {grad_fn, output_nr});\n } else {\n grad_fn->add_input_metadata(Node::undefined_input());\n }\n}\n```\n\n[`set_history`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/functions/utils.h#L58-L72) calls [`set_gradient_edge`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/variable.cpp#L242-L255), which just copies the grad_fn and the `output_nr` to the `AutogradMeta` object that the tensor has.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```c++\n void set_gradient_edge(const Variable& self, Edge edge) {\n auto* meta = materialize_autograd_meta(self);\n meta->grad_fn_ = std::move(edge.function);\n meta->output_nr_ = edge.input_nr;\n // For views, make sure this new grad_fn_ is not overwritten unless it is necessary\n // in the VariableHooks::grad_fn below.\n // This logic is only relevant for custom autograd Functions for which multiple\n // operations can happen on a given Tensor before its gradient edge is set when\n // exiting the custom Function.\n auto diff_view_meta = get_view_autograd_meta(self);\n if (diff_view_meta && diff_view_meta->has_bw_view()) {\n diff_view_meta->set_attr_version(self._version());\n }\n }\n```\n\nThis tensor now will be the input to another function and the above steps will be all repeated. Check the animation below to see how the graph is created.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "\n
\n
\nFigure 2: Animation that shows the graph creation\n
\n\n### Registering Python Functions in the graph\n\nWe have seen how autograd creates the graph for the functions included in ATen. However, when we define our differentiable functions in Python, they are also included in the graph!\n\nAn autograd python defined function looks like the following:\n\n```python\nclass Exp(torch.autograd.Function):\n @staticmethod\n def forward(ctx, i):\n result = i.exp()\n ctx.save_for_backward(result)\n return result\n\n @staticmethod\n def backward(ctx, grad_output):\n result, = ctx.saved_tensors\n return grad_output * result\n\n# Call the function\nExp.apply(torch.tensor(0.5, requires_grad=True))\n# Outputs: tensor(1.6487, grad_fn=)\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "In the above snippet autograd detected our python function when creating the graph. All of this is possible thanks to the [`Function`](https://github.com/pytorch/pytorch/blob/release/1.9/torch/autograd/function.py#L106) class. Let\u2019s take a look at what happens when we call `apply`.\n\n`apply` is defined in the [`torch._C._FunctionBase`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L859-L908) class, but this class is not present in the python source. `_FunctionBase` is defined in C++ by using the python C API to hook C functions together into a single python class. We are looking for a function named [`THPFunction_apply`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L577-L633). \n\n```c++", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```c++\n\nPyObject *THPFunction_apply(PyObject *cls, PyObject *inputs)\n{\n \n // Generates the graph node\n THPObjectPtr backward_cls(PyObject_GetAttrString(cls, \"_backward_cls\"));\n if (!backward_cls) return nullptr;\n THPObjectPtr ctx_obj(PyObject_CallFunctionObjArgs(backward_cls, nullptr));\n if (!ctx_obj) return nullptr;\n THPFunction* ctx = (THPFunction*)ctx_obj.get();\n\n auto cdata = std::shared_ptr(new PyNode(std::move(ctx_obj)), deleteNode);\n ctx->cdata = cdata;\n\n // Prepare inputs and allocate context (grad fn)\n // Unpack inputs will collect the edges\n auto info_pair = unpack_input(inputs);\n UnpackedInput& unpacked_input = info_pair.first;\n InputFlags& input_info = info_pair.second;\n\n // Initialize backward function (and ctx)\n bool is_executable = input_info.is_executable;\n cdata->set_next_edges(std::move(input_info.next_edges));\n ctx->needs_input_grad = input_info.needs_input_grad.release();\n ctx->is_variable_input = std::move(input_info.is_variable_input);", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "// Prepend ctx to input_tuple, in preparation for static method call\n auto num_args = PyTuple_GET_SIZE(inputs);\n THPObjectPtr ctx_input_tuple(PyTuple_New(num_args + 1));\n if (!ctx_input_tuple) return nullptr;\n Py_INCREF(ctx);\n PyTuple_SET_ITEM(ctx_input_tuple.get(), 0, (PyObject*)ctx);\n for (int i = 0; i < num_args; ++i) {\n PyObject *arg = PyTuple_GET_ITEM(unpacked_input.input_tuple.get(), i);\n Py_INCREF(arg);\n PyTuple_SET_ITEM(ctx_input_tuple.get(), i + 1, arg);\n }\n\n // Call forward\n THPObjectPtr tensor_outputs;\n {\n AutoGradMode grad_mode(false);\n THPObjectPtr forward_fn(PyObject_GetAttrString(cls, \"forward\"));\n if (!forward_fn) return nullptr;\n tensor_outputs = PyObject_CallObject(forward_fn, ctx_input_tuple);\n if (!tensor_outputs) return nullptr;\n }", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "// Here is where the outputs gets the tensors tracked\n return process_outputs(cls, cdata, ctx, unpacked_input, inputs, std::move(tensor_outputs),\n is_executable, node);\n END_HANDLE_TH_ERRORS\n}\n```\n \nAlthough this code is hard to read at first due to all the python API calls, it essentially does the same thing as the auto-generated forward functions that we saw for ATen:\n\nCreate a `grad_fn` object.\nCollect the edges to link the current `grad_fn` with the input tensors one.\nExecute the function `forward`.\nAssign the created `grad_fn` to the output tensors metadata.\n\nThe `grad_fn` object is created in:\n\n```c++\n // Generates the graph node\n THPObjectPtr backward_cls(PyObject_GetAttrString(cls, \"_backward_cls\"));\n if (!backward_cls) return nullptr;\n THPObjectPtr ctx_obj(PyObject_CallFunctionObjArgs(backward_cls, nullptr));\n if (!ctx_obj) return nullptr;\n THPFunction* ctx = (THPFunction*)ctx_obj.get();", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "auto cdata = std::shared_ptr(new PyNode(std::move(ctx_obj)), deleteNode);\n ctx->cdata = cdata;\n```\n\nBasically, it asks the python API to get a pointer to the Python object that can execute the user-written function. Then it wraps it into a [`PyNode`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.h#L24-L58) object that is a specialized `Node` object that calls the python interpreter with the provided python function when `apply` is executed during the forward pass. Note that in the code `cdata` is the actual `Node` object that is part of the graph. `ctx` is the object that is passed to the python `forward`/`backward` functions and it is used to store autograd related information by both, the user\u2019s function and PyTorch.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "As in the regular C++ functions we also call `collect_next_edges` to track the inputs `grad_fn` objects, but this is done in [`unpack_input`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L413-L448):\n\n```c++\ntemplate\nstd::pair unpack_input(PyObject *args) {\n ...\n flags.next_edges = (flags.is_executable ? collect_next_edges(unpacked.input_vars) : edge_list());\n return std::make_pair(std::move(unpacked), std::move(flags));\n}\n```\n\nAfter this, the edges are assigned to the `grad_fn` by just doing `cdata->set_next_edges(std::move(input_info.next_edges));` and the forward function is called through the python interpreter C API.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Once the output tensors are returned from the forward pass, they are processed and converted to variables inside the [`process_outputs`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L519-L562) function.\n\n```c++\nPyObject* process_outputs(PyObject *op_obj, const std::shared_ptr& cdata,\n THPFunction* grad_fn, const UnpackedInput& unpacked,\n PyObject *inputs, THPObjectPtr&& raw_output, bool is_executable,\n torch::jit::Node* node) {\n ...\n _wrap_outputs(cdata, grad_fn, unpacked.input_vars, raw_output, outputs, is_executable);\n _trace_post_record(node, op_obj, unpacked.input_vars, outputs, is_inplace, unpack_output);\n if (is_executable) {\n _save_variables(cdata, grad_fn);\n } ...\n return outputs.release();\n}\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Here, [`_wrap_outputs`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L302-L346) is in charge of setting the forward outputs `grad_fn` to the newly created one. For this, it calls another `_wrap_outputs` function defined in a different [file](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/custom_function.cpp#L28-L105), so the process here gets a little confusing.\n\n```c++\nstatic void _wrap_outputs(const std::shared_ptr& cdata, THPFunction *self,\n const variable_list &input_vars, PyObject *raw_output, PyObject *outputs, bool is_executable)\n{\n auto cdata_if_executable = is_executable ? cdata : nullptr;\n ...\n\n // Wrap only the tensor outputs.\n // This calls csrc/autograd/custom_function.cpp\n auto wrapped_outputs = _wrap_outputs(input_vars, non_differentiable, dirty_inputs, raw_output_vars, cdata_if_executable);\n...\n}\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "The called `_wrap_outputs` is the one in charge of setting the autograd metadata in the output tensors:\n\n```c++\nstd::vector> _wrap_outputs(const variable_list &input_vars,\n const std::unordered_set &non_differentiable,\n const std::unordered_set &dirty_inputs,\n const at::ArrayRef> raw_outputs,\n const std::shared_ptr &cdata) {", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "std::unordered_set inputs;\n \u2026\n // Sets the grad_fn and output_nr of an output Variable.\n auto set_history = [&](Variable& var, uint32_t output_nr, bool is_input, bool is_modified,\n bool is_differentiable) {\n // Lots of checks\n if (!is_differentiable) {\n ...\n } else if (is_input) {\n // An input has been returned, but it wasn't modified. Return it as a view\n // so that we can attach a new grad_fn to the Variable.\n // Run in no_grad mode to mimic the behavior of the forward.\n {\n AutoGradMode grad_mode(false);\n var = var.view_as(var);\n }\n impl::set_gradient_edge(var, {cdata, output_nr});\n } else if (cdata) {\n impl::set_gradient_edge(var, {cdata, output_nr});\n }\n };\n```\n\nAnd this is where `set_gradient_edge` was called and this is how a user-written python function gets included in the computational graph with its associated backward function!\n\n# Closing remarks", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "# Closing remarks\n\nThis blog post is intended to be a code overview on how PyTorch constructs the actual computational graphs that we discussed in the previous post. The next entry will deal with how the autograd engine executes these graphs.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "[torch/autograd](https://github.com/pytorch/pytorch/tree/release/1.9/torch/autograd): This folder is where the autograd components that can be used directly from python are located. In [function.py](https://github.com/pytorch/pytorch/blob/release/1.9/torch/autograd/function.py) we find the actual definition of `torch.autograd.Function`, a class used by users to write their own differentiable functions in python as per the documentation. [functional.py](https://github.com/pytorch/pytorch/blob/release/1.9/torch/autograd/functional.py) holds components for functionally computing the jacobian vector product, hessian, and other gradient related computations of a given function.\nThe rest of the files have additional components such as gradient checkers, anomaly detection, and the autograd profiler.\n\n[torch/csrc/autograd](https://github.com/pytorch/pytorch/tree/release/1.9/torch/csrc/autograd): This is where the graph creation and execution-related code lives.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "All this code is written in C++, since it is a critical part that is required to be extremely performant. Here we have several files that implement the engine, metadata storage, and all the needed components. Alongside this, we have several files whose names start with `python_`, and their main responsibility is to allow python objects to be used in the autograd engine.\n\n# Graph Creation\n\n[Previously](https://pytorch.org/blog/overview-of-pytorch-autograd-engine/), we described the creation of a computational graph. Now, we will see how PyTorch creates these graphs with references to the actual codebase.\n\n\n
\n
\nFigure 1: Example of an augmented computational graph\n
\n\nIt all starts when in our python code, where we request a tensor to require the gradient.\n\n```py\n>>> x = torch.tensor([0.5, 0.75], requires_grad=True)\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nWhen the `required_grad` flag is set in tensor creation, c10 will [allocate](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/c10/core/TensorImpl.cpp#L382-L406) an `AutogradMeta` object that is used to hold the graph information.\n\n```c++\n\nvoid TensorImpl::set_requires_grad(bool requires_grad) {\n ...\n if (!autograd_meta_)\n autograd_meta_ = impl::GetAutogradMetaFactory()->make();\n autograd_meta_->set_requires_grad(requires_grad, this);\n}\n```\n\n\nThe `AutogradMeta` object is defined in [torch/csrc/autograd/variable.h](https://github.com/pytorch/pytorch/blob/release/1.9/torch/csrc/autograd/variable.h#L190-L286) as follows:\n\n```c++\n\nstruct TORCH_API AutogradMeta : public c10::AutogradMetaInterface {\n std::string name_;\n\n Variable grad_;\n std::shared_ptr grad_fn_;\n std::weak_ptr grad_accumulator_;\n // other fields and methods\n ...\n};\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "// other fields and methods\n ...\n};\n```\n\nThe most important fields in this structure are the computed gradient in `grad_` and a pointer to the function `grad_fn` that will be called by the engine to produce the actual gradient. Also, there is a gradient accumulator object that is used to add together all the different gradients where this tensor is involved as we will see in the graph execution.\n\n### Graphs, Nodes and Edges.\n\nNow, when we call a differentiable function that takes this tensor as an argument, the associated metadata will be populated. Let\u2019s suppose that we call a regular torch function that is implemented in ATen. Let it be the multiplication as in our previous blog post example. The resulting tensor has a field called `grad_fn` that is essentially a pointer to the function that will be used to compute the gradient of that operation.\n\n```py\n>>> x = torch.tensor([0.5, 0.75], requires_grad=True)\n>>> v = x[0] * x[1]\n>>> v\ntensor(0.3750, grad_fn=)\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": ">>> v\ntensor(0.3750, grad_fn=)\n```\n\nHere we see that the tensors\u2019 `grad_fn` has a `MulBackward0` value. This function is the same that was written in the [derivatives.yaml](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/tools/autograd/derivatives.yaml#L840-L843) file, and its C++ code was generated automatically by all the scripts in `tools/autograd`. It\u2019s auto-generated source code can be seen in `torch/csrc/autograd/generated/Functions.cpp`.\n\n```c++\nvariable_list MulBackward0::apply(variable_list&& grads) {\n std::lock_guard lock(mutex_);\n\n IndexRangeGenerator gen;\n auto self_ix = gen.range(1);\n auto other_ix = gen.range(1);\n variable_list grad_inputs(gen.size());\n auto& grad = grads[0];\n auto self = self_.unpack();\n auto other = other_.unpack();\n bool any_grad_defined = any_variable_defined(grads);\n if (should_compute_output({ other_ix })) {", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "if (should_compute_output({ other_ix })) {\n auto grad_result = any_grad_defined ? (mul_tensor_backward(grad, self, other_scalar_type)) : Tensor();\n copy_range(grad_inputs, other_ix, grad_result);\n }\n if (should_compute_output({ self_ix })) {\n auto grad_result = any_grad_defined ? (mul_tensor_backward(grad, other, self_scalar_type)) : Tensor();\n copy_range(grad_inputs, self_ix, grad_result);\n }\n return grad_inputs;\n}\n```\n\nThe `grad_fn` objects inherit from the [`TraceableFunction`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L535-L541) class, a descendant of `Node` with just a property set to enable tracing for debugging and optimization purposes. A graph by definition has nodes and edges, so these functions are indeed the nodes of the computational graph that are linked together by using `Edge` objects to enable the graph traversal later on.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "The `Node` definition can be found in the [torch/csrc/autograd/function.h](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L50-L533) file.\n\n```c++\nstruct TORCH_API Node : std::enable_shared_from_this {\n ...\n /// Evaluates the function on the given inputs and returns the result of the\n /// function call.\n variable_list operator()(variable_list&& inputs) {\n ...\n }\n\nprotected:\n /// Performs the `Node`'s actual operation.\n virtual variable_list apply(variable_list&& inputs) = 0;\n \u2026\n edge_list next_edges_;\n```\n\nEssentially we see that it has an override of the `operator ()` that performs the call to the actual function, and a pure virtual function called `apply`. The automatically generated functions override this `apply` method as we saw in the `MulBackward0` example above. Finally, the node also has a list of edges to enable graph connectivity.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "The [Edge](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/edge.h#L14-L39) object is used to link `Node`s together and its implementation is straightforward.\n\n```c++\nstruct Edge {\n ...\n /// The function this `Edge` points to.\n std::shared_ptr function;\n /// The identifier of a particular input to the function.\n uint32_t input_nr;\n};\n```\n\nIt only requires a function pointer (the actual `grad_fn` objects that the edges link together), and an input number that acts as an id for the edge.\n\n### Linking nodes together\n\nWhen we invoke the product operation of two tensors, we enter into the realm of autogenerated code. All the scripts that we saw in `tools/autograd` fill a series of templates that wrap the differentiable functions in ATen. These functions have code to construct the backward graph during the forward pass.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "The [gen_variable_type.py](https://github.com/pytorch/pytorch/blob/release/1.9/tools/autograd/gen_variable_type.py) script is in charge of writing all this wrapping code. This script is called from the [tools/autograd/gen_autograd.py](https://github.com/pytorch/pytorch/blob/release/1.9/tools/autograd/gen_autograd.py) during the pytorch build process and it will output the automatically generated function wrappers to `torch/csrc/autograd/generated/`.\n\n\n\nLet\u2019s take a look at how the tensor multiplication generated function looks like. The code has been simplified, but it can be found in the `torch/csrc/autograd/generated/VariableType_4.cpp` file when compiling pytorch from source.\n\n```c++\nat::Tensor mul_Tensor(c10::DispatchKeySet ks, const at::Tensor & self, const at::Tensor & other) {\n ...\n auto _any_requires_grad = compute_requires_grad( self, other );\n std::shared_ptr grad_fn;\n if (_any_requires_grad) {", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "if (_any_requires_grad) {\n // Creates the link to the actual grad_fn and links the graph for backward traversal\n grad_fn = std::shared_ptr(new MulBackward0(), deleteNode);\n grad_fn->set_next_edges(collect_next_edges( self, other ));\n ...\n }\n \u2026\n // Does the actual function call to ATen\n auto _tmp = ([&]() {\n at::AutoDispatchBelowADInplaceOrView guard;\n return at::redispatch::mul(ks & c10::after_autograd_keyset, self_, other_);\n })();\n\n auto result = std::move(_tmp);\n if (grad_fn) {\n // Connects the result to the graph\n set_history(flatten_tensor_args( result ), grad_fn);\n }\n ...\n return result;\n}\n```\n\nLet\u2019s walk through the most important lines of this code.\nFirst of all, the `grad_fn` object is created with: ` grad_fn = std::shared_ptr(new MulBackward0(), deleteNode);`.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "After the `grad_fn` object is created, the edges used to link the nodes together are created by using the `grad_fn->set_next_edges(collect_next_edges( self, other ));` calls.\n\n```c++\nstruct MakeNextFunctionList : IterArgs {\n edge_list next_edges;\n using IterArgs::operator();\n void operator()(const Variable& variable) {\n if (variable.defined()) {\n next_edges.push_back(impl::gradient_edge(variable));\n } else {\n next_edges.emplace_back();\n }\n }\n void operator()(const c10::optional& variable) {\n if (variable.has_value() && variable->defined()) {\n next_edges.push_back(impl::gradient_edge(*variable));\n } else {\n next_edges.emplace_back();\n }\n }\n};\n\ntemplate \nedge_list collect_next_edges(Variables&&... variables) {\n detail::MakeNextFunctionList make;\n make.apply(std::forward(variables)...);\n return std::move(make.next_edges);\n}\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "return std::move(make.next_edges);\n}\n```\n\nGiven an input variable (it\u2019s just a regular tensor), [`collect_next_edges`](\nhttps://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L597-L603)\n will create an `Edge` object by calling [`impl::gradient_edge`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/variable.cpp#L228-L240.)\n\n```c++\n Edge gradient_edge(const Variable& self) {\n // If grad_fn is null (as is the case for a leaf node), we instead\n // interpret the gradient function to be a gradient accumulator, which will\n // accumulate its inputs into the grad property of the variable. These\n // nodes get suppressed in some situations, see \"suppress gradient\n // accumulation\" below. Note that only variables which have `requires_grad =\n // True` can have gradient accumulators.\n if (const auto& gradient = self.grad_fn()) {\n return Edge(gradient, self.output_nr());\n } else {", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "} else {\n return Edge(grad_accumulator(self), 0);\n }\n }\n```\n\nTo understand how edges work, let\u2019s assume that an early executed function produced two output tensors, both with their `grad_fn` set, each tensor also has an `output_nr` property with the order in which they were returned. When creating the edges for the current `grad_fn`, an `Edge` object per input variable will be created. The edges will point to the variable\u2019s grad_fn and will also track the `output_nr` to establish ids used when traversing the graph. In the case that the input variables are \u201cleaf\u201d, i.e. they were not produced by any differentiable function, they don\u2019t have a `grad_fn` attribute set. A special function called a gradient accumulator is set by default as seen in the above code snippet.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "After the edges are created, the `grad_fn` graph Node object that is being currently created will hold them using the [`set_next_edges`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/function.h#L258-L263) function. This is what connects `grad_fn`s together, producing the computational graph.\n\n```c++\n void set_next_edges(edge_list&& next_edges) {\n next_edges_ = std::move(next_edges);\n for(const auto& next_edge : next_edges_) {\n update_topological_nr(next_edge);\n }\n }\n```\n\nNow, the forward pass of the function will execute, and after the execution `set_history` will connect the output tensors to the `grad_fn` Node. \n\n```c++\ninline void set_history(\n at::Tensor& variable,\n const std::shared_ptr& grad_fn) {\n AT_ASSERT(grad_fn);\n if (variable.defined()) {\n // If the codegen triggers this, you most likely want to add your newly added function\n // to the DONT_REQUIRE_DERIVATIVE list in tools/autograd/gen_variable_type.py", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "TORCH_INTERNAL_ASSERT(isDifferentiableType(variable.scalar_type()));\n auto output_nr =\n grad_fn->add_input_metadata(variable);\n impl::set_gradient_edge(variable, {grad_fn, output_nr});\n } else {\n grad_fn->add_input_metadata(Node::undefined_input());\n }\n}\n```\n\n[`set_history`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/functions/utils.h#L58-L72) calls [`set_gradient_edge`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/variable.cpp#L242-L255), which just copies the grad_fn and the `output_nr` to the `AutogradMeta` object that the tensor has.\n\n```c++\n void set_gradient_edge(const Variable& self, Edge edge) {\n auto* meta = materialize_autograd_meta(self);\n meta->grad_fn_ = std::move(edge.function);\n meta->output_nr_ = edge.input_nr;\n // For views, make sure this new grad_fn_ is not overwritten unless it is necessary\n // in the VariableHooks::grad_fn below.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "// in the VariableHooks::grad_fn below.\n // This logic is only relevant for custom autograd Functions for which multiple\n // operations can happen on a given Tensor before its gradient edge is set when\n // exiting the custom Function.\n auto diff_view_meta = get_view_autograd_meta(self);\n if (diff_view_meta && diff_view_meta->has_bw_view()) {\n diff_view_meta->set_attr_version(self._version());\n }\n }\n```\n\nThis tensor now will be the input to another function and the above steps will be all repeated. Check the animation below to see how the graph is created.\n\n\n
\n
\nFigure 2: Animation that shows the graph creation\n
\n\n### Registering Python Functions in the graph\n\nWe have seen how autograd creates the graph for the functions included in ATen. However, when we define our differentiable functions in Python, they are also included in the graph!", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "An autograd python defined function looks like the following:\n\n```python\nclass Exp(torch.autograd.Function):\n @staticmethod\n def forward(ctx, i):\n result = i.exp()\n ctx.save_for_backward(result)\n return result\n\n @staticmethod\n def backward(ctx, grad_output):\n result, = ctx.saved_tensors\n return grad_output * result\n\n# Call the function\nExp.apply(torch.tensor(0.5, requires_grad=True))\n# Outputs: tensor(1.6487, grad_fn=)\n```\n\nIn the above snippet autograd detected our python function when creating the graph. All of this is possible thanks to the [`Function`](https://github.com/pytorch/pytorch/blob/release/1.9/torch/autograd/function.py#L106) class. Let\u2019s take a look at what happens when we call `apply`.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "`apply` is defined in the [`torch._C._FunctionBase`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L859-L908) class, but this class is not present in the python source. `_FunctionBase` is defined in C++ by using the python C API to hook C functions together into a single python class. We are looking for a function named [`THPFunction_apply`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L577-L633). \n\n```c++\n\nPyObject *THPFunction_apply(PyObject *cls, PyObject *inputs)\n{\n \n // Generates the graph node\n THPObjectPtr backward_cls(PyObject_GetAttrString(cls, \"_backward_cls\"));\n if (!backward_cls) return nullptr;\n THPObjectPtr ctx_obj(PyObject_CallFunctionObjArgs(backward_cls, nullptr));\n if (!ctx_obj) return nullptr;\n THPFunction* ctx = (THPFunction*)ctx_obj.get();\n\n auto cdata = std::shared_ptr(new PyNode(std::move(ctx_obj)), deleteNode);", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "ctx->cdata = cdata;\n\n // Prepare inputs and allocate context (grad fn)\n // Unpack inputs will collect the edges\n auto info_pair = unpack_input(inputs);\n UnpackedInput& unpacked_input = info_pair.first;\n InputFlags& input_info = info_pair.second;\n\n // Initialize backward function (and ctx)\n bool is_executable = input_info.is_executable;\n cdata->set_next_edges(std::move(input_info.next_edges));\n ctx->needs_input_grad = input_info.needs_input_grad.release();\n ctx->is_variable_input = std::move(input_info.is_variable_input);\n\n // Prepend ctx to input_tuple, in preparation for static method call\n auto num_args = PyTuple_GET_SIZE(inputs);\n THPObjectPtr ctx_input_tuple(PyTuple_New(num_args + 1));\n if (!ctx_input_tuple) return nullptr;\n Py_INCREF(ctx);\n PyTuple_SET_ITEM(ctx_input_tuple.get(), 0, (PyObject*)ctx);\n for (int i = 0; i < num_args; ++i) {\n PyObject *arg = PyTuple_GET_ITEM(unpacked_input.input_tuple.get(), i);\n Py_INCREF(arg);", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "Py_INCREF(arg);\n PyTuple_SET_ITEM(ctx_input_tuple.get(), i + 1, arg);\n }\n\n // Call forward\n THPObjectPtr tensor_outputs;\n {\n AutoGradMode grad_mode(false);\n THPObjectPtr forward_fn(PyObject_GetAttrString(cls, \"forward\"));\n if (!forward_fn) return nullptr;\n tensor_outputs = PyObject_CallObject(forward_fn, ctx_input_tuple);\n if (!tensor_outputs) return nullptr;\n }\n\n // Here is where the outputs gets the tensors tracked\n return process_outputs(cls, cdata, ctx, unpacked_input, inputs, std::move(tensor_outputs),\n is_executable, node);\n END_HANDLE_TH_ERRORS\n}\n```\n \nAlthough this code is hard to read at first due to all the python API calls, it essentially does the same thing as the auto-generated forward functions that we saw for ATen:\n\nCreate a `grad_fn` object.\nCollect the edges to link the current `grad_fn` with the input tensors one.\nExecute the function `forward`.\nAssign the created `grad_fn` to the output tensors metadata.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "The `grad_fn` object is created in:\n\n```c++\n // Generates the graph node\n THPObjectPtr backward_cls(PyObject_GetAttrString(cls, \"_backward_cls\"));\n if (!backward_cls) return nullptr;\n THPObjectPtr ctx_obj(PyObject_CallFunctionObjArgs(backward_cls, nullptr));\n if (!ctx_obj) return nullptr;\n THPFunction* ctx = (THPFunction*)ctx_obj.get();\n\n auto cdata = std::shared_ptr(new PyNode(std::move(ctx_obj)), deleteNode);\n ctx->cdata = cdata;\n```", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "ctx->cdata = cdata;\n```\n\nBasically, it asks the python API to get a pointer to the Python object that can execute the user-written function. Then it wraps it into a [`PyNode`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.h#L24-L58) object that is a specialized `Node` object that calls the python interpreter with the provided python function when `apply` is executed during the forward pass. Note that in the code `cdata` is the actual `Node` object that is part of the graph. `ctx` is the object that is passed to the python `forward`/`backward` functions and it is used to store autograd related information by both, the user\u2019s function and PyTorch.\n\nAs in the regular C++ functions we also call `collect_next_edges` to track the inputs `grad_fn` objects, but this is done in [`unpack_input`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L413-L448):\n\n```c++", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "```c++\ntemplate\nstd::pair unpack_input(PyObject *args) {\n ...\n flags.next_edges = (flags.is_executable ? collect_next_edges(unpacked.input_vars) : edge_list());\n return std::make_pair(std::move(unpacked), std::move(flags));\n}\n```\n\nAfter this, the edges are assigned to the `grad_fn` by just doing `cdata->set_next_edges(std::move(input_info.next_edges));` and the forward function is called through the python interpreter C API.\n\nOnce the output tensors are returned from the forward pass, they are processed and converted to variables inside the [`process_outputs`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L519-L562) function.\n\n```c++\nPyObject* process_outputs(PyObject *op_obj, const std::shared_ptr& cdata,\n THPFunction* grad_fn, const UnpackedInput& unpacked,\n PyObject *inputs, THPObjectPtr&& raw_output, bool is_executable,", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "torch::jit::Node* node) {\n ...\n _wrap_outputs(cdata, grad_fn, unpacked.input_vars, raw_output, outputs, is_executable);\n _trace_post_record(node, op_obj, unpacked.input_vars, outputs, is_inplace, unpack_output);\n if (is_executable) {\n _save_variables(cdata, grad_fn);\n } ...\n return outputs.release();\n}\n```\n\nHere, [`_wrap_outputs`](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/python_function.cpp#L302-L346) is in charge of setting the forward outputs `grad_fn` to the newly created one. For this, it calls another `_wrap_outputs` function defined in a different [file](https://github.com/pytorch/pytorch/blob/e7cd59c7a061c78d8d0265e4308b5933e44f9176/torch/csrc/autograd/custom_function.cpp#L28-L105), so the process here gets a little confusing.\n\n```c++\nstatic void _wrap_outputs(const std::shared_ptr& cdata, THPFunction *self,", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "const variable_list &input_vars, PyObject *raw_output, PyObject *outputs, bool is_executable)\n{\n auto cdata_if_executable = is_executable ? cdata : nullptr;\n ...\n\n // Wrap only the tensor outputs.\n // This calls csrc/autograd/custom_function.cpp\n auto wrapped_outputs = _wrap_outputs(input_vars, non_differentiable, dirty_inputs, raw_output_vars, cdata_if_executable);\n...\n}\n```\n\nThe called `_wrap_outputs` is the one in charge of setting the autograd metadata in the output tensors:\n\n```c++\nstd::vector> _wrap_outputs(const variable_list &input_vars,\n const std::unordered_set &non_differentiable,\n const std::unordered_set &dirty_inputs,\n const at::ArrayRef> raw_outputs,\n const std::shared_ptr &cdata) {\n\n\n std::unordered_set inputs;\n \u2026\n // Sets the grad_fn and output_nr of an output Variable.\n auto set_history = [&](Variable& var, uint32_t output_nr, bool is_input, bool is_modified,", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "bool is_differentiable) {\n // Lots of checks\n if (!is_differentiable) {\n ...\n } else if (is_input) {\n // An input has been returned, but it wasn't modified. Return it as a view\n // so that we can attach a new grad_fn to the Variable.\n // Run in no_grad mode to mimic the behavior of the forward.\n {\n AutoGradMode grad_mode(false);\n var = var.view_as(var);\n }\n impl::set_gradient_edge(var, {cdata, output_nr});\n } else if (cdata) {\n impl::set_gradient_edge(var, {cdata, output_nr});\n }\n };\n```\n\nAnd this is where `set_gradient_edge` was called and this is how a user-written python function gets included in the computational graph with its associated backward function!\n\n# Closing remarks\n\nThis blog post is intended to be a code overview on how PyTorch constructs the actual computational graphs that we discussed in the previous post. The next entry will deal with how the autograd engine executes these graphs.", "metadata": {"source": "https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Efficient Multi-Objective Neural Architecture Search with Ax\"\nauthor: David Eriksson, Max Balandat\nfeatured-img: \"/assets/images/MOO-NAS-blog-img2-pareto_frontier_plot.png\"\n---\n\n## tl;dr\n\nMulti-Objective Optimization in Ax enables efficient exploration of tradeoffs (e.g. between model performance and model size or latency) in Neural Architecture Search. This method has been successfully applied at Meta for a variety of products such as On-Device AI. In this post, we provide an [end-to-end](https://pytorch.org/tutorials/intermediate/ax_multiobjective_nas_tutorial.html) tutorial that allows you to try it out yourself.\n\n## Introduction", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "## Introduction\n\nNeural networks continue to grow in both size and complexity. Developing state-of-the-art architectures is often a cumbersome and time-consuming process that requires both domain expertise and large engineering efforts. In an attempt to overcome these challenges, several Neural Architecture Search (NAS) approaches have been proposed to automatically design well-performing architectures without requiring a human in-the-loop.", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "Despite being very sample-inefficient, na\u00efve approaches like random search and grid search are still popular for both hyperparameter optimization and NAS (a [study](https://hal.archives-ouvertes.fr/hal-02447823/document) conducted at NeurIPS 2019 and ICLR 2020 found that 80% of NeurIPS papers and 88% of ICLR papers tuned their ML model hyperparameters using manual tuning, random search, or grid search). But as models are often time-consuming to train and may require large amounts of computational resources, minimizing the number of configurations that are evaluated is important.", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
@@ -661,13 +658,13 @@
{"page_content": "- Customizability of parallelism, failure tolerance, and many other settings;\n\n- A large selection of state-of-the-art optimization algorithms;\n\n- Saving in-progress experiments (to a SQL DB or json) and resuming an experiment from storage;\n\n- Easy extensibility to new backends for running trial evaluations remotely.\n\nThe following illustration from the [Ax scheduler tutorial](https://ax.dev/tutorials/scheduler.html) summarizes how the scheduler interacts with any external system used to run trial evaluations:\n\n\n\n\n
\n
\n\nTo run automated NAS with the Scheduler, the main things we need to do are:", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "- Define a [Runner](https://github.com/facebook/Ax/blob/main/ax/core/runner.py#L21), which is responsible for sending off a model with a particular architecture to be trained on a platform of our choice (like Kubernetes, or maybe just a Docker image on our local machine). In the tutorial below, we use TorchX for handling deployment of training jobs.\n\n- Define a [Metric](https://github.com/facebook/Ax/blob/main/ax/core/metric.py#L21), which is responsible for fetching the objective metrics (such as accuracy, model size, latency) from the training job. In our tutorial, we use Tensorboard to log data, and so can use the Tensorboard metrics that come bundled with Ax.\n\n## Tutorial", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "## Tutorial\n\nIn our tutorial we show how to use Ax to run multi-objective NAS for a simple neural network model on the popular MNIST dataset. While the underlying methodology can be used for more complicated models and larger datasets, we opt for a tutorial that is easily runnable end-to-end on a laptop in less than an hour. In our example, we will tune the widths of two hidden layers, the learning rate, the dropout probability, the batch size, and the number of training epochs. The goal is to trade off performance (accuracy on the validation set) and model size (the number of model parameters) using [multi-objective Bayesian optimization](https://proceedings.neurips.cc/paper/2021/file/11704817e347269b7254e744b5e22dac-Paper.pdf).\n\nThe tutorial makes use of the following PyTorch libraries:\n\n- [PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) (specifying the model and training loop)\n\n- [TorchX](https://github.com/pytorch/torchx) (for running training jobs remotely / asynchronously)", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
-{"page_content": "- [BoTorch](https://github.com/pytorch/botorch) (the Bayesian optimization library that powers Ax\u2019s algorithms)\n\nThe complete runnable example is available as a **[PyTorch Tutorial](https://pytorch.org/tutorials/intermediate/ax_multiobjective_nas_tutorial.html)**.\n\n### Results\n\nThe final results from the NAS optimization performed in the tutorial can be seen in the tradeoff plot below. Here, each point corresponds to the result of a trial, with the color representing its iteration number, and the star indicating the reference point defined by the thresholds we imposed on the objectives. We see that our method was able to successfully explore the trade-offs between validation accuracy and number of parameters and found both large models with high validation accuracy as well as small models with lower validation accuracy. Depending on the performance requirements and model size constraints, the decision maker can now choose which model to use or analyze further.", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
+{"page_content": "- [BoTorch](https://github.com/pytorch/botorch) (the Bayesian optimization library that powers Ax\u2019s algorithms)\n\nThe complete runnable example is available as a **[PyTorch Tutorial](https://pytorch.org/tutorials/intermediate/ax_multiobjective_nas_tutorial.html)**.\n\n### Results\n\nThe final results from the NAS optimization performed in the tutorial can be seen in the tradeoff plot below. Here, each point corresponds to the result of a trial, with the color representing its iteration number, and the star indicating the reference point defined by the thresholds we imposed on the objectives. We see that our method was able to successfully explore the trade-offs between validation accuracy and number of parameters and found both large models with high validation accuracy as well as small models with lower validation accuracy. Depending on the performance requirements and model size constraints, the decision maker can now choose which model to use or analyze further.\n\n", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\n\n### Visualizations\n\nAx provides a number of visualizations that make it possible to analyze and understand the results of an experiment. Here, we will focus on the performance of the Gaussian process models that model the unknown objectives, which are used to help us discover promising configurations faster. Ax makes it easy to better understand how accurate these models are and how they perform on unseen data via leave-one-out cross-validation. In the figures below, we see that the model fits look quite good - predictions are close to the actual outcomes, and predictive 95% confidence intervals cover the actual outcomes well. Additionally, we observe that the model size `(num_params)` metric is much easier to model than the validation accuracy `(val_acc)` metric.\n\n\n\n", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
-{"page_content": "\n\n\n
\n
\n
\n\n
\n
\n
\n
\n\n## Takeaways\n\n- We showed how to run a fully automated multi-objective Neural Architecture Search using Ax.\n\n- Using the Ax Scheduler, we were able to run the optimization automatically in a fully asynchronous fashion - this can be done locally (as done in the tutorial) or by deploying trials remotely to a cluster (simply by changing the TorchX scheduler configuration).\n\n- The state-of-the-art multi-objective Bayesian optimization algorithms available in Ax allowed us to efficiently explore the tradeoffs between validation accuracy and model size.\n\n## Advanced Functionality\n\nAx has a number of other advanced capabilities that we did not discuss in our tutorial. Among these are the following:\n\n### Early Stopping", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
+{"page_content": "flex-direction:row; \n }\n\n\n\n\n
\n
\n
\n\n
\n
\n
\n
\n\n## Takeaways\n\n- We showed how to run a fully automated multi-objective Neural Architecture Search using Ax.\n\n- Using the Ax Scheduler, we were able to run the optimization automatically in a fully asynchronous fashion - this can be done locally (as done in the tutorial) or by deploying trials remotely to a cluster (simply by changing the TorchX scheduler configuration).\n\n- The state-of-the-art multi-objective Bayesian optimization algorithms available in Ax allowed us to efficiently explore the tradeoffs between validation accuracy and model size.\n\n## Advanced Functionality\n\nAx has a number of other advanced capabilities that we did not discuss in our tutorial. Among these are the following:\n\n### Early Stopping", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "### Early Stopping\n\nWhen evaluating a new candidate configuration, partial learning curves are typically available while the NN training job is running. We can use the information contained in the partial curves to identify under-performing trials to stop early in order to free up computational resources for more promising candidates. While not demonstrated in the above tutorial, Ax supports early stopping out-of-the-box - see our [early stopping tutorial](https://ax.dev/versions/latest/tutorials/early_stopping/early_stopping.html) for more details.\n\n### High-dimensional search spaces", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "### High-dimensional search spaces\n\nIn our tutorial, we used Bayesian optimization with a standard Gaussian process in order to keep the runtime low. However, these models typically scale to only about 10-20 tunable parameters. Our new SAASBO method ([paper](https://proceedings.mlr.press/v161/eriksson21a/eriksson21a.pdf), [Ax tutorial](https://ax.dev/tutorials/saasbo.html), [BoTorch tutorial](https://botorch.org/tutorials/saasbo)) is very sample-efficient and enables tuning hundreds of parameters. SAASBO can easily be enabled by passing `use_saasbo=True` to `choose_generation_strategy`.\n\n## Acknowledgements\n\nWe thank the TorchX team (in particular Kiuk Chung and Tristan Rice) for their help with integrating TorchX with Ax, and the Adaptive Experimentation team @ Meta for their contributions to Ax and BoTorch.\n\n## References", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
{"page_content": "## References\n\n[D. Eriksson, P. Chuang, S. Daulton, M. Balandat. Optimizing model accuracy and latency using Bayesian multi-objective neural architecture search. Meta Research blog, July 2021.](https://research.facebook.com/blog/2021/07/optimizing-model-accuracy-and-latency-using-bayesian-multi-objective-neural-architecture-search/)", "metadata": {"source": "https://pytorch.org/blog/effective-multi-objective-nueral-architecture/", "category": "pytorch blogs"}}
-{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch Adds New Ecosystem Projects for Encrypted AI and Quantum Computing, Expands PyTorch Hub'\nauthor: Team PyTorch\n---\n\nThe PyTorch ecosystem includes projects, tools, models and libraries from a broad community of researchers in academia and industry, application developers, and ML engineers. The goal of this ecosystem is to support, accelerate, and aid in your exploration with PyTorch and help you push the state of the art, no matter what field you are exploring. Similarly, we are expanding the recently launched PyTorch Hub to further help you discover and reproduce the latest research.\n\nIn this post, we\u2019ll highlight some of the projects that have been added to the PyTorch ecosystem this year and provide some context on the criteria we use to evaluate community projects. We\u2019ll also provide an update on the fast-growing PyTorch Hub and share details on our upcoming PyTorch Summer Hackathon.", "metadata": {"source": "https://pytorch.org/blog/pytorch-ecosystem/", "category": "pytorch blogs"}}
+{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch Adds New Ecosystem Projects for Encrypted AI and Quantum Computing, Expands PyTorch Hub'\nauthor: Team PyTorch\n---\n\nThe PyTorch ecosystem includes projects, tools, models and libraries from a broad community of researchers in academia and industry, application developers, and ML engineers. The goal of this ecosystem is to support, accelerate, and aid in your exploration with PyTorch and help you push the state of the art, no matter what field you are exploring. Similarly, we are expanding the recently launched PyTorch Hub to further help you discover and reproduce the latest research.\n\nIn this post, we\u2019ll highlight some of the projects that have been added to the PyTorch ecosystem this year and provide some context on the criteria we use to evaluate community projects. We\u2019ll also provide an update on the fast-growing PyTorch Hub and share details on our upcoming PyTorch Summer Hackathon.\n\n", "metadata": {"source": "https://pytorch.org/blog/pytorch-ecosystem/", "category": "pytorch blogs"}}
{"page_content": "
\n

\n
\n\n## Recently added ecosystem projects\n\nFrom private AI to quantum computing, we\u2019ve seen the community continue to expand into new and interesting areas. The latest projects include:\n\n- [Advertorch](https://github.com/BorealisAI/advertorch): A Python toolbox for adversarial robustness research. The primary functionalities are implemented in PyTorch. Specifically, AdverTorch contains modules for generating adversarial perturbations and defending against adversarial examples, as well as scripts for adversarial training.\n\n- [botorch](https://botorch.org/): A modular and easily extensible interface for composing Bayesian optimization primitives, including probabilistic models, acquisition functions, and optimizers.\n\n- [Skorch](https://github.com/skorch-dev/skorch): A high-level library for PyTorch that provides full scikit-learn compatibility.", "metadata": {"source": "https://pytorch.org/blog/pytorch-ecosystem/", "category": "pytorch blogs"}}
{"page_content": "- [PyTorch Geometric](https://github.com/rusty1s/pytorch_geometric): A library for deep learning on irregular input data such as graphs, point clouds, and manifolds.\n\n- [PySyft](https://github.com/OpenMined/PySyft): A Python library for encrypted, privacy preserving deep learning.\n\n- [PennyLane](https://pennylane.ai/): A library for quantum ML, automatic differentiation, and optimization of hybrid quantum-classical computations.\n\n- [Flair](https://github.com/zalandoresearch/flair): A very simple framework for state-of-the-art natural language processing (NLP).\n\n### What makes a great project?\n\nWhen we review project submissions for the PyTorch ecosystem, we take into account a number of factors that we feel are important and that we would want in the projects we use ourselves. Some of these criteria include:", "metadata": {"source": "https://pytorch.org/blog/pytorch-ecosystem/", "category": "pytorch blogs"}}
{"page_content": "1. *Well-tested:* Users should be confident that ecosystem projects will work well with PyTorch, and include support for CI to ensure that testing is occurring on a continuous basis and the project can run on the latest version of PyTorch.\n2. *Clear utility:* Users should understand where each project fits within the PyTorch ecosystem and the value it brings.\n3. *Permissive licensing:* Users must be able to utilize ecosystem projects without licensing concerns. e.g. BSD-3, Apache-2 and MIT licenses\n4. *Easy onboarding:* Projects need to have support for binary installation options (pip/Conda), clear documentation and a rich set of tutorials (ideally built into Jupyter notebooks).\n5. *Ongoing maintenance:* Project authors need to be committed to supporting and maintaining their projects.\n6. *Community:* Projects should have (or be on track to building) an active, broad-based community.", "metadata": {"source": "https://pytorch.org/blog/pytorch-ecosystem/", "category": "pytorch blogs"}}
@@ -679,10 +676,10 @@
{"page_content": "---\nlayout: blog_detail\ntitle: 'PipeTransformer: Automated Elastic Pipelining for Distributed Training of Large-scale Models'\nauthor: Chaoyang He, Shen Li, Mahdi Soltanolkotabi, and Salman Avestimehr\nfeatured-img: 'assets/images/pipetransformer_overview.png'\n---\n\nIn this blog post, we describe the first peer-reviewed research paper that explores accelerating the hybrid of PyTorch DDP (`torch.nn.parallel.DistributedDataParallel`) [1] and Pipeline (`torch.distributed.pipeline`) - [PipeTransformer: Automated Elastic Pipelining for Distributed Training of Large-scale Models](http://proceedings.mlr.press/v139/he21a.html) (Transformers such as BERT [2] and ViT [3]), published at ICML 2021.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "PipeTransformer leverages automated elastic pipelining for efficient distributed training of Transformer models. In PipeTransformer, we designed an adaptive on-the-fly freeze algorithm that can identify and freeze some layers gradually during training and an elastic pipelining system that can dynamically allocate resources to train the remaining active layers. More specifically, PipeTransformer automatically excludes frozen layers from the pipeline, packs active layers into fewer GPUs, and forks more replicas to increase data-parallel width. We evaluate PipeTransformer using Vision Transformer (ViT) on ImageNet and BERT on SQuAD and GLUE datasets. Our results show that compared to the state-of-the-art baseline, PipeTransformer attains up to 2.83-fold speedup without losing accuracy. We also provide various performance analyses for a more comprehensive understanding of our algorithmic and system-wise design.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "Next, we will introduce the background, motivation, our idea, design, and how we implement the algorithm and system with PyTorch Distributed APIs.\n\n* Paper: [http://proceedings.mlr.press/v139/he21a.html](http://proceedings.mlr.press/v139/he21a.html)\n* Source Code: [https://DistML.ai](https://distml.ai).\n* Slides: [https://docs.google.com/presentation/d/1t6HWL33KIQo2as0nSHeBpXYtTBcy0nXCoLiKd0EashY/edit?usp=sharing](https://docs.google.com/presentation/d/1t6HWL33KIQo2as0nSHeBpXYtTBcy0nXCoLiKd0EashY/edit?usp=sharing)\n\n# Introduction\n
\n
\n
\nFigure 1: the Parameter Number of Transformer Models Increases Dramatically.\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "Large Transformer models [4][5] have powered accuracy breakthroughs in both natural language processing and computer vision. GPT-3 [4] hit a new record high accuracy for nearly all NLP tasks. Vision Transformer (ViT) [3] also achieved 89\\% top-1 accuracy in ImageNet, outperforming state-of-the-art convolutional networks ResNet-152 and EfficientNet. To tackle the growth in model sizes, researchers have proposed various distributed training techniques, including parameter servers [6][7][8], pipeline parallelism [9][10][11][12], intra-layer parallelism [13][14][15], and zero redundancy data-parallel [16].\n\n\nExisting distributed training solutions, however, only study scenarios where all model weights are required to be optimized throughout the training (i.e., computation and communication overhead remains relatively static over different iterations). Recent works on
progressive training suggest that parameters in neural networks can be trained dynamically:", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "\n\n\nLarge Transformer models [4][5] have powered accuracy breakthroughs in both natural language processing and computer vision. GPT-3 [4] hit a new record high accuracy for nearly all NLP tasks. Vision Transformer (ViT) [3] also achieved 89\\% top-1 accuracy in ImageNet, outperforming state-of-the-art convolutional networks ResNet-152 and EfficientNet. To tackle the growth in model sizes, researchers have proposed various distributed training techniques, including parameter servers [6][7][8], pipeline parallelism [9][10][11][12], intra-layer parallelism [13][14][15], and zero redundancy data-parallel [16].\n\n\nExisting distributed training solutions, however, only study scenarios where all model weights are required to be optimized throughout the training (i.e., computation and communication overhead remains relatively static over different iterations). Recent works on
progressive training suggest that parameters in neural networks can be trained dynamically:", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "* Freeze Training: Singular Vector Canonical Correlation Analysis for Deep Learning Dynamics and Interpretability. NeurIPS 2017\n* Efficient Training of BERT by Progressively Stacking. ICML 2019\n* Accelerating Training of Transformer-Based Language Models with Progressive Layer Dropping. NeurIPS 2020.\n* On the Transformer Growth for Progressive BERT Training. NACCL 2021\n\n\n
\n
\n
\n
\nFigure 2. Interpretable Freeze Training: DNNs converge bottom-up (Results on CIFAR10 using ResNet). Each pane shows layer-by-layer similarity using SVCCA [17][18]", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "For example, in freeze training [17][18], neural networks usually converge from the bottom-up (i.e., not all layers need to be trained all the way through training). Figure 2 shows an example of how weights gradually stabilize during training in this approach. This observation motivates us to utilize freeze training for distributed training of Transformer models to accelerate training by dynamically allocating resources to focus on a shrinking set of active layers. Such a layer freezing strategy is especially pertinent to pipeline parallelism, as excluding consecutive bottom layers from the pipeline can reduce computation, memory, and communication overhead.\n\n
\n
\n
\nFigure 3. The process of PipeTransformer\u2019s automated and elastic pipelining to accelerate distributed training of Transformer models\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "We propose PipeTransformer, an elastic pipelining training acceleration framework that automatically reacts to frozen layers by dynamically transforming the scope of the pipelined model and the number of pipeline replicas. To the best of our knowledge, this is the first paper that studies layer freezing in the context of both pipeline and data-parallel training. Figure 3 demonstrates the benefits of such a combination. First, by excluding frozen layers from the pipeline, the same model can be packed into fewer GPUs, leading to both fewer cross-GPU communications and smaller pipeline bubbles. Second, after packing the model into fewer GPUs, the same cluster can accommodate more pipeline replicas, increasing the width of data parallelism. More importantly, the speedups acquired from these two benefits are multiplicative rather than additive, further accelerating the training.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "\n\n\nWe propose PipeTransformer, an elastic pipelining training acceleration framework that automatically reacts to frozen layers by dynamically transforming the scope of the pipelined model and the number of pipeline replicas. To the best of our knowledge, this is the first paper that studies layer freezing in the context of both pipeline and data-parallel training. Figure 3 demonstrates the benefits of such a combination. First, by excluding frozen layers from the pipeline, the same model can be packed into fewer GPUs, leading to both fewer cross-GPU communications and smaller pipeline bubbles. Second, after packing the model into fewer GPUs, the same cluster can accommodate more pipeline replicas, increasing the width of data parallelism. More importantly, the speedups acquired from these two benefits are multiplicative rather than additive, further accelerating the training.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "The design of PipeTransformer faces four major challenges. First, the freeze algorithm must make on-the-fly and adaptive freezing decisions; however, existing work [17][18] only provides a posterior analysis tool. Second, the efficiency of pipeline re-partitioning results is influenced by multiple factors, including partition granularity, cross-partition activation size, and the chunking (the number of micro-batches) in mini-batches, which require reasoning and searching in a large solution space. Third, to dynamically introduce additional pipeline replicas, PipeTransformer must overcome the static nature of collective communications and avoid potentially complex cross-process messaging protocols when onboarding new processes (one pipeline is handled by one process). Finally, caching can save time for repeated forward propagation of frozen layers, but it must be shared between existing pipelines and newly added ones, as the system cannot afford to create and warm up a dedicated cache for each replica.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\nFigure 4: An Animation to Show the Dynamics of PipeTransformer\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "As shown in the animation (Figure 4), PipeTransformer is designed with four core building blocks to address the aforementioned challenges. First, we design a tunable and adaptive algorithm to generate signals that guide the selection of layers to freeze over different iterations (Freeze Algorithm). Once triggered by these signals, our elastic pipelining module (AutoPipe), then packs the remaining active layers into fewer GPUs by taking both activation sizes and variances of workloads across heterogeneous partitions (frozen layers and active layers) into account. It then splits a mini-batch into an optimal number of micro-batches based on prior profiling results for different pipeline lengths. Our next module, AutoDP, spawns additional pipeline replicas to occupy freed-up GPUs and maintains hierarchical communication process groups to attain dynamic membership for collective communications. Our final module, AutoCache, efficiently shares activations across existing and new data-parallel processes and automatically replaces stale caches during transitions.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
@@ -695,29 +692,29 @@
{"page_content": "PipeTransformer co-designs an on-the-fly freeze algorithm and an automated elastic pipelining training system that can dynamically transform the scope of the pipelined model and the number of pipeline replicas. The overall system architecture is illustrated in Figure 5. To support PipeTransformer\u2019s elastic pipelining, we maintain a customized version of PyTorch Pipeline. For data parallelism, we use PyTorch DDP as a baseline. Other libraries are standard mechanisms of an operating system (e.g.,multi-processing) and thus avoid specialized software or hardware customization requirements. To ensure the generality of our framework, we have decoupled the training system into four core components:
freeze algorithm,
AutoPipe,
AutoDP, and
AutoCache. The
freeze algorithm (grey) samples indicators from the training loop and makes layer-wise freezing decisions, which will be shared with
AutoPipe (green). AutoPipe is an elastic pipeline module that speeds up training by excluding frozen layers from the pipeline and packing the active layers into fewer GPUs (pink), leading to both fewer cross-GPU communications and smaller pipeline bubbles. Subsequently,
AutoPipe passes pipeline length information to
AutoDP (purple), which then spawns more pipeline replicas to increase data-parallel width, if possible. The illustration also includes an example in which AutoDP introduces a new replica (purple).
AutoCache (orange edges) is a cross-pipeline caching module, as illustrated by connections between pipelines. The source code architecture is aligned with Figure 5 for readability and generality.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "# Implementation Using PyTorch APIs\n\nAs can be seen from Figure 5, PipeTransformers contain four components: Freeze Algorithm, AutoPipe, AutoDP, and AutoCache. Among them, AutoPipe and AutoDP relies on PyTorch DDP (`torch.nn.parallel.DistributedDataParallel`) [1] and Pipeline (`torch.distributed.pipeline`), respectively. In this blog, we only highlight the key implementation details of AutoPipe and AutoDP. For details of Freeze Algorithm and AutoCache, please refer to our paper.\n\n## AutoPipe: Elastic Pipelining\n\nAutoPipe can accelerate training by excluding frozen layers from the pipeline and packing the active layers into fewer GPUs. This section elaborates on the key components of AutoPipe that dynamically 1) partition pipelines, 2) minimize the number of pipeline devices, and 3) optimize mini-batch chunk size accordingly.\n\n### Basic Usage of PyTorch Pipeline", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "### Basic Usage of PyTorch Pipeline\n\nBefore diving into details of AutoPipe, let us warm up the basic usage of PyTorch Pipeline (`torch.distributed.pipeline.sync.Pipe`, see [this tutorial](https://pytorch.org/docs/stable/pipeline.html)). More specially, we present a simple example to understand the design of Pipeline in practice:\n\n```python\n# Step 1: build a model including two linear layers\nfc1 = nn.Linear(16, 8).cuda(0)\nfc2 = nn.Linear(8, 4).cuda(1)\n\n# Step 2: wrap the two layers with nn.Sequential\nmodel = nn.Sequential(fc1, fc2)\n\n# Step 3: build Pipe (torch.distributed.pipeline.sync.Pipe)\nmodel = Pipe(model, chunks=8)\n\n# do training/inference\ninput = torch.rand(16, 16).cuda(0)\noutput_rref = model(input)\n```", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "In this basic example, we can see that before initializing `Pipe`, we need to partition the model `nn.Sequential` into multiple GPU devices and set optimal chunk number (`chunks`). Balancing computation time across partitions is critical to pipeline training speed, as skewed workload distributions across stages can lead to stragglers and forcing devices with lighter workloads to wait. The chunk number may also have a non-trivial influence on the throughput of the pipeline.\n\n\n### Balanced Pipeline Partitioning\n\nIn dynamic training system such as PipeTransformer, maintaining optimally balanced partitions in terms of parameter numbers does not guarantee the fastest training speed because other factors also play a crucial role:\n\n
\n
\n
\nFigure 6. The partition boundary is in the middle of a skip connection\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "output_rref = model(input)\n```\n\nIn this basic example, we can see that before initializing `Pipe`, we need to partition the model `nn.Sequential` into multiple GPU devices and set optimal chunk number (`chunks`). Balancing computation time across partitions is critical to pipeline training speed, as skewed workload distributions across stages can lead to stragglers and forcing devices with lighter workloads to wait. The chunk number may also have a non-trivial influence on the throughput of the pipeline.\n\n\n### Balanced Pipeline Partitioning\n\nIn dynamic training system such as PipeTransformer, maintaining optimally balanced partitions in terms of parameter numbers does not guarantee the fastest training speed because other factors also play a crucial role:\n\n
\n
\n
\nFigure 6. The partition boundary is in the middle of a skip connection\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "1.
Cross-partition communication overhead. Placing a partition boundary in the middle of a skip connection leads to additional communications since tensors in the skip connection must now be copied to a different GPU. For example, with BERT partitions in Figure 6, partition

must take intermediate outputs from both partition

and partition

. In contrast, if the boundary is placed after the addition layer, the communication overhead between partition

and

is visibly smaller. Our measurements show that having cross-device communication is more expensive than having slightly imbalanced partitions (see the Appendix in our paper). Therefore, we do not consider breaking skip connections (highlighted separately as an entire attention layer and MLP layer in green color at line 7 in Algorithm 1.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "2.
Frozen layer memory footprint. During training, AutoPipe must recompute partition boundaries several times to balance two distinct types of layers: frozen layers and active layers. The frozen layer's memory cost is a fraction of that inactive layer, given that the frozen layer does not need backward activation maps, optimizer states, and gradients. Instead of launching intrusive profilers to obtain thorough metrics on memory and computational cost, we define a tunable cost factor

to estimate the memory footprint ratio of a frozen layer over the same active layer. Based on empirical measurements in our experimental hardware, we set it to

.\n\n\n\n
\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "Based on the above two considerations, AutoPipe balances pipeline partitions based on parameter sizes. More specifically, AutoPipe uses a greedy algorithm to allocate all frozen and active layers to evenly distribute partitioned sublayers into

GPU devices. Pseudocode is described as the `load\\_balance()` function in Algorithm 1. The frozen layers are extracted from the original model and kept in a separate model instance

in the first device of a pipeline.\n\nNote that the partition algorithm employed in this paper is not the only option; PipeTransformer is modularized to work with any alternatives.\n\n\n### Pipeline Compression", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\nBased on the above two considerations, AutoPipe balances pipeline partitions based on parameter sizes. More specifically, AutoPipe uses a greedy algorithm to allocate all frozen and active layers to evenly distribute partitioned sublayers into

GPU devices. Pseudocode is described as the `load\\_balance()` function in Algorithm 1. The frozen layers are extracted from the original model and kept in a separate model instance

in the first device of a pipeline.\n\nNote that the partition algorithm employed in this paper is not the only option; PipeTransformer is modularized to work with any alternatives.\n\n\n### Pipeline Compression", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "### Pipeline Compression\n\nPipeline compression helps to free up GPUs to accommodate more pipeline replicas and reduce the number of cross-device communications between partitions. To determine the timing of compression, we can estimate the memory cost of the largest partition after compression, and then compare it with that of the largest partition of a pipeline at timestep

. To avoid extensive memory profiling, the compression algorithm uses the parameter size as a proxy for the training memory footprint. Based on this simplification, the criterion of pipeline compression is as follows:\n\n
\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "Once the freeze notification is received, AutoPipe will always attempt to divide the pipeline length

by 2 (e.g., from 8 to 4, then 2). By using

as the input, the compression algorithm can verify if the result satisfies the criterion in Equation (1). Pseudocode is shown in lines 25-33 in Algorithm 1. Note that this compression makes the acceleration ratio exponentially increase during training, meaning that if a GPU server has a larger number of GPUs (e.g., more than 8), the acceleration ratio will be further amplified.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "
\n
\n
\nFigure 7. Pipeline Bubble:
, and
denote forward, backward, and the optimizer update of micro-batch
on device
, respectively. The total bubble size in each iteration is
times per micro-batch forward and backward cost.\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "Additionally, such a technique can also speed up training by shrinking the size of pipeline bubbles. To explain bubble sizes in a pipeline, Figure 7 depicts how 4 micro-batches run through a 4-device pipeline

. In general, the total bubble size is
\")
times per micro-batch forward and backward cost. Therefore, it is clear that shorter pipelines have smaller bubble sizes.\n\n### Dynamic Number of Micro-Batches", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\nOnce the freeze notification is received, AutoPipe will always attempt to divide the pipeline length

by 2 (e.g., from 8 to 4, then 2). By using

as the input, the compression algorithm can verify if the result satisfies the criterion in Equation (1). Pseudocode is shown in lines 25-33 in Algorithm 1. Note that this compression makes the acceleration ratio exponentially increase during training, meaning that if a GPU server has a larger number of GPUs (e.g., more than 8), the acceleration ratio will be further amplified.\n\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\nFigure 7. Pipeline Bubble:
, and
denote forward, backward, and the optimizer update of micro-batch
on device
, respectively. The total bubble size in each iteration is
times per micro-batch forward and backward cost.\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "\n\nAdditionally, such a technique can also speed up training by shrinking the size of pipeline bubbles. To explain bubble sizes in a pipeline, Figure 7 depicts how 4 micro-batches run through a 4-device pipeline

. In general, the total bubble size is
\")
times per micro-batch forward and backward cost. Therefore, it is clear that shorter pipelines have smaller bubble sizes.\n\n### Dynamic Number of Micro-Batches", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "Prior pipeline parallel systems use a fixed number of micro-batches per mini-batch (

). GPipe suggests

, where

is the number of partitions (pipeline length). However, given that PipeTransformer dynamically configures

, we find it to be sub-optimal to maintain a static

during training. Moreover, when integrated with DDP, the value of

also has an impact on the efficiency of DDP gradient synchronizations. Since DDP must wait for the last micro-batch to finish its backward computation on a parameter before launching its gradient synchronization, finer micro-batches lead to a smaller overlap between computation and communication. Hence, instead of using a static value, PipeTransformer searches for optimal

on the fly in the hybrid of DDP environment by enumerating

values ranging from

to

. For a specific training environment, the profiling needs only to be done once (see Algorithm 1 line 35).", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "For the complete source code, please refer to `https://github.com/Distributed-AI/PipeTransformer/blob/master/pipe_transformer/pipe/auto_pipe.py`.\n\n## AutoDP: Spawning More Pipeline Replicas\nAs AutoPipe compresses the same pipeline into fewer GPUs, AutoDP can automatically spawn new pipeline replicas to increase data-parallel width.\n\nDespite the conceptual simplicity, subtle dependencies on communications and states require careful design. The challenges are threefold:\n\n1.
DDP Communication: Collective communications in PyTorch DDP requires static membership, which prevents new pipelines from connecting with existing ones;\n\n2.
State Synchronization: newly activated processes must be consistent with existing pipelines in the training progress (e.g., epoch number and learning rate), weights and optimizer states, the boundary of frozen layers, and pipeline GPU range;", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "3.
Dataset Redistribution: the dataset should be re-balanced to match a dynamic number of pipelines. This not only avoids stragglers but also ensures that gradients from all DDP processes are equally weighted.\n\n
\n
\n
\nFigure 8. AutoDP: handling dynamical data-parallel with messaging between double process groups (Process 0-7 belong to machine 0, while process 8-15 belong to machine 1)\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "To tackle these challenges, we create double communication process groups for DDP. As in the example shown in Figure 8, the message process group (purple) is responsible for light-weight control messages and covers all processes, while the active training process group (yellow) only contains active processes and serves as a vehicle for heavy-weight tensor communications during training. The message group remains static, whereas the training group is dismantled and reconstructed to match active processes.\nIn T0, only processes 0 and 8 are active. During the transition to T1, process 0 activates processes 1 and 9 (newly added pipeline replicas) and synchronizes necessary information mentioned above using the message group. The four active processes then form a new training group, allowing static collective communications adaptive to dynamic memberships.\nTo redistribute the dataset, we implement a variant of DistributedSampler that can seamlessly adjust data samples to match the number of active pipeline replicas.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "The above design also naturally helps to reduce DDP communication overhead. More specifically, when transitioning from T0 to T1, processes 0 and 1 destroy the existing DDP instances, and active processes construct a new DDP training group using a cached pipelined model (AutoPipe stores frozen model and cached model separately).\n\nWe use the following APIs to implement the design above.\n\n```python\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\n# initialize the process group (this must be called in the initialization of PyTorch DDP)\ndist.init_process_group(init_method='tcp://' + str(self.config.master_addr) + ':' +\nstr(self.config.master_port), backend=Backend.GLOO, rank=self.global_rank, world_size=self.world_size)\n...\n\n# create active process group (yellow color)\nself.active_process_group = dist.new_group(ranks=self.active_ranks, backend=Backend.NCCL, timeout=timedelta(days=365))\n...", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "# create message process group (yellow color)\nself.comm_broadcast_group = dist.new_group(ranks=[i for i in range(self.world_size)], backend=Backend.GLOO, timeout=timedelta(days=365))\n...\n\n# create DDP-enabled model when the number of data-parallel workers is changed. Note:\n# 1. The process group to be used for distributed data all-reduction.\nIf None, the default process group, which is created by torch.distributed.init_process_group, will be used.\nIn our case, we set it as self.active_process_group\n# 2. device_ids should be set when the pipeline length = 1 (the model resides on a single CUDA device).\n\nself.pipe_len = gpu_num_per_process\nif gpu_num_per_process > 1:\n model = DDP(model, process_group=self.active_process_group, find_unused_parameters=True)\nelse:\n model = DDP(model, device_ids=[self.local_rank], process_group=self.active_process_group, find_unused_parameters=True)", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "# to broadcast message among processes, we use dist.broadcast_object_list\ndef dist_broadcast(object_list, src, group):\n \"\"\"Broadcasts a given object to all parties.\"\"\"\n dist.broadcast_object_list(object_list, src, group=group)\n return object_list\n```\nFor the complete source code, please refer to `https://github.com/Distributed-AI/PipeTransformer/blob/master/pipe_transformer/dp/auto_dp.py`.\n\n# Experiments\n\nThis section first summarizes experiment setups and then evaluates PipeTransformer using computer vision and natural language processing tasks.\n\n
Hardware. Experiments were conducted on 2 identical machines connected by InfiniBand CX353A (

GB/s), where each machine is equipped with 8 NVIDIA Quadro RTX 5000 (16GB GPU memory). GPU-to-GPU bandwidth within a machine (PCI 3.0, 16 lanes) is

GB/s.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "
Implementation. We used PyTorch Pipe as a building block. The BERT model definition, configuration, and related tokenizer are from HuggingFace 3.5.0. We implemented Vision Transformer using PyTorch by following its TensorFlow implementation. More details can be found in our source code.\n\n
Models and Datasets. Experiments employ two representative Transformers in CV and NLP: Vision Transformer (ViT) and BERT. ViT was run on an image classification task, initialized with pre-trained weights on ImageNet21K and fine-tuned on ImageNet and CIFAR-100. BERT was run on two tasks, text classification on the SST-2 dataset from the General Language Understanding Evaluation (GLUE) benchmark, and question answering on the SQuAD v1.1 Dataset (Stanford Question Answering), which is a collection of 100k crowdsourced question/answer pairs.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "3.
Dataset Redistribution: the dataset should be re-balanced to match a dynamic number of pipelines. This not only avoids stragglers but also ensures that gradients from all DDP processes are equally weighted.\n\n
\n
\n
\nFigure 8. AutoDP: handling dynamical data-parallel with messaging between double process groups (Process 0-7 belong to machine 0, while process 8-15 belong to machine 1)\n
\n\n\n\nTo tackle these challenges, we create double communication process groups for DDP. As in the example shown in Figure 8, the message process group (purple) is responsible for light-weight control messages and covers all processes, while the active training process group (yellow) only contains active processes and serves as a vehicle for heavy-weight tensor communications during training. The message group remains static, whereas the training group is dismantled and reconstructed to match active processes.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "In T0, only processes 0 and 8 are active. During the transition to T1, process 0 activates processes 1 and 9 (newly added pipeline replicas) and synchronizes necessary information mentioned above using the message group. The four active processes then form a new training group, allowing static collective communications adaptive to dynamic memberships.\nTo redistribute the dataset, we implement a variant of DistributedSampler that can seamlessly adjust data samples to match the number of active pipeline replicas.\n\nThe above design also naturally helps to reduce DDP communication overhead. More specifically, when transitioning from T0 to T1, processes 0 and 1 destroy the existing DDP instances, and active processes construct a new DDP training group using a cached pipelined model (AutoPipe stores frozen model and cached model separately).\n\nWe use the following APIs to implement the design above.\n\n```python\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "# initialize the process group (this must be called in the initialization of PyTorch DDP)\ndist.init_process_group(init_method='tcp://' + str(self.config.master_addr) + ':' +\nstr(self.config.master_port), backend=Backend.GLOO, rank=self.global_rank, world_size=self.world_size)\n...\n\n# create active process group (yellow color)\nself.active_process_group = dist.new_group(ranks=self.active_ranks, backend=Backend.NCCL, timeout=timedelta(days=365))\n...\n\n# create message process group (yellow color)\nself.comm_broadcast_group = dist.new_group(ranks=[i for i in range(self.world_size)], backend=Backend.GLOO, timeout=timedelta(days=365))\n...\n\n# create DDP-enabled model when the number of data-parallel workers is changed. Note:\n# 1. The process group to be used for distributed data all-reduction.\nIf None, the default process group, which is created by torch.distributed.init_process_group, will be used.\nIn our case, we set it as self.active_process_group", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "# 2. device_ids should be set when the pipeline length = 1 (the model resides on a single CUDA device).\n\nself.pipe_len = gpu_num_per_process\nif gpu_num_per_process > 1:\n model = DDP(model, process_group=self.active_process_group, find_unused_parameters=True)\nelse:\n model = DDP(model, device_ids=[self.local_rank], process_group=self.active_process_group, find_unused_parameters=True)\n\n# to broadcast message among processes, we use dist.broadcast_object_list\ndef dist_broadcast(object_list, src, group):\n \"\"\"Broadcasts a given object to all parties.\"\"\"\n dist.broadcast_object_list(object_list, src, group=group)\n return object_list\n```\nFor the complete source code, please refer to `https://github.com/Distributed-AI/PipeTransformer/blob/master/pipe_transformer/dp/auto_dp.py`.\n\n# Experiments\n\nThis section first summarizes experiment setups and then evaluates PipeTransformer using computer vision and natural language processing tasks.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
Hardware. Experiments were conducted on 2 identical machines connected by InfiniBand CX353A (

GB/s), where each machine is equipped with 8 NVIDIA Quadro RTX 5000 (16GB GPU memory). GPU-to-GPU bandwidth within a machine (PCI 3.0, 16 lanes) is

GB/s.\n\n
Implementation. We used PyTorch Pipe as a building block. The BERT model definition, configuration, and related tokenizer are from HuggingFace 3.5.0. We implemented Vision Transformer using PyTorch by following its TensorFlow implementation. More details can be found in our source code.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
Models and Datasets. Experiments employ two representative Transformers in CV and NLP: Vision Transformer (ViT) and BERT. ViT was run on an image classification task, initialized with pre-trained weights on ImageNet21K and fine-tuned on ImageNet and CIFAR-100. BERT was run on two tasks, text classification on the SST-2 dataset from the General Language Understanding Evaluation (GLUE) benchmark, and question answering on the SQuAD v1.1 Dataset (Stanford Question Answering), which is a collection of 100k crowdsourced question/answer pairs.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "
Training Schemes. Given that large models normally would require thousands of GPU-days {\\emph{e.g.}, GPT-3) if trained from scratch, fine-tuning downstream tasks using pre-trained models has become a trend in CV and NLP communities. Moreover, PipeTransformer is a complex training system that involves multiple core components. Thus, for the first version of PipeTransformer system development and algorithmic research, it is not cost-efficient to develop and evaluate from scratch using large-scale pre-training. Therefore, the experiments presented in this section focuses on pre-trained models. Note that since the model architectures in pre-training and fine-tuning are the same, PipeTransformer can serve both. We discussed pre-training results in the Appendix.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "
Baseline. Experiments in this section compare PipeTransformer to the state-of-the-art framework, a hybrid scheme of PyTorch Pipeline (PyTorch\u2019s implementation of GPipe) and PyTorch DDP. Since this is the first paper that studies accelerating distributed training by freezing layers, there are no perfectly aligned counterpart solutions yet.\n\n
Hyper-parameters. Experiments use ViT-B/16 (12 transformer layers,

input patch size) for ImageNet and CIFAR-100, BERT-large-uncased (24 layers) for SQuAD 1.1, and BERT-base-uncased (12 layers) for SST-2. With PipeTransformer, ViT and BERT training can set the per-pipeline batch size to around 400 and 64, respectively. Other hyperparameters (e.g., epoch, learning rate) for all experiments are presented in Appendix.\n\n## Overall Training Acceleration\n
\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "We summarize the overall experimental results in the table above. Note that the speedup we report is based on a conservative

value that can obtain comparable or even higher accuracy. A more aggressive

(

,

) can obtain a higher speedup but may lead to a slight loss in accuracy. Note that the model size of BERT (24 layers) is larger than ViT-B/16 (12 layers), thus it takes more time for communication.\n\n## Performance Analysis\n\n### Speedup Breakdown\n\nThis section presents evaluation results and analyzes the performance of different components in \\autopipe. More experimental results can be found in the Appendix.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "
\n
\n
\nFigure 9. Speedup Breakdown (ViT on ImageNet)\n
\n\nTo understand the efficacy of all four components and their impacts on training speed, we experimented with different combinations and used their training sample throughput (samples/second) and speedup ratio as metrics. Results are illustrated in Figure 9. Key takeaways from these experimental results are:\n\n1. the main speedup is the result of elastic pipelining which is achieved through the joint use of AutoPipe and AutoDP;\n2. AutoCache's contribution is amplified by AutoDP;\n3. freeze training alone without system-wise adjustment even downgrades the training speed.\n\n### Tuning

in Freezing Algorithm", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "
\n
\n
\nFigure 10. Tuning
in Freezing Algorithm\n
\n\nWe ran experiments to show how the

in the freeze algorithms influences training speed. The result clearly demonstrates that a larger

(excessive freeze) leads to a greater speedup but suffers from a slight performance degradation. In the case shown in Figure 10, where

, freeze training outperforms normal training and obtains a

-fold speedup. We provide more results in the Appendix.\n\n### Optimal Chunks in the elastic pipeline", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "### Optimal Chunks in the elastic pipeline\n\n
\n
\n
\nFigure 11. Optimal chunk number in the elastic pipeline\n
\n\nWe profiled the optimal number of micro-batches

for different pipeline lengths

. Results are summarized in Figure 11. As we can see, different

values lead to different optimal

, and the throughput gaps across different M values are large (as shown when

), which confirms the necessity of an anterior profiler in elastic pipelining.\n\n### Understanding the Timing of Caching", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
-{"page_content": "### Understanding the Timing of Caching\n\n
\n
\n
\nFigure 12. the timing of caching\n
\n\nTo evaluate AutoCache, we compared the sample throughput of training that activates AutoCache from epoch

(blue) with the training job without AutoCache (red). Figure 12 shows that enabling caching too early can slow down training, as caching can be more expensive than the forward propagation on a small number of frozen layers. After more layers are frozen, caching activations clearly outperform the corresponding forward propagation. As a result, AutoCache uses a profiler to determine the proper timing to enable caching. In our system, for ViT (12 layers), caching starts from 3 frozen layers, while for BERT (24 layers), caching starts from 5 frozen layers.\n\nFor more detailed experimental analysis, please refer to our paper.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\nWe summarize the overall experimental results in the table above. Note that the speedup we report is based on a conservative

value that can obtain comparable or even higher accuracy. A more aggressive

(

,

) can obtain a higher speedup but may lead to a slight loss in accuracy. Note that the model size of BERT (24 layers) is larger than ViT-B/16 (12 layers), thus it takes more time for communication.\n\n## Performance Analysis\n\n### Speedup Breakdown\n\nThis section presents evaluation results and analyzes the performance of different components in \\autopipe. More experimental results can be found in the Appendix.\n\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\n
\n
\nFigure 9. Speedup Breakdown (ViT on ImageNet)\n
\n\nTo understand the efficacy of all four components and their impacts on training speed, we experimented with different combinations and used their training sample throughput (samples/second) and speedup ratio as metrics. Results are illustrated in Figure 9. Key takeaways from these experimental results are:\n\n1. the main speedup is the result of elastic pipelining which is achieved through the joint use of AutoPipe and AutoDP;\n2. AutoCache's contribution is amplified by AutoDP;\n3. freeze training alone without system-wise adjustment even downgrades the training speed.\n\n### Tuning

in Freezing Algorithm\n\n
\n
\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\nFigure 10. Tuning
in Freezing Algorithm\n
\n\nWe ran experiments to show how the

in the freeze algorithms influences training speed. The result clearly demonstrates that a larger

(excessive freeze) leads to a greater speedup but suffers from a slight performance degradation. In the case shown in Figure 10, where

, freeze training outperforms normal training and obtains a

-fold speedup. We provide more results in the Appendix.\n\n### Optimal Chunks in the elastic pipeline\n\n
\n
\n
\nFigure 11. Optimal chunk number in the elastic pipeline\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "\n\nWe profiled the optimal number of micro-batches

for different pipeline lengths

. Results are summarized in Figure 11. As we can see, different

values lead to different optimal

, and the throughput gaps across different M values are large (as shown when

), which confirms the necessity of an anterior profiler in elastic pipelining.\n\n### Understanding the Timing of Caching\n\n
\n
\n
\nFigure 12. the timing of caching\n
", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
+{"page_content": "
\nFigure 12. the timing of caching\n\n\nTo evaluate AutoCache, we compared the sample throughput of training that activates AutoCache from epoch

(blue) with the training job without AutoCache (red). Figure 12 shows that enabling caching too early can slow down training, as caching can be more expensive than the forward propagation on a small number of frozen layers. After more layers are frozen, caching activations clearly outperform the corresponding forward propagation. As a result, AutoCache uses a profiler to determine the proper timing to enable caching. In our system, for ViT (12 layers), caching starts from 3 frozen layers, while for BERT (24 layers), caching starts from 5 frozen layers.\n\nFor more detailed experimental analysis, please refer to our paper.\n\n# Summarization", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "# Summarization\nThis blog introduces PipeTransformer, a holistic solution that combines elastic pipeline-parallel and data-parallel for distributed training using PyTorch Distributed APIs. More specifically, PipeTransformer incrementally freezes layers in the pipeline, packs remaining active layers into fewer GPUs, and forks more pipeline replicas to increase the data-parallel width. Evaluations on ViT and BERT models show that compared to the state-of-the-art baseline, PipeTransformer attains up to 2.83\u00d7 speedups without accuracy loss.\n\n\n# Reference\n\n[1] Li, S., Zhao, Y., Varma, R., Salpekar, O., Noordhuis, P., Li,T., Paszke, A., Smith, J., Vaughan, B., Damania, P., et al. Pytorch Distributed: Experiences on Accelerating Dataparallel Training. Proceedings of the VLDB Endowment,13(12), 2020\n\n[2] Devlin, J., Chang, M. W., Lee, K., and Toutanova, K. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In NAACL-HLT, 2019", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "[3] Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., et al. An image is Worth 16x16 words: Transformers for Image Recognition at Scale.\n\n[4] Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., et al. Language Models are Few-shot Learners.\n\n[5] Lepikhin, D., Lee, H., Xu, Y., Chen, D., Firat, O., Huang, Y., Krikun, M., Shazeer, N., and Chen, Z. Gshard: Scaling Giant Models with Conditional Computation and Automatic Sharding.\n\n[6] Li, M., Andersen, D. G., Park, J. W., Smola, A. J., Ahmed, A., Josifovski, V., Long, J., Shekita, E. J., and Su, B. Y. Scaling Distributed Machine Learning with the Parameter Server. In 11th {USENIX} Symposium on Operating Systems Design and Implementation ({OSDI} 14), pp. 583\u2013598, 2014.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
{"page_content": "[7] Jiang, Y., Zhu, Y., Lan, C., Yi, B., Cui, Y., and Guo, C. A Unified Architecture for Accelerating Distributed DNN Training in Heterogeneous GPU/CPU Clusters. In 14th USENIX Symposium on Operating Systems Design and Implementation (OSDI 20), pp. 463\u2013479. USENIX Association, November 2020. ISBN 978-1-939133-19- 9.\n\n[8] Kim, S., Yu, G. I., Park, H., Cho, S., Jeong, E., Ha, H., Lee, S., Jeong, J. S., and Chun, B. G. Parallax: Sparsity-aware Data Parallel Training of Deep Neural Networks. In Proceedings of the Fourteenth EuroSys Conference 2019, pp. 1\u201315, 2019.\n\n[9] Kim, C., Lee, H., Jeong, M., Baek, W., Yoon, B., Kim, I., Lim, S., and Kim, S. TorchGPipe: On-the-fly Pipeline Parallelism for Training Giant Models.\n\n[10] Huang, Y., Cheng, Y., Bapna, A., Firat, O., Chen, M. X., Chen, D., Lee, H., Ngiam, J., Le, Q. V., Wu, Y., et al. Gpipe: Efficient Training of Giant Neural Networks using Pipeline Parallelism.", "metadata": {"source": "https://pytorch.org/blog/pipetransformer-automated-elastic-pipelining/", "category": "pytorch blogs"}}
@@ -728,76 +725,75 @@
{"page_content": "## Serving Strategies\n\nThat zoomed-in view of how you use models in inference isn't usually the whole story, though. In a real world machine learning system, you often need to do more than just run a single inference operation in the REPL or Jupyter notebook. Instead, you usually need to integrate your model into a larger application in some way. Depending on what you need to do, you can usually take one of the following approaches.\n\n### Direct embedding\n\nIn application settings like mobile, we often just directly call the model as part of a larger program. This isn't just for apps; usually this is how robotics and dedicated devices work as well. At a code-level, the call to the model is exactly the same as what is shown above in the section about inference shown above. A key concern is often that a Python interpreter is not present in such environments, which is why PyTorch allows you to call your models from C++ and ship a model without the need for a Python runtime.\n\n### Model microservices", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
{"page_content": "### Model microservices\n\nIf you're using your model in a server side context and you're managing multiple models, you might choose to treat each individual model (or each individual model version) as a separate service, usually using some sort of packaging mechanism like a Docker container. Then that service is often made network accessible via some sort of service, either using JSON over HTTP or an RPC technology like gRPC. The key characteristic of this approach is that you're defining a service with a single endpoint that just calls your model. Then you do do all of your model management (promotion, rollback, etc.) via whatever system you already use to manage your services (e.g. kubernetes, ECS).\n\n### Model servers", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
{"page_content": "### Model servers\n\nAn additional possible solution is to use a model server. This is an application built to manage and serve models. It allows you to upload multiple models and get distinct prediction endpoints for each of them. Typically such systems include a number of other features to help solve more of the whole problem of managing and serving models. This can include things like metrics, visualization, data pre-processing, and more. Even something as simple as having a system for automatically versioning models can make building important features like model rollbacks much easier.\n\n### Evolving Patterns", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
-{"page_content": "### Evolving Patterns\n\nThe above is a somewhat arbitrary breakdown of different approaches based on a snapshot in time. Design patterns are still evolving. Recently, model server designs have started to adopt more of the technologies of general service infrastructure such as Docker containers and kubernetes, so many model servers have started to share properties of the model microservice design discussed above. For a deeper dive into the general concepts of model server designs, you can check out my [book on machine learning systems](https://www.manning.com/books/machine-learning-systems).\n\n## Serving PyTorch Models\n\nSo, if you're a PyTorch user, what should you use if you want to take your models to production?", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
-{"page_content": "If you're on mobile or working on an embedded system like a robot, direct embedding in your application is often the right choice. \nFor mobile specifically, your use case might be served by the ONNX export functionality.\nNote that ONNX, by its very nature, has limitations and doesn't support all of the functionality provided by the larger PyTorch project.\nYou can check out [this tutorial](https://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html) on deploying PyTorch models to mobile using ONNX to see if this path might suit your use case. \nThat said, we've heard that there's a lot more that PyTorch users want to do on mobile, so look for more mobile-specific functionality in PyTorch in the future.\nFor other embedded systems, like robots, running [inference on a PyTorch model from the C++ API](https://pytorch.org/tutorials/advanced/cpp_export.html) could be the right solution.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
-{"page_content": "If you can't use the cloud or prefer to manage all services using the same technology, you can follow [this example](https://medium.com/datadriveninvestor/deploy-your-pytorch-model-to-production-f69460192217) to build a simple model microservice using the Flask web framework.\n\nIf you want to manage multiple models within a non-cloud service solution, there are teams developing PyTorch support in model servers like [MLFlow](https://mlflow.org/), [Kubeflow](https://www.kubeflow.org/), and [RedisAI.](https://oss.redislabs.com/redisai/) We're excited to see innovation from multiple teams building OSS model servers, and we'll continue to highlight innovation in the PyTorch ecosystem in the future.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
+{"page_content": "### Evolving Patterns\n\nThe above is a somewhat arbitrary breakdown of different approaches based on a snapshot in time. Design patterns are still evolving. Recently, model server designs have started to adopt more of the technologies of general service infrastructure such as Docker containers and kubernetes, so many model servers have started to share properties of the model microservice design discussed above. For a deeper dive into the general concepts of model server designs, you can check out my [book on machine learning systems](https://www.manning.com/books/machine-learning-systems).\n\n## Serving PyTorch Models\n\nSo, if you're a PyTorch user, what should you use if you want to take your models to production?\n\nIf you're on mobile or working on an embedded system like a robot, direct embedding in your application is often the right choice. \nFor mobile specifically, your use case might be served by the ONNX export functionality.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
+{"page_content": "Note that ONNX, by its very nature, has limitations and doesn't support all of the functionality provided by the larger PyTorch project.\nYou can check out [this tutorial](https://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html) on deploying PyTorch models to mobile using ONNX to see if this path might suit your use case. \nThat said, we've heard that there's a lot more that PyTorch users want to do on mobile, so look for more mobile-specific functionality in PyTorch in the future.\nFor other embedded systems, like robots, running [inference on a PyTorch model from the C++ API](https://pytorch.org/tutorials/advanced/cpp_export.html) could be the right solution.\n\nIf you can't use the cloud or prefer to manage all services using the same technology, you can follow [this example](https://medium.com/datadriveninvestor/deploy-your-pytorch-model-to-production-f69460192217) to build a simple model microservice using the Flask web framework.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
+{"page_content": "If you want to manage multiple models within a non-cloud service solution, there are teams developing PyTorch support in model servers like [MLFlow](https://mlflow.org/), [Kubeflow](https://www.kubeflow.org/), and [RedisAI.](https://oss.redislabs.com/redisai/) We're excited to see innovation from multiple teams building OSS model servers, and we'll continue to highlight innovation in the PyTorch ecosystem in the future.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
{"page_content": "If you can use the cloud for your application, there are several great choices for working with models in the cloud. For AWS Sagemaker, you can start find a guide to [all of the resources from AWS for working with PyTorch](https://docs.aws.amazon.com/sagemaker/latest/dg/pytorch.html), including docs on how to use the [Sagemaker Python SDK](https://sagemaker.readthedocs.io/en/stable/using_pytorch.html). You can also see [some](https://youtu.be/5h1Ot2dPi2E) [talks](https://youtu.be/qc5ZikKw9_w) we've given on using PyTorch on Sagemaker. Finally, if you happen to be using PyTorch via FastAI, then they've written a [really simple guide](https://course.fast.ai/deployment_amzn_sagemaker.html) to getting up and running on Sagemaker.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
{"page_content": "The story is similar across other major clouds. On Google Cloud, you can follow [these instructions](https://cloud.google.com/deep-learning-vm/docs/pytorch_start_instance) to get access to a Deep Learning VM with PyTorch pre-installed. On Microsoft Azure, you have a number of ways to get started from [Azure Machine Learning Service](https://azure.microsoft.com/en-us/services/machine-learning-service/) to [Azure Notebooks](https://notebooks.azure.com/pytorch/projects/tutorials) showing how to use PyTorch.\n\n## Your Models\n\nWhichever approach you take to bringing your PyTorch models to production, we want to support you and enable your success. Do you love one of the options above? Are you having difficulty with that one crucial feature you can't find support for? We'd love to discuss more on the [deployment category](https://discuss.pytorch.org/c/deployment) on the PyTorch Discuss forums. We'd love to help, and where you're seeing success, amplify your story.", "metadata": {"source": "https://pytorch.org/blog/model-serving-in-pyorch/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'Accelerating PyTorch with CUDA Graphs'\nauthor: Vinh Nguyen, Michael Carilli, Sukru Burc Eryilmaz, Vartika Singh, Michelle Lin, Natalia Gimelshein, Alban Desmaison, Edward Yang\nfeatured-img: 'assets/images/cudagraphs-pytorch.png'\n---", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "Today, we are pleased to announce a new advanced CUDA feature, CUDA Graphs, has been brought to PyTorch. Modern DL frameworks have complicated software stacks that incur significant overheads associated with the submission of each operation to the GPU. When DL workloads are strong-scaled to many GPUs for performance, the time taken by each GPU operation diminishes to just a few microseconds and, in these cases, the high work submission latencies of frameworks often lead to low utilization of the GPU. As GPUs get faster and workloads are scaled to more devices, the likelihood of workloads suffering from these launch-induced stalls increases. To overcome these performance overheads, NVIDIA engineers worked with PyTorch developers to enable CUDA graph execution natively in PyTorch. This design was instrumental in scaling NVIDIA\u2019s MLPerf workloads (implemented in PyTorch) to over 4000 GPUs in order to achieve [record-breaking performance](https://blogs.nvidia.com/blog/2021/06/30/mlperf-ai-training-partners/).", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "
\n

\n
", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "CUDA graphs support in PyTorch is just one more example of a long collaboration between NVIDIA and Facebook engineers. [torch.cuda.amp](https://pytorch.org/docs/stable/amp.html), for example, trains with half precision while maintaining the network accuracy achieved with single precision and automatically utilizing tensor cores wherever possible. AMP delivers up to 3X higher performance than FP32 with just a few lines of code change. Similarly, NVIDIA\u2019s [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) was trained using PyTorch on up to 3072 GPUs. In PyTorch, one of the most performant methods to scale-out GPU training is with [torch.nn.parallel.DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel) coupled with the NVIDIA Collective Communications Library ([NCCL](https://developer.nvidia.com/nccl)) backend.\n\n\n# CUDA Graphs", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "
\n\nCUDA graphs support in PyTorch is just one more example of a long collaboration between NVIDIA and Facebook engineers. [torch.cuda.amp](https://pytorch.org/docs/stable/amp.html), for example, trains with half precision while maintaining the network accuracy achieved with single precision and automatically utilizing tensor cores wherever possible. AMP delivers up to 3X higher performance than FP32 with just a few lines of code change. Similarly, NVIDIA\u2019s [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) was trained using PyTorch on up to 3072 GPUs. In PyTorch, one of the most performant methods to scale-out GPU training is with [torch.nn.parallel.DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel) coupled with the NVIDIA Collective Communications Library ([NCCL](https://developer.nvidia.com/nccl)) backend.\n\n\n# CUDA Graphs", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "# CUDA Graphs\n\n\n[CUDA Graphs](https://developer.nvidia.com/blog/cuda-10-features-revealed/), which made its debut in CUDA 10, let a series of CUDA kernels to be defined and encapsulated as a single unit, i.e., a graph of operations, rather than a sequence of individually-launched operations. It provides a mechanism to launch multiple GPU operations through a single CPU operation, and hence reduces the launching overheads.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "The benefits of CUDA graphs can be demonstrated with the simple example in Figure 1. On the top, a sequence of short kernels is launched one-by-one by the CPU. The CPU launching overhead creates a significant gap in between the kernels. If we replace this sequence of kernels with a CUDA graph, initially we will need to spend a little extra time on building the graph and launching the whole graph in one go on the first occasion, but subsequent executions will be very fast, as there will be very little gap between the kernels. The difference is more pronounced when the same sequence of operations is repeated many times, for example, overy many training steps. In that case, the initial costs of building and launching the graph will be amortized over the entire number of training iterations. For a more comprehensive introduction on the topic, see our blog \n [Getting Started with CUDA Graphs](https://developer.nvidia.com/blog/cuda-graphs) and GTC talk [Effortless CUDA Graphs](https://www.nvidia.com/en-us/on-demand/session/gtcspring21-s32082/).", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "\n
\n
\n\tFigure 1. Benefits of using CUDA graphs\n
\n\n\n## NCCL support for CUDA graphs\n\n\nThe previously mentioned benefits of reducing launch overheads also extend to NCCL kernel launches. NCCL enables GPU-based collective and P2P communications. With [NCCL support for CUDA graphs](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/cudagraph.html), we can eliminate the NCCL kernel launch overhead.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "Additionally, kernel launch timing can be unpredictable due to various CPU load and operating system factors. Such time skews can be harmful to the performance of NCCL collective operations. With CUDA graphs, kernels are clustered together so that performance is consistent across ranks in a distributed workload. This is especially useful in large clusters where even a single slow node can bring down overall cluster level performance.\n\nFor distributed multi-GPU workloads, NCCL is used for collective communications. If we look at training a neural network that leverages data parallelism, without NCCL support for CUDA graphs, we\u2019ll need a separate launch for each of forward/back propagation and NCCL AllReduce. By contrast, with NCCL support for CUDA graphs, we can reduce launch overhead by lumping together the forward/backward propagation and NCCL AllReduce all in a single graph launch.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "The benefits of CUDA graphs can be demonstrated with the simple example in Figure 1. On the top, a sequence of short kernels is launched one-by-one by the CPU. The CPU launching overhead creates a significant gap in between the kernels. If we replace this sequence of kernels with a CUDA graph, initially we will need to spend a little extra time on building the graph and launching the whole graph in one go on the first occasion, but subsequent executions will be very fast, as there will be very little gap between the kernels. The difference is more pronounced when the same sequence of operations is repeated many times, for example, overy many training steps. In that case, the initial costs of building and launching the graph will be amortized over the entire number of training iterations. For a more comprehensive introduction on the topic, see our blog", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "[Getting Started with CUDA Graphs](https://developer.nvidia.com/blog/cuda-graphs) and GTC talk [Effortless CUDA Graphs](https://www.nvidia.com/en-us/on-demand/session/gtcspring21-s32082/).\n\n\n\n
\n
\n\tFigure 1. Benefits of using CUDA graphs\n
\n\n\n## NCCL support for CUDA graphs\n\n\nThe previously mentioned benefits of reducing launch overheads also extend to NCCL kernel launches. NCCL enables GPU-based collective and P2P communications. With [NCCL support for CUDA graphs](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/cudagraph.html), we can eliminate the NCCL kernel launch overhead.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "Additionally, kernel launch timing can be unpredictable due to various CPU load and operating system factors. Such time skews can be harmful to the performance of NCCL collective operations. With CUDA graphs, kernels are clustered together so that performance is consistent across ranks in a distributed workload. This is especially useful in large clusters where even a single slow node can bring down overall cluster level performance.\n\nFor distributed multi-GPU workloads, NCCL is used for collective communications. If we look at training a neural network that leverages data parallelism, without NCCL support for CUDA graphs, we\u2019ll need a separate launch for each of forward/back propagation and NCCL AllReduce. By contrast, with NCCL support for CUDA graphs, we can reduce launch overhead by lumping together the forward/backward propagation and NCCL AllReduce all in a single graph launch.\n\n\n", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\n Figure 2. Looking at a typical neural network, all the kernel launches for NCCL AllReduce can be bundled into a graph to reduce overhead launch time.\n
\n\n\n# PyTorch CUDA Graphs\n\n\nFrom PyTorch v1.10, the CUDA graphs functionality is made available as a set of beta APIs. \n\n### API overview", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "### API overview\n\nPyTorch supports the construction of CUDA graphs using [stream capture](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#creating-a-graph-using-stream-capture), which puts a CUDA stream in capture mode. CUDA work issued to a capturing stream doesn\u2019t actually run on the GPU. Instead, the work is recorded in a graph. After capture, the graph can be launched to run the GPU work as many times as needed. Each replay runs the same kernels with the same arguments. For pointer arguments this means the same memory addresses are used. By filling input memory with new data (e.g., from a new batch) before each replay, you can rerun the same work on new data.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "Replaying a graph sacrifices the dynamic flexibility of typical eager execution in exchange for greatly reduced CPU overhead. A graph\u2019s arguments and kernels are fixed, so a graph replay skips all layers of argument setup and kernel dispatch, including Python, C++, and CUDA driver overheads. Under the hood, a replay submits the entire graph\u2019s work to the GPU with a single call to [cudaGraphLaunch](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__GRAPH.html#group__CUDART__GRAPH_1g1accfe1da0c605a577c22d9751a09597). Kernels in a replay also execute slightly faster on the GPU, but eliding CPU overhead is the main benefit.\n\nYou should try CUDA graphs if all or part of your network is graph-safe (usually this means static shapes and static control flow, but see the other [constraints](https://pytorch.org/docs/master/notes/cuda.html#constraints)) and you suspect its runtime is at least somewhat CPU-limited.\n\n### API example", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "### API example\n\nPyTorch exposes graphs via a raw [`torch.cuda.CUDAGraph`](https://pytorch.org/docs/master/generated/torch.cuda.graph.html#torch.cuda.graph)class and two convenience wrappers, [`torch.cuda.graph`](https://pytorch.org/docs/master/generated/torch.cuda.graph.html#torch.cuda.graph) and [`torch.cuda.make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables).", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "[`torch.cuda.graph`](https://pytorch.org/docs/master/generated/torch.cuda.graph.html#torch.cuda.graph) is a simple, versatile context manager that captures CUDA work in its context. Before capture, warm up the workload to be captured by running a few eager iterations. Warmup must occur on a side stream. Because the graph reads from and writes to the same memory addresses in every replay, you must maintain long-lived references to tensors that hold input and output data during capture. To run the graph on new input data, copy new data to the capture\u2019s input tensor(s), replay the graph, then read the new output from the capture\u2019s output tensor(s).\n\nIf the entire network is capture safe, one can capture and replay the whole network as in the following example.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "```python\nN, D_in, H, D_out = 640, 4096, 2048, 1024\nmodel = torch.nn.Sequential(torch.nn.Linear(D_in, H),\n torch.nn.Dropout(p=0.2),\n torch.nn.Linear(H, D_out),\n torch.nn.Dropout(p=0.1)).cuda()\nloss_fn = torch.nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.1)\n\n# Placeholders used for capture\nstatic_input = torch.randn(N, D_in, device='cuda')\nstatic_target = torch.randn(N, D_out, device='cuda')\n\n# warmup\n# Uses static_input and static_target here for convenience,\n# but in a real setting, because the warmup includes optimizer.step()\n# you must use a few batches of real data.\ns = torch.cuda.Stream()\ns.wait_stream(torch.cuda.current_stream())\nwith torch.cuda.stream(s):\n for i in range(3):\n optimizer.zero_grad(set_to_none=True)\n y_pred = model(static_input)\n loss = loss_fn(y_pred, static_target)\n loss.backward()\n optimizer.step()\ntorch.cuda.current_stream().wait_stream(s)", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "# capture\ng = torch.cuda.CUDAGraph()\n# Sets grads to None before capture, so backward() will create\n# .grad attributes with allocations from the graph's private pool\noptimizer.zero_grad(set_to_none=True)\nwith torch.cuda.graph(g):\n static_y_pred = model(static_input)\n static_loss = loss_fn(static_y_pred, static_target)\n static_loss.backward()\n optimizer.step()\n\nreal_inputs = [torch.rand_like(static_input) for _ in range(10)]\nreal_targets = [torch.rand_like(static_target) for _ in range(10)]", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "for data, target in zip(real_inputs, real_targets):\n # Fills the graph's input memory with new data to compute on\n static_input.copy_(data)\n static_target.copy_(target)\n # replay() includes forward, backward, and step.\n # You don't even need to call optimizer.zero_grad() between iterations\n # because the captured backward refills static .grad tensors in place.\n g.replay()\n # Params have been updated. static_y_pred, static_loss, and .grad\n # attributes hold values from computing on this iteration's data.\n```\n\nIf some of your network is unsafe to capture (e.g., due to dynamic control flow, dynamic shapes, CPU syncs, or essential CPU-side logic), you can run the unsafe part(s) eagerly and use [`torch.cuda.make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables) to graph only the capture-safe part(s). This is demonstrated next.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "[`torch.cuda.graph`](https://pytorch.org/docs/master/generated/torch.cuda.graph.html#torch.cuda.graph) is a simple, versatile context manager that captures CUDA work in its context. Before capture, warm up the workload to be captured by running a few eager iterations. Warmup must occur on a side stream. Because the graph reads from and writes to the same memory addresses in every replay, you must maintain long-lived references to tensors that hold input and output data during capture. To run the graph on new input data, copy new data to the capture\u2019s input tensor(s), replay the graph, then read the new output from the capture\u2019s output tensor(s).\n\nIf the entire network is capture safe, one can capture and replay the whole network as in the following example. \n\n```python\nN, D_in, H, D_out = 640, 4096, 2048, 1024\nmodel = torch.nn.Sequential(torch.nn.Linear(D_in, H),\n torch.nn.Dropout(p=0.2),\n torch.nn.Linear(H, D_out),", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "torch.nn.Dropout(p=0.1)).cuda()\nloss_fn = torch.nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.1)\n\n# Placeholders used for capture\nstatic_input = torch.randn(N, D_in, device='cuda')\nstatic_target = torch.randn(N, D_out, device='cuda')\n\n# warmup\n# Uses static_input and static_target here for convenience,\n# but in a real setting, because the warmup includes optimizer.step()\n# you must use a few batches of real data.\ns = torch.cuda.Stream()\ns.wait_stream(torch.cuda.current_stream())\nwith torch.cuda.stream(s):\n for i in range(3):\n optimizer.zero_grad(set_to_none=True)\n y_pred = model(static_input)\n loss = loss_fn(y_pred, static_target)\n loss.backward()\n optimizer.step()\ntorch.cuda.current_stream().wait_stream(s)\n\n# capture\ng = torch.cuda.CUDAGraph()\n# Sets grads to None before capture, so backward() will create\n# .grad attributes with allocations from the graph's private pool\noptimizer.zero_grad(set_to_none=True)", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "optimizer.zero_grad(set_to_none=True)\nwith torch.cuda.graph(g):\n static_y_pred = model(static_input)\n static_loss = loss_fn(static_y_pred, static_target)\n static_loss.backward()\n optimizer.step()\n\nreal_inputs = [torch.rand_like(static_input) for _ in range(10)]\nreal_targets = [torch.rand_like(static_target) for _ in range(10)]\n\nfor data, target in zip(real_inputs, real_targets):\n # Fills the graph's input memory with new data to compute on\n static_input.copy_(data)\n static_target.copy_(target)\n # replay() includes forward, backward, and step.\n # You don't even need to call optimizer.zero_grad() between iterations\n # because the captured backward refills static .grad tensors in place.\n g.replay()\n # Params have been updated. static_y_pred, static_loss, and .grad\n # attributes hold values from computing on this iteration's data.\n```", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "```\n\nIf some of your network is unsafe to capture (e.g., due to dynamic control flow, dynamic shapes, CPU syncs, or essential CPU-side logic), you can run the unsafe part(s) eagerly and use [`torch.cuda.make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables) to graph only the capture-safe part(s). This is demonstrated next.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "[`make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables) accepts callables (functions or [`nn.Module`](https://pytorch.org/docs/master/generated/torch.nn.Module.html#torch.nn.Module) and returns graphed versions. By default, callables returned by [`make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables) are autograd-aware, and can be used in the training loop as direct replacements for the functions or [`nn.Module`](https://pytorch.org/docs/master/generated/torch.nn.Module.html#torch.nn.Module) you passed. [`make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables) internally creates [`CUDAGraph`](https://pytorch.org/docs/master/generated/torch.cuda.CUDAGraph.html#torch.cuda.CUDAGraph) objects, runs warm up iterations, and maintains static inputs and outputs as needed. Therefore, (unlike with [`torch.cuda.graph`](https://pytorch.org/docs/master/generated/torch.cuda.graph.html#torch.cuda.graph)) you don\u2019t need to handle those manually.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "In the following example, data-dependent dynamic control flow means the network isn\u2019t capturable end-to-end, but [`make_graphed_callables`](https://pytorch.org/docs/master/generated/torch.cuda.make_graphed_callables.html#torch.cuda.make_graphed_callables)() lets us capture and run graph-safe sections as graphs regardless:\n\n\n```python\nN, D_in, H, D_out = 640, 4096, 2048, 1024\n\nmodule1 = torch.nn.Linear(D_in, H).cuda()\nmodule2 = torch.nn.Linear(H, D_out).cuda()\nmodule3 = torch.nn.Linear(H, D_out).cuda()\n\nloss_fn = torch.nn.MSELoss()\noptimizer = torch.optim.SGD(chain(module1.parameters(),\n module2.parameters(),\n module3.parameters()),\n lr=0.1)\n\n# Sample inputs used for capture\n# requires_grad state of sample inputs must match\n# requires_grad state of real inputs each callable will see.\nx = torch.randn(N, D_in, device='cuda')\nh = torch.randn(N, H, device='cuda', requires_grad=True)", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "module1 = torch.cuda.make_graphed_callables(module1, (x,))\nmodule2 = torch.cuda.make_graphed_callables(module2, (h,))\nmodule3 = torch.cuda.make_graphed_callables(module3, (h,))\n\nreal_inputs = [torch.rand_like(x) for _ in range(10)]\nreal_targets = [torch.randn(N, D_out, device=\"cuda\") for _ in range(10)]\n\nfor data, target in zip(real_inputs, real_targets):\n optimizer.zero_grad(set_to_none=True)\n\n tmp = module1(data) # forward ops run as a graph\n\n if tmp.sum().item() > 0:\n tmp = module2(tmp) # forward ops run as a graph\n else:\n tmp = module3(tmp) # forward ops run as a graph\n\n loss = loss_fn(tmp, target)\n # module2's or module3's (whichever was chosen) backward ops,\n # as well as module1's backward ops, run as graphs\n loss.backward()\n optimizer.step()\n```\n\n# Example use cases\n## MLPerf v1.0 training workloads", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "The PyTorch CUDA graphs functionality was instrumental in scaling NVIDIA\u2019s MLPerf training v1.0 workloads (implemented in PyTorch) to over 4000 GPUs, setting new [records across the board](https://blogs.nvidia.com/blog/2021/06/30/mlperf-ai-training-partners/). We illustrate below two MLPerf workloads where the most significant gains were observed with the use of CUDA graphs, yielding up to ~1.7x speedup.\n\n| | Number of GPUs | Speedup from CUDA-graphs |\n|-----------------------------|----------------:|-------------------------:|\n| Mask R-CNN | 272 | 1.70\u00d7 |\n| BERT | 4096 | 1.12\u00d7 |\n\nTable 1. MLPerf training v1.0 performance improvement with PyTorch CUDA graph.\n\n### Mask R-CNN", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "### Mask R-CNN\n\nDeep learning frameworks use GPUs to accelerate computations, but a significant amount of code still runs on CPU cores. CPU cores process meta-data like tensor shapes in order to prepare arguments needed to launch GPU kernels. Processing meta-data is a fixed cost while the cost of the computational work done by the GPUs is positively correlated with batch size. For large batch sizes, CPU overhead is a negligible percentage of total run time cost, but at small batch sizes CPU overhead can become larger than GPU run time. When that happens, GPUs go idle between kernel calls. This issue can be identified on an NSight timeline plot in Figure 3. The plot below shows the \u201cbackbone\u201d portion of Mask R-CNN with per-gpu batch size of 1 before graphing. The green portion shows CPU load while the blue portion shows GPU load. In this profile we see that the CPU is maxed out at 100% load while GPU is idle most of the time, there is a lot of empty space between GPU kernels.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "## MLPerf v1.0 training workloads\n\nThe PyTorch CUDA graphs functionality was instrumental in scaling NVIDIA\u2019s MLPerf training v1.0 workloads (implemented in PyTorch) to over 4000 GPUs, setting new [records across the board](https://blogs.nvidia.com/blog/2021/06/30/mlperf-ai-training-partners/). We illustrate below two MLPerf workloads where the most significant gains were observed with the use of CUDA graphs, yielding up to ~1.7x speedup.\n\n| | Number of GPUs | Speedup from CUDA-graphs |\n|-----------------------------|----------------:|-------------------------:|\n| Mask R-CNN | 272 | 1.70\u00d7 |\n| BERT | 4096 | 1.12\u00d7 |\n\nTable 1. MLPerf training v1.0 performance improvement with PyTorch CUDA graph.\n\n### Mask R-CNN", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "### Mask R-CNN\n\nDeep learning frameworks use GPUs to accelerate computations, but a significant amount of code still runs on CPU cores. CPU cores process meta-data like tensor shapes in order to prepare arguments needed to launch GPU kernels. Processing meta-data is a fixed cost while the cost of the computational work done by the GPUs is positively correlated with batch size. For large batch sizes, CPU overhead is a negligible percentage of total run time cost, but at small batch sizes CPU overhead can become larger than GPU run time. When that happens, GPUs go idle between kernel calls. This issue can be identified on an NSight timeline plot in Figure 3. The plot below shows the \u201cbackbone\u201d portion of Mask R-CNN with per-gpu batch size of 1 before graphing. The green portion shows CPU load while the blue portion shows GPU load. In this profile we see that the CPU is maxed out at 100% load while GPU is idle most of the time, there is a lot of empty space between GPU kernels.\n\n", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "
\n
\n
\n Figure 3: NSight timeline plot of Mask R-CNN\n
\n\nCUDA graphs can automatically eliminate CPU overhead when tensor shapes are static. A complete graph of all the kernel calls is captured during the first step, in subsequent steps the entire graph is launched with a single op, eliminating all the CPU overhead, as observed in Figure 4.. \n\n\n
\n
\n Figure 4: CUDA graphs optimization\n
", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "With graphing, we see that the GPU kernels are tightly packed and GPU utilization remains high. The graphed portion now runs in 6 ms instead of 31ms, a speedup of 5x. We did not graph the entire model, mostly just the resnet backbone, which resulted in an overall speedup of ~1.7x.\nIn order to increase the scope of the graph, we made some changes in the software stack to eliminate some of the CPU-GPU synchronization points. In MLPerf v1.0, this work included changing the implementation of torch.randperm function to use CUB instead of Thrust because the latter is a synchronous C++ template library. These improvements are available in the latest NGC container.\n\n\n### BERT", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "
\n Figure 4: CUDA graphs optimization\n\n\nWith graphing, we see that the GPU kernels are tightly packed and GPU utilization remains high. The graphed portion now runs in 6 ms instead of 31ms, a speedup of 5x. We did not graph the entire model, mostly just the resnet backbone, which resulted in an overall speedup of ~1.7x.\nIn order to increase the scope of the graph, we made some changes in the software stack to eliminate some of the CPU-GPU synchronization points. In MLPerf v1.0, this work included changing the implementation of torch.randperm function to use CUB instead of Thrust because the latter is a synchronous C++ template library. These improvements are available in the latest NGC container.\n\n\n### BERT", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "Similarly, by graph capturing the model, we eliminate CPU overhead and accompanying synchronization overhead. CUDA graphs implementation results in a 1.12x performance boost for our max-scale BERT configuration. To maximize the benefits from CUDA graphs, it is important to keep the scope of the graph as large as possible. To achieve this, we modified the model script to remove CPU-GPU synchronizations during the execution such that the full model can be graph captured. Furthermore, we also made sure that the tensor sizes during the execution are static within the scope of the graph. For instance, in BERT, only a specific subset of total tokens contribute to loss function, determined by a pre-generated mask tensor. Extracting the indices of valid tokens from this mask, and using these indices to gather the tokens that contribute to the loss, results in a tensor with a dynamic shape, i.e. with shape that is not constant across iterations. In order to make sure tensor sizes are static, instead of using the dynamic-shape tensors in the loss computation, we used static shape tensors where a mask is used to indicate which elements are valid. As a result, all tensor shapes are static. Dynamic shapes also require CPU-GPU synchronization since it has to involve the framework\u2019s memory management on the CPU side. With static-only shapes, no CPU-GPU synchronizations are necessary. This is shown in Figure 5.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "\n\t
\n\t
\n\tFigure 5. By using a fixed size tensor and a boolean mask as described in the text, we are able to eliminate CPU synchronizations needed for dynamic sized tensors \n
\n\n\n## CUDA graphs in NVIDIA DL examples collection\n\nSingle GPU use cases can also benefit from using CUDA Graphs. This is particularly true for workloads launching many short kernels with small batches. A good example is training and inference for recommender systems. Below we present preliminary benchmark results for NVIDIA's implementation of the Deep Learning Recommendation Model (DLRM) from our Deep Learning Examples collection. Using CUDA graphs for this workload provides significant speedups for both training and inference. The effect is particularly visible when using very small batch sizes, where CPU overheads are more pronounced.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "CUDA graphs are being actively integrated into other PyTorch NGC model scripts and the NVIDIA Github deep learning examples. Stay tuned for more examples on how to use it.\n\n\n\n\t
\n
\n\n\t
\n
\n\tFigure 6: CUDA graphs optimization for the DLRM model.\n
\n\n\n# Call to action: CUDA Graphs in PyTorch v1.10", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "# Call to action: CUDA Graphs in PyTorch v1.10\n\nCUDA graphs can provide substantial benefits for workloads that comprise many small GPU kernels and hence bogged down by CPU launch overheads. This has been demonstrated in our MLPerf efforts, optimizing PyTorch models. Many of these optimizations, including CUDA graphs, have or will eventually be integrated into our PyTorch NGC model scripts [collection](https://ngc.nvidia.com/catalog/collections?orderBy=scoreDESC&pageNumber=0&query=pytorch&quickFilter=&filters=) and the NVIDIA [Github deep learning examples](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/). For now, check out our open-source MLPerf training v1.0 [implementation](https://github.com/mlcommons/training_results_v1.0/tree/master/NVIDIA) which could serve as a good starting point to see CUDA graph in action. Alternatively, try the PyTorch CUDA graphs API on your own workloads.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "We thank many NVIDIAN\u2019s and Facebook engineers for their discussions and suggestions: \n[Karthik Mandakolathur US](mailto:karthik@nvidia.com),\n[Tomasz Grel](mailto:tgrel@nvidia.com), \n[PLJoey Conway](mailto:jconway@nvidia.com), \n[Arslan Zulfiqar US](mailto:azulfiqar@nvidia.com)\n\n## Authors bios\n\n[**Vinh Nguyen**](mailto:vinhn@nvidia.com)\n*DL Engineer, NVIDIA*\n\nVinh is a Deep learning engineer and data scientist, having published more than 50 scientific articles attracting more than 2500 citations. At NVIDIA, his work spans a wide range of deep learning and AI applications, including speech, language and vision processing, and recommender systems.\n\n[**Michael Carilli**](mailto:mcarilli@nvidia.com)\n*Senior Developer Technology Engineer, NVIDIA*", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
-{"page_content": "Michael worked at the Air Force Research Laboratory optimizing CFD code for modern parallel architectures. He holds a PhD in computational physics from the University of California, Santa Barbara. A member of the PyTorch team, he focuses on making GPU training fast, numerically stable, and easy(er) for internal teams, external customers, and Pytorch community users.\n\n[**Sukru Burc Eryilmaz**](mailto:seryilmaz@nvidia.com)\n*Senior Architect in Dev Arch, NVIDIA*\n\nSukru received his PhD from Stanford University, and B.S from Bilkent University. He currently works on improving the end-to-end performance of neural network training both at single-node scale and supercomputer scale. \n\n[**Vartika Singh**](mailto:vartikas@nvidia.com)\n*Tech Partner Lead for DL Frameworks and Libraries, NVIDIA*", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "# Call to action: CUDA Graphs in PyTorch v1.10\n\nCUDA graphs can provide substantial benefits for workloads that comprise many small GPU kernels and hence bogged down by CPU launch overheads. This has been demonstrated in our MLPerf efforts, optimizing PyTorch models. Many of these optimizations, including CUDA graphs, have or will eventually be integrated into our PyTorch NGC model scripts [collection](https://ngc.nvidia.com/catalog/collections?orderBy=scoreDESC&pageNumber=0&query=pytorch&quickFilter=&filters=) and the NVIDIA [Github deep learning examples](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/). For now, check out our open-source MLPerf training v1.0 [implementation](https://github.com/mlcommons/training_results_v1.0/tree/master/NVIDIA) which could serve as a good starting point to see CUDA graph in action. Alternatively, try the PyTorch CUDA graphs API on your own workloads.\n\nWe thank many NVIDIAN\u2019s and Facebook engineers for their discussions and suggestions:", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "[Karthik Mandakolathur US](mailto:karthik@nvidia.com),\n[Tomasz Grel](mailto:tgrel@nvidia.com), \n[PLJoey Conway](mailto:jconway@nvidia.com), \n[Arslan Zulfiqar US](mailto:azulfiqar@nvidia.com)\n\n## Authors bios\n\n[**Vinh Nguyen**](mailto:vinhn@nvidia.com)\n*DL Engineer, NVIDIA*\n\nVinh is a Deep learning engineer and data scientist, having published more than 50 scientific articles attracting more than 2500 citations. At NVIDIA, his work spans a wide range of deep learning and AI applications, including speech, language and vision processing, and recommender systems.\n\n[**Michael Carilli**](mailto:mcarilli@nvidia.com)\n*Senior Developer Technology Engineer, NVIDIA*", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
+{"page_content": "*Senior Developer Technology Engineer, NVIDIA*\n\nMichael worked at the Air Force Research Laboratory optimizing CFD code for modern parallel architectures. He holds a PhD in computational physics from the University of California, Santa Barbara. A member of the PyTorch team, he focuses on making GPU training fast, numerically stable, and easy(er) for internal teams, external customers, and Pytorch community users.\n\n[**Sukru Burc Eryilmaz**](mailto:seryilmaz@nvidia.com)\n*Senior Architect in Dev Arch, NVIDIA*\n\nSukru received his PhD from Stanford University, and B.S from Bilkent University. He currently works on improving the end-to-end performance of neural network training both at single-node scale and supercomputer scale. \n\n[**Vartika Singh**](mailto:vartikas@nvidia.com)\n*Tech Partner Lead for DL Frameworks and Libraries, NVIDIA*", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "Vartika has led teams working in confluence of cloud and distributed computing, scaling and AI, influencing the design and strategy of major corporations. She currently works with the major frameworks and compiler organizations and developers within and outside NVIDIA, to help the design to work efficiently and optimally on NVIDIA hardware.\n\n[**Michelle Lin**](mailto:miclin@nvidia.com)\n*Product Intern, NVIDIA*\n\nMichelle is currently pursuing an undergraduate degree in Computer Science and Business Administration at UC Berkeley. She is currently managing execution of projects such as conducting market research and creating marketing assets for Magnum IO.\n\n[**Natalia Gimelshein**](mailto:ngimel@fb.com)\n*Applied Research Scientist, Facebook*\n\nNatalia Gimelshein worked on GPU performance optimization for deep learning workloads at NVIDIA and Facebook. She is currently a member of the PyTorch core team, working with partners to seamlessly support new software and hardware features.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "[**Alban Desmaison**](mailto:albandes@fb.com)\n*Research Engineer, Facebook*\n\nAlban studied engineering and did a PhD in Machine Learning and Optimization, during which he was an OSS contributor to PyTorch prior to joining Facebook. His main responsibilities are maintaining some core library and features (autograd, optim, nn) and working on making PyTorch better in general.\n\n[**Edward Yang**](mailto:ezyang@fb.com)\n*Research Engineer, Facebook*\n\nEdward studied CS at MIT and then Stanford before starting at Facebook. He is a part of the PyTorch core team and is one of the leading contributors to PyTorch.", "metadata": {"source": "https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'PyTorch 1.10 Release, including CUDA Graphs APIs, Frontend and Compiler Improvements'\nauthor: Team PyTorch\n---\n\nWe are excited to announce the release of PyTorch 1.10. This release is composed of over 3,400 commits since 1.9, made by 426 contributors. We want to sincerely thank our community for continuously improving PyTorch. \n\nPyTorch 1.10 updates are focused on improving training and performance of PyTorch, and developer usability. The full release notes are available [here](https://github.com/pytorch/pytorch/releases/tag/v1.10.0). Highlights include:\n1. CUDA Graphs APIs are integrated to reduce CPU overheads for CUDA workloads.\n2. Several frontend APIs such as FX, torch.special, and nn.Module Parametrization, have moved from beta to stable. \n3. Support for automatic fusion in JIT Compiler expands to CPUs in addition to GPUs.\n4. Android NNAPI support is now available in beta.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "Along with 1.10, we are also releasing major updates to the PyTorch libraries, which you can read about in [this blog post](https://pytorch.org/blog/pytorch-1.10-new-library-releases/).\n\n\n\n# Frontend APIs\n\n### (Stable) Python code transformations with FX\n\nFX provides a Pythonic platform for transforming and lowering PyTorch programs. It is a toolkit for pass writers to facilitate Python-to-Python transformation of functions and nn.Module instances. This toolkit aims to support a subset of Python language semantics\u2014rather than the whole Python language\u2014to facilitate ease of implementation of transforms. With 1.10, FX is moving to stable. \n\nYou can learn more about FX in the [official documentation](https://pytorch.org/docs/master/fx.html) and [GitHub examples](https://github.com/pytorch/examples/tree/master/fx) of program transformations implemented using ```torch.fx```.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "Along with 1.10, we are also releasing major updates to the PyTorch libraries, which you can read about in [this blog post](https://pytorch.org/blog/pytorch-1.10-new-library-releases/).\n\n\n\n# Frontend APIs\n\n### (Stable) Python code transformations with FX\n\nFX provides a Pythonic platform for transforming and lowering PyTorch programs. It is a toolkit for pass writers to facilitate Python-to-Python transformation of functions and nn.Module instances. This toolkit aims to support a subset of Python language semantics\u2014rather than the whole Python language\u2014to facilitate ease of implementation of transforms. With 1.10, FX is moving to stable. \n\nYou can learn more about FX in the [official documentation](https://pytorch.org/docs/master/fx.html) and [GitHub examples](https://github.com/pytorch/examples/tree/master/fx) of program transformations implemented using ```torch.fx```.\n\n### (Stable) *torch.special*", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
{"page_content": "### (Stable) *torch.special* \nA ```torch.special module```, analogous to [SciPy\u2019s special module](https://docs.scipy.org/doc/scipy/reference/special.html), is now available in stable. The module has 30 operations, including gamma, Bessel, and (Gauss) error functions. \n\nRefer to this [documentation](https://pytorch.org/docs/master/special.html) for more details.\n\n### (Stable) nn.Module Parametrization \n```nn.Module``` parametrizaton, a feature that allows users to parametrize any parameter or buffer of an ```nn.Module``` without modifying the ```nn.Module``` itself, is available in stable. This release adds weight normalization (```weight_norm```), orthogonal parametrization (matrix constraints and part of pruning) and more flexibility when creating your own parametrization.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "Refer to this [tutorial](https://pytorch.org/tutorials/intermediate/parametrizations.html) and the general [documentation](https://pytorch.org/docs/master/generated/torch.nn.utils.parametrizations.spectral_norm.html?highlight=parametrize) for more details.\n\n### (Beta) CUDA Graphs APIs Integration\nPyTorch now integrates CUDA Graphs APIs to reduce CPU overheads for CUDA workloads.\n\nCUDA Graphs greatly reduce the CPU overhead for CPU-bound cuda workloads and thus improve performance by increasing GPU utilization. For distributed workloads, CUDA Graphs also reduce jitter, and since parallel workloads have to wait for the slowest worker, reducing jitter improves overall parallel efficiency.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "Integration allows seamless interop between the parts of the network captured by cuda graphs, and parts of the network that cannot be captured due to graph limitations. \n \nRead the [note](https://pytorch.org/docs/master/notes/cuda.html#cuda-graphs) for more details and examples, and refer to the general [documentation](https://pytorch.org/docs/master/generated/torch.cuda.CUDAGraph.html#torch.cuda.CUDAGraph) for additional information.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "### [Beta] Conjugate View\nPyTorch\u2019s conjugation for complex tensors ([torch.conj()](https://pytorch.org/docs/1.10.0/generated/torch.conj.html?highlight=conj#torch.conj)) is now a constant time operation, and returns a view of the input tensor with a conjugate bit set as can be seen by calling [torch.is_conj()](https://pytorch.org/docs/1.10.0/generated/torch.is_conj.html?highlight=is_conj#torch.is_conj) . This has already been leveraged in various other PyTorch operations like matrix multiplication, dot product etc., to fuse conjugation with the operation leading to significant performance gain and memory savings on both CPU and CUDA.\n\n# Distributed Training", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "### Distributed Training Releases Now in Stable \nIn 1.10, there are a number of features that are moving from beta to stable in the distributed package:\n* **(Stable) Remote Module**: This feature allows users to operate a module on a remote worker like using a local module, where the RPCs are transparent to the user. Refer to this [documentation](https://pytorch.org/docs/master/rpc.html#remotemodule) for more details.\n* **(Stable) DDP Communication Hook**: This feature allows users to override how DDP synchronizes gradients across processes. Refer to this [documentation](https://pytorch.org/docs/master/rpc.html#remotemodule) for more details. \n* **(Stable) ZeroRedundancyOptimizer**: This feature can be used in conjunction with DistributedDataParallel to reduce the size of per-process optimizer states. With this stable release, it now can handle uneven inputs to different data-parallel workers. Check out this [tutorial](https://pytorch.org/tutorials/advanced/generic_join.html). We also improved the parameter partition algorithm to better balance memory and computation overhead across processes. Refer to this [documentation](https://pytorch.org/docs/master/distributed.optim.html) and this [tutorial](https://pytorch.org/tutorials/recipes/zero_redundancy_optimizer.html) to learn more.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "# Performance Optimization and Tooling\n\n### [Beta] Profile-directed typing in TorchScript \nTorchScript has a hard requirement for source code to have type annotations in order for compilation to be successful. For a long time, it was only possible to add missing or incorrect type annotations through trial and error (i.e., by fixing the type-checking errors generated by torch.jit.script one by one), which was inefficient and time consuming. \n\nNow, we have enabled profile directed typing for torch.jit.script by leveraging existing tools like MonkeyType, which makes the process much easier, faster, and more efficient. For more details, refer to the [documentation](https://pytorch.org/docs/1.9.0/jit.html).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "### (Beta) CPU Fusion \nIn PyTorch 1.10, we've added an LLVM-based JIT compiler for CPUs that can fuse together sequences of `torch` library calls to improve performance. While we've had this capability for some time on GPUs, this release is the first time we've brought compilation to the CPU. \nYou can check out a few performance results for yourself in this [Colab notebook](https://colab.research.google.com/drive/1xaH-L0XjsxUcS15GG220mtyrvIgDoZl6?usp=sharing).\n\n### (Beta) PyTorch Profiler \nThe objective of PyTorch Profiler is to target the execution steps that are the most costly in time and/or memory, and visualize the workload distribution between GPUs and CPUs. PyTorch 1.10 includes the following key features:", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "* **Enhanced Memory View**: This helps you understand your memory usage better. This tool will help you avoid Out of Memory errors by showing active memory allocations at various points of your program run.\n* **Enhanced Automated Recommendations**: This helps provide automated performance recommendations to help optimize your model. The tools recommend changes to batch size, TensorCore, memory reduction technologies, etc.\n* **Enhanced Kernel View**: Additional columns show grid and block sizes as well as shared memory usage and registers per thread.\n* **Distributed Training**: Gloo is now supported for distributed training jobs.\n* **Correlate Operators in the Forward & Backward Pass**: This helps map the operators found in the forward pass to the backward pass, and vice versa, in a trace view.\n* **TensorCore**: This tool shows the Tensor Core (TC) usage and provides recommendations for data scientists and framework developers.\n* **NVTX**: Support for NVTX markers was ported from the legacy autograd profiler.\n* **Support for profiling on mobile devices**: The PyTorch profiler now has better integration with TorchScript and mobile backends, enabling trace collection for mobile workloads.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
-{"page_content": "Refer to this [documentation](https://pytorch.org/docs/stable/profiler.html) for details. Check out this [tutorial](https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) to learn how to get started with this feature. \n\n# PyTorch Mobile\n\n### (Beta) Android NNAPI Support in Beta \nLast year we [released prototype support](https://medium.com/pytorch/pytorch-mobile-now-supports-android-nnapi-e2a2aeb74534) for Android\u2019s Neural Networks API (NNAPI). NNAPI allows Android apps to run computationally intensive neural networks on the most powerful and efficient parts of the chips that power mobile phones, including GPUs (Graphics Processing Units) and NPUs (specialized Neural Processing Units). \n\nSince the prototype we\u2019ve added more op coverage, added support for load-time flexible shapes and ability to run the model on the host for testing. Try out this feature using the [tutorial](https://pytorch.org/tutorials/prototype/nnapi_mobilenetv2.html).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "Refer to this [tutorial](https://pytorch.org/tutorials/intermediate/parametrizations.html) and the general [documentation](https://pytorch.org/docs/master/generated/torch.nn.utils.parametrizations.spectral_norm.html?highlight=parametrize) for more details.\n\n### (Beta) CUDA Graphs APIs Integration\nPyTorch now integrates CUDA Graphs APIs to reduce CPU overheads for CUDA workloads.\n\nCUDA Graphs greatly reduce the CPU overhead for CPU-bound cuda workloads and thus improve performance by increasing GPU utilization. For distributed workloads, CUDA Graphs also reduce jitter, and since parallel workloads have to wait for the slowest worker, reducing jitter improves overall parallel efficiency.\n\nIntegration allows seamless interop between the parts of the network captured by cuda graphs, and parts of the network that cannot be captured due to graph limitations.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "Read the [note](https://pytorch.org/docs/master/notes/cuda.html#cuda-graphs) for more details and examples, and refer to the general [documentation](https://pytorch.org/docs/master/generated/torch.cuda.CUDAGraph.html#torch.cuda.CUDAGraph) for additional information. \n\n### [Beta] Conjugate View\nPyTorch\u2019s conjugation for complex tensors ([torch.conj()](https://pytorch.org/docs/1.10.0/generated/torch.conj.html?highlight=conj#torch.conj)) is now a constant time operation, and returns a view of the input tensor with a conjugate bit set as can be seen by calling [torch.is_conj()](https://pytorch.org/docs/1.10.0/generated/torch.is_conj.html?highlight=is_conj#torch.is_conj) . This has already been leveraged in various other PyTorch operations like matrix multiplication, dot product etc., to fuse conjugation with the operation leading to significant performance gain and memory savings on both CPU and CUDA.\n\n# Distributed Training\n\n### Distributed Training Releases Now in Stable", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "### Distributed Training Releases Now in Stable \nIn 1.10, there are a number of features that are moving from beta to stable in the distributed package:\n* **(Stable) Remote Module**: This feature allows users to operate a module on a remote worker like using a local module, where the RPCs are transparent to the user. Refer to this [documentation](https://pytorch.org/docs/master/rpc.html#remotemodule) for more details.\n* **(Stable) DDP Communication Hook**: This feature allows users to override how DDP synchronizes gradients across processes. Refer to this [documentation](https://pytorch.org/docs/master/rpc.html#remotemodule) for more details.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "* **(Stable) ZeroRedundancyOptimizer**: This feature can be used in conjunction with DistributedDataParallel to reduce the size of per-process optimizer states. With this stable release, it now can handle uneven inputs to different data-parallel workers. Check out this [tutorial](https://pytorch.org/tutorials/advanced/generic_join.html). We also improved the parameter partition algorithm to better balance memory and computation overhead across processes. Refer to this [documentation](https://pytorch.org/docs/master/distributed.optim.html) and this [tutorial](https://pytorch.org/tutorials/recipes/zero_redundancy_optimizer.html) to learn more. \n\n# Performance Optimization and Tooling\n\n### [Beta] Profile-directed typing in TorchScript", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "### [Beta] Profile-directed typing in TorchScript \nTorchScript has a hard requirement for source code to have type annotations in order for compilation to be successful. For a long time, it was only possible to add missing or incorrect type annotations through trial and error (i.e., by fixing the type-checking errors generated by torch.jit.script one by one), which was inefficient and time consuming. \n\nNow, we have enabled profile directed typing for torch.jit.script by leveraging existing tools like MonkeyType, which makes the process much easier, faster, and more efficient. For more details, refer to the [documentation](https://pytorch.org/docs/1.9.0/jit.html).\n\n### (Beta) CPU Fusion \nIn PyTorch 1.10, we've added an LLVM-based JIT compiler for CPUs that can fuse together sequences of `torch` library calls to improve performance. While we've had this capability for some time on GPUs, this release is the first time we've brought compilation to the CPU.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "You can check out a few performance results for yourself in this [Colab notebook](https://colab.research.google.com/drive/1xaH-L0XjsxUcS15GG220mtyrvIgDoZl6?usp=sharing).\n\n### (Beta) PyTorch Profiler \nThe objective of PyTorch Profiler is to target the execution steps that are the most costly in time and/or memory, and visualize the workload distribution between GPUs and CPUs. PyTorch 1.10 includes the following key features:\n\n* **Enhanced Memory View**: This helps you understand your memory usage better. This tool will help you avoid Out of Memory errors by showing active memory allocations at various points of your program run.\n* **Enhanced Automated Recommendations**: This helps provide automated performance recommendations to help optimize your model. The tools recommend changes to batch size, TensorCore, memory reduction technologies, etc.\n* **Enhanced Kernel View**: Additional columns show grid and block sizes as well as shared memory usage and registers per thread.", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "* **Distributed Training**: Gloo is now supported for distributed training jobs.\n* **Correlate Operators in the Forward & Backward Pass**: This helps map the operators found in the forward pass to the backward pass, and vice versa, in a trace view.\n* **TensorCore**: This tool shows the Tensor Core (TC) usage and provides recommendations for data scientists and framework developers.\n* **NVTX**: Support for NVTX markers was ported from the legacy autograd profiler.\n* **Support for profiling on mobile devices**: The PyTorch profiler now has better integration with TorchScript and mobile backends, enabling trace collection for mobile workloads.\n\nRefer to this [documentation](https://pytorch.org/docs/stable/profiler.html) for details. Check out this [tutorial](https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) to learn how to get started with this feature. \n\n# PyTorch Mobile\n\n### (Beta) Android NNAPI Support in Beta", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
+{"page_content": "### (Beta) Android NNAPI Support in Beta \nLast year we [released prototype support](https://medium.com/pytorch/pytorch-mobile-now-supports-android-nnapi-e2a2aeb74534) for Android\u2019s Neural Networks API (NNAPI). NNAPI allows Android apps to run computationally intensive neural networks on the most powerful and efficient parts of the chips that power mobile phones, including GPUs (Graphics Processing Units) and NPUs (specialized Neural Processing Units). \n\nSince the prototype we\u2019ve added more op coverage, added support for load-time flexible shapes and ability to run the model on the host for testing. Try out this feature using the [tutorial](https://pytorch.org/tutorials/prototype/nnapi_mobilenetv2.html).", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
{"page_content": "Additionally, Transfer Learning steps have been added to Object Detection examples. Check out this [GitHub page](https://github.com/pytorch/android-demo-app/tree/master/ObjectDetection#transfer-learning) to learn more. Please provide your feedback or ask questions on the [forum](https://discuss.pytorch.org/c/mobile/18). You can also check out [this presentation](https://www.youtube.com/watch?v=B-2spa3UCTU) to get an overview. \n\nThanks for reading. If you\u2019re interested in these updates and want to join the PyTorch community, we encourage you to join the [discussion forums](https://discuss.pytorch.org/) and [open GitHub issues](https://github.com/pytorch/pytorch/issues). To get the latest news from PyTorch, follow us on [Twitter](https://twitter.com/PyTorch), [Medium](https://medium.com/pytorch), [YouTube](https://www.youtube.com/pytorch), and [LinkedIn](https://www.linkedin.com/company/pytorch). \n\nCheers!\nTeam PyTorch", "metadata": {"source": "https://pytorch.org/blog/pytorch-1.10-released/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Ambient Clinical Intelligence: Generating Medical Reports with PyTorch\"\nauthor: Miguel Del-Agua, Principal Research Scientist, Nuance and Jeremy Jancsary, Senior Principal Research Scientist, Nuance\nfeatured-img: \"\"\n---\n\n## Introduction\n\nComplete and accurate clinical documentation is an essential tool for tracking patient care. It allows for treatment plans to be shared among care teams to aid in continuity of care and ensures a transparent and effective process for reimbursement.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Physicians are responsible for documenting patient care. Traditional clinical documentation methods have resulted in a sub-par patient-provider experience, less time interacting with patients, and decreased work-life balance. A significant amount of physicians\u2019 time is spent in front of the computer doing administrative tasks. As a result, patients are less satisfied with the overall experience, and physicians, who prepare for years studying medicine, cannot practice at the top of their license and are burned out. Every hour physicians provide direct clinical face time to patients results in nearly two additional hours spent on EHR and desk work within the clinic day. Outside office hours, physicians [spend another 1 to 2 hours of personal](https://www.acpjournals.org/doi/10.7326/m16-0961) time each night doing additional computer and other clerical work.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "* [42% of all physicians reported having burnout. \u2013 Medscape](https://www.medscape.com/slideshow/2020-lifestyle-burnout-6012460)\n* [The problem has grown worse due to the pandemic with 64% of U.S. physicians now reporting burnout. - AAFP](https://www.aafp.org/journals/fpm/blogs/inpractice/entry/covid_burnout_survey.html#:~:text=Physician%20burnout%20was%20already%20a,5%2C000%20%E2%80%94%20practice%20in%20the%20U.S.)\n* [\"Too many bureaucratic tasks e.g., charting and paperwork\" is the leading contribution to burnout, increased computerization ranks 4th.](https://login.medscape.com/login/sso/getlogin?urlCache=aHR0cHM6Ly93d3cubWVkc2NhcGUuY29tL3NsaWRlc2hvdy8yMDIwLWxpZmVzdHlsZS1idXJub3V0LTYwMTI0NjA%3D&ac=401) - Medscape\n* [75% of U.S. Consumers Wish Their Healthcare Experiences Were More Personalized,](https://www.businesswire.com/news/home/20200218005006/en/75-of-U.S.-Consumers-Wish-Their-Healthcare-Experiences-Were-More-Personalized-Redpoint-Global-Survey-Reveals)- Business Wire\n* [61% of patients would visit their healthcare provider more often if the communication experience felt more personalized.](https://www.businesswire.com/news/home/20200218005006/en/75-of-U.S.-Consumers-Wish-Their-Healthcare-Experiences-Were-More-Personalized-Redpoint-Global-Survey-Reveals) \u2013 Business Wire", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Physician burnout is one of the primary causes for increased [medical errors](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6175626/), malpractice suits, turnover, and decreased access to care. Burnout leads to an increase in healthcare costs and a decrease in overall patient satisfaction. [Burnout costs the United States $4.6 billion a year.](https://www.nejm.org/doi/full/10.1056/NEJMp2003149)\n\nWhat can we do to bring back trust, joy, and humanity to the delivery of healthcare? A significant portion of the administrative work consists of entering patient data into Electronic Health Records (EHRs) and creating clinical documentation. Clinical documentation is created from information already in the EHR as well as from the patient-provider encounter conversation.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "This article will showcase how the Nuance Dragon Ambient eXperience (DAX), an AI-powered, voice-enabled, ambient clinical intelligence solution, automatically documents patient encounters accurately and efficiently at the point of care and the technologies that enable it.\n\nNuance DAX enhances the quality of care and patient experience, increases provider efficiency and satisfaction, and improves financial outcomes. It can be used in office and telehealth settings in all ambulatory specialties, including primary and urgent care.\n\n\n
\n
\n\n## Natural Language Processing", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## Natural Language Processing\n\nNatural Language Processing (NLP) is one of the most challenging fields in Artificial Intelligence (AI). It comprehends a set of algorithms that allow computers to understand or generate the language used by humans. These algorithms can process and analyze vast amounts of natural language data from different sources (either sound or text) to build models that can understand, classify, or even generate natural language as humans would. Like other fields in AI, NLP has significantly progressed thanks to the advent of Deep Learning (DL), which has resulted in models that can obtain results on par with humans in some tasks.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "Physicians are responsible for documenting patient care. Traditional clinical documentation methods have resulted in a sub-par patient-provider experience, less time interacting with patients, and decreased work-life balance. A significant amount of physicians\u2019 time is spent in front of the computer doing administrative tasks. As a result, patients are less satisfied with the overall experience, and physicians, who prepare for years studying medicine, cannot practice at the top of their license and are burned out. Every hour physicians provide direct clinical face time to patients results in nearly two additional hours spent on EHR and desk work within the clinic day. Outside office hours, physicians [spend another 1 to 2 hours of personal](https://www.acpjournals.org/doi/10.7326/m16-0961) time each night doing additional computer and other clerical work.\n\n* [42% of all physicians reported having burnout. \u2013 Medscape](https://www.medscape.com/slideshow/2020-lifestyle-burnout-6012460)", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "* [The problem has grown worse due to the pandemic with 64% of U.S. physicians now reporting burnout. - AAFP](https://www.aafp.org/journals/fpm/blogs/inpractice/entry/covid_burnout_survey.html#:~:text=Physician%20burnout%20was%20already%20a,5%2C000%20%E2%80%94%20practice%20in%20the%20U.S.)\n* [\"Too many bureaucratic tasks e.g., charting and paperwork\" is the leading contribution to burnout, increased computerization ranks 4th.](https://login.medscape.com/login/sso/getlogin?urlCache=aHR0cHM6Ly93d3cubWVkc2NhcGUuY29tL3NsaWRlc2hvdy8yMDIwLWxpZmVzdHlsZS1idXJub3V0LTYwMTI0NjA%3D&ac=401) - Medscape\n* [75% of U.S. Consumers Wish Their Healthcare Experiences Were More Personalized,](https://www.businesswire.com/news/home/20200218005006/en/75-of-U.S.-Consumers-Wish-Their-Healthcare-Experiences-Were-More-Personalized-Redpoint-Global-Survey-Reveals)- Business Wire", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "* [61% of patients would visit their healthcare provider more often if the communication experience felt more personalized.](https://www.businesswire.com/news/home/20200218005006/en/75-of-U.S.-Consumers-Wish-Their-Healthcare-Experiences-Were-More-Personalized-Redpoint-Global-Survey-Reveals) \u2013 Business Wire\n\nPhysician burnout is one of the primary causes for increased [medical errors](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6175626/), malpractice suits, turnover, and decreased access to care. Burnout leads to an increase in healthcare costs and a decrease in overall patient satisfaction. [Burnout costs the United States $4.6 billion a year.](https://www.nejm.org/doi/full/10.1056/NEJMp2003149)", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "What can we do to bring back trust, joy, and humanity to the delivery of healthcare? A significant portion of the administrative work consists of entering patient data into Electronic Health Records (EHRs) and creating clinical documentation. Clinical documentation is created from information already in the EHR as well as from the patient-provider encounter conversation. \n\nThis article will showcase how the Nuance Dragon Ambient eXperience (DAX), an AI-powered, voice-enabled, ambient clinical intelligence solution, automatically documents patient encounters accurately and efficiently at the point of care and the technologies that enable it.\n\nNuance DAX enhances the quality of care and patient experience, increases provider efficiency and satisfaction, and improves financial outcomes. It can be used in office and telehealth settings in all ambulatory specialties, including primary and urgent care.\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\n\n## Natural Language Processing\n\nNatural Language Processing (NLP) is one of the most challenging fields in Artificial Intelligence (AI). It comprehends a set of algorithms that allow computers to understand or generate the language used by humans. These algorithms can process and analyze vast amounts of natural language data from different sources (either sound or text) to build models that can understand, classify, or even generate natural language as humans would. Like other fields in AI, NLP has significantly progressed thanks to the advent of Deep Learning (DL), which has resulted in models that can obtain results on par with humans in some tasks.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "These advanced NLP techniques are being applied in healthcare. During a typical patient-provider encounter, a conversation ensues where the doctor constructs, through questions and answers, a chronological description of the development of the patient's presenting illness or symptoms. A physician examines the patient and makes clinical decisions to establish a diagnosis and determine a treatment plan. This conversation, and data in the EHR, provide the required information for physicians to generate the clinical documentation, referred to as medical reports.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Two main NLP components play a role in automating the creation of clinical documentation. The first component, Automatic Speech Recognition (ASR), is used to translate speech into text. It takes the audio recording of the encounter and generates a conversation transcription (cf. Figure 2). The second component, Automatic Text Summarization, helps generate summaries from large text documents. This component is responsible for understanding and capturing the nuances and most essential aspects from the transcribed conversation into a final report in narrative form (cf. Figure 3), structured form, or a combination of both.\n\nWe will focus on this second component, Automatic Text Summarization, which is a difficult task with many challenges:", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "* Its performance is tied to the ASR quality from multiple speakers (noisy input).\n* The input is conversational in nature and contains layman's terms.\n* Protected Health Information (PHI) regulations limit medical data access.\n* The information for one output sentence is potentially spread across multiple conversation turns.\n* There is no explicit sentence alignment between input and output.\n* Various medical specialties, encounter types, and EHR systems constitute a broad and complex output space. \n* Physicians have different styles of conducting encounters and have their preferences for medical reports; there is no standard. \n* Standard summarization metrics might differ from human judgment of quality.\n\n\n
\n
\n\n\nFigure 2: Transcript of a patient-doctor conversation\n
\n\n\n
\n
", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "\nFigure 3: Excerpt of an AI-generated medical report. HPI stands for History of present illness.\n
\n\n## Text Summarization with PyTorch and Fairseq\n\n[PyTorch](https://pytorch.org/) is an open-source machine learning framework developed by Facebook that helps researchers prototype Deep Learning models. The [Fairseq](https://github.com/pytorch/fairseq) toolkit is built on top of PyTorch and focuses on sequence generation tasks, such as Neural Machine Translation (NMT) or Text Summarization. Fairseq features an active community that is continuously providing reference implementations of state-of-the-art models. It contains many built-in components (model architectures, modules, loss functions, and optimizers) and is easily extendable with plugins.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "Two main NLP components play a role in automating the creation of clinical documentation. The first component, Automatic Speech Recognition (ASR), is used to translate speech into text. It takes the audio recording of the encounter and generates a conversation transcription (cf. Figure 2). The second component, Automatic Text Summarization, helps generate summaries from large text documents. This component is responsible for understanding and capturing the nuances and most essential aspects from the transcribed conversation into a final report in narrative form (cf. Figure 3), structured form, or a combination of both.\n\nWe will focus on this second component, Automatic Text Summarization, which is a difficult task with many challenges:\n\n* Its performance is tied to the ASR quality from multiple speakers (noisy input).\n* The input is conversational in nature and contains layman's terms.\n* Protected Health Information (PHI) regulations limit medical data access.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "* The information for one output sentence is potentially spread across multiple conversation turns.\n* There is no explicit sentence alignment between input and output.\n* Various medical specialties, encounter types, and EHR systems constitute a broad and complex output space. \n* Physicians have different styles of conducting encounters and have their preferences for medical reports; there is no standard. \n* Standard summarization metrics might differ from human judgment of quality.\n\n\n
\n
\n\n\nFigure 2: Transcript of a patient-doctor conversation\n
\n\n\n
\n
\n\n\nFigure 3: Excerpt of an AI-generated medical report. HPI stands for History of present illness.\n
\n\n## Text Summarization with PyTorch and Fairseq", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "## Text Summarization with PyTorch and Fairseq\n\n[PyTorch](https://pytorch.org/) is an open-source machine learning framework developed by Facebook that helps researchers prototype Deep Learning models. The [Fairseq](https://github.com/pytorch/fairseq) toolkit is built on top of PyTorch and focuses on sequence generation tasks, such as Neural Machine Translation (NMT) or Text Summarization. Fairseq features an active community that is continuously providing reference implementations of state-of-the-art models. It contains many built-in components (model architectures, modules, loss functions, and optimizers) and is easily extendable with plugins.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "Text summarization constitutes a significant challenge in NLP. We need models capable of generating a short version of a document while retaining the key points and avoiding uninformative content. These challenges can be addressed with different approaches. 1). Abstractive text summarization aimed at training models that can generate a summary in narrative form. 2). Extractive methods where the models are trained to select the most important parts from the input text. 3). A combination of the two, where the essential parts from the input are selected and then summarized in an abstractive fashion. Hence, summarization can be accomplished via a single end-to-end network or as a pipeline of extractive and abstractive components. To that end, Fairseq provides all the necessary tools to be successful in our endeavor. It features either end-to-end models such as the classical Transformer, different types of Language Models and pre-trained versions that enable researchers to focus on what matters most\u2014to build state-of-the-art models that generate valuable reports.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "However, we are not just summarizing the transcribed conversation; we generate high-quality medical reports, which have many considerations.\n\n* Every section of a medical report is different in terms of content, structure, fluency, etc.\n* All medical facts mentioned in the conversation should be present in the report, for example, a particular treatment or dosage.\n* In the healthcare domain, the vocabulary is extensive, and models need to deal with medical terminology.\n* Patient-doctor conversations are usually much longer than the final report.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "All these challenges require our researchers to run a battery of extensive experiments. Thanks to the flexibility of PyTorch and Fairseq, their productivity has greatly increased. Further, the ecosystem offers an easy path from ideation, implementation, experimentation, and final roll-out to production. Using multiple GPUs or CPUs is as simple as providing an additional argument to the tools, and because of the tight Python integration, PyTorch code can be easily debugged.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "In our continuous effort to contribute to the open-source community, features have been developed at Nuance and pushed to the Fairseq GitHub repository. These try to overcome some of the challenges mentioned such as, facilitating copying of, especially rare or unseen, words from the input to summary, training speedups by improving Tensor Core utilization, and ensuring TorchScript compatibility of different Transformer configurations. Following, we will show an example of how to train a Transformer model with a Pointer Generator mechanism (Transformer-PG), which can copy words from the input.\n\n## How to build a Transformer model with a Pointer Generator mechanism\n\nIn this step-by-step guide, it is assumed the user has already installed PyTorch and Fairseq.\n\n### 1. Create a vocabulary and extend it with source position markers:\n\nThese markers will allow the model to point to any word in the input sequence.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```python\nvocab_size=\nposition_markers=512\nexport LC_ALL=C\ncat train.src train.tgt |\n tr -s '[:space:]' '\\n' |\n sort |\n uniq -c |\n sort -k1,1bnr -k2 |\n head -n \"$((vocab_size - 4))\" |\n awk '{ print $2 \" \" $1 }' > dict.pg.txt\npython3 -c \"[print(' 0'.format(n)) for n in range($position_markers)]\" >> dict.pg.txt\n```\n\nThis will create a file \"dict.pg.txt\" that contains the \\ most frequent words followed by 512 position markers named from \"\\\" to \"\\\".\n\nIn case we have an input like\n\n```python\nsrc = \"Hello, I'm The Dogtor\"\n```\n\nit could happen that our model has been trained without the word \"Dogtor\" in its vocabulary. Therefore, when we feed this sequence into the model, it should be converted to:\n\n```python\nsrc = \"Hello, I'm The \"\n```", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```python\nsrc = \"Hello, I'm The \"\n```\n\nNow, \"\\\" is part of our vocabulary and could be predicted by the model (this is where the pointer-generator comes in). In such a case, we will only need to post-process the output to replace \"\\\" by the word at input position 3.\n\n### 2. Preprocess the text data to replace unknown words by its positional markers:\n\nWe can use the scripts from [https://github.com/pytorch/fairseq/tree/master/examples/pointer_generator](https://github.com/pytorch/fairseq/tree/master/examples/pointer_generator).\n\n```python\n# Considering we have our data in:\n# train_src = /path/to/train.src\n# train_tgt = /path/to/train.tgt\n# valid_src = /path/to/valid.src\n# valid_tgt = /path/to/valid.tgt\n./preprocess.py --source /path/to/train.src \\\n --target /path/to/train.tgt \\\n --vocab <(cut -d' ' -f1 dict.pg.txt) \\\n --source-out /path/to/train.pg.src \\\n --target-out /path/to/train.pg.tgt", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "./preprocess.py --source /path/to/valid.src \\\n --target /path/to/valid.tgt \\\n --vocab <(cut -d' ' -f1 dict.pg.txt) \\\n --source-out /path/to/valid.pg.src \\\n --target-out /path/to/valid.pg.tgt\n\n./preprocess.py --source /path/to/test.src \\\n --vocab <(cut -d' ' -f1 dict.pg.txt) \\\n --source-out /path/to/test.pg.src\n```\n\n### 3. Now let's binarize the data, so that it can be processed faster:", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "```python\nfairseq-preprocess --task \"translation\" \\\n --source-lang \"pg.src\" \\\n --target-lang \"pg.tgt\" \\\n --trainpref /path/to/train \\\n --validpref /path/to/valid \\\n --srcdict dict.pg.txt \\\n --cpu \\\n --joined-dictionary \\\n --destdir \n```\t\t \n\t\t\t\t \nYou might notice the type of task is \"translation\". This is because there is no \"summarization\" task available; we could understand it as a kind of NMT task where the input and output languages are shared and the output (summary) is shorter than the input.\n\n### 4. Now we can train the model:", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "### 4. Now we can train the model:\n\n```python\nfairseq-train \\\n --save-dir \\\n --task \"translation\" \\\n --source-lang \"src\" \\\n --target-lang \"tgt\" \\\n --arch \"transformer_pointer_generator\" \\\n --max-source-positions 512 \\\n --max-target-positions 128 \\\n --truncate-source \\\n --max-tokens 2048 \\\n --required-batch-size-multiple 1 \\\n --required-seq-len-multiple 8 \\\n --share-all-embeddings \\\n --dropout 0.1 \\\n --criterion \"cross_entropy\" \\\n --optimizer adam \\\n --adam-betas '(0.9, 0.98)' \\\n --adam-eps 1e-9 \\\n --update-freq 4 \\\n --lr 0.004 \\\n # Pointer Generator\n --alignment-layer -1 \\\n --alignment-heads 1 \\\n --source-position-markers 512\n```", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "This configuration makes use of features Nuance has contributed back to Fairseq:\n\n* Transformer with a Pointer Generator mechanism to facilitate copying of words from the input.\n* Sequence length padded to a multiple of 8 to better use tensor cores and reduce training time.\n\n### 5. Now let's take a look at how to generate a summary with our new medical report generation system:\n\n```python\nimport torch\nfrom examples.pointer_generator.pointer_generator_src.transformer_pg import TransformerPointerGeneratorModel\n\n# Patient-Doctor conversation\ninput = \"[doctor] Lisa Simpson, thirty six year old female, presents to the clinic today because \" \\\n \"she has severe right wrist pain\"\n\n# Load the model\nmodel = TransformerPointerGeneratorModel.from_pretrained(data_name_or_path=,\n model_name_or_path=,\n checkpoint_file=\"checkpoint_best.pt\")\n\nresult = model.translate([input], beam=2)", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "result = model.translate([input], beam=2)\n\nprint(result[0])\nMs. is a 36-year-old female who presents to the clinic today for evaluation of her right wrist.\n```\n\n### 6. Alternatively, we can use fairseq-interactive and a postprocessing tool to substitute positional unknown tokens by its words from the input:\n\n```python\nfairseq-interactive \\\n --batch-size \\\n --task translation \\\n --source-lang src \\\n --target-lang tgt \\\n --path /checkpoint_last.pt \\\n --input /path/to/test.pg.src \\\n --buffer-size 20 \\\n --max-len-a 0 \\\n --max-len-b 128 \\\n --beam 2 \\\n --skip-invalid-size-inputs-valid-test | tee generate.out\n\ngrep \"^H-\" generate.out | cut -f 3- > generate.hyp\n\n./postprocess.py \\\n\t--source <(awk 'NF<512' /path/to/test.pg.src) \\\n\t--target generate.hyp \\\n\t--target-out generate.hyp.processed\n```", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "Now we have the final set of reports in \"generate.hyp.processed\", with \"\\\" replaced by the original word from the input sequence.\n\n## Model Deployment\n\nPyTorch offers great flexibility in modeling and a rich surrounding ecosystem. However, while several recent articles have suggested that the use of PyTorch in research and academia may be close to surpassing TensorFlow, there seems to be an overall sense of TensorFlow being the preferred platform for deployment to production. Is this still the case in 2021? Teams looking to serve their PyTorch models in production have a few options.\n\nBefore describing our journey, let's take a brief detour and define the term model.\n\n### Models as computation graphs", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "In our continuous effort to contribute to the open-source community, features have been developed at Nuance and pushed to the Fairseq GitHub repository. These try to overcome some of the challenges mentioned such as, facilitating copying of, especially rare or unseen, words from the input to summary, training speedups by improving Tensor Core utilization, and ensuring TorchScript compatibility of different Transformer configurations. Following, we will show an example of how to train a Transformer model with a Pointer Generator mechanism (Transformer-PG), which can copy words from the input.\n\n## How to build a Transformer model with a Pointer Generator mechanism\n\nIn this step-by-step guide, it is assumed the user has already installed PyTorch and Fairseq.\n\n### 1. Create a vocabulary and extend it with source position markers:\n\nThese markers will allow the model to point to any word in the input sequence.\n\n```python\nvocab_size=\nposition_markers=512\nexport LC_ALL=C\ncat train.src train.tgt |", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "export LC_ALL=C\ncat train.src train.tgt |\n tr -s '[:space:]' '\\n' |\n sort |\n uniq -c |\n sort -k1,1bnr -k2 |\n head -n \"$((vocab_size - 4))\" |\n awk '{ print $2 \" \" $1 }' > dict.pg.txt\npython3 -c \"[print(' 0'.format(n)) for n in range($position_markers)]\" >> dict.pg.txt\n```\n\nThis will create a file \"dict.pg.txt\" that contains the \\ most frequent words followed by 512 position markers named from \"\\\" to \"\\\".\n\nIn case we have an input like\n\n```python\nsrc = \"Hello, I'm The Dogtor\"\n```\n\nit could happen that our model has been trained without the word \"Dogtor\" in its vocabulary. Therefore, when we feed this sequence into the model, it should be converted to:\n\n```python\nsrc = \"Hello, I'm The \"\n```\n\nNow, \"\\\" is part of our vocabulary and could be predicted by the model (this is where the pointer-generator comes in). In such a case, we will only need to post-process the output to replace \"\\\" by the word at input position 3.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "### 2. Preprocess the text data to replace unknown words by its positional markers:\n\nWe can use the scripts from [https://github.com/pytorch/fairseq/tree/master/examples/pointer_generator](https://github.com/pytorch/fairseq/tree/master/examples/pointer_generator).\n\n```python\n# Considering we have our data in:\n# train_src = /path/to/train.src\n# train_tgt = /path/to/train.tgt\n# valid_src = /path/to/valid.src\n# valid_tgt = /path/to/valid.tgt\n./preprocess.py --source /path/to/train.src \\\n --target /path/to/train.tgt \\\n --vocab <(cut -d' ' -f1 dict.pg.txt) \\\n --source-out /path/to/train.pg.src \\\n --target-out /path/to/train.pg.tgt\n\n./preprocess.py --source /path/to/valid.src \\\n --target /path/to/valid.tgt \\\n --vocab <(cut -d' ' -f1 dict.pg.txt) \\\n --source-out /path/to/valid.pg.src \\\n --target-out /path/to/valid.pg.tgt\n\n./preprocess.py --source /path/to/test.src \\", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "./preprocess.py --source /path/to/test.src \\\n --vocab <(cut -d' ' -f1 dict.pg.txt) \\\n --source-out /path/to/test.pg.src\n```\n\n### 3. Now let's binarize the data, so that it can be processed faster:\n\n```python\nfairseq-preprocess --task \"translation\" \\\n --source-lang \"pg.src\" \\\n --target-lang \"pg.tgt\" \\\n --trainpref /path/to/train \\\n --validpref /path/to/valid \\\n --srcdict dict.pg.txt \\\n --cpu \\\n --joined-dictionary \\\n --destdir \n```\t\t \n\t\t\t\t \nYou might notice the type of task is \"translation\". This is because there is no \"summarization\" task available; we could understand it as a kind of NMT task where the input and output languages are shared and the output (summary) is shorter than the input.\n\n### 4. Now we can train the model:\n\n```python\nfairseq-train \\\n --save-dir \\", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "--save-dir \\\n --task \"translation\" \\\n --source-lang \"src\" \\\n --target-lang \"tgt\" \\\n --arch \"transformer_pointer_generator\" \\\n --max-source-positions 512 \\\n --max-target-positions 128 \\\n --truncate-source \\\n --max-tokens 2048 \\\n --required-batch-size-multiple 1 \\\n --required-seq-len-multiple 8 \\\n --share-all-embeddings \\\n --dropout 0.1 \\\n --criterion \"cross_entropy\" \\\n --optimizer adam \\\n --adam-betas '(0.9, 0.98)' \\\n --adam-eps 1e-9 \\\n --update-freq 4 \\\n --lr 0.004 \\\n # Pointer Generator\n --alignment-layer -1 \\\n --alignment-heads 1 \\\n --source-position-markers 512\n```\n\nThis configuration makes use of features Nuance has contributed back to Fairseq:", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "* Transformer with a Pointer Generator mechanism to facilitate copying of words from the input.\n* Sequence length padded to a multiple of 8 to better use tensor cores and reduce training time.\n\n### 5. Now let's take a look at how to generate a summary with our new medical report generation system:\n\n```python\nimport torch\nfrom examples.pointer_generator.pointer_generator_src.transformer_pg import TransformerPointerGeneratorModel\n\n# Patient-Doctor conversation\ninput = \"[doctor] Lisa Simpson, thirty six year old female, presents to the clinic today because \" \\\n \"she has severe right wrist pain\"\n\n# Load the model\nmodel = TransformerPointerGeneratorModel.from_pretrained(data_name_or_path=,\n model_name_or_path=,\n checkpoint_file=\"checkpoint_best.pt\")\n\nresult = model.translate([input], beam=2)\n\nprint(result[0])", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "print(result[0])\nMs. is a 36-year-old female who presents to the clinic today for evaluation of her right wrist.\n```\n\n### 6. Alternatively, we can use fairseq-interactive and a postprocessing tool to substitute positional unknown tokens by its words from the input:\n\n```python\nfairseq-interactive \\\n --batch-size \\\n --task translation \\\n --source-lang src \\\n --target-lang tgt \\\n --path /checkpoint_last.pt \\\n --input /path/to/test.pg.src \\\n --buffer-size 20 \\\n --max-len-a 0 \\\n --max-len-b 128 \\\n --beam 2 \\\n --skip-invalid-size-inputs-valid-test | tee generate.out\n\ngrep \"^H-\" generate.out | cut -f 3- > generate.hyp\n\n./postprocess.py \\\n\t--source <(awk 'NF<512' /path/to/test.pg.src) \\\n\t--target generate.hyp \\\n\t--target-out generate.hyp.processed\n```", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "--target-out generate.hyp.processed\n```\n\nNow we have the final set of reports in \"generate.hyp.processed\", with \"\\\" replaced by the original word from the input sequence.\n\n## Model Deployment\n\nPyTorch offers great flexibility in modeling and a rich surrounding ecosystem. However, while several recent articles have suggested that the use of PyTorch in research and academia may be close to surpassing TensorFlow, there seems to be an overall sense of TensorFlow being the preferred platform for deployment to production. Is this still the case in 2021? Teams looking to serve their PyTorch models in production have a few options.\n\nBefore describing our journey, let's take a brief detour and define the term model.\n\n### Models as computation graphs", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "A few years back, it was still common for machine learning toolkits to support only particular classes of models of a rather fixed and rigid structure, with only a few degrees of freedom (like the kernel of a support vector machine or the number of hidden layers of a neural network). Inspired by foundational work in Theano, toolkits like Microsoft's CNTK or Google's TensorFlow were among the first to popularize a more flexible view on models, as computation graphs with associated parameters that can be estimated from data. This view blurred the boundaries between popular types of models (such as DNNs or SVMs), as it became easy to blend the characteristics of each into your type of graph. Still, such a graph had to be defined upfront before estimating its parameters, and it was pretty static. This made it easy to save models to a self-contained bundle, like a TensorFlow SavedModel (such a bundle simply contains the structure of the graph, as well as the concrete values of the estimated parameters). However, debugging such models can be difficult because the statements in the Python code that build the graph are logically separate from the lines that execute it. Researchers also long for easier ways of expressing dynamic behavior, such as the computation steps of the forward pass of a model being conditionally dependent on its input data (or its previous output).", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "Most recently, the above limitations have led to a second revolution spearheaded by PyTorch and TensorFlow 2. The computation graph is no longer defined explicitly. Instead, it will be populated implicitly as the Python code executes operations on tensor arguments. An essential technique that powers this development is automatic differentiation. As the computation graph is being built implicitly while executing the steps of the forward pass, all the necessary data will be tracked for later computation of the gradient concerning the model parameters. This allows for great flexibility in training a model, but it raises an important question. If the computation happening inside a model is only implicitly defined through our Python code's steps as it executes concrete data, what is it that we want to save as a model? The answer \u2013 at least initially \u2013 was the Python code with all its dependencies, along with the estimated parameters. This is undesirable for practical reasons. For instance, there is a danger that the team working on model deployment does not exactly reproduce the Python code dependencies used during training, leading to subtly divergent behavior. The solution typically consists of combining two techniques, scripting and tracing, that is, extra annotations in your Python code and execution of your code on exemplary input data, allowing PyTorch to define and save the graph that should be executed during later inference on new, unseen data. This requires some discipline by whoever creates the model code (arguably voiding some of the original flexibility of eager execution), but it results in a self-contained model bundle in TorchScript format. The solution in TensorFlow 2 is remarkably similar.", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "### Serving our report generation models", "metadata": {"source": "https://pytorch.org/blog/ambient-clinical-intelligence-generating-medical-reports-with-pytorch/", "category": "pytorch blogs"}}
@@ -809,59 +805,60 @@
{"page_content": "---\nlayout: blog_detail\ntitle: 'Microsoft becomes maintainer of the Windows version of PyTorch'\nauthor: Maxim Lukiyanov - Principal PM at Microsoft, Emad Barsoum - Group EM at Microsoft, Guoliang Hua - Principal EM at Microsoft, Nikita Shulga - Tech Lead at Facebook, Geeta Chauhan - PE Lead at Facebook, Chris Gottbrath - Technical PM at Facebook, Jiachen Pu - Engineer at Facebook\n\n---\n\nAlong with the PyTorch 1.6 release, we are excited to announce that Microsoft has expanded its participation in the PyTorch community and will be responsible for the development and maintenance of the PyTorch build for Windows.", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
{"page_content": "According to the latest [Stack Overflow developer survey](https://insights.stackoverflow.com/survey/2020#technology-developers-primary-operating-systems), Windows remains the primary operating system for the developer community (46% Windows vs 28% MacOS). [Jiachen Pu](https://github.com/peterjc123) initially made a heroic effort to add support for PyTorch on Windows, but due to limited resources, Windows support for PyTorch has lagged behind other platforms. Lack of test coverage resulted in unexpected issues popping up every now and then. Some of the core tutorials, meant for new users to learn and adopt PyTorch, would fail to run. The installation experience was also not as smooth, with the lack of official PyPI support for PyTorch on Windows. Lastly, some of the PyTorch functionality was simply not available on the Windows platform, such as the TorchAudio domain library and distributed training support. To help alleviate this pain, Microsoft is happy to bring its Windows expertise to the table and bring PyTorch on Windows to its best possible self.", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
{"page_content": "In the PyTorch 1.6 release, we have improved the core quality of the Windows build by bringing test coverage up to par with Linux for core PyTorch and its domain libraries and by automating tutorial testing. Thanks to the broader PyTorch community, which contributed TorchAudio support to Windows, we were able to add test coverage to all three domain libraries: TorchVision, TorchText and TorchAudio. In subsequent releases of PyTorch, we will continue improving the Windows experience based on community feedback and requests. So far, the feedback we received from the community points to distributed training support and a better installation experience using pip as the next areas of improvement.", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "In addition to the native Windows experience, Microsoft released a preview adding [GPU compute support to Windows Subsystem for Linux (WSL) 2](https://blogs.windows.com/windowsdeveloper/2020/06/17/gpu-accelerated-ml-training-inside-the-windows-subsystem-for-linux/) distros, with a focus on enabling AI and ML developer workflows. WSL is designed for developers that want to run any Linux based tools directly on Windows. This preview enables valuable scenarios for a variety of frameworks and Python packages that utilize [NVIDIA CUDA](https://developer.nvidia.com/cuda/wsl) for acceleration and only support Linux. This means WSL customers using the preview can run native Linux based PyTorch applications on Windows unmodified without the need for a traditional virtual machine or a dual boot setup.", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## Getting started with PyTorch on Windows\nIt's easy to get started with PyTorch on Windows. To install PyTorch using Anaconda with the latest GPU support, run the command below. To install different supported configurations of PyTorch, refer to the installation instructions on [pytorch.org](https://pytorch.org).\n\n`conda install pytorch torchvision cudatoolkit=10.2 -c pytorch`\n\nOnce you install PyTorch, learn more by visiting the [PyTorch Tutorials](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html) and [documentation](https://pytorch.org/docs/stable/index.html).\n\n\n

\n
", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## Getting started with PyTorch on Windows Subsystem for Linux\nThe [preview of NVIDIA CUDA support in WSL](https://docs.microsoft.com/en-us/windows/win32/direct3d12/gpu-cuda-in-wsl) is now available to Windows Insiders running Build 20150 or higher. In WSL, the command to install PyTorch using Anaconda is the same as the above command for native Windows. If you prefer pip, use the command below.\n\n`pip install torch torchvision`\n\nYou can use the same tutorials and documentation inside your WSL environment as on native Windows. This functionality is still in preview so if you run into issues with WSL please share feedback via the [WSL GitHub repo](https://github.com/microsoft/WSL) or with NVIDIA CUDA support share via NVIDIA\u2019s [Community Forum for CUDA on WSL](https://forums.developer.nvidia.com/c/accelerated-computing/cuda/cuda-on-windows-subsystem-for-linux/303).", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "In addition to the native Windows experience, Microsoft released a preview adding [GPU compute support to Windows Subsystem for Linux (WSL) 2](https://blogs.windows.com/windowsdeveloper/2020/06/17/gpu-accelerated-ml-training-inside-the-windows-subsystem-for-linux/) distros, with a focus on enabling AI and ML developer workflows. WSL is designed for developers that want to run any Linux based tools directly on Windows. This preview enables valuable scenarios for a variety of frameworks and Python packages that utilize [NVIDIA CUDA](https://developer.nvidia.com/cuda/wsl) for acceleration and only support Linux. This means WSL customers using the preview can run native Linux based PyTorch applications on Windows unmodified without the need for a traditional virtual machine or a dual boot setup.\n\n## Getting started with PyTorch on Windows", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "## Getting started with PyTorch on Windows\nIt's easy to get started with PyTorch on Windows. To install PyTorch using Anaconda with the latest GPU support, run the command below. To install different supported configurations of PyTorch, refer to the installation instructions on [pytorch.org](https://pytorch.org).\n\n`conda install pytorch torchvision cudatoolkit=10.2 -c pytorch`\n\nOnce you install PyTorch, learn more by visiting the [PyTorch Tutorials](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html) and [documentation](https://pytorch.org/docs/stable/index.html).\n\n\n

\n
\n\n## Getting started with PyTorch on Windows Subsystem for Linux", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "The [preview of NVIDIA CUDA support in WSL](https://docs.microsoft.com/en-us/windows/win32/direct3d12/gpu-cuda-in-wsl) is now available to Windows Insiders running Build 20150 or higher. In WSL, the command to install PyTorch using Anaconda is the same as the above command for native Windows. If you prefer pip, use the command below.\n\n`pip install torch torchvision`\n\nYou can use the same tutorials and documentation inside your WSL environment as on native Windows. This functionality is still in preview so if you run into issues with WSL please share feedback via the [WSL GitHub repo](https://github.com/microsoft/WSL) or with NVIDIA CUDA support share via NVIDIA\u2019s [Community Forum for CUDA on WSL](https://forums.developer.nvidia.com/c/accelerated-computing/cuda/cuda-on-windows-subsystem-for-linux/303).\n\n## Feedback", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
{"page_content": "## Feedback\nIf you find gaps in the PyTorch experience on Windows, please let us know on the [PyTorch discussion forum](https://discuss.pytorch.org/c/windows/26) or file an issue on [GitHub](https://github.com/pytorch/pytorch) using the #module: windows label.", "metadata": {"source": "https://pytorch.org/blog/microsoft-becomes-maintainer-of-the-windows-version-of-pytorch/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: \"Accelerated PyTorch 2 Transformers\"\nauthor: Michael Gschwind, Driss Guessous, Christian Puhrsch\n---\n\nThe PyTorch 2.0 release includes a new high-performance implementation of the PyTorch Transformer API with the goal of making training and deployment of state-of-the-art Transformer models affordable. Following the successful release of \u201cfastpath\u201d inference execution (\u201cBetter Transformer\u201d), this release introduces high-performance support for training and inference using a custom kernel architecture for scaled dot product attention (SPDA).", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
-{"page_content": "You can take advantage of the new fused SDPA kernels either by calling the new SDPA operator directly (as described in the [SDPA tutorial](https://pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html#beta-implementing-high-performance-transformers-with-scaled-dot-product-attention-sdpa)), or transparently via integration into the pre-existing PyTorch Transformer API. All features of the PyTorch Transformer API will continue to work compatibly, with many features mapped to high-performance SDPA kernels, while other features are impossible to support with higher performance (e.g., need_weights, as per below) while expanded high-performance support for other features may still be under active development. \\\n \\\nSimilar to the \u201cfastpath\u201d architecture, custom kernels are fully integrated into the PyTorch Transformer API \u2013 thus, using the native Transformer and MultiHeadAttention API will enable users to transparently see significant speed improvements. Unlike the \u201cfastpath\u201d architecture, the newly introduced \u201ccustom kernels\u201d support many more use cases including models using Cross-Attention, Transformer Decoders, and for training models, in addition to the existing fastpath inference for fixed and variable sequence length Transformer Encoder and Self Attention use cases.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
+{"page_content": "You can take advantage of the new fused SDPA kernels either by calling the new SDPA operator directly (as described in the [SDPA tutorial](https://pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html#beta-implementing-high-performance-transformers-with-scaled-dot-product-attention-sdpa)), or transparently via integration into the pre-existing PyTorch Transformer API. All features of the PyTorch Transformer API will continue to work compatibly, with many features mapped to high-performance SDPA kernels, while other features are impossible to support with higher performance (e.g., need_weights, as per below) while expanded high-performance support for other features may still be under active development. \\\n \\", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
+{"page_content": "\\\nSimilar to the \u201cfastpath\u201d architecture, custom kernels are fully integrated into the PyTorch Transformer API \u2013 thus, using the native Transformer and MultiHeadAttention API will enable users to transparently see significant speed improvements. Unlike the \u201cfastpath\u201d architecture, the newly introduced \u201ccustom kernels\u201d support many more use cases including models using Cross-Attention, Transformer Decoders, and for training models, in addition to the existing fastpath inference for fixed and variable sequence length Transformer Encoder and Self Attention use cases.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
{"page_content": "To take full advantage of different hardware models and Transformer use cases, multiple SDPA custom kernels are supported, with custom kernel selection logic that will pick the highest-performance kernel for a given model and hardware type. In particular, the first custom kernels included with the PyTorch 2.0 release are the [Flash Attention](https://arxiv.org/abs/2205.14135) kernel (sdpa_flash, for 16-bit floating point training and inference on Nvidia GPUs with SM80+ architecture level) and the [xFormers memory-efficient attention](https://github.com/facebookresearch/xformers) kernel (sdpa_mem_eff, for 16-bit and 32-bit floating point training and inference on a broad range of Nvidia GPUs). A general-purpose kernel sdpa_math provides an implementation when the custom kernels are not applicable.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
-{"page_content": "As mentioned, custom kernels provide a wider range of support for execution scenarios To ensure efficient execution (e,g., to use GPU tensor cores), model configurations need to meet a small number of requirements. This list of requirements will evolve over time, prospectively relaxing constraints limiting the usage of currently supported custom kernels, or providing additional kernels in the future.\n\nFor the most up to date list of custom kernels and dispatch constraints, you can refer to [sdp_utils.h](https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/transformers/cuda/sdp_utils.h). As of PyTorch 2.0, the existing fused SDPA kernels have the following constraints:", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
-{"page_content": "* Flash Attention only supports 16 bit floating point data types (float16 and bfloat16).\n* The head dimension must be a multiple of 8 for 16-bit floating point numbers and a multiple of 4 for 32-bit floating point numbers. At present, the maximum head_dim support for the Flash Attention custom kernel is 128.\n* The CUDA architecture level must be sm5x or better for the mem_efficient kernel, and sm80 for Flash Attention.\n* Flash Attention supports arbitrary dropout, in PyTorch 2.0 the mem_efficient kernel does not support dropout (i.e., dropout must be set to zero for this kernel to be selected in PyTorch 2.0). \n* To support variable-sequence length batches, all SDPA kernels support Nested Tensor inputs that combine input data and padding information using variable sequence length tensors for forward. (You can find more information about Nested Tensors in the [Nested Tensor tutorial](https://pytorch.org/tutorials/prototype/nestedtensor.html).)\n* You can specify both a _key_padding_mask_ and an _attn_mask_ by combining them before passing them to the SDPA operator. In particular, you can use the per-batch-element key padding mask of the nn.Transformer API to implement training for variable-sequence length inputs in a batch.\n* At present, the only attention mask supported by fused kernel implementation is the causal mask commonly used for training. To specify the causal mask in custom kernels, it must be specified with the _is_causal_ boolean and _attn_mask_ must be None. \n* Support for Nested Tensors is still under development. Specifically, in PyTorch 2.0, only the sdpa_math kernel supports training with Nested Tensors. Also, PyTorch 2.0 does not support Nested Tensors as part of code being compiled with torch.compile(). \n* The SDPA operator does not support returning averaged attention weights because computing them defeats the optimizations that enabled fused kernels to execute more efficiently. The argument _need_weights_ for torch.nn.MultiheadAttention's forward function defaults to True. In order to use the fused kernels, _need_weights_ needs to be set to _need_weights=False_.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
+{"page_content": "As mentioned, custom kernels provide a wider range of support for execution scenarios To ensure efficient execution (e,g., to use GPU tensor cores), model configurations need to meet a small number of requirements. This list of requirements will evolve over time, prospectively relaxing constraints limiting the usage of currently supported custom kernels, or providing additional kernels in the future.\n\nFor the most up to date list of custom kernels and dispatch constraints, you can refer to [sdp_utils.h](https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/transformers/cuda/sdp_utils.h). As of PyTorch 2.0, the existing fused SDPA kernels have the following constraints:\n\n\n\n* Flash Attention only supports 16 bit floating point data types (float16 and bfloat16).\n* The head dimension must be a multiple of 8 for 16-bit floating point numbers and a multiple of 4 for 32-bit floating point numbers. At present, the maximum head_dim support for the Flash Attention custom kernel is 128.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
+{"page_content": "* The CUDA architecture level must be sm5x or better for the mem_efficient kernel, and sm80 for Flash Attention.\n* Flash Attention supports arbitrary dropout, in PyTorch 2.0 the mem_efficient kernel does not support dropout (i.e., dropout must be set to zero for this kernel to be selected in PyTorch 2.0). \n* To support variable-sequence length batches, all SDPA kernels support Nested Tensor inputs that combine input data and padding information using variable sequence length tensors for forward. (You can find more information about Nested Tensors in the [Nested Tensor tutorial](https://pytorch.org/tutorials/prototype/nestedtensor.html).)\n* You can specify both a _key_padding_mask_ and an _attn_mask_ by combining them before passing them to the SDPA operator. In particular, you can use the per-batch-element key padding mask of the nn.Transformer API to implement training for variable-sequence length inputs in a batch.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
+{"page_content": "* At present, the only attention mask supported by fused kernel implementation is the causal mask commonly used for training. To specify the causal mask in custom kernels, it must be specified with the _is_causal_ boolean and _attn_mask_ must be None. \n* Support for Nested Tensors is still under development. Specifically, in PyTorch 2.0, only the sdpa_math kernel supports training with Nested Tensors. Also, PyTorch 2.0 does not support Nested Tensors as part of code being compiled with torch.compile(). \n* The SDPA operator does not support returning averaged attention weights because computing them defeats the optimizations that enabled fused kernels to execute more efficiently. The argument _need_weights_ for torch.nn.MultiheadAttention's forward function defaults to True. In order to use the fused kernels, _need_weights_ needs to be set to _need_weights=False_.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
{"page_content": "We find that an attention mask is rarely used in real-world applications, except for the causal mask during training. Consequently, we reduce kernel complexity and compute cost by building in the option to use a causal mask as attention mask, and select this new capability with the _is_causal_ parameter introduced in conjunction with the new SDPA operator. \n\nProviding the _is_causal_ Boolean flag for the frequently used causal mask also obviates the expensive and memory-intensive allocation of a causal mask, increasing training memory efficiency by allowing more memory to be used for large batch sizes, and reduce memory bandwidth and cache contention \u2013 which are both at a premium in GPU accelerators \u2013 by not needing to load an attention mask tensor.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
{"page_content": "If the constraints of none of the available custom kernels are met, then training falls back to using the default sdpa_math kernel, implementing the mathematical equations for scaled dot product attention using a sequence of PyTorch operator to implement SDPA. This is the most general \u201ccatch-all\u201d fallback kernel to ensure successful training for all models.\n\nIn addition to the existing Transformer API, model developers may also use the scaled dot product attention kernels directly by calling the new `scaled_dot_product_attention()` operator. This operator may be used to efficiently implement multi-head attention by combining it with in-projection and outprojection, as described in the [SDPA tutorial](https://pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html).", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
{"page_content": "In addition to adding custom kernels, Accelerated PyTorch 2 Transformers are integrated with PyTorch 2.0 compilation. To use your model while benefiting from the additional acceleration of PT2-compilation (for inference or training), pre-process the model with\n\n\n```\nmodel = torch.compile(model)\n```\n\n\nWe have achieved major speedups for training transformer models and in particular large language models with Accelerated PyTorch 2 Transformers using a combination of custom kernels and torch.compile(). \n\n\n{:width=\"100%\"}\nFigure: Using scaled dot product attention with custom kernels and torch.compile delivers significant speedups for training large language models, such as for [nanoGPT](https://github.com/karpathy/nanoGPT) shown here.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
{"page_content": "Finally, because the custom kernels are much more memory efficient, try to increase the size of training batches to achieve faster training with increased batch size.\n\nIn addition to automatic kernel selection, a context manager enables developers to override the kernel selection algorithm \u2013 this is not required for day to day operation, but enables developers to debug their code as well as enable performance engineers to override kernel selection. The SDPA tutorial provides additional information on using the SDPA context manager.\n\nIn addition to availability as part of the nn.Transformer API, Accelerated PyTorch 2 Transformer custom kernels are also available in conjunction with the torchtext, torchvision, and fairseq domain libraries with the launch of PyTorch 2.0.", "metadata": {"source": "https://pytorch.org/blog/accelerated-pytorch-2/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'Mapillary Research: Seamless Scene Segmentation and In-Place Activated BatchNorm'\nauthor: Lorenzo Porzi, Mapillary\nredirect_from: /2019/07/23/mapillary-research.html\n---\n\nWith roads in developed countries like the US changing up to 15% annually, Mapillary addresses a growing demand for keeping maps updated by combining images from any camera into a 3D visualization of the world. Mapillary's independent and collaborative approach enables anyone to collect, share, and use street-level images for improving maps, developing cities, and advancing the automotive industry.\n\nToday, people and organizations all over the world have contributed more than 600 million images toward Mapillary's mission of helping people understand the world's places through images and making this data available, with clients and partners including the World Bank, HERE, and Toyota Research Institute.", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
{"page_content": "Mapillary\u2019s computer vision technology brings intelligence to maps in an unprecedented way, increasing our overall understanding of the world. [Mapillary](https://www.mapillary.com/) runs state-of-the-art semantic image analysis and image-based 3d modeling at scale and on all its images. In this post we discuss two recent works from Mapillary Research and their implementations in PyTorch - Seamless Scene Segmentation [1] and In-Place Activated BatchNorm [2] - generating Panoptic segmentation results and saving up to 50% of GPU memory during training, respectively.\n\n## Seamless Scene Segmentation\n\n_Github project page: [https://github.com/mapillary/seamseg/](https://github.com/mapillary/seamseg/)_\n\n\n

\n
", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
-{"page_content": "The objective of Seamless Scene Segmentation is to predict a \u201cpanoptic\u201d segmentation [3] from an image, that is a complete labeling where each pixel is assigned with a class id and, where possible, an instance id. Like many modern CNNs dealing with instance detection and segmentation, we adopt the Mask R-CNN framework [4], using ResNet50 + FPN [5] as a backbone. This architecture works in two stages: first, the \u201cProposal Head\u201d selects a set of candidate bounding boxes on the image (i.e. the proposals) that could contain an object; then, the \u201cMask Head\u201d focuses on each proposal, predicting its class and segmentation mask. The output of this process is a \u201csparse\u201d instance segmentation, covering only the parts of the image that contain countable objects (e.g. cars and pedestrians).", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
+{"page_content": "
\n\nThe objective of Seamless Scene Segmentation is to predict a \u201cpanoptic\u201d segmentation [3] from an image, that is a complete labeling where each pixel is assigned with a class id and, where possible, an instance id. Like many modern CNNs dealing with instance detection and segmentation, we adopt the Mask R-CNN framework [4], using ResNet50 + FPN [5] as a backbone. This architecture works in two stages: first, the \u201cProposal Head\u201d selects a set of candidate bounding boxes on the image (i.e. the proposals) that could contain an object; then, the \u201cMask Head\u201d focuses on each proposal, predicting its class and segmentation mask. The output of this process is a \u201csparse\u201d instance segmentation, covering only the parts of the image that contain countable objects (e.g. cars and pedestrians).", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
{"page_content": "To complete our panoptic approach coined Seamless Scene Segmentation, we add a third stage to Mask R-CNN. Stemming from the same backbone, the \u201cSemantic Head\u201d predicts a dense semantic segmentation over the whole image, also accounting for the uncountable or amorphous classes (e.g. road and sky). The outputs of the Mask and Semantic heads are finally fused using a simple non-maximum suppression algorithm to generate the final panoptic prediction. All details about the actual network architecture, used losses and underlying math can be found at the [project website](https://research.mapillary.com/publication/cvpr19a) for our CVPR 2019 paper [1].", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
{"page_content": "While several versions of Mask R-CNN are publicly available, including an [official implementation](https://github.com/facebookresearch/Detectron) written in Caffe2, at Mapillary we decided to build Seamless Scene Segmentation from scratch using PyTorch, in order to have full control and understanding of the whole pipeline. While doing so we encountered a couple of main stumbling blocks, and had to come up with some creative workarounds we are going to describe next.\n\n## Dealing with variable-sized tensors", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
{"page_content": "## Dealing with variable-sized tensors\n\nSomething that sets aside panoptic segmentation networks from traditional CNNs is the prevalence of variable-sized data. In fact, many of the quantities we are dealing with cannot be easily represented with fixed sized tensors: each image contains a different number of objects, the Proposal head can produce a different number of proposals for each image, and the images themselves can have different sizes. While this is not a problem per-se -- one could just process images one at a time -- we would still like to exploit batch-level parallelism as much as possible. Furthermore, when performing distributed training with multiple GPUs, `DistributedDataParallel` expects its inputs to be batched, uniformly-sized tensors.\n\n
\n

\n
", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
-{"page_content": "Our solution to these issues is to wrap each batch of variable-sized tensors in a `PackedSequence`. `PackedSequence` is little more than a glorified list class for tensors, tagging its contents as \u201crelated\u201d, ensuring that they all share the same type, and providing useful methods like moving all the tensors to a particular device, etc. When performing light-weight operations that wouldn\u2019t be much faster with batch-level parallelism, we simply iterate over the contents of the `PackedSequence` in a for loop. When performance is crucial, e.g. in the body of the network, we simply concatenate the contents of the PackedSequence, adding zero padding as required (like in RNNs with variable-length inputs), and keeping track of the original dimensions of each tensor.\n\n`PackedSequence`s also help us deal with the second problem highlighted above. We slightly modify `DistributedDataParallel` to recognize `PackedSequence` inputs, splitting them in equally sized chunks and distributing their contents across the GPUs.", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
-{"page_content": "## Asymmetric computational graphs with Distributed Data Parallel\n\nAnother, perhaps more subtle, peculiarity of our network is that it can generate asymmetric computational graphs across GPUs. In fact, some of the modules that compose the network are \u201coptional\u201d, in the sense that they are not always computed for all images. As an example, when the Proposal head doesn\u2019t output any proposal, the Mask head is not traversed at all. If we are training on multiple GPUs with `DistributedDataParallel`, this results in one of the replicas not computing gradients for the Mask head parameters.\n\nPrior to PyTorch 1.1, this resulted in a crash, so we had to develop a workaround. Our simple but effective solution was to compute a \u201cfake forward pass\u201d when no actual forward is required, i.e. something like this:\n\n```python\ndef fake_forward():\n fake_input = get_correctly_shaped_fake_input()\n fake_output = mask_head(fake_input)\n fake_loss = fake_output.sum() * 0\n return fake_loss\n```", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
-{"page_content": "Here, we generate a batch of bogus data, pass it through the Mask head, and return a loss that always back-progates zeros to all parameters.\n\nStarting from PyTorch 1.1 this workaround is no longer required: by setting `find_unused_parameters=True` in the constructor, `DistributedDataParallel` is told to identify parameters whose gradients have not been computed by all replicas and correctly handle them. This leads to some substantial simplifications in our code base!\n\n## In-place Activated BatchNorm\n\n_Github project page: [https://github.com/mapillary/inplace_abn/](https://github.com/mapillary/inplace_abn/)_", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
+{"page_content": "
\n\nOur solution to these issues is to wrap each batch of variable-sized tensors in a `PackedSequence`. `PackedSequence` is little more than a glorified list class for tensors, tagging its contents as \u201crelated\u201d, ensuring that they all share the same type, and providing useful methods like moving all the tensors to a particular device, etc. When performing light-weight operations that wouldn\u2019t be much faster with batch-level parallelism, we simply iterate over the contents of the `PackedSequence` in a for loop. When performance is crucial, e.g. in the body of the network, we simply concatenate the contents of the PackedSequence, adding zero padding as required (like in RNNs with variable-length inputs), and keeping track of the original dimensions of each tensor.", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
+{"page_content": "`PackedSequence`s also help us deal with the second problem highlighted above. We slightly modify `DistributedDataParallel` to recognize `PackedSequence` inputs, splitting them in equally sized chunks and distributing their contents across the GPUs.\n\n## Asymmetric computational graphs with Distributed Data Parallel\n\nAnother, perhaps more subtle, peculiarity of our network is that it can generate asymmetric computational graphs across GPUs. In fact, some of the modules that compose the network are \u201coptional\u201d, in the sense that they are not always computed for all images. As an example, when the Proposal head doesn\u2019t output any proposal, the Mask head is not traversed at all. If we are training on multiple GPUs with `DistributedDataParallel`, this results in one of the replicas not computing gradients for the Mask head parameters.", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
+{"page_content": "Prior to PyTorch 1.1, this resulted in a crash, so we had to develop a workaround. Our simple but effective solution was to compute a \u201cfake forward pass\u201d when no actual forward is required, i.e. something like this:\n\n```python\ndef fake_forward():\n fake_input = get_correctly_shaped_fake_input()\n fake_output = mask_head(fake_input)\n fake_loss = fake_output.sum() * 0\n return fake_loss\n```\n\nHere, we generate a batch of bogus data, pass it through the Mask head, and return a loss that always back-progates zeros to all parameters.\n\nStarting from PyTorch 1.1 this workaround is no longer required: by setting `find_unused_parameters=True` in the constructor, `DistributedDataParallel` is told to identify parameters whose gradients have not been computed by all replicas and correctly handle them. This leads to some substantial simplifications in our code base!\n\n## In-place Activated BatchNorm\n\n_Github project page: [https://github.com/mapillary/inplace_abn/](https://github.com/mapillary/inplace_abn/)_", "metadata": {"source": "https://pytorch.org/blog/mapillary-research/", "category": "pytorch blogs"}}
{"page_content": "Most researchers would probably agree that there are always constraints in terms of available GPU resources, regardless if their research lab has access to only a few or multiple thousands of GPUs. In a time where at Mapillary we still worked at rather few and mostly 12GB Titan X - style prosumer GPUs, we were searching for a solution that virtually enhances the usable memory during training, so we would be able to obtain and push state-of-the-art results on dense labeling tasks like semantic segmentation. In-place activated BatchNorm is enabling us to use up to 50% more memory (at little computational overhead) and is therefore deeply integrated in all our current projects (including Seamless Scene Segmentation described above).\n\n\nFigure 2: TFLOPs/sec usage for T5-XL(3B) and T5-XXL (11B) as we increase number of nodes\n
\n\n## IBM Cloud AI System and Middleware\n\nThe AI infrastructure used for this work is a large-scale AI system on IBM Cloud consisting of nearly 200 nodes, each node with 8 NVIDIA A100 80GB cards, 96 vCPUs, and 1.2TB CPU RAM. The GPU cards within a node are connected via NVLink with a card-to-card bandwidth of 600GBps. Nodes are connected by 2 x 100Gbps Ethernet links with SRIOV based TCP/IP stack, providing a usable bandwidth of 120Gbps.", "metadata": {"source": "https://pytorch.org/blog/scaling-pytorch-fsdp-for-training-foundation-models-on-ibm-cloud/", "category": "pytorch blogs"}}
-{"page_content": "The IBM Cloud AI System has been production-ready since May of 2022 and is configured with the OpenShift container platform to run AI workloads. We also built a software stack for production AI workloads that provide end-to-end tools for training workloads. The middleware leverages Ray for pre and post processing workloads and PyTorch for training of models. We also integrate a Kubernetes native scheduler, MCAD, that manages multiple jobs with job queuing, gang scheduling, prioritization, and quota management. A multi-NIC CNI discovers all available network interfaces and handles them as a single NIC pool enabling optimized use of the network interfaces in Kubernetes. Finally, CodeFlare CLI supports a single pane for observability of the full stack using a desktop CLI (e.g., GPU utilization, application metrics like loss, gradient norm).\n\n", "metadata": {"source": "https://pytorch.org/blog/scaling-pytorch-fsdp-for-training-foundation-models-on-ibm-cloud/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\nFigure 2: TFLOPs/sec usage for T5-XL(3B) and T5-XXL (11B) as we increase number of nodes\n
\n\n## IBM Cloud AI System and Middleware\n\nThe AI infrastructure used for this work is a large-scale AI system on IBM Cloud consisting of nearly 200 nodes, each node with 8 NVIDIA A100 80GB cards, 96 vCPUs, and 1.2TB CPU RAM. The GPU cards within a node are connected via NVLink with a card-to-card bandwidth of 600GBps. Nodes are connected by 2 x 100Gbps Ethernet links with SRIOV based TCP/IP stack, providing a usable bandwidth of 120Gbps.", "metadata": {"source": "https://pytorch.org/blog/scaling-pytorch-fsdp-for-training-foundation-models-on-ibm-cloud/", "category": "pytorch blogs"}}
+{"page_content": "The IBM Cloud AI System has been production-ready since May of 2022 and is configured with the OpenShift container platform to run AI workloads. We also built a software stack for production AI workloads that provide end-to-end tools for training workloads. The middleware leverages Ray for pre and post processing workloads and PyTorch for training of models. We also integrate a Kubernetes native scheduler, MCAD, that manages multiple jobs with job queuing, gang scheduling, prioritization, and quota management. A multi-NIC CNI discovers all available network interfaces and handles them as a single NIC pool enabling optimized use of the network interfaces in Kubernetes. Finally, CodeFlare CLI supports a single pane for observability of the full stack using a desktop CLI (e.g., GPU utilization, application metrics like loss, gradient norm).\n\n", "metadata": {"source": "https://pytorch.org/blog/scaling-pytorch-fsdp-for-training-foundation-models-on-ibm-cloud/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
{"page_content": "
\nFigure 1: Performance gains of 8 training scenarios from HuggingFace\u2019s Transformer repository. First performance boost in the dark green is due to replacing the optimizer with an NVIDIA Apex fused AdamW optimizer. The light green is due to adding nvFuser. Models were run with batch size and sequence lengths of [64, 128], [8, 512], [2, 1024], [64, 128], [8, 512], [8, src_seql=512, tgt_seql=128], [8, src_seql=1024, tgt_seql=128], and [8, 512] respectively. All networks were run with Automatic Mixed Precision (AMP) enabled with dtype=float16.\n
", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "While these speedups are significant, it\u2019s important to understand that nvFuser doesn\u2019t (yet) automate everything about running networks quickly. For HuggingFace Transformers, for example, it was important to use the AdamW fused optimizer from [NVIDIA\u2019s Apex repository](https://github.com/NVIDIA/apex) as the optimizer otherwise consumed a large portion of runtime. Using the fused AdamW optimizer to make the network faster exposes the next major performance bottleneck \u2014 memory bound operations. These operations are optimized by nvFuser, providing another large performance boost. With the fused optimizer and nvFuser enabled, the training speed of these networks improved between 1.12x to 1.5x.\nHuggingFace Transformer models were run with [the torch.amp module](https://pytorch.org/docs/stable/amp.html). (\u201camp\u201d stands for Automated Mixed Precision, see the [\u201cWhat Every User Should Know about Mixed Precision in PyTorch\u201d](https://pytorch.org/blog/what-every-user-should-know-about-mixed-precision-training-in-pytorch/) blog post for details.) An option to use nvFuser was added to HuggingFace\u2019sTrainer. If you have [TorchDynamo installed](https://github.com/pytorch/torchdynamo#requirements-and-setup) you can activate it to enable nvFuser in HuggingFace by passing *torchdynamo = \u2018nvfuser\u2019* to the Trainer class.\nnvFuser has great support for normalization kernels and related fusions frequently found in Natural Language Processing (NLP) models, and it is recommended users try nvFuser in their NLP workloads.", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "## PyTorch Image Models (TIMM) Benchmarks\nnvFuser, can also significantly reduce the training time of TIMM networks, up to over 1.3x vs. eager PyTorch, and up to 1.44x vs. eager PyTorch when combined with the torch.amp module. Figure 1 shows nvFuser\u2019s speedup without torch.amp, and when torch.amp is used with the NHWC (\u201cchannels last\u201d) and NCHW (\u201cchannels first\u201d) formats. nvFuser is integrated in TIMM through FuncTorch tracing directly (without TorchDynamo) and can be used by adding the [--aot-autograd command line argument](https://github.com/rwightman/pytorch-image-models/commit/ca991c1fa57373286b9876aa63370fd19f5d6032) when running the TIMM benchmark or training script.\n\n\nFigure 1: The Y-axis is the performance gain nvFuser provides over not using nvFuser. A value of 1.0 means no change in perf, 2.0 would mean nvFuser is twice as fast, 0.5 would mean nvFuser takes twice the time to run. Square markers are with float16 Automatic Mixed Precision (AMP) and channels first contiguous inputs, circle markers are float32 inputs, and triangles are with float16 AMP and channels last contiguous inputs. Missing data points are due to an error being encountered when tracing.\n
", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\n\nWhile these speedups are significant, it\u2019s important to understand that nvFuser doesn\u2019t (yet) automate everything about running networks quickly. For HuggingFace Transformers, for example, it was important to use the AdamW fused optimizer from [NVIDIA\u2019s Apex repository](https://github.com/NVIDIA/apex) as the optimizer otherwise consumed a large portion of runtime. Using the fused AdamW optimizer to make the network faster exposes the next major performance bottleneck \u2014 memory bound operations. These operations are optimized by nvFuser, providing another large performance boost. With the fused optimizer and nvFuser enabled, the training speed of these networks improved between 1.12x to 1.5x.", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "HuggingFace Transformer models were run with [the torch.amp module](https://pytorch.org/docs/stable/amp.html). (\u201camp\u201d stands for Automated Mixed Precision, see the [\u201cWhat Every User Should Know about Mixed Precision in PyTorch\u201d](https://pytorch.org/blog/what-every-user-should-know-about-mixed-precision-training-in-pytorch/) blog post for details.) An option to use nvFuser was added to HuggingFace\u2019sTrainer. If you have [TorchDynamo installed](https://github.com/pytorch/torchdynamo#requirements-and-setup) you can activate it to enable nvFuser in HuggingFace by passing *torchdynamo = \u2018nvfuser\u2019* to the Trainer class.\nnvFuser has great support for normalization kernels and related fusions frequently found in Natural Language Processing (NLP) models, and it is recommended users try nvFuser in their NLP workloads.\n\n## PyTorch Image Models (TIMM) Benchmarks", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "## PyTorch Image Models (TIMM) Benchmarks\nnvFuser, can also significantly reduce the training time of TIMM networks, up to over 1.3x vs. eager PyTorch, and up to 1.44x vs. eager PyTorch when combined with the torch.amp module. Figure 1 shows nvFuser\u2019s speedup without torch.amp, and when torch.amp is used with the NHWC (\u201cchannels last\u201d) and NCHW (\u201cchannels first\u201d) formats. nvFuser is integrated in TIMM through FuncTorch tracing directly (without TorchDynamo) and can be used by adding the [--aot-autograd command line argument](https://github.com/rwightman/pytorch-image-models/commit/ca991c1fa57373286b9876aa63370fd19f5d6032) when running the TIMM benchmark or training script.\n\n", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\nFigure 1: The Y-axis is the performance gain nvFuser provides over not using nvFuser. A value of 1.0 means no change in perf, 2.0 would mean nvFuser is twice as fast, 0.5 would mean nvFuser takes twice the time to run. Square markers are with float16 Automatic Mixed Precision (AMP) and channels first contiguous inputs, circle markers are float32 inputs, and triangles are with float16 AMP and channels last contiguous inputs. Missing data points are due to an error being encountered when tracing.\n
", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
{"page_content": "When running with float32 precision nvFuser provides a 1.12x geometric mean (\u201cgeomean\u201d) speedup on TIMM networks, and when running with torch.amp and \u201cchannels first\u201d it provides a 1.14x geomean speedup. However, nvFuser currently doesn\u2019t speedup torch.amp and \u201cchannels last\u201d training (a .9x geomean regression), so we recommend not using it in those cases. We are actively working on improving \u201cchannels last\u201d performance now, and soon we will have two additional optimization strategies (grid persistent optimizations for channels-last normalizations and fast transposes) which we expect will provide speedups comparable to \u201cchannels first\u201d in PyTorch version 1.13 and later. Many of nvFuser\u2019s optimizations can also help in inference cases. However, in PyTorch when running inference on small batch sizes, the performance is typically limited by CPU overhead, which nvFuser can\u2019t completely remove or fix. Therefore, typically the most important optimization for inference is to enable [CUDA Graphs](https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/) when possible. Once CUDA Graphs is enabled, then it can also be beneficial to also enable fusion through nvFuser. Performance of inference is shown in Figure 2 and Figure 3. Inference is only run with float16 AMP as it is uncommon to run inference workloads in full float32 precision.", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "\nFigure 2: Performance gains of enabling CUDA Graphs, and CUDA Graphs with nvFuser compared to the performance of native PyTorch without CUDA Graphs and nvFuser across TIMM models with float16 AMP, channels first inputs, and a batch size of 1 and 8 respectively. There is a geomean speedup of 2.74x with CUDA Graphs and 2.71x with CUDA Graphs + nvFuser respectively. nvFuser provides a maximum regression of 0.68x and a maximum performance gain of 2.74x (relative to CUDA Graphs without nvFuser). Performance gain is measured relative to the average time per iteration PyTorch takes without CUDA Graphs and without nvFuser. Models are sorted by how much additional performance nvFuser is providing.\n
", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "\nFigure 3: Performance gains of enabling CUDA Graphs, and CUDA Graphs with nvFuser compared to the performance of native PyTorch without CUDA Graphs and nvFuser across TIMM models with AMP, channels last inputs, and a batch size of 1 and 8 respectively. There is a geomean speedup of 2.29x with CUDA Graphs and 2.95x with CUDA Graphs + nvFuser respectively. nvFuser provides a maximum regression of 0.86x and a maximum performance gain of 3.82x (relative to CUDA Graphs without nvFuser). Performance gain is measured relative to the average time per iteration PyTorch takes without CUDA Graphs and without nvFuser. Models are sorted by how much additional performance nvFuser is providing.\n
", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
-{"page_content": "So far nvFuser performance has not been tuned for inference workloads so its performance benefit is not consistent across all cases. However, there are still many models that benefit significantly from nvFuser during inference and we encourage users to try nvFuser in inference workloads to see if you would benefit today. Performance of nvFuser in inference workloads will improve in the future and if you\u2019re interested in nvFuser in inference workloads please reach out to us on the PyTorch forums.\n\n## Getting Started - Accelerate Your Scripts with nvFuser", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\nFigure 2: Performance gains of enabling CUDA Graphs, and CUDA Graphs with nvFuser compared to the performance of native PyTorch without CUDA Graphs and nvFuser across TIMM models with float16 AMP, channels first inputs, and a batch size of 1 and 8 respectively. There is a geomean speedup of 2.74x with CUDA Graphs and 2.71x with CUDA Graphs + nvFuser respectively. nvFuser provides a maximum regression of 0.68x and a maximum performance gain of 2.74x (relative to CUDA Graphs without nvFuser). Performance gain is measured relative to the average time per iteration PyTorch takes without CUDA Graphs and without nvFuser. Models are sorted by how much additional performance nvFuser is providing.\n
\n\n", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "
\n\n\nFigure 3: Performance gains of enabling CUDA Graphs, and CUDA Graphs with nvFuser compared to the performance of native PyTorch without CUDA Graphs and nvFuser across TIMM models with AMP, channels last inputs, and a batch size of 1 and 8 respectively. There is a geomean speedup of 2.29x with CUDA Graphs and 2.95x with CUDA Graphs + nvFuser respectively. nvFuser provides a maximum regression of 0.86x and a maximum performance gain of 3.82x (relative to CUDA Graphs without nvFuser). Performance gain is measured relative to the average time per iteration PyTorch takes without CUDA Graphs and without nvFuser. Models are sorted by how much additional performance nvFuser is providing.\n
", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
+{"page_content": "\n\nSo far nvFuser performance has not been tuned for inference workloads so its performance benefit is not consistent across all cases. However, there are still many models that benefit significantly from nvFuser during inference and we encourage users to try nvFuser in inference workloads to see if you would benefit today. Performance of nvFuser in inference workloads will improve in the future and if you\u2019re interested in nvFuser in inference workloads please reach out to us on the PyTorch forums.\n\n## Getting Started - Accelerate Your Scripts with nvFuser", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
{"page_content": "We\u2019ve created [a tutorial](https://pytorch.org/tutorials/intermediate/nvfuser_intro_tutorial.html) demonstrating how to take advantage of nvFuser to accelerate part of a standard transformer block, and how nvFuser can be used to define fast and novel operations. There are still some rough edges in nvFuser that we\u2019re working hard on improving as we\u2019ve outlined in this blog post. However we\u2019ve also demonstrated some great improvements for training speed on multiple networks in HuggingFace and TIMM and we expect there are opportunities in your networks where nvFuser can help today, and many more opportunities it will help in the future.\nIf you would like to learn more about nvFuser we recommend watching our presentations from NVIDIA\u2019s GTC conference [GTC 2022](https://www.nvidia.com/en-us/on-demand/session/gtcspring22-s41958/) and [GTC 2021](https://www.nvidia.com/en-us/on-demand/session/gtcspring21-s31952/).", "metadata": {"source": "https://pytorch.org/blog/introducing-nvfuser-a-deep-learning-compiler-for-pytorch/", "category": "pytorch blogs"}}
{"page_content": "---\nlayout: blog_detail\ntitle: 'Introducing PyTorch Profiler - the new and improved performance tool'\nauthor: Maxim Lukiyanov - Principal PM at Microsoft, Guoliang Hua - Principal Engineering Manager at Microsoft, Geeta Chauhan - Partner Engineering Lead at Facebook, Gisle Dankel - Tech Lead at Facebook\n---\n\nAlong with [PyTorch 1.8.1 release](https://github.com/pytorch/pytorch/releases/tag/v1.8.1), we are excited to announce PyTorch Profiler \u2013 the new and improved performance debugging profiler for PyTorch. Developed as part of a collaboration between Microsoft and Facebook, the PyTorch Profiler is an open-source tool that enables accurate and efficient performance analysis and troubleshooting for large-scale deep learning models.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-profiler-the-new-and-improved-performance-tool/", "category": "pytorch blogs"}}
{"page_content": "Analyzing and improving large-scale deep learning model performance is an ongoing challenge that grows in importance as the model sizes increase. For a long time, PyTorch users had a hard time solving this challenge due to the lack of available tools. There were standard performance debugging tools that provide GPU hardware level information but missed PyTorch-specific context of operations. In order to recover missed information, users needed to combine multiple tools together or manually add minimum correlation information to make sense of the data. There was also the autograd profiler (```torch.autograd.profiler```) which can capture information about PyTorch operations but does not capture detailed GPU hardware-level information and cannot provide support for visualization.", "metadata": {"source": "https://pytorch.org/blog/introducing-pytorch-profiler-the-new-and-improved-performance-tool/", "category": "pytorch blogs"}}
{"page_content": "The new PyTorch Profiler (```torch.profiler```) is a tool that brings both types of information together and then builds experience that realizes the full potential of that information. This new profiler collects both GPU hardware and PyTorch related information, correlates them, performs automatic detection of bottlenecks in the model, and generates recommendations on how to resolve these bottlenecks. All of this information from the profiler is visualized for the user in TensorBoard. The new Profiler API is natively supported in PyTorch and delivers the simplest experience available to date where users can profile their models without installing any additional packages and see results immediately in TensorBoard with the new PyTorch Profiler plugin. Below is the screenshot of PyTorch Profiler - automatic bottleneck detection. \n\n", "metadata": {"source": "https://pytorch.org/blog/how-disney-improved-activity-recognition-with-multimodal-approaches-with-pytorch/", "category": "pytorch blogs"}}
{"page_content": "