import{S as r6,i as o6,s as s6,e as r,k as h,w as d,t as i,M as i6,c as o,d as t,m,a as s,x as c,h as n,b as f,N as K2,G as a,g as p,y as u,q as g,o as w,B as v,v as n6}from"../chunks/vendor-hf-doc-builder.js";import{T as a6}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 l6(bo){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 p6(bo){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 h6(bo){let b,A,$,U,nn,Ht,Hc,ln,Yc,Wp,Me,Vc,Eo,Xc,Zc,Bp,q,Qc,$o,Jc,Kc,Yt,eu,tu,Fp,Oe,pn,ae,ko,au,ru,Po,ou,su,Ao,iu,nu,k,re,To,lu,pu,zo,hu,mu,xo,fu,du,oe,Go,cu,uu,Uo,gu,wu,So,vu,yu,se,jo,_u,bu,Do,Eu,$u,Io,ku,Pu,ie,No,Au,Tu,Mo,zu,xu,Oo,Gu,Uu,ne,qo,Su,ju,Co,Du,Iu,Lo,Nu,Mu,le,Wo,Ou,qu,Bo,Cu,Lu,Fo,Wu,Bu,pe,Ro,Fu,Ru,Ho,Hu,Yu,Yo,Vu,Rp,Vo,Xu,Hp,Vt,Yp,C,Zu,hn,Qu,Ju,mn,Ku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r,S1,j1,Vr,D1,I1,Gi,N1,M1,ld,Ie,Nt,_p,Xr,O1,bp,q1,pd,Ui,C1,hd,Mt,L1,Si,W1,B1,md,Ne,Ot,Ep,Zr,F1,$p,R1,fd,qt,H1,Qr,Y1,V1,dd,O,kp,X1,Z1,Jr,Q1,J1,Pp,K1,e2,cd,ji,t2,ud,Kr,Ap,a2,r2,gd,Ct,Di,Tp,o2,s2,i2,Ii,zp,n2,l2,wd,eo,xp,p2,h2,vd,I,to,Gp,m2,f2,ao,d2,c2,ro,Up,u2,g2,oo,w2,v2,so,Sp,y2,_2,io,b2,E2,no,jp,$2,k2,lo,P2,yd,po,Dp,A2,T2,_d,N,ho,Ip,z2,x2,mo,G2,U2,fo,Np,S2,j2,co,D2,I2,uo,Mp,N2,M2,go,O2,q2,wo,Op,C2,L2,vo,W2,bd;return Ht=new _({}),Vt=new y({props:{code:"pip install transformers datasets accelerate nvidia-ml-py3",highlighted:"pip install transformers datasets accelerate nvidia-ml-py3"}}),Xt=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>)`}}),Zt=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()`}}),Qt=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.`}}),Jt=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.`}}),Kt=new _({}),ea=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.`}}),ta=new y({props:{code:"nvidia-smi",highlighted:"nvidia-smi"}}),aa=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 |
+-----------------------------------------------------------------------------+`}}),ra=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>,
}`}}),Fe=new a6({props:{$$slots:{default:[l6]},$$scope:{ctx:bo}}}),oa=new _({}),sa=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)`}}),ia=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.`}}),na=new _({}),ga=new _({}),va=new _({}),ka=new _({}),Pa=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)`}}),Aa=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.`}}),xa=new _({}),Ua=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)`}}),Sa=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.`}}),ja=new _({}),Oa=new _({}),qa=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)`}}),Ca=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.`}}),La=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)`}}),Wa=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.`}}),Ba=new _({}),Fa=new y({props:{code:"TrainingArguments(bf16=True)",highlighted:'TrainingArguments(bf16=<span class="hljs-literal">True</span>)'}}),Ra=new _({}),Ha=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`}}),Va=new y({props:{code:"TrainingArguments(tf32=True)",highlighted:'TrainingArguments(tf32=<span class="hljs-literal">True</span>)'}}),Qa=new _({}),Ja=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}]`}}),or=new _({}),sr=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)`}}),ir=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.`}}),nr=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)`}}),lr=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.`}}),pr=new _({}),ut=new a6({props:{$$slots:{default:[p6]},$$scope:{ctx:bo}}}),mr=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,
)`}}),fr=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)`}}),dr=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.`}}),cr=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)`}}),ur=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.`}}),gr=new _({}),wr=new _({}),vr=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,
)`}}),yr=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()`}}),$r=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.`}}),Pr=new _({}),Ar=new _({}),xr=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>)'}}),Sr=new _({}),jr=new _({}),Dr=new _({}),Or=new _({}),qr=new _({}),Xr=new _({}),Zr=new _({}),{c(){b=r("meta"),A=h(),$=r("h1"),U=r("a"),nn=r("span"),d(Ht.$$.fragment),Hc=h(),ln=r("span"),Yc=i("Efficient Training on a Single GPU"),Wp=h(),Me=r("p"),Vc=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 "),Eo=r("a"),Xc=i("multi-GPU section"),Zc=i("."),Bp=h(),q=r("p"),Qc=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 "),$o=r("a"),Jc=i("Trainer"),Kc=i(" and "),Yt=r("a"),eu=i("\u{1F917} Accelerate"),tu=i(". Each method can improve speed or memory usage which is summarized in the table below:"),Fp=h(),Oe=r("table"),pn=r("thead"),ae=r("tr"),ko=r("th"),au=i("Method"),ru=h(),Po=r("th"),ou=i("Speed"),su=h(),Ao=r("th"),iu=i("Memory"),nu=h(),k=r("tbody"),re=r("tr"),To=r("td"),lu=i("Gradient accumulation"),pu=h(),zo=r("td"),hu=i("No"),mu=h(),xo=r("td"),fu=i("Yes"),du=h(),oe=r("tr"),Go=r("td"),cu=i("Gradient checkpointing"),uu=h(),Uo=r("td"),gu=i("No"),wu=h(),So=r("td"),vu=i("Yes"),yu=h(),se=r("tr"),jo=r("td"),_u=i("Mixed precision training"),bu=h(),Do=r("td"),Eu=i("Yes"),$u=h(),Io=r("td"),ku=i("(No)"),Pu=h(),ie=r("tr"),No=r("td"),Au=i("Batch size"),Tu=h(),Mo=r("td"),zu=i("Yes"),xu=h(),Oo=r("td"),Gu=i("Yes"),Uu=h(),ne=r("tr"),qo=r("td"),Su=i("Optimizer choice"),ju=h(),Co=r("td"),Du=i("Yes"),Iu=h(),Lo=r("td"),Nu=i("Yes"),Mu=h(),le=r("tr"),Wo=r("td"),Ou=i("DataLoader"),qu=h(),Bo=r("td"),Cu=i("Yes"),Lu=h(),Fo=r("td"),Wu=i("No"),Bu=h(),pe=r("tr"),Ro=r("td"),Fu=i("DeepSpeed Zero"),Ru=h(),Ho=r("td"),Hu=i("No"),Yu=h(),Yo=r("td"),Vu=i("Yes"),Rp=h(),Vo=r("p"),Xu=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:"),Hp=h(),d(Vt.$$.fragment),Yp=h(),C=r("p"),Zu=i("The "),hn=r("code"),Qu=i("nvidia-ml-py3"),Ju=i(" library allows us to monitor the memory usage of the models from within Python. You might be familiar with the "),mn=r("code"),Ku=i("nvidia-smi"),eg=i(" command in the terminal - this library allows to access the same information in Python directly."),Vp=h(),qe=r("p"),tg=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 "),fn=r("code"),ag=i("Dataset"),rg=i(" with PyTorch format."),Xp=h(),d(Xt.$$.fragment),Zp=h(),Ce=r("p"),og=i("We want to print some summary statistics for the GPU utilization and the training run with the "),Xo=r("a"),sg=i("Trainer"),ig=i(". We setup a two helper functions to do just that:"),Qp=h(),d(Zt.$$.fragment),Jp=h(),Zo=r("p"),ng=i("Let\u2019s verify that we start with a free GPU memory:"),Kp=h(),d(Qt.$$.fragment),eh=h(),Qo=r("p"),lg=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."),th=h(),d(Jt.$$.fragment),ah=h(),Jo=r("p"),pg=i("We see that the kernels alone take up 1.3GB of GPU memory. Now let\u2019s see how much space the model uses."),rh=h(),he=r("h2"),Le=r("a"),dn=r("span"),d(Kt.$$.fragment),hg=h(),cn=r("span"),mg=i("Load Model"),oh=h(),We=r("p"),fg=i("First, we load the "),un=r("code"),dg=i("bert-large-uncased"),cg=i(" model. We load the model weights directly to the GPU so that we can check how much space just weights use."),sh=h(),d(ea.$$.fragment),ih=h(),Be=r("p"),ug=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 "),gn=r("code"),gg=i("nvidia-smi"),wg=i(" CLI:"),nh=h(),d(ta.$$.fragment),lh=h(),d(aa.$$.fragment),ph=h(),Ko=r("p"),vg=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:"),hh=h(),d(ra.$$.fragment),mh=h(),d(Fe.$$.fragment),fh=h(),me=r("h2"),Re=r("a"),wn=r("span"),d(oa.$$.fragment),yg=h(),vn=r("span"),_g=i("Vanilla Training"),dh=h(),He=r("p"),bg=i("As a first experiment we will use the "),es=r("a"),Eg=i("Trainer"),$g=i(" and train the model without any further modifications and a batch size of 4:"),ch=h(),d(sa.$$.fragment),uh=h(),d(ia.$$.fragment),gh=h(),ts=r("p"),kg=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."),wh=h(),fe=r("h2"),Ye=r("a"),yn=r("span"),d(na.$$.fragment),Pg=h(),_n=r("span"),Ag=i("Anatomy of Model's Operations"),vh=h(),as=r("p"),Tg=i("Transformers architecture includes 3 main groups of operations grouped below by compute-intensity."),yh=h(),L=r("ol"),la=r("li"),bn=r("p"),En=r("strong"),zg=i("Tensor Contractions"),xg=h(),pa=r("p"),Gg=i("Linear layers and components of Multi-Head Attention all do batched "),$n=r("strong"),Ug=i("matrix-matrix multiplications"),Sg=i(". These operations are the most compute-intensive part of training a transformer."),jg=h(),ha=r("li"),kn=r("p"),Pn=r("strong"),Dg=i("Statistical Normalizations"),Ig=h(),ma=r("p"),Ng=i("Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more "),An=r("strong"),Mg=i("reduction operations"),Og=i(", the result of which is then applied via a map."),qg=h(),fa=r("li"),Tn=r("p"),zn=r("strong"),Cg=i("Element-wise Operators"),Lg=h(),da=r("p"),Wg=i("These are the remaining operators: "),xn=r("strong"),Bg=i("biases, dropout, activations, and residual connections"),Fg=i(". These are the least compute-intensive operations."),_h=h(),rs=r("p"),Rg=i("This knowledge can be helpful to know when analyzing performance bottlenecks."),bh=h(),ca=r("p"),Hg=i("This summary is derived from "),ua=r("a"),Yg=i("Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020"),Eh=h(),de=r("h2"),Ve=r("a"),Gn=r("span"),d(ga.$$.fragment),Vg=h(),Un=r("span"),Xg=i("Anatomy of Model's Memory"),$h=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
`),os=r("p"),Zg=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."),kh=h(),ss=r("p"),Qg=i("Let\u2019s look at the details."),Ph=h(),is=r("p"),Sn=r("strong"),Jg=i("Model Weights:"),Ah=h(),Xe=r("ul"),jn=r("li"),Kg=i("4 bytes * number of parameters for fp32 training"),ew=h(),Dn=r("li"),tw=i("6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)"),Th=h(),ns=r("p"),In=r("strong"),aw=i("Optimizer States:"),zh=h(),W=r("ul"),Nn=r("li"),rw=i("8 bytes * number of parameters for normal AdamW (maintains 2 states)"),ow=h(),ls=r("li"),sw=i("2 bytes * number of parameters for 8-bit AdamW optimizers like "),wa=r("a"),iw=i("bitsandbytes"),nw=h(),Mn=r("li"),lw=i("4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)"),xh=h(),ps=r("p"),On=r("strong"),pw=i("Gradients"),Gh=h(),hs=r("ul"),qn=r("li"),hw=i("4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)"),Uh=h(),ms=r("p"),Cn=r("strong"),mw=i("Forward Activations"),Sh=h(),fs=r("ul"),Ln=r("li"),fw=i("size depends on many factors, the key ones being sequence length, hidden size and batch size."),jh=h(),ds=r("p"),dw=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."),Dh=h(),cs=r("p"),Wn=r("strong"),cw=i("Temporary Memory"),Ih=h(),us=r("p"),uw=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."),Nh=h(),gs=r("p"),Bn=r("strong"),gw=i("Functionality-specific memory"),Mh=h(),ws=r("p"),ww=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."),Oh=h(),vs=r("p"),Ze=r("strong"),Fn=r("code"),vw=i("forward"),yw=i(" vs "),Rn=r("code"),_w=i("backward"),bw=i(" Execution Speed"),qh=h(),ys=r("p"),Ew=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)."),Ch=h(),_s=r("p"),$w=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."),Lh=h(),ce=r("h2"),Qe=r("a"),Hn=r("span"),d(va.$$.fragment),kw=h(),Yn=r("span"),Pw=i("Batch sizes"),Wh=h(),bs=r("p"),Aw=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."),Bh=h(),B=r("p"),Tw=i("For example for fully connected layers (which correspond to GEMMs), NVIDIA provides recommendations for "),ya=r("a"),zw=i("input/output neuron counts"),xw=i(" and "),_a=r("a"),Gw=i("batch size"),Uw=i("."),Fh=h(),ba=r("p"),Ea=r("a"),Sw=i("Tensor Core Requirements"),jw=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!"),Rh=h(),Je=r("p"),Dw=i("For parameters that are small, there is also "),$a=r("a"),Iw=i("Dimension Quantization Effects"),Nw=i(" to consider, this is where tiling happens and the right multiplier can have a significant speedup."),Hh=h(),ue=r("h2"),Ke=r("a"),Vn=r("span"),d(ka.$$.fragment),Mw=h(),Xn=r("span"),Ow=i("Gradient Accumulation"),Yh=h(),Es=r("p"),qw=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."),Vh=h(),S=r("p"),Cw=i("We can use gradient accumulation in the "),$s=r("a"),Lw=i("Trainer"),Ww=i(" by simply adding the "),Zn=r("code"),Bw=i("gradient_accumulation_steps"),Fw=i(" argument to "),ks=r("a"),Rw=i("TrainingArguments"),Hw=i(". Let\u2019s see how it impacts the models memory footprint:"),Xh=h(),d(Pa.$$.fragment),Zh=h(),d(Aa.$$.fragment),Qh=h(),T=r("p"),Yw=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 "),Qn=r("code"),Vw=i("per_device_train_batch_size=1"),Xw=i(" and "),Jn=r("code"),Zw=i("gradient_accumulation_steps=64"),Qw=i(" but instead "),Kn=r("code"),Jw=i("per_device_train_batch_size=4"),Kw=i(" and "),el=r("code"),ev=i("gradient_accumulation_steps=16"),tv=i(" which has the same effective batch size while making better use of the available GPU resources."),Jh=h(),F=r("p"),av=i("For more details see the benchmarks for "),Ta=r("a"),rv=i("RTX-3090"),ov=i(`
and `),za=r("a"),sv=i("A100"),iv=i("."),Kh=h(),Ps=r("p"),nv=i("Next we have a look at another trick to save a little bit more GPU memory called gradient checkpointing."),em=h(),ge=r("h2"),et=r("a"),tl=r("span"),d(xa.$$.fragment),lv=h(),al=r("span"),pv=i("Gradient Checkpointing"),tm=h(),As=r("p"),hv=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."),am=h(),tt=r("p"),mv=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 "),Ga=r("a"),fv=i("this great article"),dv=i(" explaining the ideas behind gradient checkpointing."),rm=h(),R=r("p"),cv=i("To enable gradient checkpointing in the "),Ts=r("a"),uv=i("Trainer"),gv=i(" we only need to pass it as a flag to the "),zs=r("a"),wv=i("TrainingArguments"),vv=i(". Everything else is handled under the hood:"),om=h(),d(Ua.$$.fragment),sm=h(),d(Sa.$$.fragment),im=h(),xs=r("p"),yv=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."),nm=h(),we=r("h2"),at=r("a"),rl=r("span"),d(ja.$$.fragment),_v=h(),ol=r("span"),bv=i("Floating Data Types"),lm=h(),Gs=r("p"),Ev=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:"),pm=h(),j=r("ul"),Da=r("li"),$v=i("fp32 ("),sl=r("code"),kv=i("float32"),Pv=i(")"),Av=h(),Ia=r("li"),Tv=i("fp16 ("),il=r("code"),zv=i("float16"),xv=i(")"),Gv=h(),Na=r("li"),Uv=i("bf16 ("),nl=r("code"),Sv=i("bfloat16"),jv=i(")"),Dv=h(),ll=r("li"),Iv=i("tf32 (CUDA internal data type)"),hm=h(),Us=r("p"),Nv=i("Here is a diagram that shows how these data types correlate to each other."),mm=h(),ve=r("p"),Ss=r("img"),Mv=i(`
(source: `),Ma=r("a"),Ov=i("NVIDIA Blog"),qv=i(")"),fm=h(),js=r("p"),Cv=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/"),dm=h(),ye=r("h3"),rt=r("a"),pl=r("span"),d(Oa.$$.fragment),Lv=h(),hl=r("span"),Wv=i("FP16 Training"),cm=h(),H=r("p"),Bv=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 "),ml=r("code"),Fv=i("fp16"),Rv=i(" flag to "),fl=r("code"),Hv=i("True"),Yv=i(":"),um=h(),d(qa.$$.fragment),gm=h(),d(Ca.$$.fragment),wm=h(),Ds=r("p"),Vv=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:"),vm=h(),d(La.$$.fragment),ym=h(),d(Wa.$$.fragment),_m=h(),Is=r("p"),Xv=i("We can see that with these tweaks we use about half the GPU memory as at the beginning while also being slightly faster."),bm=h(),_e=r("h3"),ot=r("a"),dl=r("span"),d(Ba.$$.fragment),Zv=h(),cl=r("span"),Qv=i("BF16"),Em=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"),Ns=r("p"),Jv=i("You can enable BF16 in the \u{1F917} Trainer with:"),$m=h(),d(Fa.$$.fragment),km=h(),be=r("h3"),st=r("a"),ul=r("span"),d(Ra.$$.fragment),Kv=h(),gl=r("span"),ey=i("TF32"),Pm=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.
`),Ms=r("p"),ty=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:"),Am=h(),d(Ha.$$.fragment),Tm=h(),Os=r("p"),ay=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."),zm=h(),it=r("p"),ry=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 "),Ya=r("a"),oy=i("NVIDIA research"),sy=i(" the majority of machine learning training shouldn\u2019t be impacted and showed the same perplexity and convergence as the fp32 training."),xm=h(),qs=r("p"),iy=i("If you\u2019re already using fp16 or bf16 mixed precision it may help with the throughput as well."),Gm=h(),Cs=r("p"),ny=i("You can enable this mode in the \u{1F917} Trainer with:"),Um=h(),d(Va.$$.fragment),Sm=h(),Ls=r("p"),ly=i("By default the PyTorch default is used."),jm=h(),Y=r("p"),py=i("Note: tf32 mode is internal to CUDA and can\u2019t be accessed directly via "),wl=r("code"),hy=i("tensor.to(dtype=torch.tf32)"),my=i(" as "),vl=r("code"),fy=i("torch.tf32"),dy=i(" doesn\u2019t exist."),Dm=h(),nt=r("p"),cy=i("Note: you need "),yl=r("code"),uy=i("torch>=1.7"),gy=i(" to enjoy this feature."),Im=h(),V=r("p"),wy=i(`You can also see a variety of benchmarks on tf32 vs other precisions:
`),Xa=r("a"),vy=i("RTX-3090"),yy=i(` and
`),Za=r("a"),_y=i("A100"),by=i("."),Nm=h(),Ws=r("p"),Ey=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."),Mm=h(),Ee=r("h2"),lt=r("a"),_l=r("span"),d(Qa.$$.fragment),$y=h(),bl=r("span"),ky=i("Optimizer"),Om=h(),Bs=r("p"),Py=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."),qm=h(),pt=r("p"),Ay=i("HF Trainer integrates a variety of optimisers that can be used out of box. To activate the desired optimizer simply pass the "),El=r("code"),Ty=i("--optim"),zy=i(" flag to the command line."),Cm=h(),Fs=r("p"),xy=i("To see which optimizers are currently supported:"),Lm=h(),d(Ja.$$.fragment),Wm=h(),X=r("p"),Gy=i("For example, if you have "),Ka=r("a"),Uy=i("NVIDIA/apex"),Sy=i(" installed "),$l=r("code"),jy=i("--optim adamw_apex_fused"),Dy=i(" will give you the fastest training experience among all supported AdamW optimizers."),Bm=h(),ht=r("p"),Iy=i("On the other hand "),er=r("a"),Ny=i("8bit BNB optimizer"),My=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."),Fm=h(),mt=r("p"),Oy=i("Let\u2019s get a feel for the numbers and use for example use a 3B-parameter model, like "),kl=r("code"),qy=i("t5-3b"),Cy=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:"),Rm=h(),Z=r("ul"),tr=r("li"),Ly=i("A standard AdamW uses 8 bytes for each parameter, here the optimizer will need ("),Pl=r("code"),Wy=i("8*3"),By=i(") 24GB of GPU memory."),Fy=h(),ar=r("li"),Ry=i("Adafactor uses slightly more than 4 bytes, so ("),Al=r("code"),Hy=i("4*3"),Yy=i(") 12GB and then some extra."),Vy=h(),rr=r("li"),Xy=i("8bit BNB quantized optimizer will use only ("),Tl=r("code"),Zy=i("2*3"),Qy=i(") 6GB if all optimizer states are quantized."),Hm=h(),Rs=r("p"),Jy=i("Let\u2019s have a look at Adafactor first."),Ym=h(),$e=r("h3"),ft=r("a"),zl=r("span"),d(or.$$.fragment),Ky=h(),xl=r("span"),e_=i("Adafactor"),Vm=h(),dt=r("p"),t_=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 "),Gl=r("code"),a_=i('optim="adafactor"'),r_=i(":"),Xm=h(),d(sr.$$.fragment),Zm=h(),d(ir.$$.fragment),Qm=h(),Hs=r("p"),o_=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:"),Jm=h(),d(nr.$$.fragment),Km=h(),d(lr.$$.fragment),ef=h(),Ys=r("p"),s_=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."),tf=h(),ke=r("h3"),ct=r("a"),Ul=r("span"),d(pr.$$.fragment),i_=h(),Sl=r("span"),n_=i("8-bit Adam"),af=h(),Vs=r("p"),l_=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."),rf=h(),z=r("p"),p_=i("In contrast to the previous approaches is this one not integrated into the "),Xs=r("a"),h_=i("Trainer"),m_=i(" as a simple flag. We need to install the 8-bit optimizer and then pass it as a custom optimizer to the "),Zs=r("a"),f_=i("Trainer"),d_=i(". Follow the installation guide in the Github "),hr=r("a"),c_=i("repo"),u_=i(" to install the "),jl=r("code"),g_=i("bitsandbytes"),w_=i(" library that implements the 8-bit Adam optimizer."),of=h(),Qs=r("p"),v_=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."),sf=h(),d(ut.$$.fragment),nf=h(),d(mr.$$.fragment),lf=h(),gt=r("p"),y_=i("We can now pass the custom optimizer as an argument to the "),Dl=r("code"),__=i("Trainer"),b_=i(":"),pf=h(),d(fr.$$.fragment),hf=h(),d(dr.$$.fragment),mf=h(),Js=r("p"),E_=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:"),ff=h(),d(cr.$$.fragment),df=h(),d(ur.$$.fragment),cf=h(),Ks=r("p"),$_=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:"),uf=h(),ei=r("p"),ti=r("img"),gf=h(),Pe=r("h3"),wt=r("a"),Il=r("span"),d(gr.$$.fragment),k_=h(),Nl=r("span"),Ml=r("code"),P_=i("_multi_tensor"),wf=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
`),Ae=r("h2"),vt=r("a"),Ol=r("span"),d(wr.$$.fragment),A_=h(),ql=r("span"),T_=i("Using \u{1F917} Accelerate"),vf=h(),Q=r("p"),z_=i("So far we have used the "),ai=r("a"),x_=i("Trainer"),G_=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 "),ri=r("a"),U_=i("TrainingArguments"),S_=i(" to wrap the training settings:"),yf=h(),d(vr.$$.fragment),_f=h(),oi=r("p"),j_=i("The full example training loop with \u{1F917} Accelerate is only a handful of lines of code long:"),bf=h(),d(yr.$$.fragment),Ef=h(),P=r("p"),D_=i("First we wrap the dataset in a "),_r=r("a"),Cl=r("code"),I_=i("DataLoader"),N_=i(". Then we can enable gradient checkpointing by calling the model\u2019s "),si=r("a"),M_=i("gradient_checkpointing_enable()"),O_=i(" method. When we initialize the "),br=r("a"),Ll=r("code"),q_=i("Accelerator"),C_=i(" we can specify if we want to use mixed precision training and it will take care of it for us in the "),Wl=r("code"),L_=i("prepare"),W_=i(" call. During the "),Er=r("a"),Bl=r("code"),B_=i("prepare"),F_=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."),$f=h(),yt=r("p"),R_=i("Finally, we can write the main training loop. Note that the "),Fl=r("code"),H_=i("backward"),Y_=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:"),kf=h(),d($r.$$.fragment),Pf=h(),_t=r("p"),V_=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 "),kr=r("a"),X_=i("Accelerate documentation"),Z_=i("."),Af=h(),Te=r("h2"),bt=r("a"),Rl=r("span"),d(Pr.$$.fragment),Q_=h(),Hl=r("span"),J_=i("DataLoader"),Tf=h(),ii=r("p"),K_=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."),zf=h(),Et=r("ul"),ni=r("li"),Yl=r("code"),eb=i("DataLoader(pin_memory=True, ...)"),tb=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."),ab=h(),li=r("li"),Vl=r("code"),rb=i("DataLoader(num_workers=4, ...)"),ob=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."),xf=h(),ze=r("h2"),$t=r("a"),Xl=r("span"),d(Ar.$$.fragment),sb=h(),Zl=r("span"),ib=i("DeepSpeed ZeRO"),Gf=h(),kt=r("p"),nb=i("The in-depth details on how to use Deepspeed can be found "),pi=r("a"),lb=i("here"),pb=i("."),Uf=h(),hi=r("p"),hb=i("First, a quick decision tree:"),Sf=h(),Pt=r("ol"),Ql=r("li"),mb=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."),fb=h(),Jl=r("li"),db=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."),jf=h(),At=r("p"),cb=i("Now if the decision tree suggested you use DeepSpeed first you need to "),mi=r("a"),ub=i("install it"),gb=i(", then follow one of the following guides to create a configuration file and launch DeepSpeed."),Df=h(),fi=r("p"),wb=i("Activation:"),If=h(),D=r("ul"),Kl=r("li"),Tr=r("p"),vb=i("HF Trainer-based examples: see this "),di=r("a"),yb=i("guide"),_b=i("."),bb=h(),zr=r("li"),ep=r("p"),Eb=i("Custom HF Trainer-based program: Same as above, but pass:"),$b=h(),d(xr.$$.fragment),kb=h(),tp=r("li"),Gr=r("p"),Pb=i("Deployment in Notebooks: see this "),ci=r("a"),Ab=i("guide"),Tb=i("."),zb=h(),ap=r("li"),xe=r("p"),xb=i("Custom training loop: This is somewhat complex but you can study how this is implemented in "),Ur=r("a"),Gb=i("HF Trainer"),Ub=i(" - simply search for "),rp=r("code"),Sb=i("deepspeed"),jb=i(" in the code."),Nf=h(),Ge=r("h2"),Tt=r("a"),op=r("span"),d(Sr.$$.fragment),Db=h(),sp=r("span"),Ib=i("Choice of GPU"),Mf=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.
`),ui=r("p"),Nb=i("Now, let\u2019s take a step back and discuss what we should optimize for when scaling the training of large models."),Of=h(),Ue=r("h2"),zt=r("a"),ip=r("span"),d(jr.$$.fragment),Mb=h(),np=r("span"),Ob=i("How to scale"),qf=h(),gi=r("p"),qb=i("When we train models there are a two aspects we want to optimize at the same time:"),Cf=h(),xt=r("ul"),lp=r("li"),Cb=i("Data throughput/training time"),Lb=h(),pp=r("li"),Wb=i("Model performance"),Lf=h(),wi=r("p"),Bb=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."),Wf=h(),vi=r("p"),Fb=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."),Bf=h(),Se=r("h2"),Gt=r("a"),hp=r("span"),d(Dr.$$.fragment),Rb=h(),mp=r("span"),Hb=i("Efficient Software Prebuilds"),Ff=h(),Ut=r("p"),Yb=i("PyTorch\u2019s "),Ir=r("a"),Vb=i("pip and conda builds"),Xb=i(" come prebuit with the cuda toolkit which is enough to run PyTorch, but it is insufficient if you need to build cuda extensions."),Rf=h(),St=r("p"),Zb=i("At times it may take an additional effort to pre-build some components, e.g., if you\u2019re using libraries like "),fp=r("code"),Qb=i("apex"),Jb=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."),Hf=h(),yi=r("p"),Kb=i("This approach is also useful if you want to tweak the pytorch source and/or make a new customized build."),Yf=h(),J=r("p"),e1=i("To find the docker image version you want start "),Nr=r("a"),t1=i("here"),a1=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 "),Mr=r("a"),r1=i("the index of all PyTorch NGC images"),o1=i("."),Vf=h(),_i=r("p"),s1=i("Next follow the instructions to download and deploy the docker image."),Xf=h(),je=r("h2"),jt=r("a"),dp=r("span"),d(Or.$$.fragment),i1=h(),cp=r("span"),n1=i("Sparsity"),Zf=h(),De=r("h3"),Dt=r("a"),up=r("span"),d(qr.$$.fragment),l1=h(),gp=r("span"),p1=i("Mixture of Experts"),Qf=h(),bi=r("p"),h1=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.`),Jf=h(),Ei=r("p"),m1=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."),Kf=h(),$i=r("p"),f1=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."),ed=h(),ki=r("p"),Pi=r("img"),td=h(),It=r("p"),d1=i("(source: "),Cr=r("a"),c1=i("GLAM"),u1=i(")"),ad=h(),Ai=r("p"),g1=i("You can find exhaustive details and comparison tables in the papers listed at the end of this section."),rd=h(),Ti=r("p"),w1=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."),od=h(),zi=r("p"),v1=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."),sd=h(),xi=r("p"),y1=i("Most related papers and implementations are built around Tensorflow/TPUs:"),id=h(),K=r("ul"),wp=r("li"),Lr=r("a"),_1=i("GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding"),b1=h(),vp=r("li"),Wr=r("a"),E1=i("Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity"),$1=h(),yp=r("li"),Br=r("a"),k1=i("GLaM: Generalist Language Model (GLaM)"),nd=h(),E=r("p"),P1=i("And for Pytorch DeepSpeed has built one as well: "),Fr=r("a"),A1=i("DeepSpeed-MoE: Advancing Mixture-of-Experts Inference and Training to Power Next-Generation AI Scale"),T1=i(", "),Rr=r("a"),z1=i("Mixture of Experts"),x1=i(" - blog posts:  "),Hr=r("a"),G1=i("1"),U1=i(", "),Yr=r("a"),S1=i("2"),j1=i(" and specific deployment with large transformer-based natural language generation models: "),Vr=r("a"),D1=i("blog post"),I1=i(", "),Gi=r("a"),N1=i("Megatron-Deepspeed branch"),M1=i("."),ld=h(),Ie=r("h2"),Nt=r("a"),_p=r("span"),d(Xr.$$.fragment),O1=h(),bp=r("span"),q1=i("Scaling beyond a single GPU"),pd=h(),Ui=r("p"),C1=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."),hd=h(),Mt=r("p"),L1=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 "),Si=r("a"),W1=i("\u201CMulti-GPU training\u201D section"),B1=i("."),md=h(),Ne=r("h2"),Ot=r("a"),Ep=r("span"),d(Zr.$$.fragment),F1=h(),$p=r("span"),R1=i("Using torch.compile"),fd=h(),qt=r("p"),H1=i("PyTorch 2.0 introduces a new compile function, you can learn more about it "),Qr=r("a"),Y1=i("in their documentation"),V1=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."),dd=h(),O=r("p"),kp=r("code"),X1=i("torch.compile"),Z1=i(" has a growing list of backends, which can be found in "),Jr=r("a"),Q1=i("backends.py"),J1=i(`
or `),Pp=r("code"),K1=i("torchdynamo.list_backends()"),e2=i(" each of which with its optional dependencies."),cd=h(),ji=r("p"),t2=i("Some of the most commonly used backends are"),ud=h(),Kr=r("p"),Ap=r("strong"),a2=i("Debugging backends"),r2=i(":"),gd=h(),Ct=r("ul"),Di=r("li"),Tp=r("code"),o2=i('dynamo.optimize("eager")'),s2=i(" - Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues."),i2=h(),Ii=r("li"),zp=r("code"),n2=i('dynamo.optimize("aot_eager")'),l2=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."),wd=h(),eo=r("p"),xp=r("strong"),p2=i("Training & inference backends"),h2=i(":"),vd=h(),I=r("ul"),to=r("li"),Gp=r("code"),m2=i('dynamo.optimize("inductor")'),f2=i(" - Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels  "),ao=r("a"),d2=i("Read more"),c2=h(),ro=r("li"),Up=r("code"),u2=i('dynamo.optimize("nvfuser")'),g2=i(" -  nvFuser with TorchScript. "),oo=r("a"),w2=i("Read more"),v2=h(),so=r("li"),Sp=r("code"),y2=i('dynamo.optimize("aot_nvfuser")'),_2=i(" -  nvFuser with AotAutograd. "),io=r("a"),b2=i("Read more"),E2=h(),no=r("li"),jp=r("code"),$2=i('dynamo.optimize("aot_cudagraphs")'),k2=i(" - cudagraphs with AotAutograd. "),lo=r("a"),P2=i("Read more"),yd=h(),po=r("p"),Dp=r("strong"),A2=i("Inference-only backend"),T2=i("s:"),_d=h(),N=r("ul"),ho=r("li"),Ip=r("code"),z2=i('dynamo.optimize("ofi")'),x2=i(" -  Uses Torchscript optimize_for_inference.  "),mo=r("a"),G2=i("Read more"),U2=h(),fo=r("li"),Np=r("code"),S2=i('dynamo.optimize("fx2trt")'),j2=i(" -  Uses Nvidia TensorRT for inference optimizations.  "),co=r("a"),D2=i("Read more"),I2=h(),uo=r("li"),Mp=r("code"),N2=i('dynamo.optimize("onnxrt")'),M2=i(" -  Uses ONNXRT for inference on CPU/GPU.  "),go=r("a"),O2=i("Read more"),q2=h(),wo=r("li"),Op=r("code"),C2=i('dynamo.optimize("ipex")'),L2=i(" -  Uses IPEX for inference on CPU.  "),vo=r("a"),W2=i("Read more"),this.h()},l(e){const l=i6('[data-svelte="svelte-1phssyn"]',document.head);b=o(l,"META",{name:!0,content:!0}),l.forEach(t),A=m(e),$=o(e,"H1",{class:!0});var yo=s($);U=o(yo,"A",{id:!0,class:!0,href:!0});var qp=s(U);nn=o(qp,"SPAN",{});var r3=s(nn);c(Ht.$$.fragment,r3),r3.forEach(t),qp.forEach(t),Hc=m(yo),ln=o(yo,"SPAN",{});var o3=s(ln);Yc=n(o3,"Efficient Training on a Single GPU"),o3.forEach(t),yo.forEach(t),Wp=m(e),Me=o(e,"P",{});var Ed=s(Me);Vc=n(Ed,"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 "),Eo=o(Ed,"A",{href:!0});var s3=s(Eo);Xc=n(s3,"multi-GPU section"),s3.forEach(t),Zc=n(Ed,"."),Ed.forEach(t),Bp=m(e),q=o(e,"P",{});var Ni=s(q);Qc=n(Ni,"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 "),$o=o(Ni,"A",{href:!0});var i3=s($o);Jc=n(i3,"Trainer"),i3.forEach(t),Kc=n(Ni," and "),Yt=o(Ni,"A",{href:!0,rel:!0});var n3=s(Yt);eu=n(n3,"\u{1F917} Accelerate"),n3.forEach(t),tu=n(Ni,". Each method can improve speed or memory usage which is summarized in the table below:"),Ni.forEach(t),Fp=m(e),Oe=o(e,"TABLE",{});var $d=s(Oe);pn=o($d,"THEAD",{});var l3=s(pn);ae=o(l3,"TR",{});var Mi=s(ae);ko=o(Mi,"TH",{align:!0});var p3=s(ko);au=n(p3,"Method"),p3.forEach(t),ru=m(Mi),Po=o(Mi,"TH",{align:!0});var h3=s(Po);ou=n(h3,"Speed"),h3.forEach(t),su=m(Mi),Ao=o(Mi,"TH",{align:!0});var m3=s(Ao);iu=n(m3,"Memory"),m3.forEach(t),Mi.forEach(t),l3.forEach(t),nu=m($d),k=o($d,"TBODY",{});var x=s(k);re=o(x,"TR",{});var Oi=s(re);To=o(Oi,"TD",{align:!0});var f3=s(To);lu=n(f3,"Gradient accumulation"),f3.forEach(t),pu=m(Oi),zo=o(Oi,"TD",{align:!0});var d3=s(zo);hu=n(d3,"No"),d3.forEach(t),mu=m(Oi),xo=o(Oi,"TD",{align:!0});var c3=s(xo);fu=n(c3,"Yes"),c3.forEach(t),Oi.forEach(t),du=m(x),oe=o(x,"TR",{});var qi=s(oe);Go=o(qi,"TD",{align:!0});var u3=s(Go);cu=n(u3,"Gradient checkpointing"),u3.forEach(t),uu=m(qi),Uo=o(qi,"TD",{align:!0});var g3=s(Uo);gu=n(g3,"No"),g3.forEach(t),wu=m(qi),So=o(qi,"TD",{align:!0});var w3=s(So);vu=n(w3,"Yes"),w3.forEach(t),qi.forEach(t),yu=m(x),se=o(x,"TR",{});var Ci=s(se);jo=o(Ci,"TD",{align:!0});var v3=s(jo);_u=n(v3,"Mixed precision training"),v3.forEach(t),bu=m(Ci),Do=o(Ci,"TD",{align:!0});var y3=s(Do);Eu=n(y3,"Yes"),y3.forEach(t),$u=m(Ci),Io=o(Ci,"TD",{align:!0});var _3=s(Io);ku=n(_3,"(No)"),_3.forEach(t),Ci.forEach(t),Pu=m(x),ie=o(x,"TR",{});var Li=s(ie);No=o(Li,"TD",{align:!0});var b3=s(No);Au=n(b3,"Batch size"),b3.forEach(t),Tu=m(Li),Mo=o(Li,"TD",{align:!0});var E3=s(Mo);zu=n(E3,"Yes"),E3.forEach(t),xu=m(Li),Oo=o(Li,"TD",{align:!0});var $3=s(Oo);Gu=n($3,"Yes"),$3.forEach(t),Li.forEach(t),Uu=m(x),ne=o(x,"TR",{});var Wi=s(ne);qo=o(Wi,"TD",{align:!0});var k3=s(qo);Su=n(k3,"Optimizer choice"),k3.forEach(t),ju=m(Wi),Co=o(Wi,"TD",{align:!0});var P3=s(Co);Du=n(P3,"Yes"),P3.forEach(t),Iu=m(Wi),Lo=o(Wi,"TD",{align:!0});var A3=s(Lo);Nu=n(A3,"Yes"),A3.forEach(t),Wi.forEach(t),Mu=m(x),le=o(x,"TR",{});var Bi=s(le);Wo=o(Bi,"TD",{align:!0});var T3=s(Wo);Ou=n(T3,"DataLoader"),T3.forEach(t),qu=m(Bi),Bo=o(Bi,"TD",{align:!0});var z3=s(Bo);Cu=n(z3,"Yes"),z3.forEach(t),Lu=m(Bi),Fo=o(Bi,"TD",{align:!0});var x3=s(Fo);Wu=n(x3,"No"),x3.forEach(t),Bi.forEach(t),Bu=m(x),pe=o(x,"TR",{});var Fi=s(pe);Ro=o(Fi,"TD",{align:!0});var G3=s(Ro);Fu=n(G3,"DeepSpeed Zero"),G3.forEach(t),Ru=m(Fi),Ho=o(Fi,"TD",{align:!0});var U3=s(Ho);Hu=n(U3,"No"),U3.forEach(t),Yu=m(Fi),Yo=o(Fi,"TD",{align:!0});var S3=s(Yo);Vu=n(S3,"Yes"),S3.forEach(t),Fi.forEach(t),x.forEach(t),$d.forEach(t),Rp=m(e),Vo=o(e,"P",{});var j3=s(Vo);Xu=n(j3,"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:"),j3.forEach(t),Hp=m(e),c(Vt.$$.fragment,e),Yp=m(e),C=o(e,"P",{});var Ri=s(C);Zu=n(Ri,"The "),hn=o(Ri,"CODE",{});var D3=s(hn);Qu=n(D3,"nvidia-ml-py3"),D3.forEach(t),Ju=n(Ri," library allows us to monitor the memory usage of the models from within Python. You might be familiar with the "),mn=o(Ri,"CODE",{});var I3=s(mn);Ku=n(I3,"nvidia-smi"),I3.forEach(t),eg=n(Ri," command in the terminal - this library allows to access the same information in Python directly."),Ri.forEach(t),Vp=m(e),qe=o(e,"P",{});var kd=s(qe);tg=n(kd,"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 "),fn=o(kd,"CODE",{});var N3=s(fn);ag=n(N3,"Dataset"),N3.forEach(t),rg=n(kd," with PyTorch format."),kd.forEach(t),Xp=m(e),c(Xt.$$.fragment,e),Zp=m(e),Ce=o(e,"P",{});var Pd=s(Ce);og=n(Pd,"We want to print some summary statistics for the GPU utilization and the training run with the "),Xo=o(Pd,"A",{href:!0});var M3=s(Xo);sg=n(M3,"Trainer"),M3.forEach(t),ig=n(Pd,". We setup a two helper functions to do just that:"),Pd.forEach(t),Qp=m(e),c(Zt.$$.fragment,e),Jp=m(e),Zo=o(e,"P",{});var O3=s(Zo);ng=n(O3,"Let\u2019s verify that we start with a free GPU memory:"),O3.forEach(t),Kp=m(e),c(Qt.$$.fragment,e),eh=m(e),Qo=o(e,"P",{});var q3=s(Qo);lg=n(q3,"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."),q3.forEach(t),th=m(e),c(Jt.$$.fragment,e),ah=m(e),Jo=o(e,"P",{});var C3=s(Jo);pg=n(C3,"We see that the kernels alone take up 1.3GB of GPU memory. Now let\u2019s see how much space the model uses."),C3.forEach(t),rh=m(e),he=o(e,"H2",{class:!0});var Ad=s(he);Le=o(Ad,"A",{id:!0,class:!0,href:!0});var L3=s(Le);dn=o(L3,"SPAN",{});var W3=s(dn);c(Kt.$$.fragment,W3),W3.forEach(t),L3.forEach(t),hg=m(Ad),cn=o(Ad,"SPAN",{});var B3=s(cn);mg=n(B3,"Load Model"),B3.forEach(t),Ad.forEach(t),oh=m(e),We=o(e,"P",{});var Td=s(We);fg=n(Td,"First, we load the "),un=o(Td,"CODE",{});var F3=s(un);dg=n(F3,"bert-large-uncased"),F3.forEach(t),cg=n(Td," model. We load the model weights directly to the GPU so that we can check how much space just weights use."),Td.forEach(t),sh=m(e),c(ea.$$.fragment,e),ih=m(e),Be=o(e,"P",{});var zd=s(Be);ug=n(zd,"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 "),gn=o(zd,"CODE",{});var R3=s(gn);gg=n(R3,"nvidia-smi"),R3.forEach(t),wg=n(zd," CLI:"),zd.forEach(t),nh=m(e),c(ta.$$.fragment,e),lh=m(e),c(aa.$$.fragment,e),ph=m(e),Ko=o(e,"P",{});var H3=s(Ko);vg=n(H3,"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:"),H3.forEach(t),hh=m(e),c(ra.$$.fragment,e),mh=m(e),c(Fe.$$.fragment,e),fh=m(e),me=o(e,"H2",{class:!0});var xd=s(me);Re=o(xd,"A",{id:!0,class:!0,href:!0});var Y3=s(Re);wn=o(Y3,"SPAN",{});var V3=s(wn);c(oa.$$.fragment,V3),V3.forEach(t),Y3.forEach(t),yg=m(xd),vn=o(xd,"SPAN",{});var X3=s(vn);_g=n(X3,"Vanilla Training"),X3.forEach(t),xd.forEach(t),dh=m(e),He=o(e,"P",{});var Gd=s(He);bg=n(Gd,"As a first experiment we will use the "),es=o(Gd,"A",{href:!0});var Z3=s(es);Eg=n(Z3,"Trainer"),Z3.forEach(t),$g=n(Gd," and train the model without any further modifications and a batch size of 4:"),Gd.forEach(t),ch=m(e),c(sa.$$.fragment,e),uh=m(e),c(ia.$$.fragment,e),gh=m(e),ts=o(e,"P",{});var Q3=s(ts);kg=n(Q3,"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."),Q3.forEach(t),wh=m(e),fe=o(e,"H2",{class:!0});var Ud=s(fe);Ye=o(Ud,"A",{id:!0,class:!0,href:!0});var J3=s(Ye);yn=o(J3,"SPAN",{});var K3=s(yn);c(na.$$.fragment,K3),K3.forEach(t),J3.forEach(t),Pg=m(Ud),_n=o(Ud,"SPAN",{});var eE=s(_n);Ag=n(eE,"Anatomy of Model's Operations"),eE.forEach(t),Ud.forEach(t),vh=m(e),as=o(e,"P",{});var tE=s(as);Tg=n(tE,"Transformers architecture includes 3 main groups of operations grouped below by compute-intensity."),tE.forEach(t),yh=m(e),L=o(e,"OL",{});var Hi=s(L);la=o(Hi,"LI",{});var Sd=s(la);bn=o(Sd,"P",{});var aE=s(bn);En=o(aE,"STRONG",{});var rE=s(En);zg=n(rE,"Tensor Contractions"),rE.forEach(t),aE.forEach(t),xg=m(Sd),pa=o(Sd,"P",{});var jd=s(pa);Gg=n(jd,"Linear layers and components of Multi-Head Attention all do batched "),$n=o(jd,"STRONG",{});var oE=s($n);Ug=n(oE,"matrix-matrix multiplications"),oE.forEach(t),Sg=n(jd,". These operations are the most compute-intensive part of training a transformer."),jd.forEach(t),Sd.forEach(t),jg=m(Hi),ha=o(Hi,"LI",{});var Dd=s(ha);kn=o(Dd,"P",{});var sE=s(kn);Pn=o(sE,"STRONG",{});var iE=s(Pn);Dg=n(iE,"Statistical Normalizations"),iE.forEach(t),sE.forEach(t),Ig=m(Dd),ma=o(Dd,"P",{});var Id=s(ma);Ng=n(Id,"Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more "),An=o(Id,"STRONG",{});var nE=s(An);Mg=n(nE,"reduction operations"),nE.forEach(t),Og=n(Id,", the result of which is then applied via a map."),Id.forEach(t),Dd.forEach(t),qg=m(Hi),fa=o(Hi,"LI",{});var Nd=s(fa);Tn=o(Nd,"P",{});var lE=s(Tn);zn=o(lE,"STRONG",{});var pE=s(zn);Cg=n(pE,"Element-wise Operators"),pE.forEach(t),lE.forEach(t),Lg=m(Nd),da=o(Nd,"P",{});var Md=s(da);Wg=n(Md,"These are the remaining operators: "),xn=o(Md,"STRONG",{});var hE=s(xn);Bg=n(hE,"biases, dropout, activations, and residual connections"),hE.forEach(t),Fg=n(Md,". These are the least compute-intensive operations."),Md.forEach(t),Nd.forEach(t),Hi.forEach(t),_h=m(e),rs=o(e,"P",{});var mE=s(rs);Rg=n(mE,"This knowledge can be helpful to know when analyzing performance bottlenecks."),mE.forEach(t),bh=m(e),ca=o(e,"P",{});var B2=s(ca);Hg=n(B2,"This summary is derived from "),ua=o(B2,"A",{href:!0,rel:!0});var fE=s(ua);Yg=n(fE,"Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020"),fE.forEach(t),B2.forEach(t),Eh=m(e),de=o(e,"H2",{class:!0});var Od=s(de);Ve=o(Od,"A",{id:!0,class:!0,href:!0});var dE=s(Ve);Gn=o(dE,"SPAN",{});var cE=s(Gn);c(ga.$$.fragment,cE),cE.forEach(t),dE.forEach(t),Vg=m(Od),Un=o(Od,"SPAN",{});var uE=s(Un);Xg=n(uE,"Anatomy of Model's Memory"),uE.forEach(t),Od.forEach(t),$h=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
`),os=o(e,"P",{});var gE=s(os);Zg=n(gE,"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."),gE.forEach(t),kh=m(e),ss=o(e,"P",{});var wE=s(ss);Qg=n(wE,"Let\u2019s look at the details."),wE.forEach(t),Ph=m(e),is=o(e,"P",{});var vE=s(is);Sn=o(vE,"STRONG",{});var yE=s(Sn);Jg=n(yE,"Model Weights:"),yE.forEach(t),vE.forEach(t),Ah=m(e),Xe=o(e,"UL",{});var qd=s(Xe);jn=o(qd,"LI",{});var _E=s(jn);Kg=n(_E,"4 bytes * number of parameters for fp32 training"),_E.forEach(t),ew=m(qd),Dn=o(qd,"LI",{});var bE=s(Dn);tw=n(bE,"6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)"),bE.forEach(t),qd.forEach(t),Th=m(e),ns=o(e,"P",{});var EE=s(ns);In=o(EE,"STRONG",{});var $E=s(In);aw=n($E,"Optimizer States:"),$E.forEach(t),EE.forEach(t),zh=m(e),W=o(e,"UL",{});var Yi=s(W);Nn=o(Yi,"LI",{});var kE=s(Nn);rw=n(kE,"8 bytes * number of parameters for normal AdamW (maintains 2 states)"),kE.forEach(t),ow=m(Yi),ls=o(Yi,"LI",{});var F2=s(ls);sw=n(F2,"2 bytes * number of parameters for 8-bit AdamW optimizers like "),wa=o(F2,"A",{href:!0,rel:!0});var PE=s(wa);iw=n(PE,"bitsandbytes"),PE.forEach(t),F2.forEach(t),nw=m(Yi),Mn=o(Yi,"LI",{});var AE=s(Mn);lw=n(AE,"4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)"),AE.forEach(t),Yi.forEach(t),xh=m(e),ps=o(e,"P",{});var TE=s(ps);On=o(TE,"STRONG",{});var zE=s(On);pw=n(zE,"Gradients"),zE.forEach(t),TE.forEach(t),Gh=m(e),hs=o(e,"UL",{});var xE=s(hs);qn=o(xE,"LI",{});var GE=s(qn);hw=n(GE,"4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)"),GE.forEach(t),xE.forEach(t),Uh=m(e),ms=o(e,"P",{});var UE=s(ms);Cn=o(UE,"STRONG",{});var SE=s(Cn);mw=n(SE,"Forward Activations"),SE.forEach(t),UE.forEach(t),Sh=m(e),fs=o(e,"UL",{});var jE=s(fs);Ln=o(jE,"LI",{});var DE=s(Ln);fw=n(DE,"size depends on many factors, the key ones being sequence length, hidden size and batch size."),DE.forEach(t),jE.forEach(t),jh=m(e),ds=o(e,"P",{});var IE=s(ds);dw=n(IE,"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."),IE.forEach(t),Dh=m(e),cs=o(e,"P",{});var NE=s(cs);Wn=o(NE,"STRONG",{});var ME=s(Wn);cw=n(ME,"Temporary Memory"),ME.forEach(t),NE.forEach(t),Ih=m(e),us=o(e,"P",{});var OE=s(us);uw=n(OE,"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."),OE.forEach(t),Nh=m(e),gs=o(e,"P",{});var qE=s(gs);Bn=o(qE,"STRONG",{});var CE=s(Bn);gw=n(CE,"Functionality-specific memory"),CE.forEach(t),qE.forEach(t),Mh=m(e),ws=o(e,"P",{});var LE=s(ws);ww=n(LE,"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."),LE.forEach(t),Oh=m(e),vs=o(e,"P",{});var WE=s(vs);Ze=o(WE,"STRONG",{});var Cp=s(Ze);Fn=o(Cp,"CODE",{});var BE=s(Fn);vw=n(BE,"forward"),BE.forEach(t),yw=n(Cp," vs "),Rn=o(Cp,"CODE",{});var FE=s(Rn);_w=n(FE,"backward"),FE.forEach(t),bw=n(Cp," Execution Speed"),Cp.forEach(t),WE.forEach(t),qh=m(e),ys=o(e,"P",{});var RE=s(ys);Ew=n(RE,"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)."),RE.forEach(t),Ch=m(e),_s=o(e,"P",{});var HE=s(_s);$w=n(HE,"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."),HE.forEach(t),Lh=m(e),ce=o(e,"H2",{class:!0});var Cd=s(ce);Qe=o(Cd,"A",{id:!0,class:!0,href:!0});var YE=s(Qe);Hn=o(YE,"SPAN",{});var VE=s(Hn);c(va.$$.fragment,VE),VE.forEach(t),YE.forEach(t),kw=m(Cd),Yn=o(Cd,"SPAN",{});var XE=s(Yn);Pw=n(XE,"Batch sizes"),XE.forEach(t),Cd.forEach(t),Wh=m(e),bs=o(e,"P",{});var ZE=s(bs);Aw=n(ZE,"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."),ZE.forEach(t),Bh=m(e),B=o(e,"P",{});var Vi=s(B);Tw=n(Vi,"For example for fully connected layers (which correspond to GEMMs), NVIDIA provides recommendations for "),ya=o(Vi,"A",{href:!0,rel:!0});var QE=s(ya);zw=n(QE,"input/output neuron counts"),QE.forEach(t),xw=n(Vi," and "),_a=o(Vi,"A",{href:!0,rel:!0});var JE=s(_a);Gw=n(JE,"batch size"),JE.forEach(t),Uw=n(Vi,"."),Vi.forEach(t),Fh=m(e),ba=o(e,"P",{});var R2=s(ba);Ea=o(R2,"A",{href:!0,rel:!0});var KE=s(Ea);Sw=n(KE,"Tensor Core Requirements"),KE.forEach(t),jw=n(R2," 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!"),R2.forEach(t),Rh=m(e),Je=o(e,"P",{});var Ld=s(Je);Dw=n(Ld,"For parameters that are small, there is also "),$a=o(Ld,"A",{href:!0,rel:!0});var e$=s($a);Iw=n(e$,"Dimension Quantization Effects"),e$.forEach(t),Nw=n(Ld," to consider, this is where tiling happens and the right multiplier can have a significant speedup."),Ld.forEach(t),Hh=m(e),ue=o(e,"H2",{class:!0});var Wd=s(ue);Ke=o(Wd,"A",{id:!0,class:!0,href:!0});var t$=s(Ke);Vn=o(t$,"SPAN",{});var a$=s(Vn);c(ka.$$.fragment,a$),a$.forEach(t),t$.forEach(t),Mw=m(Wd),Xn=o(Wd,"SPAN",{});var r$=s(Xn);Ow=n(r$,"Gradient Accumulation"),r$.forEach(t),Wd.forEach(t),Yh=m(e),Es=o(e,"P",{});var o$=s(Es);qw=n(o$,"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."),o$.forEach(t),Vh=m(e),S=o(e,"P",{});var Lt=s(S);Cw=n(Lt,"We can use gradient accumulation in the "),$s=o(Lt,"A",{href:!0});var s$=s($s);Lw=n(s$,"Trainer"),s$.forEach(t),Ww=n(Lt," by simply adding the "),Zn=o(Lt,"CODE",{});var i$=s(Zn);Bw=n(i$,"gradient_accumulation_steps"),i$.forEach(t),Fw=n(Lt," argument to "),ks=o(Lt,"A",{href:!0});var n$=s(ks);Rw=n(n$,"TrainingArguments"),n$.forEach(t),Hw=n(Lt,". Let\u2019s see how it impacts the models memory footprint:"),Lt.forEach(t),Xh=m(e),c(Pa.$$.fragment,e),Zh=m(e),c(Aa.$$.fragment,e),Qh=m(e),T=o(e,"P",{});var ee=s(T);Yw=n(ee,"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 "),Qn=o(ee,"CODE",{});var l$=s(Qn);Vw=n(l$,"per_device_train_batch_size=1"),l$.forEach(t),Xw=n(ee," and "),Jn=o(ee,"CODE",{});var p$=s(Jn);Zw=n(p$,"gradient_accumulation_steps=64"),p$.forEach(t),Qw=n(ee," but instead "),Kn=o(ee,"CODE",{});var h$=s(Kn);Jw=n(h$,"per_device_train_batch_size=4"),h$.forEach(t),Kw=n(ee," and "),el=o(ee,"CODE",{});var m$=s(el);ev=n(m$,"gradient_accumulation_steps=16"),m$.forEach(t),tv=n(ee," which has the same effective batch size while making better use of the available GPU resources."),ee.forEach(t),Jh=m(e),F=o(e,"P",{});var Xi=s(F);av=n(Xi,"For more details see the benchmarks for "),Ta=o(Xi,"A",{href:!0,rel:!0});var f$=s(Ta);rv=n(f$,"RTX-3090"),f$.forEach(t),ov=n(Xi,`
and `),za=o(Xi,"A",{href:!0,rel:!0});var d$=s(za);sv=n(d$,"A100"),d$.forEach(t),iv=n(Xi,"."),Xi.forEach(t),Kh=m(e),Ps=o(e,"P",{});var c$=s(Ps);nv=n(c$,"Next we have a look at another trick to save a little bit more GPU memory called gradient checkpointing."),c$.forEach(t),em=m(e),ge=o(e,"H2",{class:!0});var Bd=s(ge);et=o(Bd,"A",{id:!0,class:!0,href:!0});var u$=s(et);tl=o(u$,"SPAN",{});var g$=s(tl);c(xa.$$.fragment,g$),g$.forEach(t),u$.forEach(t),lv=m(Bd),al=o(Bd,"SPAN",{});var w$=s(al);pv=n(w$,"Gradient Checkpointing"),w$.forEach(t),Bd.forEach(t),tm=m(e),As=o(e,"P",{});var v$=s(As);hv=n(v$,"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."),v$.forEach(t),am=m(e),tt=o(e,"P",{});var Fd=s(tt);mv=n(Fd,"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 "),Ga=o(Fd,"A",{href:!0,rel:!0});var y$=s(Ga);fv=n(y$,"this great article"),y$.forEach(t),dv=n(Fd," explaining the ideas behind gradient checkpointing."),Fd.forEach(t),rm=m(e),R=o(e,"P",{});var Zi=s(R);cv=n(Zi,"To enable gradient checkpointing in the "),Ts=o(Zi,"A",{href:!0});var _$=s(Ts);uv=n(_$,"Trainer"),_$.forEach(t),gv=n(Zi," we only need to pass it as a flag to the "),zs=o(Zi,"A",{href:!0});var b$=s(zs);wv=n(b$,"TrainingArguments"),b$.forEach(t),vv=n(Zi,". Everything else is handled under the hood:"),Zi.forEach(t),om=m(e),c(Ua.$$.fragment,e),sm=m(e),c(Sa.$$.fragment,e),im=m(e),xs=o(e,"P",{});var E$=s(xs);yv=n(E$,"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."),E$.forEach(t),nm=m(e),we=o(e,"H2",{class:!0});var Rd=s(we);at=o(Rd,"A",{id:!0,class:!0,href:!0});var $$=s(at);rl=o($$,"SPAN",{});var k$=s(rl);c(ja.$$.fragment,k$),k$.forEach(t),$$.forEach(t),_v=m(Rd),ol=o(Rd,"SPAN",{});var P$=s(ol);bv=n(P$,"Floating Data Types"),P$.forEach(t),Rd.forEach(t),lm=m(e),Gs=o(e,"P",{});var A$=s(Gs);Ev=n(A$,"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:"),A$.forEach(t),pm=m(e),j=o(e,"UL",{});var Wt=s(j);Da=o(Wt,"LI",{});var Hd=s(Da);$v=n(Hd,"fp32 ("),sl=o(Hd,"CODE",{});var T$=s(sl);kv=n(T$,"float32"),T$.forEach(t),Pv=n(Hd,")"),Hd.forEach(t),Av=m(Wt),Ia=o(Wt,"LI",{});var Yd=s(Ia);Tv=n(Yd,"fp16 ("),il=o(Yd,"CODE",{});var z$=s(il);zv=n(z$,"float16"),z$.forEach(t),xv=n(Yd,")"),Yd.forEach(t),Gv=m(Wt),Na=o(Wt,"LI",{});var Vd=s(Na);Uv=n(Vd,"bf16 ("),nl=o(Vd,"CODE",{});var x$=s(nl);Sv=n(x$,"bfloat16"),x$.forEach(t),jv=n(Vd,")"),Vd.forEach(t),Dv=m(Wt),ll=o(Wt,"LI",{});var G$=s(ll);Iv=n(G$,"tf32 (CUDA internal data type)"),G$.forEach(t),Wt.forEach(t),hm=m(e),Us=o(e,"P",{});var U$=s(Us);Nv=n(U$,"Here is a diagram that shows how these data types correlate to each other."),U$.forEach(t),mm=m(e),ve=o(e,"P",{});var Lp=s(ve);Ss=o(Lp,"IMG",{src:!0,alt:!0}),Mv=n(Lp,`
(source: `),Ma=o(Lp,"A",{href:!0,rel:!0});var S$=s(Ma);Ov=n(S$,"NVIDIA Blog"),S$.forEach(t),qv=n(Lp,")"),Lp.forEach(t),fm=m(e),js=o(e,"P",{});var j$=s(js);Cv=n(j$,"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/"),j$.forEach(t),dm=m(e),ye=o(e,"H3",{class:!0});var Xd=s(ye);rt=o(Xd,"A",{id:!0,class:!0,href:!0});var D$=s(rt);pl=o(D$,"SPAN",{});var I$=s(pl);c(Oa.$$.fragment,I$),I$.forEach(t),D$.forEach(t),Lv=m(Xd),hl=o(Xd,"SPAN",{});var N$=s(hl);Wv=n(N$,"FP16 Training"),N$.forEach(t),Xd.forEach(t),cm=m(e),H=o(e,"P",{});var Qi=s(H);Bv=n(Qi,"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 "),ml=o(Qi,"CODE",{});var M$=s(ml);Fv=n(M$,"fp16"),M$.forEach(t),Rv=n(Qi," flag to "),fl=o(Qi,"CODE",{});var O$=s(fl);Hv=n(O$,"True"),O$.forEach(t),Yv=n(Qi,":"),Qi.forEach(t),um=m(e),c(qa.$$.fragment,e),gm=m(e),c(Ca.$$.fragment,e),wm=m(e),Ds=o(e,"P",{});var q$=s(Ds);Vv=n(q$,"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:"),q$.forEach(t),vm=m(e),c(La.$$.fragment,e),ym=m(e),c(Wa.$$.fragment,e),_m=m(e),Is=o(e,"P",{});var C$=s(Is);Xv=n(C$,"We can see that with these tweaks we use about half the GPU memory as at the beginning while also being slightly faster."),C$.forEach(t),bm=m(e),_e=o(e,"H3",{class:!0});var Zd=s(_e);ot=o(Zd,"A",{id:!0,class:!0,href:!0});var L$=s(ot);dl=o(L$,"SPAN",{});var W$=s(dl);c(Ba.$$.fragment,W$),W$.forEach(t),L$.forEach(t),Zv=m(Zd),cl=o(Zd,"SPAN",{});var B$=s(cl);Qv=n(B$,"BF16"),B$.forEach(t),Zd.forEach(t),Em=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"),Ns=o(e,"P",{});var F$=s(Ns);Jv=n(F$,"You can enable BF16 in the \u{1F917} Trainer with:"),F$.forEach(t),$m=m(e),c(Fa.$$.fragment,e),km=m(e),be=o(e,"H3",{class:!0});var Qd=s(be);st=o(Qd,"A",{id:!0,class:!0,href:!0});var R$=s(st);ul=o(R$,"SPAN",{});var H$=s(ul);c(Ra.$$.fragment,H$),H$.forEach(t),R$.forEach(t),Kv=m(Qd),gl=o(Qd,"SPAN",{});var Y$=s(gl);ey=n(Y$,"TF32"),Y$.forEach(t),Qd.forEach(t),Pm=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.
`),Ms=o(e,"P",{});var V$=s(Ms);ty=n(V$,"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:"),V$.forEach(t),Am=m(e),c(Ha.$$.fragment,e),Tm=m(e),Os=o(e,"P",{});var X$=s(Os);ay=n(X$,"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."),X$.forEach(t),zm=m(e),it=o(e,"P",{});var Jd=s(it);ry=n(Jd,"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 "),Ya=o(Jd,"A",{href:!0,rel:!0});var Z$=s(Ya);oy=n(Z$,"NVIDIA research"),Z$.forEach(t),sy=n(Jd," the majority of machine learning training shouldn\u2019t be impacted and showed the same perplexity and convergence as the fp32 training."),Jd.forEach(t),xm=m(e),qs=o(e,"P",{});var Q$=s(qs);iy=n(Q$,"If you\u2019re already using fp16 or bf16 mixed precision it may help with the throughput as well."),Q$.forEach(t),Gm=m(e),Cs=o(e,"P",{});var J$=s(Cs);ny=n(J$,"You can enable this mode in the \u{1F917} Trainer with:"),J$.forEach(t),Um=m(e),c(Va.$$.fragment,e),Sm=m(e),Ls=o(e,"P",{});var K$=s(Ls);ly=n(K$,"By default the PyTorch default is used."),K$.forEach(t),jm=m(e),Y=o(e,"P",{});var Ji=s(Y);py=n(Ji,"Note: tf32 mode is internal to CUDA and can\u2019t be accessed directly via "),wl=o(Ji,"CODE",{});var e0=s(wl);hy=n(e0,"tensor.to(dtype=torch.tf32)"),e0.forEach(t),my=n(Ji," as "),vl=o(Ji,"CODE",{});var t0=s(vl);fy=n(t0,"torch.tf32"),t0.forEach(t),dy=n(Ji," doesn\u2019t exist."),Ji.forEach(t),Dm=m(e),nt=o(e,"P",{});var Kd=s(nt);cy=n(Kd,"Note: you need "),yl=o(Kd,"CODE",{});var a0=s(yl);uy=n(a0,"torch>=1.7"),a0.forEach(t),gy=n(Kd," to enjoy this feature."),Kd.forEach(t),Im=m(e),V=o(e,"P",{});var Ki=s(V);wy=n(Ki,`You can also see a variety of benchmarks on tf32 vs other precisions:
`),Xa=o(Ki,"A",{href:!0,rel:!0});var r0=s(Xa);vy=n(r0,"RTX-3090"),r0.forEach(t),yy=n(Ki,` and
`),Za=o(Ki,"A",{href:!0,rel:!0});var o0=s(Za);_y=n(o0,"A100"),o0.forEach(t),by=n(Ki,"."),Ki.forEach(t),Nm=m(e),Ws=o(e,"P",{});var s0=s(Ws);Ey=n(s0,"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."),s0.forEach(t),Mm=m(e),Ee=o(e,"H2",{class:!0});var ec=s(Ee);lt=o(ec,"A",{id:!0,class:!0,href:!0});var i0=s(lt);_l=o(i0,"SPAN",{});var n0=s(_l);c(Qa.$$.fragment,n0),n0.forEach(t),i0.forEach(t),$y=m(ec),bl=o(ec,"SPAN",{});var l0=s(bl);ky=n(l0,"Optimizer"),l0.forEach(t),ec.forEach(t),Om=m(e),Bs=o(e,"P",{});var p0=s(Bs);Py=n(p0,"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."),p0.forEach(t),qm=m(e),pt=o(e,"P",{});var tc=s(pt);Ay=n(tc,"HF Trainer integrates a variety of optimisers that can be used out of box. To activate the desired optimizer simply pass the "),El=o(tc,"CODE",{});var h0=s(El);Ty=n(h0,"--optim"),h0.forEach(t),zy=n(tc," flag to the command line."),tc.forEach(t),Cm=m(e),Fs=o(e,"P",{});var m0=s(Fs);xy=n(m0,"To see which optimizers are currently supported:"),m0.forEach(t),Lm=m(e),c(Ja.$$.fragment,e),Wm=m(e),X=o(e,"P",{});var en=s(X);Gy=n(en,"For example, if you have "),Ka=o(en,"A",{href:!0,rel:!0});var f0=s(Ka);Uy=n(f0,"NVIDIA/apex"),f0.forEach(t),Sy=n(en," installed "),$l=o(en,"CODE",{});var d0=s($l);jy=n(d0,"--optim adamw_apex_fused"),d0.forEach(t),Dy=n(en," will give you the fastest training experience among all supported AdamW optimizers."),en.forEach(t),Bm=m(e),ht=o(e,"P",{});var ac=s(ht);Iy=n(ac,"On the other hand "),er=o(ac,"A",{href:!0,rel:!0});var c0=s(er);Ny=n(c0,"8bit BNB optimizer"),c0.forEach(t),My=n(ac," 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."),ac.forEach(t),Fm=m(e),mt=o(e,"P",{});var rc=s(mt);Oy=n(rc,"Let\u2019s get a feel for the numbers and use for example use a 3B-parameter model, like "),kl=o(rc,"CODE",{});var u0=s(kl);qy=n(u0,"t5-3b"),u0.forEach(t),Cy=n(rc,". 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:"),rc.forEach(t),Rm=m(e),Z=o(e,"UL",{});var tn=s(Z);tr=o(tn,"LI",{});var oc=s(tr);Ly=n(oc,"A standard AdamW uses 8 bytes for each parameter, here the optimizer will need ("),Pl=o(oc,"CODE",{});var g0=s(Pl);Wy=n(g0,"8*3"),g0.forEach(t),By=n(oc,") 24GB of GPU memory."),oc.forEach(t),Fy=m(tn),ar=o(tn,"LI",{});var sc=s(ar);Ry=n(sc,"Adafactor uses slightly more than 4 bytes, so ("),Al=o(sc,"CODE",{});var w0=s(Al);Hy=n(w0,"4*3"),w0.forEach(t),Yy=n(sc,") 12GB and then some extra."),sc.forEach(t),Vy=m(tn),rr=o(tn,"LI",{});var ic=s(rr);Xy=n(ic,"8bit BNB quantized optimizer will use only ("),Tl=o(ic,"CODE",{});var v0=s(Tl);Zy=n(v0,"2*3"),v0.forEach(t),Qy=n(ic,") 6GB if all optimizer states are quantized."),ic.forEach(t),tn.forEach(t),Hm=m(e),Rs=o(e,"P",{});var y0=s(Rs);Jy=n(y0,"Let\u2019s have a look at Adafactor first."),y0.forEach(t),Ym=m(e),$e=o(e,"H3",{class:!0});var nc=s($e);ft=o(nc,"A",{id:!0,class:!0,href:!0});var _0=s(ft);zl=o(_0,"SPAN",{});var b0=s(zl);c(or.$$.fragment,b0),b0.forEach(t),_0.forEach(t),Ky=m(nc),xl=o(nc,"SPAN",{});var E0=s(xl);e_=n(E0,"Adafactor"),E0.forEach(t),nc.forEach(t),Vm=m(e),dt=o(e,"P",{});var lc=s(dt);t_=n(lc,"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 "),Gl=o(lc,"CODE",{});var $0=s(Gl);a_=n($0,'optim="adafactor"'),$0.forEach(t),r_=n(lc,":"),lc.forEach(t),Xm=m(e),c(sr.$$.fragment,e),Zm=m(e),c(ir.$$.fragment,e),Qm=m(e),Hs=o(e,"P",{});var k0=s(Hs);o_=n(k0,"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:"),k0.forEach(t),Jm=m(e),c(nr.$$.fragment,e),Km=m(e),c(lr.$$.fragment,e),ef=m(e),Ys=o(e,"P",{});var P0=s(Ys);s_=n(P0,"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."),P0.forEach(t),tf=m(e),ke=o(e,"H3",{class:!0});var pc=s(ke);ct=o(pc,"A",{id:!0,class:!0,href:!0});var A0=s(ct);Ul=o(A0,"SPAN",{});var T0=s(Ul);c(pr.$$.fragment,T0),T0.forEach(t),A0.forEach(t),i_=m(pc),Sl=o(pc,"SPAN",{});var z0=s(Sl);n_=n(z0,"8-bit Adam"),z0.forEach(t),pc.forEach(t),af=m(e),Vs=o(e,"P",{});var x0=s(Vs);l_=n(x0,"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."),x0.forEach(t),rf=m(e),z=o(e,"P",{});var te=s(z);p_=n(te,"In contrast to the previous approaches is this one not integrated into the "),Xs=o(te,"A",{href:!0});var G0=s(Xs);h_=n(G0,"Trainer"),G0.forEach(t),m_=n(te," as a simple flag. We need to install the 8-bit optimizer and then pass it as a custom optimizer to the "),Zs=o(te,"A",{href:!0});var U0=s(Zs);f_=n(U0,"Trainer"),U0.forEach(t),d_=n(te,". Follow the installation guide in the Github "),hr=o(te,"A",{href:!0,rel:!0});var S0=s(hr);c_=n(S0,"repo"),S0.forEach(t),u_=n(te," to install the "),jl=o(te,"CODE",{});var j0=s(jl);g_=n(j0,"bitsandbytes"),j0.forEach(t),w_=n(te," library that implements the 8-bit Adam optimizer."),te.forEach(t),of=m(e),Qs=o(e,"P",{});var D0=s(Qs);v_=n(D0,"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."),D0.forEach(t),sf=m(e),c(ut.$$.fragment,e),nf=m(e),c(mr.$$.fragment,e),lf=m(e),gt=o(e,"P",{});var hc=s(gt);y_=n(hc,"We can now pass the custom optimizer as an argument to the "),Dl=o(hc,"CODE",{});var I0=s(Dl);__=n(I0,"Trainer"),I0.forEach(t),b_=n(hc,":"),hc.forEach(t),pf=m(e),c(fr.$$.fragment,e),hf=m(e),c(dr.$$.fragment,e),mf=m(e),Js=o(e,"P",{});var N0=s(Js);E_=n(N0,"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:"),N0.forEach(t),ff=m(e),c(cr.$$.fragment,e),df=m(e),c(ur.$$.fragment,e),cf=m(e),Ks=o(e,"P",{});var M0=s(Ks);$_=n(M0,"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:"),M0.forEach(t),uf=m(e),ei=o(e,"P",{});var O0=s(ei);ti=o(O0,"IMG",{src:!0,alt:!0}),O0.forEach(t),gf=m(e),Pe=o(e,"H3",{class:!0});var mc=s(Pe);wt=o(mc,"A",{id:!0,class:!0,href:!0});var q0=s(wt);Il=o(q0,"SPAN",{});var C0=s(Il);c(gr.$$.fragment,C0),C0.forEach(t),q0.forEach(t),k_=m(mc),Nl=o(mc,"SPAN",{});var L0=s(Nl);Ml=o(L0,"CODE",{});var W0=s(Ml);P_=n(W0,"_multi_tensor"),W0.forEach(t),L0.forEach(t),mc.forEach(t),wf=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
`),Ae=o(e,"H2",{class:!0});var fc=s(Ae);vt=o(fc,"A",{id:!0,class:!0,href:!0});var B0=s(vt);Ol=o(B0,"SPAN",{});var F0=s(Ol);c(wr.$$.fragment,F0),F0.forEach(t),B0.forEach(t),A_=m(fc),ql=o(fc,"SPAN",{});var R0=s(ql);T_=n(R0,"Using \u{1F917} Accelerate"),R0.forEach(t),fc.forEach(t),vf=m(e),Q=o(e,"P",{});var an=s(Q);z_=n(an,"So far we have used the "),ai=o(an,"A",{href:!0});var H0=s(ai);x_=n(H0,"Trainer"),H0.forEach(t),G_=n(an," 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 "),ri=o(an,"A",{href:!0});var Y0=s(ri);U_=n(Y0,"TrainingArguments"),Y0.forEach(t),S_=n(an," to wrap the training settings:"),an.forEach(t),yf=m(e),c(vr.$$.fragment,e),_f=m(e),oi=o(e,"P",{});var V0=s(oi);j_=n(V0,"The full example training loop with \u{1F917} Accelerate is only a handful of lines of code long:"),V0.forEach(t),bf=m(e),c(yr.$$.fragment,e),Ef=m(e),P=o(e,"P",{});var M=s(P);D_=n(M,"First we wrap the dataset in a "),_r=o(M,"A",{href:!0,rel:!0});var X0=s(_r);Cl=o(X0,"CODE",{});var Z0=s(Cl);I_=n(Z0,"DataLoader"),Z0.forEach(t),X0.forEach(t),N_=n(M,". Then we can enable gradient checkpointing by calling the model\u2019s "),si=o(M,"A",{href:!0});var Q0=s(si);M_=n(Q0,"gradient_checkpointing_enable()"),Q0.forEach(t),O_=n(M," method. When we initialize the "),br=o(M,"A",{href:!0,rel:!0});var J0=s(br);Ll=o(J0,"CODE",{});var K0=s(Ll);q_=n(K0,"Accelerator"),K0.forEach(t),J0.forEach(t),C_=n(M," we can specify if we want to use mixed precision training and it will take care of it for us in the "),Wl=o(M,"CODE",{});var e4=s(Wl);L_=n(e4,"prepare"),e4.forEach(t),W_=n(M," call. During the "),Er=o(M,"A",{href:!0,rel:!0});var t4=s(Er);Bl=o(t4,"CODE",{});var a4=s(Bl);B_=n(a4,"prepare"),a4.forEach(t),t4.forEach(t),F_=n(M," 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."),M.forEach(t),$f=m(e),yt=o(e,"P",{});var dc=s(yt);R_=n(dc,"Finally, we can write the main training loop. Note that the "),Fl=o(dc,"CODE",{});var r4=s(Fl);H_=n(r4,"backward"),r4.forEach(t),Y_=n(dc," 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:"),dc.forEach(t),kf=m(e),c($r.$$.fragment,e),Pf=m(e),_t=o(e,"P",{});var cc=s(_t);V_=n(cc,"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 "),kr=o(cc,"A",{href:!0,rel:!0});var o4=s(kr);X_=n(o4,"Accelerate documentation"),o4.forEach(t),Z_=n(cc,"."),cc.forEach(t),Af=m(e),Te=o(e,"H2",{class:!0});var uc=s(Te);bt=o(uc,"A",{id:!0,class:!0,href:!0});var s4=s(bt);Rl=o(s4,"SPAN",{});var i4=s(Rl);c(Pr.$$.fragment,i4),i4.forEach(t),s4.forEach(t),Q_=m(uc),Hl=o(uc,"SPAN",{});var n4=s(Hl);J_=n(n4,"DataLoader"),n4.forEach(t),uc.forEach(t),Tf=m(e),ii=o(e,"P",{});var l4=s(ii);K_=n(l4,"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."),l4.forEach(t),zf=m(e),Et=o(e,"UL",{});var gc=s(Et);ni=o(gc,"LI",{});var H2=s(ni);Yl=o(H2,"CODE",{});var p4=s(Yl);eb=n(p4,"DataLoader(pin_memory=True, ...)"),p4.forEach(t),tb=n(H2," 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."),H2.forEach(t),ab=m(gc),li=o(gc,"LI",{});var Y2=s(li);Vl=o(Y2,"CODE",{});var h4=s(Vl);rb=n(h4,"DataLoader(num_workers=4, ...)"),h4.forEach(t),ob=n(Y2," - 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."),Y2.forEach(t),gc.forEach(t),xf=m(e),ze=o(e,"H2",{class:!0});var wc=s(ze);$t=o(wc,"A",{id:!0,class:!0,href:!0});var m4=s($t);Xl=o(m4,"SPAN",{});var f4=s(Xl);c(Ar.$$.fragment,f4),f4.forEach(t),m4.forEach(t),sb=m(wc),Zl=o(wc,"SPAN",{});var d4=s(Zl);ib=n(d4,"DeepSpeed ZeRO"),d4.forEach(t),wc.forEach(t),Gf=m(e),kt=o(e,"P",{});var vc=s(kt);nb=n(vc,"The in-depth details on how to use Deepspeed can be found "),pi=o(vc,"A",{href:!0});var c4=s(pi);lb=n(c4,"here"),c4.forEach(t),pb=n(vc,"."),vc.forEach(t),Uf=m(e),hi=o(e,"P",{});var u4=s(hi);hb=n(u4,"First, a quick decision tree:"),u4.forEach(t),Sf=m(e),Pt=o(e,"OL",{});var yc=s(Pt);Ql=o(yc,"LI",{});var g4=s(Ql);mb=n(g4,"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."),g4.forEach(t),fb=m(yc),Jl=o(yc,"LI",{});var w4=s(Jl);db=n(w4,"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."),w4.forEach(t),yc.forEach(t),jf=m(e),At=o(e,"P",{});var _c=s(At);cb=n(_c,"Now if the decision tree suggested you use DeepSpeed first you need to "),mi=o(_c,"A",{href:!0});var v4=s(mi);ub=n(v4,"install it"),v4.forEach(t),gb=n(_c,", then follow one of the following guides to create a configuration file and launch DeepSpeed."),_c.forEach(t),Df=m(e),fi=o(e,"P",{});var y4=s(fi);wb=n(y4,"Activation:"),y4.forEach(t),If=m(e),D=o(e,"UL",{});var Bt=s(D);Kl=o(Bt,"LI",{});var _4=s(Kl);Tr=o(_4,"P",{});var bc=s(Tr);vb=n(bc,"HF Trainer-based examples: see this "),di=o(bc,"A",{href:!0});var b4=s(di);yb=n(b4,"guide"),b4.forEach(t),_b=n(bc,"."),bc.forEach(t),_4.forEach(t),bb=m(Bt),zr=o(Bt,"LI",{});var Ec=s(zr);ep=o(Ec,"P",{});var E4=s(ep);Eb=n(E4,"Custom HF Trainer-based program: Same as above, but pass:"),E4.forEach(t),$b=m(Ec),c(xr.$$.fragment,Ec),Ec.forEach(t),kb=m(Bt),tp=o(Bt,"LI",{});var $4=s(tp);Gr=o($4,"P",{});var $c=s(Gr);Pb=n($c,"Deployment in Notebooks: see this "),ci=o($c,"A",{href:!0});var k4=s(ci);Ab=n(k4,"guide"),k4.forEach(t),Tb=n($c,"."),$c.forEach(t),$4.forEach(t),zb=m(Bt),ap=o(Bt,"LI",{});var P4=s(ap);xe=o(P4,"P",{});var rn=s(xe);xb=n(rn,"Custom training loop: This is somewhat complex but you can study how this is implemented in "),Ur=o(rn,"A",{href:!0,rel:!0});var A4=s(Ur);Gb=n(A4,"HF Trainer"),A4.forEach(t),Ub=n(rn," - simply search for "),rp=o(rn,"CODE",{});var T4=s(rp);Sb=n(T4,"deepspeed"),T4.forEach(t),jb=n(rn," in the code."),rn.forEach(t),P4.forEach(t),Bt.forEach(t),Nf=m(e),Ge=o(e,"H2",{class:!0});var kc=s(Ge);Tt=o(kc,"A",{id:!0,class:!0,href:!0});var z4=s(Tt);op=o(z4,"SPAN",{});var x4=s(op);c(Sr.$$.fragment,x4),x4.forEach(t),z4.forEach(t),Db=m(kc),sp=o(kc,"SPAN",{});var G4=s(sp);Ib=n(G4,"Choice of GPU"),G4.forEach(t),kc.forEach(t),Mf=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.
`),ui=o(e,"P",{});var U4=s(ui);Nb=n(U4,"Now, let\u2019s take a step back and discuss what we should optimize for when scaling the training of large models."),U4.forEach(t),Of=m(e),Ue=o(e,"H2",{class:!0});var Pc=s(Ue);zt=o(Pc,"A",{id:!0,class:!0,href:!0});var S4=s(zt);ip=o(S4,"SPAN",{});var j4=s(ip);c(jr.$$.fragment,j4),j4.forEach(t),S4.forEach(t),Mb=m(Pc),np=o(Pc,"SPAN",{});var D4=s(np);Ob=n(D4,"How to scale"),D4.forEach(t),Pc.forEach(t),qf=m(e),gi=o(e,"P",{});var I4=s(gi);qb=n(I4,"When we train models there are a two aspects we want to optimize at the same time:"),I4.forEach(t),Cf=m(e),xt=o(e,"UL",{});var Ac=s(xt);lp=o(Ac,"LI",{});var N4=s(lp);Cb=n(N4,"Data throughput/training time"),N4.forEach(t),Lb=m(Ac),pp=o(Ac,"LI",{});var M4=s(pp);Wb=n(M4,"Model performance"),M4.forEach(t),Ac.forEach(t),Lf=m(e),wi=o(e,"P",{});var O4=s(wi);Bb=n(O4,"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."),O4.forEach(t),Wf=m(e),vi=o(e,"P",{});var q4=s(vi);Fb=n(q4,"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."),q4.forEach(t),Bf=m(e),Se=o(e,"H2",{class:!0});var Tc=s(Se);Gt=o(Tc,"A",{id:!0,class:!0,href:!0});var C4=s(Gt);hp=o(C4,"SPAN",{});var L4=s(hp);c(Dr.$$.fragment,L4),L4.forEach(t),C4.forEach(t),Rb=m(Tc),mp=o(Tc,"SPAN",{});var W4=s(mp);Hb=n(W4,"Efficient Software Prebuilds"),W4.forEach(t),Tc.forEach(t),Ff=m(e),Ut=o(e,"P",{});var zc=s(Ut);Yb=n(zc,"PyTorch\u2019s "),Ir=o(zc,"A",{href:!0,rel:!0});var B4=s(Ir);Vb=n(B4,"pip and conda builds"),B4.forEach(t),Xb=n(zc," come prebuit with the cuda toolkit which is enough to run PyTorch, but it is insufficient if you need to build cuda extensions."),zc.forEach(t),Rf=m(e),St=o(e,"P",{});var xc=s(St);Zb=n(xc,"At times it may take an additional effort to pre-build some components, e.g., if you\u2019re using libraries like "),fp=o(xc,"CODE",{});var F4=s(fp);Qb=n(F4,"apex"),F4.forEach(t),Jb=n(xc," 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."),xc.forEach(t),Hf=m(e),yi=o(e,"P",{});var R4=s(yi);Kb=n(R4,"This approach is also useful if you want to tweak the pytorch source and/or make a new customized build."),R4.forEach(t),Yf=m(e),J=o(e,"P",{});var on=s(J);e1=n(on,"To find the docker image version you want start "),Nr=o(on,"A",{href:!0,rel:!0});var H4=s(Nr);t1=n(H4,"here"),H4.forEach(t),a1=n(on,", 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 "),Mr=o(on,"A",{href:!0,rel:!0});var Y4=s(Mr);r1=n(Y4,"the index of all PyTorch NGC images"),Y4.forEach(t),o1=n(on,"."),on.forEach(t),Vf=m(e),_i=o(e,"P",{});var V4=s(_i);s1=n(V4,"Next follow the instructions to download and deploy the docker image."),V4.forEach(t),Xf=m(e),je=o(e,"H2",{class:!0});var Gc=s(je);jt=o(Gc,"A",{id:!0,class:!0,href:!0});var X4=s(jt);dp=o(X4,"SPAN",{});var Z4=s(dp);c(Or.$$.fragment,Z4),Z4.forEach(t),X4.forEach(t),i1=m(Gc),cp=o(Gc,"SPAN",{});var Q4=s(cp);n1=n(Q4,"Sparsity"),Q4.forEach(t),Gc.forEach(t),Zf=m(e),De=o(e,"H3",{class:!0});var Uc=s(De);Dt=o(Uc,"A",{id:!0,class:!0,href:!0});var J4=s(Dt);up=o(J4,"SPAN",{});var K4=s(up);c(qr.$$.fragment,K4),K4.forEach(t),J4.forEach(t),l1=m(Uc),gp=o(Uc,"SPAN",{});var e5=s(gp);p1=n(e5,"Mixture of Experts"),e5.forEach(t),Uc.forEach(t),Qf=m(e),bi=o(e,"P",{});var t5=s(bi);h1=n(t5,`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.`),t5.forEach(t),Jf=m(e),Ei=o(e,"P",{});var a5=s(Ei);m1=n(a5,"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."),a5.forEach(t),Kf=m(e),$i=o(e,"P",{});var r5=s($i);f1=n(r5,"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."),r5.forEach(t),ed=m(e),ki=o(e,"P",{});var o5=s(ki);Pi=o(o5,"IMG",{src:!0,alt:!0}),o5.forEach(t),td=m(e),It=o(e,"P",{});var Sc=s(It);d1=n(Sc,"(source: "),Cr=o(Sc,"A",{href:!0,rel:!0});var s5=s(Cr);c1=n(s5,"GLAM"),s5.forEach(t),u1=n(Sc,")"),Sc.forEach(t),ad=m(e),Ai=o(e,"P",{});var i5=s(Ai);g1=n(i5,"You can find exhaustive details and comparison tables in the papers listed at the end of this section."),i5.forEach(t),rd=m(e),Ti=o(e,"P",{});var n5=s(Ti);w1=n(n5,"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."),n5.forEach(t),od=m(e),zi=o(e,"P",{});var l5=s(zi);v1=n(l5,"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."),l5.forEach(t),sd=m(e),xi=o(e,"P",{});var p5=s(xi);y1=n(p5,"Most related papers and implementations are built around Tensorflow/TPUs:"),p5.forEach(t),id=m(e),K=o(e,"UL",{});var sn=s(K);wp=o(sn,"LI",{});var h5=s(wp);Lr=o(h5,"A",{href:!0,rel:!0});var m5=s(Lr);_1=n(m5,"GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding"),m5.forEach(t),h5.forEach(t),b1=m(sn),vp=o(sn,"LI",{});var f5=s(vp);Wr=o(f5,"A",{href:!0,rel:!0});var d5=s(Wr);E1=n(d5,"Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity"),d5.forEach(t),f5.forEach(t),$1=m(sn),yp=o(sn,"LI",{});var c5=s(yp);Br=o(c5,"A",{href:!0,rel:!0});var u5=s(Br);k1=n(u5,"GLaM: Generalist Language Model (GLaM)"),u5.forEach(t),c5.forEach(t),sn.forEach(t),nd=m(e),E=o(e,"P",{});var G=s(E);P1=n(G,"And for Pytorch DeepSpeed has built one as well: "),Fr=o(G,"A",{href:!0,rel:!0});var g5=s(Fr);A1=n(g5,"DeepSpeed-MoE: Advancing Mixture-of-Experts Inference and Training to Power Next-Generation AI Scale"),g5.forEach(t),T1=n(G,", "),Rr=o(G,"A",{href:!0,rel:!0});var w5=s(Rr);z1=n(w5,"Mixture of Experts"),w5.forEach(t),x1=n(G," - blog posts:  "),Hr=o(G,"A",{href:!0,rel:!0});var v5=s(Hr);G1=n(v5,"1"),v5.forEach(t),U1=n(G,", "),Yr=o(G,"A",{href:!0,rel:!0});var y5=s(Yr);S1=n(y5,"2"),y5.forEach(t),j1=n(G," and specific deployment with large transformer-based natural language generation models: "),Vr=o(G,"A",{href:!0,rel:!0});var _5=s(Vr);D1=n(_5,"blog post"),_5.forEach(t),I1=n(G,", "),Gi=o(G,"A",{href:!0});var b5=s(Gi);N1=n(b5,"Megatron-Deepspeed branch"),b5.forEach(t),M1=n(G,"."),G.forEach(t),ld=m(e),Ie=o(e,"H2",{class:!0});var jc=s(Ie);Nt=o(jc,"A",{id:!0,class:!0,href:!0});var E5=s(Nt);_p=o(E5,"SPAN",{});var $5=s(_p);c(Xr.$$.fragment,$5),$5.forEach(t),E5.forEach(t),O1=m(jc),bp=o(jc,"SPAN",{});var k5=s(bp);q1=n(k5,"Scaling beyond a single GPU"),k5.forEach(t),jc.forEach(t),pd=m(e),Ui=o(e,"P",{});var P5=s(Ui);C1=n(P5,"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."),P5.forEach(t),hd=m(e),Mt=o(e,"P",{});var Dc=s(Mt);L1=n(Dc,"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 "),Si=o(Dc,"A",{href:!0});var A5=s(Si);W1=n(A5,"\u201CMulti-GPU training\u201D section"),A5.forEach(t),B1=n(Dc,"."),Dc.forEach(t),md=m(e),Ne=o(e,"H2",{class:!0});var Ic=s(Ne);Ot=o(Ic,"A",{id:!0,class:!0,href:!0});var T5=s(Ot);Ep=o(T5,"SPAN",{});var z5=s(Ep);c(Zr.$$.fragment,z5),z5.forEach(t),T5.forEach(t),F1=m(Ic),$p=o(Ic,"SPAN",{});var x5=s($p);R1=n(x5,"Using torch.compile"),x5.forEach(t),Ic.forEach(t),fd=m(e),qt=o(e,"P",{});var Nc=s(qt);H1=n(Nc,"PyTorch 2.0 introduces a new compile function, you can learn more about it "),Qr=o(Nc,"A",{href:!0,rel:!0});var G5=s(Qr);Y1=n(G5,"in their documentation"),G5.forEach(t),V1=n(Nc,". 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."),Nc.forEach(t),dd=m(e),O=o(e,"P",{});var _o=s(O);kp=o(_o,"CODE",{});var U5=s(kp);X1=n(U5,"torch.compile"),U5.forEach(t),Z1=n(_o," has a growing list of backends, which can be found in "),Jr=o(_o,"A",{href:!0,rel:!0});var S5=s(Jr);Q1=n(S5,"backends.py"),S5.forEach(t),J1=n(_o,`
or `),Pp=o(_o,"CODE",{});var j5=s(Pp);K1=n(j5,"torchdynamo.list_backends()"),j5.forEach(t),e2=n(_o," each of which with its optional dependencies."),_o.forEach(t),cd=m(e),ji=o(e,"P",{});var D5=s(ji);t2=n(D5,"Some of the most commonly used backends are"),D5.forEach(t),ud=m(e),Kr=o(e,"P",{});var V2=s(Kr);Ap=o(V2,"STRONG",{});var I5=s(Ap);a2=n(I5,"Debugging backends"),I5.forEach(t),r2=n(V2,":"),V2.forEach(t),gd=m(e),Ct=o(e,"UL",{});var Mc=s(Ct);Di=o(Mc,"LI",{});var X2=s(Di);Tp=o(X2,"CODE",{});var N5=s(Tp);o2=n(N5,'dynamo.optimize("eager")'),N5.forEach(t),s2=n(X2," - Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues."),X2.forEach(t),i2=m(Mc),Ii=o(Mc,"LI",{});var Z2=s(Ii);zp=o(Z2,"CODE",{});var M5=s(zp);n2=n(M5,'dynamo.optimize("aot_eager")'),M5.forEach(t),l2=n(Z2," - 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."),Z2.forEach(t),Mc.forEach(t),wd=m(e),eo=o(e,"P",{});var Q2=s(eo);xp=o(Q2,"STRONG",{});var O5=s(xp);p2=n(O5,"Training & inference backends"),O5.forEach(t),h2=n(Q2,":"),Q2.forEach(t),vd=m(e),I=o(e,"UL",{});var Ft=s(I);to=o(Ft,"LI",{});var Oc=s(to);Gp=o(Oc,"CODE",{});var q5=s(Gp);m2=n(q5,'dynamo.optimize("inductor")'),q5.forEach(t),f2=n(Oc," - Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels  "),ao=o(Oc,"A",{href:!0,rel:!0});var C5=s(ao);d2=n(C5,"Read more"),C5.forEach(t),Oc.forEach(t),c2=m(Ft),ro=o(Ft,"LI",{});var qc=s(ro);Up=o(qc,"CODE",{});var L5=s(Up);u2=n(L5,'dynamo.optimize("nvfuser")'),L5.forEach(t),g2=n(qc," -  nvFuser with TorchScript. "),oo=o(qc,"A",{href:!0,rel:!0});var W5=s(oo);w2=n(W5,"Read more"),W5.forEach(t),qc.forEach(t),v2=m(Ft),so=o(Ft,"LI",{});var Cc=s(so);Sp=o(Cc,"CODE",{});var B5=s(Sp);y2=n(B5,'dynamo.optimize("aot_nvfuser")'),B5.forEach(t),_2=n(Cc," -  nvFuser with AotAutograd. "),io=o(Cc,"A",{href:!0,rel:!0});var F5=s(io);b2=n(F5,"Read more"),F5.forEach(t),Cc.forEach(t),E2=m(Ft),no=o(Ft,"LI",{});var Lc=s(no);jp=o(Lc,"CODE",{});var R5=s(jp);$2=n(R5,'dynamo.optimize("aot_cudagraphs")'),R5.forEach(t),k2=n(Lc," - cudagraphs with AotAutograd. "),lo=o(Lc,"A",{href:!0,rel:!0});var H5=s(lo);P2=n(H5,"Read more"),H5.forEach(t),Lc.forEach(t),Ft.forEach(t),yd=m(e),po=o(e,"P",{});var J2=s(po);Dp=o(J2,"STRONG",{});var Y5=s(Dp);A2=n(Y5,"Inference-only backend"),Y5.forEach(t),T2=n(J2,"s:"),J2.forEach(t),_d=m(e),N=o(e,"UL",{});var Rt=s(N);ho=o(Rt,"LI",{});var Wc=s(ho);Ip=o(Wc,"CODE",{});var V5=s(Ip);z2=n(V5,'dynamo.optimize("ofi")'),V5.forEach(t),x2=n(Wc," -  Uses Torchscript optimize_for_inference.  "),mo=o(Wc,"A",{href:!0,rel:!0});var X5=s(mo);G2=n(X5,"Read more"),X5.forEach(t),Wc.forEach(t),U2=m(Rt),fo=o(Rt,"LI",{});var Bc=s(fo);Np=o(Bc,"CODE",{});var Z5=s(Np);S2=n(Z5,'dynamo.optimize("fx2trt")'),Z5.forEach(t),j2=n(Bc," -  Uses Nvidia TensorRT for inference optimizations.  "),co=o(Bc,"A",{href:!0,rel:!0});var Q5=s(co);D2=n(Q5,"Read more"),Q5.forEach(t),Bc.forEach(t),I2=m(Rt),uo=o(Rt,"LI",{});var Fc=s(uo);Mp=o(Fc,"CODE",{});var J5=s(Mp);N2=n(J5,'dynamo.optimize("onnxrt")'),J5.forEach(t),M2=n(Fc," -  Uses ONNXRT for inference on CPU/GPU.  "),go=o(Fc,"A",{href:!0,rel:!0});var K5=s(go);O2=n(K5,"Read more"),K5.forEach(t),Fc.forEach(t),q2=m(Rt),wo=o(Rt,"LI",{});var Rc=s(wo);Op=o(Rc,"CODE",{});var e6=s(Op);C2=n(e6,'dynamo.optimize("ipex")'),e6.forEach(t),L2=n(Rc," -  Uses IPEX for inference on CPU.  "),vo=o(Rc,"A",{href:!0,rel:!0});var t6=s(vo);W2=n(t6,"Read more"),t6.forEach(t),Rc.forEach(t),Rt.forEach(t),this.h()},h(){f(b,"name","hf:doc:metadata"),f(b,"content",JSON.stringify(m6)),f(U,"id","efficient-training-on-a-single-gpu"),f(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"),f(U,"href","#efficient-training-on-a-single-gpu"),f($,"class","relative group"),f(Eo,"href","perf_train_gpu_many"),f($o,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(Yt,"href","https://huggingface.co/docs/accelerate/"),f(Yt,"rel","nofollow"),f(ko,"align","left"),f(Po,"align","left"),f(Ao,"align","left"),f(To,"align","left"),f(zo,"align","left"),f(xo,"align","left"),f(Go,"align","left"),f(Uo,"align","left"),f(So,"align","left"),f(jo,"align","left"),f(Do,"align","left"),f(Io,"align","left"),f(No,"align","left"),f(Mo,"align","left"),f(Oo,"align","left"),f(qo,"align","left"),f(Co,"align","left"),f(Lo,"align","left"),f(Wo,"align","left"),f(Bo,"align","left"),f(Fo,"align","left"),f(Ro,"align","left"),f(Ho,"align","left"),f(Yo,"align","left"),f(Xo,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(Le,"id","load-model"),f(Le,"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"),f(Le,"href","#load-model"),f(he,"class","relative group"),f(Re,"id","vanilla-training"),f(Re,"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"),f(Re,"href","#vanilla-training"),f(me,"class","relative group"),f(es,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(Ye,"id","anatomy-of-models-operations"),f(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"),f(Ye,"href","#anatomy-of-models-operations"),f(fe,"class","relative group"),f(ua,"href","https://arxiv.org/abs/2007.00072"),f(ua,"rel","nofollow"),f(Ve,"id","anatomy-of-models-memory"),f(Ve,"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"),f(Ve,"href","#anatomy-of-models-memory"),f(de,"class","relative group"),f(wa,"href","https://github.com/TimDettmers/bitsandbytes"),f(wa,"rel","nofollow"),f(Qe,"id","batch-sizes"),f(Qe,"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"),f(Qe,"href","#batch-sizes"),f(ce,"class","relative group"),f(ya,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#input-features"),f(ya,"rel","nofollow"),f(_a,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#batch-size"),f(_a,"rel","nofollow"),f(Ea,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc"),f(Ea,"rel","nofollow"),f($a,"href","https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#dim-quantization"),f($a,"rel","nofollow"),f(Ke,"id","gradient-accumulation"),f(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"),f(Ke,"href","#gradient-accumulation"),f(ue,"class","relative group"),f($s,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(ks,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),f(Ta,"href","https://github.com/huggingface/transformers/issues/14608#issuecomment-1004392537"),f(Ta,"rel","nofollow"),f(za,"href","https://github.com/huggingface/transformers/issues/15026#issuecomment-1005033957"),f(za,"rel","nofollow"),f(et,"id","gradient-checkpointing"),f(et,"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"),f(et,"href","#gradient-checkpointing"),f(ge,"class","relative group"),f(Ga,"href","https://medium.com/tensorflow/fitting-larger-networks-into-memory-583e3c758ff9"),f(Ga,"rel","nofollow"),f(Ts,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(zs,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),f(at,"id","floating-data-types"),f(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"),f(at,"href","#floating-data-types"),f(we,"class","relative group"),K2(Ss.src,e3="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/tf32-bf16-fp16-fp32.png")||f(Ss,"src",e3),f(Ss,"alt","data types"),f(Ma,"href","https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/"),f(Ma,"rel","nofollow"),f(rt,"id","fp16-training"),f(rt,"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"),f(rt,"href","#fp16-training"),f(ye,"class","relative group"),f(ot,"id","bf16"),f(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"),f(ot,"href","#bf16"),f(_e,"class","relative group"),f(st,"id","tf32"),f(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"),f(st,"href","#tf32"),f(be,"class","relative group"),f(Ya,"href","https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/"),f(Ya,"rel","nofollow"),f(Xa,"href","https://github.com/huggingface/transformers/issues/14608#issuecomment-1004390803"),f(Xa,"rel","nofollow"),f(Za,"href","https://github.com/huggingface/transformers/issues/15026#issuecomment-1004543189"),f(Za,"rel","nofollow"),f(lt,"id","optimizer"),f(lt,"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"),f(lt,"href","#optimizer"),f(Ee,"class","relative group"),f(Ka,"href","https://github.com/NVIDIA/apex"),f(Ka,"rel","nofollow"),f(er,"href","https://github.com/TimDettmers/bitsandbytes"),f(er,"rel","nofollow"),f(ft,"id","adafactor"),f(ft,"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"),f(ft,"href","#adafactor"),f($e,"class","relative group"),f(ct,"id","8bit-adam"),f(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"),f(ct,"href","#8bit-adam"),f(ke,"class","relative group"),f(Xs,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(Zs,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(hr,"href","https://github.com/TimDettmers/bitsandbytes"),f(hr,"rel","nofollow"),K2(ti.src,t3="https://huggingface.co/datasets/lvwerra/repo-images/raw/main/gpu-memory-savings.png")||f(ti,"src",t3),f(ti,"alt","png"),f(wt,"id","multitensor"),f(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"),f(wt,"href","#multitensor"),f(Pe,"class","relative group"),f(vt,"id","using-accelerate"),f(vt,"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"),f(vt,"href","#using-accelerate"),f(Ae,"class","relative group"),f(ai,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),f(ri,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),f(_r,"href","https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader"),f(_r,"rel","nofollow"),f(si,"href","/docs/transformers/v4.27.1/en/main_classes/model#transformers.PreTrainedModel.gradient_checkpointing_enable"),f(br,"href","https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator"),f(br,"rel","nofollow"),f(Er,"href","https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare"),f(Er,"rel","nofollow"),f(kr,"href","https://huggingface.co/docs/accelerate/index"),f(kr,"rel","nofollow"),f(bt,"id","dataloader"),f(bt,"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"),f(bt,"href","#dataloader"),f(Te,"class","relative group"),f($t,"id","deepspeed-zero"),f($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"),f($t,"href","#deepspeed-zero"),f(ze,"class","relative group"),f(pi,"href","main_classes/deepspeed"),f(mi,"href","main_classes/deepspeed#installation"),f(di,"href","main_classes/deepspeed#deployment-with-one-gpu"),f(ci,"href","main_classes/deepspeed#deployment-in-notebooks"),f(Ur,"href","https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py"),f(Ur,"rel","nofollow"),f(Tt,"id","choice-of-gpu"),f(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"),f(Tt,"href","#choice-of-gpu"),f(Ge,"class","relative group"),f(zt,"id","how-to-scale"),f(zt,"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"),f(zt,"href","#how-to-scale"),f(Ue,"class","relative group"),f(Gt,"id","efficient-software-prebuilds"),f(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"),f(Gt,"href","#efficient-software-prebuilds"),f(Se,"class","relative group"),f(Ir,"href","https://pytorch.org/get-started/locally/#start-locally"),f(Ir,"rel","nofollow"),f(Nr,"href","https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/"),f(Nr,"rel","nofollow"),f(Mr,"href","https://ngc.nvidia.com/catalog/containers/nvidia:pytorch"),f(Mr,"rel","nofollow"),f(jt,"id","sparsity"),f(jt,"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"),f(jt,"href","#sparsity"),f(je,"class","relative group"),f(Dt,"id","mixture-of-experts"),f(Dt,"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"),f(Dt,"href","#mixture-of-experts"),f(De,"class","relative group"),K2(Pi.src,a3="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/perf-moe-transformer.png")||f(Pi,"src",a3),f(Pi,"alt","MoE Transformer 2x block"),f(Cr,"href","https://ai.googleblog.com/2021/12/more-efficient-in-context-learning-with.html"),f(Cr,"rel","nofollow"),f(Lr,"href","https://arxiv.org/abs/2006.16668"),f(Lr,"rel","nofollow"),f(Wr,"href","https://arxiv.org/abs/2101.03961"),f(Wr,"rel","nofollow"),f(Br,"href","https://ai.googleblog.com/2021/12/more-efficient-in-context-learning-with.html"),f(Br,"rel","nofollow"),f(Fr,"href","https://arxiv.org/abs/2201.05596"),f(Fr,"rel","nofollow"),f(Rr,"href","https://www.deepspeed.ai/tutorials/mixture-of-experts/"),f(Rr,"rel","nofollow"),f(Hr,"href","https://www.microsoft.com/en-us/research/blog/deepspeed-powers-8x-larger-moe-model-training-with-high-performance/"),f(Hr,"rel","nofollow"),f(Yr,"href","https://www.microsoft.com/en-us/research/publication/scalable-and-efficient-moe-training-for-multitask-multilingual-models/"),f(Yr,"rel","nofollow"),f(Vr,"href","https://www.deepspeed.ai/news/2021/12/09/deepspeed-moe-nlg.html"),f(Vr,"rel","nofollow"),f(Gi,"href","Thttps://github.com/microsoft/Megatron-DeepSpeed/tree/moe-training"),f(Nt,"id","scaling-beyond-a-single-gpu"),f(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"),f(Nt,"href","#scaling-beyond-a-single-gpu"),f(Ie,"class","relative group"),f(Si,"href","perf_train_gpu_many"),f(Ot,"id","using-torchcompile"),f(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"),f(Ot,"href","#using-torchcompile"),f(Ne,"class","relative group"),f(Qr,"href","https://pytorch.org/get-started/pytorch-2.0/"),f(Qr,"rel","nofollow"),f(Jr,"href","https://github.com/pytorch/pytorch/blob/master/torch/_dynamo/optimizations/backends.py"),f(Jr,"rel","nofollow"),f(ao,"href","https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747"),f(ao,"rel","nofollow"),f(oo,"href","https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593"),f(oo,"rel","nofollow"),f(io,"href","https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593"),f(io,"rel","nofollow"),f(lo,"href","https://github.com/pytorch/torchdynamo/pull/757"),f(lo,"rel","nofollow"),f(mo,"href","https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html"),f(mo,"rel","nofollow"),f(co,"href","https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst"),f(co,"rel","nofollow"),f(go,"href","https://onnxruntime.ai/"),f(go,"rel","nofollow"),f(vo,"href","https://github.com/intel/intel-extension-for-pytorch"),f(vo,"rel","nofollow")},m(e,l){a(document.head,b),p(e,A,l),p(e,$,l),a($,U),a(U,nn),u(Ht,nn,null),a($,Hc),a($,ln),a(ln,Yc),p(e,Wp,l),p(e,Me,l),a(Me,Vc),a(Me,Eo),a(Eo,Xc),a(Me,Zc),p(e,Bp,l),p(e,q,l),a(q,Qc),a(q,$o),a($o,Jc),a(q,Kc),a(q,Yt),a(Yt,eu),a(q,tu),p(e,Fp,l),p(e,Oe,l),a(Oe,pn),a(pn,ae),a(ae,ko),a(ko,au),a(ae,ru),a(ae,Po),a(Po,ou),a(ae,su),a(ae,Ao),a(Ao,iu),a(Oe,nu),a(Oe,k),a(k,re),a(re,To),a(To,lu),a(re,pu),a(re,zo),a(zo,hu),a(re,mu),a(re,xo),a(xo,fu),a(k,du),a(k,oe),a(oe,Go),a(Go,cu),a(oe,uu),a(oe,Uo),a(Uo,gu),a(oe,wu),a(oe,So),a(So,vu),a(k,yu),a(k,se),a(se,jo),a(jo,_u),a(se,bu),a(se,Do),a(Do,Eu),a(se,$u),a(se,Io),a(Io,ku),a(k,Pu),a(k,ie),a(ie,No),a(No,Au),a(ie,Tu),a(ie,Mo),a(Mo,zu),a(ie,xu),a(ie,Oo),a(Oo,Gu),a(k,Uu),a(k,ne),a(ne,qo),a(qo,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(ge,lv),a(ge,al),a(al,pv),p(e,tm,l),p(e,As,l),a(As,hv),p(e,am,l),p(e,tt,l),a(tt,mv),a(tt,Ga),a(Ga,fv),a(tt,dv),p(e,rm,l),p(e,R,l),a(R,cv),a(R,Ts),a(Ts,uv),a(R,gv),a(R,zs),a(zs,wv),a(R,vv),p(e,om,l),u(Ua,e,l),p(e,sm,l),u(Sa,e,l),p(e,im,l),p(e,xs,l),a(xs,yv),p(e,nm,l),p(e,we,l),a(we,at),a(at,rl),u(ja,rl,null),a(we,_v),a(we,ol),a(ol,bv),p(e,lm,l),p(e,Gs,l),a(Gs,Ev),p(e,pm,l),p(e,j,l),a(j,Da),a(Da,$v),a(Da,sl),a(sl,kv),a(Da,Pv),a(j,Av),a(j,Ia),a(Ia,Tv),a(Ia,il),a(il,zv),a(Ia,xv),a(j,Gv),a(j,Na),a(Na,Uv),a(Na,nl),a(nl,Sv),a(Na,jv),a(j,Dv),a(j,ll),a(ll,Iv),p(e,hm,l),p(e,Us,l),a(Us,Nv),p(e,mm,l),p(e,ve,l),a(ve,Ss),a(ve,Mv),a(ve,Ma),a(Ma,Ov),a(ve,qv),p(e,fm,l),p(e,js,l),a(js,Cv),p(e,dm,l),p(e,ye,l),a(ye,rt),a(rt,pl),u(Oa,pl,null),a(ye,Lv),a(ye,hl),a(hl,Wv),p(e,cm,l),p(e,H,l),a(H,Bv),a(H,ml),a(ml,Fv),a(H,Rv),a(H,fl),a(fl,Hv),a(H,Yv),p(e,um,l),u(qa,e,l),p(e,gm,l),u(Ca,e,l),p(e,wm,l),p(e,Ds,l),a(Ds,Vv),p(e,vm,l),u(La,e,l),p(e,ym,l),u(Wa,e,l),p(e,_m,l),p(e,Is,l),a(Is,Xv),p(e,bm,l),p(e,_e,l),a(_e,ot),a(ot,dl),u(Ba,dl,null),a(_e,Zv),a(_e,cl),a(cl,Qv),p(e,Em,l),p(e,Ns,l),a(Ns,Jv),p(e,$m,l),u(Fa,e,l),p(e,km,l),p(e,be,l),a(be,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2),a(I,so),a(so,Sp),a(Sp,y2),a(so,_2),a(so,io),a(io,b2),a(I,E2),a(I,no),a(no,jp),a(jp,$2),a(no,k2),a(no,lo),a(lo,P2),p(e,yd,l),p(e,po,l),a(po,Dp),a(Dp,A2),a(po,T2),p(e,_d,l),p(e,N,l),a(N,ho),a(ho,Ip),a(Ip,z2),a(ho,x2),a(ho,mo),a(mo,G2),a(N,U2),a(N,fo),a(fo,Np),a(Np,S2),a(fo,j2),a(fo,co),a(co,D2),a(N,I2),a(N,uo),a(uo,Mp),a(Mp,N2),a(uo,M2),a(uo,go),a(go,O2),a(N,q2),a(N,wo),a(wo,Op),a(Op,C2),a(wo,L2),a(wo,vo),a(vo,W2),bd=!0},p(e,[l]){const yo={};l&2&&(yo.$$scope={dirty:l,ctx:e}),Fe.$set(yo);const qp={};l&2&&(qp.$$scope={dirty:l,ctx:e}),ut.$set(qp)},i(e){bd||(g(Ht.$$.fragment,e),g(Vt.$$.fragment,e),g(Xt.$$.fragment,e),g(Zt.$$.fragment,e),g(Qt.$$.fragment,e),g(Jt.$$.fragment,e),g(Kt.$$.fragment,e),g(ea.$$.fragment,e),g(ta.$$.fragment,e),g(aa.$$.fragment,e),g(ra.$$.fragment,e),g(Fe.$$.fragment,e),g(oa.$$.fragment,e),g(sa.$$.fragment,e),g(ia.$$.fragment,e),g(na.$$.fragment,e),g(ga.$$.fragment,e),g(va.$$.fragment,e),g(ka.$$.fragment,e),g(Pa.$$.fragment,e),g(Aa.$$.fragment,e),g(xa.$$.fragment,e),g(Ua.$$.fragment,e),g(Sa.$$.fragment,e),g(ja.$$.fragment,e),g(Oa.$$.fragment,e),g(qa.$$.fragment,e),g(Ca.$$.fragment,e),g(La.$$.fragment,e),g(Wa.$$.fragment,e),g(Ba.$$.fragment,e),g(Fa.$$.fragment,e),g(Ra.$$.fragment,e),g(Ha.$$.fragment,e),g(Va.$$.fragment,e),g(Qa.$$.fragment,e),g(Ja.$$.fragment,e),g(or.$$.fragment,e),g(sr.$$.fragment,e),g(ir.$$.fragment,e),g(nr.$$.fragment,e),g(lr.$$.fragment,e),g(pr.$$.fragment,e),g(ut.$$.fragment,e),g(mr.$$.fragment,e),g(fr.$$.fragment,e),g(dr.$$.fragment,e),g(cr.$$.fragment,e),g(ur.$$.fragment,e),g(gr.$$.fragment,e),g(wr.$$.fragment,e),g(vr.$$.fragment,e),g(yr.$$.fragment,e),g($r.$$.fragment,e),g(Pr.$$.fragment,e),g(Ar.$$.fragment,e),g(xr.$$.fragment,e),g(Sr.$$.fragment,e),g(jr.$$.fragment,e),g(Dr.$$.fragment,e),g(Or.$$.fragment,e),g(qr.$$.fragment,e),g(Xr.$$.fragment,e),g(Zr.$$.fragment,e),bd=!0)},o(e){w(Ht.$$.fragment,e),w(Vt.$$.fragment,e),w(Xt.$$.fragment,e),w(Zt.$$.fragment,e),w(Qt.$$.fragment,e),w(Jt.$$.fragment,e),w(Kt.$$.fragment,e),w(ea.$$.fragment,e),w(ta.$$.fragment,e),w(aa.$$.fragment,e),w(ra.$$.fragment,e),w(Fe.$$.fragment,e),w(oa.$$.fragment,e),w(sa.$$.fragment,e),w(ia.$$.fragment,e),w(na.$$.fragment,e),w(ga.$$.fragment,e),w(va.$$.fragment,e),w(ka.$$.fragment,e),w(Pa.$$.fragment,e),w(Aa.$$.fragment,e),w(xa.$$.fragment,e),w(Ua.$$.fragment,e),w(Sa.$$.fragment,e),w(ja.$$.fragment,e),w(Oa.$$.fragment,e),w(qa.$$.fragment,e),w(Ca.$$.fragment,e),w(La.$$.fragment,e),w(Wa.$$.fragment,e),w(Ba.$$.fragment,e),w(Fa.$$.fragment,e),w(Ra.$$.fragment,e),w(Ha.$$.fragment,e),w(Va.$$.fragment,e),w(Qa.$$.fragment,e),w(Ja.$$.fragment,e),w(or.$$.fragment,e),w(sr.$$.fragment,e),w(ir.$$.fragment,e),w(nr.$$.fragment,e),w(lr.$$.fragment,e),w(pr.$$.fragment,e),w(ut.$$.fragment,e),w(mr.$$.fragment,e),w(fr.$$.fragment,e),w(dr.$$.fragment,e),w(cr.$$.fragment,e),w(ur.$$.fragment,e),w(gr.$$.fragment,e),w(wr.$$.fragment,e),w(vr.$$.fragment,e),w(yr.$$.fragment,e),w($r.$$.fragment,e),w(Pr.$$.fragment,e),w(Ar.$$.fragment,e),w(xr.$$.fragment,e),w(Sr.$$.fragment,e),w(jr.$$.fragment,e),w(Dr.$$.fragment,e),w(Or.$$.fragment,e),w(qr.$$.fragment,e),w(Xr.$$.fragment,e),w(Zr.$$.fragment,e),bd=!1},d(e){t(b),e&&t(A),e&&t($),v(Ht),e&&t(Wp),e&&t(Me),e&&t(Bp),e&&t(q),e&&t(Fp),e&&t(Oe),e&&t(Rp),e&&t(Vo),e&&t(Hp),v(Vt,e),e&&t(Yp),e&&t(C),e&&t(Vp),e&&t(qe),e&&t(Xp),v(Xt,e),e&&t(Zp),e&&t(Ce),e&&t(Qp),v(Zt,e),e&&t(Jp),e&&t(Zo),e&&t(Kp),v(Qt,e),e&&t(eh),e&&t(Qo),e&&t(th),v(Jt,e),e&&t(ah),e&&t(Jo),e&&t(rh),e&&t(he),v(Kt),e&&t(oh),e&&t(We),e&&t(sh),v(ea,e),e&&t(ih),e&&t(Be),e&&t(nh),v(ta,e),e&&t(lh),v(aa,e),e&&t(ph),e&&t(Ko),e&&t(hh),v(ra,e),e&&t(mh),v(Fe,e),e&&t(fh),e&&t(me),v(oa),e&&t(dh),e&&t(He),e&&t(ch),v(sa,e),e&&t(uh),v(ia,e),e&&t(gh),e&&t(ts),e&&t(wh),e&&t(fe),v(na),e&&t(vh),e&&t(as),e&&t(yh),e&&t(L),e&&t(_h),e&&t(rs),e&&t(bh),e&&t(ca),e&&t(Eh),e&&t(de),v(ga),e&&t($h),e&&t(os),e&&t(kh),e&&t(ss),e&&t(Ph),e&&t(is),e&&t(Ah),e&&t(Xe),e&&t(Th),e&&t(ns),e&&t(zh),e&&t(W),e&&t(xh),e&&t(ps),e&&t(Gh),e&&t(hs),e&&t(Uh),e&&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&&t(Rf),e&&t(St),e&&t(Hf),e&&t(yi),e&&t(Yf),e&&t(J),e&&t(Vf),e&&t(_i),e&&t(Xf),e&&t(je),v(Or),e&&t(Zf),e&&t(De),v(qr),e&&t(Qf),e&&t(bi),e&&t(Jf),e&&t(Ei),e&&t(Kf),e&&t($i),e&&t(ed),e&&t(ki),e&&t(td),e&&t(It),e&&t(ad),e&&t(Ai),e&&t(rd),e&&t(Ti),e&&t(od),e&&t(zi),e&&t(sd),e&&t(xi),e&&t(id),e&&t(K),e&&t(nd),e&&t(E),e&&t(ld),e&&t(Ie),v(Xr),e&&t(pd),e&&t(Ui),e&&t(hd),e&&t(Mt),e&&t(md),e&&t(Ne),v(Zr),e&&t(fd),e&&t(qt),e&&t(dd),e&&t(O),e&&t(cd),e&&t(ji),e&&t(ud),e&&t(Kr),e&&t(gd),e&&t(Ct),e&&t(wd),e&&t(eo),e&&t(vd),e&&t(I),e&&t(yd),e&&t(po),e&&t(_d),e&&t(N)}}}const m6={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-torchcompile",title:"Using torch.compile"}],title:"Efficient Training on a Single GPU"};function f6(bo){return n6(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class w6 extends r6{constructor(b){super();o6(this,b,f6,h6,s6,{})}}export{w6 as default,m6 as metadata};
