SPDZ基础使用手册(深度学习视角)

news2024/9/21 4:38:39

基本类型

深度学习中最常使用的便是秘密定点数sfix,有关定点数的高级运算协议请参阅Paper: Secure Computation With Fixed-Point Numbers.

容器类型

SPDZ的深度学习框架主要基于TensorFlow实现,其中使用的容器是张量Tensor,在库中的定义如下:

def Tensor(cls, shape):
    """
    Type-dependent tensor of any dimension::

        a = sfix.Tensor([10, 10])
    """
    if len(shape) == 1:
        return Array(shape[0], cls)
    else:
        return MultiArray(shape, cls)

可以看出使用Tensor在大多数情况就是在使用MultiArray,类比Python基础类型的多维列表。

这里举一个例子:

a = sint.Tensor([3, 10, 10])    #创建张量,类型为sint,内容是3个10×10的矩阵
a[0].input_from(0)    #第一个矩阵从第0方读取数据
a[1].input_from(1)    #第二个矩阵从第1方读取数据
a[2][:] = a[0][:] * a[1][:]    #第三个矩阵由前两个矩阵元素对应相乘实现;[:] 表示选择这个矩阵的所有元素。

MultiArray的其它用法

assign(other, base=0)

        Assign container to content. Not implemented for floating-point.

                Parameters other – container of matching size and type

assign_all(value)

        Assign the same value to all entries.

                Parameters value – convertible to relevant basic type

assign_part_vector(vector, base=0)

        Assign vector from range of the first dimension, including all entries in further dimensions.

                Parameters

                        • vector – updated entries

                        • base – index in first dimension (regint/cint/int)

assign_vector(vector, base=0)

               Assign vector to content. Not implemented for floating-point.

                Parameters

                                • vector – vector of matching size convertible to relevant basic type

                                • base – compile-time (int)

direct_mul(other, reduce=True, indices=None, res_type=None)

        Matrix multiplication in the virtual machine. Unlike dot(), this only works for sint and sfix, and it returns a vector instead of a data structure.

                Parameters

                        • self Matrix / 2-dimensional MultiArray

                        • other Matrix / 2-dimensional MultiArray

                        • indices – 4-tuple of regint vectors for index selection (default is complete multiplication)

                Returns Matrix as vector of relevant type (row-major)

PS: 不常用,因为泛用性很差,只能针对二维数组;也是库里自带函数的通病,以至于很多tf的很多高级函数在库中都是不存在的。

dot(other, res_params=None, n_threads=None)

        Matrix-matrix and matrix-vector multiplication.

                Parameters

                • self – two-dimensional

                • other – Matrix or Array of matching size and type

                • n_threads – number of threads (default: all in same thread)

        Return type Matrix or Array of appropriate size and type

input_from(player, budget=None, raw=False, **kwargs)

        Fill with inputs from player if supported by type.

                Parameters player – public (regint/cint/int)

randomize(*args, n_threads=None)

        Randomize according to data type. If it is sfix, the following will sample an individual         uniformly random entry of the multi-array M roughly in the range [𝑎, 𝑏]:

M.randomize(a, b)

reveal()

        Reveal to MultiArray of same shape.

reveal_list()

        Reveal as list.

sort(key_indices=None, n_bits=None)

        Sort sub-arrays (different first index) in place. This uses radix sort.

                Parameters

                        • key_indices – indices to sorting keys, for example (1, 2) to sort three-dimensional array a by keys a[*][1][2]. Default is (0, ..., 0) of correct length.

                        • n_bits – number of bits in keys (default: global bit length)

…………

重要模块 - Compiler.library 

Compiler.library.do_while(loop_fn, g=None)

        Do-while loop. The loop is stopped if the return value is zero. It must be public. The following executes exactly once:

@do_while
def _():
    ...
    return regint(0)

Compiler.library.for_range(start, stop=None, step=None)

        Decorator to execute loop bodies consecutively. Arguments work as in Python range(), but         they can be any public integer. Information has to be passed out via container types such as         Array or using update(). Note that changing Python data structures such as lists within the         loop is not possible, but the compiler cannot warn about this.

                Parameters start/stop/step – regint/cint/int

PS: 勘误-默认参数应为stop,同Python中的 for i in range(stop)。

例:The following should output 10:

n = 10
a = sint.Array(n)
x = sint(0)
@for_range(n)
def _(i):
    a[i] = i
    x.update(x + 1)
print_ln('%s', x.reveal())

其它函数详情请参阅SPDZ手册。

…………

