FaceNet在FPGA等硬件平台上的实现

本文主要介绍将训练好的网络模型,移植到FPGA等硬件平台上所必须的准备工作。
不涉及具体的用C语言重新编写卷积操作、RAM存储等设计,本人做的只是辅助工作=-=。

项目简介

论文地址FaceNet: A Unified Embedding for Face Recognition and Clustering

将在服务器上训练好的FaceNet模型移植到FPGA等硬件平台上,实现人脸的检测推断过程。要想实现上述操作,必须先进行下面2个操作:

  1. 模型参数的提取:解析 FaceNet 的网络结构, Restore 训练好的模型,提取各网络层参数。
  2. 参数的量化压缩:模型参数量巨大(浮点),为了节省空间及方便计算,将参数量化为 8 位的
    定点数。

参数的提取

在提取参数前,我们先通过可视化工具Tensorboard解析了一下FaceNet的网络结构,它主要包含5个大模块:

block35

  1. Branch_0:32个$1 \times 1$卷积
  2. Branch_1:32个$1 \times 1$卷积、32个$3 \times 3$卷积
  3. Branch_2:32个$1 \times 1$卷积、32个$3 \times 3$卷积、32个$3 \times 3$卷积
  4. Mixed:将Branch_0、Branch_1和Branch_2连接起来
  5. Conv:32个$1 \times 1$卷积

block17

  1. Branch_0:128个$1 \times 1$卷积
  2. Branch_1:128个$1 \times 1$卷积、128个$1 \times 7$卷积、128个$7 \times 1$卷积
  3. Mixed:将Branch_0和Branch_1连接起来
  4. Conv:128个$1 \times 1$卷积

block8

  1. Branch_0:192个$1 \times 1$卷积
  2. Branch_1:192个$1 \times 1$卷积、192个$1 \times 3$卷积、192个$3 \times 1$卷积
  3. Mixed:将Branch_0和Branch_1连接起来
  4. Conv:192个$1 \times 1$卷积

reduction_a

  1. Branch_0:192个$3 \times 3$(stride=2)卷积
  2. Branch_1:192个$1 \times 1$卷积、256个$3 \times 3$卷积、384个$3 \times 3$(stride=2)卷积
  3. Branch_2:$3 \times 3$,步长为2的最大池化
  4. Mixed:将Branch_0、Branch_1和Branch_2连接起来

reduction_b

  1. Branch_0:256个$1 \times 1$卷积、384个$3 \times 3$(stride=2)卷积
  2. Branch_1:256个$1 \times 1$卷积、256个$3 \times 3$(stride=2)卷积
  3. Branch_2:256个$1 \times 1$卷积、256个$3 \times 3$卷积、256个$3 \times 3$(stride=2)卷积
  4. Branch_3:$3 \times 3$,步长为2的最大池化
  5. Mixed:将Branch_0、Branch_1、Branch_2和Branch_3连接起来

总的网络结构如下所示

  1. Conv2d_1a:32个$3 \times 3$,stride=2的卷积
  2. Conv2d_2a:32个$3 \times 3$的卷积
  3. Conv2d_2b:64个$3 \times 3$的卷积
  4. MaxPool_3a:$3 \times 3$,stride=2的最大池化
  5. Conv2d_3b:80个$1 \times 1$的卷积
  6. Conv2d_4a:192个$3 \times 3$的卷积
  7. Conv2d_4b:256个$3 \times 3$,stride=2的卷积
  8. repeat:5个block35模块
  9. Mixed_6a:1个reduction_a模块
  10. repeat1:10个block17模块
  11. Mixed_7a:1个reduction_b模块
  12. repeat2:5个block8模块
  13. block8:1个block8模块
  14. Logits:平均池化、flatten、Dropout

代码实现

代码中会用到float_to_bin()这一个量化函数,下面会有所介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os
from tensorflow.python import pywrap_tensorflow
import numpy as np
import math
import float_bin
import xiaoshu_bin
Max = 35.004695892333984 #参数的最大值
Min = -11.588409423828125 #参数最小值
Mean = -0.0007627065894155365 #参数均值

#导入模型
checkpoint_path = os.path.join('facenet_lmq/20170512-110547', "model-20170512-110547.ckpt-250000")
#读取模型参数
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
#获取参数中所有的key、value值
var_to_shape_map = reader.get_variable_to_shape_map()

