Skip to content

Commit a69782e

Browse files
committed
Sync.
1 parent 8ca746c commit a69782e

File tree

13 files changed

+223
-320
lines changed

13 files changed

+223
-320
lines changed

efficientdet/Det-AdvProp.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Det-AdvProp
2-
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google/automl/blob/master/efficientdet
3-
/det_advprop_tutorial.ipynb)
2+
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google/automl/blob/master/efficientdet/det_advprop_tutorial.ipynb)
43

54
[1] Xiangning Chen, Cihang Xie, Mingxing Tan, Li Zhang, Cho-Jui Hsieh, Boqing
65
Gong. CVPR 2021. Arxiv link: https://arxiv.org/abs/2103.13886
@@ -31,7 +30,7 @@ EfficientDet-D5 + Det-AdvProp + AA ([ckpt](https://storage.googleapis.com/cloud-
3130

3231
<sup>Unlike the vanilla EfficientDet that scales the image with mean and std,
3332
here we scale the input to the range of [-1, 1] to make it easier for performing
34-
adversarial attack. Please see [this Colab](??) for reproducing the
33+
adversarial attack. Please see [this Colab](https://github.com/google/automl/blob/master/efficientdet/det_advprop_tutorial.ipynb) for reproducing the
3534
results.</sup>
3635

3736
## 2. Robust Against Common Corruptions

efficientdet/det_advprop_tutorial.ipynb

Lines changed: 98 additions & 227 deletions
Large diffs are not rendered by default.

efficientdet/keras/efficientdet_keras.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,7 @@ def __init__(self,
668668
is_training_bn: True if we train the BatchNorm.
669669
act_type: String of the activation used.
670670
strategy: string to specify training strategy for TPU/GPU/CPU.
671+
name: string of name.
671672
**kwargs: other parameters.
672673
"""
673674
super().__init__(name=name, **kwargs)

efficientdet/keras/eval_tflite.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ def __init__(self, tflite_model_path, only_network=False):
8080
def run(self, image):
8181
"""Runs inference with Lite model."""
8282
interpreter = self.interpreter
83+
signature_fn = interpreter.get_signature_runner()
8384
input_details = self.input_details
8485
output_details = self.output_details
8586

@@ -88,12 +89,12 @@ def run(self, image):
8889
scale, zero_point = input_detail['quantization']
8990
image = image / scale + zero_point
9091
image = np.array(image, dtype=input_detail['dtype'])
91-
interpreter.set_tensor(input_detail['index'], image)
92-
interpreter.invoke()
92+
93+
output = signature_fn(images=image)
9394

9495
def get_output(idx):
9596
output_detail = output_details[idx]
96-
output_tensor = interpreter.get_tensor(output_detail['index'])
97+
output_tensor = output[f'output_{idx}']
9798
if output_detail['quantization'] != (DEFAULT_SCALE, DEFAULT_ZERO_POINT):
9899
# Dequantize the output
99100
scale, zero_point = output_detail['quantization']
@@ -105,14 +106,14 @@ def get_output(idx):
105106
if not self.only_network:
106107
# TFLite model with post-processing.
107108
# Four Outputs:
108-
# detection_boxes: a float32 tensor of shape [1, num_boxes, 4] with box
109-
# locations
110-
# detection_classes: a float32 tensor of shape [1, num_boxes]
111-
# with class indices
112-
# detection_scores: a float32 tensor of shape [1, num_boxes]
113-
# with class scores
114109
# num_boxes: a float32 tensor of size 1 containing the number of
115110
# detected boxes
111+
# detection_scores: a float32 tensor of shape [1, num_boxes]
112+
# with class scores
113+
# detection_classes: a float32 tensor of shape [1, num_boxes]
114+
# with class indices
115+
# detection_boxes: a float32 tensor of shape [1, num_boxes, 4] with box
116+
# locations
116117
return [get_output(i) for i in range(output_size)]
117118
else:
118119
# TFLite model only contains network without post-processing.

efficientdet/keras/segmentation.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ def main(_):
9090
validation_data=test_dataset,
9191
callbacks=[])
9292

93-
model.save_weights('./testdata/segmentation')
93+
model.save_weights(
94+
'./testdata/segmentation')
9495

9596
print(create_mask(model(tf.ones((1, 512, 512, 3)), False)))
9697

efficientdet/keras/util_keras.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
"""Common keras utils."""
1616
import collections
1717

18-
from typing import Text
18+
from typing import Optional, Text
1919
from absl import logging
2020
import tensorflow as tf
2121
import utils
@@ -32,7 +32,7 @@ def build_batch_norm(is_training_bn: bool,
3232
data_format: Text = 'channels_last',
3333
momentum: float = 0.99,
3434
epsilon: float = 1e-3,
35-
strategy: Text = None,
35+
strategy: Optional[Text] = None,
3636
name: Text = 'tpu_batch_normalization'):
3737
"""Build a batch normalization layer.
3838

efficientdet/model_inspect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ def convert_tr(self, graph_def, fetches):
429429
"""Convert to TensorRT."""
430430
from tensorflow.python.compiler.tensorrt import trt # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top
431431
converter = trt.TrtGraphConverter(
432-
nodes_blacklist=[t.split(':')[0] for t in fetches],
432+
nodes_denylist=[t.split(':')[0] for t in fetches],
433433
input_graph_def=graph_def,
434434
precision_mode=self.tensorrt)
435435
infer_graph = converter.convert()

efficientnetv2/datasets.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,11 @@ def dataset_parser(self, value):
328328
features['orig_image'] = tf.image.decode_image(image_bytes)
329329
return features, labels
330330

331+
def fetch_dataset(self, filename):
332+
buffer_size = (self.file_buffer_size_m or 8) * 1024 * 1024 # 8 MiB
333+
dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)
334+
return dataset
335+
331336
def make_source_dataset(self, index, num_hosts):
332337
"""See base class."""
333338
if self.data_dir == 'null' or not self.data_dir:
@@ -354,14 +359,9 @@ def make_source_dataset(self, index, num_hosts):
354359
if self.is_training and not self.cache:
355360
dataset = dataset.repeat()
356361

357-
def fetch_dataset(filename):
358-
buffer_size = (self.file_buffer_size_m or 8) * 1024 * 1024 # 8 MiB
359-
dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)
360-
return dataset
361-
362362
# Read the data from disk in parallel
363363
dataset = dataset.interleave(
364-
fetch_dataset,
364+
self.fetch_dataset,
365365
num_parallel_calls=tf.data.experimental.AUTOTUNE,
366366
deterministic=self.debug)
367367

efficientnetv2/effnetv2_model.py

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,7 @@ def __init__(self,
511511
Args:
512512
model_name: A string of model name.
513513
model_config: A dict of model configurations or a string of hparams.
514+
include_top: If True, include the top layer for classification.
514515
name: A string of layer name.
515516
516517
Raises:
@@ -581,17 +582,17 @@ def summary(self, input_shape=(224, 224, 3), **kargs):
581582
return model.summary()
582583

583584
def get_model_with_inputs(self, inputs, **kargs):
584-
model = tf.keras.Model(inputs=[inputs], outputs=self.call(inputs, training=True))
585-
return model
585+
model = tf.keras.Model(
586+
inputs=[inputs], outputs=self.call(inputs, training=True))
587+
return model
586588

587589
def call(self, inputs, training, with_endpoints=False):
588590
"""Implementation of call().
589591
590592
Args:
591593
inputs: input tensors.
592594
training: boolean, whether the model is constructed for training.
593-
features_only: build the base feature network only.
594-
single_out: If true, only return the single output.
595+
with_endpoints: If true, return a list of endpoints.
595596
596597
Returns:
597598
output tensors.
@@ -657,7 +658,7 @@ def get_model(model_name,
657658
pretrained=True,
658659
training=True,
659660
with_endpoints=False,
660-
**kargs):
661+
**kwargs):
661662
"""Get a EfficientNet V1 or V2 model instance.
662663
663664
This is a simply utility for finetuning or inference.
@@ -669,23 +670,29 @@ def get_model(model_name,
669670
pretrained: if true, download the checkpoint. If string, load the ckpt.
670671
training: If true, all model variables are trainable.
671672
with_endpoints: whether to return all intermedia endpoints.
673+
**kwargs: additional parameters for keras model, such as name=xx.
672674
673675
Returns:
674676
A single tensor if with_endpoints if False; otherwise, a list of tensor.
675677
"""
676-
net = EffNetV2Model(model_name, model_config, include_top)
678+
net = EffNetV2Model(model_name, model_config, include_top, **kwargs)
677679
net(tf.keras.Input(shape=(None, None, 3)),
678680
training=training,
679681
with_endpoints=with_endpoints)
680-
if pretrained is True:
682+
if pretrained is True: # pylint: disable=g-bool-id-comparison
683+
# pylint: disable=line-too-long
681684
# download checkpoint and set pretrained path. Supported models include:
682-
# efficientnetv2-s, efficientnetv2-m, efficientnetv2-l,
683-
# efficientnetv2-b0, efficientnetv2-b1, efficientnetv2-b2, efficientnetv2-b3,
684-
# efficientnet-b0, efficientnet-b1, efficientnet-b2, efficientnet-b3,
685-
# efficientnet-b4, efficientnet-b5, efficientnet-b6, efficientnet-b7, efficientnet-l2
686-
# More V2 ckpts: https://github.com/google/automl/tree/master/efficientnetv2
687-
# More V1 ckpts: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet
688-
url = f'https://storage.googleapis.com/cloud-tpu-checkpoints/efficientnet/v2/{model_name}.tgz'
685+
# efficientnetv2-s, efficientnetv2-m, efficientnetv2-l,
686+
# efficientnetv2-b0, efficientnetv2-b1, efficientnetv2-b2, efficientnetv2-b3,
687+
# efficientnet-b0, efficientnet-b1, efficientnet-b2, efficientnet-b3,
688+
# efficientnet-b4, efficientnet-b5, efficientnet-b6, efficientnet-b7,
689+
# efficientnet-l2
690+
# v2: https://github.com/google/automl/tree/master/efficientnetv2
691+
# v1: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet
692+
# pylint: enable=line-too-long
693+
694+
url = ('https://storage.googleapis.com/cloud-tpu-checkpoints/'
695+
f'efficientnet/v2/{model_name}.tgz')
689696
pretrained_ckpt = tf.keras.utils.get_file(model_name, url, untar=True)
690697
else:
691698
pretrained_ckpt = pretrained
@@ -695,4 +702,4 @@ def get_model(model_name,
695702
pretrained_ckpt = tf.train.latest_checkpoint(pretrained_ckpt)
696703
net.load_weights(pretrained_ckpt)
697704

698-
return net
705+
return net

efficientnetv2/infer.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# limitations under the License.
1414
# ==============================================================================
1515
"""A simple example on how to use keras model for inference."""
16-
import copy
1716
import time
1817
from absl import app
1918
from absl import flags
@@ -22,12 +21,10 @@
2221
import tensorflow.compat.v1 as tf1
2322
import tensorflow_datasets as tfds
2423

25-
import datasets
26-
import effnetv2_configs
2724
import effnetv2_model
28-
import hparams
2925
import preprocessing
3026
import utils
27+
3128
FLAGS = flags.FLAGS
3229

3330

@@ -47,15 +44,6 @@ def define_flags():
4744
flags.DEFINE_bool('mixed_precision', False, 'If True, use mixed precision.')
4845

4946

50-
def get_config(model_name, dataset_cfg, hparam_str=''):
51-
"""Create a keras model for EffNetV2."""
52-
config = copy.deepcopy(effnetv2_configs.get_model_config(model_name))
53-
config.update(datasets.get_dataset_config(dataset_cfg))
54-
config.override(hparam_str, allow_new_keys=True)
55-
config.model.num_classes = config.data.num_classes
56-
return config
57-
58-
5947
def build_tf2_model():
6048
"""Build the tf2 model."""
6149
tf.config.run_functions_eagerly(FLAGS.debug)
@@ -65,10 +53,14 @@ def build_tf2_model():
6553
tf.keras.mixed_precision.set_global_policy(policy)
6654

6755
model = effnetv2_model.get_model(
68-
FLAGS.model_name, FLAGS.hparam_str, include_top=True, pretrained=FLAGS.model_dir or True)
56+
FLAGS.model_name,
57+
FLAGS.hparam_str,
58+
include_top=True,
59+
pretrained=FLAGS.model_dir or True)
6960
model.summary()
7061
return model
7162

63+
7264
def tf2_eval_dataset():
7365
"""Run TF2 benchmark and inference."""
7466
model = build_tf2_model()
@@ -131,8 +123,7 @@ def tf1_benchmark():
131123
with tf1.Session() as sess:
132124
model = effnetv2_model.EffNetV2Model(FLAGS.model_name, FLAGS.hparam_str)
133125
batch_size = FLAGS.batch_size
134-
run_options = tf1.RunOptions(
135-
trace_level=tf1.RunOptions.FULL_TRACE)
126+
run_options = tf1.RunOptions(trace_level=tf1.RunOptions.FULL_TRACE)
136127
run_metadata = tf1.RunMetadata()
137128
isize = FLAGS.image_size or model.cfg.eval.isize
138129
inputs = tf.ones((batch_size, isize, isize, 3), tf.float16)

0 commit comments

Comments
 (0)