重要模块 - Compiler.mpc_math 

这块其实没啥好说的,库中都已经给了各种数学运算,直接调用就好,原理可以参阅源代码或相关论文。

重要模块 - Compiler.ml 

这块是使用SPDZ框架实现深度学习的关键,手册中直接举了几个机器学习的例子和现成的深度学习的例子,紧接着便是具体类的基和参数介绍。我们以一个深度学习的具体代码为例进行介绍。

# this trains a dense neural network on MNIST
# see https://github.com/csiro-mlai/mnist-mpc for data preparation
# 该代码在根目录的Programs/Source中

program.options_from_args()    #表示程序可以从外界(终端)获取输入

#SPDZ在0.3.7版本后有了torch导入数据的功能
if 'torch' in program.args:
    import torchvision
    data = []
    for train in True, False:
        ds = torchvision.datasets.MNIST(root='/tmp', train=train, download=True)
	# normalize to [0,1] before input
        samples = sfix.input_tensor_via(0, ds.data / 255., binary=True)
        labels = sint.input_tensor_via(0, ds.targets, binary=True, one_hot=True)
        data += [(labels, samples)]

    (training_labels, training_samples), (test_labels, test_samples) = data

#这里是正常读取处理好的数据集的方法
else:
    training_samples = sfix.Tensor([60000, 28, 28])    #为样本与标签设置存储结构
    training_labels = sint.Tensor([60000, 10])

    test_samples = sfix.Tensor([10000, 28, 28])
    test_labels = sint.Tensor([10000, 10])

    training_labels.input_from(0)    #读入数据,在根目录的Player-Data/Input-P0-0
    training_samples.input_from(0)

    test_labels.input_from(0)
    test_samples.input_from(0)    #注意导入的顺序

from Compiler import ml
tf = ml

#构建网络层,这里的层都是库中写好的,用法同tf
layers = [
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(128),
    tf.keras.layers.Activation('relu'),
    tf.keras.layers.Dense(10,  activation='softmax')
]

model = tf.keras.models.Sequential(layers)    #构建模型

optim = tf.keras.optimizers.SGD(momentum=0.9, learning_rate=0.01)    #选择优化器,设置参数

model.compile(optimizer=optim)    #编译

#Train model.
opt = model.fit(
    training_samples,
    training_labels,
    epochs=1,
    batch_size=128,
    validation_data=(test_samples, test_labels)
)

#Use model for prediction
guesses = model.predict(test_samples)

这是一段训练预测一体的代码,单独训练与预测也是可以的,只需要修改最后的代码。

目前使用这种模式的代码只可实现库中训练、库中保存秘密模型、使用库中训练好的模型预测,非常的不灵活;库中还提供了另一种模式的代码:

# this trains network D from SecureNN
# see https://github.com/csiro-mlai/mnist-mpc for data preparation
# 该代码在根目录的Programs/Source中

import ml
import math
import re
import util    #这里引用的应是Compiler中的包

program.options_from_args()
sfix.set_precision_from_args(program, True)
MultiArray.disable_index_checks()

#设置特征和标签数量
if 'profile' in program.args:
    print('Compiling for profiling')
    N = 1000
    n_test = 100
elif 'debug' in program.args:
    N = 100
    n_test = 100
elif 'debug1000' in program.args:
    N = 1000
    n_test = 1000
elif 'debug5000' in program.args:
    N = 5000
    n_test = 5000
else:
    N = 60000
    n_test = 10000

#deep-mpc库中有预处理数据集的方法,默认就是N = 60000,n_test = 10000
n_examples = N
n_features = 28 ** 2

try:    #设置轮数
    n_epochs = int(program.args[1])
except:
    n_epochs = 100

try:    #设置batch大小
    batch_size = int(program.args[2])
except:
    batch_size = N

assert batch_size <= N
ml.Layer.back_batch_size = batch_size

try:    #设置线程数
    ml.set_n_threads(int(program.args[3]))
except:
    pass

if program.options.ring:
    assert sfix.f * 4 == int(program.options.ring)

if 'stride1' in program.args:    #设置步长
    stride = (1, 1)
else:
    stride = (2, 2)

if 'valid' in program.args:    #设置padding方式
    padding = 'VALID'
    inner_dim = (28 - 4) // stride[0]
else:
    padding = 'SAME'
    inner_dim = 28 // stride[0]

layers = [    #层
    ml.FixConv2d([N, 28, 28, 1], (5, 5, 5, 1), (5,),
                 [N, inner_dim, inner_dim, 5], stride, padding),
    ml.Relu([N, inner_dim, inner_dim, 5]),
]

