-
Notifications
You must be signed in to change notification settings - Fork 2
/
attention.py
142 lines (131 loc) · 6.66 KB
/
attention.py
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
from keras import backend as K
from keras.engine.topology import Layer
from keras.layers import activations, initializers, regularizers, constraints, InputSpec
import numpy as np
import math
class Attention(Layer):
"""Just your regular densely-connected NN layer.
# Arguments
units: Positive integer, dimensionality of the output space.
activation: Activation function to use
(see [activations](../activations.md)).
If you don't specify anything, no activation is applied
(ie. "linear" activation: `a(x) = x`).
use_bias: Boolean, whether the layer uses a bias vector.
kernel_initializer: Initializer for the `kernel` weights matrix
(see [initializers](../initializers.md)).
bias_initializer: Initializer for the bias vector
(see [initializers](../initializers.md)).
kernel_regularizer: Regularizer function applied to
the `kernel` weights matrix
(see [regularizer](../regularizers.md)).
bias_regularizer: Regularizer function applied to the bias vector
(see [regularizer](../regularizers.md)).
activity_regularizer: Regularizer function applied to
the output of the layer (its "activation").
(see [regularizer](../regularizers.md)).
kernel_constraint: Constraint function applied to
the `kernel` weights matrix
(see [constraints](../constraints.md)).
bias_constraint: Constraint function applied to the bias vector
(see [constraints](../constraints.md)).
# Input shape
nD tensor with shape: `(batch_size, ..., input_dim)`.
The most common situation would be
a 2D input with shape `(batch_size, input_dim)`.
# Output shape
nD tensor with shape: `(batch_size, ..., units)`.
For instance, for a 2D input with shape `(batch_size, input_dim)`,
the output would have shape `(batch_size, units)`.
"""
def __init__(self, units,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
**kwargs):
if 'input_shape' not in kwargs and 'input_dim' in kwargs:
kwargs['input_shape'] = (kwargs.pop('input_dim'),)
super(Attention, self).__init__(**kwargs)
self.units = units
self.scaling = 1/math.sqrt(self.units)
self.activation = activations.get(activation)
self.use_bias = use_bias
self.kernel_initializer = initializers.get(kernel_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.activity_regularizer = regularizers.get(activity_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.input_spec = InputSpec(min_ndim=2)
self.supports_masking = True
self.input_spec = [InputSpec(min_ndim=3), InputSpec(min_ndim=3), InputSpec(min_ndim=3)]
def build(self, input_shape):
assert len(input_shape) >= 2
query_dim = input_shape[0][-1]
key_dim = input_shape[1][-1]
value_dim = input_shape[2][-1]
self.query_kernel = self.add_weight(shape=(query_dim, self.units),
initializer=self.kernel_initializer,
name='query_kernel',
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint)
self.key_kernel = self.add_weight(shape=(key_dim, self.units),
initializer=self.kernel_initializer,
name='key_kernel',
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint)
if self.use_bias:
self.query_bias = self.add_weight(shape=(self.units,),
initializer=self.bias_initializer,
name='query_bias',
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
self.key_bias = self.add_weight(shape=(self.units,),
initializer=self.bias_initializer,
name='key_bias',
regularizer=self.bias_regularizer,
constraint=self.bias_constraint)
else:
self.query_bias = None
self.key_bias = None
super(Attention, self).build(input_shape)
def call(self, inputs):
queries, keys, values = inputs
q = K.dot(queries, self.query_kernel)
k = K.dot(keys, self.key_kernel)
if self.use_bias:
q = K.bias_add(q, self.query_bias)
k = K.bias_add(k, self.key_bias)
if self.activation is not None:
q = self.activation(q)
weights = K.softmax(self.scaling*K.batch_dot(q, k, axes=[2,2]))
output = K.batch_dot(weights, values)
return output
def compute_output_shape(self, input_shape):
assert input_shape and len(input_shape) >= 2
assert input_shape[-1]
output_shape = list(input_shape[0])
output_shape[-1] = input_shape[2][-1]
return tuple(output_shape)
def get_config(self):
config = {
'units': self.units,
'activation': activations.serialize(self.activation),
'use_bias': self.use_bias,
'kernel_initializer': initializers.serialize(self.kernel_initializer),
'bias_initializer': initializers.serialize(self.bias_initializer),
'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),
'bias_regularizer': regularizers.serialize(self.bias_regularizer),
'activity_regularizer': regularizers.serialize(self.activity_regularizer),
'kernel_constraint': constraints.serialize(self.kernel_constraint),
'bias_constraint': constraints.serialize(self.bias_constraint)
}
base_config = super(Attention, self).get_config()
return dict(list(base_config.items()) + list(config.items()))