<meta charset="utf-8" /><meta http-equiv="content-security-policy" content=""><meta name="hf:doc:metadata" content="{&quot;local&quot;:&quot;efficient-training-on-multiple-gpus&quot;,&quot;sections&quot;:[{&quot;local&quot;:&quot;concepts&quot;,&quot;title&quot;:&quot;Concepts&quot;},{&quot;local&quot;:&quot;scalability-strategy&quot;,&quot;title&quot;:&quot;Scalability Strategy&quot;},{&quot;local&quot;:&quot;data-parallelism&quot;,&quot;sections&quot;:[{&quot;local&quot;:&quot;dp-vs-ddp&quot;,&quot;title&quot;:&quot;DP vs DDP&quot;}],&quot;title&quot;:&quot;Data Parallelism&quot;},{&quot;local&quot;:&quot;zero-data-parallelism&quot;,&quot;title&quot;:&quot;ZeRO Data Parallelism&quot;},{&quot;local&quot;:&quot;naive-model-parallelism-vertical-and-pipeline-parallelism&quot;,&quot;title&quot;:&quot;Naive Model Parallelism (Vertical) and Pipeline Parallelism&quot;},{&quot;local&quot;:&quot;tensor-parallelism&quot;,&quot;title&quot;:&quot;Tensor Parallelism&quot;},{&quot;local&quot;:&quot;dppp&quot;,&quot;title&quot;:&quot;DP+PP&quot;},{&quot;local&quot;:&quot;dppptp&quot;,&quot;title&quot;:&quot;DP+PP+TP&quot;},{&quot;local&quot;:&quot;zero-dppptp&quot;,&quot;title&quot;:&quot;ZeRO DP+PP+TP&quot;},{&quot;local&quot;:&quot;flexflow&quot;,&quot;title&quot;:&quot;FlexFlow&quot;},{&quot;local&quot;:&quot;which-strategy-to-use-when&quot;,&quot;title&quot;:&quot;Which Strategy To Use When&quot;}],&quot;title&quot;:&quot;Efficient Training on Multiple GPUs&quot;}" data-svelte="svelte-1phssyn">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/assets/pages/__layout.svelte-hf-doc-builder.css">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/start-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/chunks/vendor-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/chunks/paths-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/pages/__layout.svelte-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/pages/perf_train_gpu_many.mdx-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/chunks/Tip-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/chunks/IconCopyLink-hf-doc-builder.js">
	<link rel="modulepreload" href="/docs/transformers/pr_19043/en/_app/chunks/CodeBlock-hf-doc-builder.js"> 






<h1 class="relative group"><a id="efficient-training-on-multiple-gpus" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#efficient-training-on-multiple-gpus"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Efficient Training on Multiple GPUs
	</span></h1>

<p>When training on a single GPU is too slow or the model weights don’t fit in a single GPUs memory we use a mutli-GPU setup. Switching from a single GPU to multiple requires some form of parallelism as the work needs to be distributed. There are several techniques to achieve parallism such as data, tensor, or pipeline parallism. However, there is no one solution to fit them all and which settings works best depends on the hardware you are running on. While the main concepts most likely will apply to any other framework, this article is focused on PyTorch-based implementations.</p>


<div class="course-tip  bg-gradient-to-br dark:bg-gradient-to-r before:border-green-500 dark:before:border-green-800 from-green-50 dark:from-gray-900 to-white dark:to-gray-950 border border-green-50 text-green-700 dark:text-gray-400"><p>Note: Most of the strategies introduced in the <a href="perf_train_gpu_one">single GPU section</a> (such as mixed precision training or gradient accumulation) are generic and apply to training models in general so make sure to have a look at it before diving into the following sections such as multi-GPU or CPU training.</p></div>
<p>We will first discuss in depth various 1D parallelism techniques and their pros and cons and then look at how they can be combined into 2D and 3D parallelism to enable an even faster training and to support even bigger models. Various other powerful alternative approaches will be presented.</p>
<h2 class="relative group"><a id="concepts" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#concepts"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Concepts
	</span></h2>

<p>The following is the brief description of the main concepts that will be described later in depth in this document.</p>
<ol><li><strong>DataParallel (DP)</strong> - the same setup is replicated multiple times, and each being fed a slice of the data. The processing is done in parallel and all setups are synchronized at the end of each training step.</li>
<li><strong>TensorParallel (TP)</strong> - each tensor is split up into multiple chunks, so instead of having the whole tensor reside on a single gpu, each shard of the tensor resides on its designated gpu. During processing each shard gets processed separately and in parallel on different GPUs and the results are synced at the end of the step. This is what one may call horizontal parallelism, as the splitting happens on horizontal level.</li>
<li><strong>PipelineParallel (PP)</strong> - the model is split up vertically (layer-level) across multiple GPUs, so that only one or several layers of the model are places on a single gpu. Each gpu processes in parallel different stages of the pipeline and working on a small chunk of the batch.</li>
<li><strong>Zero Redundancy Optimizer (ZeRO)</strong> - Also performs sharding of the tensors somewhat similar to TP, except the whole tensor gets reconstructed in time for a forward or backward computation, therefore the model doesn’t need to be modified. It also supports various offloading techniques to compensate for limited GPU memory.</li>
<li><strong>Sharded DDP</strong> - is another name for the foundational ZeRO concept as used by various other implementations of ZeRO.</li></ol>
<p>Before diving deeper into the specifics of each concept we first have a look at the rough decision process when training large models on a large infrastructure. </p>
<h2 class="relative group"><a id="scalability-strategy" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#scalability-strategy"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Scalability Strategy
	</span></h2>

