import{S as ns,i as ls,s as is,e as o,k as u,w as y,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 w=l(g);A=f(w,`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.`),w.forEach(e)},m(c,w){d(c,g,w),t(g,A)},d(c){c&&e(g)}}}function us(gt){let g,A,c,w,P,z,M,q,Ge,B,S,Ue,H,ta,vt,N,ve,kt,D,_e,Je,_t,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,$e,It,we,it,$t,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,wt,ue,dt,ye,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,yt,Yt,r,v,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(){y(g.$$.fragment),A=u(),c=o("h2"),w=o("a"),P=o("span"),y(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"),vt=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"),ve=p("Trainer"),kt=p(" API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision."),D=u(),_e=o("p"),Je=p("Start by loading your model and specify the number of expected labels. From the Yelp Review "),_t=o("a"),ot=p("dataset card"),jt=p(", you know there are five labels:"),Ut=u(),y(De.$$.fragment),ie=u(),y(Xe.$$.fragment),J=u(),I=o("h3"),ae=o("a"),pe=o("span"),y(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"),$e=p("hyperparameters"),It=p(", but feel free to experiment with these to find your optimal settings."),we=u(),it=o("p"),$t=p("Specify where to save the checkpoints from your training:"),Tt=u(),y(X.$$.fragment),Ze=u(),W=o("h3"),K=o("a"),xe=o("span"),y(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"),wt=p("Trainer"),ue=p(" a function to compute and report metrics. The "),dt=o("a"),ye=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(),y(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(),y(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(),y(G.$$.fragment),Ht=u(),C=o("h3"),ne=o("a"),ce=o("span"),y(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"),yt=p(" object with your model, training arguments, training and test datasets, and evaluation function:"),Yt=u(),y(r.$$.fragment),v=u(),ge=o("p"),Pe=p("Then fine-tune your model by calling "),Kt=o("a"),qt=p("train()"),ra=p(":"),Le=u(),y(We.$$.fragment),this.h()},l(a){b(g.$$.fragment,a),A=m(a),c=n(a,"H2",{class:!0});var $=l(c);w=n($,"A",{id:!0,class:!0,href:!0});var Re=l(w);P=n(Re,"SPAN",{});var pa=l(P);b(z.$$.fragment,pa),pa.forEach(e),Re.forEach(e),M=m($),q=n($,"SPAN",{});var Zt=l(q);Ge=f(Zt,"Train with PyTorch Trainer"),Zt.forEach(e),$.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),vt=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);ve=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),_e=n(a,"P",{});var oa=l(_e);Je=f(oa,"Start by loading your model and specify the number of expected labels. From the Yelp Review "),_t=n(oa,"A",{href:!0,rel:!0});var rt=l(_t);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 va=l(se);Et=f(va,"TrainingArguments"),va.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 _a=l(Oe);$e=f(_a,"hyperparameters"),_a.forEach(e),It=f(Nt,", but feel free to experiment with these to find your optimal settings."),Nt.forEach(e),we=m(a),it=n(a,"P",{});var ha=l(it);$t=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 _=l(ft);re=f(_,"Evaluate"),_.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);wt=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 ya=l(dt);ye=f(ya,"\u{1F917} Evaluate"),ya.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 $a=l(et);sa=f($a,"metric"),$a.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),yt=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),v=m(a),ge=n(a,"P",{});var wa=l(ge);Pe=f(wa,"Then fine-tune your model by calling "),Kt=n(wa,"A",{href:!0});var xa=l(Kt);qt=f(xa,"train()"),xa.forEach(e),ra=f(wa,":"),wa.forEach(e),Le=m(a),b(We.$$.fragment,a),this.h()},h(){h(w,"id","train-with-pytorch-trainer"),h(w,"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(w,"href","#train-with-pytorch-trainer"),h(c,"class","relative group"),h(H,"href","/docs/transformers/v4.25.1/en/main_classes/trainer#transformers.Trainer"),h(N,"href","/docs/transformers/v4.25.1/en/main_classes/trainer#transformers.Trainer"),h(_t,"href","https://huggingface.co/datasets/yelp_review_full#data-fields"),h(_t,"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/v4.25.1/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/v4.25.1/en/main_classes/trainer#transformers.Trainer"),h(Me,"href","/docs/transformers/v4.25.1/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/v0.3.0/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/v4.25.1/en/main_classes/trainer#transformers.Trainer"),h(Kt,"href","/docs/transformers/v4.25.1/en/main_classes/trainer#transformers.Trainer.train")},m(a,$){k(g,a,$),d(a,A,$),d(a,c,$),t(c,w),t(w,P),k(z,P,null),t(c,M),t(c,q),t(q,Ge),d(a,B,$),d(a,S,$),t(S,Ue),t(S,H),t(H,ta),t(S,vt),t(S,N),t(N,ve),t(S,kt),d(a,D,$),d(a,_e,$),t(_e,Je),t(_e,_t),t(_t,ot),t(_e,jt),d(a,Ut,$),k(De,a,$),d(a,ie,$),k(Xe,a,$),d(a,J,$),d(a,I,$),t(I,ae),t(ae,pe),k(fe,pe,null),t(I,nt),t(I,Ie),t(Ie,Lt),d(a,Dt,$),d(a,Y,$),t(Y,lt),t(Y,se),t(se,Et),t(Y,ze),t(Y,Oe),t(Oe,$e),t(Y,It),d(a,we,$),d(a,it,$),t(it,$t),d(a,Tt,$),k(X,a,$),d(a,Ze,$),d(a,W,$),t(W,K),t(K,xe),k(O,xe,null),t(W,pt),t(W,ft),t(ft,re),d(a,de,$),d(a,x,$),t(x,he),t(he,Jt),t(x,qe),t(x,Me),t(Me,wt),t(x,ue),t(x,dt),t(dt,ye),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,$),k(F,a,$),d(a,Qe,$),d(a,L,$),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,$),k(R,a,$),d(a,tt,$),d(a,Ne,$),t(Ne,Ee),t(Ne,Ke),t(Ke,at),t(Ne,ut),d(a,zt,$),k(G,a,$),d(a,Ht,$),d(a,C,$),t(C,ne),t(ne,ce),k(Fe,ce,null),t(C,Te),t(C,mt),t(mt,xt),d(a,Xt,$),d(a,ee,$),t(ee,Ae),t(ee,le),t(le,st),t(ee,yt),d(a,Yt,$),k(r,a,$),d(a,v,$),d(a,ge,$),t(ge,Pe),t(ge,Kt),t(Kt,qt),t(ge,ra),d(a,Le,$),k(We,a,$),i=!0},p(a,$){const Re={};$&2&&(Re.$$scope={dirty:$,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(_e),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(we),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(v),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(){y(g.$$.fragment)},l(c){b(g.$$.fragment,c)},m(c,w){k(g,c,w),A=!0},p(c,w){const P={};w&2&&(P.$$scope={dirty:w,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,w,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"),w=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);w=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,w),t(g,P)},d(z){z&&e(g)}}}function gs(gt){let g,A,c,w,P,z,M,q,Ge,B,S,Ue,H,ta,vt,N,ve,kt,D,_e,Je,_t,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,$e,It,we,it,$t,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,wt,ue,dt,ye,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,yt,Yt,r,v,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(),y(c.$$.fragment),w=u(),P=o("h2"),z=o("a"),M=o("span"),y(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!"),vt=u(),N=o("h3"),ve=o("a"),kt=o("span"),y(D.$$.fragment),_e=u(),Je=o("span"),_t=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(),y(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(),y(Y.$$.fragment),lt=u(),se=o("p"),Et=p("Finally, load, "),ze=o("a"),Oe=o("code"),$e=p("compile"),It=p(", and "),we=o("a"),it=o("code"),$t=p("fit"),Tt=p(" the model:"),X=u(),y(Ze.$$.fragment),W=u(),y(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"),y(he.$$.fragment),Jt=u(),qe=o("span"),Me=p("Loading data as a tf.data.Dataset"),wt=u(),ue=o("p"),dt=p("If you want to avoid slowing down training, you can load your data as a "),ye=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(),y(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(),y(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"),yt=p("notebooks"),Yt=p(" to see this approach in action."),r=u(),v=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(),y(Le.$$.fragment),this.h()},l(i){g=n(i,"A",{id:!0}),l(g).forEach(e),A=m(i),b(c.$$.fragment,i),w=m(i),P=n(i,"H2",{class:!0});var a=l(P);z=n(a,"A",{id:!0,class:!0,href:!0});var $=l(z);M=n($,"SPAN",{});var Re=l(M);b(q.$$.fragment,Re),Re.forEach(e),$.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),vt=m(i),N=n(i,"H3",{class:!0});var St=l(N);ve=n(St,"A",{id:!0,class:!0,href:!0});var fa=l(ve);kt=n(fa,"SPAN",{});var da=l(kt);b(D.$$.fragment,da),da.forEach(e),fa.forEach(e),_e=m(St),Je=n(St,"SPAN",{});var oa=l(Je);_t=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 va=l(Oe);$e=f(va,"compile"),va.forEach(e),Nt.forEach(e),It=f(Ct,", and "),we=n(Ct,"A",{href:!0,rel:!0});var _a=l(we);it=n(_a,"CODE",{});var ha=l(it);$t=f(ha,"fit"),ha.forEach(e),_a.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 _=l(x);b(he.$$.fragment,_),_.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),wt=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 "),ye=n(ia,"CODE",{});var ua=l(ye);be=f(ua,"tf.data.Dataset"),ua.forEach(e),Be=f(ia,` instead. Although you can write your own
`),oe=n(ia,"CODE",{});var ya=l(oe);aa=f(ya,"tf.data"),ya.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 $a=l(et);sa=f($a,"label_cols"),$a.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);yt=f(Ea,"notebooks"),Ea.forEach(e),Yt=f(Ft," to see this approach in action."),Ft.forEach(e),r=m(i),v=n(i,"P",{});var Ta=l(v);ge=f(Ta,"Once you\u2019ve created a "),Pe=n(Ta,"CODE",{});var wa=l(Pe);Kt=f(wa,"tf.data.Dataset"),wa.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(ve,"id","loading-data-for-keras"),h(ve,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),h(ve,"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(we,"href","https://keras.io/api/models/model_training_apis/#fit-method"),h(we,"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/v4.25.1/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset"),h(Qe,"href","https://huggingface.co/docs/datasets/v2.7.1/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset"),h(Qe,"rel","nofollow"),h(ht,"href","/docs/transformers/v4.25.1/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,w,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,vt,a),d(i,N,a),t(N,ve),t(ve,kt),k(D,kt,null),t(N,_e),t(N,Je),t(Je,_t),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,$e),t(se,It),t(se,we),t(we,it),t(it,$t),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,wt,a),d(i,ue,a),t(ue,dt),t(ue,ye),t(ye,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,yt),t(C,Yt),d(i,r,a),d(i,v,a),t(v,ge),t(v,Pe),t(Pe,Kt),t(v,qt),d(i,ra,a),k(Le,i,a),We=!0},p(i,a){const $={};a&2&&($.$$scope={dirty:a,ctx:i}),K.$set($)},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(w),i&&e(P),T(q),i&&e(Ue),i&&e(H),i&&e(vt),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(wt),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(v),i&&e(ra),T(Le,i)}}}function vs(gt){let g,A;return g=new Ma({props:{$$slots:{default:[gs]},$$scope:{ctx:gt}}}),{c(){y(g.$$.fragment)},l(c){b(g.$$.fragment,c)},m(c,w){k(g,c,w),A=!0},p(c,w){const P={};w&2&&(P.$$scope={dirty:w,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 _s(gt){let g,A,c,w,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"),w=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);w=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,w),t(g,P),t(g,z),t(z,M),t(g,q)},d(Ge){Ge&&e(g)}}}function $s(gt){let g,A,c,w,P,z,M,q,Ge,B,S,Ue,H,ta,vt,N,ve,kt,D,_e,Je,_t,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,$e,It,we,it,$t,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,wt,ue,dt,ye,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,yt,Yt,r,v,ge,Pe,Kt,qt,ra,Le,We,i,a,$,Re,pa,Zt,St,fa,da,oa,rt,Qt,na,ga,Ct,Nt,va,_a,ha,ct,la;return g=new Ia({props:{id:"Dh9CL8fyG80"}}),S=new U({props:{code:`del model
del trainer
torch.cuda.empty_cache()`,highlighted:`<span class="hljs-keyword">del</span> 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>)'}}),$t=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:[_s]},$$scope:{ctx:gt}}}),yt=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(){y(g.$$.fragment),A=u(),c=o("p"),w=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(),y(S.$$.fragment),Ue=u(),H=o("p"),ta=p("Next, manually postprocess "),vt=o("code"),N=p("tokenized_dataset"),ve=p(" to prepare it for training."),kt=u(),D=o("ol"),_e=o("li"),Je=o("p"),_t=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(),y(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(),y(ze.$$.fragment),Oe=u(),$e=o("li"),It=o("p"),we=p("Set the format of the dataset to return PyTorch tensors instead of lists:"),it=u(),y($t.$$.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(),y(K.$$.fragment),xe=u(),O=o("h3"),pt=o("a"),ft=o("span"),y(re.$$.fragment),de=u(),x=o("span"),he=p("DataLoader"),Jt=u(),qe=o("p"),Me=p("Create a "),wt=o("code"),ue=p("DataLoader"),dt=p(" for your training and test datasets so you can iterate over batches of data:"),ye=u(),y(be.$$.fragment),Be=u(),oe=o("p"),aa=p("Load your model with the number of expected labels:"),At=u(),y(ke.$$.fragment),He=u(),Z=o("h3"),Q=o("a"),Pt=o("span"),y(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(),y(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(),y(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(),y(ce.$$.fragment),Fe=u(),y(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"),y(yt.$$.fragment),Yt=u(),r=o("span"),v=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(),y(i.$$.fragment),a=u(),$=o("h3"),Re=o("a"),pa=o("span"),y(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"),va=p("add_batch"),_a=p(" and calculate the metric at the very end."),ha=u(),y(ct.$$.fragment),this.h()},l(s){b(g.$$.fragment,s),A=m(s),c=n(s,"P",{});var _=l(c);w=n(_,"A",{href:!0});var te=l(w);P=f(te,"Trainer"),te.forEach(e),z=f(_," 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."),_.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 "),vt=n(ua,"CODE",{});var ya=l(vt);N=f(ya,"tokenized_dataset"),ya.forEach(e),ve=f(ua," to prepare it for training."),ua.forEach(e),kt=m(s),D=n(s,"OL",{});var Wt=l(D);_e=n(Wt,"LI",{});var Vt=l(_e);Je=n(Vt,"P",{});var ma=l(Je);_t=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 $a=l(pe);fe=f($a,"label"),$a.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),$e=n(Wt,"LI",{});var ka=l($e);It=n(ka,"P",{});var Ft=l(It);we=f(Ft,"Set the format of the dataset to return PyTorch tensors instead of lists:"),Ft.forEach(e),it=m(ka),b($t.$$.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 wa=l(qe);Me=f(wa,"Create a "),wt=n(wa,"CODE",{});var xa=l(wt);ue=f(xa,"DataLoader"),xa.forEach(e),dt=f(wa," for your training and test datasets so you can iterate over batches of data:"),wa.forEach(e),ye=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(yt.$$.fragment,Za),Za.forEach(e),Xa.forEach(e),Yt=m(Fa),r=n(Fa,"SPAN",{});var Qa=l(r);v=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),$=n(s,"H3",{class:!0});var Da=l($);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);va=f(rs,"add_batch"),rs.forEach(e),_a=f(za," and calculate the metric at the very end."),za.forEach(e),ha=m(s),b(ct.$$.fragment,s),this.h()},h(){h(w,"href","/docs/transformers/v4.25.1/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/v4.25.1/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($,"class","relative group"),h(na,"href","/docs/transformers/v4.25.1/en/main_classes/trainer#transformers.Trainer")},m(s,_){k(g,s,_),d(s,A,_),d(s,c,_),t(c,w),t(w,P),t(c,z),d(s,M,_),d(s,q,_),t(q,Ge),d(s,B,_),k(S,s,_),d(s,Ue,_),d(s,H,_),t(H,ta),t(H,vt),t(vt,N),t(H,ve),d(s,kt,_),d(s,D,_),t(D,_e),t(_e,Je),t(Je,_t),t(Je,ot),t(ot,jt),t(Je,Ut),t(_e,De),k(ie,_e,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,$e),t($e,It),t(It,we),t($e,it),k($t,$e,null),d(s,Tt,_),d(s,X,_),t(X,Ze),d(s,W,_),k(K,s,_),d(s,xe,_),d(s,O,_),t(O,pt),t(pt,ft),k(re,ft,null),t(O,de),t(O,x),t(x,he),d(s,Jt,_),d(s,qe,_),t(qe,Me),t(qe,wt),t(wt,ue),t(qe,dt),d(s,ye,_),k(be,s,_),d(s,Be,_),d(s,oe,_),t(oe,aa),d(s,At,_),k(ke,s,_),d(s,He,_),d(s,Z,_),t(Z,Q),t(Q,Pt),k(je,Pt,null),t(Z,Ot),t(Z,F),t(F,Qe),d(s,L,_),d(s,me,_),t(me,Ve),t(me,Se),t(Se,Mt),t(Mt,et),t(me,sa),d(s,Bt,_),k(V,s,_),d(s,Ye,_),d(s,Ce,_),t(Ce,ht),t(Ce,R),t(R,tt),t(Ce,Ne),d(s,Ee,_),k(Ke,s,_),d(s,at,_),d(s,ut,_),t(ut,zt),t(ut,G),t(G,Ht),t(ut,C),d(s,ne,_),k(ce,s,_),d(s,Fe,_),k(Te,s,_),d(s,mt,_),d(s,xt,_),t(xt,Xt),d(s,ee,_),d(s,Ae,_),t(Ae,le),t(le,st),k(yt,st,null),t(Ae,Yt),t(Ae,r),t(r,v),d(s,ge,_),d(s,Pe,_),t(Pe,Kt),t(Pe,qt),t(qt,ra),t(Pe,Le),d(s,We,_),k(i,s,_),d(s,a,_),d(s,$,_),t($,Re),t(Re,pa),k(Zt,pa,null),t($,St),t($,fa),t(fa,da),d(s,oa,_),d(s,rt,_),t(rt,Qt),t(rt,na),t(na,ga),t(rt,Ct),t(rt,Nt),t(Nt,va),t(rt,_a),d(s,ha,_),k(ct,s,_),la=!0},p(s,_){const te={};_&2&&(te.$$scope={dirty:_,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($t.$$.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(yt.$$.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($t.$$.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(yt.$$.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($t),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(ye),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(yt),s&&e(ge),s&&e(Pe),s&&e(We),T(i,s),s&&e(a),s&&e($),T(Zt),s&&e(oa),s&&e(rt),s&&e(ha),T(ct,s)}}}function ws(gt){let g,A;return g=new Ma({props:{$$slots:{default:[$s]},$$scope:{ctx:gt}}}),{c(){y(g.$$.fragment)},l(c){b(g.$$.fragment,c)},m(c,w){k(g,c,w),A=!0},p(c,w){const P={};w&2&&(P.$$scope={dirty:w,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 ys(gt){let g,A,c,w,P,z,M,q,Ge,B,S,Ue,H,ta,vt,N,ve,kt,D,_e,Je,_t,ot,jt,Ut,De,ie,Xe,J,I,ae,pe,fe,nt,Ie,Lt,Dt,Y,lt,se,Et,ze,Oe,$e,It,we,it,$t,Tt,X,Ze,W,K,xe,O,pt,ft,re,de,x,he,Jt,qe,Me,wt,ue,dt,ye,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,yt,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:[vs],pytorch:[ms]},$$scope:{ctx:gt}}}),Se=new ea({}),V=new os({props:{pytorch:!0,tensorflow:!1,jax:!1,$$slots:{pytorch:[ws]},$$scope:{ctx:gt}}}),Ee=new ea({}),{c(){g=o("meta"),A=u(),c=o("h1"),w=o("a"),P=o("span"),y(z.$$.fragment),M=u(),q=o("span"),Ge=p("Fine-tune a pretrained model"),B=u(),y(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:"),vt=u(),N=o("ul"),ve=o("li"),kt=p("Fine-tune a pretrained model with \u{1F917} Transformers "),D=o("a"),_e=p("Trainer"),Je=p("."),_t=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"),y(nt.$$.fragment),Ie=u(),Lt=o("span"),Dt=p("Prepare a dataset"),Y=u(),y(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(),$e=o("p"),It=p("Begin by loading the "),we=o("a"),it=p("Yelp Reviews"),$t=p(" dataset:"),Tt=u(),y(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(),y(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(),y(Me.$$.fragment),wt=u(),ue=o("a"),dt=u(),ye=o("h2"),be=o("a"),Be=o("span"),y(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(),y(je.$$.fragment),Ot=u(),F=o("a"),Qe=u(),L=o("h2"),me=o("a"),Ve=o("span"),y(Se.$$.fragment),Mt=u(),et=o("span"),sa=p("Train in native PyTorch"),Bt=u(),y(V.$$.fragment),Ye=u(),Ce=o("a"),ht=u(),R=o("h2"),tt=o("a"),Ne=o("span"),y(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"),yt=p(" contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow."),this.h()},l(r){const v=ps('[data-svelte="svelte-1phssyn"]',document.head);g=n(v,"META",{name:!0,content:!0}),v.forEach(e),A=m(r),c=n(r,"H1",{class:!0});var ge=l(c);w=n(ge,"A",{id:!0,class:!0,href:!0});var Pe=l(w);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),vt=m(r),N=n(r,"UL",{});var Le=l(N);ve=n(Le,"LI",{});var We=l(ve);kt=f(We,"Fine-tune a pretrained model with \u{1F917} Transformers "),D=n(We,"A",{href:!0});var i=l(D);_e=f(i,"Trainer"),i.forEach(e),Je=f(We,"."),We.forEach(e),_t=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 $=l(De);ie=f($,"Fine-tune a pretrained model in native PyTorch."),$.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),$e=n(r,"P",{});var da=l($e);It=f(da,"Begin by loading the "),we=n(da,"A",{href:!0,rel:!0});var oa=l(we);it=f(oa,"Yelp Reviews"),oa.forEach(e),$t=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),wt=m(r),ue=n(r,"A",{id:!0}),l(ue).forEach(e),dt=m(r),ye=n(r,"H2",{class:!0});var Ct=l(ye);be=n(Ct,"A",{id:!0,class:!0,href:!0});var Nt=l(be);Be=n(Nt,"SPAN",{});var va=l(Be);b(oe.$$.fragment,va),va.forEach(e),Nt.forEach(e),aa=m(Ct),At=n(Ct,"SPAN",{});var _a=l(At);ke=f(_a,"Train"),_a.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 _=l(et);sa=f(_,"Train in native PyTorch"),_.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 ya=l(at);ut=f(ya,"Additional resources"),ya.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 $a=l(Ae);le=n($a,"A",{href:!0});var ca=l(le);st=f(ca,"\u{1F917} Transformers Notebooks"),ca.forEach(e),yt=f($a," contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow."),$a.forEach(e),Gt.forEach(e),Vt.forEach(e),this.h()},h(){h(g,"name","hf:doc:metadata"),h(g,"content",JSON.stringify(bs)),h(w,"id","finetune-a-pretrained-model"),h(w,"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(w,"href","#finetune-a-pretrained-model"),h(c,"class","relative group"),h(D,"href","/docs/transformers/v4.25.1/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(we,"href","https://huggingface.co/datasets/yelp_review_full"),h(we,"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(ye,"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,v){t(document.head,g),d(r,A,v),d(r,c,v),t(c,w),t(w,P),k(z,P,null),t(c,M),t(c,q),t(q,Ge),d(r,B,v),k(S,r,v),d(r,Ue,v),d(r,H,v),t(H,ta),d(r,vt,v),d(r,N,v),t(N,ve),t(ve,kt),t(ve,D),t(D,_e),t(ve,Je),t(N,_t),t(N,ot),t(ot,jt),t(N,Ut),t(N,De),t(De,ie),d(r,Xe,v),d(r,J,v),d(r,I,v),d(r,ae,v),t(ae,pe),t(pe,fe),k(nt,fe,null),t(ae,Ie),t(ae,Lt),t(Lt,Dt),d(r,Y,v),k(lt,r,v),d(r,se,v),d(r,Et,v),t(Et,ze),d(r,Oe,v),d(r,$e,v),t($e,It),t($e,we),t(we,it),t($e,$t),d(r,Tt,v),k(X,r,v),d(r,Ze,v),d(r,W,v),t(W,K),t(W,xe),t(xe,O),t(O,pt),t(W,ft),d(r,re,v),k(de,r,v),d(r,x,v),d(r,he,v),t(he,Jt),d(r,qe,v),k(Me,r,v),d(r,wt,v),d(r,ue,v),d(r,dt,v),d(r,ye,v),t(ye,be),t(be,Be),k(oe,Be,null),t(ye,aa),t(ye,At),t(At,ke),d(r,He,v),d(r,Z,v),t(Z,Q),d(r,Pt,v),k(je,r,v),d(r,Ot,v),d(r,F,v),d(r,Qe,v),d(r,L,v),t(L,me),t(me,Ve),k(Se,Ve,null),t(L,Mt),t(L,et),t(et,sa),d(r,Bt,v),k(V,r,v),d(r,Ye,v),d(r,Ce,v),d(r,ht,v),d(r,R,v),t(R,tt),t(tt,Ne),k(Ee,Ne,null),t(R,Ke),t(R,at),t(at,ut),d(r,zt,v),d(r,G,v),t(G,Ht),d(r,C,v),d(r,ne,v),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,yt),Yt=!0},p(r,[v]){const ge={};v&2&&(ge.$$scope={dirty:v,ctx:r}),je.$set(ge);const Pe={};v&2&&(Pe.$$scope={dirty:v,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(vt),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($e),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(wt),r&&e(ue),r&&e(dt),r&&e(ye),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,ys,is,{})}}export{qs as default,bs as metadata};
