flatbuffer和protobuff
因为最近用到caffe和tensorflow lite,所以准备记录一下里面用到的两个概念flatbuffer/protobuff。protobuff
protobuff在caffe上使用很广泛,很多layer和loss等的定义都是用做的。
比如conv的定义:https://github.com/BVLC/caffe/blob/master/src/caffe/proto/caffe.proto#L592
所以通过caffe对模型进行修改等各种操作时,就很方便。
比如需要自定义一个新的layer:
# new concat layer
new_concat_layer = caffe_pb2.LayerParameter()
new_concat_layer.type = 'Concat'
new_concat_layer.name = 'Concat_' + bottoms
new_concat_layer.bottom.expand(bottoms)
new_concat_layer.top.expand(["expand" + layer.name])可以通过append和insert等插入prototxt中(之所以需要insert,使用过程中发现如果时前面引用过某些bottom或者top的值,而这些layer却在最后定义,那么caffe好像时无法解析的。)
model.insert(index, new_concat_layer)TODO: 后续补充一些概念(比如关键字的含义等)
https://github.com/protocolbuffers/protobuf/tree/master/python
三个关键字:require, optional, repeated.
https://colobu.com/2015/01/07/Protobuf-language-guide/#%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AA%E6%B6%88%E6%81%AF%E7%B1%BB%E5%9E%8B
flatbuffer
flatbuffer主要用到存储tflite模型格式的使用到,对其的深入了解时来源于想对tflite存储的模型内容一探究竟。
tflite模型schema定义在:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/schema/schema.fbs
定义的话跟protobuf一样,用table关键字定义。
比如conv的定义:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/schema/schema.fbs#L471
这个主要是理解tflite模型是如何存储的,tflite本来自带一个visualize.py的文件,可不太清楚如何使用,故直接暴力的方式装了flatbuffer,自己转到json来看。
以一个简单的模型举例子
# Define the model architecture
model = keras.Sequential([
keras.layers.InputLayer(input_shape=(28, 28)),
keras.layers.Reshape(target_shape=(28, 28, 1)),
keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu),
keras.layers.MaxPooling2D(pool_size=(2, 2)),
keras.layers.Flatten(),
keras.layers.Dense(10, activation=tf.nn.softmax)
])利用tflite工具转换到tflite模型后,通过命令export出可人理解的json数据。
可以input channel为1的conv被转换为dw conv后,其它的op都是一一对应的op,很多时候tf会做很多的优化,所以需要自己辨别一下。
其中subgraphs是定义的图结构,buffers是存放的数据。
subgraphs的结构:
op的定义,如reshape op和dw conv op:
另外可以看到tensor中是带量化参数的:
页:
[1]