"""原文の文字表現から範囲を直接予測する4方式。辞書や書式情報を使わない。""" import math import numpy as np import torch from torch import Tensor, nn from torch.nn import functional as F from shared.dataset_schema import FIELD_NAMES, validate_target, visible_value RANGE_TYPES=(*FIELD_NAMES,'person','organization','family','given') def gold_ranges(target: dict) -> list[tuple[int,int,int]]: result=[(RANGE_TYPES.index(f['label']),f['start'],f['end']-1) for f in target['fields']] for person in target['contributors']: result.append((RANGE_TYPES.index(person['kind']),person['start'],person['end']-1)) result.extend((RANGE_TYPES.index(k),v['start'],v['end']-1) for k,v in person['name_parts'].items()) return sorted(result,key=lambda r:(r[1],-r[2],r[0])) def position_features(length: int,width: int,device: torch.device) -> Tensor: positions=torch.arange(length,device=device).float()[:,None] frequency=torch.exp(torch.arange(0,width,2,device=device).float()*(-math.log(10000.)/width)) result=torch.zeros(length,width,device=device) result[:,0::2]=(positions*frequency).sin();result[:,1::2]=(positions*frequency).cos() return result def assignment(cost: np.ndarray) -> list[tuple[int,int]]: """各正解行を異なる予測列へ対応付ける最小費用割当。行数は列数以下。""" rows,columns=cost.shape if rows>columns:raise ValueError('not_enough_prediction_slots') u=np.zeros(rows+1);v=np.zeros(columns+1);p=np.zeros(columns+1,dtype=int);way=np.zeros(columns+1,dtype=int) for i in range(1,rows+1): p[0]=i;j0=0;minimum=np.full(columns+1,np.inf);used=np.zeros(columns+1,dtype=bool) while True: used[j0]=True;i0=p[j0] values=cost[i0-1]-u[i0]-v[1:] better=(values None: super().__init__();self.mode=mode self.norm=nn.LayerNorm(input_width) self.start=nn.Linear(input_width,64);self.end=nn.Linear(input_width,64) self.pair=nn.Parameter(torch.empty(len(RANGE_TYPES),65,65));nn.init.normal_(self.pair,std=.02) self.bias=nn.Parameter(torch.full((len(RANGE_TYPES),),-2.)) if mode=='query': self.memory=nn.Linear(input_width,128) self.queries=nn.Parameter(torch.randn(len(RANGE_TYPES),128)*.02) self.attention=nn.MultiheadAttention(128,4,batch_first=True) self.query_start=nn.Linear(128,64);self.query_end=nn.Linear(128,64) def forward(self,features: Tensor,lengths: Tensor) -> Tensor: x=self.norm(features);a=F.gelu(self.start(x));b=F.gelu(self.end(x)) if self.mode=='query': memory=self.memory(x);query=self.queries.unsqueeze(0).expand(len(x),-1,-1) mask=torch.arange(x.shape[1],device=x.device)[None,:]>=lengths[:,None] query=query+self.attention(query,memory,memory,key_padding_mask=mask,need_weights=False)[0] left=torch.einsum('blh,bch->bcl',a,self.query_start(query))/8 right=torch.einsum('blh,bch->bcl',b,self.query_end(query))/8 a=F.pad(a,(0,1),value=1);b=F.pad(b,(0,1),value=1) scores=torch.einsum('blh,chd,bmd->bclm',a,self.pair,b)/8+self.bias[None,:,None,None] if self.mode=='query':scores=scores+left[:,:,:,None]+right[:,:,None,:] positions=torch.arange(x.shape[1],device=x.device) valid=(positions[None,:] Tensor: scores=self(features,lengths) positive=torch.zeros_like(scores,dtype=torch.bool) for i,target in enumerate(targets): for label,start,end in gold_ranges(target):positive[i,label,start,end]=True positives=F.softplus(-scores[positive]).mean() negatives=scores.masked_fill(positive,-torch.inf).flatten(1) hard=negatives.topk(min(256,negatives.shape[1]),dim=1).values return positives+F.softplus(hard).mean() def extract(self,features: Tensor,lengths: Tensor,threshold: float) -> list[list[tuple[int,int,int,float]]]: scores=self(features,lengths);result=[] for values in scores: indices=(values>threshold).nonzero() selected=values[indices[:,0],indices[:,1],indices[:,2]] result.append([(int(c),int(a),int(b)+1,float(s)-threshold) for (c,a,b),s in zip(indices.cpu().tolist(),selected.cpu().tolist(),strict=True)]) return result class SetRangeHead(nn.Module): def __init__(self,input_width: int) -> None: super().__init__() self.memory=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,128)) self.queries=nn.Embedding(256,128) layer=nn.TransformerDecoderLayer(128,4,256,dropout=.1,batch_first=True) self.decoder=nn.TransformerDecoder(layer,2) self.types=nn.Linear(128,len(RANGE_TYPES)+1) self.start=nn.Linear(128,128);self.end=nn.Linear(128,128) def forward(self,features: Tensor,lengths: Tensor) -> tuple[Tensor,Tensor,Tensor]: memory=self.memory(features);length=memory.shape[1] memory=memory+position_features(length,128,memory.device)[None,:,:] # 1文字の外側項目と姓名が重なる最密な場合にも足りる枠数を確保する。 slots=max(64,2*length) indices=torch.arange(slots,device=memory.device) query=self.queries(indices%256)+position_features(slots,128,memory.device) query=query.unsqueeze(0).expand(len(memory),-1,-1) mask=torch.arange(length,device=memory.device)[None,:]>=lengths[:,None] query_mask=indices[None,:]>=torch.maximum(lengths*2,torch.full_like(lengths,64))[:,None] decoded=self.decoder(query,memory,memory_key_padding_mask=mask,tgt_key_padding_mask=query_mask) start=torch.einsum('bqh,blh->bql',self.start(decoded),memory)/math.sqrt(128) end=torch.einsum('bqh,blh->bql',self.end(decoded),memory)/math.sqrt(128) return self.types(decoded),start.masked_fill(mask[:,None,:],-torch.inf),end.masked_fill(mask[:,None,:],-torch.inf) def loss(self,features: Tensor,lengths: Tensor,targets: list[dict]) -> Tensor: types,start,end=self(features,lengths);type_gold=torch.full(types.shape[:2],len(RANGE_TYPES),device=types.device,dtype=torch.long) slots=torch.maximum(lengths*2,torch.full_like(lengths,64)) type_gold.masked_fill_(torch.arange(types.shape[1],device=types.device)[None,:]>=slots[:,None],-100) position_losses=[] for i,target in enumerate(targets): gold=torch.tensor(gold_ranges(target),device=types.device,dtype=torch.long) count=int(slots[i]) cost=-types[i,:count].softmax(-1)[:,gold[:,0]].T-1.5*(start[i,:count].log_softmax(-1)[:,gold[:,1]].T+end[i,:count].log_softmax(-1)[:,gold[:,2]].T) matched=assignment(cost.detach().cpu().numpy()) rows=torch.tensor([a for a,b in matched],device=types.device);columns=torch.tensor([b for a,b in matched],device=types.device) type_gold[i,columns]=gold[rows,0] position_losses.append(F.cross_entropy(start[i,columns],gold[rows,1])+F.cross_entropy(end[i,columns],gold[rows,2])) weights=torch.ones(len(RANGE_TYPES)+1,device=types.device);weights[-1]=.05 return F.cross_entropy(types.transpose(1,2),type_gold,weight=weights)+torch.stack(position_losses).mean() def extract(self,features: Tensor,lengths: Tensor,threshold: float) -> list[list[tuple[int,int,int,float]]]: types,start,end=self(features,lengths);result=[] for i in range(len(features)): count=max(64,2*int(lengths[i])) score,label=types[i,:count,:-1].max(-1);score=score-types[i,:count,-1] begins=start[i,:count].argmax(-1) positions=torch.arange(end.shape[-1],device=end.device) ends=end[i,:count].masked_fill(positions[None,:]threshold).nonzero().flatten() result.append([(int(label[j]),int(begins[j]),int(ends[j])+1,float(score[j])-threshold) for j in keep.cpu().tolist()]) return result class PointerRangeHead(nn.Module): def __init__(self,input_width: int) -> None: super().__init__();self.memory=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,128)) self.types=nn.Embedding(len(RANGE_TYPES)+2,128);self.recurrent=nn.GRU(128,128,batch_first=True) self.type_head=nn.Linear(128,len(RANGE_TYPES)+1);self.pointer=nn.Linear(128,128) self.initial=nn.Linear(128,128) def encoded(self,features: Tensor,lengths: Tensor) -> tuple[Tensor,Tensor,Tensor]: memory=self.memory(features)+position_features(features.shape[1],128,features.device)[None,:,:] mask=torch.arange(features.shape[1],device=features.device)[None,:]>=lengths[:,None] pooled=(memory*~mask[:,:,None]).sum(1)/lengths[:,None] return memory,mask,torch.tanh(self.initial(pooled))[None,:,:] def loss(self,features: Tensor,lengths: Tensor,targets: list[dict]) -> Tensor: memory,mask,initial=self.encoded(features,lengths) sequences=[[v for triple in gold_ranges(target) for v in triple]+[len(RANGE_TYPES)] for target in targets] count=max(map(len,sequences));batch=len(targets) inputs=memory.new_zeros(batch,count,128);inputs[:,0]=self.types.weight[len(RANGE_TYPES)+1] type_gold=torch.full((batch,count),-100,device=memory.device,dtype=torch.long) point_gold=torch.full_like(type_gold,-100) for i,sequence in enumerate(sequences): for t,value in enumerate(sequence): if t%3==0:type_gold[i,t]=value else:point_gold[i,t]=value if t+1btl',self.pointer(hidden),memory)/math.sqrt(128) points=points.masked_fill(mask[:,None,:],-torch.inf) return F.cross_entropy(types.transpose(1,2),type_gold)+F.cross_entropy(points.transpose(1,2),point_gold) def extract(self,features: Tensor,lengths: Tensor,threshold: float) -> list[list[tuple[int,int,int,float]]]: result=[] # 各引用の終了記号で止める。上限到達は明示的な出力失敗として返す。 for i in range(len(features)): length=int(lengths[i]);memory,mask,state=self.encoded(features[i:i+1,:length],lengths[i:i+1]) value=self.types.weight[len(RANGE_TYPES)+1][None,None,:];spans=[];ended=False for _ in range(2*length+1): hidden,state=self.recurrent(value,state);logits=self.type_head(hidden)[0,0] label=int(logits.argmax()) if label==len(RANGE_TYPES):ended=True;break confidence=float(logits[label]-logits[-1]);value=self.types.weight[label][None,None,:] hidden,state=self.recurrent(value,state) start=int((self.pointer(hidden)@memory.transpose(1,2)).argmax(-1)[0,0]);value=memory[:,start:start+1] hidden,state=self.recurrent(value,state) logits_end=(self.pointer(hidden)@memory.transpose(1,2))[0,0] logits_end[:start]=-torch.inf;end=int(logits_end.argmax()) item=(label,start,end+1,max(.001,confidence-threshold)) if confidence>threshold:spans.append(item) value=memory[:,end:end+1] if len(spans)>1 and spans[-1][:3] in [s[:3] for s in spans[:-1]]:break result.append(spans if ended else []) return result class BIORangeHead(nn.Module): needs_text=True def __init__(self,input_width: int) -> None: super().__init__() self.features=nn.Sequential(nn.LayerNorm(input_width),nn.Linear(input_width,192),nn.GELU()) self.outer=nn.Linear(192,31);self.names=nn.Linear(192,5) def forward(self,features: Tensor) -> list[Tensor]: hidden=self.features(features) return [self.outer(hidden),self.names(hidden)] def loss(self,features: Tensor,lengths: Tensor,targets: list[dict]) -> Tensor: from shared.dataset_schema import bio_labels from shared.span_tagger import OUTER_NAMES,NAME_NAMES gold=torch.full((len(targets),2,features.shape[1]),-100,device=features.device,dtype=torch.long) for i,target in enumerate(targets): outer=[(f['label'],f['start'],f['end']) for f in target['fields']]+[(p['kind'],p['start'],p['end']) for p in target['contributors']] names=[(k,v['start'],v['end']) for p in target['contributors'] for k,v in p['name_parts'].items()] gold[i,0,:int(lengths[i])]=torch.tensor(bio_labels(int(lengths[i]),outer,OUTER_NAMES),device=features.device) gold[i,1,:int(lengths[i])]=torch.tensor(bio_labels(int(lengths[i]),names,NAME_NAMES),device=features.device) scores=self(features) return sum(F.cross_entropy(score.transpose(1,2),gold[:,i]) for i,score in enumerate(scores)) def extract(self,features: Tensor,lengths: Tensor,threshold: float,texts: list[str]) -> list[list[tuple[int,int,int,float]]]: from shared.inference_strategies import structural_predictions from shared.span_tagger import EncodedCitation rows=[EncodedCitation(str(i),text,[0],[],[],[],None) for i,text in enumerate(texts)] predictions=structural_predictions(self(features),rows,1.,{'structure':'single_title'}) result=[] for prediction in predictions: spans=[(RANGE_TYPES.index(f['label']),f['start'],f['end'],1.) for f in prediction['fields']] for person in prediction['contributors']: spans.append((RANGE_TYPES.index(person['kind']),person['start'],person['end'],1.)) spans.extend((RANGE_TYPES.index(k),v['start'],v['end'],1.) for k,v in person['name_parts'].items()) result.append(spans) return result def build_range_head(architecture: str,input_width: int) -> nn.Module: if architecture in ('span','query'):return DenseRangeHead(input_width,architecture) if architecture=='bio':return BIORangeHead(input_width) if architecture=='set':return SetRangeHead(input_width) if architecture=='pointer':return PointerRangeHead(input_width) raise ValueError('unknown_range_architecture') def prediction_from_ranges(identifier: str,text: str,ranges: list[tuple[int,int,int,float]]) -> dict: """得点の高い非重複項目を選び、人物内の姓名を元の文字位置で組み立てる。""" unique={} for label,start,end,score in ranges: if 0<=start0: key=(label,start,end);unique[key]=max(score,unique.get(key,-math.inf)) outer=[(*key,score) for key,score in unique.items() if key[0]<15] by_end={} for candidate in outer:by_end.setdefault(candidate[2],[]).append(candidate) length=len(text);best=np.full((2,length+1),-np.inf);best[0,0]=0;trace={} for end in range(1,length+1): for title in (0,1):best[title,end]=best[title,end-1];trace[title,end]=(title,end-1,None) for label,start,stop,score in by_end.get(end,[]): for title in (0,1): if label==0 and title:continue next_title=int(title or label==0);value=best[title,start]+score if value>best[next_title,end]:best[next_title,end]=value;trace[next_title,end]=(title,start,(label,start,stop,score)) title=int(best[1,length]>best[0,length]);end=length;selected=[] while end: previous,start,item=trace[title,end] if item is not None:selected.append(item) title,end=previous,start result={'id':identifier,'fields':[],'contributors':[]} for label,start,end,score in sorted(selected,key=lambda r:r[1]): kind=RANGE_TYPES[label] if label<13:result['fields'].append({'label':kind,'start':start,'end':end,'value':visible_value(text[start:end],kind)});continue person={'kind':kind,'start':start,'end':end,'value':visible_value(text[start:end],'CONTRIBUTOR'),'name_parts':{}} if kind=='person': family=[None]+[(a,b,s) for (c,a,b),s in unique.items() if c==15 and start<=ag[0]:continue value=(f[2] if f else 0)+(g[2] if g else 0) if value>maximum:maximum=value;chosen=f,g for name,part in zip(('family','given'),chosen,strict=True): if part:person['name_parts'][name]={'start':part[0],'end':part[1],'value':visible_value(text[part[0]:part[1]],name)} if not person['name_parts']:person['name_parts']['family']={'start':start,'end':end,'value':visible_value(text[start:end],'family')} result['contributors'].append(person) validate_target(text,result) return result