import{S as X6,i as Z6,s as Q6,e as r,k as h,w as d,t as i,M as J6,c as o,d as t,m as f,a as s,x as c,h as n,b as m,N as I3,G as a,g as p,y as u,q as g,o as w,B as v,v as K6}from"../chunks/vendor-hf-doc-builder.js";import{T as V6}from"../chunks/Tip-hf-doc-builder.js";import{I as _}from"../chunks/IconCopyLink-hf-doc-builder.js";import{C as y}from"../chunks/CodeBlock-hf-doc-builder.js";function ek(Do){let b,A;return{c(){b=r("p"),A=i("Note: In order to properly clear the memory after experiments we need restart the Python kernel between experiments. Run all steps above and then just one of the experiments below.")},l($){b=o($,"P",{});var U=s(b);A=n(U,"Note: In order to properly clear the memory after experiments we need restart the Python kernel between experiments. Run all steps above and then just one of the experiments below."),U.forEach(t)},m($,U){p($,b,U),a(b,A)},d($){$&&t(b)}}}function tk(Do){let b;return{c(){b=i(`Note that in order to use the 8-bit optimizer with an existing pretrained model a change to the embedding layer is needed.
Read [this issue](https://github.com/huggingface/transformers/issues/14819) for more information.`)},l(A){b=n(A,`Note that in order to use the 8-bit optimizer with an existing pretrained model a change to the embedding layer is needed.
Read [this issue](https://github.com/huggingface/transformers/issues/14819) for more information.`)},m(A,$){p(A,b,$)},d(A){A&&t(b)}}}function ak(Do){let b,A,$,U,_n,Qt,uu,bn,gu,oh,qe,wu,jo,vu,yu,sh,C,_u,Io,bu,Eu,Jt,$u,ku,ih,Ce,En,re,No,Pu,Au,Mo,Tu,zu,Oo,xu,Gu,k,oe,qo,Uu,Su,Co,Du,ju,Lo,Iu,Nu,se,Wo,Mu,Ou,Bo,qu,Cu,Fo,Lu,Wu,ie,Ro,Bu,Fu,Ho,Ru,Hu,Yo,Yu,Vu,ne,Vo,Xu,Zu,Xo,Qu,Ju,Zo,Ku,eg,le,Qo,tg,ag,Jo,rg,og,Ko,sg,ig,pe,es,ng,lg,ts,pg,hg,as,fg,mg,he,rs,dg,cg,os,ug,gg,ss,wg,nh,is,vg,lh,Kt,ph,L,yg,$n,_g,bg,kn,Eg,$g,hh,Le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1,e2,Kr,t2,a2,eo,r2,o2,Wi,s2,i2,kd,Ne,Ot,Sp,to,n2,Dp,l2,Pd,Bi,p2,Ad,qt,h2,Fi,f2,m2,Td,Me,Ct,jp,ao,d2,Ip,c2,zd,I,u2,ro,Np,g2,w2,oo,v2,y2,so,_2,b2,xd,Lt,E2,io,Mp,$2,k2,Gd,no,Ud,Ri,P2,Sd,Oe,Wt,Op,lo,A2,qp,T2,Dd,Bt,z2,po,x2,G2,jd,q,Cp,U2,S2,ho,D2,j2,Lp,I2,N2,Id,Hi,M2,Nd,fo,Wp,O2,q2,Md,Ft,Yi,Bp,C2,L2,W2,Vi,Fp,B2,F2,Od,mo,Rp,R2,H2,qd,N,co,Hp,Y2,V2,uo,X2,Z2,go,Yp,Q2,J2,wo,K2,e3,vo,Vp,t3,a3,yo,r3,o3,_o,Xp,s3,i3,bo,n3,Cd,Eo,Zp,l3,p3,Ld,M,$o,Qp,h3,f3,ko,m3,d3,Po,Jp,c3,u3,Ao,g3,w3,To,Kp,v3,y3,zo,_3,b3,xo,eh,E3,$3,Go,k3,Wd;return Qt=new _({}),Kt=new y({props:{code:"pip install transformers datasets accelerate nvidia-ml-py3",highlighted:"pip install transformers datasets accelerate nvidia-ml-py3"}}),ta=new y({props:{code:`import numpy as np
from datasets import Dataset


seq_len, dataset_size = 512, 512
dummy_data = {
    "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)),
    "labels": np.random.randint(0, 1, (dataset_size)),
}
ds = Dataset.from_dict(dummy_data)
ds.set_format("pt")`,highlighted:`<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> Dataset


seq_len, dataset_size = <span class="hljs-number">512</span>, <span class="hljs-number">512</span>
dummy_data = {
    <span class="hljs-string">&quot;input_ids&quot;</span>: np.random.randint(<span class="hljs-number">100</span>, <span class="hljs-number">30000</span>, (dataset_size, seq_len)),
    <span class="hljs-string">&quot;labels&quot;</span>: np.random.randint(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, (dataset_size)),
}
ds = Dataset.from_dict(dummy_data)
ds.set_format(<span class="hljs-string">&quot;pt&quot;</span>)`}}),aa=new y({props:{code:`from pynvml import *


def print_gpu_utilization():
    nvmlInit()
    handle = nvmlDeviceGetHandleByIndex(0)
    info = nvmlDeviceGetMemoryInfo(handle)
    print(f"GPU memory occupied: {info.used//1024**2} MB.")


def print_summary(result):
    print(f"Time: {result.metrics['train_runtime']:.2f}")
    print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}")
    print_gpu_utilization()`,highlighted:`<span class="hljs-keyword">from</span> pynvml <span class="hljs-keyword">import</span> *


<span class="hljs-keyword">def</span> <span class="hljs-title function_">print_gpu_utilization</span>():
    nvmlInit()
    handle = nvmlDeviceGetHandleByIndex(<span class="hljs-number">0</span>)
    info = nvmlDeviceGetMemoryInfo(handle)
    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;GPU memory occupied: <span class="hljs-subst">{info.used//<span class="hljs-number">1024</span>**<span class="hljs-number">2</span>}</span> MB.&quot;</span>)


<span class="hljs-keyword">def</span> <span class="hljs-title function_">print_summary</span>(<span class="hljs-params">result</span>):
    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Time: <span class="hljs-subst">{result.metrics[<span class="hljs-string">&#x27;train_runtime&#x27;</span>]:<span class="hljs-number">.2</span>f}</span>&quot;</span>)
    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Samples/second: <span class="hljs-subst">{result.metrics[<span class="hljs-string">&#x27;train_samples_per_second&#x27;</span>]:<span class="hljs-number">.2</span>f}</span>&quot;</span>)
    print_gpu_utilization()`}}),ra=new y({props:{code:"print_gpu_utilization()",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>print_gpu_utilization()
GPU memory occupied: <span class="hljs-number">0</span> MB.`}}),oa=new y({props:{code:`import torch


torch.ones((1, 1)).to("cuda")
print_gpu_utilization()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch


<span class="hljs-meta">&gt;&gt;&gt; </span>torch.ones((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>)).to(<span class="hljs-string">&quot;cuda&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>print_gpu_utilization()
GPU memory occupied: <span class="hljs-number">1343</span> MB.`}}),sa=new _({}),ia=new y({props:{code:`from transformers import AutoModelForSequenceClassification


model = AutoModelForSequenceClassification.from_pretrained("bert-large-uncased").to("cuda")
print_gpu_utilization()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForSequenceClassification


<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForSequenceClassification.from_pretrained(<span class="hljs-string">&quot;bert-large-uncased&quot;</span>).to(<span class="hljs-string">&quot;cuda&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>print_gpu_utilization()
GPU memory occupied: <span class="hljs-number">2631</span> MB.`}}),na=new y({props:{code:"nvidia-smi",highlighted:"nvidia-smi"}}),la=new y({props:{code:`Tue Jan 11 08:58:05 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.91.03    Driver Version: 460.91.03    CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla V100-SXM2...  On   | 00000000:00:04.0 Off |                    0 |
| N/A   37C    P0    39W / 300W |   2631MiB / 16160MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      3721      C   ...nvs/codeparrot/bin/python     2629MiB |
+-----------------------------------------------------------------------------+`,highlighted:`Tue Jan 11 08:58:05 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.91.03    Driver Version: 460.91.03    CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla V100-SXM2...  On   | 00000000:00:04.0 Off |                    0 |
| N/A   37C    P0    39W / 300W |   2631MiB / 16160MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      3721      C   ...nvs/codeparrot/bin/python     2629MiB |
+-----------------------------------------------------------------------------+`}}),pa=new y({props:{code:`default_args = {
    "output_dir": "tmp",
    "evaluation_strategy": "steps",
    "num_train_epochs": 1,
    "log_level": "error",
    "report_to": "none",
}`,highlighted:`default_args = {
    <span class="hljs-string">&quot;output_dir&quot;</span>: <span class="hljs-string">&quot;tmp&quot;</span>,
    <span class="hljs-string">&quot;evaluation_strategy&quot;</span>: <span class="hljs-string">&quot;steps&quot;</span>,
    <span class="hljs-string">&quot;num_train_epochs&quot;</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">&quot;log_level&quot;</span>: <span class="hljs-string">&quot;error&quot;</span>,
    <span class="hljs-string">&quot;report_to&quot;</span>: <span class="hljs-string">&quot;none&quot;</span>,
}`}}),He=new V6({props:{$$slots:{default:[ek]},$$scope:{ctx:Do}}}),ha=new _({}),fa=new y({props:{code:`from transformers import TrainingArguments, Trainer, logging

logging.set_verbosity_error()


training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)
trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TrainingArguments, Trainer, logging

logging.set_verbosity_error()


training_args = TrainingArguments(per_device_train_batch_size=<span class="hljs-number">4</span>, **default_args)
trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),ma=new y({props:{code:`Time: 57.82
Samples/second: 8.86
GPU memory occupied: 14949 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 57.82
Samples/second: 8.86
GPU memory occupied: 14949 MB.`}}),da=new _({}),Ea=new _({}),ka=new _({}),Ga=new _({}),Ua=new y({props:{code:`training_args = TrainingArguments(per_device_train_batch_size=1, gradient_accumulation_steps=4, **default_args)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(per_device_train_batch_size=<span class="hljs-number">1</span>, gradient_accumulation_steps=<span class="hljs-number">4</span>, **default_args)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),Sa=new y({props:{code:`Time: 66.03
Samples/second: 7.75
GPU memory occupied: 8681 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 66.03
Samples/second: 7.75
GPU memory occupied: 8681 MB.`}}),Ia=new _({}),Ma=new y({props:{code:`training_args = TrainingArguments(
    per_device_train_batch_size=1, gradient_accumulation_steps=4, gradient_checkpointing=True, **default_args
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(
    per_device_train_batch_size=<span class="hljs-number">1</span>, gradient_accumulation_steps=<span class="hljs-number">4</span>, gradient_checkpointing=<span class="hljs-literal">True</span>, **default_args
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),Oa=new y({props:{code:`Time: 85.47
Samples/second: 5.99
GPU memory occupied: 6775 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 85.47
Samples/second: 5.99
GPU memory occupied: 6775 MB.`}}),qa=new _({}),Fa=new _({}),Ra=new y({props:{code:`training_args = TrainingArguments(per_device_train_batch_size=4, fp16=True, **default_args)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(per_device_train_batch_size=<span class="hljs-number">4</span>, fp16=<span class="hljs-literal">True</span>, **default_args)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),Ha=new y({props:{code:`Time: 27.46
Samples/second: 18.64
GPU memory occupied: 13939 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 27.46
Samples/second: 18.64
GPU memory occupied: 13939 MB.`}}),Ya=new y({props:{code:`training_args = TrainingArguments(
    per_device_train_batch_size=1,
    gradient_accumulation_steps=4,
    gradient_checkpointing=True,
    fp16=True,
    **default_args,
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(
    per_device_train_batch_size=<span class="hljs-number">1</span>,
    gradient_accumulation_steps=<span class="hljs-number">4</span>,
    gradient_checkpointing=<span class="hljs-literal">True</span>,
    fp16=<span class="hljs-literal">True</span>,
    **default_args,
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),Va=new y({props:{code:`Time: 50.76
Samples/second: 10.09
GPU memory occupied: 7275 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 50.76
Samples/second: 10.09
GPU memory occupied: 7275 MB.`}}),Xa=new _({}),Za=new y({props:{code:"TrainingArguments(bf16=True)",highlighted:'TrainingArguments(bf16=<span class="hljs-literal">True</span>)'}}),Qa=new _({}),Ja=new y({props:{code:`import torch
torch.backends.cuda.matmul.allow_tf32 = True`,highlighted:`import torch
torch<span class="hljs-selector-class">.backends</span><span class="hljs-selector-class">.cuda</span><span class="hljs-selector-class">.matmul</span><span class="hljs-selector-class">.allow_tf32</span> = True`}}),er=new y({props:{code:"TrainingArguments(tf32=True)",highlighted:'TrainingArguments(tf32=<span class="hljs-literal">True</span>)'}}),rr=new _({}),or=new y({props:{code:`$ python examples/pytorch/translation/run_translation.py -h | grep "\\-optim"
         [--optim {adamw_hf,adamw_torch,adamw_torch_xla,adamw_apex_fused,adafactor}]`,highlighted:`$ python examples/pytorch/translation/run_translation.py -h | grep <span class="hljs-string">&quot;\\-optim&quot;</span>
         [--optim {adamw_hf,adamw_torch,adamw_torch_xla,adamw_apex_fused,adafactor}]`}}),hr=new _({}),fr=new y({props:{code:`training_args = TrainingArguments(per_device_train_batch_size=4, optim="adafactor", **default_args)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(per_device_train_batch_size=<span class="hljs-number">4</span>, optim=<span class="hljs-string">&quot;adafactor&quot;</span>, **default_args)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),mr=new y({props:{code:`Time: 64.31
Samples/second: 7.96
GPU memory occupied: 12295 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 64.31
Samples/second: 7.96
GPU memory occupied: 12295 MB.`}}),dr=new y({props:{code:`training_args = TrainingArguments(
    per_device_train_batch_size=1,
    gradient_accumulation_steps=4,
    gradient_checkpointing=True,
    fp16=True,
    optim="adafactor",
    **default_args,
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(
    per_device_train_batch_size=<span class="hljs-number">1</span>,
    gradient_accumulation_steps=<span class="hljs-number">4</span>,
    gradient_checkpointing=<span class="hljs-literal">True</span>,
    fp16=<span class="hljs-literal">True</span>,
    optim=<span class="hljs-string">&quot;adafactor&quot;</span>,
    **default_args,
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds)
result = trainer.train()
print_summary(result)`}}),cr=new y({props:{code:`Time: 56.54
Samples/second: 9.06
GPU memory occupied: 4847 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 56.54
Samples/second: 9.06
GPU memory occupied: 4847 MB.`}}),ur=new _({}),wt=new V6({props:{$$slots:{default:[tk]},$$scope:{ctx:Do}}}),wr=new y({props:{code:`import bitsandbytes as bnb
from torch import nn
from transformers.trainer_pt_utils import get_parameter_names

training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)

decay_parameters = get_parameter_names(model, [nn.LayerNorm])
decay_parameters = [name for name in decay_parameters if "bias" not in name]
optimizer_grouped_parameters = [
    {
        "params": [p for n, p in model.named_parameters() if n in decay_parameters],
        "weight_decay": training_args.weight_decay,
    },
    {
        "params": [p for n, p in model.named_parameters() if n not in decay_parameters],
        "weight_decay": 0.0,
    },
]

optimizer_kwargs = {
    "betas": (training_args.adam_beta1, training_args.adam_beta2),
    "eps": training_args.adam_epsilon,
}
optimizer_kwargs["lr"] = training_args.learning_rate
adam_bnb_optim = bnb.optim.Adam8bit(
    optimizer_grouped_parameters,
    betas=(training_args.adam_beta1, training_args.adam_beta2),
    eps=training_args.adam_epsilon,
    lr=training_args.learning_rate,
)`,highlighted:`<span class="hljs-keyword">import</span> bitsandbytes <span class="hljs-keyword">as</span> bnb
<span class="hljs-keyword">from</span> torch <span class="hljs-keyword">import</span> nn
<span class="hljs-keyword">from</span> transformers.trainer_pt_utils <span class="hljs-keyword">import</span> get_parameter_names

training_args = TrainingArguments(per_device_train_batch_size=<span class="hljs-number">4</span>, **default_args)

decay_parameters = get_parameter_names(model, [nn.LayerNorm])
decay_parameters = [name <span class="hljs-keyword">for</span> name <span class="hljs-keyword">in</span> decay_parameters <span class="hljs-keyword">if</span> <span class="hljs-string">&quot;bias&quot;</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> name]
optimizer_grouped_parameters = [
    {
        <span class="hljs-string">&quot;params&quot;</span>: [p <span class="hljs-keyword">for</span> n, p <span class="hljs-keyword">in</span> model.named_parameters() <span class="hljs-keyword">if</span> n <span class="hljs-keyword">in</span> decay_parameters],
        <span class="hljs-string">&quot;weight_decay&quot;</span>: training_args.weight_decay,
    },
    {
        <span class="hljs-string">&quot;params&quot;</span>: [p <span class="hljs-keyword">for</span> n, p <span class="hljs-keyword">in</span> model.named_parameters() <span class="hljs-keyword">if</span> n <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> decay_parameters],
        <span class="hljs-string">&quot;weight_decay&quot;</span>: <span class="hljs-number">0.0</span>,
    },
]

optimizer_kwargs = {
    <span class="hljs-string">&quot;betas&quot;</span>: (training_args.adam_beta1, training_args.adam_beta2),
    <span class="hljs-string">&quot;eps&quot;</span>: training_args.adam_epsilon,
}
optimizer_kwargs[<span class="hljs-string">&quot;lr&quot;</span>] = training_args.learning_rate
adam_bnb_optim = bnb.optim.Adam8bit(
    optimizer_grouped_parameters,
    betas=(training_args.adam_beta1, training_args.adam_beta2),
    eps=training_args.adam_epsilon,
    lr=training_args.learning_rate,
)`}}),vr=new y({props:{code:`trainer = Trainer(model=model, args=training_args, train_dataset=ds, optimizers=(adam_bnb_optim, None))
result = trainer.train()
print_summary(result)`,highlighted:`trainer = Trainer(model=model, args=training_args, train_dataset=ds, optimizers=(adam_bnb_optim, <span class="hljs-literal">None</span>))
result = trainer.train()
print_summary(result)`}}),yr=new y({props:{code:`Time: 55.95
Samples/second: 9.15
GPU memory occupied: 13085 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 55.95
Samples/second: 9.15
GPU memory occupied: 13085 MB.`}}),_r=new y({props:{code:`training_args = TrainingArguments(
    per_device_train_batch_size=1,
    gradient_accumulation_steps=4,
    gradient_checkpointing=True,
    fp16=True,
    **default_args,
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds, optimizers=(adam_bnb_optim, None))
result = trainer.train()
print_summary(result)`,highlighted:`training_args = TrainingArguments(
    per_device_train_batch_size=<span class="hljs-number">1</span>,
    gradient_accumulation_steps=<span class="hljs-number">4</span>,
    gradient_checkpointing=<span class="hljs-literal">True</span>,
    fp16=<span class="hljs-literal">True</span>,
    **default_args,
)

trainer = Trainer(model=model, args=training_args, train_dataset=ds, optimizers=(adam_bnb_optim, <span class="hljs-literal">None</span>))
result = trainer.train()
print_summary(result)`}}),br=new y({props:{code:`Time: 49.46
Samples/second: 10.35
GPU memory occupied: 5363 MB.`,highlighted:`<span class="hljs-keyword">Time:</span> 49.46
Samples/second: 10.35
GPU memory occupied: 5363 MB.`}}),Er=new _({}),$r=new _({}),kr=new y({props:{code:`training_args = TrainingArguments(
    per_device_train_batch_size=1,
    gradient_accumulation_steps=4,
    gradient_checkpointing=True,
    fp16=True,
    **default_args,
)`,highlighted:`training_args = TrainingArguments(
    per_device_train_batch_size=<span class="hljs-number">1</span>,
    gradient_accumulation_steps=<span class="hljs-number">4</span>,
    gradient_checkpointing=<span class="hljs-literal">True</span>,
    fp16=<span class="hljs-literal">True</span>,
    **default_args,
)`}}),Pr=new y({props:{code:`from accelerate import Accelerator
from torch.utils.data.dataloader import DataLoader

dataloader = DataLoader(ds, batch_size=training_args.per_device_train_batch_size)

if training_args.gradient_checkpointing:
    model.gradient_checkpointing_enable()

accelerator = Accelerator(fp16=training_args.fp16)
model, optimizer, dataloader = accelerator.prepare(model, adam_bnb_optim, dataloader)

model.train()
for step, batch in enumerate(dataloader, start=1):
    loss = model(**batch).loss
    loss = loss / training_args.gradient_accumulation_steps
    accelerator.backward(loss)
    if step % training_args.gradient_accumulation_steps == 0:
        optimizer.step()
        optimizer.zero_grad()`,highlighted:`<span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator
<span class="hljs-keyword">from</span> torch.utils.data.dataloader <span class="hljs-keyword">import</span> DataLoader

dataloader = DataLoader(ds, batch_size=training_args.per_device_train_batch_size)

<span class="hljs-keyword">if</span> training_args.gradient_checkpointing:
    model.gradient_checkpointing_enable()

accelerator = Accelerator(fp16=training_args.fp16)
model, optimizer, dataloader = accelerator.prepare(model, adam_bnb_optim, dataloader)

model.train()
<span class="hljs-keyword">for</span> step, batch <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(dataloader, start=<span class="hljs-number">1</span>):
    loss = model(**batch).loss
    loss = loss / training_args.gradient_accumulation_steps
    accelerator.backward(loss)
    <span class="hljs-keyword">if</span> step % training_args.gradient_accumulation_steps == <span class="hljs-number">0</span>:
        optimizer.step()
        optimizer.zero_grad()`}}),xr=new y({props:{code:"print_gpu_utilization()",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>print_gpu_utilization()
GPU memory occupied: <span class="hljs-number">5363</span> MB.`}}),Ur=new _({}),Sr=new _({}),Ir=new y({props:{code:'TrainingArguments(deepspeed="/path/to/ds_config.json")',highlighted:'TrainingArguments(deepspeed=<span class="hljs-string">&quot;/path/to/ds_config.json&quot;</span>)'}}),Or=new _({}),qr=new _({}),Cr=new _({}),Fr=new _({}),Rr=new _({}),to=new _({}),ao=new _({}),no=new y({props:{code:"model = model.to_bettertransformer()",highlighted:"model = model.to_bettertransformer()"}}),lo=new _({}),{c(){b=r("meta"),A=h(),$=r("h1"),U=r("a"),_n=r("span"),d(Qt.$$.fragment),uu=h(),bn=r("span"),gu=i("Efficient Training on a Single GPU"),oh=h(),qe=r("p"),wu=i("This guide focuses on training large models efficiently on a single GPU. These approaches are still valid if you have access to a machine with multiple GPUs but you will also have access to additional methods outlined in the "),jo=r("a"),vu=i("multi-GPU section"),yu=i("."),sh=h(),C=r("p"),_u=i("In this section we have a look at a few tricks to reduce the memory footprint and speed up training for large models and how they are integrated in the "),Io=r("a"),bu=i("Trainer"),Eu=i(" and "),Jt=r("a"),$u=i("\u{1F917} Accelerate"),ku=i(". Each method can improve speed or memory usage which is summarized in the table below:"),ih=h(),Ce=r("table"),En=r("thead"),re=r("tr"),No=r("th"),Pu=i("Method"),Au=h(),Mo=r("th"),Tu=i("Speed"),zu=h(),Oo=r("th"),xu=i("Memory"),Gu=h(),k=r("tbody"),oe=r("tr"),qo=r("td"),Uu=i("Gradient accumulation"),Su=h(),Co=r("td"),Du=i("No"),ju=h(),Lo=r("td"),Iu=i("Yes"),Nu=h(),se=r("tr"),Wo=r("td"),Mu=i("Gradient checkpointing"),Ou=h(),Bo=r("td"),qu=i("No"),Cu=h(),Fo=r("td"),Lu=i("Yes"),Wu=h(),ie=r("tr"),Ro=r("td"),Bu=i("Mixed precision training"),Fu=h(),Ho=r("td"),Ru=i("Yes"),Hu=h(),Yo=r("td"),Yu=i("(No)"),Vu=h(),ne=r("tr"),Vo=r("td"),Xu=i("Batch size"),Zu=h(),Xo=r("td"),Qu=i("Yes"),Ju=h(),Zo=r("td"),Ku=i("Yes"),eg=h(),le=r("tr"),Qo=r("td"),tg=i("Optimizer choice"),ag=h(),Jo=r("td"),rg=i("Yes"),og=h(),Ko=r("td"),sg=i("Yes"),ig=h(),pe=r("tr"),es=r("td"),ng=i("DataLoader"),lg=h(),ts=r("td"),pg=i("Yes"),hg=h(),as=r("td"),fg=i("No"),mg=h(),he=r("tr"),rs=r("td"),dg=i("DeepSpeed Zero"),cg=h(),os=r("td"),ug=i("No"),gg=h(),ss=r("td"),wg=i("Yes"),nh=h(),is=r("p"),vg=i("A bracket means that it might not be strictly the case but is usually either not a main concern or negligible. Before we start make sure you have installed the following libraries:"),lh=h(),d(Kt.$$.fragment),ph=h(),L=r("p"),yg=i("The "),$n=r("code"),_g=i("nvidia-ml-py3"),bg=i(" library allows us to monitor the memory usage of the models from within Python. You might be familiar with the "),kn=r("code"),Eg=i("nvidia-smi"),$g=i(" command in the terminal - this library allows to access the same information in Python directly."),hh=h(),Le=r("p"),kg=i("Then we create some dummy data. We create random token IDs between 100 and 30000 and binary labels for a classifier. In total we get 512 sequences each with length 512 and store them in a "),ea=r("a"),Pg=i("Dataset"),Ag=i(" with PyTorch format."),fh=h(),d(ta.$$.fragment),mh=h(),We=r("p"),Tg=i("We want to print some summary statistics for the GPU utilization and the training run with the "),ns=r("a"),zg=i("Trainer"),xg=i(". We setup a two helper functions to do just that:"),dh=h(),d(aa.$$.fragment),ch=h(),ls=r("p"),Gg=i("Let\u2019s verify that we start with a free GPU memory:"),uh=h(),d(ra.$$.fragment),gh=h(),ps=r("p"),Ug=i("That looks good: the GPU memory is not occupied as we would expect before we load any models. If that\u2019s not the case on your machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by the user. When a model is loaded to the GPU also the kernels are loaded which can take up 1-2GB of memory. To see how much it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well."),wh=h(),d(oa.$$.fragment),vh=h(),hs=r("p"),Sg=i("We see that the kernels alone take up 1.3GB of GPU memory. Now let\u2019s see how much space the model uses."),yh=h(),fe=r("h2"),Be=r("a"),Pn=r("span"),d(sa.$$.fragment),Dg=h(),An=r("span"),jg=i("Load Model"),_h=h(),Fe=r("p"),Ig=i("First, we load the "),Tn=r("code"),Ng=i("bert-large-uncased"),Mg=i(" model. We load the model weights directly to the GPU so that we can check how much space just weights use."),bh=h(),d(ia.$$.fragment),Eh=h(),Re=r("p"),Og=i("We can see that the model weights alone take up 1.3 GB of the GPU memory. The exact number depends on the specific GPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an optimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result as with "),zn=r("code"),qg=i("nvidia-smi"),Cg=i(" CLI:"),$h=h(),d(na.$$.fragment),kh=h(),d(la.$$.fragment),Ph=h(),fs=r("p"),Lg=i("We get the same number as before and you can also see that we are using a V100 GPU with 16GB of memory. So now we can start training the model and see how the GPU memory consumption changes. First, we set up a few standard training arguments that we will use across all our experiments:"),Ah=h(),d(pa.$$.fragment),Th=h(),d(He.$$.fragment),zh=h(),me=r("h2"),Ye=r("a"),xn=r("span"),d(ha.$$.fragment),Wg=h(),Gn=r("span"),Bg=i("Vanilla Training"),xh=h(),Ve=r("p"),Fg=i("As a first experiment we will use the "),ms=r("a"),Rg=i("Trainer"),Hg=i(" and train the model without any further modifications and a batch size of 4:"),Gh=h(),d(fa.$$.fragment),Uh=h(),d(ma.$$.fragment),Sh=h(),ds=r("p"),Yg=i("We see that already a relatively small batch size almost fills up our GPU\u2019s entire memory. However, a larger batch size can often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our model\u2019s needs and not to the GPU limitations. What\u2019s interesting is that we use much more memory than the size of the model. To understand a bit better why this is the case let\u2019s have look at a model\u2019s operations and memory needs."),Dh=h(),de=r("h2"),Xe=r("a"),Un=r("span"),d(da.$$.fragment),Vg=h(),Sn=r("span"),Xg=i("Anatomy of Model's Operations"),jh=h(),cs=r("p"),Zg=i("Transformers architecture includes 3 main groups of operations grouped below by compute-intensity."),Ih=h(),W=r("ol"),ca=r("li"),Dn=r("p"),jn=r("strong"),Qg=i("Tensor Contractions"),Jg=h(),ua=r("p"),Kg=i("Linear layers and components of Multi-Head Attention all do batched "),In=r("strong"),ew=i("matrix-matrix multiplications"),tw=i(". These operations are the most compute-intensive part of training a transformer."),aw=h(),ga=r("li"),Nn=r("p"),Mn=r("strong"),rw=i("Statistical Normalizations"),ow=h(),wa=r("p"),sw=i("Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more "),On=r("strong"),iw=i("reduction operations"),nw=i(", the result of which is then applied via a map."),lw=h(),va=r("li"),qn=r("p"),Cn=r("strong"),pw=i("Element-wise Operators"),hw=h(),ya=r("p"),fw=i("These are the remaining operators: "),Ln=r("strong"),mw=i("biases, dropout, activations, and residual connections"),dw=i(". These are the least compute-intensive operations."),Nh=h(),us=r("p"),cw=i("This knowledge can be helpful to know when analyzing performance bottlenecks."),Mh=h(),_a=r("p"),uw=i("This summary is derived from "),ba=r("a"),gw=i("Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020"),Oh=h(),ce=r("h2"),Ze=r("a"),Wn=r("span"),d(Ea.$$.fragment),ww=h(),Bn=r("span"),vw=i("Anatomy of Model's Memory"),qh=i(`

We've seen that training the model uses much more memory than just putting the model on the GPU. This is because there are many components during training that use GPU memory. The components on GPU memory are the following:
1. model weights
2. optimizer states
3. gradients
4. forward activations saved for gradient computation
5. temporary buffers
6. functionality-specific memory
`),gs=r("p"),yw=i("A typical model trained in mixed precision with AdamW requires 18 bytes per model parameter plus activation memory. For inference there are no optimizer states and gradients, so we can subtract those. And thus we end up with 6 bytes per model parameter for mixed precision inference, plus activation memory."),Ch=h(),ws=r("p"),_w=i("Let\u2019s look at the details."),Lh=h(),vs=r("p"),Fn=r("strong"),bw=i("Model Weights:"),Wh=h(),Qe=r("ul"),Rn=r("li"),Ew=i("4 bytes * number of parameters for fp32 training"),$w=h(),Hn=r("li"),kw=i("6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)"),Bh=h(),ys=r("p"),Yn=r("strong"),Pw=i("Optimizer States:"),Fh=h(),B=r("ul"),Vn=r("li"),Aw=i("8 bytes * number of parameters for normal AdamW (maintains 2 states)"),Tw=h(),_s=r("li"),zw=i("2 bytes * number of parameters for 8-bit AdamW optimizers like "),$a=r("a"),xw=i("bitsandbytes"),Gw=h(),Xn=r("li"),Uw=i("4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)"),Rh=h(),bs=r("p"),Zn=r("strong"),Sw=i("Gradients"),Hh=h(),Es=r("ul"),Qn=r("li"),Dw=i("4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)"),Yh=h(),$s=r("p"),Jn=r("strong"),jw=i("Forward Activations"),Vh=h(),ks=r("ul"),Kn=r("li"),Iw=i("size depends on many factors, the key ones being sequence length, hidden size and batch size."),Xh=h(),Ps=r("p"),Nw=i("There are the input and output that are being passed and returned by the forward and the backward functions and the forward activations saved for gradient computation."),Zh=h(),As=r("p"),el=r("strong"),Mw=i("Temporary Memory"),Qh=h(),Ts=r("p"),Ow=i("Additionally there are all kinds of temporary variables which get released once the calculation is done, but in the moment these could require additional memory and could push to OOM. Therefore when coding it\u2019s crucial to think strategically about such temporary variables and sometimes to explicitly free those as soon as they are no longer needed."),Jh=h(),zs=r("p"),tl=r("strong"),qw=i("Functionality-specific memory"),Kh=h(),xs=r("p"),Cw=i("Then your software could have special memory needs. For example, when generating text using beam search, the software needs to maintain multiple copies of inputs and outputs."),ef=h(),Gs=r("p"),Je=r("strong"),al=r("code"),Lw=i("forward"),Ww=i(" vs "),rl=r("code"),Bw=i("backward"),Fw=i(" Execution Speed"),tf=h(),Us=r("p"),Rw=i("For convolutions and linear layers there are 2x flops in the backward compared to the forward, which generally translates into ~2x slower (sometimes more, because sizes in the backward tend to be more awkward). Activations are usually bandwidth-limited, and it\u2019s typical for an activation to have to read more data in the backward than in the forward (e.g. activation forward reads once, writes once, activation backward reads twice, gradOutput and output of the forward, and writes once, gradInput)."),af=h(),Ss=r("p"),Hw=i("So there are potentially a few places where we could save GPU memory or speed up operations. Let\u2019s start with a simple optimization: choosing the right batch size."),rf=h(),ue=r("h2"),Ke=r("a"),ol=r("span"),d(ka.$$.fragment),Yw=h(),sl=r("span"),Vw=i("Batch sizes"),of=h(),Ds=r("p"),Xw=i("One gets the most efficient performance when batch sizes and input/output neuron counts are divisible by a certain number, which typically starts at 8, but can be much higher as well. That number varies a lot depending on the specific hardware being used and the dtype of the model."),sf=h(),F=r("p"),Zw=i("For example for fully connected layers (which correspond to GEMMs), NVIDIA provides recommendations for "),Pa=r("a"),Qw=i("input/output neuron counts"),Jw=i(" and "),Aa=r("a"),Kw=i("batch size"),ev=i("."),nf=h(),Ta=r("p"),za=r("a"),tv=i("Tensor Core Requirements"),av=i(" define the multiplier based on the dtype and the hardware. For example, for fp16 a multiple of 8 is recommended, but on A100 it\u2019s 64!"),lf=h(),et=r("p"),rv=i("For parameters that are small, there is also "),xa=r("a"),ov=i("Dimension Quantization Effects"),sv=i(" to consider, this is where tiling happens and the right multiplier can have a significant speedup."),pf=h(),ge=r("h2"),tt=r("a"),il=r("span"),d(Ga.$$.fragment),iv=h(),nl=r("span"),nv=i("Gradient Accumulation"),hf=h(),js=r("p"),lv=i("The idea behind gradient accumulation is to instead of calculating the gradients for the whole batch at once to do it in smaller steps. The way we do that is to calculate the gradients iteratively in smaller batches by doing a forward and backward pass through the model and accumulating the gradients in the process. When enough gradients are accumulated we run the model\u2019s optimization step. This way we can easily increase the overall batch size to numbers that would never fit into the GPU\u2019s memory. In turn, however, the added forward and backward passes can slow down the training a bit."),ff=h(),S=r("p"),pv=i("We can use gradient accumulation in the "),Is=r("a"),hv=i("Trainer"),fv=i(" by simply adding the "),ll=r("code"),mv=i("gradient_accumulation_steps"),dv=i(" argument to "),Ns=r("a"),cv=i("TrainingArguments"),uv=i(". Let\u2019s see how it impacts the models memory footprint:"),mf=h(),d(Ua.$$.fragment),df=h(),d(Sa.$$.fragment),cf=h(),T=r("p"),gv=i("We can see that the memory footprint was dramatically reduced at the cost of being only slightly slower than the vanilla run. Of course, this would change as you increase the number of accumulation steps. In general you would want to max out the GPU usage as much as possible. So in our case, the batch_size of 4 was already pretty close to the GPU\u2019s limit. If we wanted to train with a batch size of 64 we should not use "),pl=r("code"),wv=i("per_device_train_batch_size=1"),vv=i(" and "),hl=r("code"),yv=i("gradient_accumulation_steps=64"),_v=i(" but instead "),fl=r("code"),bv=i("per_device_train_batch_size=4"),Ev=i(" and "),ml=r("code"),$v=i("gradient_accumulation_steps=16"),kv=i(" which has the same effective batch size while making better use of the available GPU resources."),uf=h(),R=r("p"),Pv=i("For more details see the benchmarks for "),Da=r("a"),Av=i("RTX-3090"),Tv=i(`
and `),ja=r("a"),zv=i("A100"),xv=i("."),gf=h(),Ms=r("p"),Gv=i("Next we have a look at another trick to save a little bit more GPU memory called gradient checkpointing."),wf=h(),we=r("h2"),at=r("a"),dl=r("span"),d(Ia.$$.fragment),Uv=h(),cl=r("span"),Sv=i("Gradient Checkpointing"),vf=h(),Os=r("p"),Dv=i("Even when we set the batch size to 1 and use gradient accumulation we can still run out of memory when working with large models. In order to compute the gradients during the backward pass all activations from the forward pass are normally saved. This can create a big memory overhead. Alternatively, one could forget all activations during the forward pass and recompute them on demand during the backward pass. This would however add a significant computational overhead and slow down training."),yf=h(),rt=r("p"),jv=i("Gradient checkpointing strikes a compromise between the two approaches and saves strategically selected activations throughout the computational graph so only a fraction of the activations need to be re-computed for the gradients. See "),Na=r("a"),Iv=i("this great article"),Nv=i(" explaining the ideas behind gradient checkpointing."),_f=h(),H=r("p"),Mv=i("To enable gradient checkpointing in the "),qs=r("a"),Ov=i("Trainer"),qv=i(" we only need to pass it as a flag to the "),Cs=r("a"),Cv=i("TrainingArguments"),Lv=i(". Everything else is handled under the hood:"),bf=h(),d(Ma.$$.fragment),Ef=h(),d(Oa.$$.fragment),$f=h(),Ls=r("p"),Wv=i("We can see that this saved some more memory but at the same time training became a bit slower. A general rule of thumb is that gradient checkpointing slows down training by about 20%. Let\u2019s have a look at another method with which we can regain some speed: mixed precision training."),kf=h(),ve=r("h2"),ot=r("a"),ul=r("span"),d(qa.$$.fragment),Bv=h(),gl=r("span"),Fv=i("Floating Data Types"),Pf=h(),Ws=r("p"),Rv=i("The idea of mixed precision training is that not all variables need to be stored in full (32-bit) floating point precision. If we can reduce the precision the variables and their computations are faster. Here are the commonly used floating point data types choice of which impacts both memory usage and throughput:"),Af=h(),D=r("ul"),Ca=r("li"),Hv=i("fp32 ("),wl=r("code"),Yv=i("float32"),Vv=i(")"),Xv=h(),La=r("li"),Zv=i("fp16 ("),vl=r("code"),Qv=i("float16"),Jv=i(")"),Kv=h(),Wa=r("li"),ey=i("bf16 ("),yl=r("code"),ty=i("bfloat16"),ay=i(")"),ry=h(),_l=r("li"),oy=i("tf32 (CUDA internal data type)"),Tf=h(),Bs=r("p"),sy=i("Here is a diagram that shows how these data types correlate to each other."),zf=h(),ye=r("p"),Fs=r("img"),iy=i(`
(source: `),Ba=r("a"),ny=i("NVIDIA Blog"),ly=i(")"),xf=h(),Rs=r("p"),py=i("While fp16 and fp32 have been around for quite some time, bf16 and tf32 are only available on the Ampere architecture GPUS and TPUs support bf16 as well. Let\u2019s start with the most commonly used method which is FP16 training/"),Gf=h(),_e=r("h3"),st=r("a"),bl=r("span"),d(Fa.$$.fragment),hy=h(),El=r("span"),fy=i("FP16 Training"),Uf=h(),Y=r("p"),my=i("The idea of mixed precision training is that not all variables need to be stored in full (32-bit) floating point precision. If we can reduce the precision the variales and their computations are faster. The main advantage comes from saving the activations in half (16-bit) precision. Although the gradients are also computed in half precision they are converted back to full precision for the optimization step so no memory is saved here. Since the model is present on the GPU in both 16-bit and 32-bit precision this can use more GPU memory (1.5x the original model is on the GPU), especially for small batch sizes. Since some computations are performed in full and some in half precision this approach is also called mixed precision training. Enabling mixed precision training is also just a matter of setting the "),$l=r("code"),dy=i("fp16"),cy=i(" flag to "),kl=r("code"),uy=i("True"),gy=i(":"),Sf=h(),d(Ra.$$.fragment),Df=h(),d(Ha.$$.fragment),jf=h(),Hs=r("p"),wy=i("We can see that this is almost twice as fast as the vanilla training. Let\u2019s add it to the mix of the previous methods:"),If=h(),d(Ya.$$.fragment),Nf=h(),d(Va.$$.fragment),Mf=h(),Ys=r("p"),vy=i("We can see that with these tweaks we use about half the GPU memory as at the beginning while also being slightly faster."),Of=h(),be=r("h3"),it=r("a"),Pl=r("span"),d(Xa.$$.fragment),yy=h(),Al=r("span"),_y=i("BF16"),qf=i("\n\nIf you have access to a Ampere or newer hardware you can use bf16 for your training and evaluation. While bf16 has a worse precision than fp16, it has a much much bigger dynamic range. Therefore, if in the past you were experiencing overflow issues while training the model, bf16 will prevent this from happening most of the time. Remember that in fp16 the biggest number you can have is `65535` and any number above that will overflow. A bf16 number can be as large as `3.39e+38` (!) which is about the same as fp32 - because both have 8-bits used for the numerical range.\n"),Vs=r("p"),by=i("You can enable BF16 in the \u{1F917} Trainer with:"),Cf=h(),d(Za.$$.fragment),Lf=h(),Ee=r("h3"),nt=r("a"),Tl=r("span"),d(Qa.$$.fragment),Ey=h(),zl=r("span"),$y=i("TF32"),Wf=i(`

The Ampere hardware uses a magical data type called tf32. It has the same numerical range as fp32 (8-bits), but instead of 23 bits precision it has only 10 bits (same as fp16) and uses only 19 bits in total.
`),Xs=r("p"),ky=i("It\u2019s magical in the sense that you can use the normal fp32 training and/or inference code and by enabling tf32 support you can get up to 3x throughput improvement. All you need to do is to add this to your code:"),Bf=h(),d(Ja.$$.fragment),Ff=h(),Zs=r("p"),Py=i("When this is done CUDA will automatically switch to using tf32 instead of fp32 where it\u2019s possible. This, of course, assumes that the used GPU is from the Ampere series."),Rf=h(),lt=r("p"),Ay=i("Like all cases with reduced precision this may or may not be satisfactory for your needs, so you have to experiment and see. According to "),Ka=r("a"),Ty=i("NVIDIA research"),zy=i(" the majority of machine learning training shouldn\u2019t be impacted and showed the same perplexity and convergence as the fp32 training."),Hf=h(),Qs=r("p"),xy=i("If you\u2019re already using fp16 or bf16 mixed precision it may help with the throughput as well."),Yf=h(),Js=r("p"),Gy=i("You can enable this mode in the \u{1F917} Trainer with:"),Vf=h(),d(er.$$.fragment),Xf=h(),Ks=r("p"),Uy=i("By default the PyTorch default is used."),Zf=h(),V=r("p"),Sy=i("Note: tf32 mode is internal to CUDA and can\u2019t be accessed directly via "),xl=r("code"),Dy=i("tensor.to(dtype=torch.tf32)"),jy=i(" as "),Gl=r("code"),Iy=i("torch.tf32"),Ny=i(" doesn\u2019t exist."),Qf=h(),pt=r("p"),My=i("Note: you need "),Ul=r("code"),Oy=i("torch>=1.7"),qy=i(" to enjoy this feature."),Jf=h(),X=r("p"),Cy=i(`You can also see a variety of benchmarks on tf32 vs other precisions:
`),tr=r("a"),Ly=i("RTX-3090"),Wy=i(` and
`),ar=r("a"),By=i("A100"),Fy=i("."),Kf=h(),ei=r("p"),Ry=i("We\u2019ve now seen how we can change the floating types to increase throughput, but we are not done, yet! There is another area where we can save GPU memory: the optimizer."),em=h(),$e=r("h2"),ht=r("a"),Sl=r("span"),d(rr.$$.fragment),Hy=h(),Dl=r("span"),Yy=i("Optimizer"),tm=h(),ti=r("p"),Vy=i("The most common optimizer used to train transformer model is Adam or AdamW (Adam with weight decay). Adam achieves good convergence by storing the rolling average of the previous gradients which, however, adds an additional memory footprint of the order of the number of model parameters. One remedy to this is to use an alternative optimizer such as Adafactor, which works well for some models but often it has instability issues."),am=h(),ft=r("p"),Xy=i("HF Trainer integrates a variety of optimisers that can be used out of box. To activate the desired optimizer simply pass the "),jl=r("code"),Zy=i("--optim"),Qy=i(" flag to the command line."),rm=h(),ai=r("p"),Jy=i("To see which optimizers are currently supported:"),om=h(),d(or.$$.fragment),sm=h(),Z=r("p"),Ky=i("For example, if you have "),sr=r("a"),e_=i("NVIDIA/apex"),t_=i(" installed "),Il=r("code"),a_=i("--optim adamw_apex_fused"),r_=i(" will give you the fastest training experience among all supported AdamW optimizers."),im=h(),mt=r("p"),o_=i("On the other hand "),ir=r("a"),s_=i("8bit BNB optimizer"),i_=i(" can save 3/4 of memory normally used by a typical AdamW optimizer if it is configured to quantize all optimizer states, but in some situations only some optimizer states are quintized and then more memory is used."),nm=h(),dt=r("p"),n_=i("Let\u2019s get a feel for the numbers and use for example use a 3B-parameter model, like "),Nl=r("code"),l_=i("t5-3b"),p_=i(". Note that since a Gigabyte correpsonds to a billion bytes we can simply multiply the parameters (in billions) with the number of necessary bytes per parameter to get Gigabytes of GPU memory usage:"),lm=h(),Q=r("ul"),nr=r("li"),h_=i("A standard AdamW uses 8 bytes for each parameter, here the optimizer will need ("),Ml=r("code"),f_=i("8*3"),m_=i(") 24GB of GPU memory."),d_=h(),lr=r("li"),c_=i("Adafactor uses slightly more than 4 bytes, so ("),Ol=r("code"),u_=i("4*3"),g_=i(") 12GB and then some extra."),w_=h(),pr=r("li"),v_=i("8bit BNB quantized optimizer will use only ("),ql=r("code"),y_=i("2*3"),__=i(") 6GB if all optimizer states are quantized."),pm=h(),ri=r("p"),b_=i("Let\u2019s have a look at Adafactor first."),hm=h(),ke=r("h3"),ct=r("a"),Cl=r("span"),d(hr.$$.fragment),E_=h(),Ll=r("span"),$_=i("Adafactor"),fm=h(),ut=r("p"),k_=i("Instead of keeping the rolling average for each element in the weight matrices Adafactor only stores aggregated information (row- and column-wise sums of the rolling averages) which reduces the footprint considerably. One downside of Adafactor is that in some instances convergence can be slower than Adam\u2019s so some experimentation is advised here. We can use Adafactor simply by setting "),Wl=r("code"),P_=i('optim="adafactor"'),A_=i(":"),mm=h(),d(fr.$$.fragment),dm=h(),d(mr.$$.fragment),cm=h(),oi=r("p"),T_=i("We can see that this saves a few more GB on the GPU. Let\u2019s see how it looks when we add it to the other methods we introduced earlier:"),um=h(),d(dr.$$.fragment),gm=h(),d(cr.$$.fragment),wm=h(),si=r("p"),z_=i("We went from 15 GB memory usage to 5 GB - a 3x improvement while maintaining the throughput! However, as mentioned before, the convergence of Adafactor can be worse than Adam. There is an alternative to Adafactor called 8-bit Adam that takes a slightly different approach."),vm=h(),Pe=r("h3"),gt=r("a"),Bl=r("span"),d(ur.$$.fragment),x_=h(),Fl=r("span"),G_=i("8-bit Adam"),ym=h(),ii=r("p"),U_=i("Instead of aggregating optimizer states like Adafactor, 8-bit Adam keeps the full state and quantizes it. Quantization means that it stores the state with lower precision and dequantizes it only for the optimization. This is similar to the idea behind FP16 training where using variables with lower precision saves memory."),_m=h(),z=r("p"),S_=i("In contrast to the previous approaches is this one not integrated into the "),ni=r("a"),D_=i("Trainer"),j_=i(" as a simple flag. We need to install the 8-bit optimizer and then pass it as a custom optimizer to the "),li=r("a"),I_=i("Trainer"),N_=i(". Follow the installation guide in the Github "),gr=r("a"),M_=i("repo"),O_=i(" to install the "),Rl=r("code"),q_=i("bitsandbytes"),C_=i(" library that implements the 8-bit Adam optimizer."),bm=h(),pi=r("p"),L_=i("Once installed, we just need to initialize the the optimizer. Although this looks like a considerable amount of work it actually just involves two steps: first we need to group the model\u2019s parameters into two groups where to one group we apply weight decay and to the other we don\u2019t. Usually, biases and layer norm parameters are not weight decayed. Then in a second step we just do some argument housekeeping to use the same parameters as the previously used AdamW optimizer."),Em=h(),d(wt.$$.fragment),$m=h(),d(wr.$$.fragment),km=h(),vt=r("p"),W_=i("We can now pass the custom optimizer as an argument to the "),Hl=r("code"),B_=i("Trainer"),F_=i(":"),Pm=h(),d(vr.$$.fragment),Am=h(),d(yr.$$.fragment),Tm=h(),hi=r("p"),R_=i("We can see that we get a similar memory improvement as with Adafactor while keeping the full rolling average of the gradients. Let\u2019s repeat the experiment with the full settings:"),zm=h(),d(_r.$$.fragment),xm=h(),d(br.$$.fragment),Gm=h(),fi=r("p"),H_=i("Again, we get about a 3x memory improvement and even slightly higher throughput as using Adafactor. So we have seen how we can optimize the memory footprint of large models. The following plot summarizes all our experiments:"),Um=h(),mi=r("p"),di=r("img"),Sm=h(),Ae=r("h3"),yt=r("a"),Yl=r("span"),d(Er.$$.fragment),Y_=h(),Vl=r("span"),Xl=r("code"),V_=i("_multi_tensor"),Dm=i(`

pytorch-nightly introduced \`torch.optim._multi_tensor\` which should significantly speed up the optimizers for situations with lots of small feature tensors. It should eventually become the default, but if you want to experiment with it sooner and don't mind using the bleed-edge, see: https://github.com/huggingface/transformers/issues/9965
`),Te=r("h2"),_t=r("a"),Zl=r("span"),d($r.$$.fragment),X_=h(),Ql=r("span"),Z_=i("Using \u{1F917} Accelerate"),jm=h(),J=r("p"),Q_=i("So far we have used the "),ci=r("a"),J_=i("Trainer"),K_=i(" to run the experiments but a more flexible alternative to that approach is to use \u{1F917} Accelerate. With \u{1F917} Accelerate you have full control over the training loop and can essentially write the loop in pure PyTorch with some minor modifications. In turn it allows you to easily scale across different infrastructures such as CPUs, GPUs, TPUs, or distributed multi-GPU setups without changing any code. Let\u2019s see what it takes to implement all of the above tweaks in \u{1F917} Accelerate. We can still use the "),ui=r("a"),eb=i("TrainingArguments"),tb=i(" to wrap the training settings:"),Im=h(),d(kr.$$.fragment),Nm=h(),gi=r("p"),ab=i("The full example training loop with \u{1F917} Accelerate is only a handful of lines of code long:"),Mm=h(),d(Pr.$$.fragment),Om=h(),P=r("p"),rb=i("First we wrap the dataset in a "),Ar=r("a"),Jl=r("code"),ob=i("DataLoader"),sb=i(". Then we can enable gradient checkpointing by calling the model\u2019s "),wi=r("a"),ib=i("gradient_checkpointing_enable()"),nb=i(" method. When we initialize the "),Tr=r("a"),Kl=r("code"),lb=i("Accelerator"),pb=i(" we can specify if we want to use mixed precision training and it will take care of it for us in the "),ep=r("code"),hb=i("prepare"),fb=i(" call. During the "),zr=r("a"),tp=r("code"),mb=i("prepare"),db=i(" call the dataloader will also be distributed across workers should we use multiple GPUs. We use the same 8-bit optimizer from the earlier experiments."),qm=h(),bt=r("p"),cb=i("Finally, we can write the main training loop. Note that the "),ap=r("code"),ub=i("backward"),gb=i(" call is handled by \u{1F917} Accelerate. We can also see how gradient accumulation works: we normalize the loss so we get the average at the end of accumulation and once we have enough steps we run the optimization. Now the question is: does this use the same amount of memory as the previous steps? Let\u2019s check:"),Cm=h(),d(xr.$$.fragment),Lm=h(),Et=r("p"),wb=i("Indeed it does. Implementing these optimization techniques with \u{1F917} Accelerate only takes a handful of lines of code and comes with the benefit of more flexiblity in the training loop. For a full documentation of all features have a look at the "),Gr=r("a"),vb=i("Accelerate documentation"),yb=i("."),Wm=h(),ze=r("h2"),$t=r("a"),rp=r("span"),d(Ur.$$.fragment),_b=h(),op=r("span"),bb=i("DataLoader"),Bm=h(),vi=r("p"),Eb=i("One of the important requirements to reach great training speed is the ability to feed the GPU at the maximum speed it can handle. By default everything happens in the main process and it might not be able to read the data from disk fast enough, and thus create a bottleneck, leading to GPU under-utilization."),Fm=h(),kt=r("ul"),yi=r("li"),sp=r("code"),$b=i("DataLoader(pin_memory=True, ...)"),kb=i(" which ensures that the data gets preloaded into the pinned memory on CPU and typically leads to much faster transfers from CPU to GPU memory."),Pb=h(),_i=r("li"),ip=r("code"),Ab=i("DataLoader(num_workers=4, ...)"),Tb=i(" - spawn several workers to pre-load data faster - during training watch the GPU utilization stats and if it\u2019s far from 100% experiment with raising the number of workers. Of course, the problem could be elsewhere so a very big number of workers won\u2019t necessarily lead to a better performance."),Rm=h(),xe=r("h2"),Pt=r("a"),np=r("span"),d(Sr.$$.fragment),zb=h(),lp=r("span"),xb=i("DeepSpeed ZeRO"),Hm=h(),At=r("p"),Gb=i("The in-depth details on how to use Deepspeed can be found "),bi=r("a"),Ub=i("here"),Sb=i("."),Ym=h(),Ei=r("p"),Db=i("First, a quick decision tree:"),Vm=h(),Tt=r("ol"),pp=r("li"),jb=i("Model fits onto a single GPU and you have enough space to fit a small batch size - you don\u2019t need to use Deepspeed as it\u2019ll only slow things down in this use case."),Ib=h(),hp=r("li"),Nb=i("Model doesn\u2019t fit onto a single GPU or you can\u2019t fit a small batch - use DeepSpeed ZeRO + CPU Offload and for much larger models NVMe Offload."),Xm=h(),zt=r("p"),Mb=i("Now if the decision tree suggested you use DeepSpeed first you need to "),$i=r("a"),Ob=i("install it"),qb=i(", then follow one of the following guides to create a configuration file and launch DeepSpeed."),Zm=h(),ki=r("p"),Cb=i("Activation:"),Qm=h(),j=r("ul"),fp=r("li"),Dr=r("p"),Lb=i("HF Trainer-based examples: see this "),Pi=r("a"),Wb=i("guide"),Bb=i("."),Fb=h(),jr=r("li"),mp=r("p"),Rb=i("Custom HF Trainer-based program: Same as above, but pass:"),Hb=h(),d(Ir.$$.fragment),Yb=h(),dp=r("li"),Nr=r("p"),Vb=i("Deployment in Notebooks: see this "),Ai=r("a"),Xb=i("guide"),Zb=i("."),Qb=h(),cp=r("li"),Ge=r("p"),Jb=i("Custom training loop: This is somewhat complex but you can study how this is implemented in "),Mr=r("a"),Kb=i("HF Trainer"),e1=i(" - simply search for "),up=r("code"),t1=i("deepspeed"),a1=i(" in the code."),Jm=h(),Ue=r("h2"),xt=r("a"),gp=r("span"),d(Or.$$.fragment),r1=h(),wp=r("span"),o1=i("Choice of GPU"),Km=i(`

Sometimes, even when applying all the above tweaks the throughput on a given GPU might still not be good enough. One easy solution is to change the type of GPU. For example switching from let's say a K80 (which you typically get on Google Colab) to a fancier GPU such as the V100 or A100. Although they are more expensive they are usually more cost effective than cheaper GPUs due to their larger memory and faster architecture.
`),Ti=r("p"),s1=i("Now, let\u2019s take a step back and discuss what we should optimize for when scaling the training of large models."),ed=h(),Se=r("h2"),Gt=r("a"),vp=r("span"),d(qr.$$.fragment),i1=h(),yp=r("span"),n1=i("How to scale"),td=h(),zi=r("p"),l1=i("When we train models there are a two aspects we want to optimize at the same time:"),ad=h(),Ut=r("ul"),_p=r("li"),p1=i("Data throughput/training time"),h1=h(),bp=r("li"),f1=i("Model performance"),rd=h(),xi=r("p"),m1=i("We have seen that each method changes the memory usage and throughput. In general we want to maximize the throughput (samples/second) to minimize the training cost. This is generally achieved by utilizing the GPU as much as possible and thus filling GPU memory to its limit. For example, as mentioned earlier, we only employ gradient accumulation when we want to use a batch size beyond the size of the GPU memory. If the desired batch size fits into memory then there is no reason to apply gradient accumulation which will only slow down training."),od=h(),Gi=r("p"),d1=i("The second objective is model performance. Just because we can does not mean we should use a large batch size. As part of hyperparameter tuning you should determine which batch size yields the best result and then optimize the throughput accordingly."),sd=h(),De=r("h2"),St=r("a"),Ep=r("span"),d(Cr.$$.fragment),c1=h(),$p=r("span"),u1=i("Efficient Software Prebuilds"),id=h(),Dt=r("p"),g1=i("PyTorch\u2019s "),Lr=r("a"),w1=i("pip and conda builds"),v1=i(" come prebuit with the cuda toolkit which is enough to run PyTorch, but it is insufficient if you need to build cuda extensions."),nd=h(),jt=r("p"),y1=i("At times it may take an additional effort to pre-build some components, e.g., if you\u2019re using libraries like "),kp=r("code"),_1=i("apex"),b1=i(" that don\u2019t come pre-compiled. In other situations figuring out how to install the right cuda toolkit system-wide can be complicated. To address these users\u2019 needs PyTorch and NVIDIA release a new version of NGC docker container which already comes with everything prebuilt and you just need to install your programs on it and it will run out of the box."),ld=h(),Ui=r("p"),E1=i("This approach is also useful if you want to tweak the pytorch source and/or make a new customized build."),pd=h(),K=r("p"),$1=i("To find the docker image version you want start "),Wr=r("a"),k1=i("here"),P1=i(", choose one of the latest monthly releases. Go into the release\u2019s notes for the desired release, check that the environment\u2019s components are matching your needs (including NVIDIA Driver requirements!) and then at the very top of that document go to the corresponding NGC page. If for some reason you get lost, here is "),Br=r("a"),A1=i("the index of all PyTorch NGC images"),T1=i("."),hd=h(),Si=r("p"),z1=i("Next follow the instructions to download and deploy the docker image."),fd=h(),je=r("h2"),It=r("a"),Pp=r("span"),d(Fr.$$.fragment),x1=h(),Ap=r("span"),G1=i("Sparsity"),md=h(),Ie=r("h3"),Nt=r("a"),Tp=r("span"),d(Rr.$$.fragment),U1=h(),zp=r("span"),S1=i("Mixture of Experts"),dd=h(),Di=r("p"),D1=i(`Quite a few of the recent papers reported a 4-5x training speedup and a faster inference by integrating
Mixture of Experts (MoE) into the Transformer models.`),cd=h(),ji=r("p"),j1=i("Since it has been discovered that more parameters lead to better performance, this technique allows to increase the number of parameters by an order of magnitude without increasing training costs."),ud=h(),Ii=r("p"),I1=i("In this approach every other FFN layer is replaced with a MoE Layer which consists of many experts, with a gated function that trains each expert in a balanced way depending on the input token\u2019s position in a sequence."),gd=h(),Ni=r("p"),Mi=r("img"),wd=h(),Mt=r("p"),N1=i("(source: "),Hr=r("a"),M1=i("GLAM"),O1=i(")"),vd=h(),Oi=r("p"),q1=i("You can find exhaustive details and comparison tables in the papers listed at the end of this section."),yd=h(),qi=r("p"),C1=i("The main drawback of this approach is that it requires staggering amounts of GPU memory - almost an order of magnitude larger than its dense equivalent. Various distillation and approaches are proposed to how to overcome the much higher memory requirements."),_d=h(),Ci=r("p"),L1=i("There is direct trade-off though, you can use just a few experts with a 2-3x smaller base model instead of dozens or hundreds experts leading to a 5x smaller model and thus increase the training speed moderately while increasing the memory requirements moderately as well."),bd=h(),Li=r("p"),W1=i("Most related papers and implementations are built around Tensorflow/TPUs:"),Ed=h(),ee=r("ul"),xp=r("li"),Yr=r("a"),B1=i("GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding"),F1=h(),Gp=r("li"),Vr=r("a"),R1=i("Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity"),H1=h(),Up=r("li"),Xr=r("a"),Y1=i("GLaM: Generalist Language Model (GLaM)"),$d=h(),E=r("p"),V1=i("And for Pytorch DeepSpeed has built one as well: "),Zr=r("a"),X1=i("DeepSpeed-MoE: Advancing Mixture-of-Experts Inference and Training to Power Next-Generation AI Scale"),Z1=i(", "),Qr=r("a"),Q1=i("Mixture of Experts"),J1=i(" - blog posts:  "),Jr=r("a"),K1=i("1"),e2=i(", "),Kr=r("a"),t2=i("2"),a2=i(" and specific deployment with large transformer-based natural language generation models: "),eo=r("a"),r2=i("blog post"),o2=i(", "),Wi=r("a"),s2=i("Megatron-Deepspeed branch"),i2=i("."),kd=h(),Ne=r("h2"),Ot=r("a"),Sp=r("span"),d(to.$$.fragment),n2=h(),Dp=r("span"),l2=i("Scaling beyond a single GPU"),Pd=h(),Bi=r("p"),p2=i("For some applications, such as pretraining large language models, applying all the approaches above might still not be fast enough. In this case you want to scale your experiment to several GPUs."),Ad=h(),qt=r("p"),h2=i("Another use case for training on many GPUs is if the model does not fit on a single GPU with all the mentioned tricks. There are still more methods we can apply although life starts to get a bit more complicated. This usually involves some form of pipeline or tensor parallelism where the model itself is distributed across several GPUs. One can also make use of DeepSpeed which implements some of these parallelism strategies along with some more optimization to reduce the memory footprint such as partitioning the optimizer states. You can read more about this in the "),Fi=r("a"),f2=i("\u201CMulti-GPU training\u201D section"),m2=i("."),Td=h(),Me=r("h2"),Ct=r("a"),jp=r("span"),d(ao.$$.fragment),d2=h(),Ip=r("span"),c2=i("Using PyTorch native attention"),zd=h(),I=r("p"),u2=i("PyTorch 2.0 released the native "),ro=r("a"),Np=r("code"),g2=i("torch.nn.functional.scaled_dot_product_attention"),w2=i(" (SDPA), that allows to use fused GPU kernels as "),oo=r("a"),v2=i("memory-efficient attention"),y2=i(" and "),so=r("a"),_2=i("flash attention"),b2=i("."),xd=h(),Lt=r("p"),E2=i("After installing the "),io=r("a"),Mp=r("code"),$2=i("optimum"),k2=i(" package, the relevant internal modules can be replaced to use PyTorch\u2019s native attention with:"),Gd=h(),d(no.$$.fragment),Ud=h(),Ri=r("p"),P2=i("Training can then be done as usual."),Sd=h(),Oe=r("h2"),Wt=r("a"),Op=r("span"),d(lo.$$.fragment),A2=h(),qp=r("span"),T2=i("Using torch.compile"),Dd=h(),Bt=r("p"),z2=i("PyTorch 2.0 introduces a new compile function, you can learn more about it "),po=r("a"),x2=i("in their documentation"),G2=i(". It uses Python\u2019s frame evaluation API to automatically create a graph from existing PyTorch programs. After capturing the graph, different backends can be deployed to lower the graph to an optimized engine. You can choose one option below for performance boost."),jd=h(),q=r("p"),Cp=r("code"),U2=i("torch.compile"),S2=i(" has a growing list of backends, which can be found in "),ho=r("a"),D2=i("backends.py"),j2=i(`
or `),Lp=r("code"),I2=i("torchdynamo.list_backends()"),N2=i(" each of which with its optional dependencies."),Id=h(),Hi=r("p"),M2=i("Some of the most commonly used backends are"),Nd=h(),fo=r("p"),Wp=r("strong"),O2=i("Debugging backends"),q2=i(":"),Md=h(),Ft=r("ul"),Yi=r("li"),Bp=r("code"),C2=i('dynamo.optimize("eager")'),L2=i(" - Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues."),W2=h(),Vi=r("li"),Fp=r("code"),B2=i('dynamo.optimize("aot_eager")'),F2=i(" - Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd\u2019s extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups."),Od=h(),mo=r("p"),Rp=r("strong"),R2=i("Training & inference backends"),H2=i(":"),qd=h(),N=r("ul"),co=r("li"),Hp=r("code"),Y2=i('dynamo.optimize("inductor")'),V2=i(" - Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels  "),uo=r("a"),X2=i("Read more"),Z2=h(),go=r("li"),Yp=r("code"),Q2=i('dynamo.optimize("nvfuser")'),J2=i(" -  nvFuser with TorchScript. "),wo=r("a"),K2=i("Read more"),e3=h(),vo=r("li"),Vp=r("code"),t3=i('dynamo.optimize("aot_nvfuser")'),a3=i(" -  nvFuser with AotAutograd. "),yo=r("a"),r3=i("Read more"),o3=h(),_o=r("li"),Xp=r("code"),s3=i('dynamo.optimize("aot_cudagraphs")'),i3=i(" - cudagraphs with AotAutograd. "),bo=r("a"),n3=i("Read more"),Cd=h(),Eo=r("p"),Zp=r("strong"),l3=i("Inference-only backend"),p3=i("s:"),Ld=h(),M=r("ul"),$o=r("li"),Qp=r("code"),h3=i('dynamo.optimize("ofi")'),f3=i(" -  Uses Torchscript optimize_for_inference.  "),ko=r("a"),m3=i("Read more"),d3=h(),Po=r("li"),Jp=r("code"),c3=i('dynamo.optimize("fx2trt")'),u3=i(" -  Uses Nvidia TensorRT for inference optimizations.  "),Ao=r("a"),g3=i("Read more"),w3=h(),To=r("li"),Kp=r("code"),v3=i('dynamo.optimize("onnxrt")'),y3=i(" -  Uses ONNXRT for inference on CPU/GPU.  "),zo=r("a"),_3=i("Read more"),b3=h(),xo=r("li"),eh=r("code"),E3=i('dynamo.optimize("ipex")'),$3=i(" -  Uses IPEX for inference on CPU.  "),Go=r("a"),k3=i("Read more"),this.h()},l(e){const l=J6('[data-svelte="svelte-1phssyn"]',document.head);b=o(l,"META",{name:!0,content:!0}),l.forEach(t),A=f(e),$=o(e,"H1",{class:!0});var Uo=s($);U=o(Uo,"A",{id:!0,class:!0,href:!0});var th=s(U);_n=o(th,"SPAN",{});var q3=s(_n);c(Qt.$$.fragment,q3),q3.forEach(t),th.forEach(t),uu=f(Uo),bn=o(Uo,"SPAN",{});var C3=s(bn);gu=n(C3,"Efficient Training on a Single GPU"),C3.forEach(t),Uo.forEach(t),oh=f(e),qe=o(e,"P",{});var Bd=s(qe);wu=n(Bd,"This guide focuses on training large models efficiently on a single GPU. These approaches are still valid if you have access to a machine with multiple GPUs but you will also have access to additional methods outlined in the "),jo=o(Bd,"A",{href:!0});var L3=s(jo);vu=n(L3,"multi-GPU section"),L3.forEach(t),yu=n(Bd,"."),Bd.forEach(t),sh=f(e),C=o(e,"P",{});var Xi=s(C);_u=n(Xi,"In this section we have a look at a few tricks to reduce the memory footprint and speed up training for large models and how they are integrated in the "),Io=o(Xi,"A",{href:!0});var W3=s(Io);bu=n(W3,"Trainer"),W3.forEach(t),Eu=n(Xi," and "),Jt=o(Xi,"A",{href:!0,rel:!0});var B3=s(Jt);$u=n(B3,"\u{1F917} Accelerate"),B3.forEach(t),ku=n(Xi,". Each method can improve speed or memory usage which is summarized in the table below:"),Xi.forEach(t),ih=f(e),Ce=o(e,"TABLE",{});var Fd=s(Ce);En=o(Fd,"THEAD",{});var F3=s(En);re=o(F3,"TR",{});var Zi=s(re);No=o(Zi,"TH",{align:!0});var R3=s(No);Pu=n(R3,"Method"),R3.forEach(t),Au=f(Zi),Mo=o(Zi,"TH",{align:!0});var H3=s(Mo);Tu=n(H3,"Speed"),H3.forEach(t),zu=f(Zi),Oo=o(Zi,"TH",{align:!0});var Y3=s(Oo);xu=n(Y3,"Memory"),Y3.forEach(t),Zi.forEach(t),F3.forEach(t),Gu=f(Fd),k=o(Fd,"TBODY",{});var x=s(k);oe=o(x,"TR",{});var Qi=s(oe);qo=o(Qi,"TD",{align:!0});var V3=s(qo);Uu=n(V3,"Gradient accumulation"),V3.forEach(t),Su=f(Qi),Co=o(Qi,"TD",{align:!0});var X3=s(Co);Du=n(X3,"No"),X3.forEach(t),ju=f(Qi),Lo=o(Qi,"TD",{align:!0});var Z3=s(Lo);Iu=n(Z3,"Yes"),Z3.forEach(t),Qi.forEach(t),Nu=f(x),se=o(x,"TR",{});var Ji=s(se);Wo=o(Ji,"TD",{align:!0});var Q3=s(Wo);Mu=n(Q3,"Gradient checkpointing"),Q3.forEach(t),Ou=f(Ji),Bo=o(Ji,"TD",{align:!0});var J3=s(Bo);qu=n(J3,"No"),J3.forEach(t),Cu=f(Ji),Fo=o(Ji,"TD",{align:!0});var K3=s(Fo);Lu=n(K3,"Yes"),K3.forEach(t),Ji.forEach(t),Wu=f(x),ie=o(x,"TR",{});var Ki=s(ie);Ro=o(Ki,"TD",{align:!0});var eE=s(Ro);Bu=n(eE,"Mixed precision training"),eE.forEach(t),Fu=f(Ki),Ho=o(Ki,"TD",{align:!0});var tE=s(Ho);Ru=n(tE,"Yes"),tE.forEach(t),Hu=f(Ki),Yo=o(Ki,"TD",{align:!0});var aE=s(Yo);Yu=n(aE,"(No)"),aE.forEach(t),Ki.forEach(t),Vu=f(x),ne=o(x,"TR",{});var en=s(ne);Vo=o(en,"TD",{align:!0});var rE=s(Vo);Xu=n(rE,"Batch size"),rE.forEach(t),Zu=f(en),Xo=o(en,"TD",{align:!0});var oE=s(Xo);Qu=n(oE,"Yes"),oE.forEach(t),Ju=f(en),Zo=o(en,"TD",{align:!0});var sE=s(Zo);Ku=n(sE,"Yes"),sE.forEach(t),en.forEach(t),eg=f(x),le=o(x,"TR",{});var tn=s(le);Qo=o(tn,"TD",{align:!0});var iE=s(Qo);tg=n(iE,"Optimizer choice"),iE.forEach(t),ag=f(tn),Jo=o(tn,"TD",{align:!0});var nE=s(Jo);rg=n(nE,"Yes"),nE.forEach(t),og=f(tn),Ko=o(tn,"TD",{align:!0});var lE=s(Ko);sg=n(lE,"Yes"),lE.forEach(t),tn.forEach(t),ig=f(x),pe=o(x,"TR",{});var an=s(pe);es=o(an,"TD",{align:!0});var pE=s(es);ng=n(pE,"DataLoader"),pE.forEach(t),lg=f(an),ts=o(an,"TD",{align:!0});var hE=s(ts);pg=n(hE,"Yes"),hE.forEach(t),hg=f(an),as=o(an,"TD",{align:!0});var fE=s(as);fg=n(fE,"No"),fE.forEach(t),an.forEach(t),mg=f(x),he=o(x,"TR",{});var rn=s(he);rs=o(rn,"TD",{align:!0});var mE=s(rs);dg=n(mE,"DeepSpeed Zero"),mE.forEach(t),cg=f(rn),os=o(rn,"TD",{align:!0});var dE=s(os);ug=n(dE,"No"),dE.forEach(t),gg=f(rn),ss=o(rn,"TD",{align:!0});var cE=s(ss);wg=n(cE,"Yes"),cE.forEach(t),rn.forEach(t),x.forEach(t),Fd.forEach(t),nh=f(e),is=o(e,"P",{});var uE=s(is);vg=n(uE,"A bracket means that it might not be strictly the case but is usually either not a main concern or negligible. Before we start make sure you have installed the following libraries:"),uE.forEach(t),lh=f(e),c(Kt.$$.fragment,e),ph=f(e),L=o(e,"P",{});var on=s(L);yg=n(on,"The "),$n=o(on,"CODE",{});var gE=s($n);_g=n(gE,"nvidia-ml-py3"),gE.forEach(t),bg=n(on," library allows us to monitor the memory usage of the models from within Python. You might be familiar with the "),kn=o(on,"CODE",{});var wE=s(kn);Eg=n(wE,"nvidia-smi"),wE.forEach(t),$g=n(on," command in the terminal - this library allows to access the same information in Python directly."),on.forEach(t),hh=f(e),Le=o(e,"P",{});var Rd=s(Le);kg=n(Rd,"Then we create some dummy data. We create random token IDs between 100 and 30000 and binary labels for a classifier. In total we get 512 sequences each with length 512 and store them in a "),ea=o(Rd,"A",{href:!0,rel:!0});var vE=s(ea);Pg=n(vE,"Dataset"),vE.forEach(t),Ag=n(Rd," with PyTorch format."),Rd.forEach(t),fh=f(e),c(ta.$$.fragment,e),mh=f(e),We=o(e,"P",{});var Hd=s(We);Tg=n(Hd,"We want to print some summary statistics for the GPU utilization and the training run with the "),ns=o(Hd,"A",{href:!0});var yE=s(ns);zg=n(yE,"Trainer"),yE.forEach(t),xg=n(Hd,". We setup a two helper functions to do just that:"),Hd.forEach(t),dh=f(e),c(aa.$$.fragment,e),ch=f(e),ls=o(e,"P",{});var _E=s(ls);Gg=n(_E,"Let\u2019s verify that we start with a free GPU memory:"),_E.forEach(t),uh=f(e),c(ra.$$.fragment,e),gh=f(e),ps=o(e,"P",{});var bE=s(ps);Ug=n(bE,"That looks good: the GPU memory is not occupied as we would expect before we load any models. If that\u2019s not the case on your machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by the user. When a model is loaded to the GPU also the kernels are loaded which can take up 1-2GB of memory. To see how much it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well."),bE.forEach(t),wh=f(e),c(oa.$$.fragment,e),vh=f(e),hs=o(e,"P",{});var EE=s(hs);Sg=n(EE,"We see that the kernels alone take up 1.3GB of GPU memory. Now let\u2019s see how much space the model uses."),EE.forEach(t),yh=f(e),fe=o(e,"H2",{class:!0});var Yd=s(fe);Be=o(Yd,"A",{id:!0,class:!0,href:!0});var $E=s(Be);Pn=o($E,"SPAN",{});var kE=s(Pn);c(sa.$$.fragment,kE),kE.forEach(t),$E.forEach(t),Dg=f(Yd),An=o(Yd,"SPAN",{});var PE=s(An);jg=n(PE,"Load Model"),PE.forEach(t),Yd.forEach(t),_h=f(e),Fe=o(e,"P",{});var Vd=s(Fe);Ig=n(Vd,"First, we load the "),Tn=o(Vd,"CODE",{});var AE=s(Tn);Ng=n(AE,"bert-large-uncased"),AE.forEach(t),Mg=n(Vd," model. We load the model weights directly to the GPU so that we can check how much space just weights use."),Vd.forEach(t),bh=f(e),c(ia.$$.fragment,e),Eh=f(e),Re=o(e,"P",{});var Xd=s(Re);Og=n(Xd,"We can see that the model weights alone take up 1.3 GB of the GPU memory. The exact number depends on the specific GPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an optimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result as with "),zn=o(Xd,"CODE",{});var TE=s(zn);qg=n(TE,"nvidia-smi"),TE.forEach(t),Cg=n(Xd," CLI:"),Xd.forEach(t),$h=f(e),c(na.$$.fragment,e),kh=f(e),c(la.$$.fragment,e),Ph=f(e),fs=o(e,"P",{});var zE=s(fs);Lg=n(zE,"We get the same number as before and you can also see that we are using a V100 GPU with 16GB of memory. So now we can start training the model and see how the GPU memory consumption changes. First, we set up a few standard training arguments that we will use across all our experiments:"),zE.forEach(t),Ah=f(e),c(pa.$$.fragment,e),Th=f(e),c(He.$$.fragment,e),zh=f(e),me=o(e,"H2",{class:!0});var Zd=s(me);Ye=o(Zd,"A",{id:!0,class:!0,href:!0});var xE=s(Ye);xn=o(xE,"SPAN",{});var GE=s(xn);c(ha.$$.fragment,GE),GE.forEach(t),xE.forEach(t),Wg=f(Zd),Gn=o(Zd,"SPAN",{});var UE=s(Gn);Bg=n(UE,"Vanilla Training"),UE.forEach(t),Zd.forEach(t),xh=f(e),Ve=o(e,"P",{});var Qd=s(Ve);Fg=n(Qd,"As a first experiment we will use the "),ms=o(Qd,"A",{href:!0});var SE=s(ms);Rg=n(SE,"Trainer"),SE.forEach(t),Hg=n(Qd," and train the model without any further modifications and a batch size of 4:"),Qd.forEach(t),Gh=f(e),c(fa.$$.fragment,e),Uh=f(e),c(ma.$$.fragment,e),Sh=f(e),ds=o(e,"P",{});var DE=s(ds);Yg=n(DE,"We see that already a relatively small batch size almost fills up our GPU\u2019s entire memory. However, a larger batch size can often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our model\u2019s needs and not to the GPU limitations. What\u2019s interesting is that we use much more memory than the size of the model. To understand a bit better why this is the case let\u2019s have look at a model\u2019s operations and memory needs."),DE.forEach(t),Dh=f(e),de=o(e,"H2",{class:!0});var Jd=s(de);Xe=o(Jd,"A",{id:!0,class:!0,href:!0});var jE=s(Xe);Un=o(jE,"SPAN",{});var IE=s(Un);c(da.$$.fragment,IE),IE.forEach(t),jE.forEach(t),Vg=f(Jd),Sn=o(Jd,"SPAN",{});var NE=s(Sn);Xg=n(NE,"Anatomy of Model's Operations"),NE.forEach(t),Jd.forEach(t),jh=f(e),cs=o(e,"P",{});var ME=s(cs);Zg=n(ME,"Transformers architecture includes 3 main groups of operations grouped below by compute-intensity."),ME.forEach(t),Ih=f(e),W=o(e,"OL",{});var sn=s(W);ca=o(sn,"LI",{});var Kd=s(ca);Dn=o(Kd,"P",{});var OE=s(Dn);jn=o(OE,"STRONG",{});var qE=s(jn);Qg=n(qE,"Tensor Contractions"),qE.forEach(t),OE.forEach(t),Jg=f(Kd),ua=o(Kd,"P",{});var ec=s(ua);Kg=n(ec,"Linear layers and components of Multi-Head Attention all do batched "),In=o(ec,"STRONG",{});var CE=s(In);ew=n(CE,"matrix-matrix multiplications"),CE.forEach(t),tw=n(ec,". These operations are the most compute-intensive part of training a transformer."),ec.forEach(t),Kd.forEach(t),aw=f(sn),ga=o(sn,"LI",{});var tc=s(ga);Nn=o(tc,"P",{});var LE=s(Nn);Mn=o(LE,"STRONG",{});var WE=s(Mn);rw=n(WE,"Statistical Normalizations"),WE.forEach(t),LE.forEach(t),ow=f(tc),wa=o(tc,"P",{});var ac=s(wa);sw=n(ac,"Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more "),On=o(ac,"STRONG",{});var BE=s(On);iw=n(BE,"reduction operations"),BE.forEach(t),nw=n(ac,", the result of which is then applied via a map."),ac.forEach(t),tc.forEach(t),lw=f(sn),va=o(sn,"LI",{});var rc=s(va);qn=o(rc,"P",{});var FE=s(qn);Cn=o(FE,"STRONG",{});var RE=s(Cn);pw=n(RE,"Element-wise Operators"),RE.forEach(t),FE.forEach(t),hw=f(rc),ya=o(rc,"P",{});var oc=s(ya);fw=n(oc,"These are the remaining operators: "),Ln=o(oc,"STRONG",{});var HE=s(Ln);mw=n(HE,"biases, dropout, activations, and residual connections"),HE.forEach(t),dw=n(oc,". These are the least compute-intensive operations."),oc.forEach(t),rc.forEach(t),sn.forEach(t),Nh=f(e),us=o(e,"P",{});var YE=s(us);cw=n(YE,"This knowledge can be helpful to know when analyzing performance bottlenecks."),YE.forEach(t),Mh=f(e),_a=o(e,"P",{});var P3=s(_a);uw=n(P3,"This summary is derived from "),ba=o(P3,"A",{href:!0,rel:!0});var VE=s(ba);gw=n(VE,"Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020"),VE.forEach(t),P3.forEach(t),Oh=f(e),ce=o(e,"H2",{class:!0});var sc=s(ce);Ze=o(sc,"A",{id:!0,class:!0,href:!0});var XE=s(Ze);Wn=o(XE,"SPAN",{});var ZE=s(Wn);c(Ea.$$.fragment,ZE),ZE.forEach(t),XE.forEach(t),ww=f(sc),Bn=o(sc,"SPAN",{});var QE=s(Bn);vw=n(QE,"Anatomy of Model's Memory"),QE.forEach(t),sc.forEach(t),qh=n(e,`

We've seen that training the model uses much more memory than just putting the model on the GPU. This is because there are many components during training that use GPU memory. The components on GPU memory are the following:
1. model weights
2. optimizer states
3. gradients
4. forward activations saved for gradient computation
5. temporary buffers
6. functionality-specific memory
`),gs=o(e,"P",{});var JE=s(gs);yw=n(JE,"A typical model trained in mixed precision with AdamW requires 18 bytes per model parameter plus activation memory. For inference there are no optimizer states and gradients, so we can subtract those. And thus we end up with 6 bytes per model parameter for mixed precision inference, plus activation memory."),JE.forEach(t),Ch=f(e),ws=o(e,"P",{});var KE=s(ws);_w=n(KE,"Let\u2019s look at the details."),KE.forEach(t),Lh=f(e),vs=o(e,"P",{});var e0=s(vs);Fn=o(e0,"STRONG",{});var t0=s(Fn);bw=n(t0,"Model Weights:"),t0.forEach(t),e0.forEach(t),Wh=f(e),Qe=o(e,"UL",{});var ic=s(Qe);Rn=o(ic,"LI",{});var a0=s(Rn);Ew=n(a0,"4 bytes * number of parameters for fp32 training"),a0.forEach(t),$w=f(ic),Hn=o(ic,"LI",{});var r0=s(Hn);kw=n(r0,"6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)"),r0.forEach(t),ic.forEach(t),Bh=f(e),ys=o(e,"P",{});var o0=s(ys);Yn=o(o0,"STRONG",{});var s0=s(Yn);Pw=n(s0,"Optimizer States:"),s0.forEach(t),o0.forEach(t),Fh=f(e),B=o(e,"UL",{});var nn=s(B);Vn=o(nn,"LI",{});var i0=s(Vn);Aw=n(i0,"8 bytes * number of parameters for normal AdamW (maintains 2 states)"),i0.forEach(t),Tw=f(nn),_s=o(nn,"LI",{});var A3=s(_s);zw=n(A3,"2 bytes * number of parameters for 8-bit AdamW optimizers like "),$a=o(A3,"A",{href:!0,rel:!0});var n0=s($a);xw=n(n0,"bitsandbytes"),n0.forEach(t),A3.forEach(t),Gw=f(nn),Xn=o(nn,"LI",{});var l0=s(Xn);Uw=n(l0,"4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)"),l0.forEach(t),nn.forEach(t),Rh=f(e),bs=o(e,"P",{});var p0=s(bs);Zn=o(p0,"STRONG",{});var h0=s(Zn);Sw=n(h0,"Gradients"),h0.forEach(t),p0.forEach(t),Hh=f(e),Es=o(e,"UL",{});var f0=s(Es);Qn=o(f0,"LI",{});var m0=s(Qn);Dw=n(m0,"4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)"),m0.forEach(t),f0.forEach(t),Yh=f(e),$s=o(e,"P",{});var d0=s($s);Jn=o(d0,"STRONG",{});var c0=s(Jn);jw=n(c0,"Forward Activations"),c0.forEach(t),d0.forEach(t),Vh=f(e),ks=o(e,"UL",{});var u0=s(ks);Kn=o(u0,"LI",{});var g0=s(Kn);Iw=n(g0,"size depends on many factors, the key ones being sequence length, hidden size and batch size."),g0.forEach(t),u0.forEach(t),Xh=f(e),Ps=o(e,"P",{});var w0=s(Ps);Nw=n(w0,"There are the input and output that are being passed and returned by the forward and the backward functions and the forward activations saved for gradient computation."),w0.forEach(t),Zh=f(e),As=o(e,"P",{});var v0=s(As);el=o(v0,"STRONG",{});var y0=s(el);Mw=n(y0,"Temporary Memory"),y0.forEach(t),v0.forEach(t),Qh=f(e),Ts=o(e,"P",{});var _0=s(Ts);Ow=n(_0,"Additionally there are all kinds of temporary variables which get released once the calculation is done, but in the moment these could require additional memory and could push to OOM. Therefore when coding it\u2019s crucial to think strategically about such temporary variables and sometimes to explicitly free those as soon as they are no longer needed."),_0.forEach(t),Jh=f(e),zs=o(e,"P",{});var b0=s(zs);tl=o(b0,"STRONG",{});var E0=s(tl);qw=n(E0,"Functionality-specific memory"),E0.forEach(t),b0.forEach(t),Kh=f(e),xs=o(e,"P",{});var $0=s(xs);Cw=n($0,"Then your software could have special memory needs. For example, when generating text using beam search, the software needs to maintain multiple copies of inputs and outputs."),$0.forEach(t),ef=f(e),Gs=o(e,"P",{});var k0=s(Gs);Je=o(k0,"STRONG",{});var ah=s(Je);al=o(ah,"CODE",{});var P0=s(al);Lw=n(P0,"forward"),P0.forEach(t),Ww=n(ah," vs "),rl=o(ah,"CODE",{});var A0=s(rl);Bw=n(A0,"backward"),A0.forEach(t),Fw=n(ah," Execution Speed"),ah.forEach(t),k0.forEach(t),tf=f(e),Us=o(e,"P",{});var T0=s(Us);Rw=n(T0,"For convolutions and linear layers there are 2x flops in the backward compared to the forward, which generally translates into ~2x slower (sometimes more, because sizes in the backward tend to be more awkward). Activations are usually bandwidth-limited, and it\u2019s typical for an activation to have to read more data in the backward than in the forward (e.g. activation forward reads once, writes once, activation backward reads twice, gradOutput and output of the forward, and writes once, gradInput)."),T0.forEach(t),af=f(e),Ss=o(e,"P",{});var z0=s(Ss);Hw=n(z0,"So there are potentially a few places where we could save GPU memory or speed up operations. Let\u2019s start with a simple optimization: choosing the right batch size."),z0.forEach(t),rf=f(e),ue=o(e,"H2",{class:!0});var nc=s(ue);Ke=o(nc,"A",{id:!0,class:!0,href:!0});var x0=s(Ke);ol=o(x0,"SPAN",{});var G0=s(ol);c(ka.$$.fragment,G0),G0.forEach(t),x0.forEach(t),Yw=f(nc),sl=o(nc,"SPAN",{});var U0=s(sl);Vw=n(U0,"Batch sizes"),U0.forEach(t),nc.forEach(t),of=f(e),Ds=o(e,"P",{});var S0=s(Ds);Xw=n(S0,"One gets the most efficient performance when batch sizes and input/output neuron counts are divisible by a certain number, which typically starts at 8, but can be much higher as well. That number varies a lot depending on the specific hardware being used and the dtype of the model."),S0.forEach(t),sf=f(e),F=o(e,"P",{});var ln=s(F);Zw=n(ln,"For example for fully connected layers (which correspond to GEMMs), NVIDIA provides recommendations for "),Pa=o(ln,"A",{href:!0,rel:!0});var D0=s(Pa);Qw=n(D0,"input/output neuron counts"),D0.forEach(t),Jw=n(ln," and "),Aa=o(ln,"A",{href:!0,rel:!0});var j0=s(Aa);Kw=n(j0,"batch size"),j0.forEach(t),ev=n(ln,"."),ln.forEach(t),nf=f(e),Ta=o(e,"P",{});var T3=s(Ta);za=o(T3,"A",{href:!0,rel:!0});var I0=s(za);tv=n(I0,"Tensor Core Requirements"),I0.forEach(t),av=n(T3," define the multiplier based on the dtype and the hardware. For example, for fp16 a multiple of 8 is recommended, but on A100 it\u2019s 64!"),T3.forEach(t),lf=f(e),et=o(e,"P",{});var lc=s(et);rv=n(lc,"For parameters that are small, there is also "),xa=o(lc,"A",{href:!0,rel:!0});var N0=s(xa);ov=n(N0,"Dimension Quantization Effects"),N0.forEach(t),sv=n(lc," to consider, this is where tiling happens and the right multiplier can have a significant speedup."),lc.forEach(t),pf=f(e),ge=o(e,"H2",{class:!0});var pc=s(ge);tt=o(pc,"A",{id:!0,class:!0,href:!0});var M0=s(tt);il=o(M0,"SPAN",{});var O0=s(il);c(Ga.$$.fragment,O0),O0.forEach(t),M0.forEach(t),iv=f(pc),nl=o(pc,"SPAN",{});var q0=s(nl);nv=n(q0,"Gradient Accumulation"),q0.forEach(t),pc.forEach(t),hf=f(e),js=o(e,"P",{});var C0=s(js);lv=n(C0,"The idea behind gradient accumulation is to instead of calculating the gradients for the whole batch at once to do it in smaller steps. The way we do that is to calculate the gradients iteratively in smaller batches by doing a forward and backward pass through the model and accumulating the gradients in the process. When enough gradients are accumulated we run the model\u2019s optimization step. This way we can easily increase the overall batch size to numbers that would never fit into the GPU\u2019s memory. In turn, however, the added forward and backward passes can slow down the training a bit."),C0.forEach(t),ff=f(e),S=o(e,"P",{});var Rt=s(S);pv=n(Rt,"We can use gradient accumulation in the "),Is=o(Rt,"A",{href:!0});var L0=s(Is);hv=n(L0,"Trainer"),L0.forEach(t),fv=n(Rt," by simply adding the "),ll=o(Rt,"CODE",{});var W0=s(ll);mv=n(W0,"gradient_accumulation_steps"),W0.forEach(t),dv=n(Rt," argument to "),Ns=o(Rt,"A",{href:!0});var B0=s(Ns);cv=n(B0,"TrainingArguments"),B0.forEach(t),uv=n(Rt,". Let\u2019s see how it impacts the models memory footprint:"),Rt.forEach(t),mf=f(e),c(Ua.$$.fragment,e),df=f(e),c(Sa.$$.fragment,e),cf=f(e),T=o(e,"P",{});var te=s(T);gv=n(te,"We can see that the memory footprint was dramatically reduced at the cost of being only slightly slower than the vanilla run. Of course, this would change as you increase the number of accumulation steps. In general you would want to max out the GPU usage as much as possible. So in our case, the batch_size of 4 was already pretty close to the GPU\u2019s limit. If we wanted to train with a batch size of 64 we should not use "),pl=o(te,"CODE",{});var F0=s(pl);wv=n(F0,"per_device_train_batch_size=1"),F0.forEach(t),vv=n(te," and "),hl=o(te,"CODE",{});var R0=s(hl);yv=n(R0,"gradient_accumulation_steps=64"),R0.forEach(t),_v=n(te," but instead "),fl=o(te,"CODE",{});var H0=s(fl);bv=n(H0,"per_device_train_batch_size=4"),H0.forEach(t),Ev=n(te," and "),ml=o(te,"CODE",{});var Y0=s(ml);$v=n(Y0,"gradient_accumulation_steps=16"),Y0.forEach(t),kv=n(te," which has the same effective batch size while making better use of the available GPU resources."),te.forEach(t),uf=f(e),R=o(e,"P",{});var pn=s(R);Pv=n(pn,"For more details see the benchmarks for "),Da=o(pn,"A",{href:!0,rel:!0});var V0=s(Da);Av=n(V0,"RTX-3090"),V0.forEach(t),Tv=n(pn,`
and `),ja=o(pn,"A",{href:!0,rel:!0});var X0=s(ja);zv=n(X0,"A100"),X0.forEach(t),xv=n(pn,"."),pn.forEach(t),gf=f(e),Ms=o(e,"P",{});var Z0=s(Ms);Gv=n(Z0,"Next we have a look at another trick to save a little bit more GPU memory called gradient checkpointing."),Z0.forEach(t),wf=f(e),we=o(e,"H2",{class:!0});var hc=s(we);at=o(hc,"A",{id:!0,class:!0,href:!0});var Q0=s(at);dl=o(Q0,"SPAN",{});var J0=s(dl);c(Ia.$$.fragment,J0),J0.forEach(t),Q0.forEach(t),Uv=f(hc),cl=o(hc,"SPAN",{});var K0=s(cl);Sv=n(K0,"Gradient Checkpointing"),K0.forEach(t),hc.forEach(t),vf=f(e),Os=o(e,"P",{});var e$=s(Os);Dv=n(e$,"Even when we set the batch size to 1 and use gradient accumulation we can still run out of memory when working with large models. In order to compute the gradients during the backward pass all activations from the forward pass are normally saved. This can create a big memory overhead. Alternatively, one could forget all activations during the forward pass and recompute them on demand during the backward pass. This would however add a significant computational overhead and slow down training."),e$.forEach(t),yf=f(e),rt=o(e,"P",{});var fc=s(rt);jv=n(fc,"Gradient checkpointing strikes a compromise between the two approaches and saves strategically selected activations throughout the computational graph so only a fraction of the activations need to be re-computed for the gradients. See "),Na=o(fc,"A",{href:!0,rel:!0});var t$=s(Na);Iv=n(t$,"this great article"),t$.forEach(t),Nv=n(fc," explaining the ideas behind gradient checkpointing."),fc.forEach(t),_f=f(e),H=o(e,"P",{});var hn=s(H);Mv=n(hn,"To enable gradient checkpointing in the "),qs=o(hn,"A",{href:!0});var a$=s(qs);Ov=n(a$,"Trainer"),a$.forEach(t),qv=n(hn," we only need to pass it as a flag to the "),Cs=o(hn,"A",{href:!0});var r$=s(Cs);Cv=n(r$,"TrainingArguments"),r$.forEach(t),Lv=n(hn,". Everything else is handled under the hood:"),hn.forEach(t),bf=f(e),c(Ma.$$.fragment,e),Ef=f(e),c(Oa.$$.fragment,e),$f=f(e),Ls=o(e,"P",{});var o$=s(Ls);Wv=n(o$,"We can see that this saved some more memory but at the same time training became a bit slower. A general rule of thumb is that gradient checkpointing slows down training by about 20%. Let\u2019s have a look at another method with which we can regain some speed: mixed precision training."),o$.forEach(t),kf=f(e),ve=o(e,"H2",{class:!0});var mc=s(ve);ot=o(mc,"A",{id:!0,class:!0,href:!0});var s$=s(ot);ul=o(s$,"SPAN",{});var i$=s(ul);c(qa.$$.fragment,i$),i$.forEach(t),s$.forEach(t),Bv=f(mc),gl=o(mc,"SPAN",{});var n$=s(gl);Fv=n(n$,"Floating Data Types"),n$.forEach(t),mc.forEach(t),Pf=f(e),Ws=o(e,"P",{});var l$=s(Ws);Rv=n(l$,"The idea of mixed precision training is that not all variables need to be stored in full (32-bit) floating point precision. If we can reduce the precision the variables and their computations are faster. Here are the commonly used floating point data types choice of which impacts both memory usage and throughput:"),l$.forEach(t),Af=f(e),D=o(e,"UL",{});var Ht=s(D);Ca=o(Ht,"LI",{});var dc=s(Ca);Hv=n(dc,"fp32 ("),wl=o(dc,"CODE",{});var p$=s(wl);Yv=n(p$,"float32"),p$.forEach(t),Vv=n(dc,")"),dc.forEach(t),Xv=f(Ht),La=o(Ht,"LI",{});var cc=s(La);Zv=n(cc,"fp16 ("),vl=o(cc,"CODE",{});var h$=s(vl);Qv=n(h$,"float16"),h$.forEach(t),Jv=n(cc,")"),cc.forEach(t),Kv=f(Ht),Wa=o(Ht,"LI",{});var uc=s(Wa);ey=n(uc,"bf16 ("),yl=o(uc,"CODE",{});var f$=s(yl);ty=n(f$,"bfloat16"),f$.forEach(t),ay=n(uc,")"),uc.forEach(t),ry=f(Ht),_l=o(Ht,"LI",{});var m$=s(_l);oy=n(m$,"tf32 (CUDA internal data type)"),m$.forEach(t),Ht.forEach(t),Tf=f(e),Bs=o(e,"P",{});var d$=s(Bs);sy=n(d$,"Here is a diagram that shows how these data types correlate to each other."),d$.forEach(t),zf=f(e),ye=o(e,"P",{});var rh=s(ye);Fs=o(rh,"IMG",{src:!0,alt:!0}),iy=n(rh,`
(source: `),Ba=o(rh,"A",{href:!0,rel:!0});var c$=s(Ba);ny=n(c$,"NVIDIA Blog"),c$.forEach(t),ly=n(rh,")"),rh.forEach(t),xf=f(e),Rs=o(e,"P",{});var u$=s(Rs);py=n(u$,"While fp16 and fp32 have been around for quite some time, bf16 and tf32 are only available on the Ampere architecture GPUS and TPUs support bf16 as well. Let\u2019s start with the most commonly used method which is FP16 training/"),u$.forEach(t),Gf=f(e),_e=o(e,"H3",{class:!0});var gc=s(_e);st=o(gc,"A",{id:!0,class:!0,href:!0});var g$=s(st);bl=o(g$,"SPAN",{});var w$=s(bl);c(Fa.$$.fragment,w$),w$.forEach(t),g$.forEach(t),hy=f(gc),El=o(gc,"SPAN",{});var v$=s(El);fy=n(v$,"FP16 Training"),v$.forEach(t),gc.forEach(t),Uf=f(e),Y=o(e,"P",{});var fn=s(Y);my=n(fn,"The idea of mixed precision training is that not all variables need to be stored in full (32-bit) floating point precision. If we can reduce the precision the variales and their computations are faster. The main advantage comes from saving the activations in half (16-bit) precision. Although the gradients are also computed in half precision they are converted back to full precision for the optimization step so no memory is saved here. Since the model is present on the GPU in both 16-bit and 32-bit precision this can use more GPU memory (1.5x the original model is on the GPU), especially for small batch sizes. Since some computations are performed in full and some in half precision this approach is also called mixed precision training. Enabling mixed precision training is also just a matter of setting the "),$l=o(fn,"CODE",{});var y$=s($l);dy=n(y$,"fp16"),y$.forEach(t),cy=n(fn," flag to "),kl=o(fn,"CODE",{});var _$=s(kl);uy=n(_$,"True"),_$.forEach(t),gy=n(fn,":"),fn.forEach(t),Sf=f(e),c(Ra.$$.fragment,e),Df=f(e),c(Ha.$$.fragment,e),jf=f(e),Hs=o(e,"P",{});var b$=s(Hs);wy=n(b$,"We can see that this is almost twice as fast as the vanilla training. Let\u2019s add it to the mix of the previous methods:"),b$.forEach(t),If=f(e),c(Ya.$$.fragment,e),Nf=f(e),c(Va.$$.fragment,e),Mf=f(e),Ys=o(e,"P",{});var E$=s(Ys);vy=n(E$,"We can see that with these tweaks we use about half the GPU memory as at the beginning while also being slightly faster."),E$.forEach(t),Of=f(e),be=o(e,"H3",{class:!0});var wc=s(be);it=o(wc,"A",{id:!0,class:!0,href:!0});var $$=s(it);Pl=o($$,"SPAN",{});var k$=s(Pl);c(Xa.$$.fragment,k$),k$.forEach(t),$$.forEach(t),yy=f(wc),Al=o(wc,"SPAN",{});var P$=s(Al);_y=n(P$,"BF16"),P$.forEach(t),wc.forEach(t),qf=n(e,"\n\nIf you have access to a Ampere or newer hardware you can use bf16 for your training and evaluation. While bf16 has a worse precision than fp16, it has a much much bigger dynamic range. Therefore, if in the past you were experiencing overflow issues while training the model, bf16 will prevent this from happening most of the time. Remember that in fp16 the biggest number you can have is `65535` and any number above that will overflow. A bf16 number can be as large as `3.39e+38` (!) which is about the same as fp32 - because both have 8-bits used for the numerical range.\n"),Vs=o(e,"P",{});var A$=s(Vs);by=n(A$,"You can enable BF16 in the \u{1F917} Trainer with:"),A$.forEach(t),Cf=f(e),c(Za.$$.fragment,e),Lf=f(e),Ee=o(e,"H3",{class:!0});var vc=s(Ee);nt=o(vc,"A",{id:!0,class:!0,href:!0});var T$=s(nt);Tl=o(T$,"SPAN",{});var z$=s(Tl);c(Qa.$$.fragment,z$),z$.forEach(t),T$.forEach(t),Ey=f(vc),zl=o(vc,"SPAN",{});var x$=s(zl);$y=n(x$,"TF32"),x$.forEach(t),vc.forEach(t),Wf=n(e,`

The Ampere hardware uses a magical data type called tf32. It has the same numerical range as fp32 (8-bits), but instead of 23 bits precision it has only 10 bits (same as fp16) and uses only 19 bits in total.
`),Xs=o(e,"P",{});var G$=s(Xs);ky=n(G$,"It\u2019s magical in the sense that you can use the normal fp32 training and/or inference code and by enabling tf32 support you can get up to 3x throughput improvement. All you need to do is to add this to your code:"),G$.forEach(t),Bf=f(e),c(Ja.$$.fragment,e),Ff=f(e),Zs=o(e,"P",{});var U$=s(Zs);Py=n(U$,"When this is done CUDA will automatically switch to using tf32 instead of fp32 where it\u2019s possible. This, of course, assumes that the used GPU is from the Ampere series."),U$.forEach(t),Rf=f(e),lt=o(e,"P",{});var yc=s(lt);Ay=n(yc,"Like all cases with reduced precision this may or may not be satisfactory for your needs, so you have to experiment and see. According to "),Ka=o(yc,"A",{href:!0,rel:!0});var S$=s(Ka);Ty=n(S$,"NVIDIA research"),S$.forEach(t),zy=n(yc," the majority of machine learning training shouldn\u2019t be impacted and showed the same perplexity and convergence as the fp32 training."),yc.forEach(t),Hf=f(e),Qs=o(e,"P",{});var D$=s(Qs);xy=n(D$,"If you\u2019re already using fp16 or bf16 mixed precision it may help with the throughput as well."),D$.forEach(t),Yf=f(e),Js=o(e,"P",{});var j$=s(Js);Gy=n(j$,"You can enable this mode in the \u{1F917} Trainer with:"),j$.forEach(t),Vf=f(e),c(er.$$.fragment,e),Xf=f(e),Ks=o(e,"P",{});var I$=s(Ks);Uy=n(I$,"By default the PyTorch default is used."),I$.forEach(t),Zf=f(e),V=o(e,"P",{});var mn=s(V);Sy=n(mn,"Note: tf32 mode is internal to CUDA and can\u2019t be accessed directly via "),xl=o(mn,"CODE",{});var N$=s(xl);Dy=n(N$,"tensor.to(dtype=torch.tf32)"),N$.forEach(t),jy=n(mn," as "),Gl=o(mn,"CODE",{});var M$=s(Gl);Iy=n(M$,"torch.tf32"),M$.forEach(t),Ny=n(mn," doesn\u2019t exist."),mn.forEach(t),Qf=f(e),pt=o(e,"P",{});var _c=s(pt);My=n(_c,"Note: you need "),Ul=o(_c,"CODE",{});var O$=s(Ul);Oy=n(O$,"torch>=1.7"),O$.forEach(t),qy=n(_c," to enjoy this feature."),_c.forEach(t),Jf=f(e),X=o(e,"P",{});var dn=s(X);Cy=n(dn,`You can also see a variety of benchmarks on tf32 vs other precisions:
`),tr=o(dn,"A",{href:!0,rel:!0});var q$=s(tr);Ly=n(q$,"RTX-3090"),q$.forEach(t),Wy=n(dn,` and
`),ar=o(dn,"A",{href:!0,rel:!0});var C$=s(ar);By=n(C$,"A100"),C$.forEach(t),Fy=n(dn,"."),dn.forEach(t),Kf=f(e),ei=o(e,"P",{});var L$=s(ei);Ry=n(L$,"We\u2019ve now seen how we can change the floating types to increase throughput, but we are not done, yet! There is another area where we can save GPU memory: the optimizer."),L$.forEach(t),em=f(e),$e=o(e,"H2",{class:!0});var bc=s($e);ht=o(bc,"A",{id:!0,class:!0,href:!0});var W$=s(ht);Sl=o(W$,"SPAN",{});var B$=s(Sl);c(rr.$$.fragment,B$),B$.forEach(t),W$.forEach(t),Hy=f(bc),Dl=o(bc,"SPAN",{});var F$=s(Dl);Yy=n(F$,"Optimizer"),F$.forEach(t),bc.forEach(t),tm=f(e),ti=o(e,"P",{});var R$=s(ti);Vy=n(R$,"The most common optimizer used to train transformer model is Adam or AdamW (Adam with weight decay). Adam achieves good convergence by storing the rolling average of the previous gradients which, however, adds an additional memory footprint of the order of the number of model parameters. One remedy to this is to use an alternative optimizer such as Adafactor, which works well for some models but often it has instability issues."),R$.forEach(t),am=f(e),ft=o(e,"P",{});var Ec=s(ft);Xy=n(Ec,"HF Trainer integrates a variety of optimisers that can be used out of box. To activate the desired optimizer simply pass the "),jl=o(Ec,"CODE",{});var H$=s(jl);Zy=n(H$,"--optim"),H$.forEach(t),Qy=n(Ec," flag to the command line."),Ec.forEach(t),rm=f(e),ai=o(e,"P",{});var Y$=s(ai);Jy=n(Y$,"To see which optimizers are currently supported:"),Y$.forEach(t),om=f(e),c(or.$$.fragment,e),sm=f(e),Z=o(e,"P",{});var cn=s(Z);Ky=n(cn,"For example, if you have "),sr=o(cn,"A",{href:!0,rel:!0});var V$=s(sr);e_=n(V$,"NVIDIA/apex"),V$.forEach(t),t_=n(cn," installed "),Il=o(cn,"CODE",{});var X$=s(Il);a_=n(X$,"--optim adamw_apex_fused"),X$.forEach(t),r_=n(cn," will give you the fastest training experience among all supported AdamW optimizers."),cn.forEach(t),im=f(e),mt=o(e,"P",{});var $c=s(mt);o_=n($c,"On the other hand "),ir=o($c,"A",{href:!0,rel:!0});var Z$=s(ir);s_=n(Z$,"8bit BNB optimizer"),Z$.forEach(t),i_=n($c," can save 3/4 of memory normally used by a typical AdamW optimizer if it is configured to quantize all optimizer states, but in some situations only some optimizer states are quintized and then more memory is used."),$c.forEach(t),nm=f(e),dt=o(e,"P",{});var kc=s(dt);n_=n(kc,"Let\u2019s get a feel for the numbers and use for example use a 3B-parameter model, like "),Nl=o(kc,"CODE",{});var Q$=s(Nl);l_=n(Q$,"t5-3b"),Q$.forEach(t),p_=n(kc,". Note that since a Gigabyte correpsonds to a billion bytes we can simply multiply the parameters (in billions) with the number of necessary bytes per parameter to get Gigabytes of GPU memory usage:"),kc.forEach(t),lm=f(e),Q=o(e,"UL",{});var un=s(Q);nr=o(un,"LI",{});var Pc=s(nr);h_=n(Pc,"A standard AdamW uses 8 bytes for each parameter, here the optimizer will need ("),Ml=o(Pc,"CODE",{});var J$=s(Ml);f_=n(J$,"8*3"),J$.forEach(t),m_=n(Pc,") 24GB of GPU memory."),Pc.forEach(t),d_=f(un),lr=o(un,"LI",{});var Ac=s(lr);c_=n(Ac,"Adafactor uses slightly more than 4 bytes, so ("),Ol=o(Ac,"CODE",{});var K$=s(Ol);u_=n(K$,"4*3"),K$.forEach(t),g_=n(Ac,") 12GB and then some extra."),Ac.forEach(t),w_=f(un),pr=o(un,"LI",{});var Tc=s(pr);v_=n(Tc,"8bit BNB quantized optimizer will use only ("),ql=o(Tc,"CODE",{});var e5=s(ql);y_=n(e5,"2*3"),e5.forEach(t),__=n(Tc,") 6GB if all optimizer states are quantized."),Tc.forEach(t),un.forEach(t),pm=f(e),ri=o(e,"P",{});var t5=s(ri);b_=n(t5,"Let\u2019s have a look at Adafactor first."),t5.forEach(t),hm=f(e),ke=o(e,"H3",{class:!0});var zc=s(ke);ct=o(zc,"A",{id:!0,class:!0,href:!0});var a5=s(ct);Cl=o(a5,"SPAN",{});var r5=s(Cl);c(hr.$$.fragment,r5),r5.forEach(t),a5.forEach(t),E_=f(zc),Ll=o(zc,"SPAN",{});var o5=s(Ll);$_=n(o5,"Adafactor"),o5.forEach(t),zc.forEach(t),fm=f(e),ut=o(e,"P",{});var xc=s(ut);k_=n(xc,"Instead of keeping the rolling average for each element in the weight matrices Adafactor only stores aggregated information (row- and column-wise sums of the rolling averages) which reduces the footprint considerably. One downside of Adafactor is that in some instances convergence can be slower than Adam\u2019s so some experimentation is advised here. We can use Adafactor simply by setting "),Wl=o(xc,"CODE",{});var s5=s(Wl);P_=n(s5,'optim="adafactor"'),s5.forEach(t),A_=n(xc,":"),xc.forEach(t),mm=f(e),c(fr.$$.fragment,e),dm=f(e),c(mr.$$.fragment,e),cm=f(e),oi=o(e,"P",{});var i5=s(oi);T_=n(i5,"We can see that this saves a few more GB on the GPU. Let\u2019s see how it looks when we add it to the other methods we introduced earlier:"),i5.forEach(t),um=f(e),c(dr.$$.fragment,e),gm=f(e),c(cr.$$.fragment,e),wm=f(e),si=o(e,"P",{});var n5=s(si);z_=n(n5,"We went from 15 GB memory usage to 5 GB - a 3x improvement while maintaining the throughput! However, as mentioned before, the convergence of Adafactor can be worse than Adam. There is an alternative to Adafactor called 8-bit Adam that takes a slightly different approach."),n5.forEach(t),vm=f(e),Pe=o(e,"H3",{class:!0});var Gc=s(Pe);gt=o(Gc,"A",{id:!0,class:!0,href:!0});var l5=s(gt);Bl=o(l5,"SPAN",{});var p5=s(Bl);c(ur.$$.fragment,p5),p5.forEach(t),l5.forEach(t),x_=f(Gc),Fl=o(Gc,"SPAN",{});var h5=s(Fl);G_=n(h5,"8-bit Adam"),h5.forEach(t),Gc.forEach(t),ym=f(e),ii=o(e,"P",{});var f5=s(ii);U_=n(f5,"Instead of aggregating optimizer states like Adafactor, 8-bit Adam keeps the full state and quantizes it. Quantization means that it stores the state with lower precision and dequantizes it only for the optimization. This is similar to the idea behind FP16 training where using variables with lower precision saves memory."),f5.forEach(t),_m=f(e),z=o(e,"P",{});var ae=s(z);S_=n(ae,"In contrast to the previous approaches is this one not integrated into the "),ni=o(ae,"A",{href:!0});var m5=s(ni);D_=n(m5,"Trainer"),m5.forEach(t),j_=n(ae," as a simple flag. We need to install the 8-bit optimizer and then pass it as a custom optimizer to the "),li=o(ae,"A",{href:!0});var d5=s(li);I_=n(d5,"Trainer"),d5.forEach(t),N_=n(ae,". Follow the installation guide in the Github "),gr=o(ae,"A",{href:!0,rel:!0});var c5=s(gr);M_=n(c5,"repo"),c5.forEach(t),O_=n(ae," to install the "),Rl=o(ae,"CODE",{});var u5=s(Rl);q_=n(u5,"bitsandbytes"),u5.forEach(t),C_=n(ae," library that implements the 8-bit Adam optimizer."),ae.forEach(t),bm=f(e),pi=o(e,"P",{});var g5=s(pi);L_=n(g5,"Once installed, we just need to initialize the the optimizer. Although this looks like a considerable amount of work it actually just involves two steps: first we need to group the model\u2019s parameters into two groups where to one group we apply weight decay and to the other we don\u2019t. Usually, biases and layer norm parameters are not weight decayed. Then in a second step we just do some argument housekeeping to use the same parameters as the previously used AdamW optimizer."),g5.forEach(t),Em=f(e),c(wt.$$.fragment,e),$m=f(e),c(wr.$$.fragment,e),km=f(e),vt=o(e,"P",{});var Uc=s(vt);W_=n(Uc,"We can now pass the custom optimizer as an argument to the "),Hl=o(Uc,"CODE",{});var w5=s(Hl);B_=n(w5,"Trainer"),w5.forEach(t),F_=n(Uc,":"),Uc.forEach(t),Pm=f(e),c(vr.$$.fragment,e),Am=f(e),c(yr.$$.fragment,e),Tm=f(e),hi=o(e,"P",{});var v5=s(hi);R_=n(v5,"We can see that we get a similar memory improvement as with Adafactor while keeping the full rolling average of the gradients. Let\u2019s repeat the experiment with the full settings:"),v5.forEach(t),zm=f(e),c(_r.$$.fragment,e),xm=f(e),c(br.$$.fragment,e),Gm=f(e),fi=o(e,"P",{});var y5=s(fi);H_=n(y5,"Again, we get about a 3x memory improvement and even slightly higher throughput as using Adafactor. So we have seen how we can optimize the memory footprint of large models. The following plot summarizes all our experiments:"),y5.forEach(t),Um=f(e),mi=o(e,"P",{});var _5=s(mi);di=o(_5,"IMG",{src:!0,alt:!0}),_5.forEach(t),Sm=f(e),Ae=o(e,"H3",{class:!0});var Sc=s(Ae);yt=o(Sc,"A",{id:!0,class:!0,href:!0});var b5=s(yt);Yl=o(b5,"SPAN",{});var E5=s(Yl);c(Er.$$.fragment,E5),E5.forEach(t),b5.forEach(t),Y_=f(Sc),Vl=o(Sc,"SPAN",{});var $5=s(Vl);Xl=o($5,"CODE",{});var k5=s(Xl);V_=n(k5,"_multi_tensor"),k5.forEach(t),$5.forEach(t),Sc.forEach(t),Dm=n(e,`

pytorch-nightly introduced \`torch.optim._multi_tensor\` which should significantly speed up the optimizers for situations with lots of small feature tensors. It should eventually become the default, but if you want to experiment with it sooner and don't mind using the bleed-edge, see: https://github.com/huggingface/transformers/issues/9965
`),Te=o(e,"H2",{class:!0});var Dc=s(Te);_t=o(Dc,"A",{id:!0,class:!0,href:!0});var P5=s(_t);Zl=o(P5,"SPAN",{});var A5=s(Zl);c($r.$$.fragment,A5),A5.forEach(t),P5.forEach(t),X_=f(Dc),Ql=o(Dc,"SPAN",{});var T5=s(Ql);Z_=n(T5,"Using \u{1F917} Accelerate"),T5.forEach(t),Dc.forEach(t),jm=f(e),J=o(e,"P",{});var gn=s(J);Q_=n(gn,"So far we have used the "),ci=o(gn,"A",{href:!0});var z5=s(ci);J_=n(z5,"Trainer"),z5.forEach(t),K_=n(gn," to run the experiments but a more flexible alternative to that approach is to use \u{1F917} Accelerate. With \u{1F917} Accelerate you have full control over the training loop and can essentially write the loop in pure PyTorch with some minor modifications. In turn it allows you to easily scale across different infrastructures such as CPUs, GPUs, TPUs, or distributed multi-GPU setups without changing any code. Let\u2019s see what it takes to implement all of the above tweaks in \u{1F917} Accelerate. We can still use the "),ui=o(gn,"A",{href:!0});var x5=s(ui);eb=n(x5,"TrainingArguments"),x5.forEach(t),tb=n(gn," to wrap the training settings:"),gn.forEach(t),Im=f(e),c(kr.$$.fragment,e),Nm=f(e),gi=o(e,"P",{});var G5=s(gi);ab=n(G5,"The full example training loop with \u{1F917} Accelerate is only a handful of lines of code long:"),G5.forEach(t),Mm=f(e),c(Pr.$$.fragment,e),Om=f(e),P=o(e,"P",{});var O=s(P);rb=n(O,"First we wrap the dataset in a "),Ar=o(O,"A",{href:!0,rel:!0});var U5=s(Ar);Jl=o(U5,"CODE",{});var S5=s(Jl);ob=n(S5,"DataLoader"),S5.forEach(t),U5.forEach(t),sb=n(O,". Then we can enable gradient checkpointing by calling the model\u2019s "),wi=o(O,"A",{href:!0});var D5=s(wi);ib=n(D5,"gradient_checkpointing_enable()"),D5.forEach(t),nb=n(O," method. When we initialize the "),Tr=o(O,"A",{href:!0,rel:!0});var j5=s(Tr);Kl=o(j5,"CODE",{});var I5=s(Kl);lb=n(I5,"Accelerator"),I5.forEach(t),j5.forEach(t),pb=n(O," we can specify if we want to use mixed precision training and it will take care of it for us in the "),ep=o(O,"CODE",{});var N5=s(ep);hb=n(N5,"prepare"),N5.forEach(t),fb=n(O," call. During the "),zr=o(O,"A",{href:!0,rel:!0});var M5=s(zr);tp=o(M5,"CODE",{});var O5=s(tp);mb=n(O5,"prepare"),O5.forEach(t),M5.forEach(t),db=n(O," call the dataloader will also be distributed across workers should we use multiple GPUs. We use the same 8-bit optimizer from the earlier experiments."),O.forEach(t),qm=f(e),bt=o(e,"P",{});var jc=s(bt);cb=n(jc,"Finally, we can write the main training loop. Note that the "),ap=o(jc,"CODE",{});var q5=s(ap);ub=n(q5,"backward"),q5.forEach(t),gb=n(jc," call is handled by \u{1F917} Accelerate. We can also see how gradient accumulation works: we normalize the loss so we get the average at the end of accumulation and once we have enough steps we run the optimization. Now the question is: does this use the same amount of memory as the previous steps? Let\u2019s check:"),jc.forEach(t),Cm=f(e),c(xr.$$.fragment,e),Lm=f(e),Et=o(e,"P",{});var Ic=s(Et);wb=n(Ic,"Indeed it does. Implementing these optimization techniques with \u{1F917} Accelerate only takes a handful of lines of code and comes with the benefit of more flexiblity in the training loop. For a full documentation of all features have a look at the "),Gr=o(Ic,"A",{href:!0,rel:!0});var C5=s(Gr);vb=n(C5,"Accelerate documentation"),C5.forEach(t),yb=n(Ic,"."),Ic.forEach(t),Wm=f(e),ze=o(e,"H2",{class:!0});var Nc=s(ze);$t=o(Nc,"A",{id:!0,class:!0,href:!0});var L5=s($t);rp=o(L5,"SPAN",{});var W5=s(rp);c(Ur.$$.fragment,W5),W5.forEach(t),L5.forEach(t),_b=f(Nc),op=o(Nc,"SPAN",{});var B5=s(op);bb=n(B5,"DataLoader"),B5.forEach(t),Nc.forEach(t),Bm=f(e),vi=o(e,"P",{});var F5=s(vi);Eb=n(F5,"One of the important requirements to reach great training speed is the ability to feed the GPU at the maximum speed it can handle. By default everything happens in the main process and it might not be able to read the data from disk fast enough, and thus create a bottleneck, leading to GPU under-utilization."),F5.forEach(t),Fm=f(e),kt=o(e,"UL",{});var Mc=s(kt);yi=o(Mc,"LI",{});var z3=s(yi);sp=o(z3,"CODE",{});var R5=s(sp);$b=n(R5,"DataLoader(pin_memory=True, ...)"),R5.forEach(t),kb=n(z3," which ensures that the data gets preloaded into the pinned memory on CPU and typically leads to much faster transfers from CPU to GPU memory."),z3.forEach(t),Pb=f(Mc),_i=o(Mc,"LI",{});var x3=s(_i);ip=o(x3,"CODE",{});var H5=s(ip);Ab=n(H5,"DataLoader(num_workers=4, ...)"),H5.forEach(t),Tb=n(x3," - spawn several workers to pre-load data faster - during training watch the GPU utilization stats and if it\u2019s far from 100% experiment with raising the number of workers. Of course, the problem could be elsewhere so a very big number of workers won\u2019t necessarily lead to a better performance."),x3.forEach(t),Mc.forEach(t),Rm=f(e),xe=o(e,"H2",{class:!0});var Oc=s(xe);Pt=o(Oc,"A",{id:!0,class:!0,href:!0});var Y5=s(Pt);np=o(Y5,"SPAN",{});var V5=s(np);c(Sr.$$.fragment,V5),V5.forEach(t),Y5.forEach(t),zb=f(Oc),lp=o(Oc,"SPAN",{});var X5=s(lp);xb=n(X5,"DeepSpeed ZeRO"),X5.forEach(t),Oc.forEach(t),Hm=f(e),At=o(e,"P",{});var qc=s(At);Gb=n(qc,"The in-depth details on how to use Deepspeed can be found "),bi=o(qc,"A",{href:!0});var Z5=s(bi);Ub=n(Z5,"here"),Z5.forEach(t),Sb=n(qc,"."),qc.forEach(t),Ym=f(e),Ei=o(e,"P",{});var Q5=s(Ei);Db=n(Q5,"First, a quick decision tree:"),Q5.forEach(t),Vm=f(e),Tt=o(e,"OL",{});var Cc=s(Tt);pp=o(Cc,"LI",{});var J5=s(pp);jb=n(J5,"Model fits onto a single GPU and you have enough space to fit a small batch size - you don\u2019t need to use Deepspeed as it\u2019ll only slow things down in this use case."),J5.forEach(t),Ib=f(Cc),hp=o(Cc,"LI",{});var K5=s(hp);Nb=n(K5,"Model doesn\u2019t fit onto a single GPU or you can\u2019t fit a small batch - use DeepSpeed ZeRO + CPU Offload and for much larger models NVMe Offload."),K5.forEach(t),Cc.forEach(t),Xm=f(e),zt=o(e,"P",{});var Lc=s(zt);Mb=n(Lc,"Now if the decision tree suggested you use DeepSpeed first you need to "),$i=o(Lc,"A",{href:!0});var e4=s($i);Ob=n(e4,"install it"),e4.forEach(t),qb=n(Lc,", then follow one of the following guides to create a configuration file and launch DeepSpeed."),Lc.forEach(t),Zm=f(e),ki=o(e,"P",{});var t4=s(ki);Cb=n(t4,"Activation:"),t4.forEach(t),Qm=f(e),j=o(e,"UL",{});var Yt=s(j);fp=o(Yt,"LI",{});var a4=s(fp);Dr=o(a4,"P",{});var Wc=s(Dr);Lb=n(Wc,"HF Trainer-based examples: see this "),Pi=o(Wc,"A",{href:!0});var r4=s(Pi);Wb=n(r4,"guide"),r4.forEach(t),Bb=n(Wc,"."),Wc.forEach(t),a4.forEach(t),Fb=f(Yt),jr=o(Yt,"LI",{});var Bc=s(jr);mp=o(Bc,"P",{});var o4=s(mp);Rb=n(o4,"Custom HF Trainer-based program: Same as above, but pass:"),o4.forEach(t),Hb=f(Bc),c(Ir.$$.fragment,Bc),Bc.forEach(t),Yb=f(Yt),dp=o(Yt,"LI",{});var s4=s(dp);Nr=o(s4,"P",{});var Fc=s(Nr);Vb=n(Fc,"Deployment in Notebooks: see this "),Ai=o(Fc,"A",{href:!0});var i4=s(Ai);Xb=n(i4,"guide"),i4.forEach(t),Zb=n(Fc,"."),Fc.forEach(t),s4.forEach(t),Qb=f(Yt),cp=o(Yt,"LI",{});var n4=s(cp);Ge=o(n4,"P",{});var wn=s(Ge);Jb=n(wn,"Custom training loop: This is somewhat complex but you can study how this is implemented in "),Mr=o(wn,"A",{href:!0,rel:!0});var l4=s(Mr);Kb=n(l4,"HF Trainer"),l4.forEach(t),e1=n(wn," - simply search for "),up=o(wn,"CODE",{});var p4=s(up);t1=n(p4,"deepspeed"),p4.forEach(t),a1=n(wn," in the code."),wn.forEach(t),n4.forEach(t),Yt.forEach(t),Jm=f(e),Ue=o(e,"H2",{class:!0});var Rc=s(Ue);xt=o(Rc,"A",{id:!0,class:!0,href:!0});var h4=s(xt);gp=o(h4,"SPAN",{});var f4=s(gp);c(Or.$$.fragment,f4),f4.forEach(t),h4.forEach(t),r1=f(Rc),wp=o(Rc,"SPAN",{});var m4=s(wp);o1=n(m4,"Choice of GPU"),m4.forEach(t),Rc.forEach(t),Km=n(e,`

Sometimes, even when applying all the above tweaks the throughput on a given GPU might still not be good enough. One easy solution is to change the type of GPU. For example switching from let's say a K80 (which you typically get on Google Colab) to a fancier GPU such as the V100 or A100. Although they are more expensive they are usually more cost effective than cheaper GPUs due to their larger memory and faster architecture.
`),Ti=o(e,"P",{});var d4=s(Ti);s1=n(d4,"Now, let\u2019s take a step back and discuss what we should optimize for when scaling the training of large models."),d4.forEach(t),ed=f(e),Se=o(e,"H2",{class:!0});var Hc=s(Se);Gt=o(Hc,"A",{id:!0,class:!0,href:!0});var c4=s(Gt);vp=o(c4,"SPAN",{});var u4=s(vp);c(qr.$$.fragment,u4),u4.forEach(t),c4.forEach(t),i1=f(Hc),yp=o(Hc,"SPAN",{});var g4=s(yp);n1=n(g4,"How to scale"),g4.forEach(t),Hc.forEach(t),td=f(e),zi=o(e,"P",{});var w4=s(zi);l1=n(w4,"When we train models there are a two aspects we want to optimize at the same time:"),w4.forEach(t),ad=f(e),Ut=o(e,"UL",{});var Yc=s(Ut);_p=o(Yc,"LI",{});var v4=s(_p);p1=n(v4,"Data throughput/training time"),v4.forEach(t),h1=f(Yc),bp=o(Yc,"LI",{});var y4=s(bp);f1=n(y4,"Model performance"),y4.forEach(t),Yc.forEach(t),rd=f(e),xi=o(e,"P",{});var _4=s(xi);m1=n(_4,"We have seen that each method changes the memory usage and throughput. In general we want to maximize the throughput (samples/second) to minimize the training cost. This is generally achieved by utilizing the GPU as much as possible and thus filling GPU memory to its limit. For example, as mentioned earlier, we only employ gradient accumulation when we want to use a batch size beyond the size of the GPU memory. If the desired batch size fits into memory then there is no reason to apply gradient accumulation which will only slow down training."),_4.forEach(t),od=f(e),Gi=o(e,"P",{});var b4=s(Gi);d1=n(b4,"The second objective is model performance. Just because we can does not mean we should use a large batch size. As part of hyperparameter tuning you should determine which batch size yields the best result and then optimize the throughput accordingly."),b4.forEach(t),sd=f(e),De=o(e,"H2",{class:!0});var Vc=s(De);St=o(Vc,"A",{id:!0,class:!0,href:!0});var E4=s(St);Ep=o(E4,"SPAN",{});var $4=s(Ep);c(Cr.$$.fragment,$4),$4.forEach(t),E4.forEach(t),c1=f(Vc),$p=o(Vc,"SPAN",{});var k4=s($p);u1=n(k4,"Efficient Software Prebuilds"),k4.forEach(t),Vc.forEach(t),id=f(e),Dt=o(e,"P",{});var Xc=s(Dt);g1=n(Xc,"PyTorch\u2019s "),Lr=o(Xc,"A",{href:!0,rel:!0});var P4=s(Lr);w1=n(P4,"pip and conda builds"),P4.forEach(t),v1=n(Xc," come prebuit with the cuda toolkit which is enough to run PyTorch, but it is insufficient if you need to build cuda extensions."),Xc.forEach(t),nd=f(e),jt=o(e,"P",{});var Zc=s(jt);y1=n(Zc,"At times it may take an additional effort to pre-build some components, e.g., if you\u2019re using libraries like "),kp=o(Zc,"CODE",{});var A4=s(kp);_1=n(A4,"apex"),A4.forEach(t),b1=n(Zc," that don\u2019t come pre-compiled. In other situations figuring out how to install the right cuda toolkit system-wide can be complicated. To address these users\u2019 needs PyTorch and NVIDIA release a new version of NGC docker container which already comes with everything prebuilt and you just need to install your programs on it and it will run out of the box."),Zc.forEach(t),ld=f(e),Ui=o(e,"P",{});var T4=s(Ui);E1=n(T4,"This approach is also useful if you want to tweak the pytorch source and/or make a new customized build."),T4.forEach(t),pd=f(e),K=o(e,"P",{});var vn=s(K);$1=n(vn,"To find the docker image version you want start "),Wr=o(vn,"A",{href:!0,rel:!0});var z4=s(Wr);k1=n(z4,"here"),z4.forEach(t),P1=n(vn,", choose one of the latest monthly releases. Go into the release\u2019s notes for the desired release, check that the environment\u2019s components are matching your needs (including NVIDIA Driver requirements!) and then at the very top of that document go to the corresponding NGC page. If for some reason you get lost, here is "),Br=o(vn,"A",{href:!0,rel:!0});var x4=s(Br);A1=n(x4,"the index of all PyTorch NGC images"),x4.forEach(t),T1=n(vn,"."),vn.forEach(t),hd=f(e),Si=o(e,"P",{});var G4=s(Si);z1=n(G4,"Next follow the instructions to download and deploy the docker image."),G4.forEach(t),fd=f(e),je=o(e,"H2",{class:!0});var Qc=s(je);It=o(Qc,"A",{id:!0,class:!0,href:!0});var U4=s(It);Pp=o(U4,"SPAN",{});var S4=s(Pp);c(Fr.$$.fragment,S4),S4.forEach(t),U4.forEach(t),x1=f(Qc),Ap=o(Qc,"SPAN",{});var D4=s(Ap);G1=n(D4,"Sparsity"),D4.forEach(t),Qc.forEach(t),md=f(e),Ie=o(e,"H3",{class:!0});var Jc=s(Ie);Nt=o(Jc,"A",{id:!0,class:!0,href:!0});var j4=s(Nt);Tp=o(j4,"SPAN",{});var I4=s(Tp);c(Rr.$$.fragment,I4),I4.forEach(t),j4.forEach(t),U1=f(Jc),zp=o(Jc,"SPAN",{});var N4=s(zp);S1=n(N4,"Mixture of Experts"),N4.forEach(t),Jc.forEach(t),dd=f(e),Di=o(e,"P",{});var M4=s(Di);D1=n(M4,`Quite a few of the recent papers reported a 4-5x training speedup and a faster inference by integrating
Mixture of Experts (MoE) into the Transformer models.`),M4.forEach(t),cd=f(e),ji=o(e,"P",{});var O4=s(ji);j1=n(O4,"Since it has been discovered that more parameters lead to better performance, this technique allows to increase the number of parameters by an order of magnitude without increasing training costs."),O4.forEach(t),ud=f(e),Ii=o(e,"P",{});var q4=s(Ii);I1=n(q4,"In this approach every other FFN layer is replaced with a MoE Layer which consists of many experts, with a gated function that trains each expert in a balanced way depending on the input token\u2019s position in a sequence."),q4.forEach(t),gd=f(e),Ni=o(e,"P",{});var C4=s(Ni);Mi=o(C4,"IMG",{src:!0,alt:!0}),C4.forEach(t),wd=f(e),Mt=o(e,"P",{});var Kc=s(Mt);N1=n(Kc,"(source: "),Hr=o(Kc,"A",{href:!0,rel:!0});var L4=s(Hr);M1=n(L4,"GLAM"),L4.forEach(t),O1=n(Kc,")"),Kc.forEach(t),vd=f(e),Oi=o(e,"P",{});var W4=s(Oi);q1=n(W4,"You can find exhaustive details and comparison tables in the papers listed at the end of this section."),W4.forEach(t),yd=f(e),qi=o(e,"P",{});var B4=s(qi);C1=n(B4,"The main drawback of this approach is that it requires staggering amounts of GPU memory - almost an order of magnitude larger than its dense equivalent. Various distillation and approaches are proposed to how to overcome the much higher memory requirements."),B4.forEach(t),_d=f(e),Ci=o(e,"P",{});var F4=s(Ci);L1=n(F4,"There is direct trade-off though, you can use just a few experts with a 2-3x smaller base model instead of dozens or hundreds experts leading to a 5x smaller model and thus increase the training speed moderately while increasing the memory requirements moderately as well."),F4.forEach(t),bd=f(e),Li=o(e,"P",{});var R4=s(Li);W1=n(R4,"Most related papers and implementations are built around Tensorflow/TPUs:"),R4.forEach(t),Ed=f(e),ee=o(e,"UL",{});var yn=s(ee);xp=o(yn,"LI",{});var H4=s(xp);Yr=o(H4,"A",{href:!0,rel:!0});var Y4=s(Yr);B1=n(Y4,"GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding"),Y4.forEach(t),H4.forEach(t),F1=f(yn),Gp=o(yn,"LI",{});var V4=s(Gp);Vr=o(V4,"A",{href:!0,rel:!0});var X4=s(Vr);R1=n(X4,"Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity"),X4.forEach(t),V4.forEach(t),H1=f(yn),Up=o(yn,"LI",{});var Z4=s(Up);Xr=o(Z4,"A",{href:!0,rel:!0});var Q4=s(Xr);Y1=n(Q4,"GLaM: Generalist Language Model (GLaM)"),Q4.forEach(t),Z4.forEach(t),yn.forEach(t),$d=f(e),E=o(e,"P",{});var G=s(E);V1=n(G,"And for Pytorch DeepSpeed has built one as well: "),Zr=o(G,"A",{href:!0,rel:!0});var J4=s(Zr);X1=n(J4,"DeepSpeed-MoE: Advancing Mixture-of-Experts Inference and Training to Power Next-Generation AI Scale"),J4.forEach(t),Z1=n(G,", "),Qr=o(G,"A",{href:!0,rel:!0});var K4=s(Qr);Q1=n(K4,"Mixture of Experts"),K4.forEach(t),J1=n(G," - blog posts:  "),Jr=o(G,"A",{href:!0,rel:!0});var e6=s(Jr);K1=n(e6,"1"),e6.forEach(t),e2=n(G,", "),Kr=o(G,"A",{href:!0,rel:!0});var t6=s(Kr);t2=n(t6,"2"),t6.forEach(t),a2=n(G," and specific deployment with large transformer-based natural language generation models: "),eo=o(G,"A",{href:!0,rel:!0});var a6=s(eo);r2=n(a6,"blog post"),a6.forEach(t),o2=n(G,", "),Wi=o(G,"A",{href:!0});var r6=s(Wi);s2=n(r6,"Megatron-Deepspeed branch"),r6.forEach(t),i2=n(G,"."),G.forEach(t),kd=f(e),Ne=o(e,"H2",{class:!0});var eu=s(Ne);Ot=o(eu,"A",{id:!0,class:!0,href:!0});var o6=s(Ot);Sp=o(o6,"SPAN",{});var s6=s(Sp);c(to.$$.fragment,s6),s6.forEach(t),o6.forEach(t),n2=f(eu),Dp=o(eu,"SPAN",{});var i6=s(Dp);l2=n(i6,"Scaling beyond a single GPU"),i6.forEach(t),eu.forEach(t),Pd=f(e),Bi=o(e,"P",{});var n6=s(Bi);p2=n(n6,"For some applications, such as pretraining large language models, applying all the approaches above might still not be fast enough. In this case you want to scale your experiment to several GPUs."),n6.forEach(t),Ad=f(e),qt=o(e,"P",{});var tu=s(qt);h2=n(tu,"Another use case for training on many GPUs is if the model does not fit on a single GPU with all the mentioned tricks. There are still more methods we can apply although life starts to get a bit more complicated. This usually involves some form of pipeline or tensor parallelism where the model itself is distributed across several GPUs. One can also make use of DeepSpeed which implements some of these parallelism strategies along with some more optimization to reduce the memory footprint such as partitioning the optimizer states. You can read more about this in the "),Fi=o(tu,"A",{href:!0});var l6=s(Fi);f2=n(l6,"\u201CMulti-GPU training\u201D section"),l6.forEach(t),m2=n(tu,"."),tu.forEach(t),Td=f(e),Me=o(e,"H2",{class:!0});var au=s(Me);Ct=o(au,"A",{id:!0,class:!0,href:!0});var p6=s(Ct);jp=o(p6,"SPAN",{});var h6=s(jp);c(ao.$$.fragment,h6),h6.forEach(t),p6.forEach(t),d2=f(au),Ip=o(au,"SPAN",{});var f6=s(Ip);c2=n(f6,"Using PyTorch native attention"),f6.forEach(t),au.forEach(t),zd=f(e),I=o(e,"P",{});var Vt=s(I);u2=n(Vt,"PyTorch 2.0 released the native "),ro=o(Vt,"A",{href:!0,rel:!0});var m6=s(ro);Np=o(m6,"CODE",{});var d6=s(Np);g2=n(d6,"torch.nn.functional.scaled_dot_product_attention"),d6.forEach(t),m6.forEach(t),w2=n(Vt," (SDPA), that allows to use fused GPU kernels as "),oo=o(Vt,"A",{href:!0,rel:!0});var c6=s(oo);v2=n(c6,"memory-efficient attention"),c6.forEach(t),y2=n(Vt," and "),so=o(Vt,"A",{href:!0,rel:!0});var u6=s(so);_2=n(u6,"flash attention"),u6.forEach(t),b2=n(Vt,"."),Vt.forEach(t),xd=f(e),Lt=o(e,"P",{});var ru=s(Lt);E2=n(ru,"After installing the "),io=o(ru,"A",{href:!0,rel:!0});var g6=s(io);Mp=o(g6,"CODE",{});var w6=s(Mp);$2=n(w6,"optimum"),w6.forEach(t),g6.forEach(t),k2=n(ru," package, the relevant internal modules can be replaced to use PyTorch\u2019s native attention with:"),ru.forEach(t),Gd=f(e),c(no.$$.fragment,e),Ud=f(e),Ri=o(e,"P",{});var v6=s(Ri);P2=n(v6,"Training can then be done as usual."),v6.forEach(t),Sd=f(e),Oe=o(e,"H2",{class:!0});var ou=s(Oe);Wt=o(ou,"A",{id:!0,class:!0,href:!0});var y6=s(Wt);Op=o(y6,"SPAN",{});var _6=s(Op);c(lo.$$.fragment,_6),_6.forEach(t),y6.forEach(t),A2=f(ou),qp=o(ou,"SPAN",{});var b6=s(qp);T2=n(b6,"Using torch.compile"),b6.forEach(t),ou.forEach(t),Dd=f(e),Bt=o(e,"P",{});var su=s(Bt);z2=n(su,"PyTorch 2.0 introduces a new compile function, you can learn more about it "),po=o(su,"A",{href:!0,rel:!0});var E6=s(po);x2=n(E6,"in their documentation"),E6.forEach(t),G2=n(su,". It uses Python\u2019s frame evaluation API to automatically create a graph from existing PyTorch programs. After capturing the graph, different backends can be deployed to lower the graph to an optimized engine. You can choose one option below for performance boost."),su.forEach(t),jd=f(e),q=o(e,"P",{});var So=s(q);Cp=o(So,"CODE",{});var $6=s(Cp);U2=n($6,"torch.compile"),$6.forEach(t),S2=n(So," has a growing list of backends, which can be found in "),ho=o(So,"A",{href:!0,rel:!0});var k6=s(ho);D2=n(k6,"backends.py"),k6.forEach(t),j2=n(So,`
or `),Lp=o(So,"CODE",{});var P6=s(Lp);I2=n(P6,"torchdynamo.list_backends()"),P6.forEach(t),N2=n(So," each of which with its optional dependencies."),So.forEach(t),Id=f(e),Hi=o(e,"P",{});var A6=s(Hi);M2=n(A6,"Some of the most commonly used backends are"),A6.forEach(t),Nd=f(e),fo=o(e,"P",{});var G3=s(fo);Wp=o(G3,"STRONG",{});var T6=s(Wp);O2=n(T6,"Debugging backends"),T6.forEach(t),q2=n(G3,":"),G3.forEach(t),Md=f(e),Ft=o(e,"UL",{});var iu=s(Ft);Yi=o(iu,"LI",{});var U3=s(Yi);Bp=o(U3,"CODE",{});var z6=s(Bp);C2=n(z6,'dynamo.optimize("eager")'),z6.forEach(t),L2=n(U3," - Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues."),U3.forEach(t),W2=f(iu),Vi=o(iu,"LI",{});var S3=s(Vi);Fp=o(S3,"CODE",{});var x6=s(Fp);B2=n(x6,'dynamo.optimize("aot_eager")'),x6.forEach(t),F2=n(S3," - Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd\u2019s extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups."),S3.forEach(t),iu.forEach(t),Od=f(e),mo=o(e,"P",{});var D3=s(mo);Rp=o(D3,"STRONG",{});var G6=s(Rp);R2=n(G6,"Training & inference backends"),G6.forEach(t),H2=n(D3,":"),D3.forEach(t),qd=f(e),N=o(e,"UL",{});var Xt=s(N);co=o(Xt,"LI",{});var nu=s(co);Hp=o(nu,"CODE",{});var U6=s(Hp);Y2=n(U6,'dynamo.optimize("inductor")'),U6.forEach(t),V2=n(nu," - Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels  "),uo=o(nu,"A",{href:!0,rel:!0});var S6=s(uo);X2=n(S6,"Read more"),S6.forEach(t),nu.forEach(t),Z2=f(Xt),go=o(Xt,"LI",{});var lu=s(go);Yp=o(lu,"CODE",{});var D6=s(Yp);Q2=n(D6,'dynamo.optimize("nvfuser")'),D6.forEach(t),J2=n(lu," -  nvFuser with TorchScript. "),wo=o(lu,"A",{href:!0,rel:!0});var j6=s(wo);K2=n(j6,"Read more"),j6.forEach(t),lu.forEach(t),e3=f(Xt),vo=o(Xt,"LI",{});var pu=s(vo);Vp=o(pu,"CODE",{});var I6=s(Vp);t3=n(I6,'dynamo.optimize("aot_nvfuser")'),I6.forEach(t),a3=n(pu," -  nvFuser with AotAutograd. "),yo=o(pu,"A",{href:!0,rel:!0});var N6=s(yo);r3=n(N6,"Read more"),N6.forEach(t),pu.forEach(t),o3=f(Xt),_o=o(Xt,"LI",{});var hu=s(_o);Xp=o(hu,"CODE",{});var M6=s(Xp);s3=n(M6,'dynamo.optimize("aot_cudagraphs")'),M6.forEach(t),i3=n(hu," - cudagraphs with AotAutograd. "),bo=o(hu,"A",{href:!0,rel:!0});var O6=s(bo);n3=n(O6,"Read more"),O6.forEach(t),hu.forEach(t),Xt.forEach(t),Cd=f(e),Eo=o(e,"P",{});var j3=s(Eo);Zp=o(j3,"STRONG",{});var q6=s(Zp);l3=n(q6,"Inference-only backend"),q6.forEach(t),p3=n(j3,"s:"),j3.forEach(t),Ld=f(e),M=o(e,"UL",{});var Zt=s(M);$o=o(Zt,"LI",{});var fu=s($o);Qp=o(fu,"CODE",{});var C6=s(Qp);h3=n(C6,'dynamo.optimize("ofi")'),C6.forEach(t),f3=n(fu," -  Uses Torchscript optimize_for_inference.  "),ko=o(fu,"A",{href:!0,rel:!0});var L6=s(ko);m3=n(L6,"Read more"),L6.forEach(t),fu.forEach(t),d3=f(Zt),Po=o(Zt,"LI",{});var mu=s(Po);Jp=o(mu,"CODE",{});var W6=s(Jp);c3=n(W6,'dynamo.optimize("fx2trt")'),W6.forEach(t),u3=n(mu," -  Uses Nvidia TensorRT for inference optimizations.  "),Ao=o(mu,"A",{href:!0,rel:!0});var B6=s(Ao);g3=n(B6,"Read more"),B6.forEach(t),mu.forEach(t),w3=f(Zt),To=o(Zt,"LI",{});var du=s(To);Kp=o(du,"CODE",{});var F6=s(Kp);v3=n(F6,'dynamo.optimize("onnxrt")'),F6.forEach(t),y3=n(du," -  Uses ONNXRT for inference on CPU/GPU.  "),zo=o(du,"A",{href:!0,rel:!0});var R6=s(zo);_3=n(R6,"Read more"),R6.forEach(t),du.forEach(t),b3=f(Zt),xo=o(Zt,"LI",{});var cu=s(xo);eh=o(cu,"CODE",{});var H6=s(eh);E3=n(H6,'dynamo.optimize("ipex")'),H6.forEach(t),$3=n(cu," -  Uses IPEX for inference on CPU.  "),Go=o(cu,"A",{href:!0,rel:!0});var Y6=s(Go);k3=n(Y6,"Read more"),Y6.forEach(t),cu.forEach(t),Zt.forEach(t),this.h()},h(){m(b,"name","hf:doc:metadata"),m(b,"content",JSON.stringify(rk)),m(U,"id","efficient-training-on-a-single-gpu"),m(U,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(U,"href","#efficient-training-on-a-single-gpu"),m($,"class","relative group"),m(jo,"href","perf_train_gpu_many"),m(Io,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(Jt,"href","https://huggingface.co/docs/accelerate/"),m(Jt,"rel","nofollow"),m(No,"align","left"),m(Mo,"align","left"),m(Oo,"align","left"),m(qo,"align","left"),m(Co,"align","left"),m(Lo,"align","left"),m(Wo,"align","left"),m(Bo,"align","left"),m(Fo,"align","left"),m(Ro,"align","left"),m(Ho,"align","left"),m(Yo,"align","left"),m(Vo,"align","left"),m(Xo,"align","left"),m(Zo,"align","left"),m(Qo,"align","left"),m(Jo,"align","left"),m(Ko,"align","left"),m(es,"align","left"),m(ts,"align","left"),m(as,"align","left"),m(rs,"align","left"),m(os,"align","left"),m(ss,"align","left"),m(ea,"href","https://huggingface.co/docs/datasets/v2.12.0/en/package_reference/main_classes#datasets.Dataset"),m(ea,"rel","nofollow"),m(ns,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(Be,"id","load-model"),m(Be,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Be,"href","#load-model"),m(fe,"class","relative group"),m(Ye,"id","vanilla-training"),m(Ye,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Ye,"href","#vanilla-training"),m(me,"class","relative group"),m(ms,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(Xe,"id","anatomy-of-models-operations"),m(Xe,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Xe,"href","#anatomy-of-models-operations"),m(de,"class","relative group"),m(ba,"href","https://arxiv.org/abs/2007.00072"),m(ba,"rel","nofollow"),m(Ze,"id","anatomy-of-models-memory"),m(Ze,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Ze,"href","#anatomy-of-models-memory"),m(ce,"class","relative group"),m($a,"href","https://github.com/TimDettmers/bitsandbytes"),m($a,"rel","nofollow"),m(Ke,"id","batch-sizes"),m(Ke,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Ke,"href","#batch-sizes"),m(ue,"class","relative group"),m(Pa,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#input-features"),m(Pa,"rel","nofollow"),m(Aa,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#batch-size"),m(Aa,"rel","nofollow"),m(za,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc"),m(za,"rel","nofollow"),m(xa,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#dim-quantization"),m(xa,"rel","nofollow"),m(tt,"id","gradient-accumulation"),m(tt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(tt,"href","#gradient-accumulation"),m(ge,"class","relative group"),m(Is,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(Ns,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.TrainingArguments"),m(Da,"href","https://github.com/huggingface/transformers/issues/14608#issuecomment-1004392537"),m(Da,"rel","nofollow"),m(ja,"href","https://github.com/huggingface/transformers/issues/15026#issuecomment-1005033957"),m(ja,"rel","nofollow"),m(at,"id","gradient-checkpointing"),m(at,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(at,"href","#gradient-checkpointing"),m(we,"class","relative group"),m(Na,"href","https://medium.com/tensorflow/fitting-larger-networks-into-memory-583e3c758ff9"),m(Na,"rel","nofollow"),m(qs,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(Cs,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.TrainingArguments"),m(ot,"id","floating-data-types"),m(ot,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(ot,"href","#floating-data-types"),m(ve,"class","relative group"),I3(Fs.src,N3="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tf32-bf16-fp16-fp32.png")||m(Fs,"src",N3),m(Fs,"alt","data types"),m(Ba,"href","https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/"),m(Ba,"rel","nofollow"),m(st,"id","fp16-training"),m(st,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(st,"href","#fp16-training"),m(_e,"class","relative group"),m(it,"id","bf16"),m(it,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(it,"href","#bf16"),m(be,"class","relative group"),m(nt,"id","tf32"),m(nt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(nt,"href","#tf32"),m(Ee,"class","relative group"),m(Ka,"href","https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/"),m(Ka,"rel","nofollow"),m(tr,"href","https://github.com/huggingface/transformers/issues/14608#issuecomment-1004390803"),m(tr,"rel","nofollow"),m(ar,"href","https://github.com/huggingface/transformers/issues/15026#issuecomment-1004543189"),m(ar,"rel","nofollow"),m(ht,"id","optimizer"),m(ht,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(ht,"href","#optimizer"),m($e,"class","relative group"),m(sr,"href","https://github.com/NVIDIA/apex"),m(sr,"rel","nofollow"),m(ir,"href","https://github.com/TimDettmers/bitsandbytes"),m(ir,"rel","nofollow"),m(ct,"id","adafactor"),m(ct,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(ct,"href","#adafactor"),m(ke,"class","relative group"),m(gt,"id","8bit-adam"),m(gt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(gt,"href","#8bit-adam"),m(Pe,"class","relative group"),m(ni,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(li,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(gr,"href","https://github.com/TimDettmers/bitsandbytes"),m(gr,"rel","nofollow"),I3(di.src,M3="https://huggingface.co/datasets/lvwerra/repo-images/raw/main/gpu-memory-savings.png")||m(di,"src",M3),m(di,"alt","png"),m(yt,"id","multitensor"),m(yt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(yt,"href","#multitensor"),m(Ae,"class","relative group"),m(_t,"id","using-accelerate"),m(_t,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(_t,"href","#using-accelerate"),m(Te,"class","relative group"),m(ci,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(ui,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.TrainingArguments"),m(Ar,"href","https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader"),m(Ar,"rel","nofollow"),m(wi,"href","/docs/transformers/v4.29.0/en/main_classes/model#transformers.PreTrainedModel.gradient_checkpointing_enable"),m(Tr,"href","https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator"),m(Tr,"rel","nofollow"),m(zr,"href","https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare"),m(zr,"rel","nofollow"),m(Gr,"href","https://huggingface.co/docs/accelerate/index"),m(Gr,"rel","nofollow"),m($t,"id","dataloader"),m($t,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m($t,"href","#dataloader"),m(ze,"class","relative group"),m(Pt,"id","deepspeed-zero"),m(Pt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Pt,"href","#deepspeed-zero"),m(xe,"class","relative group"),m(bi,"href","main_classes/deepspeed"),m($i,"href","main_classes/deepspeed#installation"),m(Pi,"href","main_classes/deepspeed#deployment-with-one-gpu"),m(Ai,"href","main_classes/deepspeed#deployment-in-notebooks"),m(Mr,"href","https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py"),m(Mr,"rel","nofollow"),m(xt,"id","choice-of-gpu"),m(xt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(xt,"href","#choice-of-gpu"),m(Ue,"class","relative group"),m(Gt,"id","how-to-scale"),m(Gt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Gt,"href","#how-to-scale"),m(Se,"class","relative group"),m(St,"id","efficient-software-prebuilds"),m(St,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(St,"href","#efficient-software-prebuilds"),m(De,"class","relative group"),m(Lr,"href","https://pytorch.org/get-started/locally/#start-locally"),m(Lr,"rel","nofollow"),m(Wr,"href","https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/"),m(Wr,"rel","nofollow"),m(Br,"href","https://ngc.nvidia.com/catalog/containers/nvidia:pytorch"),m(Br,"rel","nofollow"),m(It,"id","sparsity"),m(It,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(It,"href","#sparsity"),m(je,"class","relative group"),m(Nt,"id","mixture-of-experts"),m(Nt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Nt,"href","#mixture-of-experts"),m(Ie,"class","relative group"),I3(Mi.src,O3="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/perf-moe-transformer.png")||m(Mi,"src",O3),m(Mi,"alt","MoE Transformer 2x block"),m(Hr,"href","https://ai.googleblog.com/2021/12/more-efficient-in-context-learning-with.html"),m(Hr,"rel","nofollow"),m(Yr,"href","https://arxiv.org/abs/2006.16668"),m(Yr,"rel","nofollow"),m(Vr,"href","https://arxiv.org/abs/2101.03961"),m(Vr,"rel","nofollow"),m(Xr,"href","https://ai.googleblog.com/2021/12/more-efficient-in-context-learning-with.html"),m(Xr,"rel","nofollow"),m(Zr,"href","https://arxiv.org/abs/2201.05596"),m(Zr,"rel","nofollow"),m(Qr,"href","https://www.deepspeed.ai/tutorials/mixture-of-experts/"),m(Qr,"rel","nofollow"),m(Jr,"href","https://www.microsoft.com/en-us/research/blog/deepspeed-powers-8x-larger-moe-model-training-with-high-performance/"),m(Jr,"rel","nofollow"),m(Kr,"href","https://www.microsoft.com/en-us/research/publication/scalable-and-efficient-moe-training-for-multitask-multilingual-models/"),m(Kr,"rel","nofollow"),m(eo,"href","https://www.deepspeed.ai/news/2021/12/09/deepspeed-moe-nlg.html"),m(eo,"rel","nofollow"),m(Wi,"href","Thttps://github.com/microsoft/Megatron-DeepSpeed/tree/moe-training"),m(Ot,"id","scaling-beyond-a-single-gpu"),m(Ot,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Ot,"href","#scaling-beyond-a-single-gpu"),m(Ne,"class","relative group"),m(Fi,"href","perf_train_gpu_many"),m(Ct,"id","using-pytorch-native-attention"),m(Ct,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Ct,"href","#using-pytorch-native-attention"),m(Me,"class","relative group"),m(ro,"href","https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html"),m(ro,"rel","nofollow"),m(oo,"href","https://arxiv.org/abs/2112.05682"),m(oo,"rel","nofollow"),m(so,"href","https://arxiv.org/abs/2205.14135"),m(so,"rel","nofollow"),m(io,"href","https://github.com/huggingface/optimum"),m(io,"rel","nofollow"),m(Wt,"id","using-torchcompile"),m(Wt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Wt,"href","#using-torchcompile"),m(Oe,"class","relative group"),m(po,"href","https://pytorch.org/get-started/pytorch-2.0/"),m(po,"rel","nofollow"),m(ho,"href","https://github.com/pytorch/pytorch/blob/master/torch/_dynamo/optimizations/backends.py"),m(ho,"rel","nofollow"),m(uo,"href","https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747"),m(uo,"rel","nofollow"),m(wo,"href","https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593"),m(wo,"rel","nofollow"),m(yo,"href","https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593"),m(yo,"rel","nofollow"),m(bo,"href","https://github.com/pytorch/torchdynamo/pull/757"),m(bo,"rel","nofollow"),m(ko,"href","https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html"),m(ko,"rel","nofollow"),m(Ao,"href","https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst"),m(Ao,"rel","nofollow"),m(zo,"href","https://onnxruntime.ai/"),m(zo,"rel","nofollow"),m(Go,"href","https://github.com/intel/intel-extension-for-pytorch"),m(Go,"rel","nofollow")},m(e,l){a(document.head,b),p(e,A,l),p(e,$,l),a($,U),a(U,_n),u(Qt,_n,null),a($,uu),a($,bn),a(bn,gu),p(e,oh,l),p(e,qe,l),a(qe,wu),a(qe,jo),a(jo,vu),a(qe,yu),p(e,sh,l),p(e,C,l),a(C,_u),a(C,Io),a(Io,bu),a(C,Eu),a(C,Jt),a(Jt,$u),a(C,ku),p(e,ih,l),p(e,Ce,l),a(Ce,En),a(En,re),a(re,No),a(No,Pu),a(re,Au),a(re,Mo),a(Mo,Tu),a(re,zu),a(re,Oo),a(Oo,xu),a(Ce,Gu),a(Ce,k),a(k,oe),a(oe,qo),a(qo,Uu),a(oe,Su),a(oe,Co),a(Co,Du),a(oe,ju),a(oe,Lo),a(Lo,Iu),a(k,Nu),a(k,se),a(se,Wo),a(Wo,Mu),a(se,Ou),a(se,Bo),a(Bo,qu),a(se,Cu),a(se,Fo),a(Fo,Lu),a(k,Wu),a(k,ie),a(ie,Ro),a(Ro,Bu),a(ie,Fu),a(ie,Ho),a(Ho,Ru),a(ie,Hu),a(ie,Yo),a(Yo,Yu),a(k,Vu),a(k,ne),a(ne,Vo),a(Vo,Xu),a(ne,Zu),a(ne,Xo),a(Xo,Qu),a(ne,Ju),a(ne,Zo),a(Zo,Ku),a(k,eg),a(k,le),a(le,Qo),a(Qo,tg),a(le,ag),a(le,Jo),a(Jo,rg),a(le,og),a(le,Ko),a(Ko,sg),a(k,ig),a(k,pe),a(pe,es),a(es,ng),a(pe,lg),a(pe,ts),a(ts,pg),a(pe,hg),a(pe,as),a(as,fg),a(k,mg),a(k,he),a(he,rs),a(rs,dg),a(he,cg),a(he,os),a(os,ug),a(he,gg),a(he,ss),a(ss,wg),p(e,nh,l),p(e,is,l),a(is,vg),p(e,lh,l),u(Kt,e,l),p(e,ph,l),p(e,L,l),a(L,yg),a(L,$n),a($n,_g),a(L,bg),a(L,kn),a(kn,Eg),a(L,$g),p(e,hh,l),p(e,Le,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vp,t3),a(vo,a3),a(vo,yo),a(yo,r3),a(N,o3),a(N,_o),a(_o,Xp),a(Xp,s3),a(_o,i3),a(_o,bo),a(bo,n3),p(e,Cd,l),p(e,Eo,l),a(Eo,Zp),a(Zp,l3),a(Eo,p3),p(e,Ld,l),p(e,M,l),a(M,$o),a($o,Qp),a(Qp,h3),a($o,f3),a($o,ko),a(ko,m3),a(M,d3),a(M,Po),a(Po,Jp),a(Jp,c3),a(Po,u3),a(Po,Ao),a(Ao,g3),a(M,w3),a(M,To),a(To,Kp),a(Kp,v3),a(To,y3),a(To,zo),a(zo,_3),a(M,b3),a(M,xo),a(xo,eh),a(eh,E3),a(xo,$3),a(xo,Go),a(Go,k3),Wd=!0},p(e,[l]){const Uo={};l&2&&(Uo.$$scope={dirty:l,ctx:e}),He.$set(Uo);const th={};l&2&&(th.$$scope={dirty:l,ctx:e}),wt.$set(th)},i(e){Wd||(g(Qt.$$.fragment,e),g(Kt.$$.fragment,e),g(ta.$$.fragment,e),g(aa.$$.fragment,e),g(ra.$$.fragment,e),g(oa.$$.fragment,e),g(sa.$$.fragment,e),g(ia.$$.fragment,e),g(na.$$.fragment,e),g(la.$$.fragment,e),g(pa.$$.fragment,e),g(He.$$.fragment,e),g(ha.$$.fragment,e),g(fa.$$.fragment,e),g(ma.$$.fragment,e),g(da.$$.fragment,e),g(Ea.$$.fragment,e),g(ka.$$.fragment,e),g(Ga.$$.fragment,e),g(Ua.$$.fragment,e),g(Sa.$$.fragment,e),g(Ia.$$.fragment,e),g(Ma.$$.fragment,e),g(Oa.$$.fragment,e),g(qa.$$.fragment,e),g(Fa.$$.fragment,e),g(Ra.$$.fragment,e),g(Ha.$$.fragment,e),g(Ya.$$.fragment,e),g(Va.$$.fragment,e),g(Xa.$$.fragment,e),g(Za.$$.fragment,e),g(Qa.$$.fragment,e),g(Ja.$$.fragment,e),g(er.$$.fragment,e),g(rr.$$.fragment,e),g(or.$$.fragment,e),g(hr.$$.fragment,e),g(fr.$$.fragment,e),g(mr.$$.fragment,e),g(dr.$$.fragment,e),g(cr.$$.fragment,e),g(ur.$$.fragment,e),g(wt.$$.fragment,e),g(wr.$$.fragment,e),g(vr.$$.fragment,e),g(yr.$$.fragment,e),g(_r.$$.fragment,e),g(br.$$.fragment,e),g(Er.$$.fragment,e),g($r.$$.fragment,e),g(kr.$$.fragment,e),g(Pr.$$.fragment,e),g(xr.$$.fragment,e),g(Ur.$$.fragment,e),g(Sr.$$.fragment,e),g(Ir.$$.fragment,e),g(Or.$$.fragment,e),g(qr.$$.fragment,e),g(Cr.$$.fragment,e),g(Fr.$$.fragment,e),g(Rr.$$.fragment,e),g(to.$$.fragment,e),g(ao.$$.fragment,e),g(no.$$.fragment,e),g(lo.$$.fragment,e),Wd=!0)},o(e){w(Qt.$$.fragment,e),w(Kt.$$.fragment,e),w(ta.$$.fragment,e),w(aa.$$.fragment,e),w(ra.$$.fragment,e),w(oa.$$.fragment,e),w(sa.$$.fragment,e),w(ia.$$.fragment,e),w(na.$$.fragment,e),w(la.$$.fragment,e),w(pa.$$.fragment,e),w(He.$$.fragment,e),w(ha.$$.fragment,e),w(fa.$$.fragment,e),w(ma.$$.fragment,e),w(da.$$.fragment,e),w(Ea.$$.fragment,e),w(ka.$$.fragment,e),w(Ga.$$.fragment,e),w(Ua.$$.fragment,e),w(Sa.$$.fragment,e),w(Ia.$$.fragment,e),w(Ma.$$.fragment,e),w(Oa.$$.fragment,e),w(qa.$$.fragment,e),w(Fa.$$.fragment,e),w(Ra.$$.fragment,e),w(Ha.$$.fragment,e),w(Ya.$$.fragment,e),w(Va.$$.fragment,e),w(Xa.$$.fragment,e),w(Za.$$.fragment,e),w(Qa.$$.fragment,e),w(Ja.$$.fragment,e),w(er.$$.fragment,e),w(rr.$$.fragment,e),w(or.$$.fragment,e),w(hr.$$.fragment,e),w(fr.$$.fragment,e),w(mr.$$.fragment,e),w(dr.$$.fragment,e),w(cr.$$.fragment,e),w(ur.$$.fragment,e),w(wt.$$.fragment,e),w(wr.$$.fragment,e),w(vr.$$.fragment,e),w(yr.$$.fragment,e),w(_r.$$.fragment,e),w(br.$$.fragment,e),w(Er.$$.fragment,e),w($r.$$.fragment,e),w(kr.$$.fragment,e),w(Pr.$$.fragment,e),w(xr.$$.fragment,e),w(Ur.$$.fragment,e),w(Sr.$$.fragment,e),w(Ir.$$.fragment,e),w(Or.$$.fragment,e),w(qr.$$.fragment,e),w(Cr.$$.fragment,e),w(Fr.$$.fragment,e),w(Rr.$$.fragment,e),w(to.$$.fragment,e),w(ao.$$.fragment,e),w(no.$$.fragment,e),w(lo.$$.fragment,e),Wd=!1},d(e){t(b),e&&t(A),e&&t($),v(Qt),e&&t(oh),e&&t(qe),e&&t(sh),e&&t(C),e&&t(ih),e&&t(Ce),e&&t(nh),e&&t(is),e&&t(lh),v(Kt,e),e&&t(ph),e&&t(L),e&&t(hh),e&&t(Le),e&&t(fh),v(ta,e),e&&t(mh),e&&t(We),e&&t(dh),v(aa,e),e&&t(ch),e&&t(ls),e&&t(uh),v(ra,e),e&&t(gh),e&&t(ps),e&&t(wh),v(oa,e),e&&t(vh),e&&t(hs),e&&t(yh),e&&t(fe),v(sa),e&&t(_h),e&&t(Fe),e&&t(bh),v(ia,e),e&&t(Eh),e&&t(Re),e&&t($h),v(na,e),e&&t(kh),v(la,e),e&&t(Ph),e&&t(fs),e&&t(Ah),v(pa,e),e&&t(Th),v(He,e),e&&t(zh),e&&t(me),v(ha),e&&t(xh),e&&t(Ve),e&&t(Gh),v(fa,e),e&&t(Uh),v(ma,e),e&&t(Sh),e&&t(ds),e&&t(Dh),e&&t(de),v(da),e&&t(jh),e&&t(cs),e&&t(Ih),e&&t(W),e&&t(Nh),e&&t(us),e&&t(Mh),e&&t(_a),e&&t(Oh),e&&t(ce),v(Ea),e&&t(qh),e&&t(gs),e&&t(Ch),e&&t(ws),e&&t(Lh),e&&t(vs),e&&t(Wh),e&&t(Qe),e&&t(Bh),e&&t(ys),e&&t(Fh),e&&t(B),e&&t(Rh),e&&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&&t(X),e&&t(Kf),e&&t(ei),e&&t(em),e&&t($e),v(rr),e&&t(tm),e&&t(ti),e&&t(am),e&&t(ft),e&&t(rm),e&&t(ai),e&&t(om),v(or,e),e&&t(sm),e&&t(Z),e&&t(im),e&&t(mt),e&&t(nm),e&&t(dt),e&&t(lm),e&&t(Q),e&&t(pm),e&&t(ri),e&&t(hm),e&&t(ke),v(hr),e&&t(fm),e&&t(ut),e&&t(mm),v(fr,e),e&&t(dm),v(mr,e),e&&t(cm),e&&t(oi),e&&t(um),v(dr,e),e&&t(gm),v(cr,e),e&&t(wm),e&&t(si),e&&t(vm),e&&t(Pe),v(ur),e&&t(ym),e&&t(ii),e&&t(_m),e&&t(z),e&&t(bm),e&&t(pi),e&&t(Em),v(wt,e),e&&t($m),v(wr,e),e&&t(km),e&&t(vt),e&&t(Pm),v(vr,e),e&&t(Am),v(yr,e),e&&t(Tm),e&&t(hi),e&&t(zm),v(_r,e),e&&t(xm),v(br,e),e&&t(Gm),e&&t(fi),e&&t(Um),e&&t(mi),e&&t(Sm),e&&t(Ae),v(Er),e&&t(Dm),e&&t(Te),v($r),e&&t(jm),e&&t(J),e&&t(Im),v(kr,e),e&&t(Nm),e&&t(gi),e&&t(Mm),v(Pr,e),e&&t(Om),e&&t(P),e&&t(qm),e&&t(bt),e&&t(Cm),v(xr,e),e&&t(Lm),e&&t(Et),e&&t(Wm),e&&t(ze),v(Ur),e&&t(Bm),e&&t(vi),e&&t(Fm),e&&t(kt),e&&t(Rm),e&&t(xe),v(Sr),e&&t(Hm),e&&t(At),e&&t(Ym),e&&t(Ei),e&&t(Vm),e&&t(Tt),e&&t(Xm),e&&t(zt),e&&t(Zm),e&&t(ki),e&&t(Qm),e&&t(j),v(Ir),e&&t(Jm),e&&t(Ue),v(Or),e&&t(Km),e&&t(Ti),e&&t(ed),e&&t(Se),v(qr),e&&t(td),e&&t(zi),e&&t(ad),e&&t(Ut),e&&t(rd),e&&t(xi),e&&t(od),e&&t(Gi),e&&t(sd),e&&t(De),v(Cr),e&&t(id),e&&t(Dt),e&&t(nd),e&&t(jt),e&&t(ld),e&&t(Ui),e&&t(pd),e&&t(K),e&&t(hd),e&&t(Si),e&&t(fd),e&&t(je),v(Fr),e&&t(md),e&&t(Ie),v(Rr),e&&t(dd),e&&t(Di),e&&t(cd),e&&t(ji),e&&t(ud),e&&t(Ii),e&&t(gd),e&&t(Ni),e&&t(wd),e&&t(Mt),e&&t(vd),e&&t(Oi),e&&t(yd),e&&t(qi),e&&t(_d),e&&t(Ci),e&&t(bd),e&&t(Li),e&&t(Ed),e&&t(ee),e&&t($d),e&&t(E),e&&t(kd),e&&t(Ne),v(to),e&&t(Pd),e&&t(Bi),e&&t(Ad),e&&t(qt),e&&t(Td),e&&t(Me),v(ao),e&&t(zd),e&&t(I),e&&t(xd),e&&t(Lt),e&&t(Gd),v(no,e),e&&t(Ud),e&&t(Ri),e&&t(Sd),e&&t(Oe),v(lo),e&&t(Dd),e&&t(Bt),e&&t(jd),e&&t(q),e&&t(Id),e&&t(Hi),e&&t(Nd),e&&t(fo),e&&t(Md),e&&t(Ft),e&&t(Od),e&&t(mo),e&&t(qd),e&&t(N),e&&t(Cd),e&&t(Eo),e&&t(Ld),e&&t(M)}}}const rk={local:"efficient-training-on-a-single-gpu",sections:[{local:"load-model",title:"Load Model"},{local:"vanilla-training",title:"Vanilla Training"},{local:"anatomy-of-models-operations",title:"Anatomy of Model's Operations"},{local:"anatomy-of-models-memory",title:"Anatomy of Model's Memory"},{local:"batch-sizes",title:"Batch sizes"},{local:"gradient-accumulation",title:"Gradient Accumulation"},{local:"gradient-checkpointing",title:"Gradient Checkpointing"},{local:"floating-data-types",sections:[{local:"fp16-training",title:"FP16 Training"},{local:"bf16",title:"BF16"},{local:"tf32",title:"TF32"}],title:"Floating Data Types"},{local:"optimizer",sections:[{local:"adafactor",title:"Adafactor"},{local:"8bit-adam",title:"8-bit Adam"},{local:"multitensor",title:"`_multi_tensor`"}],title:"Optimizer"},{local:"using-accelerate",title:"Using \u{1F917} Accelerate"},{local:"dataloader",title:"DataLoader"},{local:"deepspeed-zero",title:"DeepSpeed ZeRO"},{local:"choice-of-gpu",title:"Choice of GPU"},{local:"how-to-scale",title:"How to scale"},{local:"efficient-software-prebuilds",title:"Efficient Software Prebuilds"},{local:"sparsity",sections:[{local:"mixture-of-experts",title:"Mixture of Experts"}],title:"Sparsity"},{local:"scaling-beyond-a-single-gpu",title:"Scaling beyond a single GPU"},{local:"using-pytorch-native-attention",title:"Using PyTorch native attention"},{local:"using-torchcompile",title:"Using torch.compile"}],title:"Efficient Training on a Single GPU"};function ok(Do){return K6(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class pk extends X6{constructor(b){super();Z6(this,b,ok,ak,Q6,{})}}export{pk as default,rk as metadata};