#填充层
if 'maxpool' in program.args:
    layers += [ml.MaxPool((N, inner_dim, inner_dim, 5))]
    inner_dim //= 2

n_inner = inner_dim ** 2 * 5

dropout = 'dropout' in program.args

if '1dense' in program.args:
    if dropout:
        layers += [ml.Dropout(N, n_inner)]
    layers += [ml.Dense(N, n_inner, 10),]
elif '2dense' in program.args:
    if dropout:
        layers += [ml.Dropout(N, n_inner)]
    layers += [
        ml.Dense(N, n_inner, 100),
        ml.Relu([N, 100]),
        ml.Dense(N, 100, 10),
    ]
    if dropout or 'dropout1' in program.args:
        layers.insert(-1, ml.Dropout(N, 100))
else:
    raise Exception('need to specify number of dense layers')

layers += [ml.MultiOutput(N, 10)]

Y = sint.Matrix(n_test, 10)    #存储测试集标签
X = sfix.Matrix(n_test, n_features)    #存储测试集特征

if not ('no_acc' in program.args and 'no_loss' in program.args):
    layers[-1].Y.input_from(0)    #读取训练集标签
    layers[0].X.input_from(0)    #读取训练集特征
    Y.input_from(0)    #读取测试集标签
    X.input_from(0)    #读取测试集特征

optim = ml.Optimizer.from_args(program, layers)    #外部读入优化器
optim.run_by_args(program, n_epochs, batch_size, X, Y)    #训练

FixConv2d参数:(input_shape, weight_shape, (out_channels,), output_shape, stride, padding)
#weight_shape:过滤器大小,就是滑动的那个框

Relu参数:([N, d, d_out])

MaxPool参数:(input_shape, pool_size, strides, padding))

Dense参数:(N, d_in, d_out)

Dropout参数:(N, d1, d2=1, alpha=0.5)       
#d1: 总维度,这通常表示特定层输入或输出的特征数量或维度。
#d2: 另一个维度,默认值为1。在某些场景下,如当需要将数据处理为三维结构(例如,在处理时间序列数据或具有多个特征映射的卷积层输出时),这个参数变得有用。
#alpha: 概率(必须是2的幂),表示每个神经元被置零的概率。默认值是0.5,意味着在每次前向传播时,有50%的概率每个神经元的输出会被置为0。

MultiOutput参数:(N, d_out)        #这一般就是最后一层了,d_out是最终分类数目

优化器

class Compiler.ml.Optimizer(layers=[], report_loss=None)

        Bases: object

        Base class for graphs of layers.

        backward(**kwargs)

                Compute backward propagation.

        eval(**kwargs)

                Compute evaluation after training.

                        Parameters

                                • data – sample data (Compiler.types.Matrix with one row per sample)

                                • top – return top prediction instead of probability distribution

                        Returns sfix/sint Array (depening on top)

class Compiler.ml.SGD(layers, n_epochs=1, debug=False, report_loss=None)

        Bases: Compiler.ml.Optimizer

        Stochastic gradient descent.

                Parameters

                        • layers – layers of linear graph

                        • n_epochs – number of epochs for training

                        • report_loss – disclose and print loss

        backward(**kwargs)

                Compute backward propagation.

        eval(**kwargs)

                Compute evaluation after training.

                Parameters

                        • data – sample data (Compiler.types.Matrix with one row per sample)

                        • top – return top prediction instead of probability distribution

                Returns sfix/sint Array (depening on top)

run/run_in_batches/run_by_args 皆是进行训练,通过run_by_args的参数可知,顺便它也能进行预测。(源码太长不再放这里了,仅简单介绍一下整个函数:)

run_by_args(self, program, n_runs, batch_size, test_X, test_Y,
                    acc_batch_size=None)

主要逻辑和功能 - run_by_args

  1. 参数解析: 方法首先解析program.args中的参数,如学习率(gamma), 折旧率(depreciation), 动量(momentum), 是否打印损失(print_losses)等。

  2. 动态配置: 根据提供的参数动态调整训练和评估配置,如是否使用动量(nomom), 是否记录每层的时间(time_layers), 是否在训练之前首先进行模型评估(acc_first), 以及是否对卷积操作进行特定的处理(full_cisc).

  3. 训练和评估: 根据n_runs参数指定的次数,执行训练循环。在每次循环中,根据配置执行前向传播(forward), 反向传播(backward), 和参数更新(update). 如果设置了测试集(test_Xtest_Y), 也会执行测试集上的评估,并计算准确率和损失。

  4. 特殊条件处理: 支持特殊的命令行参数来执行一些特定操作,如one_iter用于执行一次完整的前向和反向传播并打印权重,bench1bench10用于性能基准测试。

  5. 学习率调整: 如果检测到模型发散(crash)或准确率低于阈值,学习率(gamma)会减半以尝试恢复训练。此外,如果设置了折旧率(depreciation), 学习率将按该比率递减。

  6. 输出权重: 如果指定了model_output, 最后会输出模型的权重。