<p><strong>⇨ Single Node / Multi-GPU</strong></p>
<ul><li><p>Model fits onto a single GPU:</p>
<ol><li>DDP - Distributed DP</li>
<li>ZeRO - may or may not be faster depending on the situation and configuration used</li></ol></li>
<li><p>Model doesn’t fit onto a single GPU:</p>
<ol><li><p>PP</p></li>
<li><p>ZeRO</p></li>
<li><p>TP</p>
<p>With very fast intra-node connectivity of NVLINK or NVSwitch all three should be mostly on par, without these PP will be faster than TP or ZeRO. The degree of TP may also make a difference. Best to experiment to find the winner on your particular setup.</p>
<p>TP is almost always used within a single node. That is TP size &lt;= gpus per node.</p></li></ol></li>
<li><p>Largest Layer not fitting into a single GPU:</p>
<ol><li>If not using ZeRO - must use TP, as PP alone won’t be able to fit.</li>
<li>With ZeRO see the same entry for “Single GPU” above</li></ol></li></ul>
<p><strong>⇨ Multi-Node / Multi-GPU</strong></p>
<ul><li><p>When you have fast inter-node connectivity:</p>
<ol><li>ZeRO - as it requires close to no modifications to the model</li>
<li>PP+TP+DP - less communications, but requires massive changes to the model</li></ol></li>
<li><p>when you have slow inter-node connectivity and still low on GPU memory:</p>
<ol><li>DP+PP+TP+ZeRO-1</li></ol></li></ul>
<h2 class="relative group"><a id="data-parallelism" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#data-parallelism"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Data Parallelism
	</span></h2>

<p>Most users with just 2 GPUs already enjoy the increased training speed up thanks to <code>DataParallel</code> (DP) and <code>DistributedDataParallel</code> (DDP) that are almost trivial to use. This is a built-in feature of Pytorch. Note that in general it is advised to use DDP as it is better maintained and works for all models while DP might fail for some models. <a href="https://pytorch.org/docs/master/generated/torch.nn.DataParallel.html" rel="nofollow">PyTorch documentation</a> itself recommends the use of DDP.</p>
<h3 class="relative group"><a id="dp-vs-ddp" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#dp-vs-ddp"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>DP vs DDP
	</span></h3>

<p><code>DistributedDataParallel</code> (DDP) is typically faster than <code>DataParallel</code> (DP), but it is not always the case:</p>
<ul><li>while DP is python threads-based, DDP is multiprocess-based - and as such it has no python threads limitations, such as GIL</li>
<li>on the other hand a slow inter-connectivity between the GPU cards could lead to an actual slower outcome with DDP</li></ul>
<p>Here are the main differences in the inter-GPU communication overhead between the two modes:</p>
<p><a href="https://pytorch.org/docs/master/notes/ddp.html" rel="nofollow">DDP</a>:</p>
<ul><li>At the start time the main process replicates the model once from gpu 0 to the rest of gpus</li>
<li>Then for each batch:<ol><li>each gpu consumes each own mini-batch of data directly</li>
<li>during <code>backward</code>, once the local gradients are ready, they are then averaged across all processes</li></ol></li></ul>
<p><a href="https://pytorch.org/docs/master/generated/torch.nn.DataParallel.html" rel="nofollow">DP</a>:</p>
<p>For each batch:</p>
<ol><li>gpu 0 reads the batch of data and then sends a mini-batch to each gpu</li>
<li>replicates the up-to-date model from gpu 0 to each gpu</li>
<li>runs <code>forward</code> and sends output from each gpu to gpu 0, computes loss</li>
<li>scatters loss from gpu 0 to all gpus, runs <code>backward</code></li>
<li>sends gradients from each gpu to gpu 0 and averages those</li></ol>
<p>The only communication DDP performs per batch is sending gradients, whereas DP does 5 different data exchanges per batch.</p>
<p>DP copies data within the process via python threads, whereas DDP copies data via <a href="https://pytorch.org/docs/master/distributed.html" rel="nofollow">torch.distributed</a>.</p>
<p>Under DP gpu 0 performs a lot more work than the rest of the gpus, thus resulting in under-utilization of gpus.</p>
<p>You can use DDP across multiple machines, but this is not the case with DP.</p>
<p>There are other differences between DP and DDP but they aren’t relevant to this discussion.</p>
<p>If you want to go really deep into understanding these 2 modes, this <a href="https://www.telesens.co/2019/04/04/distributed-data-parallel-training-using-pytorch-on-aws/" rel="nofollow">article</a> is highly recommended, as it has great diagrams, includes multiple benchmarks and profiler outputs on various hardware, explains all the nuances that you may need to know.</p>
<p>Let’s look at an actual benchmark:</p>
<table><thead><tr><th align="left">Type</th>
<th>NVlink</th>
<th align="right">Time</th></tr></thead>
<tbody><tr><td align="left">2:DP</td>
<td>Y</td>
<td align="right">110s</td></tr>
<tr><td align="left">2:DDP</td>
<td>Y</td>
<td align="right">101s</td></tr>
<tr><td align="left">2:DDP</td>
<td>N</td>
<td align="right">131s</td></tr></tbody></table>
<p>Analysis:</p>
<p>Here DP is ~10% slower than DDP w/ NVlink, but ~15% faster than DDP w/o NVlink</p>
<p>The real difference will depend on how much data each GPU needs to sync with the others - the more there is to sync, the more a slow link will slow down the total runtime.</p>
<p>Here is the full benchmark code and outputs:</p>
<p><code>NCCL_P2P_DISABLE=1</code> was used to disable the NVLink feature on the corresponding benchmark.</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->
<span class="hljs-comment"># DP</span>
<span class="hljs-string">rm</span> -<span class="hljs-string">r</span> /<span class="hljs-string">tmp</span>/<span class="hljs-string">test-clm</span>; <span class="hljs-string">CUDA_VISIBLE_DEVICES</span>=<span class="hljs-string">0</span>,<span class="hljs-string">1</span> \
<span class="hljs-string">python</span> <span class="hljs-string">examples</span>/<span class="hljs-string">pytorch</span>/<span class="hljs-string">language-modeling</span>/<span class="hljs-string">run_clm</span>.<span class="hljs-string">py</span> \
<span class="hljs-built_in">--model_name_or_path</span> <span class="hljs-string">gpt2</span> <span class="hljs-built_in">--dataset_name</span> <span class="hljs-string">wikitext</span> <span class="hljs-built_in">--dataset_config_name</span> <span class="hljs-string">wikitext-2-raw-v1</span> \
<span class="hljs-built_in">--do_train</span> <span class="hljs-built_in">--output_dir</span> /<span class="hljs-string">tmp</span>/<span class="hljs-string">test-clm</span> <span class="hljs-built_in">--per_device_train_batch_size</span> <span class="hljs-string">4</span> <span class="hljs-built_in">--max_steps</span> <span class="hljs-string">200</span>