#循环存储每一个key(tensor名字)对应的value
for key in var_to_shape_map:
par_name=str(key)
par_final_name =par_name.replace('/','_') #特殊字符替换
file_path = 'D:/PycharmProjects/faceface/bb/'+par_final_name+'.txt' #创建存储路径
par_shape=reader.get_tensor(key).shape # Tensor维度
par_value=reader.get_tensor(key).flatten() #value拉平,方便下面的量化操作
# print(type(par_value))
# print(par_value.shape)
list =[]
for index in range(len(par_value)): #对每一个tensor的value量化
par_value[index] =(par_value[index]-Mean)/(Max-Min) #归一化
if ('moving_variance' in par_name): # 特殊的tensor需要进行一些处理(BN)
# for index in range(len(par_value)):
par_value[index] = 1/(math.sqrt(par_value[index]))
list.append(float_bin.float_to_bin(par_value[index])) #调用量化函数float_to_bin()
np.savetxt(file_path,np.array(list),fmt='%s',header=str(par_shape)) #存储量化后的参数
print('done')
#print(type(par_value))

参数的量化压缩

训练得到的模型参数都是浮点型的,为了节省在硬件上的存储空间并加速计算,我们将参数量化到了8位的定点数。主要包含2个函数:float_to_bin()xiaoshu_bin()

  1. float_to_bin()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    import numpy as np
    import xiaoshu_bin
    import math
    def float_to_bin(innum,n):
    global innum_abs,res_nint_array
    list = []
    min = 2**(-n) #小数位取n位后,8位定点数能表示的最小值
    max = 2**(7-n)-min #小数位取n位后,8位定点数能表示的最大值
    innum_abs = abs(innum) #不管正负,都按正数处理
    if (innum_abs<min): #如果表示的数小于最小,按最小处理
    innum_abs = min
    if (innum_abs>max): #如果表示的数大于最大,按最大处理
    innum_abs =max
    nint = math.floor(innum_abs) #取整,分割小数部分和整数部分
    nf = innum_abs-nint #小数部分
    res_nint = bin(int(nint)).replace('0b','') #整数部分直接调用bin函数处理
    nint_num = len(res_nint) #整数部分的二进制表示占的位数长度
    res_nint_array =np.zeros(nint_num) #创建矩阵
    #print(nint_num)
    res_nf = xiaoshu_bin.xiaoshu(nf,n) #小数部分调用xiaoshu_bin()函数
    if (innum>=0): #原数为正数,二进制第一位为0
    c =0
    num_add =8-n-nint_num #除去小数位和整数位占的二进制位数后,还剩几位
    num_add =np.zeros(num_add) #补0
    for value in res_nint:
    res_nint_array[c] =int(value) #整数部分二进制
    c= c+1
    #@final =[num_add,res_nint_array,n,res_nf]
    else: #原数为负数,二进制第一位为1
    d =0
    num_add = 8-n-nint_num
    num_add = np.zeros(num_add)
    num_add[0] =1
    for value in res_nint:
    res_nint_array[d] =int(value)
    d= d+1
    #final = [num_add,res_nint_array,n,res_nf]
    final_bin =np.hstack((num_add,res_nint_array,res_nf)) #最终表示
    for bin_value in final_bin:
    list.append(str(int(bin_value))) #字符串输出
    final_bin_value =''.join(list)
    return final_bin_value
    #print(float_to_bin(-4.5,3))
  2. xiaoshu_bin()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    import numpy as np
    def xiaoshu(innum, n):
    global N
    N =n #小数部分占的位数
    count =0
    temp = innum
    reco =np.zeros(N) #创建全0矩阵

    if (innum>1) or (N==0): #不是小数
    print('Error!')
    return
    while(N): #未超过小数部分的位数
    count =count+1
    if (count>N):
    N = 0
    return reco
    temp =temp*2 #小数部分不断的乘2
    if (temp>1):
    reco[count-1] =1
    temp = temp-1
    elif (temp==1):
    reco[count-1] =1
    N =0
    else:
    reco[count-1] =0

    return (reco)
    #print(xiaoshu(0.0525,4))

量化结果展示

InceptionResnetV1/Block8/Branch_0/Conv2d_1x1/BatchNorm_beta这一tensor为例:

量化前后对比

------ 本文结束------
bluesliuf wechat
坚持技术分享,欢迎大家扫码交流!