用tensorflow的layers.Layer模块改写class SelfAttention(nn.Module): def init(self,in_c,out_c,fm_sz,pos_bias = False): super(SelfAttention,self).init() self.w_q = nn.Conv2d(in_channels = in_c,out_channels = out_c,kernel_size = 1) self.w_k = nn.Conv2d(in_channels = in_c,out_channels = out_c,kernel_size = 1) self.w_v = nn.Conv2d(in_channels = in_c,out_channels = out_c,kernel_size = 1) self.pos_code = self.__getPosCode(fm_sz,out_c) self.softmax = nn.Softmax(dim = 2) self.pos_bias = pos_bias def __getPosCode(self,fm_sz,out_c): x = [] for i in range(fm_sz): x.append([np.sin,np.cos][i % 2](1 / (10000 ** (i // 2 / fm_sz)))) x = torch.from_numpy(np.array([x])).float() return torch.cat([(x + x.t()).unsqueeze(0) for i in range(out_c)]) def forward(self,x): q,k,v = self.w_q(x),self.w_k(x),self.w_v(x) pos_code = torch.cat([self.pos_code.unsqueeze(0) for i in range(x.shape[0])]).to(x.device) if self.pos_bias: att_map = torch.matmul(q,k.permute(0,1,3,2)) + pos_code else: att_map = torch.matmul(q,k.permute(0,1,3,2)) + torch.matmul(q,pos_code.permute(0,1,3,2)) am_shape = att_map.shape att_map = self.softmax(att_map.view(am_shape[0],am_shape[1],am_shape[2] * am_shape[3])).view(am_shape) return att_map * v
时间: 2024-01-15 10:04:55 浏览: 117
以下是使用tensorflow的layers.Layer模块改写的代码:
```
import tensorflow as tf
class SelfAttention(tf.keras.layers.Layer):
def __init__(self, in_c, out_c, fm_sz, pos_bias=False):
super(SelfAttention, self).__init__()
self.w_q = tf.keras.layers.Conv2D(filters=out_c, kernel_size=1, input_shape=[None, None, in_c])
self.w_k = tf.keras.layers.Conv2D(filters=out_c, kernel_size=1, input_shape=[None, None, in_c])
self.w_v = tf.keras.layers.Conv2D(filters=out_c, kernel_size=1, input_shape=[None, None, in_c])
self.pos_code = self.__getPosCode(fm_sz, out_c)
self.softmax = tf.keras.layers.Softmax(axis=2)
self.pos_bias = pos_bias
def __getPosCode(self, fm_sz, out_c):
x = []
for i in range(fm_sz):
x.append([np.sin, np.cos][i % 2](1 / (10000 ** (i // 2 / fm_sz))))
x = np.array([x], dtype=np.float32)
return tf.concat([(x + tf.transpose(x)).unsqueeze(0) for i in range(out_c)], axis=0)
def call(self, x):
q, k, v = self.w_q(x), self.w_k(x), self.w_v(x)
pos_code = tf.concat([self.pos_code[None, ...] for i in range(tf.shape(x)[0])], axis=0)
if self.pos_bias:
att_map = tf.matmul(q, tf.transpose(k, perm=[0, 1, 3, 2])) + pos_code
else:
att_map = tf.matmul(q, tf.transpose(k, perm=[0, 1, 3, 2])) + tf.matmul(q, tf.transpose(pos_code, perm=[0, 1, 3, 2]))
am_shape = tf.shape(att_map)
att_map = self.softmax(tf.reshape(att_map, [am_shape[0], am_shape[1], am_shape[2] * am_shape[3]]))
att_map = tf.reshape(att_map, am_shape)
return att_map * v
```
需要注意的是,tensorflow中没有nn.Module这个概念,而是使用tf.keras.layers.Layer作为基类。因此,我们需要在类定义中加入`tf.keras.layers.Layer`,并对一些函数名称进行修改。此外,tensorflow默认使用NHWC格式的数据,因此在调用transpose函数时需要加上perm参数进行转置,以保证维度的正确性。
阅读全文