注意:这种模式的代码编译时要加额外的参数,具体的参数请参阅csiro-mlai/deep-mpc (github.com)中的common.sh第69行。这里给一个具体的例子:

#原运行命令
./run-local.sh emul D prob 2 2 64    
 
#实际编译命令(实际上原命令包括编译与运行)
python3 ./compile.py -R 64 -K '' -CD mnist_full_D 2 128 2 trunc_pr f64 k127 2dense | grep -v WARNING   

(未完待续)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1553179.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何提bug?

很多公司都有提bug的标准&#xff0c;对于新人刚介入测试行业时&#xff0c;提bug的时候&#xff0c;描述的清晰与否就很重要&#xff0c;那一个很明朗清晰的bug应该包含那些呢&#xff1f; bug包含的要素有那些&#xff1f;&#xff08;以jira工具为例&#xff09; 1、项目名…

Parade Series - SVG Resource

iconfont https://www.iconfont.cn/?spma313x.search_index.i3.2.74e53a819tkkcG音符 <div class"form-group"><a href"Javascript:reload();" class"btn btn-icon btn-outline-light btn-block" style";"><svg t&q…

docker logs 查找日志常用命令

docker logs 是什么 docker logs 是 Docker 命令行工具提供的一个命令&#xff0c;用于查看容器的日志输出。它可以显示容器在运行过程中生成的标准输出&#xff08;stdout&#xff09;和标准错误输出&#xff08;stderr&#xff09;&#xff0c;帮助用户诊断容器的行为和排查…

Spring boot 发送文本邮件 和 html模板邮件

Spring boot 发送文本邮件 和 html模板邮件 提示&#xff1a;这里使用 spring-boot-starter-mail 发送文本邮件 和 html模板邮件 文章目录 Spring boot 发送文本邮件 和 html模板邮件一、开启QQ邮箱里的POP3/SMTP服务①&#xff1a;开启步骤 二、简单配置①&#xff1a;引入依赖…

【Linux 驱动基础】Linux platform平台设备驱动

# 前置知识 总线驱动模型简介&#xff1a; 总线是处理器与一个或者多个设备之间的通道&#xff0c;在设备模型中&#xff0c;所有的设备都是通过总线相连&#xff0c;当然也包括虚拟的 platform 平台总线。 总线驱动模型中有三要素&#xff1a; 1. 总线 /*** struct bus_ty…

RTSP应用:实现视频流的实时推送

在实现实时视频流推送的项目中&#xff0c;RTSP&#xff08;Real Time Streaming Protocol&#xff09;协议扮演着核心角色。本文将指导你通过安装FFmpeg软件&#xff0c;下载并编译live555&#xff0c;以及配置ffmpeg进行视频流推送&#xff0c;来实现一个基本的RTSP流媒体服务…

05-JavaScript对象

1. 对象 1.1 对象的相关概念 什么是对象&#xff1f; 在 JavaScript 中&#xff0c;对象是一组无序的相关属性和方法的集合&#xff0c;所有的事物都是对象&#xff0c;例如字符串、数值、数组、函数等。 对象是由属性和方法组成的。 属性&#xff1a;事物的特征&#xff0c;…

Fantasy Forest Environment

此包包含120多个预制件,您需要创建风格化的森林环境:从树木、灌木丛到岩石和蘑菇。演示场景有夏季、秋季和冬季变体! 下载:​​Unity资源商店链接资源下载链接 效果图:

Java八股文(JVM)

Java八股文のJVM JVM JVM 什么是Java虚拟机&#xff08;JVM&#xff09;&#xff1f; Java虚拟机是一个运行Java字节码的虚拟机。 它负责将Java程序翻译成机器代码并执行。 JVM的主要组成部分是什么&#xff1f; JVM包括以下组件&#xff1a; ● 类加载器&#xff08;ClassLoa…

Linux应用实战之网络服务器(三)CSS介绍

