NoteDance commited on
Commit
03d6ff2
·
verified ·
1 Parent(s): 561ad02

Upload Segformer.py

Browse files
Files changed (1) hide show
  1. Segformer.py +205 -0
Segformer.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ from tensorflow.keras.layers import Conv2d,LayerNormalization,ZeroPadding2D,UpSampling2D,Activation
3
+ from tensorflow.keras import Model
4
+ from einops import rearrange
5
+ from math import sqrt
6
+ from functools import partial
7
+
8
+ # helpers
9
+
10
+ def exists(val):
11
+ return val is not None
12
+
13
+ def cast_tuple(val, depth):
14
+ return val if isinstance(val, tuple) else (val,) * depth
15
+
16
+ # classes
17
+
18
+ class DsConv2d:
19
+ def __init__(self, dim_in, dim_out, kernel_size, padding, stride = 1, bias = True):
20
+ self.net = tf.keras.Sequential()
21
+ self.net.add(Conv2d(dim_in, kernel_size = kernel_size, strides = stride, use_bias = bias))
22
+ self.net.add(ZeroPadding2D(padding))
23
+ self.net.add(Conv2d(dim_out, kernel_size = 1, use_bias = bias))
24
+
25
+ def __call__(self, x):
26
+ return self.net(x)
27
+
28
+ class LayerNorm:
29
+ def __init__(self, dim, eps = 1e-5):
30
+ self.eps = eps
31
+ self.g = tf.Variable(tf.ones((1, dim, 1, 1)))
32
+ self.b = tf.Variable(tf.zeros((1, dim, 1, 1)))
33
+
34
+ def __call__(self, x):
35
+ std = tf.math.sqrt(tf.math.reduce_variance(x, axis=1, keepdims=True))
36
+ mean = tf.reduce_mean(x, axis= 1, keepdim = True)
37
+ return (x - mean) / (std + self.eps) * self.g + self.b
38
+
39
+ class PreNorm:
40
+ def __init__(self, dim, fn):
41
+ self.fn = fn
42
+ self.norm = LayerNormalization()
43
+
44
+ def __call__(self, x):
45
+ return self.fn(self.norm(x))
46
+
47
+ class EfficientSelfAttention:
48
+ def __init__(
49
+ self,
50
+ dim,
51
+ heads,
52
+ reduction_ratio
53
+ ):
54
+ self.scale = (dim // heads) ** -0.5
55
+ self.heads = heads
56
+
57
+ self.to_q = Conv2d(dim, 1, use_bias = False)
58
+ self.to_kv = Conv2d(dim * 2, reduction_ratio, strides = reduction_ratio, use_bias = False)
59
+ self.to_out = Conv2d(dim, 1, use_bias = False)
60
+
61
+ def __call__(self, x):
62
+ h, w = x.shape[1], x.shape[2]
63
+ heads = self.heads
64
+
65
+ q, k, v = (self.to_q(x), *tf.split(self.to_kv(x), num_or_size_splits=2, axis=-1))
66
+ q, k, v = map(lambda t: rearrange(t, 'b x y (h c) -> (b h) (x y) c', h = heads), (q, k, v))
67
+
68
+ sim = tf.einsum('b i d, b j d -> b i j', q, k) * self.scale
69
+ attn = tf.nn.softmax(sim)
70
+
71
+ out = tf.einsum('b i j, b j d -> b i d', attn, v)
72
+ out = rearrange(out, '(b h) (x y) c -> b x y (h c)', h = heads, x = h, y = w)
73
+ return self.to_out(out)
74
+
75
+ class MixFeedForward:
76
+ def __init__(
77
+ self,
78
+ dim,
79
+ expansion_factor
80
+ ):
81
+ hidden_dim = dim * expansion_factor
82
+ self.net = tf.keras.Sequential()
83
+ self.net.add(Conv2d(hidden_dim, 1))
84
+ self.net.add(DsConv2d(hidden_dim, hidden_dim, 3, padding = 1))
85
+ self.net.add(Activation('gelu'))
86
+ self.net.add(Conv2d(dim, 1))
87
+
88
+ def __call__(self, x):
89
+ return self.net(x)
90
+
91
+ class Unfold:
92
+ def __init__(self, kernel, stride, padding):
93
+ self.kernel = kernel
94
+ self.stride = stride
95
+ self.padding = padding
96
+ self.zeropadding2d = ZeroPadding2D(padding)
97
+
98
+ def __call__(self, x):
99
+ x = self.zeropadding2d(x)
100
+ x = tf.image.extract_patches(x, sizes=[1, self.kernel, self.kernel, 1], strides=[1, self.stride, self.stride, 1], rates=[1, 1, 1, 1], padding='VALID')
101
+ x = tf.reshape(x, (x.shape[0], -1, x.shape[-1]))
102
+ return x
103
+
104
+ class MiT:
105
+ def __init__(
106
+ self,
107
+ channels,
108
+ dims,
109
+ heads,
110
+ ff_expansion,
111
+ reduction_ratio,
112
+ num_layers
113
+ ):
114
+ stage_kernel_stride_pad = ((7, 4, 3), (3, 2, 1), (3, 2, 1), (3, 2, 1))
115
+
116
+ dims = (channels, *dims)
117
+ dim_pairs = list(zip(dims[:-1], dims[1:]))
118
+
119
+ self.stages = []
120
+
121
+ for (dim_in, dim_out), (kernel, stride, padding), num_layers, ff_expansion, heads, reduction_ratio in zip(dim_pairs, stage_kernel_stride_pad, num_layers, ff_expansion, heads, reduction_ratio):
122
+ get_overlap_patches = Unfold(kernel, stride, padding)
123
+ overlap_patch_embed = Conv2d(dim_out, 1)
124
+
125
+ layers = []
126
+
127
+ for _ in range(num_layers):
128
+ layers.append([
129
+ PreNorm(dim_out, EfficientSelfAttention(dim = dim_out, heads = heads, reduction_ratio = reduction_ratio)),
130
+ PreNorm(dim_out, MixFeedForward(dim = dim_out, expansion_factor = ff_expansion)),
131
+ ])
132
+
133
+ self.stages.append([
134
+ get_overlap_patches,
135
+ overlap_patch_embed,
136
+ layers
137
+ ])
138
+
139
+ def __call__(
140
+ self,
141
+ x,
142
+ return_layer_outputs = False
143
+ ):
144
+ h, w = x.shape[1], x.shape[2]
145
+
146
+ layer_outputs = []
147
+ for (get_overlap_patches, overlap_embed, layers) in self.stages:
148
+ x = get_overlap_patches(x)
149
+
150
+ num_patches = x.shape[-2]
151
+ ratio = int(sqrt((h * w) / num_patches))
152
+ x = rearrange(x, 'b (h w) c -> b h w c', h = h // ratio)
153
+
154
+ x = overlap_embed(x)
155
+ for (attn, ff) in layers:
156
+ x = attn(x) + x
157
+ x = ff(x) + x
158
+
159
+ layer_outputs.append(x)
160
+
161
+ ret = x if not return_layer_outputs else layer_outputs
162
+ return ret
163
+
164
+ class Segformer(Model):
165
+ def __init__(
166
+ self,
167
+ dims = (32, 64, 160, 256),
168
+ heads = (1, 2, 5, 8),
169
+ ff_expansion = (8, 8, 4, 4),
170
+ reduction_ratio = (8, 4, 2, 1),
171
+ num_layers = 2,
172
+ channels = 3,
173
+ decoder_dim = 256,
174
+ num_classes = 4
175
+ ):
176
+ super(Segformer, self).__init__()
177
+ dims, heads, ff_expansion, reduction_ratio, num_layers = map(partial(cast_tuple, depth = 4), (dims, heads, ff_expansion, reduction_ratio, num_layers))
178
+ assert all([*map(lambda t: len(t) == 4, (dims, heads, ff_expansion, reduction_ratio, num_layers))]), 'only four stages are allowed, all keyword arguments must be either a single value or a tuple of 4 values'
179
+
180
+ self.mit = MiT(
181
+ channels = channels,
182
+ dims = dims,
183
+ heads = heads,
184
+ ff_expansion = ff_expansion,
185
+ reduction_ratio = reduction_ratio,
186
+ num_layers = num_layers
187
+ )
188
+
189
+ self.to_fused = []
190
+ for i, dim in enumerate(dims):
191
+ to_fused = tf.keras.Sequential()
192
+ to_fused.add(Conv2d(decoder_dim, 1))
193
+ to_fused.add(UpSampling2D(2 ** i))
194
+ self.to_fused.append(to_fused)
195
+
196
+ self.to_segmentation = tf.keras.Sequential()
197
+ self.to_segmentation.add(Conv2d(decoder_dim, 1))
198
+ self.to_segmentation.add(Conv2d(num_classes, 1))
199
+
200
+ def __call__(self, x):
201
+ layer_outputs = self.mit(x, return_layer_outputs = True)
202
+
203
+ fused = [to_fused(output) for output, to_fused in zip(layer_outputs, self.to_fused)]
204
+ fused = tf.concat(fused, axis = -1)
205
+ return self.to_segmentation(fused)