File size: 11,884 Bytes
2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 a8ca4d3 2d0fc19 | 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | """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 ByteSlotContext(nn.Module):
def __init__(self, width: int, slots: int) -> None:
super().__init__()
rank = min(width, 48)
self.norm = nn.LayerNorm(width)
self.assignment = nn.Linear(width, slots, bias=False)
self.value = nn.Linear(width, rank, bias=False)
self.output = nn.Linear(rank, width, bias=False)
nn.init.zeros_(self.output.weight)
def forward(self, hidden: torch.Tensor, padding: torch.Tensor) -> torch.Tensor:
normalized = self.norm(hidden)
scores = self.assignment(normalized)
pooling = scores.transpose(1, 2).masked_fill(padding[:, None, :], -10000.).softmax(dim=-1)
summaries = pooling @ self.value(normalized)
context = scores.softmax(dim=-1) @ summaries
return hidden + self.output(context)
class ByteLayerFusion(nn.Module):
def __init__(self, width: int, layers: int) -> None:
super().__init__()
rank = 32
self.norm = nn.LayerNorm(width)
self.projections = nn.ModuleList(nn.Linear(width, rank, bias=False) for _ in range(layers))
self.gate = nn.Linear(width, rank, bias=False)
self.output = nn.Linear(rank, width, bias=False)
nn.init.zeros_(self.output.weight)
def forward(self, hidden: torch.Tensor, earlier: list[torch.Tensor]) -> torch.Tensor:
details = torch.stack([projection(self.norm(value))
for projection, value in zip(self.projections, earlier, strict=True)]).mean(dim=0)
gate = self.gate(self.norm(hidden)).sigmoid()
return hidden + self.output(torch.nn.functional.gelu(details) * gate)
class CompactByteExtractor(nn.Module):
def __init__(self, width=WIDTH, depth=DEPTH, *, character_buckets=0, context_buckets=0, global_presence=False,
residual_blend=None, parallel_tail=None, mask_convolution_padding=False, pooled_middle=None,
byte_context_slots: int = 0, byte_refinement_layers: int = 0,
byte_layer_taps: tuple[int, ...] = ()):
super().__init__()
self.width = width
self.mask_convolution_padding = mask_convolution_padding
self.anchor_depth = 0
self.residual_weight = 1.
self.primary_tail_end = 0
if residual_blend is not None:
self.anchor_depth = residual_blend['anchor_depth']
self.residual_weight = residual_blend['weight']
if not isinstance(self.anchor_depth, int) or not 0 < self.anchor_depth < depth or not 0 <= self.residual_weight <= 1:
raise ValueError('invalid_lite_residual_blend')
if parallel_tail is not None:
shared = parallel_tail['shared_layers']
weight = parallel_tail['weight']
if (residual_blend is not None or not isinstance(shared, int) or not 0 < shared < depth
or (depth - shared) % 2 or not 0 <= weight <= 1):
raise ValueError('invalid_lite_parallel_tail')
self.anchor_depth = shared
self.primary_tail_end = shared + (depth - shared) // 2
self.residual_weight = weight
self.bytes = nn.Embedding(257,24,padding_idx=0)
self.project = nn.Linear(4*24,width)
self.characters = nn.Embedding(character_buckets, 24) if character_buckets else None
self.character_projection = nn.Linear(24, width, bias=False) if character_buckets else None
self.character_context = nn.Embedding(context_buckets, 32) if context_buckets else None
self.context_projection = nn.Linear(32, width, bias=False) if context_buckets else None
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.pooled_middle = pooled_middle
if pooled_middle is not None:
if (len(pooled_middle) != 2 or any(type(index) is not int for index in pooled_middle)
or not 0 < pooled_middle[0] < pooled_middle[1] < depth or residual_blend is not None
or parallel_tail is not None or not mask_convolution_padding):
raise ValueError('invalid_pooled_byte_layers')
self.coarse_projection = nn.Linear(width, width, bias=False)
with torch.no_grad():
self.coarse_projection.weight.copy_(.5 * torch.eye(width))
self.norm = nn.LayerNorm(width)
if type(byte_context_slots) is not int or not 0 <= byte_context_slots <= 32:
raise ValueError('invalid_byte_context_slot_count')
self.slot_context = ByteSlotContext(width, byte_context_slots) if byte_context_slots else None
if type(byte_refinement_layers) is not int or not 0 <= byte_refinement_layers <= depth:
raise ValueError('invalid_byte_refinement_layer_count')
self.refinement_gates = nn.Parameter(torch.zeros(byte_refinement_layers)) if byte_refinement_layers else None
if (any(type(index) is not int or not 0 < index < depth for index in byte_layer_taps)
or tuple(sorted(set(byte_layer_taps))) != byte_layer_taps
or (byte_layer_taps and (pooled_middle is not None or parallel_tail is not None or residual_blend is not None))):
raise ValueError('invalid_byte_layer_taps')
self.layer_taps = byte_layer_taps
self.layer_fusion = ByteLayerFusion(width, len(byte_layer_taps)) if byte_layer_taps else None
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', global_presence=global_presence)
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))
if self.characters is not None or self.character_context is not None:
first, second, third, fourth = byte_ids.unbind(-1)
codes = first * 16777619 + second * 12582917 + third * 4256249 + fourth * 23
if self.characters is not None:
hidden = hidden + self.character_projection(self.characters(codes % self.characters.num_embeddings))
if self.character_context is not None:
hidden = hidden + self.context_projection(self.ngram_embeddings(codes))
hidden = hidden * valid
for convolution,norm in zip(self.local,self.local_norm,strict=True):
normalized = norm(hidden)
if self.mask_convolution_padding:
normalized = normalized.masked_fill(padding[..., None], 0.)
local = torch.nn.functional.gelu(convolution(normalized.transpose(1,2)).transpose(1,2))
hidden = (hidden+local)*valid
hidden = (hidden+.18*position_features(width,self.width,hidden.device)[None,...])*valid
if self.pooled_middle is not None:
return self.encode_with_pooled_middle(hidden, padding, lengths)
anchor = None
primary = None
earlier = []
for index, layer in enumerate(self.layers, 1):
hidden = layer(hidden,src_key_padding_mask=padding)*valid
if index in self.layer_taps:
earlier.append(hidden)
if index == self.anchor_depth:
anchor = hidden
if index == self.primary_tail_end:
primary, hidden = hidden, anchor
if primary is not None:
hidden = primary.lerp(hidden, self.residual_weight)
elif anchor is not None and self.residual_weight != 1.:
hidden = anchor.lerp(hidden, self.residual_weight)
if self.layer_fusion is not None:
hidden = self.layer_fusion(hidden, earlier) * valid
return self.finish(hidden, padding)
def encode_with_pooled_middle(self, hidden, padding, lengths):
start, end = self.pooled_middle
valid = (~padding).unsqueeze(-1)
for layer in self.layers[:start]:
hidden = layer(hidden, src_key_padding_mask=padding) * valid
fine = hidden
extended = torch.cat((hidden, torch.zeros_like(hidden[:, :1])), dim=1)
coarse_lengths = (lengths + 1) // 2
pair_end = torch.arange(extended[:, 1::2].size(1), device=hidden.device) * 2 + 1
two_characters = pair_end[None, :] < lengths[:, None]
coarse = (extended[:, :-1:2] + extended[:, 1::2]) / (1 + two_characters.unsqueeze(-1))
coarse_padding = torch.arange(coarse.size(1), device=hidden.device)[None, :] >= coarse_lengths[:, None]
anchor = coarse
for layer in self.layers[start:end]:
coarse = layer(coarse, src_key_padding_mask=coarse_padding) * (~coarse_padding).unsqueeze(-1)
change = self.coarse_projection(coarse - anchor).repeat_interleave(2, dim=1)
hidden = (fine + change[:, :fine.size(1)]) * valid
for layer in self.layers[end:]:
hidden = layer(hidden, src_key_padding_mask=padding) * valid
return self.finish(hidden, padding)
def finish(self, hidden, padding):
if self.refinement_gates is not None:
for gate, layer in zip(self.refinement_gates.unbind(), self.layers[-self.refinement_gates.numel():], strict=True):
refined = layer(hidden, src_key_padding_mask=padding)
hidden = hidden.lerp(refined, gate.tanh().to(hidden.dtype)) * (~padding).unsqueeze(-1)
if self.slot_context is not None:
hidden = self.slot_context(hidden, padding)
return self.norm(hidden) * (~padding).unsqueeze(-1)
def ngram_embeddings(self, codes):
edge = torch.zeros_like(codes[:, :1])
previous = torch.cat((edge, codes[:, :-1]), dim=1)
following = torch.cat((codes[:, 1:], edge), dim=1)
buckets = self.character_context.num_embeddings
preceding_pair = (previous * 16777619 + codes * 12582917) % buckets
following_pair = (codes * 16777619 + following * 12582917) % buckets
triple = (previous * 12582917 + codes * 4256249 + following * 16777619) % buckets
return (self.character_context(preceding_pair) + self.character_context(following_pair)
+ self.character_context(triple)) / 3
@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)]
|