File size: 8,483 Bytes
19b8775 |
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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
"""
Pytorch implementation of basic sequence to Sequence modules.
"""
import logging
import torch
import torch.nn as nn
import math
import numpy as np
import stanza.models.common.seq2seq_constant as constant
logger = logging.getLogger('stanza')
class BasicAttention(nn.Module):
"""
A basic MLP attention layer.
"""
def __init__(self, dim):
super(BasicAttention, self).__init__()
self.linear_in = nn.Linear(dim, dim, bias=False)
self.linear_c = nn.Linear(dim, dim)
self.linear_v = nn.Linear(dim, 1, bias=False)
self.linear_out = nn.Linear(dim * 2, dim, bias=False)
self.tanh = nn.Tanh()
self.sm = nn.Softmax(dim=1)
def forward(self, input, context, mask=None, attn_only=False):
"""
input: batch x dim
context: batch x sourceL x dim
"""
batch_size = context.size(0)
source_len = context.size(1)
dim = context.size(2)
target = self.linear_in(input) # batch x dim
source = self.linear_c(context.contiguous().view(-1, dim)).view(batch_size, source_len, dim)
attn = target.unsqueeze(1).expand_as(context) + source
attn = self.tanh(attn) # batch x sourceL x dim
attn = self.linear_v(attn.view(-1, dim)).view(batch_size, source_len)
if mask is not None:
attn.masked_fill_(mask, -constant.INFINITY_NUMBER)
attn = self.sm(attn)
if attn_only:
return attn
weighted_context = torch.bmm(attn.unsqueeze(1), context).squeeze(1)
h_tilde = torch.cat((weighted_context, input), 1)
h_tilde = self.tanh(self.linear_out(h_tilde))
return h_tilde, attn
class SoftDotAttention(nn.Module):
"""Soft Dot Attention.
Ref: http://www.aclweb.org/anthology/D15-1166
Adapted from PyTorch OPEN NMT.
"""
def __init__(self, dim):
"""Initialize layer."""
super(SoftDotAttention, self).__init__()
self.linear_in = nn.Linear(dim, dim, bias=False)
self.sm = nn.Softmax(dim=1)
self.linear_out = nn.Linear(dim * 2, dim, bias=False)
self.tanh = nn.Tanh()
self.mask = None
def forward(self, input, context, mask=None, attn_only=False, return_logattn=False):
"""Propagate input through the network.
input: batch x dim
context: batch x sourceL x dim
"""
target = self.linear_in(input).unsqueeze(2) # batch x dim x 1
# Get attention
attn = torch.bmm(context, target).squeeze(2) # batch x sourceL
if mask is not None:
# sett the padding attention logits to -inf
assert mask.size() == attn.size(), "Mask size must match the attention size!"
attn.masked_fill_(mask, -constant.INFINITY_NUMBER)
if return_logattn:
attn = torch.log_softmax(attn, 1)
attn_w = torch.exp(attn)
else:
attn = self.sm(attn)
attn_w = attn
if attn_only:
return attn
attn3 = attn_w.view(attn_w.size(0), 1, attn_w.size(1)) # batch x 1 x sourceL
weighted_context = torch.bmm(attn3, context).squeeze(1) # batch x dim
h_tilde = torch.cat((weighted_context, input), 1)
h_tilde = self.tanh(self.linear_out(h_tilde))
return h_tilde, attn
class LinearAttention(nn.Module):
""" A linear attention form, inspired by BiDAF:
a = W (u; v; u o v)
"""
def __init__(self, dim):
super(LinearAttention, self).__init__()
self.linear = nn.Linear(dim*3, 1, bias=False)
self.linear_out = nn.Linear(dim * 2, dim, bias=False)
self.sm = nn.Softmax(dim=1)
self.tanh = nn.Tanh()
self.mask = None
def forward(self, input, context, mask=None, attn_only=False):
"""
input: batch x dim
context: batch x sourceL x dim
"""
batch_size = context.size(0)
source_len = context.size(1)
dim = context.size(2)
u = input.unsqueeze(1).expand_as(context).contiguous().view(-1, dim) # batch*sourceL x dim
v = context.contiguous().view(-1, dim)
attn_in = torch.cat((u, v, u.mul(v)), 1)
attn = self.linear(attn_in).view(batch_size, source_len)
if mask is not None:
# sett the padding attention logits to -inf
assert mask.size() == attn.size(), "Mask size must match the attention size!"
attn.masked_fill_(mask, -constant.INFINITY_NUMBER)
attn = self.sm(attn)
if attn_only:
return attn
attn3 = attn.view(batch_size, 1, source_len) # batch x 1 x sourceL
weighted_context = torch.bmm(attn3, context).squeeze(1) # batch x dim
h_tilde = torch.cat((weighted_context, input), 1)
h_tilde = self.tanh(self.linear_out(h_tilde))
return h_tilde, attn
class DeepAttention(nn.Module):
""" A deep attention form, invented by Robert:
u = ReLU(Wx)
v = ReLU(Wy)
a = V.(u o v)
"""
def __init__(self, dim):
super(DeepAttention, self).__init__()
self.linear_in = nn.Linear(dim, dim, bias=False)
self.linear_v = nn.Linear(dim, 1, bias=False)
self.linear_out = nn.Linear(dim * 2, dim, bias=False)
self.relu = nn.ReLU()
self.sm = nn.Softmax(dim=1)
self.tanh = nn.Tanh()
self.mask = None
def forward(self, input, context, mask=None, attn_only=False):
"""
input: batch x dim
context: batch x sourceL x dim
"""
batch_size = context.size(0)
source_len = context.size(1)
dim = context.size(2)
u = input.unsqueeze(1).expand_as(context).contiguous().view(-1, dim) # batch*sourceL x dim
u = self.relu(self.linear_in(u))
v = self.relu(self.linear_in(context.contiguous().view(-1, dim)))
attn = self.linear_v(u.mul(v)).view(batch_size, source_len)
if mask is not None:
# sett the padding attention logits to -inf
assert mask.size() == attn.size(), "Mask size must match the attention size!"
attn.masked_fill_(mask, -constant.INFINITY_NUMBER)
attn = self.sm(attn)
if attn_only:
return attn
attn3 = attn.view(batch_size, 1, source_len) # batch x 1 x sourceL
weighted_context = torch.bmm(attn3, context).squeeze(1) # batch x dim
h_tilde = torch.cat((weighted_context, input), 1)
h_tilde = self.tanh(self.linear_out(h_tilde))
return h_tilde, attn
class LSTMAttention(nn.Module):
r"""A long short-term memory (LSTM) cell with attention."""
def __init__(self, input_size, hidden_size, batch_first=True, attn_type='soft'):
"""Initialize params."""
super(LSTMAttention, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.batch_first = batch_first
self.lstm_cell = nn.LSTMCell(input_size, hidden_size)
if attn_type == 'soft':
self.attention_layer = SoftDotAttention(hidden_size)
elif attn_type == 'mlp':
self.attention_layer = BasicAttention(hidden_size)
elif attn_type == 'linear':
self.attention_layer = LinearAttention(hidden_size)
elif attn_type == 'deep':
self.attention_layer = DeepAttention(hidden_size)
else:
raise Exception("Unsupported LSTM attention type: {}".format(attn_type))
logger.debug("Using {} attention for LSTM.".format(attn_type))
def forward(self, input, hidden, ctx, ctx_mask=None, return_logattn=False):
"""Propagate input through the network."""
if self.batch_first:
input = input.transpose(0,1)
output = []
attn = []
steps = range(input.size(0))
for i in steps:
hidden = self.lstm_cell(input[i], hidden)
hy, cy = hidden
h_tilde, alpha = self.attention_layer(hy, ctx, mask=ctx_mask, return_logattn=return_logattn)
output.append(h_tilde)
attn.append(alpha)
output = torch.cat(output, 0).view(input.size(0), *output[0].size())
if self.batch_first:
output = output.transpose(0,1)
if return_logattn:
attn = torch.stack(attn, 0)
if self.batch_first:
attn = attn.transpose(0, 1)
return output, hidden, attn
return output, hidden
|