import{S as m5,i as f5,s as d5,e as r,k as h,w as d,t as n,M as c5,c as s,d as t,m,a as i,x as c,h as l,b as f,N as Db,G as a,g as p,y as u,q as g,o as w,B as v,v as u5}from"../chunks/vendor-hf-doc-builder.js";import{T as h5}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 g5(Fr){let b,A;return{c(){b=r("p"),A=n("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(E){b=s(E,"P",{});var U=i(b);A=l(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(E,U){p(E,b,U),a(b,A)},d(E){E&&t(b)}}}function w5(Fr){let b;return{c(){b=n(`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=l(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,E){p(A,b,E)},d(A){A&&t(b)}}}function v5(Fr){let b,A,E,U,zo,Mt,Gd,Go,xd,Vl,De,Ud,Hr,jd,Sd,Yl,I,Dd,Rr,Nd,Id,qt,Md,qd,Xl,Ne,xo,ee,Vr,Od,Ld,Yr,Cd,Wd,Xr,Bd,Fd,k,te,Zr,Hd,Rd,Qr,Vd,Yd,Jr,Xd,Zd,ae,Kr,Qd,Jd,es,Kd,ec,ts,tc,ac,re,as,rc,sc,rs,ic,oc,ss,nc,lc,se,is,pc,hc,os,mc,fc,ns,dc,cc,ie,ls,uc,gc,ps,wc,vc,hs,yc,_c,oe,ms,bc,$c,fs,Ec,kc,ds,Pc,Ac,ne,cs,Tc,zc,us,Gc,xc,gs,Uc,Zl,ws,jc,Ql,Ot,Jl,M,Sc,Uo,Dc,Nc,jo,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b,Cl,Ir,pb,ff,$,hb,Mr,mb,fb,qr,db,cb,Or,ub,gb,Lr,wb,vb,Cr,yb,_b,Ki,bb,$b,df,Se,jt,Wl,Wr,Eb,Bl,kb,cf,eo,Pb,uf,St,Ab,to,Tb,zb,gf;return Mt=new _({}),Ot=new y({props:{code:"pip install transformers datasets accelerate nvidia-ml-py3",highlighted:"pip install transformers datasets accelerate nvidia-ml-py3"}}),Ct=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>)`}}),Wt=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()`}}),Bt=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.`}}),Ft=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.`}}),Ht=new _({}),Rt=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.`}}),Vt=new y({props:{code:"nvidia-smi",highlighted:"nvidia-smi"}}),Yt=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 |
+-----------------------------------------------------------------------------+`}}),Xt=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>,
}`}}),Ce=new h5({props:{$$slots:{default:[g5]},$$scope:{ctx:Fr}}}),Zt=new _({}),Qt=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)`}}),Jt=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.`}}),Kt=new _({}),la=new _({}),ha=new _({}),ga=new _({}),wa=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)`}}),va=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.`}}),ba=new _({}),Ea=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)`}}),ka=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.`}}),Pa=new _({}),xa=new _({}),Ua=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)`}}),ja=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.`}}),Sa=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)`}}),Da=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.`}}),Na=new _({}),Ia=new y({props:{code:"TrainingArguments(bf16=True)",highlighted:'TrainingArguments(bf16=<span class="hljs-literal">True</span>)'}}),Ma=new _({}),qa=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`}}),La=new y({props:{code:"TrainingArguments(tf32=True)",highlighted:'TrainingArguments(tf32=<span class="hljs-literal">True</span>)'}}),Ba=new _({}),Fa=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}]`}}),Qa=new _({}),Ja=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)`}}),Ka=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.`}}),er=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)`}}),tr=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.`}}),ar=new _({}),mt=new h5({props:{$$slots:{default:[w5]},$$scope:{ctx:Fr}}}),sr=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,
)`}}),ir=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)`}}),or=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.`}}),nr=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)`}}),lr=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.`}}),pr=new _({}),hr=new _({}),mr=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,
)`}}),fr=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()`}}),gr=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.`}}),vr=new _({}),yr=new _({}),$r=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>)'}}),Pr=new _({}),Ar=new _({}),Tr=new _({}),Ur=new _({}),jr=new _({}),Wr=new _({}),{c(){b=r("meta"),A=h(),E=r("h1"),U=r("a"),zo=r("span"),d(Mt.$$.fragment),Gd=h(),Go=r("span"),xd=n("Efficient Training on a Single GPU"),Vl=h(),De=r("p"),Ud=n("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 "),Hr=r("a"),jd=n("multi-GPU section"),Sd=n("."),Yl=h(),I=r("p"),Dd=n("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 "),Rr=r("a"),Nd=n("Trainer"),Id=n(" and "),qt=r("a"),Md=n("\u{1F917} Accelerate"),qd=n(". Each method can improve speed or memory usage which is summarized in the table below:"),Xl=h(),Ne=r("table"),xo=r("thead"),ee=r("tr"),Vr=r("th"),Od=n("Method"),Ld=h(),Yr=r("th"),Cd=n("Speed"),Wd=h(),Xr=r("th"),Bd=n("Memory"),Fd=h(),k=r("tbody"),te=r("tr"),Zr=r("td"),Hd=n("Gradient accumulation"),Rd=h(),Qr=r("td"),Vd=n("No"),Yd=h(),Jr=r("td"),Xd=n("Yes"),Zd=h(),ae=r("tr"),Kr=r("td"),Qd=n("Gradient checkpointing"),Jd=h(),es=r("td"),Kd=n("No"),ec=h(),ts=r("td"),tc=n("Yes"),ac=h(),re=r("tr"),as=r("td"),rc=n("Mixed precision training"),sc=h(),rs=r("td"),ic=n("Yes"),oc=h(),ss=r("td"),nc=n("(No)"),lc=h(),se=r("tr"),is=r("td"),pc=n("Batch size"),hc=h(),os=r("td"),mc=n("Yes"),fc=h(),ns=r("td"),dc=n("Yes"),cc=h(),ie=r("tr"),ls=r("td"),uc=n("Optimizer choice"),gc=h(),ps=r("td"),wc=n("Yes"),vc=h(),hs=r("td"),yc=n("Yes"),_c=h(),oe=r("tr"),ms=r("td"),bc=n("DataLoader"),$c=h(),fs=r("td"),Ec=n("Yes"),kc=h(),ds=r("td"),Pc=n("No"),Ac=h(),ne=r("tr"),cs=r("td"),Tc=n("DeepSpeed Zero"),zc=h(),us=r("td"),Gc=n("No"),xc=h(),gs=r("td"),Uc=n("Yes"),Zl=h(),ws=r("p"),jc=n("A bracket means that it might not be strictly the case but is usually either not a main concern or negligable. Before we start make sure you have installed the following libraries:"),Ql=h(),d(Ot.$$.fragment),Jl=h(),M=r("p"),Sc=n("The "),Uo=r("code"),Dc=n("nvidia-ml-py3"),Nc=n(" library allows us to monitor the memory usage of the models from within Python. You might be familiar with the "),jo=r("code"),Ic=n("nvidia-smi"),Mc=n(" command in the terminal - this library allows to access the same information in Python directly."),Kl=h(),Ie=r("p"),qc=n("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 "),Lt=r("a"),So=r("code"),Oc=n("Dataset"),Lc=n(" with PyTorch format."),ep=h(),d(Ct.$$.fragment),tp=h(),Me=r("p"),Cc=n("We want to print some summary statistics for the GPU utilization and the training run with the "),vs=r("a"),Wc=n("Trainer"),Bc=n(". We setup a two helper functions to do just that:"),ap=h(),d(Wt.$$.fragment),rp=h(),ys=r("p"),Fc=n("Let\u2019s verify that we start with a free GPU memory:"),sp=h(),d(Bt.$$.fragment),ip=h(),_s=r("p"),Hc=n("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."),op=h(),d(Ft.$$.fragment),np=h(),bs=r("p"),Rc=n("We see that the kernels alone take up 1.3GB of GPU memory. Now let\u2019s see how much space the model uses."),lp=h(),le=r("h2"),qe=r("a"),Do=r("span"),d(Ht.$$.fragment),Vc=h(),No=r("span"),Yc=n("Load Model"),pp=h(),Oe=r("p"),Xc=n("First, we load the "),Io=r("code"),Zc=n("bert-large-uncased"),Qc=n(" model. We load the model weights directly to the GPU so that we can check how much space just weights use."),hp=h(),d(Rt.$$.fragment),mp=h(),Le=r("p"),Jc=n("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 "),Mo=r("code"),Kc=n("nvidia-smi"),eu=n(" CLI:"),fp=h(),d(Vt.$$.fragment),dp=h(),d(Yt.$$.fragment),cp=h(),$s=r("p"),tu=n("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:"),up=h(),d(Xt.$$.fragment),gp=h(),d(Ce.$$.fragment),wp=h(),pe=r("h2"),We=r("a"),qo=r("span"),d(Zt.$$.fragment),au=h(),Oo=r("span"),ru=n("Vanilla Training"),vp=h(),Be=r("p"),su=n("As a first experiment we will use the "),Es=r("a"),iu=n("Trainer"),ou=n(" and train the model without any further modifications and a batch size of 4:"),yp=h(),d(Qt.$$.fragment),_p=h(),d(Jt.$$.fragment),bp=h(),ks=r("p"),nu=n("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."),$p=h(),he=r("h2"),Fe=r("a"),Lo=r("span"),d(Kt.$$.fragment),lu=h(),Co=r("span"),pu=n("Anatomy of Model's Operations"),Ep=h(),Ps=r("p"),hu=n("Transformers architecture includes 3 main groups of operations grouped below by compute-intensity."),kp=h(),q=r("ol"),ea=r("li"),Wo=r("p"),Bo=r("strong"),mu=n("Tensor Contractions"),fu=h(),ta=r("p"),du=n("Linear layers and components of Multi-Head Attention all do batched "),Fo=r("strong"),cu=n("matrix-matrix multiplications"),uu=n(". These operations are the most compute-intensive part of training a transformer."),gu=h(),aa=r("li"),Ho=r("p"),Ro=r("strong"),wu=n("Statistical Normalizations"),vu=h(),ra=r("p"),yu=n("Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more "),Vo=r("strong"),_u=n("reduction operations"),bu=n(", the result of which is then applied via a map."),$u=h(),sa=r("li"),Yo=r("p"),Xo=r("strong"),Eu=n("Element-wise Operators"),ku=h(),ia=r("p"),Pu=n("These are the remaining operators: "),Zo=r("strong"),Au=n("biases, dropout, activations, and residual connections"),Tu=n(". These are the least compute-intensive operations."),Pp=h(),As=r("p"),zu=n("This knowledge can be helpful to know when analyzing performance bottlenecks."),Ap=h(),oa=r("p"),Gu=n("This summary is derived from "),na=r("a"),xu=n("Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020"),Tp=h(),me=r("h2"),He=r("a"),Qo=r("span"),d(la.$$.fragment),Uu=h(),Jo=r("span"),ju=n("Anatomy of Model's Memory"),zp=n(`

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
`),Ts=r("p"),Su=n("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."),Gp=h(),zs=r("p"),Du=n("Let\u2019s look at the details."),xp=h(),Gs=r("p"),Ko=r("strong"),Nu=n("Model Weights:"),Up=h(),Re=r("ul"),en=r("li"),Iu=n("4 bytes * number of parameters for fp32 training"),Mu=h(),tn=r("li"),qu=n("6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)"),jp=h(),xs=r("p"),an=r("strong"),Ou=n("Optimizer States:"),Sp=h(),O=r("ul"),rn=r("li"),Lu=n("8 bytes * number of parameters for normal AdamW (maintains 2 states)"),Cu=h(),Us=r("li"),Wu=n("2 bytes * number of parameters for 8-bit AdamW optimizers like "),pa=r("a"),Bu=n("bitsandbytes"),Fu=h(),sn=r("li"),Hu=n("4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)"),Dp=h(),js=r("p"),on=r("strong"),Ru=n("Gradients"),Np=h(),Ss=r("ul"),nn=r("li"),Vu=n("4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)"),Ip=h(),Ds=r("p"),ln=r("strong"),Yu=n("Forward Activations"),Mp=h(),Ns=r("ul"),pn=r("li"),Xu=n("size depends on many factors, the key ones being sequence length, hidden size and batch size."),qp=h(),Is=r("p"),Zu=n("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."),Op=h(),Ms=r("p"),hn=r("strong"),Qu=n("Temporary Memory"),Lp=h(),qs=r("p"),Ju=n("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."),Cp=h(),Os=r("p"),mn=r("strong"),Ku=n("Functionality-specific memory"),Wp=h(),Ls=r("p"),eg=n("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."),Bp=h(),Cs=r("p"),Ve=r("strong"),fn=r("code"),tg=n("forward"),ag=n(" vs "),dn=r("code"),rg=n("backward"),sg=n(" Execution Speed"),Fp=h(),Ws=r("p"),ig=n("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)."),Hp=h(),Bs=r("p"),og=n("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."),Rp=h(),fe=r("h2"),Ye=r("a"),cn=r("span"),d(ha.$$.fragment),ng=h(),un=r("span"),lg=n("Batch sizes"),Vp=h(),Fs=r("p"),pg=n("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."),Yp=h(),L=r("p"),hg=n("For example for fully connected layers (which correspond to GEMMs), NVIDIA provides recommendations for "),ma=r("a"),mg=n("input/output neuron counts"),fg=n(" and "),fa=r("a"),dg=n("batch size"),cg=n("."),Xp=h(),da=r("p"),ca=r("a"),ug=n("Tensor Core Requirements"),gg=n(" 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!"),Zp=h(),Xe=r("p"),wg=n("For parameters that are small, there is also "),ua=r("a"),vg=n("Dimension Quantization Effects"),yg=n(" to consider, this is where tiling happens and the right multiplier can have a significant speedup."),Qp=h(),de=r("h2"),Ze=r("a"),gn=r("span"),d(ga.$$.fragment),_g=h(),wn=r("span"),bg=n("Gradient Accumulation"),Jp=h(),Hs=r("p"),$g=n("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."),Kp=h(),j=r("p"),Eg=n("We can use gradient accumulation in the "),Rs=r("a"),kg=n("Trainer"),Pg=n(" by simply adding the "),vn=r("code"),Ag=n("gradient_accumulation_steps"),Tg=n(" argument to "),Vs=r("a"),zg=n("TrainingArguments"),Gg=n(". Let\u2019s see how it impacts the models memory footprint:"),eh=h(),d(wa.$$.fragment),th=h(),d(va.$$.fragment),ah=h(),T=r("p"),xg=n("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 "),yn=r("code"),Ug=n("per_device_train_batch_size=1"),jg=n(" and "),_n=r("code"),Sg=n("gradient_accumulation_steps=64"),Dg=n(" but instead "),bn=r("code"),Ng=n("per_device_train_batch_size=4"),Ig=n(" and "),$n=r("code"),Mg=n("gradient_accumulation_steps=16"),qg=n(" which has the same effective batch size while making better use of the available GPU resources."),rh=h(),C=r("p"),Og=n("For more details see the benchmarks for "),ya=r("a"),Lg=n("RTX-3090"),Cg=n(`
and `),_a=r("a"),Wg=n("A100"),Bg=n("."),sh=h(),Ys=r("p"),Fg=n("Next we have a look at another trick to save a little bit more GPU memory called gradient checkpointing."),ih=h(),ce=r("h2"),Qe=r("a"),En=r("span"),d(ba.$$.fragment),Hg=h(),kn=r("span"),Rg=n("Gradient Checkpointing"),oh=h(),Xs=r("p"),Vg=n("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."),nh=h(),Je=r("p"),Yg=n("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 "),$a=r("a"),Xg=n("this great article"),Zg=n(" explaining the ideas behind gradient checkpointing."),lh=h(),W=r("p"),Qg=n("To enable gradient checkpointing in the "),Zs=r("a"),Jg=n("Trainer"),Kg=n(" we only need ot pass it as a flag to the "),Qs=r("a"),ew=n("TrainingArguments"),tw=n(". Everything else is handled under the hood:"),ph=h(),d(Ea.$$.fragment),hh=h(),d(ka.$$.fragment),mh=h(),Js=r("p"),aw=n("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."),fh=h(),ue=r("h2"),Ke=r("a"),Pn=r("span"),d(Pa.$$.fragment),rw=h(),An=r("span"),sw=n("Floating Data Types"),dh=h(),Ks=r("p"),iw=n("The idea of mixed precision training is that no 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. Here are the commonly used floating point data types choice of which impacts both memory usage and throughput:"),ch=h(),S=r("ul"),Aa=r("li"),ow=n("fp32 ("),Tn=r("code"),nw=n("float32"),lw=n(")"),pw=h(),Ta=r("li"),hw=n("fp16 ("),zn=r("code"),mw=n("float16"),fw=n(")"),dw=h(),za=r("li"),cw=n("bf16 ("),Gn=r("code"),uw=n("bfloat16"),gw=n(")"),ww=h(),xn=r("li"),vw=n("tf32 (CUDA internal data type)"),uh=h(),ei=r("p"),yw=n("Here is a diagram that shows how these data types correlate to each other."),gh=h(),ge=r("p"),ti=r("img"),_w=n(`
(source: `),Ga=r("a"),bw=n("NVIDIA Blog"),$w=n(")"),wh=h(),ai=r("p"),Ew=n("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/"),vh=h(),we=r("h3"),et=r("a"),Un=r("span"),d(xa.$$.fragment),kw=h(),jn=r("span"),Pw=n("FP16 Training"),yh=h(),B=r("p"),Aw=n("The idea of mixed precision training is that no 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 "),Sn=r("code"),Tw=n("fp16"),zw=n(" flag to "),Dn=r("code"),Gw=n("True"),xw=n(":"),_h=h(),d(Ua.$$.fragment),bh=h(),d(ja.$$.fragment),$h=h(),ri=r("p"),Uw=n("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:"),Eh=h(),d(Sa.$$.fragment),kh=h(),d(Da.$$.fragment),Ph=h(),si=r("p"),jw=n("We can see that with these tweaks we use about half the GPU memory as at the beginning while also being slightly faster."),Ah=h(),ve=r("h3"),tt=r("a"),Nn=r("span"),d(Na.$$.fragment),Sw=h(),In=r("span"),Dw=n("BF16"),Th=n("\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"),ii=r("p"),Nw=n("You can enable BF16 in the \u{1F917} Trainer with:"),zh=h(),d(Ia.$$.fragment),Gh=h(),ye=r("h3"),at=r("a"),Mn=r("span"),d(Ma.$$.fragment),Iw=h(),qn=r("span"),Mw=n("TF32"),xh=n(`

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.
`),oi=r("p"),qw=n("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:"),Uh=h(),d(qa.$$.fragment),jh=h(),ni=r("p"),Ow=n("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."),Sh=h(),rt=r("p"),Lw=n("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 "),Oa=r("a"),Cw=n("NVIDIA research"),Ww=n(" the majority of machine learning training shouldn\u2019t be impacted and showed the same perplexity and convergence as the fp32 training."),Dh=h(),li=r("p"),Bw=n("If you\u2019re already using fp16 or bf16 mixed precision it may help with the throughput as well."),Nh=h(),pi=r("p"),Fw=n("You can enable this mode in the \u{1F917} Trainer with:"),Ih=h(),d(La.$$.fragment),Mh=h(),hi=r("p"),Hw=n("By default the PyTorch default is used."),qh=h(),F=r("p"),Rw=n("Note: tf32 mode is internal to CUDA and can\u2019t be accessed directly via "),On=r("code"),Vw=n("tensor.to(dtype=torch.tf32)"),Yw=n(" as "),Ln=r("code"),Xw=n("torch.tf32"),Zw=n(" doesn\u2019t exit."),Oh=h(),st=r("p"),Qw=n("Note: you need "),Cn=r("code"),Jw=n("torch>=1.7"),Kw=n(" to enjoy this feature."),Lh=h(),H=r("p"),ev=n(`You can also see a variety of benchmarks on tf32 vs other precisions:
`),Ca=r("a"),tv=n("RTX-3090"),av=n(` and
`),Wa=r("a"),rv=n("A100"),sv=n("."),Ch=h(),mi=r("p"),iv=n("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."),Wh=h(),_e=r("h2"),it=r("a"),Wn=r("span"),d(Ba.$$.fragment),ov=h(),Bn=r("span"),nv=n("Optimizer"),Bh=h(),fi=r("p"),lv=n("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."),Fh=h(),ot=r("p"),pv=n("HF Trainer integrates a variety of optimisers that can be used out of box. To activate the desired optimizer simply pass the "),Fn=r("code"),hv=n("--optim"),mv=n(" flag to the command line."),Hh=h(),di=r("p"),fv=n("To see which optimizers are currently supported:"),Rh=h(),d(Fa.$$.fragment),Vh=h(),R=r("p"),dv=n("For example, if you have "),Ha=r("a"),cv=n("NVIDIA/apex"),uv=n(" installed "),Hn=r("code"),gv=n("--optim adamw_apex_fused"),wv=n(" will give you the fastest training experience among all supported AdamW optimizers."),Yh=h(),V=r("p"),vv=n("On the other hand "),Ra=r("a"),yv=n("8bit BNB optimizer"),_v=n(" 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. XXX: update once  "),Va=r("a"),bv=n("https://github.com/huggingface/transformers/pull/15622"),$v=n(" is merged."),Xh=h(),nt=r("p"),Ev=n("Let\u2019s get a feel for the numbers and use for example use a 3B-parameter model, like "),Rn=r("code"),kv=n("t5-3b"),Pv=n(". 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:"),Zh=h(),Y=r("ul"),Ya=r("li"),Av=n("A standard AdamW uses 8 bytes for each parameter, here the optimizer will need ("),Vn=r("code"),Tv=n("8*3"),zv=n(") 24GB of GPU memory."),Gv=h(),Xa=r("li"),xv=n("Adafactor uses slightly more than 4 bytes, so ("),Yn=r("code"),Uv=n("4*3"),jv=n(") 12GB and then some extra."),Sv=h(),Za=r("li"),Dv=n("8bit BNB quantized optimizer will use only ("),Xn=r("code"),Nv=n("2*3"),Iv=n(") 6GB if all optimizer states are quantized."),Qh=h(),ci=r("p"),Mv=n("Let\u2019s have a look at Adafactor first."),Jh=h(),be=r("h3"),lt=r("a"),Zn=r("span"),d(Qa.$$.fragment),qv=h(),Qn=r("span"),Ov=n("Adafactor"),Kh=h(),pt=r("p"),Lv=n("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 "),Jn=r("code"),Cv=n('optim="adafactor"'),Wv=n(":"),em=h(),d(Ja.$$.fragment),tm=h(),d(Ka.$$.fragment),am=h(),ui=r("p"),Bv=n("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:"),rm=h(),d(er.$$.fragment),sm=h(),d(tr.$$.fragment),im=h(),gi=r("p"),Fv=n("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."),om=h(),$e=r("h3"),ht=r("a"),Kn=r("span"),d(ar.$$.fragment),Hv=h(),el=r("span"),Rv=n("8-bit Adam"),nm=h(),wi=r("p"),Vv=n("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."),lm=h(),z=r("p"),Yv=n("In contrast to the previous approaches is this one not integrated into the "),vi=r("a"),Xv=n("Trainer"),Zv=n(" as a simple flag. We need to install the 8-bit optimizer and then pass it as a custom optimizer to the "),yi=r("a"),Qv=n("Trainer"),Jv=n(". Follow the installation guide in the Github "),rr=r("a"),Kv=n("repo"),ey=n(" to install the "),tl=r("code"),ty=n("bitsandbytes"),ay=n(" library that implements the 8-bit Adam optimizer."),pm=h(),_i=r("p"),ry=n("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."),hm=h(),d(mt.$$.fragment),mm=h(),d(sr.$$.fragment),fm=h(),ft=r("p"),sy=n("We can now pass the custom optimizer as an argument to the "),al=r("code"),iy=n("Trainer"),oy=n(":"),dm=h(),d(ir.$$.fragment),cm=h(),d(or.$$.fragment),um=h(),bi=r("p"),ny=n("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:"),gm=h(),d(nr.$$.fragment),wm=h(),d(lr.$$.fragment),vm=h(),$i=r("p"),ly=n("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:"),ym=h(),Ei=r("p"),ki=r("img"),_m=h(),Ee=r("h3"),dt=r("a"),rl=r("span"),d(pr.$$.fragment),py=h(),sl=r("span"),il=r("code"),hy=n("_multi_tensor"),bm=n(`

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
`),ke=r("h2"),ct=r("a"),ol=r("span"),d(hr.$$.fragment),my=h(),nl=r("span"),fy=n("Using \u{1F917} Accelerate"),$m=h(),X=r("p"),dy=n("So far we have used the "),Pi=r("a"),cy=n("Trainer"),uy=n(" 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 "),Ai=r("a"),gy=n("TrainingArguments"),wy=n(" to wrap the training settings:"),Em=h(),d(mr.$$.fragment),km=h(),Ti=r("p"),vy=n("The full example training loop with \u{1F917} Accelerate is only a handful of lines of code long:"),Pm=h(),d(fr.$$.fragment),Am=h(),P=r("p"),yy=n("First we wrap the dataset in a "),dr=r("a"),ll=r("code"),_y=n("DataLoader"),by=n(". Then we can enable gradient checkpointing by calling the model\u2019s "),zi=r("a"),$y=n("gradient_checkpointing_enable()"),Ey=n(" method. When we initialize the "),cr=r("a"),pl=r("code"),ky=n("Accelerator"),Py=n(" we can specifiy if we want to use mixed precision training and it will take care of it for us in the "),hl=r("code"),Ay=n("prepare"),Ty=n(" call. During the "),ur=r("a"),ml=r("code"),zy=n("prepare"),Gy=n(" 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."),Tm=h(),ut=r("p"),xy=n("Finally, we can write the main training loop. Note that the "),fl=r("code"),Uy=n("backward"),jy=n(" 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:"),zm=h(),d(gr.$$.fragment),Gm=h(),gt=r("p"),Sy=n("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 "),wr=r("a"),Dy=n("Accelerate documentation"),Ny=n("."),xm=h(),Pe=r("h2"),wt=r("a"),dl=r("span"),d(vr.$$.fragment),Iy=h(),cl=r("span"),My=n("DataLoader"),Um=h(),Gi=r("p"),qy=n("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."),jm=h(),vt=r("ul"),xi=r("li"),ul=r("code"),Oy=n("DataLoader(pin_memory=True, ...)"),Ly=n(" 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."),Cy=h(),Ui=r("li"),gl=r("code"),Wy=n("DataLoader(num_workers=4, ...)"),By=n(" - 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."),Sm=h(),Ae=r("h2"),yt=r("a"),wl=r("span"),d(yr.$$.fragment),Fy=h(),vl=r("span"),Hy=n("DeepSpeed ZeRO"),Dm=h(),_t=r("p"),Ry=n("The in-depth details on how to use Deepspeed can be found "),ji=r("a"),Vy=n("here"),Yy=n("."),Nm=h(),Si=r("p"),Xy=n("First, a quick decision tree:"),Im=h(),bt=r("ol"),yl=r("li"),Zy=n("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."),Qy=h(),_l=r("li"),Jy=n("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."),Mm=h(),$t=r("p"),Ky=n("Now if the decision tree suggested you use DeepSpeed first you need to "),Di=r("a"),e_=n("install it"),t_=n(", then follow one of the following guides to create a configuration file and launch DeepSpeed."),qm=h(),Ni=r("p"),a_=n("Activation:"),Om=h(),D=r("ul"),bl=r("li"),_r=r("p"),r_=n("HF Trainer-based examples: see this "),Ii=r("a"),s_=n("guide"),i_=n("."),o_=h(),br=r("li"),$l=r("p"),n_=n("Custom HF Trainer-based program: Same as above, but pass:"),l_=h(),d($r.$$.fragment),p_=h(),El=r("li"),Er=r("p"),h_=n("Deployment in Notebooks: see this "),Mi=r("a"),m_=n("guide"),f_=n("."),d_=h(),kl=r("li"),Te=r("p"),c_=n("Custom training loop: This is somewhat complex but you can study how this is implemented in "),kr=r("a"),u_=n("HF Trainer"),g_=n(" - simply search for "),Pl=r("code"),w_=n("deepspeed"),v_=n(" in the code."),Lm=h(),ze=r("h2"),Et=r("a"),Al=r("span"),d(Pr.$$.fragment),y_=h(),Tl=r("span"),__=n("Choice of GPU"),Cm=n(`

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