切分init_net

备注:原始的init加密过,不能直接使用,因此只能从源头寻找weights。幸运的是所有init_net和predict_net都采用了一种名叫proto的组织方式,所有我们学习一下proto.

'''
procedure
1. input the binary data and use the X_pd2.py to parse the binary data
2. save the structure and the parameters of each operator in a binary file.
3. read the produced binary file and test whether it is the same with the origianl binary file.
4. depend on the principle of partition to save the binary file.
'''
from caffe2.proto import caffe2_pb2 # it has the definition of message NetDef
import os
import sys
#1. 把控制台输出的内容写到特定文件里。

sys.stdout = open("mult-ops.txt", "w") 
CAFFE_MODELS = "/home/wujing/software/software/lib/python2.7/site-packages/caffe2/python/models"
MODEL = ['squeezenet', 'init_net.pb', 'predict_net.pb']

INIT_NET = os.path.join(CAFFE_MODELS, MODEL[0], MODEL[1])

#2.从NefDef中读取内容

PS: init_net和predict_net是用特定格式存储的二进制文件(X.pb),这些格式信息(称为Message)存储在了caffe2_pb2.py文件里。这个文件里有多种Message,init和predict与NetDef对应,下图是NefDef(简称ND)的结构信息。ND中有一个核心要素op,op本身也是一种Message,结构与ND类似。


#3. 核心操作

函数readOpList是拆分的核心步骤。上方右图是init_net转成明文后的结果,init_net由多个op构成,每个op都对应OperatorDef结果。因此,我们可以仿造init_net的结构特征定,制化我们的init_文件。具体过程如下:

def readOpList(init_netdef,num_layers):
   i = 0
   opslist = caffe2_pb2.NetDef()
#1.生成最外成的NetDef来承载内部的ops。
   for ops in init_netdef.op:#2.迭代init
      if i< num_layers:
         temp = opslist.op.add()
#3.向NetDef添加内容,只能先用一个变量承接.add()的调用结果,不能讲ops传入add()中
         temp.CopyFrom(ops)#4.将ops的内容复制到temp中,不能写成temp = ops,否者生成的定制文件格式是:op{} op{}。
      else:
         break
      i = i+1
   #print(opslist)# print可以在控制台输出oplist的明文
   result = opslist.SerializeToString()
#转化成二进制序列,注意:调用STS方法会直接转化oplist,函数返回结果是一个指针,不是有效的二进制序列。 这里一定要用result来承接序列化后的结果。
   return result
      
#1. read the binary data and put them into oplist
   
'''
1-1 import caffe2_pb2, it contains the definition of message NetDef which define
the structure of ops.
1-2 read the binary data of init_net into oplist
'''

#4.读取init_net文件

先创建一个对象,然后填入内容
oplist = caffe2_pb2.NetDef() #创建对象
with open(INIT_NET,"rb") as f:
   temp = f.read()
   oplist.ParseFromString(temp)#填入内容
   f.close()

#2. read the basic unit OperatorDef which is serialized as a string
result = readOpList(oplist)#获取二进制结果

#3. store the result of step 2 into a binary file
#DEST_FILE = "/home/wujing/matieral/project/test_prop/first_op.pb"
DEST_FILE = "/home/wujing/matieral/project/test_prop/string_res.txt"

#5.输入二进制结果

先判断是否存在目标文件,如果不存在,创建对应的文件;如果存在,写入内容。

if not os.path.exists(DEST_FILE):
   with open(DEST_FILE,'w+') as f:
      f.write('')
      f.close()   
with open(DEST_FILE,"wb") as f:
   f.write(result)
   f.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值