MobileNetV2 - Importing weights from TensorFlow to ACL
Output of 'python ./tensorflow_data_extractor.py -m mobilenet_v2_1.0_224.ckpt -n mobilenet_v2_1.0_224.ckpt.meta':
WARNING:tensorflow:From ./tensorflow_data_extractor.py:38: The name tf.train.import_meta_graph is deprecated. Please use tf.compat.v1.train.import_meta_graph instead.
Traceback (most recent call last):
File "./tensorflow_data_extractor.py", line 38, in
Platform: x86_64, Tensorflow version 1.14.0
Operating System: Ubuntu 18.04
Problem description: I trying to import weights from a frozen MobileNetv2 tensorflow model to use in ACL. When I run the tensorflow_data_extractor.py I get the error as reported above.
I have also tried the tf_frozen_model_extractor.py from https://review.mlplatform.org/ml/ComputeLibrary, but it does not generate any weight files. The output I get is as follows
Output of 'python ./tf_frozen_model_extractor.py -m mobilenet_v2_1.0_224_frozen.pb -d output':
WARNING:tensorflow:From ./tf_frozen_model_extractor.py:34: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.
2019-08-30 11:32:28.229868: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3392300000 Hz
2019-08-30 11:32:28.230596: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55be23bcddb0 executing computations on platform Host. Devices:
2019-08-30 11:32:28.230620: I tensorflow/compiler/xla/service/service.cc:175] StreamExecutor device (0):
WARNING:tensorflow:From ./tf_frozen_model_extractor.py:41: calling import_graph_def (from tensorflow.python.framework.importer) with op_dict is deprecated and will be removed in a future version. Instructions for updating: Please file an issue at https://github.com/tensorflow/tensorflow/issues if you depend on this feature.
I have tried the solutions presented in [1] and [2], but it does not help. Has anyone successfully extracted weights fro mobilenetv2 to use it in ACL ?
[1] https://github.com/ARM-software/ComputeLibrary/issues/504 [2] https://github.com/ARM-software/ComputeLibrary/issues/517
Hi @yasirmahmoodqureshi
The script tf_frozen_model_extractor.py does not work with tensorflow 2.0.
I made some changes to the script to make it work with tensorflow 2.0, please see below:
import argparse
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
strings_to_remove=["read", ":0"]
permutations = { 1 : [0], 2 : [1, 0], 3 : [2, 1, 0], 4 : [3, 2, 0, 1]}
if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser('Extract TensorFlow net parameters')
parser.add_argument('-m', dest='modelFile', type=str, required=True, help='Path to TensorFlow frozen graph file (.pb)')
parser.add_argument('-d', dest='dumpPath', type=str, required=False, default='./', help='Path to store the resulting files.')
parser.add_argument('--nostore', dest='storeRes', action='store_false', help='Specify if files should not be stored. Used for debugging.')
parser.set_defaults(storeRes=True)
args = parser.parse_args()
# Create directory if not present
if not os.path.exists(args.dumpPath):
os.makedirs(args.dumpPath)
# Extract parameters
with tf.Graph().as_default() as graph:
with tf.compat.v1.Session() as sess:
print("Loading model.")
with tf.io.gfile.GFile(args.modelFile, 'rb') as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, input_map=None, return_elements=None, name="", producer_op_list=None)
print("Imported graph def")
for op in graph.get_operations():
for op_input in op.inputs:
# Skip non-const values/
if "Const" in op_input.name:
varname = op.name + '/' + op_input.name
print('varname:' +varname)
t = op_input.eval()
tT = t.transpose(permutations[len(t.shape)])
t = np.ascontiguousarray(tT)
for s in strings_to_remove:
varname = varname.replace(s, "")
if os.path.sep in varname:
varname = varname.replace(os.path.sep, '_')
print("Renaming variable {0} to {1}".format(op_input.name, varname))
# Store files
if args.storeRes:
print("Saving variable {0} with shape {1} ...".format(varname, t.shape))
np.save(os.path.join(args.dumpPath, varname), t)
I used the script mentioned above to export the weights from the model https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224.tgz
Please be aware that the new script does not match the filenames in the grap example: https://github.com/ARM-software/ComputeLibrary/blob/master/examples/graph_mobilenet_v2.cpp#L147
In get_weights_accessor(data_path, "Conv_weights.npy", DataLayout::NCHW), you will have to change it to get_weights_accessor(data_path, "MobilenetV2_Conv_Conv2D_Const_90.npy", DataLayout::NCHW),. You'll have to do the same for every accessor in the example.
Hope this helps.
Hi @morgolock thank you for your script code :)
I tried to extract weight from mobilenet_v2_1.0_224.tgz https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.0_224.tgz

and got weights by npy files.
but in graph_mobilenet_v2.cpp , as you mentioned , weight's names are different.
so I tried to update weights' path, but there is no batchnorm's weights. (only depthwise, no expansion, projection)

and the number of weight files and grpah layers does not correspond one-to-one.
How can I get solve this problem...
what I mentioned is these.
get_weights_accessor(data_path, "Conv_weights.npy", DataLayout::NCHW)
get_weights_accessor(data_path, "MobilenetV2_Conv_Conv2D_Const_90.npy", DataLayout::NCHW)
thx
Hi @yasirmahmoodqureshi
I think the problem is that the graph example in ACL was based in a different model from caffe2 and not the one from tflite.
The model in the capture (from pytorch) matches the names of the layers in the graph_mobilenet_v2.cpp

You could try exporting the weights from Caffe2 following the instructions in: https://arm-software.github.io/ComputeLibrary/v19.11.1/data_import.xhtml#caffe_how_to
Alternatively you could install pytroch, download the model and export the weights.
Let me know if you need help.
Hope this helps.
Closing this due to inactivity, please reopen if you still need help.