Skip to content

Commit 3beb871

Browse files
authored
Multiple TF export improvements (ultralytics#4824)
* Add fused conv support * Set all saved_model values to non trainable * Fix TFLite fp16 model export * Fix int8 TFLite conversion
1 parent 6b44ecd commit 3beb871

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

export.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ def export_saved_model(model, im, file, dynamic,
145145
inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
146146
outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
147147
keras_model = keras.Model(inputs=inputs, outputs=outputs)
148+
keras_model.trainable = False
148149
keras_model.summary()
149150
keras_model.save(f, save_format='tf')
150151

@@ -183,15 +184,17 @@ def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('Te
183184

184185
print(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
185186
batch_size, ch, *imgsz = list(im.shape) # BCHW
186-
f = file.with_suffix('.tflite')
187+
f = str(file).replace('.pt', '-fp16.tflite')
187188

188189
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
189190
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
191+
converter.target_spec.supported_types = [tf.float16]
190192
converter.optimizations = [tf.lite.Optimize.DEFAULT]
191193
if int8:
192194
dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
193195
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
194196
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
197+
converter.target_spec.supported_types = []
195198
converter.inference_input_type = tf.uint8 # or tf.int8
196199
converter.inference_output_type = tf.uint8 # or tf.int8
197200
converter.experimental_new_quantizer = False
@@ -249,7 +252,7 @@ def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
249252
# Load PyTorch model
250253
device = select_device(device)
251254
assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
252-
model = attempt_load(weights, map_location=device, inplace=True, fuse=not any(tf_exports)) # load FP32 model
255+
model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
253256
nc, names = model.nc, model.names # number of classes, class names
254257

255258
# Input

models/tf.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,9 @@ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
7070
# see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
7171

7272
conv = keras.layers.Conv2D(
73-
c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False,
74-
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()))
73+
c2, k, s, 'SAME' if s == 1 else 'VALID', use_bias=False if hasattr(w, 'bn') else True,
74+
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
75+
bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
7576
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
7677
self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
7778

0 commit comments

Comments
 (0)