0、前言 准备做一个Linux网络服务器应用实战&#xff0c;通过网页和运行在Linux下的服务器程序通信&#xff0c;这是第三篇&#xff0c;介绍一下CSS&#xff0c;优化上一篇文章中制作的HTML页面。 1、CSS常用语法 CSS&#xff08;层叠样式表&#xff09;是用于描述HTML或XML…

数据库原理与应用(SQL Server)笔记 关系数据库

目录 一、关系数据库的基本概念&#xff08;一&#xff09;关系数据库的定义&#xff08;二&#xff09;基本表、视图&#xff08;三&#xff09;元组、属性、域&#xff08;四&#xff09;候选码、主码、外码 二、关系模型三、关系的完整性&#xff08;一&#xff09;实体完整…

Android Studio控制台输出中文乱码问题

控制台乱码现象 安卓在调试阶段&#xff0c;需要查看app运行时的输出信息、出错提示信息。 乱码&#xff0c;会极大的阻碍开发者前进的信心&#xff0c;不能及时的根据提示信息定位问题&#xff0c;因此我们需要查看没有乱码的打印信息。 解决步骤&#xff1a; step1: 找到st…

阿里通义千问Qwen1.5开源MoE模型

介绍 2024年3月28日&#xff0c;阿里团队推出了Qwen系列的首个MoE模型&#xff0c;Qwen1.5-MoE-A2.7B。它仅拥有27亿个激活参数&#xff0c;但其性能却能与当前最先进的70亿参数模型&#xff0c;如Mistral 7B和Qwen1.5-7B相媲美。相较于包含65亿个Non-Embedding参数的Qwen1.5-…

电脑关机速度很慢怎么解决?

给电脑关机&#xff0c;总是要很久才完全关闭。这是因为计算机运行了太长时间&#xff0c;并且打开的程序太多&#xff0c;则关闭时间超过十秒钟&#xff0c;这是正常的现象。还有就是计算机升级或补丁程序更新也将导致计算机缓慢关闭。此时&#xff0c;建议耐心等待关闭完成。…

SCI论文改写、防查重神器QuillBot如何付费高级版本?

写论文时候的修改软件QuillBot&#xff0c;正常的文献里的句子帖进去&#xff0c;直接给各种倒装和各种同义词替换至少10次&#xff0c;保证查不出来是别人的句子。 QuillBot是一个帮助改写内容的转述工具。 Quillbot让你的内容重组变得简单。 转述是指你用不同的词来表达&a…

深度学习每周学习总结P3(天气识别)

&#x1f368; 本文为&#x1f517;365天深度学习训练营 中的学习记录博客&#x1f356; 原作者&#xff1a;K同学啊 | 接辅导、项目定制 数据链接 提取码&#xff1a;o3ix 目录 0. 总结1. 数据导入部分数据导入部分代码详解&#xff1a;a. 数据读取部分a.1 提问&#xff1a;关…

Nginx【概述:网页服务器 并发能力强】【常见命令】【部署实战】【反向代理】

Nginx-概述 介绍下载和安装下载安装重点目录和文件如下 Nginx-命令常用命令1). 查看版本2). 检查配置文件3). 启动4). 停止5). 重新加载 环境变量配置 Nginx-应用配置文件结构部署静态资源介绍测试1). 将静态资源上传到 /usr/local/nginx/html 目录2). 启动nginx3). 访问4). 配…

Linux命令及中间件安装

一.Linux简介 1.Linux操作系统概述 Linux是基于Unix的开源免费的操作系统&#xff0c;由于系统的稳定性和安全性几乎成为程序代码运行的最佳系统环境。Linux是由Linus Torvalds&#xff08;林纳斯托瓦兹&#xff09;起初开发的&#xff0c;由于源代码的开放性&#xff0c;现在…

Flask后端框架搭建个人图库

Hello&#xff0c;我是"小恒不会java" 前言 最近发现自己有一些站点图片丢失&#xff0c;原来是用了人家的链接。考虑到使用对象存储容易被刷流量&#xff0c;可以用flask这种轻量级框架快速实现网页登陆操作&#xff0c;行&#xff0c;也就不考虑正式生产环境那些复…

Leetcode146. LRU 缓存

Every day a Leetcode 题目来源&#xff1a;146. LRU 缓存 解法1&#xff1a;哈希表 链表 代码&#xff1a; /** lc appleetcode.cn id146 langcpp** [146] LRU 缓存*/// lc codestart class LRUCache { private:unordered_map<int, list<pair<int, int>>:…