File size: 2,873 Bytes
70e6a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""Extract citations from UTF-8 bytes aligned to the original character positions."""

import numpy as np
import torch
from torch import nn

from shared.bibform_trial import trim_whitespace_boundaries
from shared.bibform_trial_model import TrialBIO,utf8_character_ids
from shared.range_extraction import position_features


WIDTH = 144
DEPTH = 8


def pack_bytes(rows,device):
    lengths = [len(row['text']) for row in rows]
    if not lengths or min(lengths)==0:
        raise ValueError('byte_extractor_requires_nonempty_text')
    values = np.zeros((len(rows),max(lengths),4),dtype=np.int64)
    for index,row in enumerate(rows):
        values[index,:lengths[index]] = utf8_character_ids(row['text'])
    return torch.from_numpy(values).to(device),torch.tensor(lengths,device=device)


class CompactByteExtractor(nn.Module):
    def __init__(self,width=WIDTH,depth=DEPTH):
        super().__init__()
        self.width = width
        self.bytes = nn.Embedding(257,24,padding_idx=0)
        self.project = nn.Linear(4*24,width)
        self.local = nn.ModuleList(nn.Conv1d(width,width,3,padding=dilation,dilation=dilation)
                                   for dilation in (1,2,4))
        self.local_norm = nn.ModuleList(nn.LayerNorm(width) for _ in self.local)
        self.layers = nn.ModuleList(nn.TransformerEncoderLayer(
            width,6,dim_feedforward=2*width,dropout=.08,activation='gelu',batch_first=True,norm_first=True)
            for _ in range(depth))
        self.norm = nn.LayerNorm(width)
        self.head = TrialBIO(width=width,hidden_width=width,role_hidden_width=96,
                             structure='unrestricted',label_transitions=True,
                             transition_scale=.25,role_decoder='powerset',boundary_weight=2.3,
                             structural_loss='reference_mean')

    def encode(self,byte_ids,lengths):
        width = byte_ids.size(1)
        padding = torch.arange(width,device=byte_ids.device)[None,:]>=lengths[:,None]
        valid = ~padding[...,None]
        hidden = self.project(self.bytes(byte_ids).flatten(-2))*valid
        for convolution,norm in zip(self.local,self.local_norm,strict=True):
            local = torch.nn.functional.gelu(convolution(norm(hidden).transpose(1,2)).transpose(1,2))
            hidden = (hidden+local)*valid
        hidden = (hidden+.18*position_features(width,self.width,hidden.device)[None,...])*valid
        for layer in self.layers:
            hidden = layer(hidden,src_key_padding_mask=padding)*valid
        return self.norm(hidden)*valid

    @torch.inference_mode()
    def predict(self,rows,device):
        raw,lengths = pack_bytes(rows,device)
        features = self.encode(raw,lengths)
        return [trim_whitespace_boundaries(row['text'],result) for row,result in
                zip(rows,self.head.predict(features,lengths,rows),strict=True)]