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