Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/core/leras/layers/InstanceNorm2D.py
628 views
1
from core.leras import nn
2
tf = nn.tf
3
4
class InstanceNorm2D(nn.LayerBase):
5
def __init__(self, in_ch, dtype=None, **kwargs):
6
self.in_ch = in_ch
7
8
if dtype is None:
9
dtype = nn.floatx
10
self.dtype = dtype
11
12
super().__init__(**kwargs)
13
14
def build_weights(self):
15
kernel_initializer = tf.initializers.glorot_uniform(dtype=self.dtype)
16
self.weight = tf.get_variable("weight", (self.in_ch,), dtype=self.dtype, initializer=kernel_initializer )
17
self.bias = tf.get_variable("bias", (self.in_ch,), dtype=self.dtype, initializer=tf.initializers.zeros() )
18
19
def get_weights(self):
20
return [self.weight, self.bias]
21
22
def forward(self, x):
23
if nn.data_format == "NHWC":
24
shape = (1,1,1,self.in_ch)
25
else:
26
shape = (1,self.in_ch,1,1)
27
28
weight = tf.reshape ( self.weight , shape )
29
bias = tf.reshape ( self.bias , shape )
30
31
x_mean = tf.reduce_mean(x, axis=nn.conv2d_spatial_axes, keepdims=True )
32
x_std = tf.math.reduce_std(x, axis=nn.conv2d_spatial_axes, keepdims=True ) + 1e-5
33
34
x = (x - x_mean) / x_std
35
x *= weight
36
x += bias
37
38
return x
39
40
nn.InstanceNorm2D = InstanceNorm2D
41