import numpy from transformers import TokenClassificationPipeline class UniversalDependenciesPipeline(TokenClassificationPipeline): def __init__(self,**kwargs): super().__init__(**kwargs) x=self.model.config.label2id self.root=numpy.full((len(x)),numpy.nan) self.arc_start=numpy.full((len(x)),numpy.nan) self.arc_tail=numpy.full((len(x)),numpy.nan) for k,v in x.items(): if k.endswith("|root"): self.root[v]=0 elif k.endswith("-s"): self.arc_start[v]=0 elif k.endswith("-t"): self.arc_tail[v]=0 def _forward(self,model_inputs): import torch v=model_inputs["input_ids"][0].tolist() with torch.no_grad(): e=self.model(input_ids=torch.tensor([v+v[1:]*(len(v)-3)]).to(self.device)) return {"logits":e.logits,**model_inputs} def check_model_type(self,supported_models): pass def postprocess(self,model_outputs,**kwargs): if "logits" not in model_outputs: return "".join(self.postprocess(x,**kwargs) for x in model_outputs) m=model_outputs["logits"][0].cpu().numpy() w=len(model_outputs["input_ids"][0])-2 e=numpy.zeros((w,w,m.shape[-1])) for i in range(w): k=numpy.roll(m[i*(w+2)+1]+self.arc_tail,-1) for j in range(w): if i==j: e[i,i]=m[i*(w+1)+j+1]+self.root else: e[j,i]=m[i*(w+1)+j+1]+self.arc_start+k g=self.model.config.label2id["X|goeswith-s"] r=numpy.tri(e.shape[0]) for i in range(e.shape[0]): for j in range(i+2,e.shape[1]): r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1 e[:,:,g]+=numpy.where(r==0,0,numpy.nan) m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2) h=self.chu_liu_edmonds(m) z=[i for i,j in enumerate(h) if i==j] if len(z)>1: k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m) m[:,z]+=[[0 if j in z and (i!=j or i==k) else h for i in z] for j in range(m.shape[0])] h=self.chu_liu_edmonds(m) v=[(s,e) for s,e in model_outputs["offset_mapping"][0].tolist() if sb else b-1 for a,b in enumerate(h) if i!=a] v[i-1]=(v[i-1][0],v.pop(i)[1]) q.pop(i) elif v[i-1][1]>v[i][0]: h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a] v[i-1]=(v[i-1][0],v.pop(i)[1]) q.pop(i) t=model_outputs["sentence"].replace("\n"," ") u="# text = "+t+"\n" for i,(s,e) in enumerate(v): u+="\t".join([str(i+1),t[s:e],"_",q[i][0],"_","_" if len(q[i])<3 else "|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),"root" if q[i][-1]=="root" else q[i][-1][0:-2],"_","_" if i+1