OpenLab-NLP commited on
Commit
0f46930
·
verified ·
1 Parent(s): 3fcbd4c

Create HyperConv1D.py

Browse files
Files changed (1) hide show
  1. HyperConv1D.py +64 -0
HyperConv1D.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class HyperConv1D(layers.Layer):
2
+ def __init__(self, d_model, k=7, mem_size=64, hyper_dim=128, dropout=0.0):
3
+ super().__init__()
4
+ assert k % 2 == 1
5
+ self.k = k
6
+ self.d_model = d_model
7
+ self.mem_size = mem_size
8
+
9
+ # Input projection
10
+ self.input_proj = layers.Dense(d_model, name="input_proj")
11
+
12
+ # Local depthwise conv
13
+ self.local_conv = layers.DepthwiseConv1D(kernel_size=k, padding='same', activation='silu')
14
+ self.local_proj = layers.Dense(d_model, name="local_proj")
15
+
16
+ # Hypernetwork: global -> scale vector
17
+ self.hyper = tf.keras.Sequential([
18
+ layers.Dense(hyper_dim, activation='gelu'),
19
+ layers.Dense(d_model)
20
+ ], name="hyper")
21
+
22
+ # Associative memory
23
+ self.mem_keys = self.add_weight((mem_size, d_model), initializer='glorot_uniform', trainable=True)
24
+ self.mem_vals = self.add_weight((mem_size, d_model), initializer='glorot_uniform', trainable=True)
25
+ self.mem_proj = layers.Dense(d_model)
26
+
27
+ self.norm = layers.LayerNormalization()
28
+ self.attn_pool = layers.Dense(1)
29
+
30
+ def call(self, x):
31
+ x_in = x
32
+ x_dtype = x.dtype # 입력 dtype 기억
33
+
34
+ # 1) input projection
35
+ x_proj = self.input_proj(x)
36
+ # memory와 연산 위해 dtype 통일
37
+ mem_dtype = self.mem_keys.dtype
38
+ x_proj = tf.cast(x_proj, mem_dtype)
39
+
40
+ # 2) local conv
41
+ out_local = self.local_conv(x_proj)
42
+ # hypernetwork scaling
43
+ global_z = self.attn_pool(x_proj)
44
+ global_z = tf.nn.softmax(global_z, axis=1)
45
+ global_z = tf.reduce_sum(x_proj * global_z, axis=1)
46
+
47
+ scale = tf.expand_dims(tf.nn.sigmoid(self.hyper(global_z)), 1)
48
+ out_local = out_local * scale
49
+ out_local = self.local_proj(out_local)
50
+
51
+
52
+ # 3) associative memory
53
+ sims = tf.matmul(x_proj, self.mem_keys, transpose_b=True) / tf.math.sqrt(tf.cast(self.d_model, mem_dtype))
54
+ attn = tf.nn.softmax(sims, axis=-1)
55
+ mem_read = tf.matmul(attn, self.mem_vals)
56
+ mem_read = self.mem_proj(mem_read)
57
+
58
+ # 4) fuse & residual
59
+ out = out_local + mem_read
60
+ out = self.norm(x_proj + out)
61
+ out = tf.nn.silu(out)
62
+
63
+ # 최종 출력 dtype 원래 입력 dtype으로 캐스트
64
+ return tf.cast(out, x_dtype)