Datasets:
File size: 7,199 Bytes
651b674 | 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 | """Window encoder, dialog context and parallel fact queries."""
import math
import torch
from torch import nn
from transformers import AutoModel
from .config import ATTRIBUTES, OBJECT_TYPES
from .temporal import TIME_FIELDS, TIME_KINDS
class FactSetNet(nn.Module):
def __init__(self, backbone, config, vocabulary):
super().__init__()
self.backbone = backbone
self.config = config
limit = getattr(backbone.config, "max_position_embeddings", None)
if limit is not None and config.max_length > limit:
raise ValueError(f"Window length {config.max_length} exceeds backbone limit {limit}")
hidden = config.hidden_size
self.projection = nn.Linear(backbone.config.hidden_size, hidden)
context_layer = nn.TransformerEncoderLayer(
hidden, config.attention_heads, hidden * 4, config.dropout,
batch_first=True, norm_first=True,
)
self.context = nn.TransformerEncoder(context_layer, 1, enable_nested_tensor=False)
decoder_layer = nn.TransformerDecoderLayer(
hidden, config.attention_heads, hidden * 4, config.dropout,
batch_first=True, norm_first=True,
)
self.decoder = nn.TransformerDecoder(decoder_layer, config.decoder_layers,
norm=nn.LayerNorm(hidden))
self.queries = nn.Embedding(config.queries, hidden)
self.classifiers = nn.ModuleDict({
"attribute": nn.Linear(hidden, len(ATTRIBUTES) + 1),
"polarity": nn.Linear(hidden, 2),
"object_type": nn.Linear(hidden, len(OBJECT_TYPES)),
"object": nn.Linear(hidden, len(vocabulary["objects"])),
"value": nn.Linear(hidden, len(vocabulary["values"])),
})
self.pointers = nn.ModuleDict({
name: nn.Linear(hidden, hidden) for name in (
"source", "source_start", "source_end", "object_start", "object_end",
"value_start", "value_end", "date_from", "date_to",
)
})
if config.date_encoder == 'linear':
self.date_projection = nn.Linear(3, hidden)
else:
from .date_candidates import DAY_BUCKETS,DATE_KINDS
self.date_day_embedding = nn.Embedding(DAY_BUCKETS,32,padding_idx=0)
self.date_weekday_embedding = nn.Embedding(8,8,padding_idx=0)
self.date_kind_embedding = nn.Embedding(len(DATE_KINDS),16,padding_idx=0)
self.date_projection = nn.Sequential(
nn.Linear(3+32+8+16+hidden,hidden),nn.GELU(),nn.Linear(hidden,hidden))
if config.temporal_spans:
for field in TIME_FIELDS:
self.classifiers[f"{field}_kind"] = nn.Linear(hidden, len(TIME_KINDS))
for boundary in ("start", "end"):
self.pointers[f"{field}_{boundary}"] = nn.Linear(hidden, hidden)
@classmethod
def pretrained(cls, config, vocabulary):
return cls(AutoModel.from_pretrained(config.backbone), config, vocabulary)
def date_memory(self, encoded, token_states, turn_states):
features=encoded['date_features'].to(token_states.dtype)
if self.config.date_encoder == 'nonlinear':
if self.config.date_span_features:
starts,ends=encoded['date_span_starts'],encoded['date_span_ends']
valid=(starts>=0)&(ends>=starts)
cs=torch.cat([token_states.new_zeros(1,token_states.shape[1]),token_states.cumsum(0)],0)
span=(cs[(ends+1).clamp_min(0)]-cs[starts.clamp_min(0)])/(ends-starts+1).clamp_min(1).unsqueeze(1)
span=span*valid.unsqueeze(1)
else:
# Keep the architecture and initial parameters identical to the
# span-enabled arm; ablate only the expression token features.
span=token_states.new_zeros(features.shape[0],token_states.shape[1])
features=torch.cat([features,
self.date_day_embedding(encoded['date_day_buckets']).to(features.dtype),
self.date_weekday_embedding(encoded['date_weekdays']).to(features.dtype),
self.date_kind_embedding(encoded['date_kinds']).to(features.dtype),span],-1)
states=self.date_projection(features)
turns=encoded['date_turns']
return states+turn_states[turns.clamp_min(0)]*(turns>=0).unsqueeze(1)
def forward(self, encoded):
hidden = self.projection(self.backbone(**encoded["inputs"]).last_hidden_state)
mapping = encoded["mapping"].flatten()
valid = mapping >= 0
token_states = hidden.new_zeros((encoded["num_tokens"], self.config.hidden_size))
token_states.index_add_(0, mapping[valid], hidden.flatten(0, 1)[valid])
counts = hidden.new_zeros(encoded["num_tokens"])
counts.index_add_(0, mapping[valid], hidden.new_ones(int(valid.sum())))
token_states = token_states / counts.clamp_min(1).unsqueeze(1)
positions = encoded["token_turns"]
content = positions >= 0
turn_states = hidden.new_zeros((encoded["num_turns"], self.config.hidden_size))
turn_states.index_add_(0, positions[content], token_states[content])
turn_counts = hidden.new_zeros(encoded["num_turns"])
turn_counts.index_add_(0, positions[content], hidden.new_ones(int(content.sum())))
turn_states = turn_states / turn_counts.clamp_min(1).unsqueeze(1)
# Absolute turn order remains available beyond the encoder window.
order = torch.arange(encoded["num_turns"], device=hidden.device).unsqueeze(1)
frequencies = torch.exp(torch.arange(0, self.config.hidden_size, 2,
device=hidden.device) *
(-math.log(10000.0) / self.config.hidden_size))
positional = torch.zeros_like(turn_states)
positional[:, 0::2] = torch.sin(order * frequencies)
positional[:, 1::2] = torch.cos(order * frequencies[:positional[:, 1::2].shape[1]])
turn_states = self.context((turn_states + positional).unsqueeze(0)).squeeze(0)
token_states = token_states + turn_states[positions.clamp_min(0)] * content.unsqueeze(1)
queries = self.decoder(self.queries.weight.unsqueeze(0),
token_states.unsqueeze(0)).squeeze(0)
output = {name: layer(queries) for name, layer in self.classifiers.items()}
date_turns = encoded["date_turns"]
date_states = self.date_memory(encoded,token_states,turn_states)
for name, pointer in self.pointers.items():
memory = token_states
if name == "source":
memory = turn_states
elif name.startswith("date_"):
memory = date_states
logits = pointer(queries) @ memory.T / math.sqrt(self.config.hidden_size)
if name.endswith(("_start", "_end")):
logits = logits.masked_fill(~content.unsqueeze(0), -1e4)
if name == "date_from":
logits = logits.masked_fill(encoded["date_features"][:, 2].bool(), -1e4)
output[name] = logits
return output
|