import{S as ns,i as ls,s as is,e as o,k as u,w,t as p,M as ps,c as n,d as e,m,a as l,x as b,h as f,b as h,G as t,g as d,y as k,q as j,o as E,B as T,v as fs}from"../chunks/vendor-hf-doc-builder.js";import{T as Oa}from"../chunks/Tip-hf-doc-builder.js";import{Y as Ia}from"../chunks/Youtube-hf-doc-builder.js";import{I as ea}from"../chunks/IconCopyLink-hf-doc-builder.js";import{C as U}from"../chunks/CodeBlock-hf-doc-builder.js";import{D as ds}from"../chunks/DocNotebookDropdown-hf-doc-builder.js";import{F as os,M as Ma}from"../chunks/Markdown-hf-doc-builder.js";function hs(gt){let g,A;return{c(){g=o("p"),A=p(`You will see a warning about some of the pretrained weights not being used and some weights being randomly
initialized. Don\u2019t worry, this is completely normal! The pretrained head of the BERT model is discarded, and replaced with a randomly initialized classification head. You will fine-tune this new model head on your sequence classification task, transferring the knowledge of the pretrained model to it.`)},l(c){g=n(c,"P",{});var $=l(g);A=f($,`You will see a warning about some of the pretrained weights not being used and some weights being randomly
initialized. Don\u2019t worry, this is completely normal! The pretrained head of the BERT model is discarded, and replaced with a randomly initialized classification head. You will fine-tune this new model head on your sequence classification task, transferring the knowledge of the pretrained model to it.`),$.forEach(e)},m(c,$){d(c,g,$),t(g,A)},d(c){c&&e(g)}}}function us(gt){let g,A,c,$,P,z,M,q,Ge,B,S,Ue,H,ta,_t,N,_e,kt,D,ve,Je,vt,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,ye,It,$e,it,yt,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,$t,ue,dt,we,be,Be,oe,aa,At,ke,He,Z,Q,Pt,je,Ot,F,Qe,L,me,Ve,Se,Mt,et,sa,Bt,V,Ye,Ce,ht,R,tt,Ne,Ee,Ke,at,ut,zt,G,Ht,C,ne,ce,Fe,Te,mt,xt,Xt,ee,Ae,le,st,wt,Yt,r,_,ge,Pe,Kt,qt,ra,Le,We,i;return g=new Ia({props:{id:"nvBXf7s7vTI"}}),z=new ea({}),De=new U({props:{code:`from transformers import AutoModelForSequenceClassification

model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)`,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-base-cased&quot;</span>, num_labels=<span class="hljs-number">5</span>)`}}),Xe=new Oa({props:{$$slots:{default:[hs]},$$scope:{ctx:gt}}}),fe=new ea({}),X=new U({props:{code:`from transformers import TrainingArguments

training_args = TrainingArguments(output_dir="test_trainer")`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TrainingArguments

<span class="hljs-meta">&gt;&gt;&gt; </span>training_args = TrainingArguments(output_dir=<span class="hljs-string">&quot;test_trainer&quot;</span>)`}}),O=new ea({}),F=new U({props:{code:`import numpy as np
import evaluate

metric = evaluate.load("accuracy")`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> evaluate

<span class="hljs-meta">&gt;&gt;&gt; </span>metric = evaluate.load(<span class="hljs-string">&quot;accuracy&quot;</span>)`}}),R=new U({props:{code:`def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = np.argmax(logits, axis=-1)
    return metric.compute(predictions=predictions, references=labels)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">compute_metrics</span>(<span class="hljs-params">eval_pred</span>):
<span class="hljs-meta">... </span>    logits, labels = eval_pred
<span class="hljs-meta">... </span>    predictions = np.argmax(logits, axis=-<span class="hljs-number">1</span>)
<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> metric.compute(predictions=predictions, references=labels)`}}),G=new U({props:{code:`from transformers import TrainingArguments, Trainer

training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TrainingArguments, Trainer

<span class="hljs-meta">&gt;&gt;&gt; </span>training_args = TrainingArguments(output_dir=<span class="hljs-string">&quot;test_trainer&quot;</span>, evaluation_strategy=<span class="hljs-string">&quot;epoch&quot;</span>)`}}),Fe=new ea({}),r=new U({props:{code:`trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=small_train_dataset,
    eval_dataset=small_eval_dataset,
    compute_metrics=compute_metrics,
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>trainer = Trainer(
<span class="hljs-meta">... </span>    model=model,
<span class="hljs-meta">... </span>    args=training_args,
<span class="hljs-meta">... </span>    train_dataset=small_train_dataset,
<span class="hljs-meta">... </span>    eval_dataset=small_eval_dataset,
<span class="hljs-meta">... </span>    compute_metrics=compute_metrics,
<span class="hljs-meta">... </span>)`}}),We=new U({props:{code:"trainer.train()",highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.train()'}}),{c(){w(g.$$.fragment),A=u(),c=o("h2"),$=o("a"),P=o("span"),w(z.$$.fragment),M=u(),q=o("span"),Ge=p("Train with PyTorch Trainer"),B=u(),S=o("p"),Ue=p("\u{1F917} Transformers provides a "),H=o("a"),ta=p("Trainer"),_t=p(" class optimized for training \u{1F917} Transformers models, making it easier to start training without manually writing your own training loop. The "),N=o("a"),_e=p("Trainer"),kt=p(" API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision."),D=u(),ve=o("p"),Je=p("Start by loading your model and specify the number of expected labels. From the Yelp Review "),vt=o("a"),ot=p("dataset card"),jt=p(", you know there are five labels:"),Ut=u(),w(De.$$.fragment),ie=u(),w(Xe.$$.fragment),J=u(),I=o("h3"),ae=o("a"),pe=o("span"),w(fe.$$.fragment),nt=u(),Ie=o("span"),Lt=p("Training hyperparameters"),Dt=u(),Y=o("p"),lt=p("Next, create a "),se=o("a"),Et=p("TrainingArguments"),ze=p(" class which contains all the hyperparameters you can tune as well as flags for activating different training options. For this tutorial you can start with the default training "),Oe=o("a"),ye=p("hyperparameters"),It=p(", but feel free to experiment with these to find your optimal settings."),$e=u(),it=o("p"),yt=p("Specify where to save the checkpoints from your training:"),Tt=u(),w(X.$$.fragment),Ze=u(),W=o("h3"),K=o("a"),xe=o("span"),w(O.$$.fragment),pt=u(),ft=o("span"),re=p("Evaluate"),de=u(),x=o("p"),he=o("a"),Jt=p("Trainer"),qe=p(" does not automatically evaluate model performance during training. You\u2019ll need to pass "),Me=o("a"),$t=p("Trainer"),ue=p(" a function to compute and report metrics. The "),dt=o("a"),we=p("\u{1F917} Evaluate"),be=p(" library provides a simple "),Be=o("a"),oe=o("code"),aa=p("accuracy"),At=p(" function you can load with the "),ke=o("a"),He=p("evaluate.load"),Z=p(" (see this "),Q=o("a"),Pt=p("quicktour"),je=p(" for more information) function:"),Ot=u(),w(F.$$.fragment),Qe=u(),L=o("p"),me=p("Call "),Ve=o("code"),Se=p("compute"),Mt=p(" on "),et=o("code"),sa=p("metric"),Bt=p(" to calculate the accuracy of your predictions. Before passing your predictions to "),V=o("code"),Ye=p("compute"),Ce=p(", you need to convert the predictions to logits (remember all \u{1F917} Transformers models return logits):"),ht=u(),w(R.$$.fragment),tt=u(),Ne=o("p"),Ee=p("If you\u2019d like to monitor your evaluation metrics during fine-tuning, specify the "),Ke=o("code"),at=p("evaluation_strategy"),ut=p(" parameter in your training arguments to report the evaluation metric at the end of each epoch:"),zt=u(),w(G.$$.fragment),Ht=u(),C=o("h3"),ne=o("a"),ce=o("span"),w(Fe.$$.fragment),Te=u(),mt=o("span"),xt=p("Trainer"),Xt=u(),ee=o("p"),Ae=p("Create a "),le=o("a"),st=p("Trainer"),wt=p(" object with your model, training arguments, training and test datasets, and evaluation function:"),Yt=u(),w(r.$$.fragment),_=u(),ge=o("p"),Pe=p("Then fine-tune your model by calling "),Kt=o("a"),qt=p("train()"),ra=p(":"),Le=u(),w(We.$$.fragment),this.h()},l(a){b(g.$$.fragment,a),A=m(a),c=n(a,"H2",{class:!0});var y=l(c);$=n(y,"A",{id:!0,class:!0,href:!0});var Re=l($);P=n(Re,"SPAN",{});var pa=l(P);b(z.$$.fragment,pa),pa.forEach(e),Re.forEach(e),M=m(y),q=n(y,"SPAN",{});var Zt=l(q);Ge=f(Zt,"Train with PyTorch Trainer"),Zt.forEach(e),y.forEach(e),B=m(a),S=n(a,"P",{});var St=l(S);Ue=f(St,"\u{1F917} Transformers provides a "),H=n(St,"A",{href:!0});var fa=l(H);ta=f(fa,"Trainer"),fa.forEach(e),_t=f(St," class optimized for training \u{1F917} Transformers models, making it easier to start training without manually writing your own training loop. The "),N=n(St,"A",{href:!0});var da=l(N);_e=f(da,"Trainer"),da.forEach(e),kt=f(St," API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision."),St.forEach(e),D=m(a),ve=n(a,"P",{});var oa=l(ve);Je=f(oa,"Start by loading your model and specify the number of expected labels. From the Yelp Review "),vt=n(oa,"A",{href:!0,rel:!0});var rt=l(vt);ot=f(rt,"dataset card"),rt.forEach(e),jt=f(oa,", you know there are five labels:"),oa.forEach(e),Ut=m(a),b(De.$$.fragment,a),ie=m(a),b(Xe.$$.fragment,a),J=m(a),I=n(a,"H3",{class:!0});var Qt=l(I);ae=n(Qt,"A",{id:!0,class:!0,href:!0});var na=l(ae);pe=n(na,"SPAN",{});var ga=l(pe);b(fe.$$.fragment,ga),ga.forEach(e),na.forEach(e),nt=m(Qt),Ie=n(Qt,"SPAN",{});var Ct=l(Ie);Lt=f(Ct,"Training hyperparameters"),Ct.forEach(e),Qt.forEach(e),Dt=m(a),Y=n(a,"P",{});var Nt=l(Y);lt=f(Nt,"Next, create a "),se=n(Nt,"A",{href:!0});var _a=l(se);Et=f(_a,"TrainingArguments"),_a.forEach(e),ze=f(Nt," class which contains all the hyperparameters you can tune as well as flags for activating different training options. For this tutorial you can start with the default training "),Oe=n(Nt,"A",{href:!0,rel:!0});var va=l(Oe);ye=f(va,"hyperparameters"),va.forEach(e),It=f(Nt,", but feel free to experiment with these to find your optimal settings."),Nt.forEach(e),$e=m(a),it=n(a,"P",{});var ha=l(it);yt=f(ha,"Specify where to save the checkpoints from your training:"),ha.forEach(e),Tt=m(a),b(X.$$.fragment,a),Ze=m(a),W=n(a,"H3",{class:!0});var ct=l(W);K=n(ct,"A",{id:!0,class:!0,href:!0});var la=l(K);xe=n(la,"SPAN",{});var s=l(xe);b(O.$$.fragment,s),s.forEach(e),la.forEach(e),pt=m(ct),ft=n(ct,"SPAN",{});var v=l(ft);re=f(v,"Evaluate"),v.forEach(e),ct.forEach(e),de=m(a),x=n(a,"P",{});var te=l(x);he=n(te,"A",{href:!0});var ia=l(he);Jt=f(ia,"Trainer"),ia.forEach(e),qe=f(te," does not automatically evaluate model performance during training. You\u2019ll need to pass "),Me=n(te,"A",{href:!0});var ua=l(Me);$t=f(ua,"Trainer"),ua.forEach(e),ue=f(te," a function to compute and report metrics. The "),dt=n(te,"A",{href:!0,rel:!0});var wa=l(dt);we=f(wa,"\u{1F917} Evaluate"),wa.forEach(e),be=f(te," library provides a simple "),Be=n(te,"A",{href:!0,rel:!0});var Wt=l(Be);oe=n(Wt,"CODE",{});var Vt=l(oe);aa=f(Vt,"accuracy"),Vt.forEach(e),Wt.forEach(e),At=f(te," function you can load with the "),ke=n(te,"A",{href:!0,rel:!0});var ma=l(ke);He=f(ma,"evaluate.load"),ma.forEach(e),Z=f(te," (see this "),Q=n(te,"A",{href:!0,rel:!0});var Rt=l(Q);Pt=f(Rt,"quicktour"),Rt.forEach(e),je=f(te," for more information) function:"),te.forEach(e),Ot=m(a),b(F.$$.fragment,a),Qe=m(a),L=n(a,"P",{});var bt=l(L);me=f(bt,"Call "),Ve=n(bt,"CODE",{});var Gt=l(Ve);Se=f(Gt,"compute"),Gt.forEach(e),Mt=f(bt," on "),et=n(bt,"CODE",{});var ya=l(et);sa=f(ya,"metric"),ya.forEach(e),Bt=f(bt," to calculate the accuracy of your predictions. Before passing your predictions to "),V=n(bt,"CODE",{});var ca=l(V);Ye=f(ca,"compute"),ca.forEach(e),Ce=f(bt,", you need to convert the predictions to logits (remember all \u{1F917} Transformers models return logits):"),bt.forEach(e),ht=m(a),b(R.$$.fragment,a),tt=m(a),Ne=n(a,"P",{});var ba=l(Ne);Ee=f(ba,"If you\u2019d like to monitor your evaluation metrics during fine-tuning, specify the "),Ke=n(ba,"CODE",{});var ka=l(Ke);at=f(ka,"evaluation_strategy"),ka.forEach(e),ut=f(ba," parameter in your training arguments to report the evaluation metric at the end of each epoch:"),ba.forEach(e),zt=m(a),b(G.$$.fragment,a),Ht=m(a),C=n(a,"H3",{class:!0});var Ft=l(C);ne=n(Ft,"A",{id:!0,class:!0,href:!0});var Aa=l(ne);ce=n(Aa,"SPAN",{});var ja=l(ce);b(Fe.$$.fragment,ja),ja.forEach(e),Aa.forEach(e),Te=m(Ft),mt=n(Ft,"SPAN",{});var Pa=l(mt);xt=f(Pa,"Trainer"),Pa.forEach(e),Ft.forEach(e),Xt=m(a),ee=n(a,"P",{});var Ea=l(ee);Ae=f(Ea,"Create a "),le=n(Ea,"A",{href:!0});var Ta=l(le);st=f(Ta,"Trainer"),Ta.forEach(e),wt=f(Ea," object with your model, training arguments, training and test datasets, and evaluation function:"),Ea.forEach(e),Yt=m(a),b(r.$$.fragment,a),_=m(a),ge=n(a,"P",{});var $a=l(ge);Pe=f($a,"Then fine-tune your model by calling "),Kt=n($a,"A",{href:!0});var xa=l(Kt);qt=f(xa,"train()"),xa.forEach(e),ra=f($a,":"),$a.forEach(e),Le=m(a),b(We.$$.fragment,a),this.h()},h(){h($,"id","train-with-pytorch-trainer"),h($,"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"),h($,"href","#train-with-pytorch-trainer"),h(c,"class","relative group"),h(H,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(N,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(vt,"href","https://huggingface.co/datasets/yelp_review_full#data-fields"),h(vt,"rel","nofollow"),h(ae,"id","training-hyperparameters"),h(ae,"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"),h(ae,"href","#training-hyperparameters"),h(I,"class","relative group"),h(se,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.TrainingArguments"),h(Oe,"href","https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments"),h(Oe,"rel","nofollow"),h(K,"id","evaluate"),h(K,"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"),h(K,"href","#evaluate"),h(W,"class","relative group"),h(he,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(Me,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(dt,"href","https://huggingface.co/docs/evaluate/index"),h(dt,"rel","nofollow"),h(Be,"href","https://huggingface.co/spaces/evaluate-metric/accuracy"),h(Be,"rel","nofollow"),h(ke,"href","https://huggingface.co/docs/evaluate/main/en/package_reference/loading_methods#evaluate.load"),h(ke,"rel","nofollow"),h(Q,"href","https://huggingface.co/docs/evaluate/a_quick_tour"),h(Q,"rel","nofollow"),h(ne,"id","trainer"),h(ne,"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"),h(ne,"href","#trainer"),h(C,"class","relative group"),h(le,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(Kt,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer.train")},m(a,y){k(g,a,y),d(a,A,y),d(a,c,y),t(c,$),t($,P),k(z,P,null),t(c,M),t(c,q),t(q,Ge),d(a,B,y),d(a,S,y),t(S,Ue),t(S,H),t(H,ta),t(S,_t),t(S,N),t(N,_e),t(S,kt),d(a,D,y),d(a,ve,y),t(ve,Je),t(ve,vt),t(vt,ot),t(ve,jt),d(a,Ut,y),k(De,a,y),d(a,ie,y),k(Xe,a,y),d(a,J,y),d(a,I,y),t(I,ae),t(ae,pe),k(fe,pe,null),t(I,nt),t(I,Ie),t(Ie,Lt),d(a,Dt,y),d(a,Y,y),t(Y,lt),t(Y,se),t(se,Et),t(Y,ze),t(Y,Oe),t(Oe,ye),t(Y,It),d(a,$e,y),d(a,it,y),t(it,yt),d(a,Tt,y),k(X,a,y),d(a,Ze,y),d(a,W,y),t(W,K),t(K,xe),k(O,xe,null),t(W,pt),t(W,ft),t(ft,re),d(a,de,y),d(a,x,y),t(x,he),t(he,Jt),t(x,qe),t(x,Me),t(Me,$t),t(x,ue),t(x,dt),t(dt,we),t(x,be),t(x,Be),t(Be,oe),t(oe,aa),t(x,At),t(x,ke),t(ke,He),t(x,Z),t(x,Q),t(Q,Pt),t(x,je),d(a,Ot,y),k(F,a,y),d(a,Qe,y),d(a,L,y),t(L,me),t(L,Ve),t(Ve,Se),t(L,Mt),t(L,et),t(et,sa),t(L,Bt),t(L,V),t(V,Ye),t(L,Ce),d(a,ht,y),k(R,a,y),d(a,tt,y),d(a,Ne,y),t(Ne,Ee),t(Ne,Ke),t(Ke,at),t(Ne,ut),d(a,zt,y),k(G,a,y),d(a,Ht,y),d(a,C,y),t(C,ne),t(ne,ce),k(Fe,ce,null),t(C,Te),t(C,mt),t(mt,xt),d(a,Xt,y),d(a,ee,y),t(ee,Ae),t(ee,le),t(le,st),t(ee,wt),d(a,Yt,y),k(r,a,y),d(a,_,y),d(a,ge,y),t(ge,Pe),t(ge,Kt),t(Kt,qt),t(ge,ra),d(a,Le,y),k(We,a,y),i=!0},p(a,y){const Re={};y&2&&(Re.$$scope={dirty:y,ctx:a}),Xe.$set(Re)},i(a){i||(j(g.$$.fragment,a),j(z.$$.fragment,a),j(De.$$.fragment,a),j(Xe.$$.fragment,a),j(fe.$$.fragment,a),j(X.$$.fragment,a),j(O.$$.fragment,a),j(F.$$.fragment,a),j(R.$$.fragment,a),j(G.$$.fragment,a),j(Fe.$$.fragment,a),j(r.$$.fragment,a),j(We.$$.fragment,a),i=!0)},o(a){E(g.$$.fragment,a),E(z.$$.fragment,a),E(De.$$.fragment,a),E(Xe.$$.fragment,a),E(fe.$$.fragment,a),E(X.$$.fragment,a),E(O.$$.fragment,a),E(F.$$.fragment,a),E(R.$$.fragment,a),E(G.$$.fragment,a),E(Fe.$$.fragment,a),E(r.$$.fragment,a),E(We.$$.fragment,a),i=!1},d(a){T(g,a),a&&e(A),a&&e(c),T(z),a&&e(B),a&&e(S),a&&e(D),a&&e(ve),a&&e(Ut),T(De,a),a&&e(ie),T(Xe,a),a&&e(J),a&&e(I),T(fe),a&&e(Dt),a&&e(Y),a&&e($e),a&&e(it),a&&e(Tt),T(X,a),a&&e(Ze),a&&e(W),T(O),a&&e(de),a&&e(x),a&&e(Ot),T(F,a),a&&e(Qe),a&&e(L),a&&e(ht),T(R,a),a&&e(tt),a&&e(Ne),a&&e(zt),T(G,a),a&&e(Ht),a&&e(C),T(Fe),a&&e(Xt),a&&e(ee),a&&e(Yt),T(r,a),a&&e(_),a&&e(ge),a&&e(Le),T(We,a)}}}function ms(gt){let g,A;return g=new Ma({props:{$$slots:{default:[us]},$$scope:{ctx:gt}}}),{c(){w(g.$$.fragment)},l(c){b(g.$$.fragment,c)},m(c,$){k(g,c,$),A=!0},p(c,$){const P={};$&2&&(P.$$scope={dirty:$,ctx:c}),g.$set(P)},i(c){A||(j(g.$$.fragment,c),A=!0)},o(c){E(g.$$.fragment,c),A=!1},d(c){T(g,c)}}}function cs(gt){let g,A,c,$,P;return{c(){g=o("p"),A=p("You don\u2019t have to pass a loss argument to your models when you "),c=o("code"),$=p("compile()"),P=p(` them! Hugging Face models automatically
choose a loss that is appropriate for their task and model architecture if this argument is left blank. You can always
override this by specifying a loss yourself if you want to!`)},l(z){g=n(z,"P",{});var M=l(g);A=f(M,"You don\u2019t have to pass a loss argument to your models when you "),c=n(M,"CODE",{});var q=l(c);$=f(q,"compile()"),q.forEach(e),P=f(M,` them! Hugging Face models automatically
choose a loss that is appropriate for their task and model architecture if this argument is left blank. You can always
override this by specifying a loss yourself if you want to!`),M.forEach(e)},m(z,M){d(z,g,M),t(g,A),t(g,c),t(c,$),t(g,P)},d(z){z&&e(g)}}}function gs(gt){let g,A,c,$,P,z,M,q,Ge,B,S,Ue,H,ta,_t,N,_e,kt,D,ve,Je,vt,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,ye,It,$e,it,yt,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,$t,ue,dt,we,be,Be,oe,aa,At,ke,He,Z,Q,Pt,je,Ot,F,Qe,L,me,Ve,Se,Mt,et,sa,Bt,V,Ye,Ce,ht,R,tt,Ne,Ee,Ke,at,ut,zt,G,Ht,C,ne,ce,Fe,Te,mt,xt,Xt,ee,Ae,le,st,wt,Yt,r,_,ge,Pe,Kt,qt,ra,Le,We;return c=new Ia({props:{id:"rnTGBy2ax1c"}}),q=new ea({}),D=new ea({}),fe=new U({props:{code:`from datasets import load_dataset

dataset = load_dataset("glue", "cola")
dataset = dataset["train"]  # Just take the training split for now`,highlighted:`<span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset

dataset = load_dataset(<span class="hljs-string">&quot;glue&quot;</span>, <span class="hljs-string">&quot;cola&quot;</span>)
dataset = dataset[<span class="hljs-string">&quot;train&quot;</span>]  <span class="hljs-comment"># Just take the training split for now</span>`}}),Y=new U({props:{code:`from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
tokenized_data = tokenizer(dataset["text"], return_tensors="np", padding=True)

labels = np.array(dataset["label"])  # Label is already an array of 0 and 1`,highlighted:`<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;bert-base-cased&quot;</span>)
tokenized_data = tokenizer(dataset[<span class="hljs-string">&quot;text&quot;</span>], return_tensors=<span class="hljs-string">&quot;np&quot;</span>, padding=<span class="hljs-literal">True</span>)

labels = np.array(dataset[<span class="hljs-string">&quot;label&quot;</span>])  <span class="hljs-comment"># Label is already an array of 0 and 1</span>`}}),Ze=new U({props:{code:`from transformers import TFAutoModelForSequenceClassification
from tensorflow.keras.optimizers import Adam

# Load and compile our model
model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased")
# Lower learning rates are often better for fine-tuning transformers
model.compile(optimizer=Adam(3e-5))

model.fit(tokenized_data, labels)`,highlighted:`<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TFAutoModelForSequenceClassification
<span class="hljs-keyword">from</span> tensorflow.keras.optimizers <span class="hljs-keyword">import</span> Adam

<span class="hljs-comment"># Load and compile our model</span>
model = TFAutoModelForSequenceClassification.from_pretrained(<span class="hljs-string">&quot;bert-base-cased&quot;</span>)
<span class="hljs-comment"># Lower learning rates are often better for fine-tuning transformers</span>
model.<span class="hljs-built_in">compile</span>(optimizer=Adam(<span class="hljs-number">3e-5</span>))

model.fit(tokenized_data, labels)`}}),K=new Oa({props:{$$slots:{default:[cs]},$$scope:{ctx:gt}}}),he=new ea({}),Ee=new U({props:{code:`def tokenize_dataset(data):
    # Keys of the returned dictionary will be added to the dataset as columns
    return tokenizer(data["text"])


dataset = dataset.map(tokenize_dataset)`,highlighted:`<span class="hljs-keyword">def</span> <span class="hljs-title function_">tokenize_dataset</span>(<span class="hljs-params">data</span>):
    <span class="hljs-comment"># Keys of the returned dictionary will be added to the dataset as columns</span>
    <span class="hljs-keyword">return</span> tokenizer(data[<span class="hljs-string">&quot;text&quot;</span>])


dataset = dataset.<span class="hljs-built_in">map</span>(tokenize_dataset)`}}),G=new U({props:{code:"tf_dataset = model.prepare_tf_dataset(dataset, batch_size=16, shuffle=True, tokenizer=tokenizer)",highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>tf_dataset = model.prepare_tf_dataset(dataset, batch_size=<span class="hljs-number">16</span>, shuffle=<span class="hljs-literal">True</span>, tokenizer=tokenizer)'}}),Le=new U({props:{code:`model.compile(optimizer=Adam(3e-5))

model.fit(tf_dataset)`,highlighted:`model.<span class="hljs-built_in">compile</span>(optimizer=Adam(<span class="hljs-number">3e-5</span>))

model.fit(tf_dataset)`}}),{c(){g=o("a"),A=u(),w(c.$$.fragment),$=u(),P=o("h2"),z=o("a"),M=o("span"),w(q.$$.fragment),Ge=u(),B=o("span"),S=p("Train a TensorFlow model with Keras"),Ue=u(),H=o("p"),ta=p("You can also train \u{1F917} Transformers models in TensorFlow with the Keras API!"),_t=u(),N=o("h3"),_e=o("a"),kt=o("span"),w(D.$$.fragment),ve=u(),Je=o("span"),vt=p("Loading data for Keras"),ot=u(),jt=o("p"),Ut=p(`When you want to train a \u{1F917} Transformers model with the Keras API, you need to convert your dataset to a format that
Keras understands. If your dataset is small, you can just convert the whole thing to NumPy arrays and pass it to Keras.
Let\u2019s try that first before we do anything more complicated.`),De=u(),ie=o("p"),Xe=p("First, load a dataset. We\u2019ll use the CoLA dataset from the "),J=o("a"),I=p("GLUE benchmark"),ae=p(`,
since it\u2019s a simple binary text classification task, and just take the training split for now.`),pe=u(),w(fe.$$.fragment),nt=u(),Ie=o("p"),Lt=p(`Next, load a tokenizer and tokenize the data as NumPy arrays. Note that the labels are already a list of 0 and 1s,
so we can just convert that directly to a NumPy array without tokenization!`),Dt=u(),w(Y.$$.fragment),lt=u(),se=o("p"),Et=p("Finally, load, "),ze=o("a"),Oe=o("code"),ye=p("compile"),It=p(", and "),$e=o("a"),it=o("code"),yt=p("fit"),Tt=p(" the model:"),X=u(),w(Ze.$$.fragment),W=u(),w(K.$$.fragment),xe=u(),O=o("p"),pt=p(`This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why?
Because the tokenized array and labels would have to be fully loaded into memory, and because NumPy doesn\u2019t handle
\u201Cjagged\u201D arrays, so every tokenized sample would have to be padded to the length of the longest sample in the whole
dataset. That\u2019s going to make your array even bigger, and all those padding tokens will slow down training too!`),ft=u(),re=o("h3"),de=o("a"),x=o("span"),w(he.$$.fragment),Jt=u(),qe=o("span"),Me=p("Loading data as a tf.data.Dataset"),$t=u(),ue=o("p"),dt=p("If you want to avoid slowing down training, you can load your data as a "),we=o("code"),be=p("tf.data.Dataset"),Be=p(` instead. Although you can write your own
`),oe=o("code"),aa=p("tf.data"),At=p(" pipeline if you want, we have two convenience methods for doing this:"),ke=u(),He=o("ul"),Z=o("li"),Q=o("a"),Pt=p("prepare_tf_dataset()"),je=p(`: This is the method we recommend in most cases. Because it is a method
on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and
discard the others to make a simpler, more performant dataset.`),Ot=u(),F=o("li"),Qe=o("a"),L=p("to_tf_dataset"),me=p(`: This method is more low-level, and is useful when you want to exactly control how
your dataset is created, by specifying exactly which `),Ve=o("code"),Se=p("columns"),Mt=p(" and "),et=o("code"),sa=p("label_cols"),Bt=p(" to include."),V=u(),Ye=o("p"),Ce=p("Before you can use "),ht=o("a"),R=p("prepare_tf_dataset()"),tt=p(`, you will need to add the tokenizer outputs to your dataset as columns, as shown in
the following code sample:`),Ne=u(),w(Ee.$$.fragment),Ke=u(),at=o("p"),ut=p(`Remember that Hugging Face datasets are stored on disk by default, so this will not inflate your memory usage! Once the
columns have been added, you can stream batches from the dataset and add padding to each batch, which greatly
reduces the number of padding tokens compared to padding the entire dataset.`),zt=u(),w(G.$$.fragment),Ht=u(),C=o("p"),ne=p("Note that in the code sample above, you need to pass the tokenizer to "),ce=o("code"),Fe=p("prepare_tf_dataset"),Te=p(` so it can correctly pad batches as they\u2019re loaded.
If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument.
If you need to do something more complex than just padding samples (e.g. corrupting tokens for masked language
modelling), you can use the `),mt=o("code"),xt=p("collate_fn"),Xt=p(` argument instead to pass a function that will be called to transform the
list of samples into a batch and apply any preprocessing you want. See our
`),ee=o("a"),Ae=p("examples"),le=p(` or
`),st=o("a"),wt=p("notebooks"),Yt=p(" to see this approach in action."),r=u(),_=o("p"),ge=p("Once you\u2019ve created a "),Pe=o("code"),Kt=p("tf.data.Dataset"),qt=p(", you can compile and fit the model as before:"),ra=u(),w(Le.$$.fragment),this.h()},l(i){g=n(i,"A",{id:!0}),l(g).forEach(e),A=m(i),b(c.$$.fragment,i),$=m(i),P=n(i,"H2",{class:!0});var a=l(P);z=n(a,"A",{id:!0,class:!0,href:!0});var y=l(z);M=n(y,"SPAN",{});var Re=l(M);b(q.$$.fragment,Re),Re.forEach(e),y.forEach(e),Ge=m(a),B=n(a,"SPAN",{});var pa=l(B);S=f(pa,"Train a TensorFlow model with Keras"),pa.forEach(e),a.forEach(e),Ue=m(i),H=n(i,"P",{});var Zt=l(H);ta=f(Zt,"You can also train \u{1F917} Transformers models in TensorFlow with the Keras API!"),Zt.forEach(e),_t=m(i),N=n(i,"H3",{class:!0});var St=l(N);_e=n(St,"A",{id:!0,class:!0,href:!0});var fa=l(_e);kt=n(fa,"SPAN",{});var da=l(kt);b(D.$$.fragment,da),da.forEach(e),fa.forEach(e),ve=m(St),Je=n(St,"SPAN",{});var oa=l(Je);vt=f(oa,"Loading data for Keras"),oa.forEach(e),St.forEach(e),ot=m(i),jt=n(i,"P",{});var rt=l(jt);Ut=f(rt,`When you want to train a \u{1F917} Transformers model with the Keras API, you need to convert your dataset to a format that
Keras understands. If your dataset is small, you can just convert the whole thing to NumPy arrays and pass it to Keras.
Let\u2019s try that first before we do anything more complicated.`),rt.forEach(e),De=m(i),ie=n(i,"P",{});var Qt=l(ie);Xe=f(Qt,"First, load a dataset. We\u2019ll use the CoLA dataset from the "),J=n(Qt,"A",{href:!0,rel:!0});var na=l(J);I=f(na,"GLUE benchmark"),na.forEach(e),ae=f(Qt,`,
since it\u2019s a simple binary text classification task, and just take the training split for now.`),Qt.forEach(e),pe=m(i),b(fe.$$.fragment,i),nt=m(i),Ie=n(i,"P",{});var ga=l(Ie);Lt=f(ga,`Next, load a tokenizer and tokenize the data as NumPy arrays. Note that the labels are already a list of 0 and 1s,
so we can just convert that directly to a NumPy array without tokenization!`),ga.forEach(e),Dt=m(i),b(Y.$$.fragment,i),lt=m(i),se=n(i,"P",{});var Ct=l(se);Et=f(Ct,"Finally, load, "),ze=n(Ct,"A",{href:!0,rel:!0});var Nt=l(ze);Oe=n(Nt,"CODE",{});var _a=l(Oe);ye=f(_a,"compile"),_a.forEach(e),Nt.forEach(e),It=f(Ct,", and "),$e=n(Ct,"A",{href:!0,rel:!0});var va=l($e);it=n(va,"CODE",{});var ha=l(it);yt=f(ha,"fit"),ha.forEach(e),va.forEach(e),Tt=f(Ct," the model:"),Ct.forEach(e),X=m(i),b(Ze.$$.fragment,i),W=m(i),b(K.$$.fragment,i),xe=m(i),O=n(i,"P",{});var ct=l(O);pt=f(ct,`This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why?
Because the tokenized array and labels would have to be fully loaded into memory, and because NumPy doesn\u2019t handle
\u201Cjagged\u201D arrays, so every tokenized sample would have to be padded to the length of the longest sample in the whole
dataset. That\u2019s going to make your array even bigger, and all those padding tokens will slow down training too!`),ct.forEach(e),ft=m(i),re=n(i,"H3",{class:!0});var la=l(re);de=n(la,"A",{id:!0,class:!0,href:!0});var s=l(de);x=n(s,"SPAN",{});var v=l(x);b(he.$$.fragment,v),v.forEach(e),s.forEach(e),Jt=m(la),qe=n(la,"SPAN",{});var te=l(qe);Me=f(te,"Loading data as a tf.data.Dataset"),te.forEach(e),la.forEach(e),$t=m(i),ue=n(i,"P",{});var ia=l(ue);dt=f(ia,"If you want to avoid slowing down training, you can load your data as a "),we=n(ia,"CODE",{});var ua=l(we);be=f(ua,"tf.data.Dataset"),ua.forEach(e),Be=f(ia,` instead. Although you can write your own
`),oe=n(ia,"CODE",{});var wa=l(oe);aa=f(wa,"tf.data"),wa.forEach(e),At=f(ia," pipeline if you want, we have two convenience methods for doing this:"),ia.forEach(e),ke=m(i),He=n(i,"UL",{});var Wt=l(He);Z=n(Wt,"LI",{});var Vt=l(Z);Q=n(Vt,"A",{href:!0});var ma=l(Q);Pt=f(ma,"prepare_tf_dataset()"),ma.forEach(e),je=f(Vt,`: This is the method we recommend in most cases. Because it is a method
on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and
discard the others to make a simpler, more performant dataset.`),Vt.forEach(e),Ot=m(Wt),F=n(Wt,"LI",{});var Rt=l(F);Qe=n(Rt,"A",{href:!0,rel:!0});var bt=l(Qe);L=f(bt,"to_tf_dataset"),bt.forEach(e),me=f(Rt,`: This method is more low-level, and is useful when you want to exactly control how
your dataset is created, by specifying exactly which `),Ve=n(Rt,"CODE",{});var Gt=l(Ve);Se=f(Gt,"columns"),Gt.forEach(e),Mt=f(Rt," and "),et=n(Rt,"CODE",{});var ya=l(et);sa=f(ya,"label_cols"),ya.forEach(e),Bt=f(Rt," to include."),Rt.forEach(e),Wt.forEach(e),V=m(i),Ye=n(i,"P",{});var ca=l(Ye);Ce=f(ca,"Before you can use "),ht=n(ca,"A",{href:!0});var ba=l(ht);R=f(ba,"prepare_tf_dataset()"),ba.forEach(e),tt=f(ca,`, you will need to add the tokenizer outputs to your dataset as columns, as shown in
the following code sample:`),ca.forEach(e),Ne=m(i),b(Ee.$$.fragment,i),Ke=m(i),at=n(i,"P",{});var ka=l(at);ut=f(ka,`Remember that Hugging Face datasets are stored on disk by default, so this will not inflate your memory usage! Once the
columns have been added, you can stream batches from the dataset and add padding to each batch, which greatly
reduces the number of padding tokens compared to padding the entire dataset.`),ka.forEach(e),zt=m(i),b(G.$$.fragment,i),Ht=m(i),C=n(i,"P",{});var Ft=l(C);ne=f(Ft,"Note that in the code sample above, you need to pass the tokenizer to "),ce=n(Ft,"CODE",{});var Aa=l(ce);Fe=f(Aa,"prepare_tf_dataset"),Aa.forEach(e),Te=f(Ft,` so it can correctly pad batches as they\u2019re loaded.
If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument.
If you need to do something more complex than just padding samples (e.g. corrupting tokens for masked language
modelling), you can use the `),mt=n(Ft,"CODE",{});var ja=l(mt);xt=f(ja,"collate_fn"),ja.forEach(e),Xt=f(Ft,` argument instead to pass a function that will be called to transform the
list of samples into a batch and apply any preprocessing you want. See our
`),ee=n(Ft,"A",{href:!0,rel:!0});var Pa=l(ee);Ae=f(Pa,"examples"),Pa.forEach(e),le=f(Ft,` or
`),st=n(Ft,"A",{href:!0,rel:!0});var Ea=l(st);wt=f(Ea,"notebooks"),Ea.forEach(e),Yt=f(Ft," to see this approach in action."),Ft.forEach(e),r=m(i),_=n(i,"P",{});var Ta=l(_);ge=f(Ta,"Once you\u2019ve created a "),Pe=n(Ta,"CODE",{});var $a=l(Pe);Kt=f($a,"tf.data.Dataset"),$a.forEach(e),qt=f(Ta,", you can compile and fit the model as before:"),Ta.forEach(e),ra=m(i),b(Le.$$.fragment,i),this.h()},h(){h(g,"id","keras"),h(z,"id","train-a-tensorflow-model-with-keras"),h(z,"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"),h(z,"href","#train-a-tensorflow-model-with-keras"),h(P,"class","relative group"),h(_e,"id","loading-data-for-keras"),h(_e,"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"),h(_e,"href","#loading-data-for-keras"),h(N,"class","relative group"),h(J,"href","https://huggingface.co/datasets/glue"),h(J,"rel","nofollow"),h(ze,"href","https://keras.io/api/models/model_training_apis/#compile-method"),h(ze,"rel","nofollow"),h($e,"href","https://keras.io/api/models/model_training_apis/#fit-method"),h($e,"rel","nofollow"),h(de,"id","loading-data-as-a-tfdatadataset"),h(de,"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"),h(de,"href","#loading-data-as-a-tfdatadataset"),h(re,"class","relative group"),h(Q,"href","/docs/transformers/pr_19043/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset"),h(Qe,"href","https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset"),h(Qe,"rel","nofollow"),h(ht,"href","/docs/transformers/pr_19043/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset"),h(ee,"href","https://github.com/huggingface/transformers/tree/main/examples"),h(ee,"rel","nofollow"),h(st,"href","https://huggingface.co/docs/transformers/notebooks"),h(st,"rel","nofollow")},m(i,a){d(i,g,a),d(i,A,a),k(c,i,a),d(i,$,a),d(i,P,a),t(P,z),t(z,M),k(q,M,null),t(P,Ge),t(P,B),t(B,S),d(i,Ue,a),d(i,H,a),t(H,ta),d(i,_t,a),d(i,N,a),t(N,_e),t(_e,kt),k(D,kt,null),t(N,ve),t(N,Je),t(Je,vt),d(i,ot,a),d(i,jt,a),t(jt,Ut),d(i,De,a),d(i,ie,a),t(ie,Xe),t(ie,J),t(J,I),t(ie,ae),d(i,pe,a),k(fe,i,a),d(i,nt,a),d(i,Ie,a),t(Ie,Lt),d(i,Dt,a),k(Y,i,a),d(i,lt,a),d(i,se,a),t(se,Et),t(se,ze),t(ze,Oe),t(Oe,ye),t(se,It),t(se,$e),t($e,it),t(it,yt),t(se,Tt),d(i,X,a),k(Ze,i,a),d(i,W,a),k(K,i,a),d(i,xe,a),d(i,O,a),t(O,pt),d(i,ft,a),d(i,re,a),t(re,de),t(de,x),k(he,x,null),t(re,Jt),t(re,qe),t(qe,Me),d(i,$t,a),d(i,ue,a),t(ue,dt),t(ue,we),t(we,be),t(ue,Be),t(ue,oe),t(oe,aa),t(ue,At),d(i,ke,a),d(i,He,a),t(He,Z),t(Z,Q),t(Q,Pt),t(Z,je),t(He,Ot),t(He,F),t(F,Qe),t(Qe,L),t(F,me),t(F,Ve),t(Ve,Se),t(F,Mt),t(F,et),t(et,sa),t(F,Bt),d(i,V,a),d(i,Ye,a),t(Ye,Ce),t(Ye,ht),t(ht,R),t(Ye,tt),d(i,Ne,a),k(Ee,i,a),d(i,Ke,a),d(i,at,a),t(at,ut),d(i,zt,a),k(G,i,a),d(i,Ht,a),d(i,C,a),t(C,ne),t(C,ce),t(ce,Fe),t(C,Te),t(C,mt),t(mt,xt),t(C,Xt),t(C,ee),t(ee,Ae),t(C,le),t(C,st),t(st,wt),t(C,Yt),d(i,r,a),d(i,_,a),t(_,ge),t(_,Pe),t(Pe,Kt),t(_,qt),d(i,ra,a),k(Le,i,a),We=!0},p(i,a){const y={};a&2&&(y.$$scope={dirty:a,ctx:i}),K.$set(y)},i(i){We||(j(c.$$.fragment,i),j(q.$$.fragment,i),j(D.$$.fragment,i),j(fe.$$.fragment,i),j(Y.$$.fragment,i),j(Ze.$$.fragment,i),j(K.$$.fragment,i),j(he.$$.fragment,i),j(Ee.$$.fragment,i),j(G.$$.fragment,i),j(Le.$$.fragment,i),We=!0)},o(i){E(c.$$.fragment,i),E(q.$$.fragment,i),E(D.$$.fragment,i),E(fe.$$.fragment,i),E(Y.$$.fragment,i),E(Ze.$$.fragment,i),E(K.$$.fragment,i),E(he.$$.fragment,i),E(Ee.$$.fragment,i),E(G.$$.fragment,i),E(Le.$$.fragment,i),We=!1},d(i){i&&e(g),i&&e(A),T(c,i),i&&e($),i&&e(P),T(q),i&&e(Ue),i&&e(H),i&&e(_t),i&&e(N),T(D),i&&e(ot),i&&e(jt),i&&e(De),i&&e(ie),i&&e(pe),T(fe,i),i&&e(nt),i&&e(Ie),i&&e(Dt),T(Y,i),i&&e(lt),i&&e(se),i&&e(X),T(Ze,i),i&&e(W),T(K,i),i&&e(xe),i&&e(O),i&&e(ft),i&&e(re),T(he),i&&e($t),i&&e(ue),i&&e(ke),i&&e(He),i&&e(V),i&&e(Ye),i&&e(Ne),T(Ee,i),i&&e(Ke),i&&e(at),i&&e(zt),T(G,i),i&&e(Ht),i&&e(C),i&&e(r),i&&e(_),i&&e(ra),T(Le,i)}}}function _s(gt){let g,A;return g=new Ma({props:{$$slots:{default:[gs]},$$scope:{ctx:gt}}}),{c(){w(g.$$.fragment)},l(c){b(g.$$.fragment,c)},m(c,$){k(g,c,$),A=!0},p(c,$){const P={};$&2&&(P.$$scope={dirty:$,ctx:c}),g.$set(P)},i(c){A||(j(g.$$.fragment,c),A=!0)},o(c){E(g.$$.fragment,c),A=!1},d(c){T(g,c)}}}function vs(gt){let g,A,c,$,P,z,M,q;return{c(){g=o("p"),A=p("Get free access to a cloud GPU if you don\u2019t have one with a hosted notebook like "),c=o("a"),$=p("Colaboratory"),P=p(" or "),z=o("a"),M=p("SageMaker StudioLab"),q=p("."),this.h()},l(Ge){g=n(Ge,"P",{});var B=l(g);A=f(B,"Get free access to a cloud GPU if you don\u2019t have one with a hosted notebook like "),c=n(B,"A",{href:!0,rel:!0});var S=l(c);$=f(S,"Colaboratory"),S.forEach(e),P=f(B," or "),z=n(B,"A",{href:!0,rel:!0});var Ue=l(z);M=f(Ue,"SageMaker StudioLab"),Ue.forEach(e),q=f(B,"."),B.forEach(e),this.h()},h(){h(c,"href","https://colab.research.google.com/"),h(c,"rel","nofollow"),h(z,"href","https://studiolab.sagemaker.aws/"),h(z,"rel","nofollow")},m(Ge,B){d(Ge,g,B),t(g,A),t(g,c),t(c,$),t(g,P),t(g,z),t(z,M),t(g,q)},d(Ge){Ge&&e(g)}}}function ys(gt){let g,A,c,$,P,z,M,q,Ge,B,S,Ue,H,ta,_t,N,_e,kt,D,ve,Je,vt,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,ye,It,$e,it,yt,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,$t,ue,dt,we,be,Be,oe,aa,At,ke,He,Z,Q,Pt,je,Ot,F,Qe,L,me,Ve,Se,Mt,et,sa,Bt,V,Ye,Ce,ht,R,tt,Ne,Ee,Ke,at,ut,zt,G,Ht,C,ne,ce,Fe,Te,mt,xt,Xt,ee,Ae,le,st,wt,Yt,r,_,ge,Pe,Kt,qt,ra,Le,We,i,a,y,Re,pa,Zt,St,fa,da,oa,rt,Qt,na,ga,Ct,Nt,_a,va,ha,ct,la;return g=new Ia({props:{id:"Dh9CL8fyG80"}}),S=new U({props:{code:`del model
del pytorch_model
del trainer
torch.cuda.empty_cache()`,highlighted:`<span class="hljs-keyword">del</span> model
<span class="hljs-keyword">del</span> pytorch_model
<span class="hljs-keyword">del</span> trainer
torch.cuda.empty_cache()`}}),ie=new U({props:{code:'tokenized_datasets = tokenized_datasets.remove_columns(["text"])',highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>tokenized_datasets = tokenized_datasets.remove_columns([<span class="hljs-string">&quot;text&quot;</span>])'}}),ze=new U({props:{code:'tokenized_datasets = tokenized_datasets.rename_column("label", "labels")',highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>tokenized_datasets = tokenized_datasets.rename_column(<span class="hljs-string">&quot;label&quot;</span>, <span class="hljs-string">&quot;labels&quot;</span>)'}}),yt=new U({props:{code:'tokenized_datasets.set_format("torch")',highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>tokenized_datasets.set_format(<span class="hljs-string">&quot;torch&quot;</span>)'}}),K=new U({props:{code:`small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>small_train_dataset = tokenized_datasets[<span class="hljs-string">&quot;train&quot;</span>].shuffle(seed=<span class="hljs-number">42</span>).select(<span class="hljs-built_in">range</span>(<span class="hljs-number">1000</span>))
<span class="hljs-meta">&gt;&gt;&gt; </span>small_eval_dataset = tokenized_datasets[<span class="hljs-string">&quot;test&quot;</span>].shuffle(seed=<span class="hljs-number">42</span>).select(<span class="hljs-built_in">range</span>(<span class="hljs-number">1000</span>))`}}),re=new ea({}),be=new U({props:{code:`from torch.utils.data import DataLoader

train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> torch.utils.data <span class="hljs-keyword">import</span> DataLoader

<span class="hljs-meta">&gt;&gt;&gt; </span>train_dataloader = DataLoader(small_train_dataset, shuffle=<span class="hljs-literal">True</span>, batch_size=<span class="hljs-number">8</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>eval_dataloader = DataLoader(small_eval_dataset, batch_size=<span class="hljs-number">8</span>)`}}),ke=new U({props:{code:`from transformers import AutoModelForSequenceClassification

model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)`,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-base-cased&quot;</span>, num_labels=<span class="hljs-number">5</span>)`}}),je=new ea({}),V=new U({props:{code:`from torch.optim import AdamW

optimizer = AdamW(model.parameters(), lr=5e-5)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> torch.optim <span class="hljs-keyword">import</span> AdamW

<span class="hljs-meta">&gt;&gt;&gt; </span>optimizer = AdamW(model.parameters(), lr=<span class="hljs-number">5e-5</span>)`}}),Ke=new U({props:{code:`from transformers import get_scheduler

num_epochs = 3
num_training_steps = num_epochs * len(train_dataloader)
lr_scheduler = get_scheduler(
    name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> get_scheduler

<span class="hljs-meta">&gt;&gt;&gt; </span>num_epochs = <span class="hljs-number">3</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>num_training_steps = num_epochs * <span class="hljs-built_in">len</span>(train_dataloader)
<span class="hljs-meta">&gt;&gt;&gt; </span>lr_scheduler = get_scheduler(
<span class="hljs-meta">... </span>    name=<span class="hljs-string">&quot;linear&quot;</span>, optimizer=optimizer, num_warmup_steps=<span class="hljs-number">0</span>, num_training_steps=num_training_steps
<span class="hljs-meta">... </span>)`}}),ce=new U({props:{code:`import torch

device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
model.to(device)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch

<span class="hljs-meta">&gt;&gt;&gt; </span>device = torch.device(<span class="hljs-string">&quot;cuda&quot;</span>) <span class="hljs-keyword">if</span> torch.cuda.is_available() <span class="hljs-keyword">else</span> torch.device(<span class="hljs-string">&quot;cpu&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model.to(device)`}}),Te=new Oa({props:{$$slots:{default:[vs]},$$scope:{ctx:gt}}}),wt=new ea({}),i=new U({props:{code:`from tqdm.auto import tqdm

progress_bar = tqdm(range(num_training_steps))

model.train()
for epoch in range(num_epochs):
    for batch in train_dataloader:
        batch = {k: v.to(device) for k, v in batch.items()}
        outputs = model(**batch)
        loss = outputs.loss
        loss.backward()

        optimizer.step()
        lr_scheduler.step()
        optimizer.zero_grad()
        progress_bar.update(1)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> tqdm.auto <span class="hljs-keyword">import</span> tqdm

<span class="hljs-meta">&gt;&gt;&gt; </span>progress_bar = tqdm(<span class="hljs-built_in">range</span>(num_training_steps))

<span class="hljs-meta">&gt;&gt;&gt; </span>model.train()
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> epoch <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(num_epochs):
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> train_dataloader:
<span class="hljs-meta">... </span>        batch = {k: v.to(device) <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> batch.items()}
<span class="hljs-meta">... </span>        outputs = model(**batch)
<span class="hljs-meta">... </span>        loss = outputs.loss
<span class="hljs-meta">... </span>        loss.backward()

<span class="hljs-meta">... </span>        optimizer.step()
<span class="hljs-meta">... </span>        lr_scheduler.step()
<span class="hljs-meta">... </span>        optimizer.zero_grad()
<span class="hljs-meta">... </span>        progress_bar.update(<span class="hljs-number">1</span>)`}}),Zt=new ea({}),ct=new U({props:{code:`import evaluate

metric = evaluate.load("accuracy")
model.eval()
for batch in eval_dataloader:
    batch = {k: v.to(device) for k, v in batch.items()}
    with torch.no_grad():
        outputs = model(**batch)

    logits = outputs.logits
    predictions = torch.argmax(logits, dim=-1)
    metric.add_batch(predictions=predictions, references=batch["labels"])

metric.compute()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> evaluate

<span class="hljs-meta">&gt;&gt;&gt; </span>metric = evaluate.load(<span class="hljs-string">&quot;accuracy&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model.<span class="hljs-built_in">eval</span>()
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> eval_dataloader:
<span class="hljs-meta">... </span>    batch = {k: v.to(device) <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> batch.items()}
<span class="hljs-meta">... </span>    <span class="hljs-keyword">with</span> torch.no_grad():
<span class="hljs-meta">... </span>        outputs = model(**batch)

<span class="hljs-meta">... </span>    logits = outputs.logits
<span class="hljs-meta">... </span>    predictions = torch.argmax(logits, dim=-<span class="hljs-number">1</span>)
<span class="hljs-meta">... </span>    metric.add_batch(predictions=predictions, references=batch[<span class="hljs-string">&quot;labels&quot;</span>])

<span class="hljs-meta">&gt;&gt;&gt; </span>metric.compute()`}}),{c(){w(g.$$.fragment),A=u(),c=o("p"),$=o("a"),P=p("Trainer"),z=p(" takes care of the training loop and allows you to fine-tune a model in a single line of code. For users who prefer to write their own training loop, you can also fine-tune a \u{1F917} Transformers model in native PyTorch."),M=u(),q=o("p"),Ge=p("At this point, you may need to restart your notebook or execute the following code to free some memory:"),B=u(),w(S.$$.fragment),Ue=u(),H=o("p"),ta=p("Next, manually postprocess "),_t=o("code"),N=p("tokenized_dataset"),_e=p(" to prepare it for training."),kt=u(),D=o("ol"),ve=o("li"),Je=o("p"),vt=p("Remove the "),ot=o("code"),jt=p("text"),Ut=p(" column because the model does not accept raw text as an input:"),De=u(),w(ie.$$.fragment),Xe=u(),J=o("li"),I=o("p"),ae=p("Rename the "),pe=o("code"),fe=p("label"),nt=p(" column to "),Ie=o("code"),Lt=p("labels"),Dt=p(" because the model expects the argument to be named "),Y=o("code"),lt=p("labels"),se=p(":"),Et=u(),w(ze.$$.fragment),Oe=u(),ye=o("li"),It=o("p"),$e=p("Set the format of the dataset to return PyTorch tensors instead of lists:"),it=u(),w(yt.$$.fragment),Tt=u(),X=o("p"),Ze=p("Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:"),W=u(),w(K.$$.fragment),xe=u(),O=o("h3"),pt=o("a"),ft=o("span"),w(re.$$.fragment),de=u(),x=o("span"),he=p("DataLoader"),Jt=u(),qe=o("p"),Me=p("Create a "),$t=o("code"),ue=p("DataLoader"),dt=p(" for your training and test datasets so you can iterate over batches of data:"),we=u(),w(be.$$.fragment),Be=u(),oe=o("p"),aa=p("Load your model with the number of expected labels:"),At=u(),w(ke.$$.fragment),He=u(),Z=o("h3"),Q=o("a"),Pt=o("span"),w(je.$$.fragment),Ot=u(),F=o("span"),Qe=p("Optimizer and learning rate scheduler"),L=u(),me=o("p"),Ve=p("Create an optimizer and learning rate scheduler to fine-tune the model. Let\u2019s use the "),Se=o("a"),Mt=o("code"),et=p("AdamW"),sa=p(" optimizer from PyTorch:"),Bt=u(),w(V.$$.fragment),Ye=u(),Ce=o("p"),ht=p("Create the default learning rate scheduler from "),R=o("a"),tt=p("Trainer"),Ne=p(":"),Ee=u(),w(Ke.$$.fragment),at=u(),ut=o("p"),zt=p("Lastly, specify "),G=o("code"),Ht=p("device"),C=p(" to use a GPU if you have access to one. Otherwise, training on a CPU may take several hours instead of a couple of minutes."),ne=u(),w(ce.$$.fragment),Fe=u(),w(Te.$$.fragment),mt=u(),xt=o("p"),Xt=p("Great, now you are ready to train! \u{1F973}"),ee=u(),Ae=o("h3"),le=o("a"),st=o("span"),w(wt.$$.fragment),Yt=u(),r=o("span"),_=p("Training loop"),ge=u(),Pe=o("p"),Kt=p("To keep track of your training progress, use the "),qt=o("a"),ra=p("tqdm"),Le=p(" library to add a progress bar over the number of training steps:"),We=u(),w(i.$$.fragment),a=u(),y=o("h3"),Re=o("a"),pa=o("span"),w(Zt.$$.fragment),St=u(),fa=o("span"),da=p("Evaluate"),oa=u(),rt=o("p"),Qt=p("Just like how you added an evaluation function to "),na=o("a"),ga=p("Trainer"),Ct=p(", you need to do the same when you write your own training loop. But instead of calculating and reporting the metric at the end of each epoch, this time you\u2019ll accumulate all the batches with "),Nt=o("code"),_a=p("add_batch"),va=p(" and calculate the metric at the very end."),ha=u(),w(ct.$$.fragment),this.h()},l(s){b(g.$$.fragment,s),A=m(s),c=n(s,"P",{});var v=l(c);$=n(v,"A",{href:!0});var te=l($);P=f(te,"Trainer"),te.forEach(e),z=f(v," takes care of the training loop and allows you to fine-tune a model in a single line of code. For users who prefer to write their own training loop, you can also fine-tune a \u{1F917} Transformers model in native PyTorch."),v.forEach(e),M=m(s),q=n(s,"P",{});var ia=l(q);Ge=f(ia,"At this point, you may need to restart your notebook or execute the following code to free some memory:"),ia.forEach(e),B=m(s),b(S.$$.fragment,s),Ue=m(s),H=n(s,"P",{});var ua=l(H);ta=f(ua,"Next, manually postprocess "),_t=n(ua,"CODE",{});var wa=l(_t);N=f(wa,"tokenized_dataset"),wa.forEach(e),_e=f(ua," to prepare it for training."),ua.forEach(e),kt=m(s),D=n(s,"OL",{});var Wt=l(D);ve=n(Wt,"LI",{});var Vt=l(ve);Je=n(Vt,"P",{});var ma=l(Je);vt=f(ma,"Remove the "),ot=n(ma,"CODE",{});var Rt=l(ot);jt=f(Rt,"text"),Rt.forEach(e),Ut=f(ma," column because the model does not accept raw text as an input:"),ma.forEach(e),De=m(Vt),b(ie.$$.fragment,Vt),Vt.forEach(e),Xe=m(Wt),J=n(Wt,"LI",{});var bt=l(J);I=n(bt,"P",{});var Gt=l(I);ae=f(Gt,"Rename the "),pe=n(Gt,"CODE",{});var ya=l(pe);fe=f(ya,"label"),ya.forEach(e),nt=f(Gt," column to "),Ie=n(Gt,"CODE",{});var ca=l(Ie);Lt=f(ca,"labels"),ca.forEach(e),Dt=f(Gt," because the model expects the argument to be named "),Y=n(Gt,"CODE",{});var ba=l(Y);lt=f(ba,"labels"),ba.forEach(e),se=f(Gt,":"),Gt.forEach(e),Et=m(bt),b(ze.$$.fragment,bt),bt.forEach(e),Oe=m(Wt),ye=n(Wt,"LI",{});var ka=l(ye);It=n(ka,"P",{});var Ft=l(It);$e=f(Ft,"Set the format of the dataset to return PyTorch tensors instead of lists:"),Ft.forEach(e),it=m(ka),b(yt.$$.fragment,ka),ka.forEach(e),Wt.forEach(e),Tt=m(s),X=n(s,"P",{});var Aa=l(X);Ze=f(Aa,"Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:"),Aa.forEach(e),W=m(s),b(K.$$.fragment,s),xe=m(s),O=n(s,"H3",{class:!0});var ja=l(O);pt=n(ja,"A",{id:!0,class:!0,href:!0});var Pa=l(pt);ft=n(Pa,"SPAN",{});var Ea=l(ft);b(re.$$.fragment,Ea),Ea.forEach(e),Pa.forEach(e),de=m(ja),x=n(ja,"SPAN",{});var Ta=l(x);he=f(Ta,"DataLoader"),Ta.forEach(e),ja.forEach(e),Jt=m(s),qe=n(s,"P",{});var $a=l(qe);Me=f($a,"Create a "),$t=n($a,"CODE",{});var xa=l($t);ue=f(xa,"DataLoader"),xa.forEach(e),dt=f($a," for your training and test datasets so you can iterate over batches of data:"),$a.forEach(e),we=m(s),b(be.$$.fragment,s),Be=m(s),oe=n(s,"P",{});var Ba=l(oe);aa=f(Ba,"Load your model with the number of expected labels:"),Ba.forEach(e),At=m(s),b(ke.$$.fragment,s),He=m(s),Z=n(s,"H3",{class:!0});var qa=l(Z);Q=n(qa,"A",{id:!0,class:!0,href:!0});var Ha=l(Q);Pt=n(Ha,"SPAN",{});var Ya=l(Pt);b(je.$$.fragment,Ya),Ya.forEach(e),Ha.forEach(e),Ot=m(qa),F=n(qa,"SPAN",{});var Ka=l(F);Qe=f(Ka,"Optimizer and learning rate scheduler"),Ka.forEach(e),qa.forEach(e),L=m(s),me=n(s,"P",{});var Sa=l(me);Ve=f(Sa,"Create an optimizer and learning rate scheduler to fine-tune the model. Let\u2019s use the "),Se=n(Sa,"A",{href:!0,rel:!0});var Wa=l(Se);Mt=n(Wa,"CODE",{});var Ra=l(Mt);et=f(Ra,"AdamW"),Ra.forEach(e),Wa.forEach(e),sa=f(Sa," optimizer from PyTorch:"),Sa.forEach(e),Bt=m(s),b(V.$$.fragment,s),Ye=m(s),Ce=n(s,"P",{});var Ca=l(Ce);ht=f(Ca,"Create the default learning rate scheduler from "),R=n(Ca,"A",{href:!0});var Ga=l(R);tt=f(Ga,"Trainer"),Ga.forEach(e),Ne=f(Ca,":"),Ca.forEach(e),Ee=m(s),b(Ke.$$.fragment,s),at=m(s),ut=n(s,"P",{});var Na=l(ut);zt=f(Na,"Lastly, specify "),G=n(Na,"CODE",{});var Ua=l(G);Ht=f(Ua,"device"),Ua.forEach(e),C=f(Na," to use a GPU if you have access to one. Otherwise, training on a CPU may take several hours instead of a couple of minutes."),Na.forEach(e),ne=m(s),b(ce.$$.fragment,s),Fe=m(s),b(Te.$$.fragment,s),mt=m(s),xt=n(s,"P",{});var Ja=l(xt);Xt=f(Ja,"Great, now you are ready to train! \u{1F973}"),Ja.forEach(e),ee=m(s),Ae=n(s,"H3",{class:!0});var Fa=l(Ae);le=n(Fa,"A",{id:!0,class:!0,href:!0});var Xa=l(le);st=n(Xa,"SPAN",{});var Za=l(st);b(wt.$$.fragment,Za),Za.forEach(e),Xa.forEach(e),Yt=m(Fa),r=n(Fa,"SPAN",{});var Qa=l(r);_=f(Qa,"Training loop"),Qa.forEach(e),Fa.forEach(e),ge=m(s),Pe=n(s,"P",{});var La=l(Pe);Kt=f(La,"To keep track of your training progress, use the "),qt=n(La,"A",{href:!0,rel:!0});var Va=l(qt);ra=f(Va,"tqdm"),Va.forEach(e),Le=f(La," library to add a progress bar over the number of training steps:"),La.forEach(e),We=m(s),b(i.$$.fragment,s),a=m(s),y=n(s,"H3",{class:!0});var Da=l(y);Re=n(Da,"A",{id:!0,class:!0,href:!0});var es=l(Re);pa=n(es,"SPAN",{});var ts=l(pa);b(Zt.$$.fragment,ts),ts.forEach(e),es.forEach(e),St=m(Da),fa=n(Da,"SPAN",{});var as=l(fa);da=f(as,"Evaluate"),as.forEach(e),Da.forEach(e),oa=m(s),rt=n(s,"P",{});var za=l(rt);Qt=f(za,"Just like how you added an evaluation function to "),na=n(za,"A",{href:!0});var ss=l(na);ga=f(ss,"Trainer"),ss.forEach(e),Ct=f(za,", you need to do the same when you write your own training loop. But instead of calculating and reporting the metric at the end of each epoch, this time you\u2019ll accumulate all the batches with "),Nt=n(za,"CODE",{});var rs=l(Nt);_a=f(rs,"add_batch"),rs.forEach(e),va=f(za," and calculate the metric at the very end."),za.forEach(e),ha=m(s),b(ct.$$.fragment,s),this.h()},h(){h($,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(pt,"id","dataloader"),h(pt,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),h(pt,"href","#dataloader"),h(O,"class","relative group"),h(Q,"id","optimizer-and-learning-rate-scheduler"),h(Q,"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"),h(Q,"href","#optimizer-and-learning-rate-scheduler"),h(Z,"class","relative group"),h(Se,"href","https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html"),h(Se,"rel","nofollow"),h(R,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(le,"id","training-loop"),h(le,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),h(le,"href","#training-loop"),h(Ae,"class","relative group"),h(qt,"href","https://tqdm.github.io/"),h(qt,"rel","nofollow"),h(Re,"id","evaluate"),h(Re,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),h(Re,"href","#evaluate"),h(y,"class","relative group"),h(na,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer")},m(s,v){k(g,s,v),d(s,A,v),d(s,c,v),t(c,$),t($,P),t(c,z),d(s,M,v),d(s,q,v),t(q,Ge),d(s,B,v),k(S,s,v),d(s,Ue,v),d(s,H,v),t(H,ta),t(H,_t),t(_t,N),t(H,_e),d(s,kt,v),d(s,D,v),t(D,ve),t(ve,Je),t(Je,vt),t(Je,ot),t(ot,jt),t(Je,Ut),t(ve,De),k(ie,ve,null),t(D,Xe),t(D,J),t(J,I),t(I,ae),t(I,pe),t(pe,fe),t(I,nt),t(I,Ie),t(Ie,Lt),t(I,Dt),t(I,Y),t(Y,lt),t(I,se),t(J,Et),k(ze,J,null),t(D,Oe),t(D,ye),t(ye,It),t(It,$e),t(ye,it),k(yt,ye,null),d(s,Tt,v),d(s,X,v),t(X,Ze),d(s,W,v),k(K,s,v),d(s,xe,v),d(s,O,v),t(O,pt),t(pt,ft),k(re,ft,null),t(O,de),t(O,x),t(x,he),d(s,Jt,v),d(s,qe,v),t(qe,Me),t(qe,$t),t($t,ue),t(qe,dt),d(s,we,v),k(be,s,v),d(s,Be,v),d(s,oe,v),t(oe,aa),d(s,At,v),k(ke,s,v),d(s,He,v),d(s,Z,v),t(Z,Q),t(Q,Pt),k(je,Pt,null),t(Z,Ot),t(Z,F),t(F,Qe),d(s,L,v),d(s,me,v),t(me,Ve),t(me,Se),t(Se,Mt),t(Mt,et),t(me,sa),d(s,Bt,v),k(V,s,v),d(s,Ye,v),d(s,Ce,v),t(Ce,ht),t(Ce,R),t(R,tt),t(Ce,Ne),d(s,Ee,v),k(Ke,s,v),d(s,at,v),d(s,ut,v),t(ut,zt),t(ut,G),t(G,Ht),t(ut,C),d(s,ne,v),k(ce,s,v),d(s,Fe,v),k(Te,s,v),d(s,mt,v),d(s,xt,v),t(xt,Xt),d(s,ee,v),d(s,Ae,v),t(Ae,le),t(le,st),k(wt,st,null),t(Ae,Yt),t(Ae,r),t(r,_),d(s,ge,v),d(s,Pe,v),t(Pe,Kt),t(Pe,qt),t(qt,ra),t(Pe,Le),d(s,We,v),k(i,s,v),d(s,a,v),d(s,y,v),t(y,Re),t(Re,pa),k(Zt,pa,null),t(y,St),t(y,fa),t(fa,da),d(s,oa,v),d(s,rt,v),t(rt,Qt),t(rt,na),t(na,ga),t(rt,Ct),t(rt,Nt),t(Nt,_a),t(rt,va),d(s,ha,v),k(ct,s,v),la=!0},p(s,v){const te={};v&2&&(te.$$scope={dirty:v,ctx:s}),Te.$set(te)},i(s){la||(j(g.$$.fragment,s),j(S.$$.fragment,s),j(ie.$$.fragment,s),j(ze.$$.fragment,s),j(yt.$$.fragment,s),j(K.$$.fragment,s),j(re.$$.fragment,s),j(be.$$.fragment,s),j(ke.$$.fragment,s),j(je.$$.fragment,s),j(V.$$.fragment,s),j(Ke.$$.fragment,s),j(ce.$$.fragment,s),j(Te.$$.fragment,s),j(wt.$$.fragment,s),j(i.$$.fragment,s),j(Zt.$$.fragment,s),j(ct.$$.fragment,s),la=!0)},o(s){E(g.$$.fragment,s),E(S.$$.fragment,s),E(ie.$$.fragment,s),E(ze.$$.fragment,s),E(yt.$$.fragment,s),E(K.$$.fragment,s),E(re.$$.fragment,s),E(be.$$.fragment,s),E(ke.$$.fragment,s),E(je.$$.fragment,s),E(V.$$.fragment,s),E(Ke.$$.fragment,s),E(ce.$$.fragment,s),E(Te.$$.fragment,s),E(wt.$$.fragment,s),E(i.$$.fragment,s),E(Zt.$$.fragment,s),E(ct.$$.fragment,s),la=!1},d(s){T(g,s),s&&e(A),s&&e(c),s&&e(M),s&&e(q),s&&e(B),T(S,s),s&&e(Ue),s&&e(H),s&&e(kt),s&&e(D),T(ie),T(ze),T(yt),s&&e(Tt),s&&e(X),s&&e(W),T(K,s),s&&e(xe),s&&e(O),T(re),s&&e(Jt),s&&e(qe),s&&e(we),T(be,s),s&&e(Be),s&&e(oe),s&&e(At),T(ke,s),s&&e(He),s&&e(Z),T(je),s&&e(L),s&&e(me),s&&e(Bt),T(V,s),s&&e(Ye),s&&e(Ce),s&&e(Ee),T(Ke,s),s&&e(at),s&&e(ut),s&&e(ne),T(ce,s),s&&e(Fe),T(Te,s),s&&e(mt),s&&e(xt),s&&e(ee),s&&e(Ae),T(wt),s&&e(ge),s&&e(Pe),s&&e(We),T(i,s),s&&e(a),s&&e(y),T(Zt),s&&e(oa),s&&e(rt),s&&e(ha),T(ct,s)}}}function $s(gt){let g,A;return g=new Ma({props:{$$slots:{default:[ys]},$$scope:{ctx:gt}}}),{c(){w(g.$$.fragment)},l(c){b(g.$$.fragment,c)},m(c,$){k(g,c,$),A=!0},p(c,$){const P={};$&2&&(P.$$scope={dirty:$,ctx:c}),g.$set(P)},i(c){A||(j(g.$$.fragment,c),A=!0)},o(c){E(g.$$.fragment,c),A=!1},d(c){T(g,c)}}}function ws(gt){let g,A,c,$,P,z,M,q,Ge,B,S,Ue,H,ta,_t,N,_e,kt,D,ve,Je,vt,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,ye,It,$e,it,yt,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,$t,ue,dt,we,be,Be,oe,aa,At,ke,He,Z,Q,Pt,je,Ot,F,Qe,L,me,Ve,Se,Mt,et,sa,Bt,V,Ye,Ce,ht,R,tt,Ne,Ee,Ke,at,ut,zt,G,Ht,C,ne,ce,Fe,Te,mt,xt,Xt,ee,Ae,le,st,wt,Yt;return z=new ea({}),S=new ds({props:{classNames:"absolute z-10 right-0 top-0",options:[{label:"Mixed",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb"},{label:"PyTorch",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/pytorch/training.ipynb"},{label:"TensorFlow",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tensorflow/training.ipynb"},{label:"Mixed",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb"},{label:"PyTorch",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/pytorch/training.ipynb"},{label:"TensorFlow",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tensorflow/training.ipynb"}]}}),nt=new ea({}),lt=new Ia({props:{id:"_BZearw7f0w"}}),X=new U({props:{code:`from datasets import load_dataset

dataset = load_dataset("yelp_review_full")
dataset["train"][100]`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset

<span class="hljs-meta">&gt;&gt;&gt; </span>dataset = load_dataset(<span class="hljs-string">&quot;yelp_review_full&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>dataset[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">100</span>]
{<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-number">0</span>,
 <span class="hljs-string">&#x27;text&#x27;</span>: <span class="hljs-string">&#x27;My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\\\nThe cashier took my friends\\&#x27;s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\\&#x27;s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\\\&quot;serving off their orders\\\\&quot; when they didn\\&#x27;t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\\\nThe manager was rude when giving me my order. She didn\\&#x27;t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\\\nI\\&#x27;ve eaten at various McDonalds restaurants for over 30 years. I\\&#x27;ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!&#x27;</span>}`}}),de=new U({props:{code:`from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")


def tokenize_function(examples):
    return tokenizer(examples["text"], padding="max_length", truncation=True)


tokenized_datasets = dataset.map(tokenize_function, batched=True)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer

<span class="hljs-meta">&gt;&gt;&gt; </span>tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;bert-base-cased&quot;</span>)


<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">tokenize_function</span>(<span class="hljs-params">examples</span>):
<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> tokenizer(examples[<span class="hljs-string">&quot;text&quot;</span>], padding=<span class="hljs-string">&quot;max_length&quot;</span>, truncation=<span class="hljs-literal">True</span>)


<span class="hljs-meta">&gt;&gt;&gt; </span>tokenized_datasets = dataset.<span class="hljs-built_in">map</span>(tokenize_function, batched=<span class="hljs-literal">True</span>)`}}),Me=new U({props:{code:`small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>small_train_dataset = tokenized_datasets[<span class="hljs-string">&quot;train&quot;</span>].shuffle(seed=<span class="hljs-number">42</span>).select(<span class="hljs-built_in">range</span>(<span class="hljs-number">1000</span>))
<span class="hljs-meta">&gt;&gt;&gt; </span>small_eval_dataset = tokenized_datasets[<span class="hljs-string">&quot;test&quot;</span>].shuffle(seed=<span class="hljs-number">42</span>).select(<span class="hljs-built_in">range</span>(<span class="hljs-number">1000</span>))`}}),oe=new ea({}),je=new os({props:{pytorch:!0,tensorflow:!0,jax:!1,$$slots:{tensorflow:[_s],pytorch:[ms]},$$scope:{ctx:gt}}}),Se=new ea({}),V=new os({props:{pytorch:!0,tensorflow:!1,jax:!1,$$slots:{pytorch:[$s]},$$scope:{ctx:gt}}}),Ee=new ea({}),{c(){g=o("meta"),A=u(),c=o("h1"),$=o("a"),P=o("span"),w(z.$$.fragment),M=u(),q=o("span"),Ge=p("Fine-tune a pretrained model"),B=u(),w(S.$$.fragment),Ue=u(),H=o("p"),ta=p("There are significant benefits to using a pretrained model. It reduces computation costs, your carbon footprint, and allows you to use state-of-the-art models without having to train one from scratch. \u{1F917} Transformers provides access to thousands of pretrained models for a wide range of tasks. When you use a pretrained model, you train it on a dataset specific to your task. This is known as fine-tuning, an incredibly powerful training technique. In this tutorial, you will fine-tune a pretrained model with a deep learning framework of your choice:"),_t=u(),N=o("ul"),_e=o("li"),kt=p("Fine-tune a pretrained model with \u{1F917} Transformers "),D=o("a"),ve=p("Trainer"),Je=p("."),vt=u(),ot=o("li"),jt=p("Fine-tune a pretrained model in TensorFlow with Keras."),Ut=u(),De=o("li"),ie=p("Fine-tune a pretrained model in native PyTorch."),Xe=u(),J=o("a"),I=u(),ae=o("h2"),pe=o("a"),fe=o("span"),w(nt.$$.fragment),Ie=u(),Lt=o("span"),Dt=p("Prepare a dataset"),Y=u(),w(lt.$$.fragment),se=u(),Et=o("p"),ze=p("Before you can fine-tune a pretrained model, download a dataset and prepare it for training. The previous tutorial showed you how to process data for training, and now you get an opportunity to put those skills to the test!"),Oe=u(),ye=o("p"),It=p("Begin by loading the "),$e=o("a"),it=p("Yelp Reviews"),yt=p(" dataset:"),Tt=u(),w(X.$$.fragment),Ze=u(),W=o("p"),K=p("As you now know, you need a tokenizer to process the text and include a padding and truncation strategy to handle any variable sequence lengths. To process your dataset in one step, use \u{1F917} Datasets "),xe=o("a"),O=o("code"),pt=p("map"),ft=p(" method to apply a preprocessing function over the entire dataset:"),re=u(),w(de.$$.fragment),x=u(),he=o("p"),Jt=p("If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:"),qe=u(),w(Me.$$.fragment),$t=u(),ue=o("a"),dt=u(),we=o("h2"),be=o("a"),Be=o("span"),w(oe.$$.fragment),aa=u(),At=o("span"),ke=p("Train"),He=u(),Z=o("p"),Q=p(`At this point, you should follow the section corresponding to the framework you want to use. You can use the links
in the right sidebar to jump to the one you want - and if you want to hide all of the content for a given framework,
just use the button at the top-right of that framework\u2019s block!`),Pt=u(),w(je.$$.fragment),Ot=u(),F=o("a"),Qe=u(),L=o("h2"),me=o("a"),Ve=o("span"),w(Se.$$.fragment),Mt=u(),et=o("span"),sa=p("Train in native PyTorch"),Bt=u(),w(V.$$.fragment),Ye=u(),Ce=o("a"),ht=u(),R=o("h2"),tt=o("a"),Ne=o("span"),w(Ee.$$.fragment),Ke=u(),at=o("span"),ut=p("Additional resources"),zt=u(),G=o("p"),Ht=p("For more fine-tuning examples, refer to:"),C=u(),ne=o("ul"),ce=o("li"),Fe=o("p"),Te=o("a"),mt=p("\u{1F917} Transformers Examples"),xt=p(` includes scripts
to train common NLP tasks in PyTorch and TensorFlow.`),Xt=u(),ee=o("li"),Ae=o("p"),le=o("a"),st=p("\u{1F917} Transformers Notebooks"),wt=p(" contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow."),this.h()},l(r){const _=ps('[data-svelte="svelte-1phssyn"]',document.head);g=n(_,"META",{name:!0,content:!0}),_.forEach(e),A=m(r),c=n(r,"H1",{class:!0});var ge=l(c);$=n(ge,"A",{id:!0,class:!0,href:!0});var Pe=l($);P=n(Pe,"SPAN",{});var Kt=l(P);b(z.$$.fragment,Kt),Kt.forEach(e),Pe.forEach(e),M=m(ge),q=n(ge,"SPAN",{});var qt=l(q);Ge=f(qt,"Fine-tune a pretrained model"),qt.forEach(e),ge.forEach(e),B=m(r),b(S.$$.fragment,r),Ue=m(r),H=n(r,"P",{});var ra=l(H);ta=f(ra,"There are significant benefits to using a pretrained model. It reduces computation costs, your carbon footprint, and allows you to use state-of-the-art models without having to train one from scratch. \u{1F917} Transformers provides access to thousands of pretrained models for a wide range of tasks. When you use a pretrained model, you train it on a dataset specific to your task. This is known as fine-tuning, an incredibly powerful training technique. In this tutorial, you will fine-tune a pretrained model with a deep learning framework of your choice:"),ra.forEach(e),_t=m(r),N=n(r,"UL",{});var Le=l(N);_e=n(Le,"LI",{});var We=l(_e);kt=f(We,"Fine-tune a pretrained model with \u{1F917} Transformers "),D=n(We,"A",{href:!0});var i=l(D);ve=f(i,"Trainer"),i.forEach(e),Je=f(We,"."),We.forEach(e),vt=m(Le),ot=n(Le,"LI",{});var a=l(ot);jt=f(a,"Fine-tune a pretrained model in TensorFlow with Keras."),a.forEach(e),Ut=m(Le),De=n(Le,"LI",{});var y=l(De);ie=f(y,"Fine-tune a pretrained model in native PyTorch."),y.forEach(e),Le.forEach(e),Xe=m(r),J=n(r,"A",{id:!0}),l(J).forEach(e),I=m(r),ae=n(r,"H2",{class:!0});var Re=l(ae);pe=n(Re,"A",{id:!0,class:!0,href:!0});var pa=l(pe);fe=n(pa,"SPAN",{});var Zt=l(fe);b(nt.$$.fragment,Zt),Zt.forEach(e),pa.forEach(e),Ie=m(Re),Lt=n(Re,"SPAN",{});var St=l(Lt);Dt=f(St,"Prepare a dataset"),St.forEach(e),Re.forEach(e),Y=m(r),b(lt.$$.fragment,r),se=m(r),Et=n(r,"P",{});var fa=l(Et);ze=f(fa,"Before you can fine-tune a pretrained model, download a dataset and prepare it for training. The previous tutorial showed you how to process data for training, and now you get an opportunity to put those skills to the test!"),fa.forEach(e),Oe=m(r),ye=n(r,"P",{});var da=l(ye);It=f(da,"Begin by loading the "),$e=n(da,"A",{href:!0,rel:!0});var oa=l($e);it=f(oa,"Yelp Reviews"),oa.forEach(e),yt=f(da," dataset:"),da.forEach(e),Tt=m(r),b(X.$$.fragment,r),Ze=m(r),W=n(r,"P",{});var rt=l(W);K=f(rt,"As you now know, you need a tokenizer to process the text and include a padding and truncation strategy to handle any variable sequence lengths. To process your dataset in one step, use \u{1F917} Datasets "),xe=n(rt,"A",{href:!0,rel:!0});var Qt=l(xe);O=n(Qt,"CODE",{});var na=l(O);pt=f(na,"map"),na.forEach(e),Qt.forEach(e),ft=f(rt," method to apply a preprocessing function over the entire dataset:"),rt.forEach(e),re=m(r),b(de.$$.fragment,r),x=m(r),he=n(r,"P",{});var ga=l(he);Jt=f(ga,"If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:"),ga.forEach(e),qe=m(r),b(Me.$$.fragment,r),$t=m(r),ue=n(r,"A",{id:!0}),l(ue).forEach(e),dt=m(r),we=n(r,"H2",{class:!0});var Ct=l(we);be=n(Ct,"A",{id:!0,class:!0,href:!0});var Nt=l(be);Be=n(Nt,"SPAN",{});var _a=l(Be);b(oe.$$.fragment,_a),_a.forEach(e),Nt.forEach(e),aa=m(Ct),At=n(Ct,"SPAN",{});var va=l(At);ke=f(va,"Train"),va.forEach(e),Ct.forEach(e),He=m(r),Z=n(r,"P",{});var ha=l(Z);Q=f(ha,`At this point, you should follow the section corresponding to the framework you want to use. You can use the links
in the right sidebar to jump to the one you want - and if you want to hide all of the content for a given framework,
just use the button at the top-right of that framework\u2019s block!`),ha.forEach(e),Pt=m(r),b(je.$$.fragment,r),Ot=m(r),F=n(r,"A",{id:!0}),l(F).forEach(e),Qe=m(r),L=n(r,"H2",{class:!0});var ct=l(L);me=n(ct,"A",{id:!0,class:!0,href:!0});var la=l(me);Ve=n(la,"SPAN",{});var s=l(Ve);b(Se.$$.fragment,s),s.forEach(e),la.forEach(e),Mt=m(ct),et=n(ct,"SPAN",{});var v=l(et);sa=f(v,"Train in native PyTorch"),v.forEach(e),ct.forEach(e),Bt=m(r),b(V.$$.fragment,r),Ye=m(r),Ce=n(r,"A",{id:!0}),l(Ce).forEach(e),ht=m(r),R=n(r,"H2",{class:!0});var te=l(R);tt=n(te,"A",{id:!0,class:!0,href:!0});var ia=l(tt);Ne=n(ia,"SPAN",{});var ua=l(Ne);b(Ee.$$.fragment,ua),ua.forEach(e),ia.forEach(e),Ke=m(te),at=n(te,"SPAN",{});var wa=l(at);ut=f(wa,"Additional resources"),wa.forEach(e),te.forEach(e),zt=m(r),G=n(r,"P",{});var Wt=l(G);Ht=f(Wt,"For more fine-tuning examples, refer to:"),Wt.forEach(e),C=m(r),ne=n(r,"UL",{});var Vt=l(ne);ce=n(Vt,"LI",{});var ma=l(ce);Fe=n(ma,"P",{});var Rt=l(Fe);Te=n(Rt,"A",{href:!0,rel:!0});var bt=l(Te);mt=f(bt,"\u{1F917} Transformers Examples"),bt.forEach(e),xt=f(Rt,` includes scripts
to train common NLP tasks in PyTorch and TensorFlow.`),Rt.forEach(e),ma.forEach(e),Xt=m(Vt),ee=n(Vt,"LI",{});var Gt=l(ee);Ae=n(Gt,"P",{});var ya=l(Ae);le=n(ya,"A",{href:!0});var ca=l(le);st=f(ca,"\u{1F917} Transformers Notebooks"),ca.forEach(e),wt=f(ya," contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow."),ya.forEach(e),Gt.forEach(e),Vt.forEach(e),this.h()},h(){h(g,"name","hf:doc:metadata"),h(g,"content",JSON.stringify(bs)),h($,"id","finetune-a-pretrained-model"),h($,"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"),h($,"href","#finetune-a-pretrained-model"),h(c,"class","relative group"),h(D,"href","/docs/transformers/pr_19043/en/main_classes/trainer#transformers.Trainer"),h(J,"id","data-processing"),h(pe,"id","prepare-a-dataset"),h(pe,"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"),h(pe,"href","#prepare-a-dataset"),h(ae,"class","relative group"),h($e,"href","https://huggingface.co/datasets/yelp_review_full"),h($e,"rel","nofollow"),h(xe,"href","https://huggingface.co/docs/datasets/process.html#map"),h(xe,"rel","nofollow"),h(ue,"id","trainer"),h(be,"id","train"),h(be,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),h(be,"href","#train"),h(we,"class","relative group"),h(F,"id","pytorch_native"),h(me,"id","train-in-native-pytorch"),h(me,"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"),h(me,"href","#train-in-native-pytorch"),h(L,"class","relative group"),h(Ce,"id","additional-resources"),h(tt,"id","additional-resources"),h(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"),h(tt,"href","#additional-resources"),h(R,"class","relative group"),h(Te,"href","https://github.com/huggingface/transformers/tree/main/examples"),h(Te,"rel","nofollow"),h(le,"href","notebooks")},m(r,_){t(document.head,g),d(r,A,_),d(r,c,_),t(c,$),t($,P),k(z,P,null),t(c,M),t(c,q),t(q,Ge),d(r,B,_),k(S,r,_),d(r,Ue,_),d(r,H,_),t(H,ta),d(r,_t,_),d(r,N,_),t(N,_e),t(_e,kt),t(_e,D),t(D,ve),t(_e,Je),t(N,vt),t(N,ot),t(ot,jt),t(N,Ut),t(N,De),t(De,ie),d(r,Xe,_),d(r,J,_),d(r,I,_),d(r,ae,_),t(ae,pe),t(pe,fe),k(nt,fe,null),t(ae,Ie),t(ae,Lt),t(Lt,Dt),d(r,Y,_),k(lt,r,_),d(r,se,_),d(r,Et,_),t(Et,ze),d(r,Oe,_),d(r,ye,_),t(ye,It),t(ye,$e),t($e,it),t(ye,yt),d(r,Tt,_),k(X,r,_),d(r,Ze,_),d(r,W,_),t(W,K),t(W,xe),t(xe,O),t(O,pt),t(W,ft),d(r,re,_),k(de,r,_),d(r,x,_),d(r,he,_),t(he,Jt),d(r,qe,_),k(Me,r,_),d(r,$t,_),d(r,ue,_),d(r,dt,_),d(r,we,_),t(we,be),t(be,Be),k(oe,Be,null),t(we,aa),t(we,At),t(At,ke),d(r,He,_),d(r,Z,_),t(Z,Q),d(r,Pt,_),k(je,r,_),d(r,Ot,_),d(r,F,_),d(r,Qe,_),d(r,L,_),t(L,me),t(me,Ve),k(Se,Ve,null),t(L,Mt),t(L,et),t(et,sa),d(r,Bt,_),k(V,r,_),d(r,Ye,_),d(r,Ce,_),d(r,ht,_),d(r,R,_),t(R,tt),t(tt,Ne),k(Ee,Ne,null),t(R,Ke),t(R,at),t(at,ut),d(r,zt,_),d(r,G,_),t(G,Ht),d(r,C,_),d(r,ne,_),t(ne,ce),t(ce,Fe),t(Fe,Te),t(Te,mt),t(Fe,xt),t(ne,Xt),t(ne,ee),t(ee,Ae),t(Ae,le),t(le,st),t(Ae,wt),Yt=!0},p(r,[_]){const ge={};_&2&&(ge.$$scope={dirty:_,ctx:r}),je.$set(ge);const Pe={};_&2&&(Pe.$$scope={dirty:_,ctx:r}),V.$set(Pe)},i(r){Yt||(j(z.$$.fragment,r),j(S.$$.fragment,r),j(nt.$$.fragment,r),j(lt.$$.fragment,r),j(X.$$.fragment,r),j(de.$$.fragment,r),j(Me.$$.fragment,r),j(oe.$$.fragment,r),j(je.$$.fragment,r),j(Se.$$.fragment,r),j(V.$$.fragment,r),j(Ee.$$.fragment,r),Yt=!0)},o(r){E(z.$$.fragment,r),E(S.$$.fragment,r),E(nt.$$.fragment,r),E(lt.$$.fragment,r),E(X.$$.fragment,r),E(de.$$.fragment,r),E(Me.$$.fragment,r),E(oe.$$.fragment,r),E(je.$$.fragment,r),E(Se.$$.fragment,r),E(V.$$.fragment,r),E(Ee.$$.fragment,r),Yt=!1},d(r){e(g),r&&e(A),r&&e(c),T(z),r&&e(B),T(S,r),r&&e(Ue),r&&e(H),r&&e(_t),r&&e(N),r&&e(Xe),r&&e(J),r&&e(I),r&&e(ae),T(nt),r&&e(Y),T(lt,r),r&&e(se),r&&e(Et),r&&e(Oe),r&&e(ye),r&&e(Tt),T(X,r),r&&e(Ze),r&&e(W),r&&e(re),T(de,r),r&&e(x),r&&e(he),r&&e(qe),T(Me,r),r&&e($t),r&&e(ue),r&&e(dt),r&&e(we),T(oe),r&&e(He),r&&e(Z),r&&e(Pt),T(je,r),r&&e(Ot),r&&e(F),r&&e(Qe),r&&e(L),T(Se),r&&e(Bt),T(V,r),r&&e(Ye),r&&e(Ce),r&&e(ht),r&&e(R),T(Ee),r&&e(zt),r&&e(G),r&&e(C),r&&e(ne)}}}const bs={local:"finetune-a-pretrained-model",sections:[{local:"prepare-a-dataset",title:"Prepare a dataset"},{local:"train",title:"Train"},{local:"train-with-pytorch-trainer",sections:[{local:"training-hyperparameters",title:"Training hyperparameters"},{local:"evaluate",title:"Evaluate"},{local:"trainer",title:"Trainer"}],title:"Train with PyTorch Trainer"},{local:"train-a-tensorflow-model-with-keras",sections:[{local:"loading-data-for-keras",title:"Loading data for Keras"},{local:"loading-data-as-a-tfdatadataset",title:"Loading data as a tf.data.Dataset"}],title:"Train a TensorFlow model with Keras"},{local:"train-in-native-pytorch",sections:[{local:"dataloader",title:"DataLoader"},{local:"optimizer-and-learning-rate-scheduler",title:"Optimizer and learning rate scheduler"},{local:"training-loop",title:"Training loop"},{local:"evaluate",title:"Evaluate"}],title:"Train in native PyTorch"},{local:"additional-resources",title:"Additional resources"}],title:"Fine-tune a pretrained model"};function ks(gt){return fs(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class qs extends ns{constructor(g){super();ls(this,g,ks,ws,is,{})}}export{qs as default,bs as metadata};
