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