import{s as xs,o as Es,n as Js}from"../chunks/scheduler.b9285784.js";import{S as Hs,i as $s,e as c,s as t,c as y,h as Ks,a as p,d as a,b as n,f as Qs,g as j,j as d,k as Ss,v as Ls,l as Ds,m as e,n as o,t as w,o as r,p as J}from"../chunks/index.26bc89a1.js";import{T as rs}from"../chunks/Tip.e4eba3d6.js";import{C as qs,H as G,E as Ps}from"../chunks/MermaidChart.svelte_svelte_type_style_lang.7242ff19.js";import{C as u}from"../chunks/CodeBlock.c8ee1711.js";function Os(I){let M,h='In its current state, this code is not going to perform gradient accumulation efficiently due to a process called gradient synchronization. Read more about that in the <a href="../concept_guides/gradient_synchronization">Concepts tutorial</a>!';return{c(){M=c("p"),M.innerHTML=h},l(i){M=p(i,"P",{"data-svelte-h":!0}),d(M)!=="svelte-s0dec7"&&(M.innerHTML=h)},m(i,U){e(i,M,U)},p:Js,d(i){i&&a(M)}}}function la(I){let M,h=`Typically with gradient accumulation, you would need to adjust the number of steps to reflect the change in total batches you are
training on. Accelerate automagically does this for you by default. Behind the scenes we instantiate a <code>GradientAccumulationPlugin</code> configured to do this.`;return{c(){M=c("p"),M.innerHTML=h},l(i){M=p(i,"P",{"data-svelte-h":!0}),d(M)!=="svelte-1jsd87o"&&(M.innerHTML=h)},m(i,U){e(i,M,U)},p:Js,d(i){i&&a(M)}}}function sa(I){let M,h='The <a href="/docs/accelerate/main/en/package_reference/state#accelerate.state.GradientState">state.GradientState</a> is sync’d with the active dataloader being iterated upon. As such it assumes naively that when we have reached the end of the dataloader everything will sync and a step will be performed. To disable this, set <code>sync_with_dataloader</code> to be <code>False</code> in the <code>GradientAccumulationPlugin</code>:',i,U,b;return U=new u({props:{code:"ZnJvbSUyMGFjY2VsZXJhdGUlMjBpbXBvcnQlMjBBY2NlbGVyYXRvciUwQWZyb20lMjBhY2NlbGVyYXRlLnV0aWxzJTIwaW1wb3J0JTIwR3JhZGllbnRBY2N1bXVsYXRpb25QbHVnaW4lMEElMEFwbHVnaW4lMjAlM0QlMjBHcmFkaWVudEFjY3VtdWxhdGlvblBsdWdpbihzeW5jX3dpdGhfZGF0YWxvYWRlciUzREZhbHNlKSUwQWFjY2VsZXJhdG9yJTIwJTNEJTIwQWNjZWxlcmF0b3IoLi4uJTJDJTIwZ3JhZGllbnRfYWNjdW11bGF0aW9uX3BsdWdpbiUzRHBsdWdpbik=",highlighted:`<span class="hljs-keyword">from</span> accelerate import Accelerator
<span class="hljs-keyword">from</span> accelerate.utils import GradientAccumulationPlugin

plugin = GradientAccumulationPlugin(<span class="hljs-attribute">sync_with_dataloader</span>=<span class="hljs-literal">False</span>)
accelerator = Accelerator(<span class="hljs-built_in">..</span>., <span class="hljs-attribute">gradient_accumulation_plugin</span>=plugin)`,wrap:!1}}),{c(){M=c("p"),M.innerHTML=h,i=t(),y(U.$$.fragment)},l(m){M=p(m,"P",{"data-svelte-h":!0}),d(M)!=="svelte-lg50r9"&&(M.innerHTML=h),i=n(m),j(U.$$.fragment,m)},m(m,T){e(m,M,T),e(m,i,T),o(U,m,T),b=!0},p:Js,i(m){b||(w(U.$$.fragment,m),b=!0)},o(m){r(U.$$.fragment,m),b=!1},d(m){m&&(a(M),a(i)),J(U,m)}}}function aa(I){let M,h="It’s important that <strong>only one forward/backward</strong> should be done inside the context manager <code>with accelerator.accumulate(model)</code>.";return{c(){M=c("p"),M.innerHTML=h},l(i){M=p(i,"P",{"data-svelte-h":!0}),d(M)!=="svelte-1kw2co7"&&(M.innerHTML=h)},m(i,U){e(i,M,U)},p:Js,d(i){i&&a(M)}}}function ea(I){let M,h,i,U,b,m,T,hl,X,ds=`Gradient accumulation is a technique where you can train on bigger batch sizes than
your machine would normally be able to fit into memory. This is done by accumulating gradients over
several batches, and only stepping the optimizer after a certain number of batches have been performed.`,ul,f,ms=`While technically standard gradient accumulation code would work fine in a distributed setup, it is not the most efficient
method for doing so and you may experience considerable slowdowns!`,bl,Y,Us=`In this tutorial you will see how to quickly setup gradient accumulation and perform it with the utilities provided in Accelerate,
which can total to adding just one new line of code!`,Tl,V,hs="This example will use a very simplistic PyTorch training loop that performs gradient accumulation every two batches:",Il,R,Gl,_,Cl,g,us="First the code shown earlier will be converted to utilize Accelerate without the special gradient accumulation helper:",Wl,N,Zl,C,Bl,k,Al,v,bs=`All that is left now is to let Accelerate handle the gradient accumulation for us. To do so you should pass in a <code>gradient_accumulation_steps</code> parameter to <a href="/docs/accelerate/main/en/package_reference/accelerator#accelerate.Accelerator">Accelerator</a>, dictating the number
of steps to perform before each call to <code>step()</code> and how to automatically adjust the loss during the call to <a href="/docs/accelerate/main/en/package_reference/accelerator#accelerate.Accelerator.backward">backward()</a>:`,Xl,F,fl,z,Ts=`Alternatively, you can pass in a <code>gradient_accumulation_plugin</code> parameter to the <a href="/docs/accelerate/main/en/package_reference/accelerator#accelerate.Accelerator">Accelerator</a> object’s <code>__init__</code>, which will allow you to further customize the gradient accumulation behavior.
Read more about that in the <a href="../package_reference/accelerator#accelerate.utils.GradientAccumulationPlugin">GradientAccumulationPlugin</a> docs.`,Yl,Q,Is=`From here you can use the <a href="/docs/accelerate/main/en/package_reference/accelerator#accelerate.Accelerator.accumulate">accumulate()</a> context manager from inside your training loop to automatically perform the gradient accumulation for you!
You just wrap it around the entire training part of our code:`,Vl,S,Rl,x,Gs="You can remove all the special checks for the step number and the loss adjustment:",_l,E,gl,H,Cs='As you can see the <a href="/docs/accelerate/main/en/package_reference/accelerator#accelerate.Accelerator">Accelerator</a> is able to keep track of the batch number you are on and it will automatically know whether to step through the prepared optimizer and how to adjust the loss.',Nl,W,kl,Z,vl,$,Fl,K,Ws="Below is the finished implementation for performing gradient accumulation with Accelerate",zl,L,Ql,B,Sl,D,Zs='To learn more about what magic this wraps around, read the <a href="../concept_guides/gradient_synchronization">Gradient Synchronization concept guide</a>',xl,q,El,P,Bs="Here is a self-contained example that you can run to see gradient accumulation in action with Accelerate:",Hl,O,$l,ll,Kl,sl,Ll,al,As='As was pointed out in this <a href="https://huggingface.co/blog/gradient_accumulation" rel="nofollow">blog-post</a>, which points out a common error that occurs when performing gradient accumulation on training samples of variable size:',Dl,el,Xs="<p>[…] for gradient accumulation across token-level tasks like causal LM training, the correct loss should be computed by the <strong>total loss across all batches in a gradient accumulation step</strong> divided by the <strong>total number of all non padding tokens in those batches</strong>. This is not the same as the average of the per-batch loss values.</p>",ql,tl,fs="In other words, some adjustments must be made on losses that operate on a token-level basis.",Pl,nl,Ol,Ml,ls,cl,ss,pl,as,il,Ys="Results on a single device - gradient accumulation steps set to 1 and batch_size set to 8:",es,yl,ts,jl,Vs="Results on a two devices set-up - gradient accumulation steps set to 2 and batch_size set to 4.",ns,ol,Ms,wl,cs,rl,Rs='Please find a complete example script on a real world training run in the examples folder at the path <a href="https://github.com/huggingface/accelerate/blob/main/examples/by_feature/gradient_accumulation_for_autoregressive_models.py" rel="nofollow"><code>accelerate/examples/by_feature/gradient_accumulation_for_autoregressive_models.py</code></a>.',ps,Jl,_s="Running it on several training configurations with constant global batch size equal to 32 gives the following graph:",is,A,gs='<img src="https://huggingface.co/datasets/hf-audio/gradient_accumulation_example/resolve/main/training_losses.png"/>',ys,dl,Ns='Note that the training losses are exactly the same up to training step 20. The small deviation after this training step occurs at the very end of the first epoch, because, by <a href="https://huggingface.co/docs/accelerate/en/package_reference/torch_wrappers#accelerate.data_loader.prepare_data_loader.even_batches" rel="nofollow">default</a>, the dataloader duplicates the samples at the beginning of the dataset when the total batch size doesn’t exactly divide the dataset.',js,ml,os,Ul,ws;return b=new qs({props:{containerStyle:"float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"}}),T=new G({props:{title:"Performing gradient accumulation with Accelerate",local:"performing-gradient-accumulation-with-accelerate",headingTag:"h1"}}),R=new u({props:{code:"ZGV2aWNlJTIwJTNEJTIwJTIyY3VkYSUyMiUwQW1vZGVsLnRvKGRldmljZSklMEElMEFncmFkaWVudF9hY2N1bXVsYXRpb25fc3RlcHMlMjAlM0QlMjAyJTBBJTBBZm9yJTIwaW5kZXglMkMlMjBiYXRjaCUyMGluJTIwZW51bWVyYXRlKHRyYWluaW5nX2RhdGFsb2FkZXIpJTNBJTBBJTIwJTIwJTIwJTIwaW5wdXRzJTJDJTIwdGFyZ2V0cyUyMCUzRCUyMGJhdGNoJTBBJTIwJTIwJTIwJTIwaW5wdXRzJTIwJTNEJTIwaW5wdXRzLnRvKGRldmljZSklMEElMjAlMjAlMjAlMjB0YXJnZXRzJTIwJTNEJTIwdGFyZ2V0cy50byhkZXZpY2UpJTBBJTIwJTIwJTIwJTIwb3V0cHV0cyUyMCUzRCUyMG1vZGVsKGlucHV0cyklMEElMjAlMjAlMjAlMjBsb3NzJTIwJTNEJTIwbG9zc19mdW5jdGlvbihvdXRwdXRzJTJDJTIwdGFyZ2V0cyklMEElMjAlMjAlMjAlMjBsb3NzJTIwJTNEJTIwbG9zcyUyMCUyRiUyMGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUwQSUyMCUyMCUyMCUyMGxvc3MuYmFja3dhcmQoKSUwQSUyMCUyMCUyMCUyMGlmJTIwKGluZGV4JTIwJTJCJTIwMSklMjAlMjUlMjBncmFkaWVudF9hY2N1bXVsYXRpb25fc3RlcHMlMjAlM0QlM0QlMjAwJTNBJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwb3B0aW1pemVyLnN0ZXAoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMHNjaGVkdWxlci5zdGVwKCklMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBvcHRpbWl6ZXIuemVyb19ncmFkKCk=",highlighted:`device = <span class="hljs-string">&quot;cuda&quot;</span>
model.to(device)

gradient_accumulation_steps = <span class="hljs-number">2</span>

<span class="hljs-keyword">for</span> index, batch <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(training_dataloader):
    inputs, targets = batch
    inputs = inputs.to(device)
    targets = targets.to(device)
    outputs = model(inputs)
    loss = loss_function(outputs, targets)
    loss = loss / gradient_accumulation_steps
    loss.backward()
    <span class="hljs-keyword">if</span> (index + <span class="hljs-number">1</span>) % gradient_accumulation_steps == <span class="hljs-number">0</span>:
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()`,wrap:!1}}),_=new G({props:{title:"Converting it to Accelerate",local:"converting-it-to-accelerate",headingTag:"h2"}}),N=new u({props:{code:"JTJCJTIwZnJvbSUyMGFjY2VsZXJhdGUlMjBpbXBvcnQlMjBBY2NlbGVyYXRvciUwQSUyQiUyMGFjY2VsZXJhdG9yJTIwJTNEJTIwQWNjZWxlcmF0b3IoKSUwQSUwQSUyQiUyMG1vZGVsJTJDJTIwb3B0aW1pemVyJTJDJTIwdHJhaW5pbmdfZGF0YWxvYWRlciUyQyUyMHNjaGVkdWxlciUyMCUzRCUyMGFjY2VsZXJhdG9yLnByZXBhcmUoJTBBJTJCJTIwJTIwJTIwJTIwJTIwbW9kZWwlMkMlMjBvcHRpbWl6ZXIlMkMlMjB0cmFpbmluZ19kYXRhbG9hZGVyJTJDJTIwc2NoZWR1bGVyJTBBJTJCJTIwKSUwQSUwQSUyMCUyMGZvciUyMGluZGV4JTJDJTIwYmF0Y2glMjBpbiUyMGVudW1lcmF0ZSh0cmFpbmluZ19kYXRhbG9hZGVyKSUzQSUwQSUyMCUyMCUyMCUyMCUyMCUyMGlucHV0cyUyQyUyMHRhcmdldHMlMjAlM0QlMjBiYXRjaCUwQS0lMjAlMjAlMjAlMjAlMjBpbnB1dHMlMjAlM0QlMjBpbnB1dHMudG8oZGV2aWNlKSUwQS0lMjAlMjAlMjAlMjAlMjB0YXJnZXRzJTIwJTNEJTIwdGFyZ2V0cy50byhkZXZpY2UpJTBBJTIwJTIwJTIwJTIwJTIwJTIwb3V0cHV0cyUyMCUzRCUyMG1vZGVsKGlucHV0cyklMEElMjAlMjAlMjAlMjAlMjAlMjBsb3NzJTIwJTNEJTIwbG9zc19mdW5jdGlvbihvdXRwdXRzJTJDJTIwdGFyZ2V0cyklMEElMjAlMjAlMjAlMjAlMjAlMjBsb3NzJTIwJTNEJTIwbG9zcyUyMCUyRiUyMGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUwQSUyQiUyMCUyMCUyMCUyMCUyMGFjY2VsZXJhdG9yLmJhY2t3YXJkKGxvc3MpJTBBJTIwJTIwJTIwJTIwJTIwJTIwaWYlMjAoaW5kZXglMkIxKSUyMCUyNSUyMGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUyMCUzRCUzRCUyMDAlM0ElMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBvcHRpbWl6ZXIuc3RlcCgpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwc2NoZWR1bGVyLnN0ZXAoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMG9wdGltaXplci56ZXJvX2dyYWQoKQ==",highlighted:`<span class="hljs-addition">+ from accelerate import Accelerator</span>
<span class="hljs-addition">+ accelerator = Accelerator()</span>

<span class="hljs-addition">+ model, optimizer, training_dataloader, scheduler = accelerator.prepare(</span>
<span class="hljs-addition">+     model, optimizer, training_dataloader, scheduler</span>
<span class="hljs-addition">+ )</span>

  for index, batch in enumerate(training_dataloader):
      inputs, targets = batch
<span class="hljs-deletion">-     inputs = inputs.to(device)</span>
<span class="hljs-deletion">-     targets = targets.to(device)</span>
      outputs = model(inputs)
      loss = loss_function(outputs, targets)
      loss = loss / gradient_accumulation_steps
<span class="hljs-addition">+     accelerator.backward(loss)</span>
      if (index+1) % gradient_accumulation_steps == 0:
          optimizer.step()
          scheduler.step()
          optimizer.zero_grad()`,wrap:!1}}),C=new rs({props:{warning:!0,$$slots:{default:[Os]},$$scope:{ctx:I}}}),k=new G({props:{title:"Letting Accelerate handle gradient accumulation",local:"letting-accelerate-handle-gradient-accumulation",headingTag:"h2"}}),F=new u({props:{code:"JTIwJTIwZnJvbSUyMGFjY2VsZXJhdGUlMjBpbXBvcnQlMjBBY2NlbGVyYXRvciUwQS0lMjBhY2NlbGVyYXRvciUyMCUzRCUyMEFjY2VsZXJhdG9yKCklMEElMkIlMjBhY2NlbGVyYXRvciUyMCUzRCUyMEFjY2VsZXJhdG9yKGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUzRDIp",highlighted:`  from accelerate import Accelerator
<span class="hljs-deletion">- accelerator = Accelerator()</span>
<span class="hljs-addition">+ accelerator = Accelerator(gradient_accumulation_steps=2)</span>`,wrap:!1}}),S=new u({props:{code:"LSUyMGZvciUyMGluZGV4JTJDJTIwYmF0Y2glMjBpbiUyMGVudW1lcmF0ZSh0cmFpbmluZ19kYXRhbG9hZGVyKSUzQSUwQSUyQiUyMGZvciUyMGJhdGNoJTIwaW4lMjB0cmFpbmluZ19kYXRhbG9hZGVyJTNBJTBBJTJCJTIwJTIwJTIwJTIwJTIwd2l0aCUyMGFjY2VsZXJhdG9yLmFjY3VtdWxhdGUobW9kZWwpJTNBJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwaW5wdXRzJTJDJTIwdGFyZ2V0cyUyMCUzRCUyMGJhdGNoJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwb3V0cHV0cyUyMCUzRCUyMG1vZGVsKGlucHV0cyk=",highlighted:`<span class="hljs-deletion">- for index, batch in enumerate(training_dataloader):</span>
<span class="hljs-addition">+ for batch in training_dataloader:</span>
<span class="hljs-addition">+     with accelerator.accumulate(model):</span>
          inputs, targets = batch
          outputs = model(inputs)`,wrap:!1}}),E=new u({props:{code:"LSUyMGxvc3MlMjAlM0QlMjBsb3NzJTIwJTJGJTIwZ3JhZGllbnRfYWNjdW11bGF0aW9uX3N0ZXBzJTBBJTIwJTIwYWNjZWxlcmF0b3IuYmFja3dhcmQobG9zcyklMEEtJTIwaWYlMjAoaW5kZXglMkIxKSUyMCUyNSUyMGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUyMCUzRCUzRCUyMDAlM0ElMEElMjAlMjBvcHRpbWl6ZXIuc3RlcCgpJTBBJTIwJTIwc2NoZWR1bGVyLnN0ZXAoKSUwQSUyMCUyMG9wdGltaXplci56ZXJvX2dyYWQoKQ==",highlighted:`<span class="hljs-deletion">- loss = loss / gradient_accumulation_steps</span>
  accelerator.backward(loss)
<span class="hljs-deletion">- if (index+1) % gradient_accumulation_steps == 0:</span>
  optimizer.step()
  scheduler.step()
  optimizer.zero_grad()`,wrap:!1}}),W=new rs({props:{$$slots:{default:[la]},$$scope:{ctx:I}}}),Z=new rs({props:{warning:!0,$$slots:{default:[sa]},$$scope:{ctx:I}}}),$=new G({props:{title:"The finished code",local:"the-finished-code",headingTag:"h2"}}),L=new u({props:{code:"ZnJvbSUyMGFjY2VsZXJhdGUlMjBpbXBvcnQlMjBBY2NlbGVyYXRvciUwQWFjY2VsZXJhdG9yJTIwJTNEJTIwQWNjZWxlcmF0b3IoZ3JhZGllbnRfYWNjdW11bGF0aW9uX3N0ZXBzJTNEMiklMEFtb2RlbCUyQyUyMG9wdGltaXplciUyQyUyMHRyYWluaW5nX2RhdGFsb2FkZXIlMkMlMjBzY2hlZHVsZXIlMjAlM0QlMjBhY2NlbGVyYXRvci5wcmVwYXJlKCUwQSUyMCUyMCUyMCUyMG1vZGVsJTJDJTIwb3B0aW1pemVyJTJDJTIwdHJhaW5pbmdfZGF0YWxvYWRlciUyQyUyMHNjaGVkdWxlciUwQSklMEFmb3IlMjBiYXRjaCUyMGluJTIwdHJhaW5pbmdfZGF0YWxvYWRlciUzQSUwQSUyMCUyMCUyMCUyMHdpdGglMjBhY2NlbGVyYXRvci5hY2N1bXVsYXRlKG1vZGVsKSUzQSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMGlucHV0cyUyQyUyMHRhcmdldHMlMjAlM0QlMjBiYXRjaCUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMG91dHB1dHMlMjAlM0QlMjBtb2RlbChpbnB1dHMpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwbG9zcyUyMCUzRCUyMGxvc3NfZnVuY3Rpb24ob3V0cHV0cyUyQyUyMHRhcmdldHMpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwYWNjZWxlcmF0b3IuYmFja3dhcmQobG9zcyklMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBvcHRpbWl6ZXIuc3RlcCgpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwc2NoZWR1bGVyLnN0ZXAoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMG9wdGltaXplci56ZXJvX2dyYWQoKQ==",highlighted:`<span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator
accelerator = Accelerator(gradient_accumulation_steps=<span class="hljs-number">2</span>)
model, optimizer, training_dataloader, scheduler = accelerator.prepare(
    model, optimizer, training_dataloader, scheduler
)
<span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> training_dataloader:
    <span class="hljs-keyword">with</span> accelerator.accumulate(model):
        inputs, targets = batch
        outputs = model(inputs)
        loss = loss_function(outputs, targets)
        accelerator.backward(loss)
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()`,wrap:!1}}),B=new rs({props:{warning:!0,$$slots:{default:[aa]},$$scope:{ctx:I}}}),q=new G({props:{title:"Self-contained example",local:"self-contained-example",headingTag:"h2"}}),O=new u({props:{code:"aW1wb3J0JTIwdG9yY2glMEFpbXBvcnQlMjBjb3B5JTBBZnJvbSUyMGFjY2VsZXJhdGUlMjBpbXBvcnQlMjBBY2NlbGVyYXRvciUwQWZyb20lMjBhY2NlbGVyYXRlLnV0aWxzJTIwaW1wb3J0JTIwc2V0X3NlZWQlMEFmcm9tJTIwdG9yY2gudXRpbHMuZGF0YSUyMGltcG9ydCUyMFRlbnNvckRhdGFzZXQlMkMlMjBEYXRhTG9hZGVyJTBBJTBBJTIzJTIwc2VlZCUwQXNldF9zZWVkKDApJTBBJTBBJTIzJTIwZGVmaW5lJTIwdG95JTIwaW5wdXRzJTIwYW5kJTIwbGFiZWxzJTBBeCUyMCUzRCUyMHRvcmNoLnRlbnNvciglNUIxLiUyQyUyMDIuJTJDJTIwMy4lMkMlMjA0LiUyQyUyMDUuJTJDJTIwNi4lMkMlMjA3LiUyQyUyMDguJTVEKSUwQXklMjAlM0QlMjB0b3JjaC50ZW5zb3IoJTVCMi4lMkMlMjA0LiUyQyUyMDYuJTJDJTIwOC4lMkMlMjAxMC4lMkMlMjAxMi4lMkMlMjAxNC4lMkMlMjAxNi4lNUQpJTBBZ3JhZGllbnRfYWNjdW11bGF0aW9uX3N0ZXBzJTIwJTNEJTIwNCUwQXBlcl9kZXZpY2VfYmF0Y2hfc2l6ZSUyMCUzRCUyMGxlbih4KSUyMCUyRiUyRiUyMGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUwQSUwQSUyMyUyMGRlZmluZSUyMGRhdGFzZXQlMjBhbmQlMjBkYXRhbG9hZGVyJTBBZGF0YXNldCUyMCUzRCUyMFRlbnNvckRhdGFzZXQoeCUyQyUyMHkpJTBBZGF0YWxvYWRlciUyMCUzRCUyMERhdGFMb2FkZXIoZGF0YXNldCUyQyUyMGJhdGNoX3NpemUlM0RwZXJfZGV2aWNlX2JhdGNoX3NpemUpJTBBJTBBJTIzJTIwZGVmaW5lJTIwbW9kZWwlMkMlMjBvcHRpbWl6ZXIlMjBhbmQlMjBsb3NzJTIwZnVuY3Rpb24lMEFjbGFzcyUyMFNpbXBsZUxpbmVhck1vZGVsKHRvcmNoLm5uLk1vZHVsZSklM0ElMEElMjAlMjAlMjAlMjBkZWYlMjBfX2luaXRfXyhzZWxmKSUzQSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMHN1cGVyKFNpbXBsZUxpbmVhck1vZGVsJTJDJTIwc2VsZikuX19pbml0X18oKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMHNlbGYud2VpZ2h0JTIwJTNEJTIwdG9yY2gubm4uUGFyYW1ldGVyKHRvcmNoLnplcm9zKCgxJTJDJTIwMSkpKSUwQSUwQSUyMCUyMCUyMCUyMGRlZiUyMGZvcndhcmQoc2VsZiUyQyUyMGlucHV0cyklM0ElMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjByZXR1cm4lMjBpbnB1dHMlMjAlNDAlMjBzZWxmLndlaWdodCUwQSUwQW1vZGVsJTIwJTNEJTIwU2ltcGxlTGluZWFyTW9kZWwoKSUwQW1vZGVsX2Nsb25lJTIwJTNEJTIwY29weS5kZWVwY29weShtb2RlbCklMEFjcml0ZXJpb24lMjAlM0QlMjB0b3JjaC5ubi5NU0VMb3NzKCklMEFtb2RlbF9vcHRpbWl6ZXIlMjAlM0QlMjB0b3JjaC5vcHRpbS5TR0QobW9kZWwucGFyYW1ldGVycygpJTJDJTIwbHIlM0QwLjAyKSUwQWFjY2VsZXJhdG9yJTIwJTNEJTIwQWNjZWxlcmF0b3IoZ3JhZGllbnRfYWNjdW11bGF0aW9uX3N0ZXBzJTNEZ3JhZGllbnRfYWNjdW11bGF0aW9uX3N0ZXBzKSUwQW1vZGVsJTJDJTIwbW9kZWxfb3B0aW1pemVyJTJDJTIwZGF0YWxvYWRlciUyMCUzRCUyMGFjY2VsZXJhdG9yLnByZXBhcmUobW9kZWwlMkMlMjBtb2RlbF9vcHRpbWl6ZXIlMkMlMjBkYXRhbG9hZGVyKSUwQW1vZGVsX2Nsb25lX29wdGltaXplciUyMCUzRCUyMHRvcmNoLm9wdGltLlNHRChtb2RlbF9jbG9uZS5wYXJhbWV0ZXJzKCklMkMlMjBsciUzRDAuMDIpJTBBcHJpbnQoZiUyMmluaXRpYWwlMjBtb2RlbCUyMHdlaWdodCUyMGlzJTIwJTdCbW9kZWwud2VpZ2h0Lm1lYW4oKS5pdGVtKCklM0EuNWYlN0QlMjIpJTBBcHJpbnQoZiUyMmluaXRpYWwlMjBtb2RlbCUyMHdlaWdodCUyMGlzJTIwJTdCbW9kZWxfY2xvbmUud2VpZ2h0Lm1lYW4oKS5pdGVtKCklM0EuNWYlN0QlMjIpJTBBZm9yJTIwaSUyQyUyMChpbnB1dHMlMkMlMjBsYWJlbHMpJTIwaW4lMjBlbnVtZXJhdGUoZGF0YWxvYWRlciklM0ElMEElMjAlMjAlMjAlMjB3aXRoJTIwYWNjZWxlcmF0b3IuYWNjdW11bGF0ZShtb2RlbCklM0ElMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBpbnB1dHMlMjAlM0QlMjBpbnB1dHMudmlldygtMSUyQyUyMDEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwcHJpbnQoaSUyQyUyMGlucHV0cy5mbGF0dGVuKCkpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwbGFiZWxzJTIwJTNEJTIwbGFiZWxzLnZpZXcoLTElMkMlMjAxKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMG91dHB1dHMlMjAlM0QlMjBtb2RlbChpbnB1dHMpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwbG9zcyUyMCUzRCUyMGNyaXRlcmlvbihvdXRwdXRzJTJDJTIwbGFiZWxzKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMGFjY2VsZXJhdG9yLmJhY2t3YXJkKGxvc3MpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwbW9kZWxfb3B0aW1pemVyLnN0ZXAoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMG1vZGVsX29wdGltaXplci56ZXJvX2dyYWQoKSUwQWxvc3MlMjAlM0QlMjBjcml0ZXJpb24oeC52aWV3KC0xJTJDJTIwMSklMjAlNDAlMjBtb2RlbF9jbG9uZS53ZWlnaHQlMkMlMjB5LnZpZXcoLTElMkMlMjAxKSklMEFtb2RlbF9jbG9uZV9vcHRpbWl6ZXIuemVyb19ncmFkKCklMEFsb3NzLmJhY2t3YXJkKCklMEFtb2RlbF9jbG9uZV9vcHRpbWl6ZXIuc3RlcCgpJTBBcHJpbnQoZiUyMnclMkYlMjBhY2N1bXVsYXRpb24lMkMlMjB0aGUlMjBmaW5hbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAlN0Jtb2RlbC53ZWlnaHQubWVhbigpLml0ZW0oKSUzQS41ZiU3RCUyMiklMEFwcmludChmJTIydyUyRm8lMjBhY2N1bXVsYXRpb24lMkMlMjB0aGUlMjBmaW5hbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAlN0Jtb2RlbF9jbG9uZS53ZWlnaHQubWVhbigpLml0ZW0oKSUzQS41ZiU3RCUyMik=",highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> copy
<span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator
<span class="hljs-keyword">from</span> accelerate.utils <span class="hljs-keyword">import</span> set_seed
<span class="hljs-keyword">from</span> torch.utils.data <span class="hljs-keyword">import</span> TensorDataset, DataLoader

<span class="hljs-comment"># seed</span>
set_seed(<span class="hljs-number">0</span>)

<span class="hljs-comment"># define toy inputs and labels</span>
x = torch.tensor([<span class="hljs-number">1.</span>, <span class="hljs-number">2.</span>, <span class="hljs-number">3.</span>, <span class="hljs-number">4.</span>, <span class="hljs-number">5.</span>, <span class="hljs-number">6.</span>, <span class="hljs-number">7.</span>, <span class="hljs-number">8.</span>])
y = torch.tensor([<span class="hljs-number">2.</span>, <span class="hljs-number">4.</span>, <span class="hljs-number">6.</span>, <span class="hljs-number">8.</span>, <span class="hljs-number">10.</span>, <span class="hljs-number">12.</span>, <span class="hljs-number">14.</span>, <span class="hljs-number">16.</span>])
gradient_accumulation_steps = <span class="hljs-number">4</span>
per_device_batch_size = <span class="hljs-built_in">len</span>(x) // gradient_accumulation_steps

<span class="hljs-comment"># define dataset and dataloader</span>
dataset = TensorDataset(x, y)
dataloader = DataLoader(dataset, batch_size=per_device_batch_size)

<span class="hljs-comment"># define model, optimizer and loss function</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">SimpleLinearModel</span>(torch.nn.Module):
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):
        <span class="hljs-built_in">super</span>(SimpleLinearModel, self).__init__()
        self.weight = torch.nn.Parameter(torch.zeros((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)))

    <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">self, inputs</span>):
        <span class="hljs-keyword">return</span> inputs @ self.weight

model = SimpleLinearModel()
model_clone = copy.deepcopy(model)
criterion = torch.nn.MSELoss()
model_optimizer = torch.optim.SGD(model.parameters(), lr=<span class="hljs-number">0.02</span>)
accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
model, model_optimizer, dataloader = accelerator.prepare(model, model_optimizer, dataloader)
model_clone_optimizer = torch.optim.SGD(model_clone.parameters(), lr=<span class="hljs-number">0.02</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;initial model weight is <span class="hljs-subst">{model.weight.mean().item():<span class="hljs-number">.5</span>f}</span>&quot;</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;initial model weight is <span class="hljs-subst">{model_clone.weight.mean().item():<span class="hljs-number">.5</span>f}</span>&quot;</span>)
<span class="hljs-keyword">for</span> i, (inputs, labels) <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(dataloader):
    <span class="hljs-keyword">with</span> accelerator.accumulate(model):
        inputs = inputs.view(-<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)
        <span class="hljs-built_in">print</span>(i, inputs.flatten())
        labels = labels.view(-<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        accelerator.backward(loss)
        model_optimizer.step()
        model_optimizer.zero_grad()
loss = criterion(x.view(-<span class="hljs-number">1</span>, <span class="hljs-number">1</span>) @ model_clone.weight, y.view(-<span class="hljs-number">1</span>, <span class="hljs-number">1</span>))
model_clone_optimizer.zero_grad()
loss.backward()
model_clone_optimizer.step()
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;w/ accumulation, the final model weight is <span class="hljs-subst">{model.weight.mean().item():<span class="hljs-number">.5</span>f}</span>&quot;</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;w/o accumulation, the final model weight is <span class="hljs-subst">{model_clone.weight.mean().item():<span class="hljs-number">.5</span>f}</span>&quot;</span>)`,wrap:!1}}),ll=new u({props:{code:"aW5pdGlhbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAwLjAwMDAwJTBBaW5pdGlhbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAwLjAwMDAwJTBBMCUyMHRlbnNvciglNUIxLiUyQyUyMDIuJTVEKSUwQTElMjB0ZW5zb3IoJTVCMy4lMkMlMjA0LiU1RCklMEEyJTIwdGVuc29yKCU1QjUuJTJDJTIwNi4lNUQpJTBBMyUyMHRlbnNvciglNUI3LiUyQyUyMDguJTVEKSUwQXclMkYlMjBhY2N1bXVsYXRpb24lMkMlMjB0aGUlMjBmaW5hbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAyLjA0MDAwJTBBdyUyRm8lMjBhY2N1bXVsYXRpb24lMkMlMjB0aGUlMjBmaW5hbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAyLjA0MDAw",highlighted:`<span class="hljs-attribute">initial</span> model weight is <span class="hljs-number">0</span>.<span class="hljs-number">00000</span>
<span class="hljs-attribute">initial</span> model weight is <span class="hljs-number">0</span>.<span class="hljs-number">00000</span>
<span class="hljs-attribute">0</span> tensor([<span class="hljs-number">1</span>., <span class="hljs-number">2</span>.])
<span class="hljs-attribute">1</span> tensor([<span class="hljs-number">3</span>., <span class="hljs-number">4</span>.])
<span class="hljs-attribute">2</span> tensor([<span class="hljs-number">5</span>., <span class="hljs-number">6</span>.])
<span class="hljs-attribute">3</span> tensor([<span class="hljs-number">7</span>., <span class="hljs-number">8</span>.])
<span class="hljs-attribute">w</span>/ accumulation, the final model weight is <span class="hljs-number">2</span>.<span class="hljs-number">04000</span>
<span class="hljs-attribute">w</span>/o accumulation, the final model weight is <span class="hljs-number">2</span>.<span class="hljs-number">04000</span>`,wrap:!1}}),sl=new G({props:{title:"Gradient accumulation on training samples of variable size",local:"gradient-accumulation-on-training-samples-of-variable-size",headingTag:"h2"}}),nl=new G({props:{title:"Skeleton code",local:"skeleton-code",headingTag:"h3"}}),Ml=new u({props:{code:" ",highlighted:`<span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator
<span class="hljs-keyword">import</span> math
<span class="hljs-keyword">import</span> contextlib

gradient_accumulation_steps = <span class="hljs-number">2</span>
accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)
model, optimizer, training_dataloader, scheduler = accelerator.prepare(
    model, optimizer, training_dataloader, scheduler
)

training_iterator = <span class="hljs-built_in">iter</span>(training_dataloader)
num_samples_in_epoch = <span class="hljs-built_in">len</span>(training_dataloader)
remainder = num_samples_in_epoch % gradient_accumulation_steps
remainder = remainder <span class="hljs-keyword">if</span> remainder != <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> gradient_accumulation_steps
total_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)
        

total_batched_samples = <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> update_step <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(total_updates):
        <span class="hljs-comment"># In order to correctly the total number of non-padded tokens on which we&#x27;ll compute the cross-entropy loss</span>
        <span class="hljs-comment"># we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples</span>
        batch_samples = []
        num_batches_in_step = gradient_accumulation_steps <span class="hljs-keyword">if</span> update_step != (total_updates - <span class="hljs-number">1</span>) <span class="hljs-keyword">else</span> remainder
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(num_batches_in_step):
            batch_samples += [<span class="hljs-built_in">next</span>(training_iterator)]
            
        <span class="hljs-comment"># get local num items in batch </span>
        num_items_in_batch = <span class="hljs-built_in">sum</span>([(batch[<span class="hljs-string">&quot;labels&quot;</span>].ne(-<span class="hljs-number">100</span>)).<span class="hljs-built_in">sum</span>() <span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> batch_samples])
        <span class="hljs-comment"># to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.</span>
        num_items_in_batch = accelerator.gather(num_items_in_batch).<span class="hljs-built_in">sum</span>().item()
            
        <span class="hljs-keyword">for</span> i, batch <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(batch_samples):
            <span class="hljs-comment"># if we perform gradient accumulation in a multi-devices set-up, we want to avoid unnecessary communications when accumulating</span>
            <span class="hljs-comment"># cf: https://muellerzr.github.io/blog/gradient_accumulation.html</span>
            <span class="hljs-keyword">if</span> (i &lt; <span class="hljs-built_in">len</span>(batch_samples) - <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> accelerator.num_processes &gt; <span class="hljs-number">1</span>):
                ctx = model.no_sync
            <span class="hljs-keyword">else</span>:
                ctx = contextlib.nullcontext
            
            total_batched_samples += <span class="hljs-number">1</span>

            <span class="hljs-keyword">with</span> ctx():
                inputs, targets = batch
                outputs = model(inputs)
                loss = loss_function(outputs, targets) <span class="hljs-comment"># the loss function should sum over samples rather than averaging</span>
                
                <span class="hljs-comment"># We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices</span>
                <span class="hljs-comment"># Same reason for gradient_accumulation_steps, but this times it&#x27;s Accelerate that calculate the average gradient across the accumulated steps</span>
                loss = (loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
                
                accelerator.backward(loss)

        <span class="hljs-comment"># Sync gradients and perform optimization steps once every gradient_accumulation_steps</span>
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()`,wrap:!1}}),cl=new G({props:{title:"Self-contained causal LM example",local:"self-contained-causal-lm-example",headingTag:"h3"}}),pl=new u({props:{code:" ",highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> copy
<span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator
<span class="hljs-keyword">from</span> accelerate.utils <span class="hljs-keyword">import</span> set_seed
<span class="hljs-keyword">from</span> accelerate.logging <span class="hljs-keyword">import</span>  get_logger
<span class="hljs-keyword">from</span> torch.utils.data <span class="hljs-keyword">import</span> Dataset, DataLoader
<span class="hljs-keyword">import</span> math
<span class="hljs-keyword">import</span> contexlib

<span class="hljs-comment"># seed</span>
set_seed(<span class="hljs-number">0</span>)
logger = get_logger(__name__)

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDataset</span>(<span class="hljs-title class_ inherited__">Dataset</span>):
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, num_samples</span>):
        <span class="hljs-built_in">super</span>().__init__()
        self.<span class="hljs-built_in">len</span> = num_samples

    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__getitem__</span>(<span class="hljs-params">self, index</span>):
        input_ids = torch.arange(<span class="hljs-number">1</span>, index+<span class="hljs-number">2</span>, dtype=torch.float32)
        labels = torch.remainder(input_ids, <span class="hljs-number">2</span>)
        <span class="hljs-keyword">return</span> {<span class="hljs-string">&quot;input_ids&quot;</span>: input_ids, <span class="hljs-string">&quot;labels&quot;</span>: labels}

    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__len__</span>(<span class="hljs-params">self</span>):
        <span class="hljs-keyword">return</span> self.<span class="hljs-built_in">len</span>
    
<span class="hljs-keyword">def</span> <span class="hljs-title function_">collate_fn</span>(<span class="hljs-params">features</span>):
    input_ids = torch.nn.utils.rnn.pad_sequence([f[<span class="hljs-string">&quot;input_ids&quot;</span>] <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> features], batch_first=<span class="hljs-literal">True</span>, padding_value=-<span class="hljs-number">100</span>)
    labels = torch.nn.utils.rnn.pad_sequence([f[<span class="hljs-string">&quot;labels&quot;</span>] <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> features], batch_first=<span class="hljs-literal">True</span>, padding_value=-<span class="hljs-number">100</span>)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">&quot;input_ids&quot;</span>: input_ids[..., <span class="hljs-literal">None</span>], <span class="hljs-string">&quot;labels&quot;</span>: labels[..., <span class="hljs-literal">None</span>]}

<span class="hljs-comment"># define toy inputs and labels</span>
gradient_accumulation_steps = <span class="hljs-number">2</span>
per_device_batch_size = <span class="hljs-number">4</span>

<span class="hljs-comment"># define accelerator</span>
accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps)

<span class="hljs-comment"># define dataset and dataloader</span>
<span class="hljs-comment"># for this toy example, we&#x27;ll compute gradient descent over one single global batch</span>
dataset = MyDataset(per_device_batch_size*gradient_accumulation_steps*accelerator.num_processes)
dataloader = DataLoader(dataset, batch_size=per_device_batch_size, collate_fn=collate_fn)

<span class="hljs-comment"># define model, model_optimizer and loss function</span>
model = torch.nn.Linear(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, bias=<span class="hljs-literal">False</span>)
model_clone = copy.deepcopy(model)
criterion = torch.nn.CrossEntropyLoss(reduction=<span class="hljs-string">&quot;sum&quot;</span>) <span class="hljs-comment"># must sum over samples rather than averaging</span>
model_optimizer = torch.optim.SGD(model.parameters(), lr=<span class="hljs-number">0.08</span>)


logger.warning(<span class="hljs-string">f&quot;initial model weight is <span class="hljs-subst">{model.weight.detach().cpu().squeeze()}</span>&quot;</span>)
logger.warning(<span class="hljs-string">f&quot;initial model clone weight is <span class="hljs-subst">{model_clone.weight.detach().cpu().squeeze()}</span>&quot;</span>)

<span class="hljs-comment"># prepare artifacts - accelerator handles device placement and dataloader splitting</span>
model, model_optimizer = accelerator.prepare(model, model_optimizer)
dataloader = accelerator.prepare_data_loader(dataloader, device_placement=<span class="hljs-literal">True</span>)
training_iterator = <span class="hljs-built_in">iter</span>(dataloader)

num_samples_in_epoch = <span class="hljs-built_in">len</span>(dataloader)
remainder = num_samples_in_epoch % gradient_accumulation_steps
remainder = remainder <span class="hljs-keyword">if</span> remainder != <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> gradient_accumulation_steps
total_gradient_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)

total_batched_samples = <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> update_step <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(total_gradient_updates):
        <span class="hljs-comment"># In order to correctly the total number of non-padded tokens on which we&#x27;ll compute the cross-entropy loss</span>
        <span class="hljs-comment"># we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples</span>
        batch_samples = []
        num_batches_in_step = gradient_accumulation_steps <span class="hljs-keyword">if</span> update_step != (total_gradient_updates - <span class="hljs-number">1</span>) <span class="hljs-keyword">else</span> remainder
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(num_batches_in_step):
            batch_samples += [<span class="hljs-built_in">next</span>(training_iterator)]
            
        <span class="hljs-comment"># get local num items in batch </span>
        local_num_items_in_batch = <span class="hljs-built_in">sum</span>([(batch[<span class="hljs-string">&quot;labels&quot;</span>].ne(-<span class="hljs-number">100</span>)).<span class="hljs-built_in">sum</span>() <span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> batch_samples])
        logger.warning(<span class="hljs-string">f&quot;Step <span class="hljs-subst">{update_step}</span> - Device <span class="hljs-subst">{accelerator.process_index}</span> - num items in the local batch <span class="hljs-subst">{local_num_items_in_batch}</span>&quot;</span>, main_process_only=<span class="hljs-literal">False</span>)

        <span class="hljs-comment"># to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.</span>
        num_items_in_batch = accelerator.gather(local_num_items_in_batch).<span class="hljs-built_in">sum</span>().item()
        logger.warning(<span class="hljs-string">f&quot;Total num items <span class="hljs-subst">{num_items_in_batch}</span>&quot;</span>)

        <span class="hljs-keyword">for</span> i, batch <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(batch_samples):
            inputs, labels = batch[<span class="hljs-string">&quot;input_ids&quot;</span>], batch[<span class="hljs-string">&quot;labels&quot;</span>]
            total_batched_samples += <span class="hljs-number">1</span>
            <span class="hljs-comment"># if we perform gradient accumulation in a multi-devices set-up, we want to avoid unnecessary communications when accumulating</span>
            <span class="hljs-comment"># cf: https://muellerzr.github.io/blog/gradient_accumulation.html</span>
            <span class="hljs-keyword">if</span> (i &lt; <span class="hljs-built_in">len</span>(batch_samples) - <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> accelerator.num_processes &gt; <span class="hljs-number">1</span>):
                ctx = model.no_sync
            <span class="hljs-keyword">else</span>:
                ctx = contextlib.nullcontext
            <span class="hljs-keyword">with</span> ctx():

                outputs = model(inputs)
                loss = criterion(outputs.view(-<span class="hljs-number">1</span>, <span class="hljs-number">2</span>), labels.view(-<span class="hljs-number">1</span>).to(torch.int64))
                
                <span class="hljs-comment"># We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices</span>
                <span class="hljs-comment"># Same reason for gradient_accumulation_steps, but this times it&#x27;s Accelerate that calculate the average gradient across the accumulated steps </span>
                loss = (loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
                accelerator.backward(loss)
        model_optimizer.step()
        model_optimizer.zero_grad()
                

logger.warning(<span class="hljs-string">f&quot;Device <span class="hljs-subst">{accelerator.process_index}</span> - w/ accumulation, the final model weight is <span class="hljs-subst">{accelerator.unwrap_model(model).weight.detach().cpu().squeeze()}</span>&quot;</span>, main_process_only=<span class="hljs-literal">False</span>)

<span class="hljs-comment"># We know do the same operation but on a single device and without gradient accumulation</span>

<span class="hljs-keyword">if</span> accelerator.is_main_process:
    <span class="hljs-comment"># prepare one single entire batch</span>
    dataloader = DataLoader(dataset, batch_size=<span class="hljs-built_in">len</span>(dataset), collate_fn=collate_fn)
    full_batch_without_accum = <span class="hljs-built_in">next</span>(<span class="hljs-built_in">iter</span>(dataloader))
    total_inputs, total_labels = full_batch_without_accum[<span class="hljs-string">&quot;input_ids&quot;</span>], full_batch_without_accum[<span class="hljs-string">&quot;labels&quot;</span>]
    model_clone_optimizer = torch.optim.SGD(model_clone.parameters(), lr=<span class="hljs-number">0.08</span>)
    
    <span class="hljs-comment"># train the cloned model</span>
    loss = torch.nn.CrossEntropyLoss(reduction=<span class="hljs-string">&quot;mean&quot;</span>)(model_clone(total_inputs).view(-<span class="hljs-number">1</span>, <span class="hljs-number">2</span>), total_labels.view(-<span class="hljs-number">1</span>).to(torch.int64))
    model_clone_optimizer.zero_grad()
    loss.backward()
    model_clone_optimizer.step()
    
    <span class="hljs-comment"># We should have the same final weights.</span>
    logger.warning(<span class="hljs-string">f&quot;w/o accumulation, the final model weight is <span class="hljs-subst">{model_clone.weight.detach().cpu().squeeze()}</span>&quot;</span>)
`,wrap:!1}}),yl=new u({props:{code:"aW5pdGlhbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjB0ZW5zb3IoJTVCLTAuMDA3NSUyQyUyMCUyMDAuNTM2NCU1RCklMEFpbml0aWFsJTIwbW9kZWwlMjBjbG9uZSUyMHdlaWdodCUyMGlzJTIwdGVuc29yKCU1Qi0wLjAwNzUlMkMlMjAlMjAwLjUzNjQlNUQpJTBBU3RlcCUyMDAlMjAtJTIwRGV2aWNlJTIwMCUyMC0lMjBudW0lMjBpdGVtcyUyMGluJTIwdGhlJTIwbG9jYWwlMjBiYXRjaCUyMDM2JTBBVG90YWwlMjBudW0lMjBpdGVtcyUyMDM2JTBBRGV2aWNlJTIwMCUyMC0lMjB3JTJGJTIwYWNjdW11bGF0aW9uJTJDJTIwdGhlJTIwZmluYWwlMjBtb2RlbCUyMHdlaWdodCUyMGlzJTIwdGVuc29yKCU1QjAuMDk1MyUyQyUyMDAuNDMzNyU1RCklMEF3JTJGbyUyMGFjY3VtdWxhdGlvbiUyQyUyMHRoZSUyMGZpbmFsJTIwbW9kZWwlMjB3ZWlnaHQlMjBpcyUyMHRlbnNvciglNUIwLjA5NTMlMkMlMjAwLjQzMzclNUQp",highlighted:`<span class="hljs-attribute">initial</span> model weight is tensor([-<span class="hljs-number">0</span>.<span class="hljs-number">0075</span>,  <span class="hljs-number">0</span>.<span class="hljs-number">5364</span>])
<span class="hljs-attribute">initial</span> model clone weight is tensor([-<span class="hljs-number">0</span>.<span class="hljs-number">0075</span>,  <span class="hljs-number">0</span>.<span class="hljs-number">5364</span>])
<span class="hljs-attribute">Step</span> <span class="hljs-number">0</span> - Device <span class="hljs-number">0</span> - num items in the local batch <span class="hljs-number">36</span>
<span class="hljs-attribute">Total</span> num items <span class="hljs-number">36</span>
<span class="hljs-attribute">Device</span> <span class="hljs-number">0</span> - w/ accumulation, the final model weight is tensor([<span class="hljs-number">0</span>.<span class="hljs-number">0953</span>, <span class="hljs-number">0</span>.<span class="hljs-number">4337</span>])
<span class="hljs-attribute">w</span>/o accumulation, the final model weight is tensor([<span class="hljs-number">0</span>.<span class="hljs-number">0953</span>, <span class="hljs-number">0</span>.<span class="hljs-number">4337</span>])`,wrap:!1}}),ol=new u({props:{code:"aW5pdGlhbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjB0ZW5zb3IoJTVCLTAuMDA3NSUyQyUyMCUyMDAuNTM2NCU1RCklMEFpbml0aWFsJTIwbW9kZWwlMjBjbG9uZSUyMHdlaWdodCUyMGlzJTIwdGVuc29yKCU1Qi0wLjAwNzUlMkMlMjAlMjAwLjUzNjQlNUQpJTBBU3RlcCUyMDAlMjAtJTIwRGV2aWNlJTIwMCUyMC0lMjBudW0lMjBpdGVtcyUyMGluJTIwdGhlJTIwbG9jYWwlMjBiYXRjaCUyMDUyJTBBU3RlcCUyMDAlMjAtJTIwRGV2aWNlJTIwMSUyMC0lMjBudW0lMjBpdGVtcyUyMGluJTIwdGhlJTIwbG9jYWwlMjBiYXRjaCUyMDg0JTBBVG90YWwlMjBudW0lMjBpdGVtcyUyMDEzNiUwQURldmljZSUyMDElMjAtJTIwdyUyRiUyMGFjY3VtdWxhdGlvbiUyQyUyMHRoZSUyMGZpbmFsJTIwbW9kZWwlMjB3ZWlnaHQlMjBpcyUyMHRlbnNvciglNUIwLjIxMTclMkMlMjAwLjMxNzIlNUQpJTBBRGV2aWNlJTIwMCUyMC0lMjB3JTJGJTIwYWNjdW11bGF0aW9uJTJDJTIwdGhlJTIwZmluYWwlMjBtb2RlbCUyMHdlaWdodCUyMGlzJTIwdGVuc29yKCU1QjAuMjExNyUyQyUyMDAuMzE3MiU1RCklMEF3JTJGbyUyMGFjY3VtdWxhdGlvbiUyQyUyMHRoZSUyMGZpbmFsJTIwbW9kZWwlMjB3ZWlnaHQlMjBpcyUyMHRlbnNvciglNUIwLjIxMTclMkMlMjAwLjMxNzIlNUQp",highlighted:`<span class="hljs-attribute">initial</span> model weight is tensor([-<span class="hljs-number">0</span>.<span class="hljs-number">0075</span>,  <span class="hljs-number">0</span>.<span class="hljs-number">5364</span>])
<span class="hljs-attribute">initial</span> model clone weight is tensor([-<span class="hljs-number">0</span>.<span class="hljs-number">0075</span>,  <span class="hljs-number">0</span>.<span class="hljs-number">5364</span>])
<span class="hljs-attribute">Step</span> <span class="hljs-number">0</span> - Device <span class="hljs-number">0</span> - num items in the local batch <span class="hljs-number">52</span>
<span class="hljs-attribute">Step</span> <span class="hljs-number">0</span> - Device <span class="hljs-number">1</span> - num items in the local batch <span class="hljs-number">84</span>
<span class="hljs-attribute">Total</span> num items <span class="hljs-number">136</span>
<span class="hljs-attribute">Device</span> <span class="hljs-number">1</span> - w/ accumulation, the final model weight is tensor([<span class="hljs-number">0</span>.<span class="hljs-number">2117</span>, <span class="hljs-number">0</span>.<span class="hljs-number">3172</span>])
<span class="hljs-attribute">Device</span> <span class="hljs-number">0</span> - w/ accumulation, the final model weight is tensor([<span class="hljs-number">0</span>.<span class="hljs-number">2117</span>, <span class="hljs-number">0</span>.<span class="hljs-number">3172</span>])
<span class="hljs-attribute">w</span>/o accumulation, the final model weight is tensor([<span class="hljs-number">0</span>.<span class="hljs-number">2117</span>, <span class="hljs-number">0</span>.<span class="hljs-number">3172</span>])`,wrap:!1}}),wl=new G({props:{title:"To go further:",local:"to-go-further",headingTag:"h3"}}),ml=new Ps({props:{source:"https://github.com/huggingface/accelerate/blob/main/docs/source/usage_guides/gradient_accumulation.md"}}),{c(){M=c("meta"),h=t(),i=c("p"),U=t(),y(b.$$.fragment),m=t(),y(T.$$.fragment),hl=t(),X=c("p"),X.textContent=ds,ul=t(),f=c("p"),f.textContent=ms,bl=t(),Y=c("p"),Y.textContent=Us,Tl=t(),V=c("p"),V.textContent=hs,Il=t(),y(R.$$.fragment),Gl=t(),y(_.$$.fragment),Cl=t(),g=c("p"),g.textContent=us,Wl=t(),y(N.$$.fragment),Zl=t(),y(C.$$.fragment),Bl=t(),y(k.$$.fragment),Al=t(),v=c("p"),v.innerHTML=bs,Xl=t(),y(F.$$.fragment),fl=t(),z=c("p"),z.innerHTML=Ts,Yl=t(),Q=c("p"),Q.innerHTML=Is,Vl=t(),y(S.$$.fragment),Rl=t(),x=c("p"),x.textContent=Gs,_l=t(),y(E.$$.fragment),gl=t(),H=c("p"),H.innerHTML=Cs,Nl=t(),y(W.$$.fragment),kl=t(),y(Z.$$.fragment),vl=t(),y($.$$.fragment),Fl=t(),K=c("p"),K.textContent=Ws,zl=t(),y(L.$$.fragment),Ql=t(),y(B.$$.fragment),Sl=t(),D=c("p"),D.innerHTML=Zs,xl=t(),y(q.$$.fragment),El=t(),P=c("p"),P.textContent=Bs,Hl=t(),y(O.$$.fragment),$l=t(),y(ll.$$.fragment),Kl=t(),y(sl.$$.fragment),Ll=t(),al=c("p"),al.innerHTML=As,Dl=t(),el=c("blockquote"),el.innerHTML=Xs,ql=t(),tl=c("p"),tl.textContent=fs,Pl=t(),y(nl.$$.fragment),Ol=t(),y(Ml.$$.fragment),ls=t(),y(cl.$$.fragment),ss=t(),y(pl.$$.fragment),as=t(),il=c("p"),il.textContent=Ys,es=t(),y(yl.$$.fragment),ts=t(),jl=c("p"),jl.textContent=Vs,ns=t(),y(ol.$$.fragment),Ms=t(),y(wl.$$.fragment),cs=t(),rl=c("p"),rl.innerHTML=Rs,ps=t(),Jl=c("p"),Jl.textContent=_s,is=t(),A=c("div"),A.innerHTML=gs,ys=t(),dl=c("p"),dl.innerHTML=Ns,js=t(),y(ml.$$.fragment),os=t(),Ul=c("p"),this.h()},l(l){const s=Ks("svelte-u9bgzb",document.head);M=p(s,"META",{name:!0,content:!0}),s.forEach(a),h=n(l),i=p(l,"P",{}),Qs(i).forEach(a),U=n(l),j(b.$$.fragment,l),m=n(l),j(T.$$.fragment,l),hl=n(l),X=p(l,"P",{"data-svelte-h":!0}),d(X)!=="svelte-1762c2w"&&(X.textContent=ds),ul=n(l),f=p(l,"P",{"data-svelte-h":!0}),d(f)!=="svelte-1u2vc4p"&&(f.textContent=ms),bl=n(l),Y=p(l,"P",{"data-svelte-h":!0}),d(Y)!=="svelte-dgpyx1"&&(Y.textContent=Us),Tl=n(l),V=p(l,"P",{"data-svelte-h":!0}),d(V)!=="svelte-n9bxrd"&&(V.textContent=hs),Il=n(l),j(R.$$.fragment,l),Gl=n(l),j(_.$$.fragment,l),Cl=n(l),g=p(l,"P",{"data-svelte-h":!0}),d(g)!=="svelte-1cm6g3v"&&(g.textContent=us),Wl=n(l),j(N.$$.fragment,l),Zl=n(l),j(C.$$.fragment,l),Bl=n(l),j(k.$$.fragment,l),Al=n(l),v=p(l,"P",{"data-svelte-h":!0}),d(v)!=="svelte-129aclo"&&(v.innerHTML=bs),Xl=n(l),j(F.$$.fragment,l),fl=n(l),z=p(l,"P",{"data-svelte-h":!0}),d(z)!=="svelte-j5vx6o"&&(z.innerHTML=Ts),Yl=n(l),Q=p(l,"P",{"data-svelte-h":!0}),d(Q)!=="svelte-1yxrf5e"&&(Q.innerHTML=Is),Vl=n(l),j(S.$$.fragment,l),Rl=n(l),x=p(l,"P",{"data-svelte-h":!0}),d(x)!=="svelte-1mcvl9w"&&(x.textContent=Gs),_l=n(l),j(E.$$.fragment,l),gl=n(l),H=p(l,"P",{"data-svelte-h":!0}),d(H)!=="svelte-1g13ex2"&&(H.innerHTML=Cs),Nl=n(l),j(W.$$.fragment,l),kl=n(l),j(Z.$$.fragment,l),vl=n(l),j($.$$.fragment,l),Fl=n(l),K=p(l,"P",{"data-svelte-h":!0}),d(K)!=="svelte-1ynctgg"&&(K.textContent=Ws),zl=n(l),j(L.$$.fragment,l),Ql=n(l),j(B.$$.fragment,l),Sl=n(l),D=p(l,"P",{"data-svelte-h":!0}),d(D)!=="svelte-aw0h59"&&(D.innerHTML=Zs),xl=n(l),j(q.$$.fragment,l),El=n(l),P=p(l,"P",{"data-svelte-h":!0}),d(P)!=="svelte-1e26tlz"&&(P.textContent=Bs),Hl=n(l),j(O.$$.fragment,l),$l=n(l),j(ll.$$.fragment,l),Kl=n(l),j(sl.$$.fragment,l),Ll=n(l),al=p(l,"P",{"data-svelte-h":!0}),d(al)!=="svelte-yaf5ek"&&(al.innerHTML=As),Dl=n(l),el=p(l,"BLOCKQUOTE",{"data-svelte-h":!0}),d(el)!=="svelte-1dpvjrf"&&(el.innerHTML=Xs),ql=n(l),tl=p(l,"P",{"data-svelte-h":!0}),d(tl)!=="svelte-ffthww"&&(tl.textContent=fs),Pl=n(l),j(nl.$$.fragment,l),Ol=n(l),j(Ml.$$.fragment,l),ls=n(l),j(cl.$$.fragment,l),ss=n(l),j(pl.$$.fragment,l),as=n(l),il=p(l,"P",{"data-svelte-h":!0}),d(il)!=="svelte-1oywi83"&&(il.textContent=Ys),es=n(l),j(yl.$$.fragment,l),ts=n(l),jl=p(l,"P",{"data-svelte-h":!0}),d(jl)!=="svelte-1519q1p"&&(jl.textContent=Vs),ns=n(l),j(ol.$$.fragment,l),Ms=n(l),j(wl.$$.fragment,l),cs=n(l),rl=p(l,"P",{"data-svelte-h":!0}),d(rl)!=="svelte-14ssh20"&&(rl.innerHTML=Rs),ps=n(l),Jl=p(l,"P",{"data-svelte-h":!0}),d(Jl)!=="svelte-1mi0t6"&&(Jl.textContent=_s),is=n(l),A=p(l,"DIV",{style:!0,"data-svelte-h":!0}),d(A)!=="svelte-11tj8ly"&&(A.innerHTML=gs),ys=n(l),dl=p(l,"P",{"data-svelte-h":!0}),d(dl)!=="svelte-vzj4yr"&&(dl.innerHTML=Ns),js=n(l),j(ml.$$.fragment,l),os=n(l),Ul=p(l,"P",{}),Qs(Ul).forEach(a),this.h()},h(){Ss(M,"name","hf:doc:metadata"),Ss(M,"content",ta),Ls(A,"text-align","center")},m(l,s){Ds(document.head,M),e(l,h,s),e(l,i,s),e(l,U,s),o(b,l,s),e(l,m,s),o(T,l,s),e(l,hl,s),e(l,X,s),e(l,ul,s),e(l,f,s),e(l,bl,s),e(l,Y,s),e(l,Tl,s),e(l,V,s),e(l,Il,s),o(R,l,s),e(l,Gl,s),o(_,l,s),e(l,Cl,s),e(l,g,s),e(l,Wl,s),o(N,l,s),e(l,Zl,s),o(C,l,s),e(l,Bl,s),o(k,l,s),e(l,Al,s),e(l,v,s),e(l,Xl,s),o(F,l,s),e(l,fl,s),e(l,z,s),e(l,Yl,s),e(l,Q,s),e(l,Vl,s),o(S,l,s),e(l,Rl,s),e(l,x,s),e(l,_l,s),o(E,l,s),e(l,gl,s),e(l,H,s),e(l,Nl,s),o(W,l,s),e(l,kl,s),o(Z,l,s),e(l,vl,s),o($,l,s),e(l,Fl,s),e(l,K,s),e(l,zl,s),o(L,l,s),e(l,Ql,s),o(B,l,s),e(l,Sl,s),e(l,D,s),e(l,xl,s),o(q,l,s),e(l,El,s),e(l,P,s),e(l,Hl,s),o(O,l,s),e(l,$l,s),o(ll,l,s),e(l,Kl,s),o(sl,l,s),e(l,Ll,s),e(l,al,s),e(l,Dl,s),e(l,el,s),e(l,ql,s),e(l,tl,s),e(l,Pl,s),o(nl,l,s),e(l,Ol,s),o(Ml,l,s),e(l,ls,s),o(cl,l,s),e(l,ss,s),o(pl,l,s),e(l,as,s),e(l,il,s),e(l,es,s),o(yl,l,s),e(l,ts,s),e(l,jl,s),e(l,ns,s),o(ol,l,s),e(l,Ms,s),o(wl,l,s),e(l,cs,s),e(l,rl,s),e(l,ps,s),e(l,Jl,s),e(l,is,s),e(l,A,s),e(l,ys,s),e(l,dl,s),e(l,js,s),o(ml,l,s),e(l,os,s),e(l,Ul,s),ws=!0},p(l,[s]){const ks={};s&2&&(ks.$$scope={dirty:s,ctx:l}),C.$set(ks);const vs={};s&2&&(vs.$$scope={dirty:s,ctx:l}),W.$set(vs);const Fs={};s&2&&(Fs.$$scope={dirty:s,ctx:l}),Z.$set(Fs);const zs={};s&2&&(zs.$$scope={dirty:s,ctx:l}),B.$set(zs)},i(l){ws||(w(b.$$.fragment,l),w(T.$$.fragment,l),w(R.$$.fragment,l),w(_.$$.fragment,l),w(N.$$.fragment,l),w(C.$$.fragment,l),w(k.$$.fragment,l),w(F.$$.fragment,l),w(S.$$.fragment,l),w(E.$$.fragment,l),w(W.$$.fragment,l),w(Z.$$.fragment,l),w($.$$.fragment,l),w(L.$$.fragment,l),w(B.$$.fragment,l),w(q.$$.fragment,l),w(O.$$.fragment,l),w(ll.$$.fragment,l),w(sl.$$.fragment,l),w(nl.$$.fragment,l),w(Ml.$$.fragment,l),w(cl.$$.fragment,l),w(pl.$$.fragment,l),w(yl.$$.fragment,l),w(ol.$$.fragment,l),w(wl.$$.fragment,l),w(ml.$$.fragment,l),ws=!0)},o(l){r(b.$$.fragment,l),r(T.$$.fragment,l),r(R.$$.fragment,l),r(_.$$.fragment,l),r(N.$$.fragment,l),r(C.$$.fragment,l),r(k.$$.fragment,l),r(F.$$.fragment,l),r(S.$$.fragment,l),r(E.$$.fragment,l),r(W.$$.fragment,l),r(Z.$$.fragment,l),r($.$$.fragment,l),r(L.$$.fragment,l),r(B.$$.fragment,l),r(q.$$.fragment,l),r(O.$$.fragment,l),r(ll.$$.fragment,l),r(sl.$$.fragment,l),r(nl.$$.fragment,l),r(Ml.$$.fragment,l),r(cl.$$.fragment,l),r(pl.$$.fragment,l),r(yl.$$.fragment,l),r(ol.$$.fragment,l),r(wl.$$.fragment,l),r(ml.$$.fragment,l),ws=!1},d(l){l&&(a(h),a(i),a(U),a(m),a(hl),a(X),a(ul),a(f),a(bl),a(Y),a(Tl),a(V),a(Il),a(Gl),a(Cl),a(g),a(Wl),a(Zl),a(Bl),a(Al),a(v),a(Xl),a(fl),a(z),a(Yl),a(Q),a(Vl),a(Rl),a(x),a(_l),a(gl),a(H),a(Nl),a(kl),a(vl),a(Fl),a(K),a(zl),a(Ql),a(Sl),a(D),a(xl),a(El),a(P),a(Hl),a($l),a(Kl),a(Ll),a(al),a(Dl),a(el),a(ql),a(tl),a(Pl),a(Ol),a(ls),a(ss),a(as),a(il),a(es),a(ts),a(jl),a(ns),a(Ms),a(cs),a(rl),a(ps),a(Jl),a(is),a(A),a(ys),a(dl),a(js),a(os),a(Ul)),a(M),J(b,l),J(T,l),J(R,l),J(_,l),J(N,l),J(C,l),J(k,l),J(F,l),J(S,l),J(E,l),J(W,l),J(Z,l),J($,l),J(L,l),J(B,l),J(q,l),J(O,l),J(ll,l),J(sl,l),J(nl,l),J(Ml,l),J(cl,l),J(pl,l),J(yl,l),J(ol,l),J(wl,l),J(ml,l)}}}const ta='{"title":"Performing gradient accumulation with Accelerate","local":"performing-gradient-accumulation-with-accelerate","sections":[{"title":"Converting it to Accelerate","local":"converting-it-to-accelerate","sections":[],"depth":2},{"title":"Letting Accelerate handle gradient accumulation","local":"letting-accelerate-handle-gradient-accumulation","sections":[],"depth":2},{"title":"The finished code","local":"the-finished-code","sections":[],"depth":2},{"title":"Self-contained example","local":"self-contained-example","sections":[],"depth":2},{"title":"Gradient accumulation on training samples of variable size","local":"gradient-accumulation-on-training-samples-of-variable-size","sections":[{"title":"Skeleton code","local":"skeleton-code","sections":[],"depth":3},{"title":"Self-contained causal LM example","local":"self-contained-causal-lm-example","sections":[],"depth":3},{"title":"To go further:","local":"to-go-further","sections":[],"depth":3}],"depth":2}],"depth":1}';function na(I){return Es(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class ja extends Hs{constructor(M){super(),$s(this,M,na,ea,xs,{})}}export{ja as component};
