import numpy from transformers import TokenClassificationPipeline class BellmanFordTokenClassificationPipeline(TokenClassificationPipeline): def __init__(self,**kwargs): super().__init__(**kwargs) x=self.model.config.label2id y=[k for k in x if k.find("|")<0 and not k.startswith("I-")] self.transition=numpy.full((len(x),len(x)),-numpy.inf) for k,v in x.items(): if k.find("|")<0: for j in ["I-"+k[2:]] if k.startswith("B-") else [k]+y if k.startswith("I-") else y: self.transition[v,x[j]]=0 def check_model_type(self,supported_models): pass def postprocess(self,model_outputs,**kwargs): if "logits" not in model_outputs: return self.postprocess(model_outputs[0],**kwargs) return self.bellman_ford_token_classification(model_outputs,**kwargs) def bellman_ford_token_classification(self,model_outputs,**kwargs): m=model_outputs["logits"][0].numpy() e=numpy.exp(m-numpy.max(m,axis=-1,keepdims=True)) z=e/e.sum(axis=-1,keepdims=True) for i in range(m.shape[0]-1,0,-1): m[i-1]+=numpy.max(m[i]+self.transition,axis=1) k=[numpy.argmax(m[0]+self.transition[0])] for i in range(1,m.shape[0]): k.append(numpy.argmax(m[i]+self.transition[k[-1]])) w=[{"entity":self.model.config.id2label[j],"start":s,"end":e,"score":z[i,j]} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s0: self.left_arc[v]=0 elif k.find("|r-")>0: self.right_arc[v]=0 def postprocess(self,model_outputs,**kwargs): import torch kwargs["aggregation_strategy"]="simple" if "logits" not in model_outputs: return self.postprocess(model_outputs[0],**kwargs) w=self.bellman_ford_token_classification(model_outputs,**kwargs) off=[(t["start"],t["end"]) for t in w] for i,(s,e) in reversed(list(enumerate(off))): if s0: d=d.lstrip() off[i]=(off[i][0]+j,off[i][1]) j=len(d)-len(d.rstrip()) if j>0: d=d.rstrip() off[i]=(off[i][0],off[i][1]-j) if d.strip()=="": off.pop(i) w.pop(i) v=self.tokenizer([t["text"] for t in w],add_special_tokens=False) x=[not t["entity_group"].endswith(".") for t in w] if len(x)<127: x=[True]*len(x) else: k=sum([len(x)-i+1 if b else 0 for i,b in enumerate(x)])+1 for i in numpy.argsort(numpy.array([t["score"] for t in w])): if x[i]==False and k+len(x)-i<8192: x[i]=True k+=len(x)-i+1 ids=[-1] for i in range(len(x)): if x[i]: ids.append(i) for j in range(i+1,len(x)): ids.append(j) ids.append(-1) with torch.no_grad(): e=self.model.get_input_embeddings().weight m=[] for j in v["input_ids"]: if j==[]: j=[self.tokenizer.unk_token_id] m.append(e[j,:].sum(axis=0)) m.append(e[self.tokenizer.sep_token_id,:]) m=torch.stack(m).to(self.device) e=self.model(inputs_embeds=torch.unsqueeze(m[ids,:],0)) m=e.logits[0].cpu().numpy() e=numpy.full((len(x),len(x),m.shape[-1]),m.min()) k=1 for i in range(len(x)): if x[i]: e[i,i]=m[k]+self.root k+=1 for j in range(1,len(x)-i): e[i+j,i]=m[k]+self.left_arc e[i,i+j]=m[k]+self.right_arc k+=1 k+=1 m,p=numpy.max(e,axis=2),numpy.argmax(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.argmax(m[z,z])],numpy.min(m)-numpy.max(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) q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)] t=model_outputs["sentence"].replace("\n"," ") u="# text = "+t+"\n" for i,(s,e) in enumerate(off): 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][2:],"_","_" if i+1