{<span class="hljs-string">&#x27;train_runtime&#x27;</span>: <span class="hljs-string">110</span>.<span class="hljs-string">5948</span>, <span class="hljs-string">&#x27;train_samples_per_second&#x27;</span>: <span class="hljs-string">1</span>.<span class="hljs-string">808</span>, <span class="hljs-string">&#x27;epoch&#x27;</span>: <span class="hljs-string">0</span>.<span class="hljs-string">69</span>}

<span class="hljs-comment"># DDP w/ NVlink</span>
<span class="hljs-string">rm</span> -<span class="hljs-string">r</span> /<span class="hljs-string">tmp</span>/<span class="hljs-string">test-clm</span>; <span class="hljs-string">CUDA_VISIBLE_DEVICES</span>=<span class="hljs-string">0</span>,<span class="hljs-string">1</span> \
<span class="hljs-string">python</span> -<span class="hljs-string">m</span> <span class="hljs-string">torch</span>.<span class="hljs-string">distributed</span>.<span class="hljs-string">launch</span> <span class="hljs-built_in">--nproc_per_node</span> <span class="hljs-string">2</span> <span class="hljs-string">examples</span>/<span class="hljs-string">pytorch</span>/<span class="hljs-string">language-modeling</span>/<span class="hljs-string">run_clm</span>.<span class="hljs-string">py</span> \
<span class="hljs-built_in">--model_name_or_path</span> <span class="hljs-string">gpt2</span> <span class="hljs-built_in">--dataset_name</span> <span class="hljs-string">wikitext</span> <span class="hljs-built_in">--dataset_config_name</span> <span class="hljs-string">wikitext-2-raw-v1</span> \
<span class="hljs-built_in">--do_train</span> <span class="hljs-built_in">--output_dir</span> /<span class="hljs-string">tmp</span>/<span class="hljs-string">test-clm</span> <span class="hljs-built_in">--per_device_train_batch_size</span> <span class="hljs-string">4</span> <span class="hljs-built_in">--max_steps</span> <span class="hljs-string">200</span>

{<span class="hljs-string">&#x27;train_runtime&#x27;</span>: <span class="hljs-string">101</span>.<span class="hljs-string">9003</span>, <span class="hljs-string">&#x27;train_samples_per_second&#x27;</span>: <span class="hljs-string">1</span>.<span class="hljs-string">963</span>, <span class="hljs-string">&#x27;epoch&#x27;</span>: <span class="hljs-string">0</span>.<span class="hljs-string">69</span>}

<span class="hljs-comment"># DDP w/o NVlink</span>
<span class="hljs-string">rm</span> -<span class="hljs-string">r</span> /<span class="hljs-string">tmp</span>/<span class="hljs-string">test-clm</span>; <span class="hljs-string">NCCL_P2P_DISABLE</span>=<span class="hljs-string">1</span> <span class="hljs-string">CUDA_VISIBLE_DEVICES</span>=<span class="hljs-string">0</span>,<span class="hljs-string">1</span> \
<span class="hljs-string">python</span> -<span class="hljs-string">m</span> <span class="hljs-string">torch</span>.<span class="hljs-string">distributed</span>.<span class="hljs-string">launch</span> <span class="hljs-built_in">--nproc_per_node</span> <span class="hljs-string">2</span> <span class="hljs-string">examples</span>/<span class="hljs-string">pytorch</span>/<span class="hljs-string">language-modeling</span>/<span class="hljs-string">run_clm</span>.<span class="hljs-string">py</span> \
<span class="hljs-built_in">--model_name_or_path</span> <span class="hljs-string">gpt2</span> <span class="hljs-built_in">--dataset_name</span> <span class="hljs-string">wikitext</span> <span class="hljs-built_in">--dataset_config_name</span> <span class="hljs-string">wikitext-2-raw-v1</span> \
<span class="hljs-built_in">--do_train</span> <span class="hljs-built_in">--output_dir</span> /<span class="hljs-string">tmp</span>/<span class="hljs-string">test-clm</span> <span class="hljs-built_in">--per_device_train_batch_size</span> <span class="hljs-string">4</span> <span class="hljs-built_in">--max_steps</span> <span class="hljs-string">200</span>

{<span class="hljs-string">&#x27;train_runtime&#x27;</span>: <span class="hljs-string">131</span>.<span class="hljs-string">4367</span>, <span class="hljs-string">&#x27;train_samples_per_second&#x27;</span>: <span class="hljs-string">1</span>.<span class="hljs-string">522</span>, <span class="hljs-string">&#x27;epoch&#x27;</span>: <span class="hljs-string">0</span>.<span class="hljs-string">69</span>}<!-- HTML_TAG_END --></pre></div>
<p>Hardware: 2x TITAN RTX 24GB each + NVlink with 2 NVLinks (<code>NV2</code> in <code>nvidia-smi topo -m</code>)
Software: <code>pytorch-1.8-to-be</code> + <code>cuda-11.0</code> / <code>transformers==4.3.0.dev0</code></p>
<h2 class="relative group"><a id="zero-data-parallelism" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#zero-data-parallelism"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>ZeRO Data Parallelism
	</span></h2>

<p>ZeRO-powered data parallelism (ZeRO-DP) is described on the following diagram from this <a href="https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/" rel="nofollow">blog post</a>
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero.png" alt="DeepSpeed-Image-1"></p>
<p>It can be difficult to wrap one’s head around it, but in reality the concept is quite simple. This is just the usual <code>DataParallel</code> (DP), except, instead of replicating the full model params, gradients and optimizer states, each GPU stores only a slice of it.  And then at run-time when the full layer params are needed just for the given layer, all GPUs synchronize to give each other parts that they miss - this is it.</p>
<p>Consider this simple model with 3 layers, where each layer has 3 params:</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->La |<span class="hljs-string"> Lb </span>|<span class="hljs-string"> Lc
---</span>|<span class="hljs-string">----</span>|<span class="hljs-string">---
a0 </span>|<span class="hljs-string"> b0 </span>|<span class="hljs-string"> c0
a1 </span>|<span class="hljs-string"> b1 </span>|<span class="hljs-string"> c1
a2 </span>|<span class="hljs-string"> b2 </span>|<span class="hljs-string"> c2</span><!-- HTML_TAG_END --></pre></div>
<p>Layer La has weights a0, a1 and a2.</p>
<p>If we have 3 GPUs, the Sharded DDP (= Zero-DP) splits the model onto 3 GPUs like so:</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->GPU0:
La |<span class="hljs-string"> Lb </span>|<span class="hljs-string"> Lc
---</span>|<span class="hljs-string">----</span>|<span class="hljs-string">---
a0 </span>|<span class="hljs-string"> b0 </span>|<span class="hljs-string"> c0

GPU1:
La </span>|<span class="hljs-string"> Lb </span>|<span class="hljs-string"> Lc
---</span>|<span class="hljs-string">----</span>|<span class="hljs-string">---
a1 </span>|<span class="hljs-string"> b1 </span>|<span class="hljs-string"> c1

GPU2:
La </span>|<span class="hljs-string"> Lb </span>|<span class="hljs-string"> Lc
---</span>|<span class="hljs-string">----</span>|<span class="hljs-string">---
a2 </span>|<span class="hljs-string"> b2 </span>|<span class="hljs-string"> c2</span><!-- HTML_TAG_END --></pre></div>
<p>In a way this is the same horizontal slicing, as tensor parallelism, if you imagine the typical DNN diagram. Vertical slicing is where one puts whole layer-groups on different GPUs. But it’s just the starting point.</p>
<p>Now each of these GPUs will get the usual mini-batch as it works in DP:</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START --><span class="hljs-attribute">x0</span> <span class="hljs-operator">=</span>&gt; GPU0
<span class="hljs-attribute">x1</span> <span class="hljs-operator">=</span>&gt; GPU1
<span class="hljs-attribute">x2</span> <span class="hljs-operator">=</span>&gt; GPU2<!-- HTML_TAG_END --></pre></div>
<p>The inputs are unmodified - they think they are going to be processed by the normal model.</p>
<p>First, the inputs hit the layer La.</p>
<p>Let’s focus just on GPU0: x0 needs a0, a1, a2 params to do its forward path, but GPU0 has only a0 - it gets sent a1 from GPU1 and a2 from GPU2, bringing all pieces of the model together.</p>
<p>In parallel, GPU1 gets mini-batch x1 and it only has a1, but needs a0 and a2 params, so it gets those from GPU0 and GPU2.</p>
<p>Same happens to GPU2 that gets input x2. It gets a0 and a1 from GPU0 and GPU1, and with its a2 it reconstructs the full tensor.</p>
<p>All 3 GPUs get the full tensors reconstructed and a forward happens.</p>
<p>As soon as the calculation is done, the data that is no longer needed gets dropped - it’s only used during the calculation. The reconstruction is done efficiently via a pre-fetch.</p>
<p>And the whole process is repeated for layer Lb, then Lc forward-wise, and then backward Lc -&gt; Lb -&gt; La.</p>
<p>To me this sounds like an efficient group backpacking weight distribution strategy:</p>
<ol><li>person A carries the tent</li>
<li>person B carries the stove</li>
<li>person C carries the axe</li></ol>
<p>Now each night they all share what they have with others and get from others what they don’t have, and in the morning they pack up their allocated type of gear and continue on their way. This is Sharded DDP / Zero DP.</p>
<p>Compare this strategy to the simple one where each person has to carry their own tent, stove and axe, which would be far more inefficient. This is DataParallel (DP and DDP) in Pytorch.</p>
<p>While reading the literature on this topic you may encounter the following synonyms: Sharded, Partitioned.</p>
<p>If you pay close attention the way ZeRO partitions the model’s weights - it looks very similar to tensor parallelism which will be discussed later. This is because it partitions/shards each layer’s weights, unlike vertical model parallelism which is discussed next.</p>
<p>Implementations:</p>
<ul><li><a href="https://www.deepspeed.ai/features/#the-zero-redundancy-optimizer" rel="nofollow">DeepSpeed</a> ZeRO-DP stages 1+2+3</li>
<li><a href="https://github.com/facebookresearch/fairscale/#optimizer-state-sharding-zero" rel="nofollow">Fairscale</a> ZeRO-DP stages 1+2+3</li>
<li><a href="main_classes/trainer#trainer-integrations"><code>transformers</code> integration</a></li></ul>
<h2 class="relative group"><a id="naive-model-parallelism-vertical-and-pipeline-parallelism" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#naive-model-parallelism-vertical-and-pipeline-parallelism"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Naive Model Parallelism (Vertical) and Pipeline Parallelism
	</span></h2>

<p>Naive Model Parallelism (MP) is where one spreads groups of model layers across multiple GPUs. The mechanism is relatively simple - switch the desired layers <code>.to()</code> the desired devices and now whenever the data goes in and out those layers switch the data to the same device as the layer and leave the rest unmodified.</p>
<p>We refer to it as Vertical MP, because if you remember how most models are drawn, we slice the layers vertically. For example, if the following diagram shows an 8-layer model:</p>

	<div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5   text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
	<div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div>
	Copied</div></button></div>
	<pre><!-- HTML_TAG_START -->===================  ===================
|<span class="hljs-string">  0 </span>|<span class="hljs-string"> 1 </span>|<span class="hljs-string"> 2 </span>|<span class="hljs-string"> 3  </span>|<span class="hljs-string">  </span>|<span class="hljs-string">  4 </span>|<span class="hljs-string"> 5 </span>|<span class="hljs-string"> 6 </span>|<span class="hljs-string"> 7  </span>|
===================  ===================
        gpu0                 gpu1<!-- HTML_TAG_END --></pre></div>
<p>we just sliced it in 2 vertically, placing layers 0-3 onto GPU0 and 4-7 to GPU1.</p>
<p>Now while data travels from layer 0 to 1, 1 to 2 and 2 to 3 this is just the normal model. But when data needs to pass from layer 3 to layer 4 it needs to travel from GPU0 to GPU1 which introduces a communication overhead. If the participating GPUs are on the same compute node (e.g. same physical machine) this copying is pretty fast, but if the GPUs are located on different compute nodes (e.g. multiple machines) the communication overhead could be significantly larger.</p>
<p>Then layers 4 to 5 to 6 to 7 are as a normal model would have and when the 7th layer completes we often need to send the data back to layer 0 where the labels are (or alternatively send the labels to the last layer). Now the loss can be computed and the optimizer can do its work.</p>
<p>Problems:</p>
<ul><li>the main deficiency and why this one is called “naive” MP, is that all but one GPU is idle at any given moment. So if 4 GPUs are used, it’s almost identical to quadrupling the amount of memory of a single GPU, and ignoring the rest of the hardware. Plus there is the overhead of copying the data between devices. So 4x 6GB cards will be able to accommodate the same size as 1x 24GB card using naive MP, except the latter will complete the training faster, since it doesn’t have the data copying overhead. But, say, if you have 40GB cards and need to fit a 45GB model you can with 4x 40GB cards (but barely because of the gradient and optimizer states)</li>
<li>shared embeddings may need to get copied back and forth between GPUs.</li></ul>
<p>Pipeline Parallelism (PP) is almost identical to a naive MP, but it solves the GPU idling problem, by chunking the incoming batch into micro-batches and artificially creating a pipeline, which allows different GPUs to concurrently participate in the computation process.</p>
<p>The following illustration from the <a href="https://ai.googleblog.com/2019/03/introducing-gpipe-open-source-library.html" rel="nofollow">GPipe paper</a> shows the naive MP on the top, and PP on the bottom:</p>
<p><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-gpipe-bubble.png" alt="mp-pp"></p>
<p>It’s easy to see from the bottom diagram how PP has less dead zones, where GPUs are idle. The idle parts are referred to as the “bubble”.</p>
<p>Both parts of the diagram show a parallelism that is of degree 4. That is 4 GPUs are participating in the pipeline. So there is the forward path of 4 pipe stages F0, F1, F2 and F3 and then the return reverse order backward path of B3, B2, B1 and B0.</p>
<p>PP introduces a new hyper-parameter to tune and it’s <code>chunks</code> which defines how many chunks of data are sent in a sequence through the same pipe stage. For example, in the bottomw diagram you can see that <code>chunks=4</code>. GPU0 performs the same forward path on chunk 0, 1, 2 and 3 (F0,0, F0,1, F0,2, F0,3) and then it waits for other GPUs to do their work and only when their work is starting to be complete, GPU0 starts to work again doing the backward path for chunks 3, 2, 1 and 0 (B0,3, B0,2, B0,1, B0,0).</p>
<p>Note that conceptually this is the same concept as gradient accumulation steps (GAS). Pytorch uses <code>chunks</code>, whereas DeepSpeed refers to the same hyper-parameter as GAS.</p>
<p>Because of the chunks, PP introduces the concept of micro-batches (MBS). DP splits the global data batch size into mini-batches, so if you have a DP degree of 4, a global batch size of 1024 gets split up into 4 mini-batches of 256 each (1024/4). And if the number of <code>chunks</code> (or GAS) is 32 we end up with a micro-batch size of 8 (256/32). Each Pipeline stage works with a single micro-batch at a time.</p>
<p>To calculate the global batch size of the DP + PP setup we then do: <code>mbs*chunks*dp_degree</code> (<code>8*32*4=1024</code>).</p>
<p>Let’s go back to the diagram.</p>
<p>With <code>chunks=1</code> you end up with the naive MP, which is very inefficient. With a very large <code>chunks</code> value you end up with tiny micro-batch sizes which could be not every efficient either. So one has to experiment to find the value that leads to the highest efficient utilization of the gpus.</p>
<p>While the diagram shows that there is a bubble of “dead” time that can’t be parallelized because the last <code>forward</code> stage has to wait for <code>backward</code> to complete the pipeline, the purpose of finding the best value for <code>chunks</code> is to enable a high concurrent GPU utilization across all participating GPUs which translates to minimizing the size of the bubble.</p>
<p>There are 2 groups of solutions - the traditional Pipeline API and the more modern solutions that make things much easier for the end user.</p>
<p>Traditional Pipeline API solutions:</p>
<ul><li>PyTorch</li>
<li>FairScale</li>
<li>DeepSpeed</li>
<li>Megatron-LM</li></ul>
<p>Modern solutions:</p>
<ul><li>Varuna</li>
<li>Sagemaker</li></ul>
<p>Problems with traditional Pipeline API solutions:</p>
<ul><li>have to modify the model quite heavily, because Pipeline requires one to rewrite the normal flow of modules into a <code>nn.Sequential</code> sequence of the same, which may require changes to the design of the model.</li>
<li>currently the Pipeline API is very restricted. If you had a bunch of python variables being passed in the very first stage of the Pipeline, you will have to find a way around it. Currently, the pipeline interface requires either a single Tensor or a tuple of Tensors as the only input and output. These tensors must have a batch size as the very first dimension, since pipeline is going to chunk the mini batch into micro-batches. Possible improvements are being discussed here <a href="https://github.com/pytorch/pytorch/pull/50693" rel="nofollow">https://github.com/pytorch/pytorch/pull/50693</a></li>
<li>conditional control flow at the level of pipe stages is not possible - e.g., Encoder-Decoder models like T5 require special workarounds to handle a conditional encoder stage.</li>
<li>have to arrange each layer so that the output of one model becomes an input to the other model.</li></ul>
<p>We are yet to experiment with Varuna and SageMaker but their papers report that they have overcome the list of problems mentioned above and that they require much smaller changes to the user’s model.</p>
<p>Implementations:</p>
<ul><li><a href="https://pytorch.org/docs/stable/pipeline.html" rel="nofollow">Pytorch</a> (initial support in pytorch-1.8, and progressively getting improved in 1.9 and more so in 1.10). Some <a href="https://github.com/pytorch/pytorch/blob/master/benchmarks/distributed/pipeline/pipe.py" rel="nofollow">examples</a></li>
<li><a href="https://fairscale.readthedocs.io/en/latest/tutorials/pipe.html" rel="nofollow">FairScale</a></li>
<li><a href="https://www.deepspeed.ai/tutorials/pipeline/" rel="nofollow">DeepSpeed</a></li>
<li><a href="https://github.com/NVIDIA/Megatron-LM" rel="nofollow">Megatron-LM</a> has an internal implementation - no API.</li>
<li><a href="https://github.com/microsoft/varuna" rel="nofollow">Varuna</a></li>
<li><a href="https://arxiv.org/abs/2111.05972" rel="nofollow">SageMaker</a> - this is a proprietary solution that can only be used on AWS.</li>
<li><a href="https://github.com/tunib-ai/oslo" rel="nofollow">OSLO</a> - this is implemented based on the Hugging Face Transformers.</li></ul>
<p>🤗 Transformers status: as of this writing none of the models supports full-PP. GPT2 and T5 models have naive MP support. The main obstacle is being unable to convert the models to <code>nn.Sequential</code> and have all the inputs to be Tensors. This is because currently the models include many features that make the conversion very complicated, and will need to be removed to accomplish that.</p>
<p>Other approaches:</p>
<p>DeepSpeed, Varuna and SageMaker use the concept of an <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/model-parallel-core-features.html" rel="nofollow">Interleaved Pipeline</a>
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-sagemaker-interleaved-pipeline.png" alt="interleaved-pipeline-execution"></p>
<p>Here the bubble (idle time) is further minimized by prioritizing backward passes.</p>
<p>Varuna further tries to improve the schedule by using simulations to discover the most efficient scheduling.</p>
<p>OSLO has pipeline parallelism implementation based on the Transformers without <code>nn.Sequential</code> converting.</p>
<h2 class="relative group"><a id="tensor-parallelism" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#tensor-parallelism"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Tensor Parallelism
	</span></h2>

<p>In Tensor Parallelism each GPU processes only a slice of a tensor and only aggregates the full tensor for operations that require the whole thing.</p>
<p>In this section we use concepts and diagrams from the <a href="https://github.com/NVIDIA/Megatron-LM" rel="nofollow">Megatron-LM</a> paper: <a href="https://arxiv.org/abs/2104.04473" rel="nofollow">Efficient Large-Scale Language Model Training on GPU Clusters</a>.</p>
<p>The main building block of any transformer is a fully connected <code>nn.Linear</code> followed by a nonlinear activation <code>GeLU</code>.</p>
<p>Following the Megatron’s paper notation, we can write the dot-product part of it as <code>Y = GeLU(XA)</code>, where <code>X</code> and <code>Y</code> are the input and output vectors, and <code>A</code> is the weight matrix.</p>
<p>If we look at the computation in matrix form, it’s easy to see how the matrix multiplication can be split between multiple GPUs:
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-tp-parallel_gemm.png" alt="Parallel GEMM"></p>
<p>If we split the weight matrix <code>A</code> column-wise across <code>N</code> GPUs and perform matrix multiplications <code>XA_1</code> through <code>XA_n</code> in parallel, then we will end up with <code>N</code> output vectors <code>Y_1, Y_2, ..., Y_n</code> which can be fed into <code>GeLU</code> independently:
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-tp-independent-gelu.png" alt="independent GeLU"></p>
<p>Using this principle, we can update an MLP of arbitrary depth, without the need for any synchronization between GPUs until the very end, where we need to reconstruct the output vector from shards. The Megatron-LM paper authors provide a helpful illustration for that:
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-tp-parallel_shard_processing.png" alt="parallel shard processing"></p>
<p>Parallelizing the multi-headed attention layers is even simpler, since they are already inherently parallel, due to having multiple independent heads!
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-tp-parallel_self_attention.png" alt="parallel self-attention"></p>
<p>Special considerations: TP requires very fast network, and therefore it’s not advisable to do TP across more than one node. Practically, if a node has 4 GPUs, the highest TP degree is therefore 4. If you need a TP degree of 8, you need to use nodes that have at least 8 GPUs.</p>
<p>This section is based on the original much more <a href="https://github.com/huggingface/transformers/issues/10321#issuecomment-783543530" rel="nofollow">detailed TP overview</a>.
by <a href="https://github.com/anton-l" rel="nofollow">@anton-l</a>.</p>
<p>SageMaker combines TP with DP for a more efficient processing.</p>
<p>Alternative names:</p>
<ul><li>DeepSpeed calls it <a href="https://www.deepspeed.ai/features/#model-parallelism" rel="nofollow">tensor slicing</a></li></ul>
<p>Implementations:</p>
<ul><li><a href="https://github.com/NVIDIA/Megatron-LM" rel="nofollow">Megatron-LM</a> has an internal implementation, as it’s very model-specific</li>
<li><a href="https://github.com/tunib-ai/parallelformers" rel="nofollow">parallelformers</a> (only inference at the moment)</li>
<li><a href="https://arxiv.org/abs/2111.05972" rel="nofollow">SageMaker</a> - this is a proprietary solution that can only be used on AWS.</li>
<li><a href="https://github.com/tunib-ai/oslo" rel="nofollow">OSLO</a> has the tensor parallelism implementation based on the Transformers.</li></ul>
<p>🤗 Transformers status:</p>
<ul><li>core: not yet implemented in the core</li>
<li>but if you want inference <a href="https://github.com/tunib-ai/parallelformers" rel="nofollow">parallelformers</a> provides this support for most of our models. So until this is implemented in the core you can use theirs. And hopefully training mode will be supported too.</li>
<li>Deepspeed-Inference also supports our BERT, GPT-2, and GPT-Neo models in their super-fast CUDA-kernel-based inference mode, see more <a href="https://www.deepspeed.ai/tutorials/inference-tutorial/" rel="nofollow">here</a></li></ul>
<h2 class="relative group"><a id="dppp" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#dppp"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>DP+PP
	</span></h2>

<p>The following diagram from the DeepSpeed <a href="https://www.deepspeed.ai/tutorials/pipeline/" rel="nofollow">pipeline tutorial</a> demonstrates how one combines DP with PP.</p>
<p><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero-dp-pp.png" alt="dp-pp-2d"></p>
<p>Here it’s important to see how DP rank 0 doesn’t see GPU2 and DP rank 1 doesn’t see GPU3. To DP there is just GPUs 0 and 1 where it feeds data as if there were just 2 GPUs. GPU0 “secretly” offloads some of its load to GPU2 using PP. And GPU1 does the same by enlisting GPU3 to its aid.</p>
<p>Since each dimension requires at least 2 GPUs, here you’d need at least 4 GPUs.</p>
<p>Implementations:</p>
<ul><li><a href="https://github.com/microsoft/DeepSpeed" rel="nofollow">DeepSpeed</a></li>
<li><a href="https://github.com/NVIDIA/Megatron-LM" rel="nofollow">Megatron-LM</a></li>
<li><a href="https://github.com/microsoft/varuna" rel="nofollow">Varuna</a></li>
<li><a href="https://arxiv.org/abs/2111.05972" rel="nofollow">SageMaker</a></li>
<li><a href="https://github.com/tunib-ai/oslo" rel="nofollow">OSLO</a></li></ul>
<p>🤗 Transformers status: not yet implemented</p>
<h2 class="relative group"><a id="dppptp" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#dppptp"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>DP+PP+TP
	</span></h2>

<p>To get an even more efficient training a 3D parallelism is used where PP is combined with TP and DP. This can be seen in the following diagram.</p>
<p><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-deepspeed-3d.png" alt="dp-pp-tp-3d"></p>
<p>This diagram is from a blog post <a href="https://www.microsoft.com/en-us/research/blog/deepspeed-extreme-scale-model-training-for-everyone/" rel="nofollow">3D parallelism: Scaling to trillion-parameter models</a>, which is a good read as well.</p>
<p>Since each dimension requires at least 2 GPUs, here you’d need at least 8 GPUs.</p>
<p>Implementations:</p>
<ul><li><a href="https://github.com/microsoft/DeepSpeed" rel="nofollow">DeepSpeed</a> - DeepSpeed also includes an even more efficient DP, which they call ZeRO-DP.</li>
<li><a href="https://github.com/NVIDIA/Megatron-LM" rel="nofollow">Megatron-LM</a></li>
<li><a href="https://github.com/microsoft/varuna" rel="nofollow">Varuna</a></li>
<li><a href="https://arxiv.org/abs/2111.05972" rel="nofollow">SageMaker</a></li>
<li><a href="https://github.com/tunib-ai/oslo" rel="nofollow">OSLO</a></li></ul>
<p>🤗 Transformers status: not yet implemented, since we have no PP and TP.</p>
<h2 class="relative group"><a id="zero-dppptp" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#zero-dppptp"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>ZeRO DP+PP+TP
	</span></h2>

<p>One of the main features of DeepSpeed is ZeRO, which is a super-scalable extension of DP. It has already been discussed in <a href="#zero-data-parallelism">ZeRO Data Parallelism</a>. Normally it’s a standalone feature that doesn’t require PP or TP. But it can be combined with PP and TP.</p>
<p>When ZeRO-DP is combined with PP (and optionally TP) it typically enables only ZeRO stage 1 (optimizer sharding).</p>
<p>While it’s theoretically possible to use ZeRO stage 2 (gradient sharding) with Pipeline Parallelism, it will have bad performance impacts. There would need to be an additional reduce-scatter collective for every micro-batch to aggregate the gradients before sharding, which adds a potentially significant communication overhead. By nature of Pipeline Parallelism, small micro-batches are used and instead the focus is on trying to balance arithmetic intensity (micro-batch size) with minimizing the Pipeline bubble (number of micro-batches). Therefore those communication costs are going to hurt.</p>
<p>In addition, There are already fewer layers than normal due to PP and so the memory savings won’t be huge. PP already reduces gradient size by <code>1/PP</code>, and so gradient sharding savings on top of that are less significant than pure DP.</p>
<p>ZeRO stage 3 is not a good choice either for the same reason - more inter-node communications required.</p>
<p>And since we have ZeRO, the other benefit is ZeRO-Offload. Since this is stage 1 optimizer states can be offloaded to CPU.</p>
<p>Implementations:</p>
<ul><li><a href="https://github.com/microsoft/Megatron-DeepSpeed" rel="nofollow">Megatron-DeepSpeed</a> and <a href="https://github.com/bigscience-workshop/Megatron-DeepSpeed" rel="nofollow">Megatron-Deepspeed from BigScience</a>, which is the fork of the former repo.</li>
<li><a href="https://github.com/tunib-ai/oslo" rel="nofollow">OSLO</a></li></ul>
<p>Important papers:</p>
<ul><li><a href="https://arxiv.org/abs/2201.11990" rel="nofollow">Using DeepSpeed and Megatron to Train Megatron-Turing NLG 530B, A Large-Scale Generative Language Model</a></li></ul>
<p>🤗 Transformers status: not yet implemented, since we have no PP and TP.</p>
<h2 class="relative group"><a id="flexflow" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#flexflow"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>FlexFlow
	</span></h2>

<p><a href="https://github.com/flexflow/FlexFlow" rel="nofollow">FlexFlow</a> also solves the parallelization problem in a slightly different approach.</p>
<p>Paper: <a href="https://arxiv.org/abs/1807.05358" rel="nofollow">“Beyond Data and Model Parallelism for Deep Neural Networks” by Zhihao Jia, Matei Zaharia, Alex Aiken</a></p>
<p>It performs a sort of 4D Parallelism over Sample-Operator-Attribute-Parameter.</p>
<ol><li>Sample = Data Parallelism (sample-wise parallel)</li>
<li>Operator = Parallelize a single operation into several sub-operations</li>
<li>Attribute = Data Parallelism (length-wise parallel)</li>
<li>Parameter = Model Parallelism (regardless of dimension - horizontal or vertical)</li></ol>
<p>Examples:</p>
<ul><li>Sample</li></ul>
<p>Let’s take 10 batches of sequence length 512. If we parallelize them by sample dimension into 2 devices, we get 10 x 512 which becomes be 5 x 2 x 512.</p>
<ul><li>Operator</li></ul>
<p>If we perform layer normalization, we compute std first and mean second, and then we can normalize data. Operator parallelism allows computing std and mean in parallel. So if we parallelize them by operator dimension into 2 devices (cuda:0, cuda:1), first we copy input data into both devices, and cuda:0 computes std, cuda:1 computes mean at the same time.</p>
<ul><li>Attribute</li></ul>
<p>We have 10 batches of 512 length. If we parallelize them by attribute dimension into 2 devices, 10 x 512 will be 10 x 2 x 256.</p>
<ul><li>Parameter</li></ul>
<p>It is similar with tensor model parallelism or naive layer-wise model parallelism.</p>
<p><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-flexflow.jpeg" alt="flex-flow-soap"></p>
<p>The significance of this framework is that it takes resources like (1) GPU/TPU/CPU vs. (2) RAM/DRAM vs. (3) fast-intra-connect/slow-inter-connect and it automatically optimizes all these  algorithmically deciding which parallelisation to use where.</p>
<p>One very important aspect is that FlexFlow is designed for optimizing DNN parallelizations for models with static and fixed workloads, since models with dynamic behavior may prefer different parallelization strategies across iterations.</p>
<p>So the promise is very attractive - it runs a 30min simulation on the cluster of choice and it comes up with the best strategy to utilise this specific environment. If you add/remove/replace any parts it’ll run and re-optimize the plan for that. And then you can train. A different setup will have its own custom optimization.</p>
<p>🤗 Transformers status: not yet integrated. We already have our models FX-trace-able via <a href="https://github.com/huggingface/transformers/blob/master/src/transformers/utils/fx.py" rel="nofollow">transformers.utils.fx</a>, which is a prerequisite for FlexFlow, so someone needs to figure out what needs to be done to make FlexFlow work with our models.</p>
<h2 class="relative group"><a id="which-strategy-to-use-when" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#which-strategy-to-use-when"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a>
	<span>Which Strategy To Use When
	</span></h2>

<p>Here is a very rough outline at which parallelism strategy to use when. The first on each list is typically faster.</p>
<p><strong>⇨ Single GPU</strong></p>
<ul><li><p>Model fits onto a single GPU:</p>
<ol><li>Normal use</li></ol></li>
<li><p>Model doesn’t fit onto a single GPU:</p>
<ol><li>ZeRO + Offload CPU and optionally NVMe</li>
<li>as above plus Memory Centric Tiling (see below for details) if the largest layer can’t fit into a single GPU</li></ol></li>
<li><p>Largest Layer not fitting into a single GPU:</p></li></ul>
<ol><li>ZeRO - Enable <a href="https://deepspeed.readthedocs.io/en/latest/zero3.html#memory-centric-tiling" rel="nofollow">Memory Centric Tiling</a> (MCT). It allows you to run arbitrarily large layers by automatically splitting them and executing them sequentially. MCT reduces the number of parameters that are live on a GPU, but it does not affect the activation memory. As this need is very rare as of this writing a manual override of <code>torch.nn.Linear</code> needs to be done by the user.</li></ol>
<p><strong>⇨ Single Node / Multi-GPU</strong></p>
<ul><li><p>Model fits onto a single GPU:</p>
<ol><li>DDP - Distributed DP</li>
<li>ZeRO - may or may not be faster depending on the situation and configuration used</li></ol></li>
<li><p>Model doesn’t fit onto a single GPU:</p>
<ol><li><p>PP</p></li>
<li><p>ZeRO</p></li>
<li><p>TP</p>
<p>With very fast intra-node connectivity of NVLINK or NVSwitch all three should be mostly on par, without these PP will be faster than TP or ZeRO. The degree of TP may also make a difference. Best to experiment to find the winner on your particular setup.</p>
<p>TP is almost always used within a single node. That is TP size &lt;= gpus per node.</p></li></ol></li>
<li><p>Largest Layer not fitting into a single GPU:</p>
<ol><li>If not using ZeRO - must use TP, as PP alone won’t be able to fit.</li>
<li>With ZeRO see the same entry for “Single GPU” above</li></ol></li></ul>
<p><strong>⇨ Multi-Node / Multi-GPU</strong></p>
<ul><li><p>When you have fast inter-node connectivity:</p>
<ol><li>ZeRO - as it requires close to no modifications to the model</li>
<li>PP+TP+DP - less communications, but requires massive changes to the model</li></ol></li>
<li><p>when you have slow inter-node connectivity and still low on GPU memory:</p>
<ol><li>DP+PP+TP+ZeRO-1</li></ol></li></ul>


		<script type="module" data-hydrate="br644y">
		import { start } from "/docs/transformers/pr_19043/en/_app/start-hf-doc-builder.js";
		start({
			target: document.querySelector('[data-hydrate="br644y"]').parentNode,
			paths: {"base":"/docs/transformers/pr_19043/en","assets":"/docs/transformers/pr_19043/en"},
			session: {},
			route: false,
			spa: false,
			trailing_slash: "never",
			hydrate: {
				status: 200,
				error: null,
				nodes: [
					import("/docs/transformers/pr_19043/en/_app/pages/__layout.svelte-hf-doc-builder.js"),
						import("/docs/transformers/pr_19043/en/_app/pages/perf_train_gpu_many.mdx-hf-doc-builder.js")
				],
				params: {}
			}
		});
	</script>
