import{S as $c,i as qc,s as Ec,e as o,k as h,w as u,t,M as Ac,c as i,d as a,m as c,a as r,x as m,h as n,b as d,N as Dc,G as e,g as p,y as g,q as f,o as x,B as _,v as Tc}from"../../chunks/vendor-hf-doc-builder.js";import{T as Lc}from"../../chunks/Tip-hf-doc-builder.js";import{I as Ts}from"../../chunks/IconCopyLink-hf-doc-builder.js";import{C as j}from"../../chunks/CodeBlock-hf-doc-builder.js";import{D as Pc}from"../../chunks/DocNotebookDropdown-hf-doc-builder.js";function Cc(Pt){let k,is,A,v,C,Q,Ls,O,Ps,rs,D,ps;return{c(){k=o("p"),is=t("The task illustrated in this tutorial is supported by the following model architectures:"),A=h(),v=o("p"),C=o("a"),Q=t("LayoutLM"),Ls=t(", "),O=o("a"),Ps=t("LayoutLMv2"),rs=t(", "),D=o("a"),ps=t("LayoutLMv3"),this.h()},l(b){k=i(b,"P",{});var S=r(k);is=n(S,"The task illustrated in this tutorial is supported by the following model architectures:"),S.forEach(a),A=c(b),v=i(b,"P",{});var R=r(v);C=i(R,"A",{href:!0});var Y=r(C);Q=n(Y,"LayoutLM"),Y.forEach(a),Ls=n(R,", "),O=i(R,"A",{href:!0});var De=r(O);Ps=n(De,"LayoutLMv2"),De.forEach(a),rs=n(R,", "),D=i(R,"A",{href:!0});var Cs=r(D);ps=n(Cs,"LayoutLMv3"),Cs.forEach(a),R.forEach(a),this.h()},h(){d(C,"href","../model_doc/layoutlm"),d(O,"href","../model_doc/layoutlmv2"),d(D,"href","../model_doc/layoutlmv3")},m(b,S){p(b,k,S),e(k,is),p(b,A,S),p(b,v,S),e(v,C),e(C,Q),e(v,Ls),e(v,O),e(O,Ps),e(v,rs),e(v,D),e(D,ps)},d(b){b&&a(k),b&&a(A),b&&a(v)}}}function Oc(Pt){let k,is,A,v,C,Q,Ls,O,Ps,rs,D,ps,b,S,R,Y,De,Cs,hs,J,$l,Te,ql,El,Os,Al,Dl,Tl,ba,Ll,Ct,cs,Ot,Le,Pl,It,Pe,Cl,zt,Is,Mt,zs,Nt,Ms,Ft,Ce,Ol,Qt,Oe,Il,Rt,Ns,St,Ie,zl,Ht,Fs,Wt,X,ds,ya,Qs,Ml,ka,Nl,Vt,H,Fl,Rs,Ql,Rl,Ss,Sl,Hl,Bt,Hs,Gt,ze,Wl,Ut,Ws,Kt,Me,Vl,Yt,$,Ne,$a,Bl,Gl,Ul,Fe,qa,Kl,Yl,Jl,Qe,Ea,Xl,Zl,so,Re,Aa,eo,ao,to,us,Da,no,lo,Ta,oo,io,ro,Se,La,po,ho,Jt,ms,co,Pa,uo,mo,Xt,Vs,Zt,I,go,Ca,fo,xo,Z,_o,Oa,jo,wo,vo,Bs,bo,yo,sn,Gs,en,W,ko,He,$o,qo,Us,Ia,Eo,Ao,Do,an,Ks,tn,We,To,nn,Ys,ln,Js,Ve,wp,on,ss,gs,za,Xs,Lo,Ma,Po,rn,fs,Co,Be,Oo,Io,pn,Zs,hn,es,xs,Na,se,zo,Fa,Mo,cn,_s,No,Qa,Fo,Qo,dn,ee,un,js,Ro,Ra,So,Ho,mn,ae,gn,as,ws,Sa,te,Wo,Ha,Vo,fn,q,Bo,Wa,Go,Uo,Va,Ko,Yo,Ba,Jo,Xo,Ga,Zo,si,Ua,ei,ai,xn,ne,_n,z,ti,Ka,ni,li,Ya,oi,ii,Ja,ri,pi,jn,Ge,hi,wn,w,ci,Xa,di,ui,Za,mi,gi,st,fi,xi,et,_i,ji,at,wi,vi,tt,bi,yi,nt,ki,$i,lt,qi,Ei,vn,le,bn,Ue,Ai,yn,oe,kn,Ke,Di,$n,ie,qn,Ye,Ti,En,V,Je,ot,Li,Pi,Ci,Xe,it,Oi,Ii,zi,vs,rt,Mi,Ni,pt,Fi,Qi,An,Ze,Ri,Dn,re,Tn,sa,Si,Ln,pe,Pn,ea,Hi,Cn,he,On,ts,bs,ht,ce,Wi,ct,Vi,In,B,Bi,aa,Gi,Ui,de,Ki,Yi,zn,ns,ys,dt,ue,Ji,ut,Xi,Mn,ta,Zi,Nn,T,me,sr,na,er,ar,tr,ge,nr,la,lr,or,ir,fe,rr,oa,pr,hr,cr,xe,dr,ia,ur,mr,gr,_e,fr,ra,xr,_r,Fn,je,Qn,E,jr,pa,wr,vr,mt,br,yr,gt,kr,$r,ft,qr,Er,xt,Ar,Dr,Rn,we,Sn,ha,Tr,Hn,ve,Wn,ks,Lr,ca,Pr,Cr,Vn,be,Bn,$s,Or,_t,Ir,zr,Gn,ye,Un,ls,qs,jt,ke,Mr,wt,Nr,Kn,Es,Fr,da,Qr,Rr,Yn,ua,Sr,Jn,$e,Xn,ma,Hr,Zn,qe,sl,ga,Wr,el,L,vt,Vr,Br,bt,Gr,Ur,os,Kr,yt,Yr,Jr,kt,Xr,Zr,sp,P,ep,$t,ap,tp,qt,np,lp,Et,op,ip,At,rp,pp,hp,Dt,cp,al,Ee,tl;return Q=new Ts({}),D=new Pc({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/document_question_answering.ipynb"},{label:"PyTorch",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/pytorch/document_question_answering.ipynb"},{label:"TensorFlow",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tensorflow/document_question_answering.ipynb"},{label:"Mixed",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/document_question_answering.ipynb"},{label:"PyTorch",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/pytorch/document_question_answering.ipynb"},{label:"TensorFlow",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tensorflow/document_question_answering.ipynb"}]}}),cs=new Lc({props:{$$slots:{default:[Cc]},$$scope:{ctx:Pt}}}),Is=new j({props:{code:"pip install -q transformers datasets",highlighted:"pip install -q transformers datasets"}}),zs=new j({props:{code:`pip install 'git+https://github.com/facebookresearch/detectron2.git'
pip install torchvision`,highlighted:`pip install <span class="hljs-string">&#x27;git+https://github.com/facebookresearch/detectron2.git&#x27;</span>
pip install torchvision`}}),Ms=new j({props:{code:`sudo apt install tesseract-ocr
pip install -q pytesseract`,highlighted:`sudo apt install tesseract-ocr
pip install -q pytesseract`}}),Ns=new j({props:{code:`from huggingface_hub import notebook_login

notebook_login()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login

<span class="hljs-meta">&gt;&gt;&gt; </span>notebook_login()`}}),Fs=new j({props:{code:`model_checkpoint = "microsoft/layoutlmv2-base-uncased"
batch_size = 4`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>model_checkpoint = <span class="hljs-string">&quot;microsoft/layoutlmv2-base-uncased&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>batch_size = <span class="hljs-number">4</span>`}}),Qs=new Ts({}),Hs=new j({props:{code:`from datasets import load_dataset

dataset = load_dataset("nielsr/docvqa_1200_examples")
dataset`,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;nielsr/docvqa_1200_examples&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>dataset
DatasetDict({
    train: Dataset({
        features: [<span class="hljs-string">&#x27;id&#x27;</span>, <span class="hljs-string">&#x27;image&#x27;</span>, <span class="hljs-string">&#x27;query&#x27;</span>, <span class="hljs-string">&#x27;answers&#x27;</span>, <span class="hljs-string">&#x27;words&#x27;</span>, <span class="hljs-string">&#x27;bounding_boxes&#x27;</span>, <span class="hljs-string">&#x27;answer&#x27;</span>],
        num_rows: <span class="hljs-number">1000</span>
    })
    test: Dataset({
        features: [<span class="hljs-string">&#x27;id&#x27;</span>, <span class="hljs-string">&#x27;image&#x27;</span>, <span class="hljs-string">&#x27;query&#x27;</span>, <span class="hljs-string">&#x27;answers&#x27;</span>, <span class="hljs-string">&#x27;words&#x27;</span>, <span class="hljs-string">&#x27;bounding_boxes&#x27;</span>, <span class="hljs-string">&#x27;answer&#x27;</span>],
        num_rows: <span class="hljs-number">200</span>
    })
})`}}),Ws=new j({props:{code:'dataset["train"].features',highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>dataset[<span class="hljs-string">&quot;train&quot;</span>].features'}}),Vs=new j({props:{code:`updated_dataset = dataset.map(lambda example: {"question": example["query"]["en"]}, remove_columns=["query"])
updated_dataset = updated_dataset.map(
    lambda example: {"answer": example["answers"][0]}, remove_columns=["answer", "answers"]
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>updated_dataset = dataset.<span class="hljs-built_in">map</span>(<span class="hljs-keyword">lambda</span> example: {<span class="hljs-string">&quot;question&quot;</span>: example[<span class="hljs-string">&quot;query&quot;</span>][<span class="hljs-string">&quot;en&quot;</span>]}, remove_columns=[<span class="hljs-string">&quot;query&quot;</span>])
<span class="hljs-meta">&gt;&gt;&gt; </span>updated_dataset = updated_dataset.<span class="hljs-built_in">map</span>(
<span class="hljs-meta">... </span>    <span class="hljs-keyword">lambda</span> example: {<span class="hljs-string">&quot;answer&quot;</span>: example[<span class="hljs-string">&quot;answers&quot;</span>][<span class="hljs-number">0</span>]}, remove_columns=[<span class="hljs-string">&quot;answer&quot;</span>, <span class="hljs-string">&quot;answers&quot;</span>]
<span class="hljs-meta">... </span>)`}}),Gs=new j({props:{code:'updated_dataset = updated_dataset.filter(lambda x: len(x["words"]) + len(x["question"].split()) < 512)',highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>updated_dataset = updated_dataset.<span class="hljs-built_in">filter</span>(<span class="hljs-keyword">lambda</span> x: <span class="hljs-built_in">len</span>(x[<span class="hljs-string">&quot;words&quot;</span>]) + <span class="hljs-built_in">len</span>(x[<span class="hljs-string">&quot;question&quot;</span>].split()) &lt; <span class="hljs-number">512</span>)'}}),Ks=new j({props:{code:`updated_dataset = updated_dataset.remove_columns("words")
updated_dataset = updated_dataset.remove_columns("bounding_boxes")`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>updated_dataset = updated_dataset.remove_columns(<span class="hljs-string">&quot;words&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>updated_dataset = updated_dataset.remove_columns(<span class="hljs-string">&quot;bounding_boxes&quot;</span>)`}}),Ys=new j({props:{code:'updated_dataset["train"][11]["image"]',highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>updated_dataset[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">11</span>][<span class="hljs-string">&quot;image&quot;</span>]'}}),Xs=new Ts({}),Zs=new j({props:{code:`from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained(model_checkpoint)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor

<span class="hljs-meta">&gt;&gt;&gt; </span>processor = AutoProcessor.from_pretrained(model_checkpoint)`}}),se=new Ts({}),ee=new j({props:{code:`image_processor = processor.image_processor


def get_ocr_words_and_boxes(examples):
    images = [image.convert("RGB") for image in examples["image"]]
    encoded_inputs = image_processor(images)

    examples["image"] = encoded_inputs.pixel_values
    examples["words"] = encoded_inputs.words
    examples["boxes"] = encoded_inputs.boxes

    return examples`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>image_processor = processor.image_processor


<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_ocr_words_and_boxes</span>(<span class="hljs-params">examples</span>):
<span class="hljs-meta">... </span>    images = [image.convert(<span class="hljs-string">&quot;RGB&quot;</span>) <span class="hljs-keyword">for</span> image <span class="hljs-keyword">in</span> examples[<span class="hljs-string">&quot;image&quot;</span>]]
<span class="hljs-meta">... </span>    encoded_inputs = image_processor(images)

<span class="hljs-meta">... </span>    examples[<span class="hljs-string">&quot;image&quot;</span>] = encoded_inputs.pixel_values
<span class="hljs-meta">... </span>    examples[<span class="hljs-string">&quot;words&quot;</span>] = encoded_inputs.words
<span class="hljs-meta">... </span>    examples[<span class="hljs-string">&quot;boxes&quot;</span>] = encoded_inputs.boxes

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> examples`}}),ae=new j({props:{code:"dataset_with_ocr = updated_dataset.map(get_ocr_words_and_boxes, batched=True, batch_size=2)",highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>dataset_with_ocr = updated_dataset.<span class="hljs-built_in">map</span>(get_ocr_words_and_boxes, batched=<span class="hljs-literal">True</span>, batch_size=<span class="hljs-number">2</span>)'}}),te=new Ts({}),ne=new j({props:{code:"tokenizer = processor.tokenizer",highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>tokenizer = processor.tokenizer'}}),le=new j({props:{code:`def subfinder(words_list, answer_list):
    matches = []
    start_indices = []
    end_indices = []
    for idx, i in enumerate(range(len(words_list))):
        if words_list[i] == answer_list[0] and words_list[i : i + len(answer_list)] == answer_list:
            matches.append(answer_list)
            start_indices.append(idx)
            end_indices.append(idx + len(answer_list) - 1)
    if matches:
        return matches[0], start_indices[0], end_indices[0]
    else:
        return None, 0, 0`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">subfinder</span>(<span class="hljs-params">words_list, answer_list</span>):
<span class="hljs-meta">... </span>    matches = []
<span class="hljs-meta">... </span>    start_indices = []
<span class="hljs-meta">... </span>    end_indices = []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> idx, i <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(<span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(words_list))):
<span class="hljs-meta">... </span>        <span class="hljs-keyword">if</span> words_list[i] == answer_list[<span class="hljs-number">0</span>] <span class="hljs-keyword">and</span> words_list[i : i + <span class="hljs-built_in">len</span>(answer_list)] == answer_list:
<span class="hljs-meta">... </span>            matches.append(answer_list)
<span class="hljs-meta">... </span>            start_indices.append(idx)
<span class="hljs-meta">... </span>            end_indices.append(idx + <span class="hljs-built_in">len</span>(answer_list) - <span class="hljs-number">1</span>)
<span class="hljs-meta">... </span>    <span class="hljs-keyword">if</span> matches:
<span class="hljs-meta">... </span>        <span class="hljs-keyword">return</span> matches[<span class="hljs-number">0</span>], start_indices[<span class="hljs-number">0</span>], end_indices[<span class="hljs-number">0</span>]
<span class="hljs-meta">... </span>    <span class="hljs-keyword">else</span>:
<span class="hljs-meta">... </span>        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>`}}),oe=new j({props:{code:`example = dataset_with_ocr["train"][1]
words = [word.lower() for word in example["words"]]
match, word_idx_start, word_idx_end = subfinder(words, example["answer"].lower().split())
print("Question: ", example["question"])
print("Words:", words)
print("Answer: ", example["answer"])
print("start_index", word_idx_start)
print("end_index", word_idx_end)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>example = dataset_with_ocr[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">1</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>words = [word.lower() <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> example[<span class="hljs-string">&quot;words&quot;</span>]]
<span class="hljs-meta">&gt;&gt;&gt; </span>match, word_idx_start, word_idx_end = subfinder(words, example[<span class="hljs-string">&quot;answer&quot;</span>].lower().split())
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Question: &quot;</span>, example[<span class="hljs-string">&quot;question&quot;</span>])
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Words:&quot;</span>, words)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Answer: &quot;</span>, example[<span class="hljs-string">&quot;answer&quot;</span>])
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;start_index&quot;</span>, word_idx_start)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;end_index&quot;</span>, word_idx_end)
Question:  Who <span class="hljs-keyword">is</span> <span class="hljs-keyword">in</span>  cc <span class="hljs-keyword">in</span> this letter?
Words: [<span class="hljs-string">&#x27;wie&#x27;</span>, <span class="hljs-string">&#x27;baw&#x27;</span>, <span class="hljs-string">&#x27;brown&#x27;</span>, <span class="hljs-string">&#x27;&amp;&#x27;</span>, <span class="hljs-string">&#x27;williamson&#x27;</span>, <span class="hljs-string">&#x27;tobacco&#x27;</span>, <span class="hljs-string">&#x27;corporation&#x27;</span>, <span class="hljs-string">&#x27;research&#x27;</span>, <span class="hljs-string">&#x27;&amp;&#x27;</span>, <span class="hljs-string">&#x27;development&#x27;</span>, <span class="hljs-string">&#x27;internal&#x27;</span>, <span class="hljs-string">&#x27;correspondence&#x27;</span>, <span class="hljs-string">&#x27;to:&#x27;</span>, <span class="hljs-string">&#x27;r.&#x27;</span>, <span class="hljs-string">&#x27;h.&#x27;</span>, <span class="hljs-string">&#x27;honeycutt&#x27;</span>, <span class="hljs-string">&#x27;ce:&#x27;</span>, <span class="hljs-string">&#x27;t.f.&#x27;</span>, <span class="hljs-string">&#x27;riehl&#x27;</span>, <span class="hljs-string">&#x27;from:&#x27;</span>, <span class="hljs-string">&#x27;.&#x27;</span>, <span class="hljs-string">&#x27;c.j.&#x27;</span>, <span class="hljs-string">&#x27;cook&#x27;</span>, <span class="hljs-string">&#x27;date:&#x27;</span>, <span class="hljs-string">&#x27;may&#x27;</span>, <span class="hljs-string">&#x27;8,&#x27;</span>, <span class="hljs-string">&#x27;1995&#x27;</span>, <span class="hljs-string">&#x27;subject:&#x27;</span>, <span class="hljs-string">&#x27;review&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;existing&#x27;</span>, <span class="hljs-string">&#x27;brainstorming&#x27;</span>, <span class="hljs-string">&#x27;ideas/483&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;major&#x27;</span>, <span class="hljs-string">&#x27;function&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;product&#x27;</span>, <span class="hljs-string">&#x27;innovation&#x27;</span>, <span class="hljs-string">&#x27;graup&#x27;</span>, <span class="hljs-string">&#x27;is&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;develop&#x27;</span>, <span class="hljs-string">&#x27;marketable&#x27;</span>, <span class="hljs-string">&#x27;nove!&#x27;</span>, <span class="hljs-string">&#x27;products&#x27;</span>, <span class="hljs-string">&#x27;that&#x27;</span>, <span class="hljs-string">&#x27;would&#x27;</span>, <span class="hljs-string">&#x27;be&#x27;</span>, <span class="hljs-string">&#x27;profitable&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;manufacture&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;sell.&#x27;</span>, <span class="hljs-string">&#x27;novel&#x27;</span>, <span class="hljs-string">&#x27;is&#x27;</span>, <span class="hljs-string">&#x27;defined&#x27;</span>, <span class="hljs-string">&#x27;as:&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;new&#x27;</span>, <span class="hljs-string">&#x27;kind,&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;different&#x27;</span>, <span class="hljs-string">&#x27;from&#x27;</span>, <span class="hljs-string">&#x27;anything&#x27;</span>, <span class="hljs-string">&#x27;seen&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;known&#x27;</span>, <span class="hljs-string">&#x27;before.&#x27;</span>, <span class="hljs-string">&#x27;innovation&#x27;</span>, <span class="hljs-string">&#x27;is&#x27;</span>, <span class="hljs-string">&#x27;defined&#x27;</span>, <span class="hljs-string">&#x27;as:&#x27;</span>, <span class="hljs-string">&#x27;something&#x27;</span>, <span class="hljs-string">&#x27;new&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;different&#x27;</span>, <span class="hljs-string">&#x27;introduced;&#x27;</span>, <span class="hljs-string">&#x27;act&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;innovating;&#x27;</span>, <span class="hljs-string">&#x27;introduction&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;new&#x27;</span>, <span class="hljs-string">&#x27;things&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;methods.&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;products&#x27;</span>, <span class="hljs-string">&#x27;may&#x27;</span>, <span class="hljs-string">&#x27;incorporate&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;latest&#x27;</span>, <span class="hljs-string">&#x27;technologies,&#x27;</span>, <span class="hljs-string">&#x27;materials&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;know-how&#x27;</span>, <span class="hljs-string">&#x27;available&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;give&#x27;</span>, <span class="hljs-string">&#x27;then&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;unique&#x27;</span>, <span class="hljs-string">&#x27;taste&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;look.&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;first&#x27;</span>, <span class="hljs-string">&#x27;task&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;product&#x27;</span>, <span class="hljs-string">&#x27;innovation&#x27;</span>, <span class="hljs-string">&#x27;group&#x27;</span>, <span class="hljs-string">&#x27;was&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;assemble,&#x27;</span>, <span class="hljs-string">&#x27;review&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;categorize&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;list&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;existing&#x27;</span>, <span class="hljs-string">&#x27;brainstorming&#x27;</span>, <span class="hljs-string">&#x27;ideas.&#x27;</span>, <span class="hljs-string">&#x27;ideas&#x27;</span>, <span class="hljs-string">&#x27;were&#x27;</span>, <span class="hljs-string">&#x27;grouped&#x27;</span>, <span class="hljs-string">&#x27;into&#x27;</span>, <span class="hljs-string">&#x27;two&#x27;</span>, <span class="hljs-string">&#x27;major&#x27;</span>, <span class="hljs-string">&#x27;categories&#x27;</span>, <span class="hljs-string">&#x27;labeled&#x27;</span>, <span class="hljs-string">&#x27;appearance&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;taste/aroma.&#x27;</span>, <span class="hljs-string">&#x27;these&#x27;</span>, <span class="hljs-string">&#x27;categories&#x27;</span>, <span class="hljs-string">&#x27;are&#x27;</span>, <span class="hljs-string">&#x27;used&#x27;</span>, <span class="hljs-string">&#x27;for&#x27;</span>, <span class="hljs-string">&#x27;novel&#x27;</span>, <span class="hljs-string">&#x27;products&#x27;</span>, <span class="hljs-string">&#x27;that&#x27;</span>, <span class="hljs-string">&#x27;may&#x27;</span>, <span class="hljs-string">&#x27;differ&#x27;</span>, <span class="hljs-string">&#x27;from&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;visual&#x27;</span>, <span class="hljs-string">&#x27;and/or&#x27;</span>, <span class="hljs-string">&#x27;taste/aroma&#x27;</span>, <span class="hljs-string">&#x27;point&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;view&#x27;</span>, <span class="hljs-string">&#x27;compared&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;canventional&#x27;</span>, <span class="hljs-string">&#x27;cigarettes.&#x27;</span>, <span class="hljs-string">&#x27;other&#x27;</span>, <span class="hljs-string">&#x27;categories&#x27;</span>, <span class="hljs-string">&#x27;include&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;combination&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;the&#x27;</span>, <span class="hljs-string">&#x27;above,&#x27;</span>, <span class="hljs-string">&#x27;filters,&#x27;</span>, <span class="hljs-string">&#x27;packaging&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;brand&#x27;</span>, <span class="hljs-string">&#x27;extensions.&#x27;</span>, <span class="hljs-string">&#x27;appearance&#x27;</span>, <span class="hljs-string">&#x27;this&#x27;</span>, <span class="hljs-string">&#x27;category&#x27;</span>, <span class="hljs-string">&#x27;is&#x27;</span>, <span class="hljs-string">&#x27;used&#x27;</span>, <span class="hljs-string">&#x27;for&#x27;</span>, <span class="hljs-string">&#x27;novel&#x27;</span>, <span class="hljs-string">&#x27;cigarette&#x27;</span>, <span class="hljs-string">&#x27;constructions&#x27;</span>, <span class="hljs-string">&#x27;that&#x27;</span>, <span class="hljs-string">&#x27;yield&#x27;</span>, <span class="hljs-string">&#x27;visually&#x27;</span>, <span class="hljs-string">&#x27;different&#x27;</span>, <span class="hljs-string">&#x27;products&#x27;</span>, <span class="hljs-string">&#x27;with&#x27;</span>, <span class="hljs-string">&#x27;minimal&#x27;</span>, <span class="hljs-string">&#x27;changes&#x27;</span>, <span class="hljs-string">&#x27;in&#x27;</span>, <span class="hljs-string">&#x27;smoke&#x27;</span>, <span class="hljs-string">&#x27;chemistry&#x27;</span>, <span class="hljs-string">&#x27;two&#x27;</span>, <span class="hljs-string">&#x27;cigarettes&#x27;</span>, <span class="hljs-string">&#x27;in&#x27;</span>, <span class="hljs-string">&#x27;cne.&#x27;</span>, <span class="hljs-string">&#x27;emulti-plug&#x27;</span>, <span class="hljs-string">&#x27;te&#x27;</span>, <span class="hljs-string">&#x27;build&#x27;</span>, <span class="hljs-string">&#x27;yaur&#x27;</span>, <span class="hljs-string">&#x27;awn&#x27;</span>, <span class="hljs-string">&#x27;cigarette.&#x27;</span>, <span class="hljs-string">&#x27;eswitchable&#x27;</span>, <span class="hljs-string">&#x27;menthol&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;non&#x27;</span>, <span class="hljs-string">&#x27;menthol&#x27;</span>, <span class="hljs-string">&#x27;cigarette.&#x27;</span>, <span class="hljs-string">&#x27;*cigarettes&#x27;</span>, <span class="hljs-string">&#x27;with&#x27;</span>, <span class="hljs-string">&#x27;interspaced&#x27;</span>, <span class="hljs-string">&#x27;perforations&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;enable&#x27;</span>, <span class="hljs-string">&#x27;smoker&#x27;</span>, <span class="hljs-string">&#x27;to&#x27;</span>, <span class="hljs-string">&#x27;separate&#x27;</span>, <span class="hljs-string">&#x27;unburned&#x27;</span>, <span class="hljs-string">&#x27;section&#x27;</span>, <span class="hljs-string">&#x27;for&#x27;</span>, <span class="hljs-string">&#x27;future&#x27;</span>, <span class="hljs-string">&#x27;smoking.&#x27;</span>, <span class="hljs-string">&#x27;\xABshort&#x27;</span>, <span class="hljs-string">&#x27;cigarette,&#x27;</span>, <span class="hljs-string">&#x27;tobacco&#x27;</span>, <span class="hljs-string">&#x27;section&#x27;</span>, <span class="hljs-string">&#x27;30&#x27;</span>, <span class="hljs-string">&#x27;mm.&#x27;</span>, <span class="hljs-string">&#x27;\xABextremely&#x27;</span>, <span class="hljs-string">&#x27;fast&#x27;</span>, <span class="hljs-string">&#x27;buming&#x27;</span>, <span class="hljs-string">&#x27;cigarette.&#x27;</span>, <span class="hljs-string">&#x27;\xABnovel&#x27;</span>, <span class="hljs-string">&#x27;cigarette&#x27;</span>, <span class="hljs-string">&#x27;constructions&#x27;</span>, <span class="hljs-string">&#x27;that&#x27;</span>, <span class="hljs-string">&#x27;permit&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;significant&#x27;</span>, <span class="hljs-string">&#x27;reduction&#x27;</span>, <span class="hljs-string">&#x27;iretobacco&#x27;</span>, <span class="hljs-string">&#x27;weight&#x27;</span>, <span class="hljs-string">&#x27;while&#x27;</span>, <span class="hljs-string">&#x27;maintaining&#x27;</span>, <span class="hljs-string">&#x27;smoking&#x27;</span>, <span class="hljs-string">&#x27;mechanics&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;visual&#x27;</span>, <span class="hljs-string">&#x27;characteristics.&#x27;</span>, <span class="hljs-string">&#x27;higher&#x27;</span>, <span class="hljs-string">&#x27;basis&#x27;</span>, <span class="hljs-string">&#x27;weight&#x27;</span>, <span class="hljs-string">&#x27;paper:&#x27;</span>, <span class="hljs-string">&#x27;potential&#x27;</span>, <span class="hljs-string">&#x27;reduction&#x27;</span>, <span class="hljs-string">&#x27;in&#x27;</span>, <span class="hljs-string">&#x27;tobacco&#x27;</span>, <span class="hljs-string">&#x27;weight.&#x27;</span>, <span class="hljs-string">&#x27;\xABmore&#x27;</span>, <span class="hljs-string">&#x27;rigid&#x27;</span>, <span class="hljs-string">&#x27;tobacco&#x27;</span>, <span class="hljs-string">&#x27;column;&#x27;</span>, <span class="hljs-string">&#x27;stiffing&#x27;</span>, <span class="hljs-string">&#x27;agent&#x27;</span>, <span class="hljs-string">&#x27;for&#x27;</span>, <span class="hljs-string">&#x27;tobacco;&#x27;</span>, <span class="hljs-string">&#x27;e.g.&#x27;</span>, <span class="hljs-string">&#x27;starch&#x27;</span>, <span class="hljs-string">&#x27;*colored&#x27;</span>, <span class="hljs-string">&#x27;tow&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;cigarette&#x27;</span>, <span class="hljs-string">&#x27;papers;&#x27;</span>, <span class="hljs-string">&#x27;seasonal&#x27;</span>, <span class="hljs-string">&#x27;promotions,&#x27;</span>, <span class="hljs-string">&#x27;e.g.&#x27;</span>, <span class="hljs-string">&#x27;pastel&#x27;</span>, <span class="hljs-string">&#x27;colored&#x27;</span>, <span class="hljs-string">&#x27;cigarettes&#x27;</span>, <span class="hljs-string">&#x27;for&#x27;</span>, <span class="hljs-string">&#x27;easter&#x27;</span>, <span class="hljs-string">&#x27;or&#x27;</span>, <span class="hljs-string">&#x27;in&#x27;</span>, <span class="hljs-string">&#x27;an&#x27;</span>, <span class="hljs-string">&#x27;ebony&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;ivory&#x27;</span>, <span class="hljs-string">&#x27;brand&#x27;</span>, <span class="hljs-string">&#x27;containing&#x27;</span>, <span class="hljs-string">&#x27;a&#x27;</span>, <span class="hljs-string">&#x27;mixture&#x27;</span>, <span class="hljs-string">&#x27;of&#x27;</span>, <span class="hljs-string">&#x27;all&#x27;</span>, <span class="hljs-string">&#x27;black&#x27;</span>, <span class="hljs-string">&#x27;(black&#x27;</span>, <span class="hljs-string">&#x27;paper&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;tow)&#x27;</span>, <span class="hljs-string">&#x27;and&#x27;</span>, <span class="hljs-string">&#x27;ail&#x27;</span>, <span class="hljs-string">&#x27;white&#x27;</span>, <span class="hljs-string">&#x27;cigarettes.&#x27;</span>, <span class="hljs-string">&#x27;499150498&#x27;</span>]
Answer:  T.F. Riehl
start_index <span class="hljs-number">17</span>
end_index <span class="hljs-number">18</span>`}}),ie=new j({props:{code:`encoding = tokenizer(example["question"], example["words"], example["boxes"])
tokenizer.decode(encoding["input_ids"])`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>encoding = tokenizer(example[<span class="hljs-string">&quot;question&quot;</span>], example[<span class="hljs-string">&quot;words&quot;</span>], example[<span class="hljs-string">&quot;boxes&quot;</span>])
<span class="hljs-meta">&gt;&gt;&gt; </span>tokenizer.decode(encoding[<span class="hljs-string">&quot;input_ids&quot;</span>])
[CLS] who <span class="hljs-keyword">is</span> <span class="hljs-keyword">in</span> cc <span class="hljs-keyword">in</span> this letter? [SEP] wie baw brown &amp; williamson tobacco corporation research &amp; development ...`}}),re=new j({props:{code:`def encode_dataset(examples, max_length=512):
    questions = examples["question"]
    words = examples["words"]
    boxes = examples["boxes"]
    answers = examples["answer"]

    # encode the batch of examples and initialize the start_positions and end_positions
    encoding = tokenizer(questions, words, boxes, max_length=max_length, padding="max_length", truncation=True)
    start_positions = []
    end_positions = []

    # loop through the examples in the batch
    for i in range(len(questions)):
        cls_index = encoding["input_ids"][i].index(tokenizer.cls_token_id)

        # find the position of the answer in example's words
        words_example = [word.lower() for word in words[i]]
        answer = answers[i]
        match, word_idx_start, word_idx_end = subfinder(words_example, answer.lower().split())

        if match:
            # if match is found, use \`token_type_ids\` to find where words start in the encoding
            token_type_ids = encoding["token_type_ids"][i]
            token_start_index = 0
            while token_type_ids[token_start_index] != 1:
                token_start_index += 1

            token_end_index = len(encoding["input_ids"][i]) - 1
            while token_type_ids[token_end_index] != 1:
                token_end_index -= 1

            word_ids = encoding.word_ids(i)[token_start_index : token_end_index + 1]
            start_position = cls_index
            end_position = cls_index

            # loop over word_ids and increase \`token_start_index\` until it matches the answer position in words
            # once it matches, save the \`token_start_index\` as the \`start_position\` of the answer in the encoding
            for id in word_ids:
                if id == word_idx_start:
                    start_position = token_start_index
                else:
                    token_start_index += 1

            # similarly loop over \`word_ids\` starting from the end to find the \`end_position\` of the answer
            for id in word_ids[::-1]:
                if id == word_idx_end:
                    end_position = token_end_index
                else:
                    token_end_index -= 1

            start_positions.append(start_position)
            end_positions.append(end_position)

        else:
            start_positions.append(cls_index)
            end_positions.append(cls_index)

    encoding["image"] = examples["image"]
    encoding["start_positions"] = start_positions
    encoding["end_positions"] = end_positions

    return encoding`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">encode_dataset</span>(<span class="hljs-params">examples, max_length=<span class="hljs-number">512</span></span>):
<span class="hljs-meta">... </span>    questions = examples[<span class="hljs-string">&quot;question&quot;</span>]
<span class="hljs-meta">... </span>    words = examples[<span class="hljs-string">&quot;words&quot;</span>]
<span class="hljs-meta">... </span>    boxes = examples[<span class="hljs-string">&quot;boxes&quot;</span>]
<span class="hljs-meta">... </span>    answers = examples[<span class="hljs-string">&quot;answer&quot;</span>]

<span class="hljs-meta">... </span>    <span class="hljs-comment"># encode the batch of examples and initialize the start_positions and end_positions</span>
<span class="hljs-meta">... </span>    encoding = tokenizer(questions, words, boxes, max_length=max_length, padding=<span class="hljs-string">&quot;max_length&quot;</span>, truncation=<span class="hljs-literal">True</span>)
<span class="hljs-meta">... </span>    start_positions = []
<span class="hljs-meta">... </span>    end_positions = []

<span class="hljs-meta">... </span>    <span class="hljs-comment"># loop through the examples in the batch</span>
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(questions)):
<span class="hljs-meta">... </span>        cls_index = encoding[<span class="hljs-string">&quot;input_ids&quot;</span>][i].index(tokenizer.cls_token_id)

<span class="hljs-meta">... </span>        <span class="hljs-comment"># find the position of the answer in example&#x27;s words</span>
<span class="hljs-meta">... </span>        words_example = [word.lower() <span class="hljs-keyword">for</span> word <span class="hljs-keyword">in</span> words[i]]
<span class="hljs-meta">... </span>        answer = answers[i]
<span class="hljs-meta">... </span>        match, word_idx_start, word_idx_end = subfinder(words_example, answer.lower().split())

<span class="hljs-meta">... </span>        <span class="hljs-keyword">if</span> match:
<span class="hljs-meta">... </span>            <span class="hljs-comment"># if match is found, use \`token_type_ids\` to find where words start in the encoding</span>
<span class="hljs-meta">... </span>            token_type_ids = encoding[<span class="hljs-string">&quot;token_type_ids&quot;</span>][i]
<span class="hljs-meta">... </span>            token_start_index = <span class="hljs-number">0</span>
<span class="hljs-meta">... </span>            <span class="hljs-keyword">while</span> token_type_ids[token_start_index] != <span class="hljs-number">1</span>:
<span class="hljs-meta">... </span>                token_start_index += <span class="hljs-number">1</span>

<span class="hljs-meta">... </span>            token_end_index = <span class="hljs-built_in">len</span>(encoding[<span class="hljs-string">&quot;input_ids&quot;</span>][i]) - <span class="hljs-number">1</span>
<span class="hljs-meta">... </span>            <span class="hljs-keyword">while</span> token_type_ids[token_end_index] != <span class="hljs-number">1</span>:
<span class="hljs-meta">... </span>                token_end_index -= <span class="hljs-number">1</span>

<span class="hljs-meta">... </span>            word_ids = encoding.word_ids(i)[token_start_index : token_end_index + <span class="hljs-number">1</span>]
<span class="hljs-meta">... </span>            start_position = cls_index
<span class="hljs-meta">... </span>            end_position = cls_index

<span class="hljs-meta">... </span>            <span class="hljs-comment"># loop over word_ids and increase \`token_start_index\` until it matches the answer position in words</span>
<span class="hljs-meta">... </span>            <span class="hljs-comment"># once it matches, save the \`token_start_index\` as the \`start_position\` of the answer in the encoding</span>
<span class="hljs-meta">... </span>            <span class="hljs-keyword">for</span> <span class="hljs-built_in">id</span> <span class="hljs-keyword">in</span> word_ids:
<span class="hljs-meta">... </span>                <span class="hljs-keyword">if</span> <span class="hljs-built_in">id</span> == word_idx_start:
<span class="hljs-meta">... </span>                    start_position = token_start_index
<span class="hljs-meta">... </span>                <span class="hljs-keyword">else</span>:
<span class="hljs-meta">... </span>                    token_start_index += <span class="hljs-number">1</span>

<span class="hljs-meta">... </span>            <span class="hljs-comment"># similarly loop over \`word_ids\` starting from the end to find the \`end_position\` of the answer</span>
<span class="hljs-meta">... </span>            <span class="hljs-keyword">for</span> <span class="hljs-built_in">id</span> <span class="hljs-keyword">in</span> word_ids[::-<span class="hljs-number">1</span>]:
<span class="hljs-meta">... </span>                <span class="hljs-keyword">if</span> <span class="hljs-built_in">id</span> == word_idx_end:
<span class="hljs-meta">... </span>                    end_position = token_end_index
<span class="hljs-meta">... </span>                <span class="hljs-keyword">else</span>:
<span class="hljs-meta">... </span>                    token_end_index -= <span class="hljs-number">1</span>

<span class="hljs-meta">... </span>            start_positions.append(start_position)
<span class="hljs-meta">... </span>            end_positions.append(end_position)

<span class="hljs-meta">... </span>        <span class="hljs-keyword">else</span>:
<span class="hljs-meta">... </span>            start_positions.append(cls_index)
<span class="hljs-meta">... </span>            end_positions.append(cls_index)

<span class="hljs-meta">... </span>    encoding[<span class="hljs-string">&quot;image&quot;</span>] = examples[<span class="hljs-string">&quot;image&quot;</span>]
<span class="hljs-meta">... </span>    encoding[<span class="hljs-string">&quot;start_positions&quot;</span>] = start_positions
<span class="hljs-meta">... </span>    encoding[<span class="hljs-string">&quot;end_positions&quot;</span>] = end_positions

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> encoding`}}),pe=new j({props:{code:`encoded_train_dataset = dataset_with_ocr["train"].map(
    encode_dataset, batched=True, batch_size=2, remove_columns=dataset_with_ocr["train"].column_names
)
encoded_test_dataset = dataset_with_ocr["test"].map(
    encode_dataset, batched=True, batch_size=2, remove_columns=dataset_with_ocr["test"].column_names
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>encoded_train_dataset = dataset_with_ocr[<span class="hljs-string">&quot;train&quot;</span>].<span class="hljs-built_in">map</span>(
<span class="hljs-meta">... </span>    encode_dataset, batched=<span class="hljs-literal">True</span>, batch_size=<span class="hljs-number">2</span>, remove_columns=dataset_with_ocr[<span class="hljs-string">&quot;train&quot;</span>].column_names
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>encoded_test_dataset = dataset_with_ocr[<span class="hljs-string">&quot;test&quot;</span>].<span class="hljs-built_in">map</span>(
<span class="hljs-meta">... </span>    encode_dataset, batched=<span class="hljs-literal">True</span>, batch_size=<span class="hljs-number">2</span>, remove_columns=dataset_with_ocr[<span class="hljs-string">&quot;test&quot;</span>].column_names
<span class="hljs-meta">... </span>)`}}),he=new j({props:{code:"encoded_train_dataset.features",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>encoded_train_dataset.features
{<span class="hljs-string">&#x27;image&#x27;</span>: <span class="hljs-type">Sequence</span>(feature=<span class="hljs-type">Sequence</span>(feature=<span class="hljs-type">Sequence</span>(feature=Value(dtype=<span class="hljs-string">&#x27;uint8&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>),
 <span class="hljs-string">&#x27;input_ids&#x27;</span>: <span class="hljs-type">Sequence</span>(feature=Value(dtype=<span class="hljs-string">&#x27;int32&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>),
 <span class="hljs-string">&#x27;token_type_ids&#x27;</span>: <span class="hljs-type">Sequence</span>(feature=Value(dtype=<span class="hljs-string">&#x27;int8&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>),
 <span class="hljs-string">&#x27;attention_mask&#x27;</span>: <span class="hljs-type">Sequence</span>(feature=Value(dtype=<span class="hljs-string">&#x27;int8&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>),
 <span class="hljs-string">&#x27;bbox&#x27;</span>: <span class="hljs-type">Sequence</span>(feature=<span class="hljs-type">Sequence</span>(feature=Value(dtype=<span class="hljs-string">&#x27;int64&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>), length=-<span class="hljs-number">1</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>),
 <span class="hljs-string">&#x27;start_positions&#x27;</span>: Value(dtype=<span class="hljs-string">&#x27;int64&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>),
 <span class="hljs-string">&#x27;end_positions&#x27;</span>: Value(dtype=<span class="hljs-string">&#x27;int64&#x27;</span>, <span class="hljs-built_in">id</span>=<span class="hljs-literal">None</span>)}`}}),ce=new Ts({}),ue=new Ts({}),je=new j({props:{code:`from transformers import AutoModelForDocumentQuestionAnswering

model = AutoModelForDocumentQuestionAnswering.from_pretrained(model_checkpoint)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForDocumentQuestionAnswering

<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForDocumentQuestionAnswering.from_pretrained(model_checkpoint)`}}),we=new j({props:{code:`from transformers import TrainingArguments

# REPLACE THIS WITH YOUR REPO ID
repo_id = "MariaK/layoutlmv2-base-uncased_finetuned_docvqa"

training_args = TrainingArguments(
    output_dir=repo_id,
    per_device_train_batch_size=4,
    num_train_epochs=20,
    save_steps=200,
    logging_steps=50,
    evaluation_strategy="steps",
    learning_rate=5e-5,
    save_total_limit=2,
    remove_unused_columns=False,
    push_to_hub=True,
)`,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><span class="hljs-comment"># REPLACE THIS WITH YOUR REPO ID</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>repo_id = <span class="hljs-string">&quot;MariaK/layoutlmv2-base-uncased_finetuned_docvqa&quot;</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>training_args = TrainingArguments(
<span class="hljs-meta">... </span>    output_dir=repo_id,
<span class="hljs-meta">... </span>    per_device_train_batch_size=<span class="hljs-number">4</span>,
<span class="hljs-meta">... </span>    num_train_epochs=<span class="hljs-number">20</span>,
<span class="hljs-meta">... </span>    save_steps=<span class="hljs-number">200</span>,
<span class="hljs-meta">... </span>    logging_steps=<span class="hljs-number">50</span>,
<span class="hljs-meta">... </span>    evaluation_strategy=<span class="hljs-string">&quot;steps&quot;</span>,
<span class="hljs-meta">... </span>    learning_rate=<span class="hljs-number">5e-5</span>,
<span class="hljs-meta">... </span>    save_total_limit=<span class="hljs-number">2</span>,
<span class="hljs-meta">... </span>    remove_unused_columns=<span class="hljs-literal">False</span>,
<span class="hljs-meta">... </span>    push_to_hub=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span>)`}}),ve=new j({props:{code:`from transformers import DefaultDataCollator

data_collator = DefaultDataCollator()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> DefaultDataCollator

<span class="hljs-meta">&gt;&gt;&gt; </span>data_collator = DefaultDataCollator()`}}),be=new j({props:{code:`from transformers import Trainer

trainer = Trainer(
    model=model,
    args=training_args,
    data_collator=data_collator,
    train_dataset=encoded_train_dataset,
    eval_dataset=encoded_test_dataset,
    tokenizer=processor,
)

trainer.train()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> Trainer

<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>    data_collator=data_collator,
<span class="hljs-meta">... </span>    train_dataset=encoded_train_dataset,
<span class="hljs-meta">... </span>    eval_dataset=encoded_test_dataset,
<span class="hljs-meta">... </span>    tokenizer=processor,
<span class="hljs-meta">... </span>)

<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.train()`}}),ye=new j({props:{code:`trainer.create_model_card()
trainer.push_to_hub()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.create_model_card()
<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.push_to_hub()`}}),ke=new Ts({}),$e=new j({props:{code:`example = dataset["test"][2]
question = example["query"]["en"]
image = example["image"]
print(question)
print(example["answers"])`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>example = dataset[<span class="hljs-string">&quot;test&quot;</span>][<span class="hljs-number">2</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>question = example[<span class="hljs-string">&quot;query&quot;</span>][<span class="hljs-string">&quot;en&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>image = example[<span class="hljs-string">&quot;image&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(question)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(example[<span class="hljs-string">&quot;answers&quot;</span>])
<span class="hljs-string">&#x27;Who is \u2018presiding\u2019 TRRF GENERAL SESSION (PART 1)?&#x27;</span>
[<span class="hljs-string">&#x27;TRRF Vice President&#x27;</span>, <span class="hljs-string">&#x27;lee a. waller&#x27;</span>]`}}),qe=new j({props:{code:`from transformers import pipeline

qa_pipeline = pipeline("document-question-answering", model="MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
qa_pipeline(image, question)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline

<span class="hljs-meta">&gt;&gt;&gt; </span>qa_pipeline = pipeline(<span class="hljs-string">&quot;document-question-answering&quot;</span>, model=<span class="hljs-string">&quot;MariaK/layoutlmv2-base-uncased_finetuned_docvqa&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>qa_pipeline(image, question)
[{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.9949808120727539</span>,
  <span class="hljs-string">&#x27;answer&#x27;</span>: <span class="hljs-string">&#x27;Lee A. Waller&#x27;</span>,
  <span class="hljs-string">&#x27;start&#x27;</span>: <span class="hljs-number">55</span>,
  <span class="hljs-string">&#x27;end&#x27;</span>: <span class="hljs-number">57</span>}]`}}),Ee=new j({props:{code:`import torch
from transformers import AutoProcessor
from transformers import AutoModelForDocumentQuestionAnswering

processor = AutoProcessor.from_pretrained("MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
model = AutoModelForDocumentQuestionAnswering.from_pretrained("MariaK/layoutlmv2-base-uncased_finetuned_docvqa")

with torch.no_grad():
    encoding = processor(image.convert("RGB"), question, return_tensors="pt")
    outputs = model(**encoding)
    start_logits = outputs.start_logits
    end_logits = outputs.end_logits
    predicted_start_idx = start_logits.argmax(-1).item()
    predicted_end_idx = end_logits.argmax(-1).item()

processor.tokenizer.decode(encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1])`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForDocumentQuestionAnswering

<span class="hljs-meta">&gt;&gt;&gt; </span>processor = AutoProcessor.from_pretrained(<span class="hljs-string">&quot;MariaK/layoutlmv2-base-uncased_finetuned_docvqa&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForDocumentQuestionAnswering.from_pretrained(<span class="hljs-string">&quot;MariaK/layoutlmv2-base-uncased_finetuned_docvqa&quot;</span>)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> torch.no_grad():
<span class="hljs-meta">... </span>    encoding = processor(image.convert(<span class="hljs-string">&quot;RGB&quot;</span>), question, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-meta">... </span>    outputs = model(**encoding)
<span class="hljs-meta">... </span>    start_logits = outputs.start_logits
<span class="hljs-meta">... </span>    end_logits = outputs.end_logits
<span class="hljs-meta">... </span>    predicted_start_idx = start_logits.argmax(-<span class="hljs-number">1</span>).item()
<span class="hljs-meta">... </span>    predicted_end_idx = end_logits.argmax(-<span class="hljs-number">1</span>).item()

<span class="hljs-meta">&gt;&gt;&gt; </span>processor.tokenizer.decode(encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + <span class="hljs-number">1</span>])
<span class="hljs-string">&#x27;lee a. waller&#x27;</span>`}}),{c(){k=o("meta"),is=h(),A=o("h1"),v=o("a"),C=o("span"),u(Q.$$.fragment),Ls=h(),O=o("span"),Ps=t("Document Question Answering"),rs=h(),u(D.$$.fragment),ps=h(),b=o("p"),S=t(`Document Question Answering, also referred to as Document Visual Question Answering, is a task that involves providing
answers to questions posed about document images. The input to models supporting this task is typically a combination of an image and
a question, and the output is an answer expressed in natural language. These models utilize multiple modalities, including
text, the positions of words (bounding boxes), and the image itself.`),R=h(),Y=o("p"),De=t("This guide illustrates how to:"),Cs=h(),hs=o("ul"),J=o("li"),$l=t("Fine-tune "),Te=o("a"),ql=t("LayoutLMv2"),El=t(" on the "),Os=o("a"),Al=t("DocVQA dataset"),Dl=t("."),Tl=h(),ba=o("li"),Ll=t("Use your fine-tuned model for inference."),Ct=h(),u(cs.$$.fragment),Ot=h(),Le=o("p"),Pl=t(`LayoutLMv2 solves the document question-answering task by adding a question-answering head on top of the final hidden
states of the tokens, to predict the positions of the start and end tokens of the
answer. In other words, the problem is treated as extractive question answering: given the context, extract which piece
of information answers the question. The context comes from the output of an OCR engine, here it is Google\u2019s Tesseract.
states of the tokens, in order to predict which token is at the start of the answer and which token is at the end of the
answer. In other words, the problem is treated as extractive question answering: given the context, extract which piece
of information answers the question. The context comes from the output of an OCR engine, here it is Google\u2019s Tesseract.`),It=h(),Pe=o("p"),Cl=t("Before you begin, make sure you have all the necessary libraries installed. LayoutLMv2 depends on detectron2, torchvision and tesseract."),zt=h(),u(Is.$$.fragment),Mt=h(),u(zs.$$.fragment),Nt=h(),u(Ms.$$.fragment),Ft=h(),Ce=o("p"),Ol=t("Once you have installed all of the dependencies, restart your runtime."),Qt=h(),Oe=o("p"),Il=t(`We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the \u{1F917} Hub.
When prompted, enter your token to log in:`),Rt=h(),u(Ns.$$.fragment),St=h(),Ie=o("p"),zl=t("Let\u2019s define some global variables."),Ht=h(),u(Fs.$$.fragment),Wt=h(),X=o("h2"),ds=o("a"),ya=o("span"),u(Qs.$$.fragment),Ml=h(),ka=o("span"),Nl=t("Load the data"),Vt=h(),H=o("p"),Fl=t(`In this guide we use a small sample of preprocessed DocVQA that you can find on \u{1F917} Hub. If you\u2019d like to use the full
DocVQA dataset, you can register and download it on `),Rs=o("a"),Ql=t("DocVQA homepage"),Rl=t(`. If you do so, to
proceed with this guide check out `),Ss=o("a"),Sl=t("how to load files into a \u{1F917} dataset"),Hl=t("."),Bt=h(),u(Hs.$$.fragment),Gt=h(),ze=o("p"),Wl=t(`As you can see, the dataset is split into train and test sets already. Take a look at a random example to familiarize
yourself with the features.`),Ut=h(),u(Ws.$$.fragment),Kt=h(),Me=o("p"),Vl=t("Here\u2019s what the individual fields represent:"),Yt=h(),$=o("ul"),Ne=o("li"),$a=o("code"),Bl=t("id"),Gl=t(": the example\u2019s id"),Ul=h(),Fe=o("li"),qa=o("code"),Kl=t("image"),Yl=t(": a PIL.Image.Image object containing the document image"),Jl=h(),Qe=o("li"),Ea=o("code"),Xl=t("query"),Zl=t(": the question string - natural language asked question, in several languages"),so=h(),Re=o("li"),Aa=o("code"),eo=t("answers"),ao=t(": a list of correct answers provided by human annotators"),to=h(),us=o("li"),Da=o("code"),no=t("words"),lo=t(" and "),Ta=o("code"),oo=t("bounding_boxes"),io=t(": the results of OCR, which we will not use here"),ro=h(),Se=o("li"),La=o("code"),po=t("answer"),ho=t(": an answer matched by a different model which we will not use here"),Jt=h(),ms=o("p"),co=t("Let\u2019s leave only English questions, and drop the "),Pa=o("code"),uo=t("answer"),mo=t(` feature which appears to contain predictions by another model.
We\u2019ll also take the first of the answers from the set provided by the annotators. Alternatively, you can randomly sample it.`),Xt=h(),u(Vs.$$.fragment),Zt=h(),I=o("p"),go=t("Note that the LayoutLMv2 checkpoint that we use in this guide has been trained with "),Ca=o("code"),fo=t("max_position_embeddings = 512"),xo=t(` (you can
find this information in the `),Z=o("a"),_o=t("checkpoint\u2019s "),Oa=o("code"),jo=t("config.json"),wo=t(" file"),vo=t(`).
We can truncate the examples but to avoid the situation where the answer might be at the end of a large document and end up truncated,
here we\u2019ll remove the few examples where the embedding is likely to end up longer than 512.
If most of the documents in your dataset are long, you can implement a sliding window strategy - check out `),Bs=o("a"),bo=t("this notebook"),yo=t(" for details."),sn=h(),u(Gs.$$.fragment),en=h(),W=o("p"),ko=t(`At this point let\u2019s also remove the OCR features from this dataset. These are a result of OCR for fine-tuning a different
model. They would still require some processing if we wanted to use them, as they do not match the input requirements
of the model we use in this guide. Instead, we can use the `),He=o("a"),$o=t("LayoutLMv2Processor"),qo=t(` on the original data for both OCR and
tokenization. This way we\u2019ll get the inputs that match model\u2019s expected input. If you want to process images manually,
check out the `),Us=o("a"),Ia=o("code"),Eo=t("LayoutLMv2"),Ao=t(" model documentation"),Do=t(" to learn what input format the model expects."),an=h(),u(Ks.$$.fragment),tn=h(),We=o("p"),To=t("Finally, the data exploration won\u2019t be complete if we don\u2019t peek at an image example."),nn=h(),u(Ys.$$.fragment),ln=h(),Js=o("div"),Ve=o("img"),on=h(),ss=o("h2"),gs=o("a"),za=o("span"),u(Xs.$$.fragment),Lo=h(),Ma=o("span"),Po=t("Preprocess the data"),rn=h(),fs=o("p"),Co=t(`The Document Question Answering task is a multimodal task, and you need to make sure that the inputs from each modality
are preprocessed according to the model\u2019s expectations. Let\u2019s start by loading the `),Be=o("a"),Oo=t("LayoutLMv2Processor"),Io=t(", which internally combines an image processor that can handle image data and a tokenizer that can encode text data."),pn=h(),u(Zs.$$.fragment),hn=h(),es=o("h3"),xs=o("a"),Na=o("span"),u(se.$$.fragment),zo=h(),Fa=o("span"),Mo=t("Preprocessing document images"),cn=h(),_s=o("p"),No=t("First, let\u2019s prepare the document images for the model with the help of the "),Qa=o("code"),Fo=t("image_processor"),Qo=t(` from the processor.
By default, image processor resizes the images to 224x224, makes sure they have the correct order of color channels,
applies OCR with tesseract to get words and normalized bounding boxes. In this tutorial, all of these defaults are exactly what we need.
Write a function that applies the default image processing to a batch of images and returns the results of OCR.`),dn=h(),u(ee.$$.fragment),un=h(),js=o("p"),Ro=t("To apply this preprocessing to the entire dataset in a fast way, use "),Ra=o("code"),So=t("map"),Ho=t("."),mn=h(),u(ae.$$.fragment),gn=h(),as=o("h3"),ws=o("a"),Sa=o("span"),u(te.$$.fragment),Wo=h(),Ha=o("span"),Vo=t("Preprocessing text data"),fn=h(),q=o("p"),Bo=t(`Once we have applied OCR to the images, we need to encode the text part of the dataset to prepare it for the model.
This involves converting the words and boxes that we got in the previous step to token-level `),Wa=o("code"),Go=t("input_ids"),Uo=t(", "),Va=o("code"),Ko=t("attention_mask"),Yo=t(`,
`),Ba=o("code"),Jo=t("token_type_ids"),Xo=t(" and "),Ga=o("code"),Zo=t("bbox"),si=t(". For preprocessing text, we\u2019ll need the "),Ua=o("code"),ei=t("tokenizer"),ai=t(" from the processor."),xn=h(),u(ne.$$.fragment),_n=h(),z=o("p"),ti=t("On top of the preprocessing mentioned above, we also need to add the labels for the model. For "),Ka=o("code"),ni=t("xxxForQuestionAnswering"),li=t(` models
in \u{1F917} Transformers, the labels consist of the `),Ya=o("code"),oi=t("start_positions"),ii=t(" and "),Ja=o("code"),ri=t("end_positions"),pi=t(`, indicating which token is at the
start and which token is at the end of the answer.`),jn=h(),Ge=o("p"),hi=t("Let\u2019s start with that. Define a helper function that can find a sublist (the answer split into words) in a larger list (the words list)."),wn=h(),w=o("p"),ci=t("This function will take two lists as input, "),Xa=o("code"),di=t("words_list"),ui=t(" and "),Za=o("code"),mi=t("answer_list"),gi=t(". It will then iterate over the "),st=o("code"),fi=t("words_list"),xi=t(` and check
if the current word in the `),et=o("code"),_i=t("words_list"),ji=t(` (words_list[i]) is equal to the first word of answer_list (answer_list[0]) and if
the sublist of `),at=o("code"),wi=t("words_list"),vi=t(" starting from the current word and of the same length as "),tt=o("code"),bi=t("answer_list"),yi=t(" is equal "),nt=o("code"),ki=t("to answer_list"),$i=t(`.
If this condition is true, it means that a match has been found, and the function will record the match, its starting index (idx),
and its ending index (idx + len(answer_list) - 1). If more than one match was found, the function will return only the first one.
If no match is found, the function returns (`),lt=o("code"),qi=t("None"),Ei=t(", 0, and 0)."),vn=h(),u(le.$$.fragment),bn=h(),Ue=o("p"),Ai=t("To illustrate how this function finds the position of the answer, let\u2019s use it on an example:"),yn=h(),u(oe.$$.fragment),kn=h(),Ke=o("p"),Di=t("Once examples are encoded, however, they will look like this:"),$n=h(),u(ie.$$.fragment),qn=h(),Ye=o("p"),Ti=t("We\u2019ll need to find the position of the answer in the encoded input."),En=h(),V=o("ul"),Je=o("li"),ot=o("code"),Li=t("token_type_ids"),Pi=t(" tells us which tokens are part of the question, and which ones are part of the document\u2019s words."),Ci=h(),Xe=o("li"),it=o("code"),Oi=t("tokenizer.cls_token_id"),Ii=t(" will help find the special token at the beginning of the input."),zi=h(),vs=o("li"),rt=o("code"),Mi=t("word_ids"),Ni=t(" will help match the answer found in the original "),pt=o("code"),Fi=t("words"),Qi=t(` to the same answer in the full encoded input and determine
the start/end position of the answer in the encoded input.`),An=h(),Ze=o("p"),Ri=t("With that in mind, let\u2019s create a function to encode a batch of examples in the dataset:"),Dn=h(),u(re.$$.fragment),Tn=h(),sa=o("p"),Si=t("Now that we have this preprocessing function, we can encode the entire dataset:"),Ln=h(),u(pe.$$.fragment),Pn=h(),ea=o("p"),Hi=t("Let\u2019s check what the features of the encoded dataset look like:"),Cn=h(),u(he.$$.fragment),On=h(),ts=o("h2"),bs=o("a"),ht=o("span"),u(ce.$$.fragment),Wi=h(),ct=o("span"),Vi=t("Evaluation"),In=h(),B=o("p"),Bi=t(`Evaluation for document question answering requires a significant amount of postprocessing. To avoid taking up too much
of your time, this guide skips the evaluation step. The `),aa=o("a"),Gi=t("Trainer"),Ui=t(` still calculates the evaluation loss during training so
you\u2019re not completely in the dark about your model\u2019s performance. Extractive question answering is typically evaluated using F1/exact match.
If you\u2019d like to implement it yourself, check out the `),de=o("a"),Ki=t("Question Answering chapter"),Yi=t(`
of the Hugging Face course for inspiration.`),zn=h(),ns=o("h2"),ys=o("a"),dt=o("span"),u(ue.$$.fragment),Ji=h(),ut=o("span"),Xi=t("Train"),Mn=h(),ta=o("p"),Zi=t(`Congratulations! You\u2019ve successfully navigated the toughest part of this guide and now you are ready to train your own model.
Training involves the following steps:`),Nn=h(),T=o("ul"),me=o("li"),sr=t("Load the model with "),na=o("a"),er=t("AutoModelForDocumentQuestionAnswering"),ar=t(" using the same checkpoint as in the preprocessing."),tr=h(),ge=o("li"),nr=t("Define your training hyperparameters in "),la=o("a"),lr=t("TrainingArguments"),or=t("."),ir=h(),fe=o("li"),rr=t("Define a function to batch examples together, here the "),oa=o("a"),pr=t("DefaultDataCollator"),hr=t(" will do just fine"),cr=h(),xe=o("li"),dr=t("Pass the training arguments to "),ia=o("a"),ur=t("Trainer"),mr=t(" along with the model, dataset, and data collator."),gr=h(),_e=o("li"),fr=t("Call "),ra=o("a"),xr=t("train()"),_r=t(" to finetune your model."),Fn=h(),u(je.$$.fragment),Qn=h(),E=o("p"),jr=t("In the "),pa=o("a"),wr=t("TrainingArguments"),vr=t(" use "),mt=o("code"),br=t("output_dir"),yr=t(` to specify where to save your model, and configure hyperparameters as you see fit.
If you wish to share your model with the community, set `),gt=o("code"),kr=t("push_to_hub"),$r=t(" to "),ft=o("code"),qr=t("True"),Er=t(` (you must be signed in to Hugging Face to upload your model).
In this case the `),xt=o("code"),Ar=t("output_dir"),Dr=t(" will also be the name of the repo where your model checkpoint will be pushed."),Rn=h(),u(we.$$.fragment),Sn=h(),ha=o("p"),Tr=t("Define a simple data collator to batch examples together."),Hn=h(),u(ve.$$.fragment),Wn=h(),ks=o("p"),Lr=t("Finally, bring everything together, and call "),ca=o("a"),Pr=t("train()"),Cr=t(":"),Vn=h(),u(be.$$.fragment),Bn=h(),$s=o("p"),Or=t("To add the final model to \u{1F917} Hub, create a model card and call "),_t=o("code"),Ir=t("push_to_hub"),zr=t(":"),Gn=h(),u(ye.$$.fragment),Un=h(),ls=o("h2"),qs=o("a"),jt=o("span"),u(ke.$$.fragment),Mr=h(),wt=o("span"),Nr=t("Inference"),Kn=h(),Es=o("p"),Fr=t(`Now that you have finetuned a LayoutLMv2 model, and uploaded it to the \u{1F917} Hub, you can use it for inference. The simplest
way to try out your finetuned model for inference is to use it in a `),da=o("a"),Qr=t("Pipeline"),Rr=t("."),Yn=h(),ua=o("p"),Sr=t("Let\u2019s take an example:"),Jn=h(),u($e.$$.fragment),Xn=h(),ma=o("p"),Hr=t(`Next, instantiate a pipeline for
document question answering with your model, and pass the image + question combination to it.`),Zn=h(),u(qe.$$.fragment),sl=h(),ga=o("p"),Wr=t("You can also manually replicate the results of the pipeline if you\u2019d like:"),el=h(),L=o("ol"),vt=o("li"),Vr=t("Take an image and a question, prepare them for the model using the processor from your model."),Br=h(),bt=o("li"),Gr=t("Forward the result or preprocessing through the model."),Ur=h(),os=o("li"),Kr=t("The model returns "),yt=o("code"),Yr=t("start_logits"),Jr=t(" and "),kt=o("code"),Xr=t("end_logits"),Zr=t(`, which indicate which token is at the start of the answer and
which token is at the end of the answer. Both have shape (batch_size, sequence_length).`),sp=h(),P=o("li"),ep=t("Take an argmax on the last dimension of both the "),$t=o("code"),ap=t("start_logits"),tp=t(" and "),qt=o("code"),np=t("end_logits"),lp=t(" to get the predicted "),Et=o("code"),op=t("start_idx"),ip=t(" and "),At=o("code"),rp=t("end_idx"),pp=t("."),hp=h(),Dt=o("li"),cp=t("Decode the answer with the tokenizer."),al=h(),u(Ee.$$.fragment),this.h()},l(s){const l=Ac('[data-svelte="svelte-1phssyn"]',document.head);k=i(l,"META",{name:!0,content:!0}),l.forEach(a),is=c(s),A=i(s,"H1",{class:!0});var Ae=r(A);v=i(Ae,"A",{id:!0,class:!0,href:!0});var vp=r(v);C=i(vp,"SPAN",{});var bp=r(C);m(Q.$$.fragment,bp),bp.forEach(a),vp.forEach(a),Ls=c(Ae),O=i(Ae,"SPAN",{});var yp=r(O);Ps=n(yp,"Document Question Answering"),yp.forEach(a),Ae.forEach(a),rs=c(s),m(D.$$.fragment,s),ps=c(s),b=i(s,"P",{});var kp=r(b);S=n(kp,`Document Question Answering, also referred to as Document Visual Question Answering, is a task that involves providing
answers to questions posed about document images. The input to models supporting this task is typically a combination of an image and
a question, and the output is an answer expressed in natural language. These models utilize multiple modalities, including
text, the positions of words (bounding boxes), and the image itself.`),kp.forEach(a),R=c(s),Y=i(s,"P",{});var $p=r(Y);De=n($p,"This guide illustrates how to:"),$p.forEach(a),Cs=c(s),hs=i(s,"UL",{});var nl=r(hs);J=i(nl,"LI",{});var fa=r(J);$l=n(fa,"Fine-tune "),Te=i(fa,"A",{href:!0});var qp=r(Te);ql=n(qp,"LayoutLMv2"),qp.forEach(a),El=n(fa," on the "),Os=i(fa,"A",{href:!0,rel:!0});var Ep=r(Os);Al=n(Ep,"DocVQA dataset"),Ep.forEach(a),Dl=n(fa,"."),fa.forEach(a),Tl=c(nl),ba=i(nl,"LI",{});var Ap=r(ba);Ll=n(Ap,"Use your fine-tuned model for inference."),Ap.forEach(a),nl.forEach(a),Ct=c(s),m(cs.$$.fragment,s),Ot=c(s),Le=i(s,"P",{});var Dp=r(Le);Pl=n(Dp,`LayoutLMv2 solves the document question-answering task by adding a question-answering head on top of the final hidden
states of the tokens, to predict the positions of the start and end tokens of the
answer. In other words, the problem is treated as extractive question answering: given the context, extract which piece
of information answers the question. The context comes from the output of an OCR engine, here it is Google\u2019s Tesseract.
states of the tokens, in order to predict which token is at the start of the answer and which token is at the end of the
answer. In other words, the problem is treated as extractive question answering: given the context, extract which piece
of information answers the question. The context comes from the output of an OCR engine, here it is Google\u2019s Tesseract.`),Dp.forEach(a),It=c(s),Pe=i(s,"P",{});var Tp=r(Pe);Cl=n(Tp,"Before you begin, make sure you have all the necessary libraries installed. LayoutLMv2 depends on detectron2, torchvision and tesseract."),Tp.forEach(a),zt=c(s),m(Is.$$.fragment,s),Mt=c(s),m(zs.$$.fragment,s),Nt=c(s),m(Ms.$$.fragment,s),Ft=c(s),Ce=i(s,"P",{});var Lp=r(Ce);Ol=n(Lp,"Once you have installed all of the dependencies, restart your runtime."),Lp.forEach(a),Qt=c(s),Oe=i(s,"P",{});var Pp=r(Oe);Il=n(Pp,`We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the \u{1F917} Hub.
When prompted, enter your token to log in:`),Pp.forEach(a),Rt=c(s),m(Ns.$$.fragment,s),St=c(s),Ie=i(s,"P",{});var Cp=r(Ie);zl=n(Cp,"Let\u2019s define some global variables."),Cp.forEach(a),Ht=c(s),m(Fs.$$.fragment,s),Wt=c(s),X=i(s,"H2",{class:!0});var ll=r(X);ds=i(ll,"A",{id:!0,class:!0,href:!0});var Op=r(ds);ya=i(Op,"SPAN",{});var Ip=r(ya);m(Qs.$$.fragment,Ip),Ip.forEach(a),Op.forEach(a),Ml=c(ll),ka=i(ll,"SPAN",{});var zp=r(ka);Nl=n(zp,"Load the data"),zp.forEach(a),ll.forEach(a),Vt=c(s),H=i(s,"P",{});var xa=r(H);Fl=n(xa,`In this guide we use a small sample of preprocessed DocVQA that you can find on \u{1F917} Hub. If you\u2019d like to use the full
DocVQA dataset, you can register and download it on `),Rs=i(xa,"A",{href:!0,rel:!0});var Mp=r(Rs);Ql=n(Mp,"DocVQA homepage"),Mp.forEach(a),Rl=n(xa,`. If you do so, to
proceed with this guide check out `),Ss=i(xa,"A",{href:!0,rel:!0});var Np=r(Ss);Sl=n(Np,"how to load files into a \u{1F917} dataset"),Np.forEach(a),Hl=n(xa,"."),xa.forEach(a),Bt=c(s),m(Hs.$$.fragment,s),Gt=c(s),ze=i(s,"P",{});var Fp=r(ze);Wl=n(Fp,`As you can see, the dataset is split into train and test sets already. Take a look at a random example to familiarize
yourself with the features.`),Fp.forEach(a),Ut=c(s),m(Ws.$$.fragment,s),Kt=c(s),Me=i(s,"P",{});var Qp=r(Me);Vl=n(Qp,"Here\u2019s what the individual fields represent:"),Qp.forEach(a),Yt=c(s),$=i(s,"UL",{});var M=r($);Ne=i(M,"LI",{});var dp=r(Ne);$a=i(dp,"CODE",{});var Rp=r($a);Bl=n(Rp,"id"),Rp.forEach(a),Gl=n(dp,": the example\u2019s id"),dp.forEach(a),Ul=c(M),Fe=i(M,"LI",{});var up=r(Fe);qa=i(up,"CODE",{});var Sp=r(qa);Kl=n(Sp,"image"),Sp.forEach(a),Yl=n(up,": a PIL.Image.Image object containing the document image"),up.forEach(a),Jl=c(M),Qe=i(M,"LI",{});var mp=r(Qe);Ea=i(mp,"CODE",{});var Hp=r(Ea);Xl=n(Hp,"query"),Hp.forEach(a),Zl=n(mp,": the question string - natural language asked question, in several languages"),mp.forEach(a),so=c(M),Re=i(M,"LI",{});var gp=r(Re);Aa=i(gp,"CODE",{});var Wp=r(Aa);eo=n(Wp,"answers"),Wp.forEach(a),ao=n(gp,": a list of correct answers provided by human annotators"),gp.forEach(a),to=c(M),us=i(M,"LI",{});var Tt=r(us);Da=i(Tt,"CODE",{});var Vp=r(Da);no=n(Vp,"words"),Vp.forEach(a),lo=n(Tt," and "),Ta=i(Tt,"CODE",{});var Bp=r(Ta);oo=n(Bp,"bounding_boxes"),Bp.forEach(a),io=n(Tt,": the results of OCR, which we will not use here"),Tt.forEach(a),ro=c(M),Se=i(M,"LI",{});var fp=r(Se);La=i(fp,"CODE",{});var Gp=r(La);po=n(Gp,"answer"),Gp.forEach(a),ho=n(fp,": an answer matched by a different model which we will not use here"),fp.forEach(a),M.forEach(a),Jt=c(s),ms=i(s,"P",{});var ol=r(ms);co=n(ol,"Let\u2019s leave only English questions, and drop the "),Pa=i(ol,"CODE",{});var Up=r(Pa);uo=n(Up,"answer"),Up.forEach(a),mo=n(ol,` feature which appears to contain predictions by another model.
We\u2019ll also take the first of the answers from the set provided by the annotators. Alternatively, you can randomly sample it.`),ol.forEach(a),Xt=c(s),m(Vs.$$.fragment,s),Zt=c(s),I=i(s,"P",{});var As=r(I);go=n(As,"Note that the LayoutLMv2 checkpoint that we use in this guide has been trained with "),Ca=i(As,"CODE",{});var Kp=r(Ca);fo=n(Kp,"max_position_embeddings = 512"),Kp.forEach(a),xo=n(As,` (you can
find this information in the `),Z=i(As,"A",{href:!0,rel:!0});var il=r(Z);_o=n(il,"checkpoint\u2019s "),Oa=i(il,"CODE",{});var Yp=r(Oa);jo=n(Yp,"config.json"),Yp.forEach(a),wo=n(il," file"),il.forEach(a),vo=n(As,`).
We can truncate the examples but to avoid the situation where the answer might be at the end of a large document and end up truncated,
here we\u2019ll remove the few examples where the embedding is likely to end up longer than 512.
If most of the documents in your dataset are long, you can implement a sliding window strategy - check out `),Bs=i(As,"A",{href:!0,rel:!0});var Jp=r(Bs);bo=n(Jp,"this notebook"),Jp.forEach(a),yo=n(As," for details."),As.forEach(a),sn=c(s),m(Gs.$$.fragment,s),en=c(s),W=i(s,"P",{});var _a=r(W);ko=n(_a,`At this point let\u2019s also remove the OCR features from this dataset. These are a result of OCR for fine-tuning a different
model. They would still require some processing if we wanted to use them, as they do not match the input requirements
of the model we use in this guide. Instead, we can use the `),He=i(_a,"A",{href:!0});var Xp=r(He);$o=n(Xp,"LayoutLMv2Processor"),Xp.forEach(a),qo=n(_a,` on the original data for both OCR and
tokenization. This way we\u2019ll get the inputs that match model\u2019s expected input. If you want to process images manually,
check out the `),Us=i(_a,"A",{href:!0});var xp=r(Us);Ia=i(xp,"CODE",{});var Zp=r(Ia);Eo=n(Zp,"LayoutLMv2"),Zp.forEach(a),Ao=n(xp," model documentation"),xp.forEach(a),Do=n(_a," to learn what input format the model expects."),_a.forEach(a),an=c(s),m(Ks.$$.fragment,s),tn=c(s),We=i(s,"P",{});var sh=r(We);To=n(sh,"Finally, the data exploration won\u2019t be complete if we don\u2019t peek at an image example."),sh.forEach(a),nn=c(s),m(Ys.$$.fragment,s),ln=c(s),Js=i(s,"DIV",{class:!0});var eh=r(Js);Ve=i(eh,"IMG",{src:!0,alt:!0}),eh.forEach(a),on=c(s),ss=i(s,"H2",{class:!0});var rl=r(ss);gs=i(rl,"A",{id:!0,class:!0,href:!0});var ah=r(gs);za=i(ah,"SPAN",{});var th=r(za);m(Xs.$$.fragment,th),th.forEach(a),ah.forEach(a),Lo=c(rl),Ma=i(rl,"SPAN",{});var nh=r(Ma);Po=n(nh,"Preprocess the data"),nh.forEach(a),rl.forEach(a),rn=c(s),fs=i(s,"P",{});var pl=r(fs);Co=n(pl,`The Document Question Answering task is a multimodal task, and you need to make sure that the inputs from each modality
are preprocessed according to the model\u2019s expectations. Let\u2019s start by loading the `),Be=i(pl,"A",{href:!0});var lh=r(Be);Oo=n(lh,"LayoutLMv2Processor"),lh.forEach(a),Io=n(pl,", which internally combines an image processor that can handle image data and a tokenizer that can encode text data."),pl.forEach(a),pn=c(s),m(Zs.$$.fragment,s),hn=c(s),es=i(s,"H3",{class:!0});var hl=r(es);xs=i(hl,"A",{id:!0,class:!0,href:!0});var oh=r(xs);Na=i(oh,"SPAN",{});var ih=r(Na);m(se.$$.fragment,ih),ih.forEach(a),oh.forEach(a),zo=c(hl),Fa=i(hl,"SPAN",{});var rh=r(Fa);Mo=n(rh,"Preprocessing document images"),rh.forEach(a),hl.forEach(a),cn=c(s),_s=i(s,"P",{});var cl=r(_s);No=n(cl,"First, let\u2019s prepare the document images for the model with the help of the "),Qa=i(cl,"CODE",{});var ph=r(Qa);Fo=n(ph,"image_processor"),ph.forEach(a),Qo=n(cl,` from the processor.
By default, image processor resizes the images to 224x224, makes sure they have the correct order of color channels,
applies OCR with tesseract to get words and normalized bounding boxes. In this tutorial, all of these defaults are exactly what we need.
Write a function that applies the default image processing to a batch of images and returns the results of OCR.`),cl.forEach(a),dn=c(s),m(ee.$$.fragment,s),un=c(s),js=i(s,"P",{});var dl=r(js);Ro=n(dl,"To apply this preprocessing to the entire dataset in a fast way, use "),Ra=i(dl,"CODE",{});var hh=r(Ra);So=n(hh,"map"),hh.forEach(a),Ho=n(dl,"."),dl.forEach(a),mn=c(s),m(ae.$$.fragment,s),gn=c(s),as=i(s,"H3",{class:!0});var ul=r(as);ws=i(ul,"A",{id:!0,class:!0,href:!0});var ch=r(ws);Sa=i(ch,"SPAN",{});var dh=r(Sa);m(te.$$.fragment,dh),dh.forEach(a),ch.forEach(a),Wo=c(ul),Ha=i(ul,"SPAN",{});var uh=r(Ha);Vo=n(uh,"Preprocessing text data"),uh.forEach(a),ul.forEach(a),fn=c(s),q=i(s,"P",{});var N=r(q);Bo=n(N,`Once we have applied OCR to the images, we need to encode the text part of the dataset to prepare it for the model.
This involves converting the words and boxes that we got in the previous step to token-level `),Wa=i(N,"CODE",{});var mh=r(Wa);Go=n(mh,"input_ids"),mh.forEach(a),Uo=n(N,", "),Va=i(N,"CODE",{});var gh=r(Va);Ko=n(gh,"attention_mask"),gh.forEach(a),Yo=n(N,`,
`),Ba=i(N,"CODE",{});var fh=r(Ba);Jo=n(fh,"token_type_ids"),fh.forEach(a),Xo=n(N," and "),Ga=i(N,"CODE",{});var xh=r(Ga);Zo=n(xh,"bbox"),xh.forEach(a),si=n(N,". For preprocessing text, we\u2019ll need the "),Ua=i(N,"CODE",{});var _h=r(Ua);ei=n(_h,"tokenizer"),_h.forEach(a),ai=n(N," from the processor."),N.forEach(a),xn=c(s),m(ne.$$.fragment,s),_n=c(s),z=i(s,"P",{});var Ds=r(z);ti=n(Ds,"On top of the preprocessing mentioned above, we also need to add the labels for the model. For "),Ka=i(Ds,"CODE",{});var jh=r(Ka);ni=n(jh,"xxxForQuestionAnswering"),jh.forEach(a),li=n(Ds,` models
in \u{1F917} Transformers, the labels consist of the `),Ya=i(Ds,"CODE",{});var wh=r(Ya);oi=n(wh,"start_positions"),wh.forEach(a),ii=n(Ds," and "),Ja=i(Ds,"CODE",{});var vh=r(Ja);ri=n(vh,"end_positions"),vh.forEach(a),pi=n(Ds,`, indicating which token is at the
start and which token is at the end of the answer.`),Ds.forEach(a),jn=c(s),Ge=i(s,"P",{});var bh=r(Ge);hi=n(bh,"Let\u2019s start with that. Define a helper function that can find a sublist (the answer split into words) in a larger list (the words list)."),bh.forEach(a),wn=c(s),w=i(s,"P",{});var y=r(w);ci=n(y,"This function will take two lists as input, "),Xa=i(y,"CODE",{});var yh=r(Xa);di=n(yh,"words_list"),yh.forEach(a),ui=n(y," and "),Za=i(y,"CODE",{});var kh=r(Za);mi=n(kh,"answer_list"),kh.forEach(a),gi=n(y,". It will then iterate over the "),st=i(y,"CODE",{});var $h=r(st);fi=n($h,"words_list"),$h.forEach(a),xi=n(y,` and check
if the current word in the `),et=i(y,"CODE",{});var qh=r(et);_i=n(qh,"words_list"),qh.forEach(a),ji=n(y,` (words_list[i]) is equal to the first word of answer_list (answer_list[0]) and if
the sublist of `),at=i(y,"CODE",{});var Eh=r(at);wi=n(Eh,"words_list"),Eh.forEach(a),vi=n(y," starting from the current word and of the same length as "),tt=i(y,"CODE",{});var Ah=r(tt);bi=n(Ah,"answer_list"),Ah.forEach(a),yi=n(y," is equal "),nt=i(y,"CODE",{});var Dh=r(nt);ki=n(Dh,"to answer_list"),Dh.forEach(a),$i=n(y,`.
If this condition is true, it means that a match has been found, and the function will record the match, its starting index (idx),
and its ending index (idx + len(answer_list) - 1). If more than one match was found, the function will return only the first one.
If no match is found, the function returns (`),lt=i(y,"CODE",{});var Th=r(lt);qi=n(Th,"None"),Th.forEach(a),Ei=n(y,", 0, and 0)."),y.forEach(a),vn=c(s),m(le.$$.fragment,s),bn=c(s),Ue=i(s,"P",{});var Lh=r(Ue);Ai=n(Lh,"To illustrate how this function finds the position of the answer, let\u2019s use it on an example:"),Lh.forEach(a),yn=c(s),m(oe.$$.fragment,s),kn=c(s),Ke=i(s,"P",{});var Ph=r(Ke);Di=n(Ph,"Once examples are encoded, however, they will look like this:"),Ph.forEach(a),$n=c(s),m(ie.$$.fragment,s),qn=c(s),Ye=i(s,"P",{});var Ch=r(Ye);Ti=n(Ch,"We\u2019ll need to find the position of the answer in the encoded input."),Ch.forEach(a),En=c(s),V=i(s,"UL",{});var ja=r(V);Je=i(ja,"LI",{});var _p=r(Je);ot=i(_p,"CODE",{});var Oh=r(ot);Li=n(Oh,"token_type_ids"),Oh.forEach(a),Pi=n(_p," tells us which tokens are part of the question, and which ones are part of the document\u2019s words."),_p.forEach(a),Ci=c(ja),Xe=i(ja,"LI",{});var jp=r(Xe);it=i(jp,"CODE",{});var Ih=r(it);Oi=n(Ih,"tokenizer.cls_token_id"),Ih.forEach(a),Ii=n(jp," will help find the special token at the beginning of the input."),jp.forEach(a),zi=c(ja),vs=i(ja,"LI",{});var Lt=r(vs);rt=i(Lt,"CODE",{});var zh=r(rt);Mi=n(zh,"word_ids"),zh.forEach(a),Ni=n(Lt," will help match the answer found in the original "),pt=i(Lt,"CODE",{});var Mh=r(pt);Fi=n(Mh,"words"),Mh.forEach(a),Qi=n(Lt,` to the same answer in the full encoded input and determine
the start/end position of the answer in the encoded input.`),Lt.forEach(a),ja.forEach(a),An=c(s),Ze=i(s,"P",{});var Nh=r(Ze);Ri=n(Nh,"With that in mind, let\u2019s create a function to encode a batch of examples in the dataset:"),Nh.forEach(a),Dn=c(s),m(re.$$.fragment,s),Tn=c(s),sa=i(s,"P",{});var Fh=r(sa);Si=n(Fh,"Now that we have this preprocessing function, we can encode the entire dataset:"),Fh.forEach(a),Ln=c(s),m(pe.$$.fragment,s),Pn=c(s),ea=i(s,"P",{});var Qh=r(ea);Hi=n(Qh,"Let\u2019s check what the features of the encoded dataset look like:"),Qh.forEach(a),Cn=c(s),m(he.$$.fragment,s),On=c(s),ts=i(s,"H2",{class:!0});var ml=r(ts);bs=i(ml,"A",{id:!0,class:!0,href:!0});var Rh=r(bs);ht=i(Rh,"SPAN",{});var Sh=r(ht);m(ce.$$.fragment,Sh),Sh.forEach(a),Rh.forEach(a),Wi=c(ml),ct=i(ml,"SPAN",{});var Hh=r(ct);Vi=n(Hh,"Evaluation"),Hh.forEach(a),ml.forEach(a),In=c(s),B=i(s,"P",{});var wa=r(B);Bi=n(wa,`Evaluation for document question answering requires a significant amount of postprocessing. To avoid taking up too much
of your time, this guide skips the evaluation step. The `),aa=i(wa,"A",{href:!0});var Wh=r(aa);Gi=n(Wh,"Trainer"),Wh.forEach(a),Ui=n(wa,` still calculates the evaluation loss during training so
you\u2019re not completely in the dark about your model\u2019s performance. Extractive question answering is typically evaluated using F1/exact match.
If you\u2019d like to implement it yourself, check out the `),de=i(wa,"A",{href:!0,rel:!0});var Vh=r(de);Ki=n(Vh,"Question Answering chapter"),Vh.forEach(a),Yi=n(wa,`
of the Hugging Face course for inspiration.`),wa.forEach(a),zn=c(s),ns=i(s,"H2",{class:!0});var gl=r(ns);ys=i(gl,"A",{id:!0,class:!0,href:!0});var Bh=r(ys);dt=i(Bh,"SPAN",{});var Gh=r(dt);m(ue.$$.fragment,Gh),Gh.forEach(a),Bh.forEach(a),Ji=c(gl),ut=i(gl,"SPAN",{});var Uh=r(ut);Xi=n(Uh,"Train"),Uh.forEach(a),gl.forEach(a),Mn=c(s),ta=i(s,"P",{});var Kh=r(ta);Zi=n(Kh,`Congratulations! You\u2019ve successfully navigated the toughest part of this guide and now you are ready to train your own model.
Training involves the following steps:`),Kh.forEach(a),Nn=c(s),T=i(s,"UL",{});var G=r(T);me=i(G,"LI",{});var fl=r(me);sr=n(fl,"Load the model with "),na=i(fl,"A",{href:!0});var Yh=r(na);er=n(Yh,"AutoModelForDocumentQuestionAnswering"),Yh.forEach(a),ar=n(fl," using the same checkpoint as in the preprocessing."),fl.forEach(a),tr=c(G),ge=i(G,"LI",{});var xl=r(ge);nr=n(xl,"Define your training hyperparameters in "),la=i(xl,"A",{href:!0});var Jh=r(la);lr=n(Jh,"TrainingArguments"),Jh.forEach(a),or=n(xl,"."),xl.forEach(a),ir=c(G),fe=i(G,"LI",{});var _l=r(fe);rr=n(_l,"Define a function to batch examples together, here the "),oa=i(_l,"A",{href:!0});var Xh=r(oa);pr=n(Xh,"DefaultDataCollator"),Xh.forEach(a),hr=n(_l," will do just fine"),_l.forEach(a),cr=c(G),xe=i(G,"LI",{});var jl=r(xe);dr=n(jl,"Pass the training arguments to "),ia=i(jl,"A",{href:!0});var Zh=r(ia);ur=n(Zh,"Trainer"),Zh.forEach(a),mr=n(jl," along with the model, dataset, and data collator."),jl.forEach(a),gr=c(G),_e=i(G,"LI",{});var wl=r(_e);fr=n(wl,"Call "),ra=i(wl,"A",{href:!0});var sc=r(ra);xr=n(sc,"train()"),sc.forEach(a),_r=n(wl," to finetune your model."),wl.forEach(a),G.forEach(a),Fn=c(s),m(je.$$.fragment,s),Qn=c(s),E=i(s,"P",{});var F=r(E);jr=n(F,"In the "),pa=i(F,"A",{href:!0});var ec=r(pa);wr=n(ec,"TrainingArguments"),ec.forEach(a),vr=n(F," use "),mt=i(F,"CODE",{});var ac=r(mt);br=n(ac,"output_dir"),ac.forEach(a),yr=n(F,` to specify where to save your model, and configure hyperparameters as you see fit.
If you wish to share your model with the community, set `),gt=i(F,"CODE",{});var tc=r(gt);kr=n(tc,"push_to_hub"),tc.forEach(a),$r=n(F," to "),ft=i(F,"CODE",{});var nc=r(ft);qr=n(nc,"True"),nc.forEach(a),Er=n(F,` (you must be signed in to Hugging Face to upload your model).
In this case the `),xt=i(F,"CODE",{});var lc=r(xt);Ar=n(lc,"output_dir"),lc.forEach(a),Dr=n(F," will also be the name of the repo where your model checkpoint will be pushed."),F.forEach(a),Rn=c(s),m(we.$$.fragment,s),Sn=c(s),ha=i(s,"P",{});var oc=r(ha);Tr=n(oc,"Define a simple data collator to batch examples together."),oc.forEach(a),Hn=c(s),m(ve.$$.fragment,s),Wn=c(s),ks=i(s,"P",{});var vl=r(ks);Lr=n(vl,"Finally, bring everything together, and call "),ca=i(vl,"A",{href:!0});var ic=r(ca);Pr=n(ic,"train()"),ic.forEach(a),Cr=n(vl,":"),vl.forEach(a),Vn=c(s),m(be.$$.fragment,s),Bn=c(s),$s=i(s,"P",{});var bl=r($s);Or=n(bl,"To add the final model to \u{1F917} Hub, create a model card and call "),_t=i(bl,"CODE",{});var rc=r(_t);Ir=n(rc,"push_to_hub"),rc.forEach(a),zr=n(bl,":"),bl.forEach(a),Gn=c(s),m(ye.$$.fragment,s),Un=c(s),ls=i(s,"H2",{class:!0});var yl=r(ls);qs=i(yl,"A",{id:!0,class:!0,href:!0});var pc=r(qs);jt=i(pc,"SPAN",{});var hc=r(jt);m(ke.$$.fragment,hc),hc.forEach(a),pc.forEach(a),Mr=c(yl),wt=i(yl,"SPAN",{});var cc=r(wt);Nr=n(cc,"Inference"),cc.forEach(a),yl.forEach(a),Kn=c(s),Es=i(s,"P",{});var kl=r(Es);Fr=n(kl,`Now that you have finetuned a LayoutLMv2 model, and uploaded it to the \u{1F917} Hub, you can use it for inference. The simplest
way to try out your finetuned model for inference is to use it in a `),da=i(kl,"A",{href:!0});var dc=r(da);Qr=n(dc,"Pipeline"),dc.forEach(a),Rr=n(kl,"."),kl.forEach(a),Yn=c(s),ua=i(s,"P",{});var uc=r(ua);Sr=n(uc,"Let\u2019s take an example:"),uc.forEach(a),Jn=c(s),m($e.$$.fragment,s),Xn=c(s),ma=i(s,"P",{});var mc=r(ma);Hr=n(mc,`Next, instantiate a pipeline for
document question answering with your model, and pass the image + question combination to it.`),mc.forEach(a),Zn=c(s),m(qe.$$.fragment,s),sl=c(s),ga=i(s,"P",{});var gc=r(ga);Wr=n(gc,"You can also manually replicate the results of the pipeline if you\u2019d like:"),gc.forEach(a),el=c(s),L=i(s,"OL",{});var U=r(L);vt=i(U,"LI",{});var fc=r(vt);Vr=n(fc,"Take an image and a question, prepare them for the model using the processor from your model."),fc.forEach(a),Br=c(U),bt=i(U,"LI",{});var xc=r(bt);Gr=n(xc,"Forward the result or preprocessing through the model."),xc.forEach(a),Ur=c(U),os=i(U,"LI",{});var va=r(os);Kr=n(va,"The model returns "),yt=i(va,"CODE",{});var _c=r(yt);Yr=n(_c,"start_logits"),_c.forEach(a),Jr=n(va," and "),kt=i(va,"CODE",{});var jc=r(kt);Xr=n(jc,"end_logits"),jc.forEach(a),Zr=n(va,`, which indicate which token is at the start of the answer and
which token is at the end of the answer. Both have shape (batch_size, sequence_length).`),va.forEach(a),sp=c(U),P=i(U,"LI",{});var K=r(P);ep=n(K,"Take an argmax on the last dimension of both the "),$t=i(K,"CODE",{});var wc=r($t);ap=n(wc,"start_logits"),wc.forEach(a),tp=n(K," and "),qt=i(K,"CODE",{});var vc=r(qt);np=n(vc,"end_logits"),vc.forEach(a),lp=n(K," to get the predicted "),Et=i(K,"CODE",{});var bc=r(Et);op=n(bc,"start_idx"),bc.forEach(a),ip=n(K," and "),At=i(K,"CODE",{});var yc=r(At);rp=n(yc,"end_idx"),yc.forEach(a),pp=n(K,"."),K.forEach(a),hp=c(U),Dt=i(U,"LI",{});var kc=r(Dt);cp=n(kc,"Decode the answer with the tokenizer."),kc.forEach(a),U.forEach(a),al=c(s),m(Ee.$$.fragment,s),this.h()},h(){d(k,"name","hf:doc:metadata"),d(k,"content",JSON.stringify(Ic)),d(v,"id","document-question-answering"),d(v,"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"),d(v,"href","#document-question-answering"),d(A,"class","relative group"),d(Te,"href","../model_doc/layoutlmv2"),d(Os,"href","https://huggingface.co/datasets/nielsr/docvqa_1200_examples_donut"),d(Os,"rel","nofollow"),d(ds,"id","load-the-data"),d(ds,"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"),d(ds,"href","#load-the-data"),d(X,"class","relative group"),d(Rs,"href","https://rrc.cvc.uab.es/?ch=17"),d(Rs,"rel","nofollow"),d(Ss,"href","https://huggingface.co/docs/datasets/loading#local-and-remote-files"),d(Ss,"rel","nofollow"),d(Z,"href","https://huggingface.co/microsoft/layoutlmv2-base-uncased/blob/main/config.json#L18"),d(Z,"rel","nofollow"),d(Bs,"href","https://github.com/huggingface/notebooks/blob/main/examples/question_answering.ipynb"),d(Bs,"rel","nofollow"),d(He,"href","/docs/transformers/v4.27.1/en/model_doc/layoutlmv2#transformers.LayoutLMv2Processor"),d(Us,"href","../model_doc/layoutlmv2"),Dc(Ve.src,wp="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/docvqa_example.jpg")||d(Ve,"src",wp),d(Ve,"alt","DocVQA Image Example"),d(Js,"class","flex justify-center"),d(gs,"id","preprocess-the-data"),d(gs,"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"),d(gs,"href","#preprocess-the-data"),d(ss,"class","relative group"),d(Be,"href","/docs/transformers/v4.27.1/en/model_doc/layoutlmv2#transformers.LayoutLMv2Processor"),d(xs,"id","preprocessing-document-images"),d(xs,"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"),d(xs,"href","#preprocessing-document-images"),d(es,"class","relative group"),d(ws,"id","preprocessing-text-data"),d(ws,"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"),d(ws,"href","#preprocessing-text-data"),d(as,"class","relative group"),d(bs,"id","evaluation"),d(bs,"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"),d(bs,"href","#evaluation"),d(ts,"class","relative group"),d(aa,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),d(de,"href","https://huggingface.co/course/chapter7/7?fw=pt#postprocessing"),d(de,"rel","nofollow"),d(ys,"id","train"),d(ys,"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"),d(ys,"href","#train"),d(ns,"class","relative group"),d(na,"href","/docs/transformers/v4.27.1/en/model_doc/auto#transformers.AutoModelForDocumentQuestionAnswering"),d(la,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),d(oa,"href","/docs/transformers/v4.27.1/en/main_classes/data_collator#transformers.DefaultDataCollator"),d(ia,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),d(ra,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer.train"),d(pa,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),d(ca,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer.train"),d(qs,"id","inference"),d(qs,"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"),d(qs,"href","#inference"),d(ls,"class","relative group"),d(da,"href","/docs/transformers/v4.27.1/en/main_classes/pipelines#transformers.Pipeline")},m(s,l){e(document.head,k),p(s,is,l),p(s,A,l),e(A,v),e(v,C),g(Q,C,null),e(A,Ls),e(A,O),e(O,Ps),p(s,rs,l),g(D,s,l),p(s,ps,l),p(s,b,l),e(b,S),p(s,R,l),p(s,Y,l),e(Y,De),p(s,Cs,l),p(s,hs,l),e(hs,J),e(J,$l),e(J,Te),e(Te,ql),e(J,El),e(J,Os),e(Os,Al),e(J,Dl),e(hs,Tl),e(hs,ba),e(ba,Ll),p(s,Ct,l),g(cs,s,l),p(s,Ot,l),p(s,Le,l),e(Le,Pl),p(s,It,l),p(s,Pe,l),e(Pe,Cl),p(s,zt,l),g(Is,s,l),p(s,Mt,l),g(zs,s,l),p(s,Nt,l),g(Ms,s,l),p(s,Ft,l),p(s,Ce,l),e(Ce,Ol),p(s,Qt,l),p(s,Oe,l),e(Oe,Il),p(s,Rt,l),g(Ns,s,l),p(s,St,l),p(s,Ie,l),e(Ie,zl),p(s,Ht,l),g(Fs,s,l),p(s,Wt,l),p(s,X,l),e(X,ds),e(ds,ya),g(Qs,ya,null),e(X,Ml),e(X,ka),e(ka,Nl),p(s,Vt,l),p(s,H,l),e(H,Fl),e(H,Rs),e(Rs,Ql),e(H,Rl),e(H,Ss),e(Ss,Sl),e(H,Hl),p(s,Bt,l),g(Hs,s,l),p(s,Gt,l),p(s,ze,l),e(ze,Wl),p(s,Ut,l),g(Ws,s,l),p(s,Kt,l),p(s,Me,l),e(Me,Vl),p(s,Yt,l),p(s,$,l),e($,Ne),e(Ne,$a),e($a,Bl),e(Ne,Gl),e($,Ul),e($,Fe),e(Fe,qa),e(qa,Kl),e(Fe,Yl),e($,Jl),e($,Qe),e(Qe,Ea),e(Ea,Xl),e(Qe,Zl),e($,so),e($,Re),e(Re,Aa),e(Aa,eo),e(Re,ao),e($,to),e($,us),e(us,Da),e(Da,no),e(us,lo),e(us,Ta),e(Ta,oo),e(us,io),e($,ro),e($,Se),e(Se,La),e(La,po),e(Se,ho),p(s,Jt,l),p(s,ms,l),e(ms,co),e(ms,Pa),e(Pa,uo),e(ms,mo),p(s,Xt,l),g(Vs,s,l),p(s,Zt,l),p(s,I,l),e(I,go),e(I,Ca),e(Ca,fo),e(I,xo),e(I,Z),e(Z,_o),e(Z,Oa),e(Oa,jo),e(Z,wo),e(I,vo),e(I,Bs),e(Bs,bo),e(I,yo),p(s,sn,l),g(Gs,s,l),p(s,en,l),p(s,W,l),e(W,ko),e(W,He),e(He,$o),e(W,qo),e(W,Us),e(Us,Ia),e(Ia,Eo),e(Us,Ao),e(W,Do),p(s,an,l),g(Ks,s,l),p(s,tn,l),p(s,We,l),e(We,To),p(s,nn,l),g(Ys,s,l),p(s,ln,l),p(s,Js,l),e(Js,Ve),p(s,on,l),p(s,ss,l),e(ss,gs),e(gs,za),g(Xs,za,null),e(ss,Lo),e(ss,Ma),e(Ma,Po),p(s,rn,l),p(s,fs,l),e(fs,Co),e(fs,Be),e(Be,Oo),e(fs,Io),p(s,pn,l),g(Zs,s,l),p(s,hn,l),p(s,es,l),e(es,xs),e(xs,Na),g(se,Na,null),e(es,zo),e(es,Fa),e(Fa,Mo),p(s,cn,l),p(s,_s,l),e(_s,No),e(_s,Qa),e(Qa,Fo),e(_s,Qo),p(s,dn,l),g(ee,s,l),p(s,un,l),p(s,js,l),e(js,Ro),e(js,Ra),e(Ra,So),e(js,Ho),p(s,mn,l),g(ae,s,l),p(s,gn,l),p(s,as,l),e(as,ws),e(ws,Sa),g(te,Sa,null),e(as,Wo),e(as,Ha),e(Ha,Vo),p(s,fn,l),p(s,q,l),e(q,Bo),e(q,Wa),e(Wa,Go),e(q,Uo),e(q,Va),e(Va,Ko),e(q,Yo),e(q,Ba),e(Ba,Jo),e(q,Xo),e(q,Ga),e(Ga,Zo),e(q,si),e(q,Ua),e(Ua,ei),e(q,ai),p(s,xn,l),g(ne,s,l),p(s,_n,l),p(s,z,l),e(z,ti),e(z,Ka),e(Ka,ni),e(z,li),e(z,Ya),e(Ya,oi),e(z,ii),e(z,Ja),e(Ja,ri),e(z,pi),p(s,jn,l),p(s,Ge,l),e(Ge,hi),p(s,wn,l),p(s,w,l),e(w,ci),e(w,Xa),e(Xa,di),e(w,ui),e(w,Za),e(Za,mi),e(w,gi),e(w,st),e(st,fi),e(w,xi),e(w,et),e(et,_i),e(w,ji),e(w,at),e(at,wi),e(w,vi),e(w,tt),e(tt,bi),e(w,yi),e(w,nt),e(nt,ki),e(w,$i),e(w,lt),e(lt,qi),e(w,Ei),p(s,vn,l),g(le,s,l),p(s,bn,l),p(s,Ue,l),e(Ue,Ai),p(s,yn,l),g(oe,s,l),p(s,kn,l),p(s,Ke,l),e(Ke,Di),p(s,$n,l),g(ie,s,l),p(s,qn,l),p(s,Ye,l),e(Ye,Ti),p(s,En,l),p(s,V,l),e(V,Je),e(Je,ot),e(ot,Li),e(Je,Pi),e(V,Ci),e(V,Xe),e(Xe,it),e(it,Oi),e(Xe,Ii),e(V,zi),e(V,vs),e(vs,rt),e(rt,Mi),e(vs,Ni),e(vs,pt),e(pt,Fi),e(vs,Qi),p(s,An,l),p(s,Ze,l),e(Ze,Ri),p(s,Dn,l),g(re,s,l),p(s,Tn,l),p(s,sa,l),e(sa,Si),p(s,Ln,l),g(pe,s,l),p(s,Pn,l),p(s,ea,l),e(ea,Hi),p(s,Cn,l),g(he,s,l),p(s,On,l),p(s,ts,l),e(ts,bs),e(bs,ht),g(ce,ht,null),e(ts,Wi),e(ts,ct),e(ct,Vi),p(s,In,l),p(s,B,l),e(B,Bi),e(B,aa),e(aa,Gi),e(B,Ui),e(B,de),e(de,Ki),e(B,Yi),p(s,zn,l),p(s,ns,l),e(ns,ys),e(ys,dt),g(ue,dt,null),e(ns,Ji),e(ns,ut),e(ut,Xi),p(s,Mn,l),p(s,ta,l),e(ta,Zi),p(s,Nn,l),p(s,T,l),e(T,me),e(me,sr),e(me,na),e(na,er),e(me,ar),e(T,tr),e(T,ge),e(ge,nr),e(ge,la),e(la,lr),e(ge,or),e(T,ir),e(T,fe),e(fe,rr),e(fe,oa),e(oa,pr),e(fe,hr),e(T,cr),e(T,xe),e(xe,dr),e(xe,ia),e(ia,ur),e(xe,mr),e(T,gr),e(T,_e),e(_e,fr),e(_e,ra),e(ra,xr),e(_e,_r),p(s,Fn,l),g(je,s,l),p(s,Qn,l),p(s,E,l),e(E,jr),e(E,pa),e(pa,wr),e(E,vr),e(E,mt),e(mt,br),e(E,yr),e(E,gt),e(gt,kr),e(E,$r),e(E,ft),e(ft,qr),e(E,Er),e(E,xt),e(xt,Ar),e(E,Dr),p(s,Rn,l),g(we,s,l),p(s,Sn,l),p(s,ha,l),e(ha,Tr),p(s,Hn,l),g(ve,s,l),p(s,Wn,l),p(s,ks,l),e(ks,Lr),e(ks,ca),e(ca,Pr),e(ks,Cr),p(s,Vn,l),g(be,s,l),p(s,Bn,l),p(s,$s,l),e($s,Or),e($s,_t),e(_t,Ir),e($s,zr),p(s,Gn,l),g(ye,s,l),p(s,Un,l),p(s,ls,l),e(ls,qs),e(qs,jt),g(ke,jt,null),e(ls,Mr),e(ls,wt),e(wt,Nr),p(s,Kn,l),p(s,Es,l),e(Es,Fr),e(Es,da),e(da,Qr),e(Es,Rr),p(s,Yn,l),p(s,ua,l),e(ua,Sr),p(s,Jn,l),g($e,s,l),p(s,Xn,l),p(s,ma,l),e(ma,Hr),p(s,Zn,l),g(qe,s,l),p(s,sl,l),p(s,ga,l),e(ga,Wr),p(s,el,l),p(s,L,l),e(L,vt),e(vt,Vr),e(L,Br),e(L,bt),e(bt,Gr),e(L,Ur),e(L,os),e(os,Kr),e(os,yt),e(yt,Yr),e(os,Jr),e(os,kt),e(kt,Xr),e(os,Zr),e(L,sp),e(L,P),e(P,ep),e(P,$t),e($t,ap),e(P,tp),e(P,qt),e(qt,np),e(P,lp),e(P,Et),e(Et,op),e(P,ip),e(P,At),e(At,rp),e(P,pp),e(L,hp),e(L,Dt),e(Dt,cp),p(s,al,l),g(Ee,s,l),tl=!0},p(s,[l]){const Ae={};l&2&&(Ae.$$scope={dirty:l,ctx:s}),cs.$set(Ae)},i(s){tl||(f(Q.$$.fragment,s),f(D.$$.fragment,s),f(cs.$$.fragment,s),f(Is.$$.fragment,s),f(zs.$$.fragment,s),f(Ms.$$.fragment,s),f(Ns.$$.fragment,s),f(Fs.$$.fragment,s),f(Qs.$$.fragment,s),f(Hs.$$.fragment,s),f(Ws.$$.fragment,s),f(Vs.$$.fragment,s),f(Gs.$$.fragment,s),f(Ks.$$.fragment,s),f(Ys.$$.fragment,s),f(Xs.$$.fragment,s),f(Zs.$$.fragment,s),f(se.$$.fragment,s),f(ee.$$.fragment,s),f(ae.$$.fragment,s),f(te.$$.fragment,s),f(ne.$$.fragment,s),f(le.$$.fragment,s),f(oe.$$.fragment,s),f(ie.$$.fragment,s),f(re.$$.fragment,s),f(pe.$$.fragment,s),f(he.$$.fragment,s),f(ce.$$.fragment,s),f(ue.$$.fragment,s),f(je.$$.fragment,s),f(we.$$.fragment,s),f(ve.$$.fragment,s),f(be.$$.fragment,s),f(ye.$$.fragment,s),f(ke.$$.fragment,s),f($e.$$.fragment,s),f(qe.$$.fragment,s),f(Ee.$$.fragment,s),tl=!0)},o(s){x(Q.$$.fragment,s),x(D.$$.fragment,s),x(cs.$$.fragment,s),x(Is.$$.fragment,s),x(zs.$$.fragment,s),x(Ms.$$.fragment,s),x(Ns.$$.fragment,s),x(Fs.$$.fragment,s),x(Qs.$$.fragment,s),x(Hs.$$.fragment,s),x(Ws.$$.fragment,s),x(Vs.$$.fragment,s),x(Gs.$$.fragment,s),x(Ks.$$.fragment,s),x(Ys.$$.fragment,s),x(Xs.$$.fragment,s),x(Zs.$$.fragment,s),x(se.$$.fragment,s),x(ee.$$.fragment,s),x(ae.$$.fragment,s),x(te.$$.fragment,s),x(ne.$$.fragment,s),x(le.$$.fragment,s),x(oe.$$.fragment,s),x(ie.$$.fragment,s),x(re.$$.fragment,s),x(pe.$$.fragment,s),x(he.$$.fragment,s),x(ce.$$.fragment,s),x(ue.$$.fragment,s),x(je.$$.fragment,s),x(we.$$.fragment,s),x(ve.$$.fragment,s),x(be.$$.fragment,s),x(ye.$$.fragment,s),x(ke.$$.fragment,s),x($e.$$.fragment,s),x(qe.$$.fragment,s),x(Ee.$$.fragment,s),tl=!1},d(s){a(k),s&&a(is),s&&a(A),_(Q),s&&a(rs),_(D,s),s&&a(ps),s&&a(b),s&&a(R),s&&a(Y),s&&a(Cs),s&&a(hs),s&&a(Ct),_(cs,s),s&&a(Ot),s&&a(Le),s&&a(It),s&&a(Pe),s&&a(zt),_(Is,s),s&&a(Mt),_(zs,s),s&&a(Nt),_(Ms,s),s&&a(Ft),s&&a(Ce),s&&a(Qt),s&&a(Oe),s&&a(Rt),_(Ns,s),s&&a(St),s&&a(Ie),s&&a(Ht),_(Fs,s),s&&a(Wt),s&&a(X),_(Qs),s&&a(Vt),s&&a(H),s&&a(Bt),_(Hs,s),s&&a(Gt),s&&a(ze),s&&a(Ut),_(Ws,s),s&&a(Kt),s&&a(Me),s&&a(Yt),s&&a($),s&&a(Jt),s&&a(ms),s&&a(Xt),_(Vs,s),s&&a(Zt),s&&a(I),s&&a(sn),_(Gs,s),s&&a(en),s&&a(W),s&&a(an),_(Ks,s),s&&a(tn),s&&a(We),s&&a(nn),_(Ys,s),s&&a(ln),s&&a(Js),s&&a(on),s&&a(ss),_(Xs),s&&a(rn),s&&a(fs),s&&a(pn),_(Zs,s),s&&a(hn),s&&a(es),_(se),s&&a(cn),s&&a(_s),s&&a(dn),_(ee,s),s&&a(un),s&&a(js),s&&a(mn),_(ae,s),s&&a(gn),s&&a(as),_(te),s&&a(fn),s&&a(q),s&&a(xn),_(ne,s),s&&a(_n),s&&a(z),s&&a(jn),s&&a(Ge),s&&a(wn),s&&a(w),s&&a(vn),_(le,s),s&&a(bn),s&&a(Ue),s&&a(yn),_(oe,s),s&&a(kn),s&&a(Ke),s&&a($n),_(ie,s),s&&a(qn),s&&a(Ye),s&&a(En),s&&a(V),s&&a(An),s&&a(Ze),s&&a(Dn),_(re,s),s&&a(Tn),s&&a(sa),s&&a(Ln),_(pe,s),s&&a(Pn),s&&a(ea),s&&a(Cn),_(he,s),s&&a(On),s&&a(ts),_(ce),s&&a(In),s&&a(B),s&&a(zn),s&&a(ns),_(ue),s&&a(Mn),s&&a(ta),s&&a(Nn),s&&a(T),s&&a(Fn),_(je,s),s&&a(Qn),s&&a(E),s&&a(Rn),_(we,s),s&&a(Sn),s&&a(ha),s&&a(Hn),_(ve,s),s&&a(Wn),s&&a(ks),s&&a(Vn),_(be,s),s&&a(Bn),s&&a($s),s&&a(Gn),_(ye,s),s&&a(Un),s&&a(ls),_(ke),s&&a(Kn),s&&a(Es),s&&a(Yn),s&&a(ua),s&&a(Jn),_($e,s),s&&a(Xn),s&&a(ma),s&&a(Zn),_(qe,s),s&&a(sl),s&&a(ga),s&&a(el),s&&a(L),s&&a(al),_(Ee,s)}}}const Ic={local:"document-question-answering",sections:[{local:"load-the-data",title:"Load the data"},{local:"preprocess-the-data",sections:[{local:"preprocessing-document-images",title:"Preprocessing document images"},{local:"preprocessing-text-data",title:"Preprocessing text data"}],title:"Preprocess the data"},{local:"evaluation",title:"Evaluation"},{local:"train",title:"Train"},{local:"inference",title:"Inference"}],title:"Document Question Answering"};function zc(Pt){return Tc(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Sc extends $c{constructor(k){super();qc(this,k,zc,Oc,Ec,{})}}export{Sc as default,Ic as metadata};
