import{s as Qs,o as Ss,n as ws}from"../chunks/scheduler.defa9a21.js";import{S as xs,i as Es,g as c,s as t,r as y,A as Hs,h as p,f as a,c as n,j as Fs,u as j,x as d,k as zs,l as $s,y as Ks,a as e,v as o,d as w,t as r,w as J}from"../chunks/index.fe795e71.js";import{T as os}from"../chunks/Tip.179eb360.js";import{C as u}from"../chunks/CodeBlock.204b6c34.js";import{H as G,E as Ls}from"../chunks/getInferenceSnippets.2234a8dd.js";function Ds(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:ws,d(i){i&&a(M)}}}function qs(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:ws,d(i){i&&a(M)}}}function Ps(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:ws,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 Os(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:ws,d(i){i&&a(M)}}}function la(I){let M,h,i,U,b,m,T,rs=`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,X,Js=`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!`,hl,f,ds=`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!`,ul,Y,ms="This example will use a very simplistic PyTorch training loop that performs gradient accumulation every two batches:",bl,V,Tl,R,Il,_,Us="First the code shown earlier will be converted to utilize Accelerate without the special gradient accumulation helper:",Gl,g,Cl,C,Wl,N,Zl,k,hs=`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>:`,Bl,v,Al,F,us=`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.`,Xl,z,bs=`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:`,fl,Q,Yl,S,Ts="You can remove all the special checks for the step number and the loss adjustment:",Vl,x,Rl,E,Is='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.',_l,W,gl,Z,Nl,H,kl,$,Gs="Below is the finished implementation for performing gradient accumulation with Accelerate",vl,K,Fl,B,zl,L,Cs='To learn more about what magic this wraps around, read the <a href="../concept_guides/gradient_synchronization">Gradient Synchronization concept guide</a>',Ql,D,Sl,q,Ws="Here is a self-contained example that you can run to see gradient accumulation in action with Accelerate:",xl,P,El,O,Hl,ll,$l,sl,Zs='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:',Kl,al,Bs="<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>",Ll,el,As="In other words, some adjustments must be made on losses that operate on a token-level basis.",Dl,tl,ql,nl,Pl,Ml,Ol,cl,ls,pl,Xs="Results on a single device - gradient accumulation steps set to 1 and batch_size set to 8:",ss,il,as,yl,fs="Results on a two devices set-up - gradient accumulation steps set to 2 and batch_size set to 4.",es,jl,ts,ol,ns,wl,Ys='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>.',Ms,rl,Vs="Running it on several training configurations with constant global batch size equal to 32 gives the following graph:",cs,A,Rs='<img src="https://huggingface.co/datasets/hf-audio/gradient_accumulation_example/resolve/main/training_losses.png"/>',ps,Jl,_s='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.',is,dl,ys,ml,js;return b=new G({props:{title:"Performing gradient accumulation with Accelerate",local:"performing-gradient-accumulation-with-accelerate",headingTag:"h1"}}),V=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()
        optimiz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MCUyMGFjY2VsZXJhdG9yLmJhY2t3YXJkKGxvc3MpJTBBJTIwJTIwJTIwJTIwJTIwJTIwaWYlMjAoaW5kZXglMkIxKSUyMCUyNSUyMGdyYWRpZW50X2FjY3VtdWxhdGlvbl9zdGVwcyUyMCUzRCUzRCUyMDAlM0ElMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBvcHRpbWl6ZXIuc3RlcCgpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwc2NoZWR1bGVyLnN0ZXAoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMG9wdGltaXplci56ZXJvX2dyYWQoKQ==",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 os({props:{warning:!0,$$slots:{default:[Ds]},$$scope:{ctx:I}}}),N=new G({props:{title:"Letting Accelerate handle gradient accumulation",local:"letting-accelerate-handle-gradient-accumulation",headingTag:"h2"}}),v=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}}),Q=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}}),x=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 os({props:{$$slots:{default:[qs]},$$scope:{ctx:I}}}),Z=new os({props:{warning:!0,$$slots:{default:[Ps]},$$scope:{ctx:I}}}),H=new G({props:{title:"The finished code",local:"the-finished-code",headingTag:"h2"}}),K=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 os({props:{warning:!0,$$slots:{default:[Os]},$$scope:{ctx:I}}}),D=new G({props:{title:"Self-contained example",local:"self-contained-example",headingTag:"h2"}}),P=new u({props:{code:"aW1wb3J0JTIwdG9yY2glMEFpbXBvcnQlMjBjb3B5JTBBZnJvbSUyMGFjY2VsZXJhdGUlMjBpbXBvcnQlMjBBY2NlbGVyYXRvciUwQWZyb20lMjBhY2NlbGVyYXRlLnV0aWxzJTIwaW1wb3J0JTIwc2V0X3NlZWQlMEFmcm9tJTIwdG9yY2gudXRpbHMuZGF0YSUyMGltcG9ydCUyMFRlbnNvckRhdGFzZXQlMkMlMjBEYXRhTG9hZGVyJTBBJTBBJTIzJTIwc2VlZCUwQXNldF9zZWVkKDApJTBBJTBBJTIzJTIwZGVmaW5lJTIwdG95JTIwaW5wdXRzJTIwYW5kJTIwbGFiZWxzJTBBeCUyMCUzRCUyMHRvcmNoLnRlbnNvciglNUIxLiUyQyUyMDIu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TIwd2VpZ2h0JTIwaXMlMjAlN0Jtb2RlbC53ZWlnaHQubWVhbigpLml0ZW0oKSUzQS41ZiU3RCUyMiklMEFwcmludChmJTIydyUyRm8lMjBhY2N1bXVsYXRpb24lMkMlMjB0aGUlMjBmaW5hbCUyMG1vZGVsJTIwd2VpZ2h0JTIwaXMlMjAlN0Jtb2RlbF9jbG9uZS53ZWlnaHQubWVhbigpLml0ZW0oKSUzQS41ZiU3RCUyMik=",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}}),O=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}}),ll=new G({props:{title:"Gradient accumulation on training samples of variable size",local:"gradient-accumulation-on-training-samples-of-variable-size",headingTag:"h2"}}),tl=new G({props:{title:"Skeleton code",local:"skeleton-code",headingTag:"h3"}}),nl=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}}),Ml=new G({props:{title:"Self-contained causal LM example",local:"self-contained-causal-lm-example",headingTag:"h3"}}),cl=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}}),il=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}}),jl=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}}),ol=new G({props:{title:"To go further:",local:"to-go-further",headingTag:"h3"}}),dl=new Ls({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(),T=c("p"),T.textContent=rs,Ul=t(),X=c("p"),X.textContent=Js,hl=t(),f=c("p"),f.textContent=ds,ul=t(),Y=c("p"),Y.textContent=ms,bl=t(),y(V.$$.fragment),Tl=t(),y(R.$$.fragment),Il=t(),_=c("p"),_.textContent=Us,Gl=t(),y(g.$$.fragment),Cl=t(),y(C.$$.fragment),Wl=t(),y(N.$$.fragment),Zl=t(),k=c("p"),k.innerHTML=hs,Bl=t(),y(v.$$.fragment),Al=t(),F=c("p"),F.innerHTML=us,Xl=t(),z=c("p"),z.innerHTML=bs,fl=t(),y(Q.$$.fragment),Yl=t(),S=c("p"),S.textContent=Ts,Vl=t(),y(x.$$.fragment),Rl=t(),E=c("p"),E.innerHTML=Is,_l=t(),y(W.$$.fragment),gl=t(),y(Z.$$.fragment),Nl=t(),y(H.$$.fragment),kl=t(),$=c("p"),$.textContent=Gs,vl=t(),y(K.$$.fragment),Fl=t(),y(B.$$.fragment),zl=t(),L=c("p"),L.innerHTML=Cs,Ql=t(),y(D.$$.fragment),Sl=t(),q=c("p"),q.textContent=Ws,xl=t(),y(P.$$.fragment),El=t(),y(O.$$.fragment),Hl=t(),y(ll.$$.fragment),$l=t(),sl=c("p"),sl.innerHTML=Zs,Kl=t(),al=c("blockquote"),al.innerHTML=Bs,Ll=t(),el=c("p"),el.textContent=As,Dl=t(),y(tl.$$.fragment),ql=t(),y(nl.$$.fragment),Pl=t(),y(Ml.$$.fragment),Ol=t(),y(cl.$$.fragment),ls=t(),pl=c("p"),pl.textContent=Xs,ss=t(),y(il.$$.fragment),as=t(),yl=c("p"),yl.textContent=fs,es=t(),y(jl.$$.fragment),ts=t(),y(ol.$$.fragment),ns=t(),wl=c("p"),wl.innerHTML=Ys,Ms=t(),rl=c("p"),rl.textContent=Vs,cs=t(),A=c("div"),A.innerHTML=Rs,ps=t(),Jl=c("p"),Jl.innerHTML=_s,is=t(),y(dl.$$.fragment),ys=t(),ml=c("p"),this.h()},l(l){const s=Hs("svelte-u9bgzb",document.head);M=p(s,"META",{name:!0,content:!0}),s.forEach(a),h=n(l),i=p(l,"P",{}),Fs(i).forEach(a),U=n(l),j(b.$$.fragment,l),m=n(l),T=p(l,"P",{"data-svelte-h":!0}),d(T)!=="svelte-1762c2w"&&(T.textContent=rs),Ul=n(l),X=p(l,"P",{"data-svelte-h":!0}),d(X)!=="svelte-1u2vc4p"&&(X.textContent=Js),hl=n(l),f=p(l,"P",{"data-svelte-h":!0}),d(f)!=="svelte-dgpyx1"&&(f.textContent=ds),ul=n(l),Y=p(l,"P",{"data-svelte-h":!0}),d(Y)!=="svelte-n9bxrd"&&(Y.textContent=ms),bl=n(l),j(V.$$.fragment,l),Tl=n(l),j(R.$$.fragment,l),Il=n(l),_=p(l,"P",{"data-svelte-h":!0}),d(_)!=="svelte-1cm6g3v"&&(_.textContent=Us),Gl=n(l),j(g.$$.fragment,l),Cl=n(l),j(C.$$.fragment,l),Wl=n(l),j(N.$$.fragment,l),Zl=n(l),k=p(l,"P",{"data-svelte-h":!0}),d(k)!=="svelte-129aclo"&&(k.innerHTML=hs),Bl=n(l),j(v.$$.fragment,l),Al=n(l),F=p(l,"P",{"data-svelte-h":!0}),d(F)!=="svelte-j5vx6o"&&(F.innerHTML=us),Xl=n(l),z=p(l,"P",{"data-svelte-h":!0}),d(z)!=="svelte-1yxrf5e"&&(z.innerHTML=bs),fl=n(l),j(Q.$$.fragment,l),Yl=n(l),S=p(l,"P",{"data-svelte-h":!0}),d(S)!=="svelte-1mcvl9w"&&(S.textContent=Ts),Vl=n(l),j(x.$$.fragment,l),Rl=n(l),E=p(l,"P",{"data-svelte-h":!0}),d(E)!=="svelte-1g13ex2"&&(E.innerHTML=Is),_l=n(l),j(W.$$.fragment,l),gl=n(l),j(Z.$$.fragment,l),Nl=n(l),j(H.$$.fragment,l),kl=n(l),$=p(l,"P",{"data-svelte-h":!0}),d($)!=="svelte-1ynctgg"&&($.textContent=Gs),vl=n(l),j(K.$$.fragment,l),Fl=n(l),j(B.$$.fragment,l),zl=n(l),L=p(l,"P",{"data-svelte-h":!0}),d(L)!=="svelte-aw0h59"&&(L.innerHTML=Cs),Ql=n(l),j(D.$$.fragment,l),Sl=n(l),q=p(l,"P",{"data-svelte-h":!0}),d(q)!=="svelte-1e26tlz"&&(q.textContent=Ws),xl=n(l),j(P.$$.fragment,l),El=n(l),j(O.$$.fragment,l),Hl=n(l),j(ll.$$.fragment,l),$l=n(l),sl=p(l,"P",{"data-svelte-h":!0}),d(sl)!=="svelte-yaf5ek"&&(sl.innerHTML=Zs),Kl=n(l),al=p(l,"BLOCKQUOTE",{"data-svelte-h":!0}),d(al)!=="svelte-1dpvjrf"&&(al.innerHTML=Bs),Ll=n(l),el=p(l,"P",{"data-svelte-h":!0}),d(el)!=="svelte-ffthww"&&(el.textContent=As),Dl=n(l),j(tl.$$.fragment,l),ql=n(l),j(nl.$$.fragment,l),Pl=n(l),j(Ml.$$.fragment,l),Ol=n(l),j(cl.$$.fragment,l),ls=n(l),pl=p(l,"P",{"data-svelte-h":!0}),d(pl)!=="svelte-1oywi83"&&(pl.textContent=Xs),ss=n(l),j(il.$$.fragment,l),as=n(l),yl=p(l,"P",{"data-svelte-h":!0}),d(yl)!=="svelte-1519q1p"&&(yl.textContent=fs),es=n(l),j(jl.$$.fragment,l),ts=n(l),j(ol.$$.fragment,l),ns=n(l),wl=p(l,"P",{"data-svelte-h":!0}),d(wl)!=="svelte-14ssh20"&&(wl.innerHTML=Ys),Ms=n(l),rl=p(l,"P",{"data-svelte-h":!0}),d(rl)!=="svelte-1mi0t6"&&(rl.textContent=Vs),cs=n(l),A=p(l,"DIV",{style:!0,"data-svelte-h":!0}),d(A)!=="svelte-11tj8ly"&&(A.innerHTML=Rs),ps=n(l),Jl=p(l,"P",{"data-svelte-h":!0}),d(Jl)!=="svelte-vzj4yr"&&(Jl.innerHTML=_s),is=n(l),j(dl.$$.fragment,l),ys=n(l),ml=p(l,"P",{}),Fs(ml).forEach(a),this.h()},h(){zs(M,"name","hf:doc:metadata"),zs(M,"content",sa),$s(A,"text-align","center")},m(l,s){Ks(document.head,M),e(l,h,s),e(l,i,s),e(l,U,s),o(b,l,s),e(l,m,s),e(l,T,s),e(l,Ul,s),e(l,X,s),e(l,hl,s),e(l,f,s),e(l,ul,s),e(l,Y,s),e(l,bl,s),o(V,l,s),e(l,Tl,s),o(R,l,s),e(l,Il,s),e(l,_,s),e(l,Gl,s),o(g,l,s),e(l,Cl,s),o(C,l,s),e(l,Wl,s),o(N,l,s),e(l,Zl,s),e(l,k,s),e(l,Bl,s),o(v,l,s),e(l,Al,s),e(l,F,s),e(l,Xl,s),e(l,z,s),e(l,fl,s),o(Q,l,s),e(l,Yl,s),e(l,S,s),e(l,Vl,s),o(x,l,s),e(l,Rl,s),e(l,E,s),e(l,_l,s),o(W,l,s),e(l,gl,s),o(Z,l,s),e(l,Nl,s),o(H,l,s),e(l,kl,s),e(l,$,s),e(l,vl,s),o(K,l,s),e(l,Fl,s),o(B,l,s),e(l,zl,s),e(l,L,s),e(l,Ql,s),o(D,l,s),e(l,Sl,s),e(l,q,s),e(l,xl,s),o(P,l,s),e(l,El,s),o(O,l,s),e(l,Hl,s),o(ll,l,s),e(l,$l,s),e(l,sl,s),e(l,Kl,s),e(l,al,s),e(l,Ll,s),e(l,el,s),e(l,Dl,s),o(tl,l,s),e(l,ql,s),o(nl,l,s),e(l,Pl,s),o(Ml,l,s),e(l,Ol,s),o(cl,l,s),e(l,ls,s),e(l,pl,s),e(l,ss,s),o(il,l,s),e(l,as,s),e(l,yl,s),e(l,es,s),o(jl,l,s),e(l,ts,s),o(ol,l,s),e(l,ns,s),e(l,wl,s),e(l,Ms,s),e(l,rl,s),e(l,cs,s),e(l,A,s),e(l,ps,s),e(l,Jl,s),e(l,is,s),o(dl,l,s),e(l,ys,s),e(l,ml,s),js=!0},p(l,[s]){const gs={};s&2&&(gs.$$scope={dirty:s,ctx:l}),C.$set(gs);const Ns={};s&2&&(Ns.$$scope={dirty:s,ctx:l}),W.$set(Ns);const ks={};s&2&&(ks.$$scope={dirty:s,ctx:l}),Z.$set(ks);const vs={};s&2&&(vs.$$scope={dirty:s,ctx:l}),B.$set(vs)},i(l){js||(w(b.$$.fragment,l),w(V.$$.fragment,l),w(R.$$.fragment,l),w(g.$$.fragment,l),w(C.$$.fragment,l),w(N.$$.fragment,l),w(v.$$.fragment,l),w(Q.$$.fragment,l),w(x.$$.fragment,l),w(W.$$.fragment,l),w(Z.$$.fragment,l),w(H.$$.fragment,l),w(K.$$.fragment,l),w(B.$$.fragment,l),w(D.$$.fragment,l),w(P.$$.fragment,l),w(O.$$.fragment,l),w(ll.$$.fragment,l),w(tl.$$.fragment,l),w(nl.$$.fragment,l),w(Ml.$$.fragment,l),w(cl.$$.fragment,l),w(il.$$.fragment,l),w(jl.$$.fragment,l),w(ol.$$.fragment,l),w(dl.$$.fragment,l),js=!0)},o(l){r(b.$$.fragment,l),r(V.$$.fragment,l),r(R.$$.fragment,l),r(g.$$.fragment,l),r(C.$$.fragment,l),r(N.$$.fragment,l),r(v.$$.fragment,l),r(Q.$$.fragment,l),r(x.$$.fragment,l),r(W.$$.fragment,l),r(Z.$$.fragment,l),r(H.$$.fragment,l),r(K.$$.fragment,l),r(B.$$.fragment,l),r(D.$$.fragment,l),r(P.$$.fragment,l),r(O.$$.fragment,l),r(ll.$$.fragment,l),r(tl.$$.fragment,l),r(nl.$$.fragment,l),r(Ml.$$.fragment,l),r(cl.$$.fragment,l),r(il.$$.fragment,l),r(jl.$$.fragment,l),r(ol.$$.fragment,l),r(dl.$$.fragment,l),js=!1},d(l){l&&(a(h),a(i),a(U),a(m),a(T),a(Ul),a(X),a(hl),a(f),a(ul),a(Y),a(bl),a(Tl),a(Il),a(_),a(Gl),a(Cl),a(Wl),a(Zl),a(k),a(Bl),a(Al),a(F),a(Xl),a(z),a(fl),a(Yl),a(S),a(Vl),a(Rl),a(E),a(_l),a(gl),a(Nl),a(kl),a($),a(vl),a(Fl),a(zl),a(L),a(Ql),a(Sl),a(q),a(xl),a(El),a(Hl),a($l),a(sl),a(Kl),a(al),a(Ll),a(el),a(Dl),a(ql),a(Pl),a(Ol),a(ls),a(pl),a(ss),a(as),a(yl),a(es),a(ts),a(ns),a(wl),a(Ms),a(rl),a(cs),a(A),a(ps),a(Jl),a(is),a(ys),a(ml)),a(M),J(b,l),J(V,l),J(R,l),J(g,l),J(C,l),J(N,l),J(v,l),J(Q,l),J(x,l),J(W,l),J(Z,l),J(H,l),J(K,l),J(B,l),J(D,l),J(P,l),J(O,l),J(ll,l),J(tl,l),J(nl,l),J(Ml,l),J(cl,l),J(il,l),J(jl,l),J(ol,l),J(dl,l)}}}const sa='{"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 aa(I){return Ss(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class pa extends xs{constructor(M){super(),Es(this,M,aa,la,Qs,{})}}export{pa as component};
