/
birealnet.py
177 lines (147 loc) · 5.99 KB
/
birealnet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
from typing import Optional, Sequence, Union
import larq as lq
import tensorflow as tf
from zookeeper import Field, factory
from larq_zoo.core import utils
from larq_zoo.core.model_factory import ModelFactory
@factory
class BiRealNetFactory(ModelFactory):
"""Implementation of [Bi-Real Net](https://arxiv.org/abs/1808.00278)"""
filters: int = Field(64)
input_quantizer = "approx_sign"
kernel_quantizer = "magnitude_aware_sign"
kernel_constraint = "weight_clip"
kernel_initializer: Union[tf.keras.initializers.Initializer, str] = Field(
"glorot_normal"
)
def residual_block(
self, x, double_filters: bool = False, filters: Optional[int] = None
) -> tf.Tensor:
assert not (double_filters and filters)
# Compute dimensions
in_filters = x.get_shape().as_list()[-1]
out_filters = filters or in_filters if not double_filters else 2 * in_filters
shortcut = x
if in_filters != out_filters:
shortcut = tf.keras.layers.AvgPool2D(2, strides=2, padding="same")(shortcut)
shortcut = tf.keras.layers.Conv2D(
out_filters,
(1, 1),
kernel_initializer=self.kernel_initializer,
use_bias=False,
)(shortcut)
shortcut = tf.keras.layers.BatchNormalization(momentum=0.8)(shortcut)
x = lq.layers.QuantConv2D(
out_filters,
(3, 3),
strides=1 if out_filters == in_filters else 2,
padding="same",
input_quantizer=self.input_quantizer,
kernel_quantizer=self.kernel_quantizer,
kernel_initializer=self.kernel_initializer,
kernel_constraint=self.kernel_constraint,
use_bias=False,
)(x)
x = tf.keras.layers.BatchNormalization(momentum=0.8)(x)
return tf.keras.layers.add([x, shortcut])
def build(self) -> tf.keras.models.Model:
# Layer 1
out = tf.keras.layers.Conv2D(
self.filters,
(7, 7),
strides=2,
kernel_initializer=self.kernel_initializer,
padding="same",
use_bias=False,
)(self.image_input)
out = tf.keras.layers.BatchNormalization(momentum=0.8)(out)
out = tf.keras.layers.MaxPool2D((3, 3), strides=2, padding="same")(out)
# Layer 2
out = self.residual_block(out, filters=self.filters)
# Layer 3 - 5
for _ in range(3):
out = self.residual_block(out)
# Layer 6 - 17
for _ in range(3):
out = self.residual_block(out, double_filters=True)
for _ in range(3):
out = self.residual_block(out)
# Layer 18
if self.include_top:
out = utils.global_pool(out)
out = tf.keras.layers.Dense(self.num_classes)(out)
out = tf.keras.layers.Activation("softmax", dtype="float32")(out)
model = tf.keras.Model(inputs=self.image_input, outputs=out, name="birealnet18")
# Load weights.
if self.weights == "imagenet":
# Download appropriate file
if self.include_top:
weights_path = utils.download_pretrained_model(
model="birealnet",
version="v0.3.0",
file="birealnet_weights.h5",
file_hash="6e6efac1584fcd60dd024198c87f42eb53b5ec719a5ca1f527e1fe7e8b997117",
)
else:
weights_path = utils.download_pretrained_model(
model="birealnet",
version="v0.3.0",
file="birealnet_weights_notop.h5",
file_hash="5148b61c0c2a1094bdef811f68bf4957d5ba5f83ad26437b7a4a6855441ab46b",
)
model.load_weights(weights_path)
elif self.weights is not None:
model.load_weights(self.weights)
return model
def BiRealNet(
*, # Keyword arguments only
input_shape: Optional[Sequence[Optional[int]]] = None,
input_tensor: Optional[utils.TensorType] = None,
weights: Optional[str] = "imagenet",
include_top: bool = True,
num_classes: int = 1000,
) -> tf.keras.models.Model:
"""Instantiates the Bi-Real Net architecture.
Optionally loads weights pre-trained on ImageNet.
```netron
birealnet-v0.3.0/birealnet.json
```
```summary
literature.BiRealNet
```
```plot-altair
/plots/birealnet.vg.json
```
# ImageNet Metrics
| Top-1 Accuracy | Top-5 Accuracy | Parameters | Memory |
| -------------- | -------------- | ---------- | ------- |
| 57.47 % | 79.84 % | 11 699 112 | 4.03 MB |
# Arguments
input_shape: Optional shape tuple, to be specified if you would like to use a
model with an input image resolution that is not (224, 224, 3).
It should have exactly 3 inputs channels.
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as
image input for the model.
weights: one of `None` (random initialization), "imagenet" (pre-training on
ImageNet), or the path to the weights file to be loaded.
include_top: whether to include the fully-connected layer at the top of the
network.
num_classes: optional number of classes to classify images into, only to be
specified if `include_top` is True, and if no `weights` argument is
specified.
# Returns
A Keras model instance.
# Raises
ValueError: in case of invalid argument for `weights`, or invalid input shape.
# References
- [Bi-Real Net: Enhancing the Performance of 1-bit CNNs With Improved
Representational Capability and Advanced Training
Algorithm](https://arxiv.org/abs/1808.00278)
"""
return BiRealNetFactory(
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
num_classes=num_classes,
).build()