Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/core/leras/layers/DepthwiseConv2D.py
628 views
1
import numpy as np
2
from core.leras import nn
3
tf = nn.tf
4
5
class DepthwiseConv2D(nn.LayerBase):
6
"""
7
default kernel_initializer - CA
8
use_wscale bool enables equalized learning rate, if kernel_initializer is None, it will be forced to random_normal
9
"""
10
def __init__(self, in_ch, kernel_size, strides=1, padding='SAME', depth_multiplier=1, dilations=1, use_bias=True, use_wscale=False, kernel_initializer=None, bias_initializer=None, trainable=True, dtype=None, **kwargs ):
11
if not isinstance(strides, int):
12
raise ValueError ("strides must be an int type")
13
if not isinstance(dilations, int):
14
raise ValueError ("dilations must be an int type")
15
kernel_size = int(kernel_size)
16
17
if dtype is None:
18
dtype = nn.floatx
19
20
if isinstance(padding, str):
21
if padding == "SAME":
22
padding = ( (kernel_size - 1) * dilations + 1 ) // 2
23
elif padding == "VALID":
24
padding = 0
25
else:
26
raise ValueError ("Wrong padding type. Should be VALID SAME or INT or 4x INTs")
27
28
if isinstance(padding, int):
29
if padding != 0:
30
if nn.data_format == "NHWC":
31
padding = [ [0,0], [padding,padding], [padding,padding], [0,0] ]
32
else:
33
padding = [ [0,0], [0,0], [padding,padding], [padding,padding] ]
34
else:
35
padding = None
36
37
if nn.data_format == "NHWC":
38
strides = [1,strides,strides,1]
39
else:
40
strides = [1,1,strides,strides]
41
42
if nn.data_format == "NHWC":
43
dilations = [1,dilations,dilations,1]
44
else:
45
dilations = [1,1,dilations,dilations]
46
47
self.in_ch = in_ch
48
self.depth_multiplier = depth_multiplier
49
self.kernel_size = kernel_size
50
self.strides = strides
51
self.padding = padding
52
self.dilations = dilations
53
self.use_bias = use_bias
54
self.use_wscale = use_wscale
55
self.kernel_initializer = kernel_initializer
56
self.bias_initializer = bias_initializer
57
self.trainable = trainable
58
self.dtype = dtype
59
super().__init__(**kwargs)
60
61
def build_weights(self):
62
kernel_initializer = self.kernel_initializer
63
if self.use_wscale:
64
gain = 1.0 if self.kernel_size == 1 else np.sqrt(2)
65
fan_in = self.kernel_size*self.kernel_size*self.in_ch
66
he_std = gain / np.sqrt(fan_in)
67
self.wscale = tf.constant(he_std, dtype=self.dtype )
68
if kernel_initializer is None:
69
kernel_initializer = tf.initializers.random_normal(0, 1.0, dtype=self.dtype)
70
71
#if kernel_initializer is None:
72
# kernel_initializer = nn.initializers.ca()
73
74
self.weight = tf.get_variable("weight", (self.kernel_size,self.kernel_size,self.in_ch,self.depth_multiplier), dtype=self.dtype, initializer=kernel_initializer, trainable=self.trainable )
75
76
if self.use_bias:
77
bias_initializer = self.bias_initializer
78
if bias_initializer is None:
79
bias_initializer = tf.initializers.zeros(dtype=self.dtype)
80
81
self.bias = tf.get_variable("bias", (self.in_ch*self.depth_multiplier,), dtype=self.dtype, initializer=bias_initializer, trainable=self.trainable )
82
83
def get_weights(self):
84
weights = [self.weight]
85
if self.use_bias:
86
weights += [self.bias]
87
return weights
88
89
def forward(self, x):
90
weight = self.weight
91
if self.use_wscale:
92
weight = weight * self.wscale
93
94
if self.padding is not None:
95
x = tf.pad (x, self.padding, mode='CONSTANT')
96
97
x = tf.nn.depthwise_conv2d(x, weight, self.strides, 'VALID', data_format=nn.data_format)
98
if self.use_bias:
99
if nn.data_format == "NHWC":
100
bias = tf.reshape (self.bias, (1,1,1,self.in_ch*self.depth_multiplier) )
101
else:
102
bias = tf.reshape (self.bias, (1,self.in_ch*self.depth_multiplier,1,1) )
103
x = tf.add(x, bias)
104
return x
105
106
def __str__(self):
107
r = f"{self.__class__.__name__} : in_ch:{self.in_ch} depth_multiplier:{self.depth_multiplier} "
108
return r
109
110
nn.DepthwiseConv2D = DepthwiseConv2D
111