Cryptanalytic Extraction of Neural Network Models

Nicholas Carlini, Matthew Jagielski, Ilya Mironov

Introduction

The past decade has seen significant advances in machine learning, and deep learning in particular. Tasks viewed as being completely infeasible at the beginning of the decade became almost completely solved by the end. AlphaGo [SHM+16] defeated professional players at Go, a feat in 2014 seen as being at least ten years away [Lev14]. Accuracy on the ImageNet recognition benchmark improved from 73%73\% in 2010 to 98.7%98.7\% in 2019, a 20×20\times reduction in error rate [XLHL20]. Neural networks can generate photo-realistic high-resolution images that humans find indistinguishable from actual photographs [KLA+19]. Neural networks achieve higher accuracy than human doctors in limited settings, such as early cancer detection [EKN+17].

These advances have brought neural networks into production systems. The automatic speech recognition systems on Google’s Assistant, Apple’s Siri, and Amazon’s Alexa are all powered by speech recognition neural networks. Neural Machine Translation [BCB15] is now the technique of choice for production language translation systems [WSC+16]. Autonomous driving is only feasible because of these improved image recognition neural networks.

High-accuracy neural networks are often held secret for at least two reasons. First, they are seen as a competitive advantage and are treated as trade secrets [Wen90]; for example, none of the earlier systems are open-source. Second, is seen as improving both security and privacy to keep these models secret. With full white-box access it is easy to mount evasion attacks and generate adversarial examples [SZS+14, BCM+13] against, for instance, abuse- or spam-detection models. Further, white-box access allows model inversion attacks [FJR15]: it is possible to reconstruct identifiable images of specific people given a model trained to recognize specific human faces. Similarly, given a language model trained on text containing sensitive data (e.g., credit card numbers), a white-box attacker can pull this sensitive data out of the trained model [CLE+19].

Fortunately for providers of machine learning models, it is often expensive to reproduce a neural network. There are three reasons for this cost: first, most machine learning requires extensive training data that can be expensive to collect; second, neural networks typically need hyper-parameter tuning requiring training many models to identify the optimal final model configuration; and third, even performing a final training run given the collected training data and correctly configured model is expensive.

For all of the above reasons, it becomes clear that (a) adversaries are motivated for various reasons to obtain a copy of existing deployed neural networks, and (b) preserving the secrecy of models is highly important. In practice companies ensure the secrecy of these models by either releasing only an API allowing query access, or releasing on-device models, but attempting to tamper-proof and obfuscate the source to make it difficult to extract out of the device.

Understandably, the above weak forms of protection are often seen as insufficient. The area of “secure inference” improves on this by bringing tools from Secure Function Evaluation (SFE), which allows mutually distrustful cooperating parties to evaluate f(x)f(x) where ff is held by one party and xx by the other. The various proposals often apply fully homomorphic encryption [Gen09, GBDL+16], garbled circuits [Yao86, RWT+18], or combinations of the two [MLS+20]. Per the standard SFE guarantee, secure inference “does not hide information [about the function ff] that is revealed by the result of the prediction” [MLS+20]. However this line of work often implicitly assumes that total leakage from the predictions is small, and that recovering the function from its output would be difficult.

In total, it is clear that protecting the secrecy of neural network models is seen as important both in practice and in the academic research community. This leads to the question that we study in this paper:

Is it possible to extract an identical copy of a neural network given oracle (black-box) access to the target model?

While this question is not new [TZJ+16, MSDH19, JCB+20, RK20], we argue that model extraction should be studied as a cryptanalytic problem. To do this, we focus on model extraction in an idealized environment where a machine learning model is made available as an oracle O\mathcal{O} that can be queried, but with no timing or other side channels. This setting captures that of obfuscated models made public, prediction APIs, and secure inference.

The key insight of this paper is that model extraction is closely related to an extremely well-studied problem in cryptography: the cryptanalysis of blockciphers. Informally, a symmetric-key encryption algorithm is a keyed function Ek ⁣:X→YE_{k}\colon\mathcal{X}\to\mathcal{Y} that maps inputs (plaintexts) x∈Xx\in\mathcal{X} to outputs (ciphertexts) y∈Yy\in\mathcal{Y}. We expect all practically important ciphers to be resistant, at the very least, to key recovery under the adaptive chosen-plaintext attack, i.e., given some bounded number of (adaptively chosen) plaintext/ciphertext pairs {(xi,yi)}\{(x_{i},y_{i})\} an encryption algorithm is designed so that the key kk cannot be extracted by a computationally-bounded adversary.

Contrast this to machine learning. A neural network model is (informally) a parameterized function fθ ⁣:X→Yf_{\theta}\colon\mathcal{X}\to\mathcal{Y} that maps input (e.g., images) x∈Xx\in\mathcal{X} to outputs (e.g., labels) y∈Yy\in\mathcal{Y}. A model extraction attack adaptively queries the neural network to obtain a set of input/output pairs {(xi,yi)}\{(x_{i},y_{i})\} that reveals information about the weights θ\theta. Neural networks are not constructed by design to be resistant to such attacks.

Thus, viewed appropriately, performing a model extraction attack—learning the weights θ\theta given oracle access to the function fθf_{\theta}—is a similar problem to performing a chosen-plaintext attack on a nontraditional “encryption” algorithm.

Given that it took the field of cryptography decades to design encryption algorithms secure against chosen-plaintext attacks, it would be deeply surprising if neural networks, where such attacks are not even considered in their design, were not vulnerable. Worse, the primary objective of cipher design is robustness against such attacks. Machine learning models, on the other hand, are primarily designed to be accurate at some underlying task, making the design of chosen-plaintext secure neural networks an even more challenging problem.

There are three differences separating model extraction from standard cryptanalysis that make model extraction nontrivial and interesting to study.

First, the attack success criterion differs. While a cryptographic break can be successful even without learning key bits—for example by distinguishing the algorithm from a pseudo-random function, only “total breaks” that reveal (some of) the actual model parameters θ\theta are interesting for model extraction.

Second, the earlier analogy to keyed ciphers is imperfect. Neural networks typically take high-dimensional inputs (e.g., images) and return low-dimensional outputs (e.g., a single probability). It is almost more appropriate to make an analogy to cryptanalysis of keyed many-to-one functions, such as MACs. However, the security properties of MACs are quite different from those of machine learning models, for example second preimages are expected rather than shunned in neural networks.

Finally, and the largest difference in practice, is that machine learning models deal in fixed- or floating-point reals rather than finite field arithmetic. As such, there are many components to our attack that would be significantly simplified given infinitely precise floating-point math, but given the realities of modern machine learning, require far more sophisticated attack techniques.

2 Our Results

We introduce a differential attack that is effective at performing functionally-equivalent neural network model extraction attacks. Our attack traces the neural network’s evaluation on pairs of examples that differ in a few entries and uses this to recover the layers (analogous to the rounds of a block cipher) of a neural network one by one. To evaluate the efficacy of our attack, we formalize the definition of fidelity introduced in prior work [JCB+20] and quantify the degree to which a model extraction attack has succeeded:

Two models ff and gg are (ϵ,δ)(\epsilon,\delta)-functionally equivalent on SS if

Table 1 reports the results of our differential attack across a wide range of model sizes and architectures, reporting both (ε,δ)(\varepsilon,\delta)-functional equivalence on the set S=d0S=^{d_{0}}, the input space of the model, along with a direct measurement of max⁡  ∣θ−θ^∣\max\,\,\lvert\theta-\hat{\theta}\rvert, directly measuring the error between the actual model weights θ\theta and the extracted weights θ^\hat{\theta} (as described in Section 6.2).

The remainder of this paper is structured as follows. We introduce the notation, threat model, and attacker goals and assumptions used in Section 2. In Section 4 we introduce an idealized attack that extracts (0,0)(0,0)-functionally-equivalent neural networks assuming infinite precision arithmetic. Section 5 develops an instantiation of this attack that works in practice with finite-precision arithmetic to yield (ε,δ)(\varepsilon,\delta)-functionally equivalent attacks.

3 Related Work

Model extraction attacks are classified into two categories [JCB+20]: task accuracy extraction and fidelity extraction. The first paper to study task accuracy extraction [TZJ+16] introduced techniques to steal similar models that approximately solve the same underlying decision task on the natural data distribution, but do not necessarily match the predictions of the oracle precisely. While further work exists in this space [CCG+20, KTP+20], we instead focus on fidelity extraction where the adversary aims to faithfully reproduce the predictions of the oracle model, when it is incorrect with respect to the ground truth. Again, [TZJ+16] studied this problem and developed (what we would now call) functionally equivalent extraction for the case of completely linear models.

This attack was then extended by a theoretical result defining and giving a method for performing functionally-equivalent extraction for neural networks with one layer, assuming oracle access to the gradients [MSDH19]. A concrete implementation of this one layer attack that works in practice, handling floating point imprecision, was subsequently developed through applying finite differences to estimate the gradient [JCB+20]. Parallel work to this also extended on these results, focusing on deeper networks, but required tens to hundreds of millions of queries [RK20]; while the theoretical results extended to deep networks, the implementation in practice only extracts up to the first two layers. Our work builds on all of these four results to develop an approach that is 10610^{6} times more accurate, requiring 10310^{3} times fewer queries, and applies to larger models.

Even without query access, it is possible to steal models with just a cache side-channel [BBJP19], although with less fidelity than our attack that we introduce which are 220×2^{20}\times more precise. Other attacks target hyperparameter extraction—that is, extracting high-level details about the model: through what method it was trained, if it contains convolutions, or related questions [WG18]. It is further possible to steal hyperparameters with cache side channels [HDK+20].

Recent work has studied the learnability of deep neural networks with random weights in the statistical query (SQ) model [DGKP20], showing that learnability drops off exponentially with the depth of the network. This line of work does not address the cryptographic hardness of extraction in the non-SQ model—precisely the question addressed in this work in the empirical setting.

While not directly related to our problem, it is worth noting that we are not the first to treat neural networks as just another type of mathematical function that can be analyzed without any specific knowledge of machine learning. Shamir et al. [SSRD19] explain the existence of adversarial examples [SZS+14, BCM+13], which capture evasion attacks on machine learning classifiers, by considering an abstract model of neural networks.

In a number of places, our attack draws inspiration from the cryptanalysis of keyed block-ciphers, most prominently differential cryptanalysis [BS91]. We neither assume nor require familiarity with this field, but the informed reader may enjoy certain parallels.

Preliminaries

This paper studies an abstraction of neural networks as functions f ⁣:X→Yf\colon\mathcal{X}\to\mathcal{Y}. Our results are independent of any methods for selecting the function ff (e.g., stochastic gradient descent), and are independent of any utility of the function ff. As such, machine learning knowledge is neither expected nor necessary.

A kk-deep neural network fθ(x)f_{\theta}(x) is a function parameterized by θ\theta that takes inputs from an input space X\mathcal{X} and returns values in an output space Y\mathcal{Y}. The function ff is composed as a sequence of functions alternating between linear layers fjf_{j} and a nonlinear function (acting component-wise) σ\sigma:

While representing each layer fjf_{j} as a full matrix product is the most general definition of a layer, which is called fully connected, often layers have more structure. For example, it is common to use (discrete) convolutions in neural networks that operate on images. Convolutional layers take the input as a n×mn\times m matrix and convolve it with a kernel, such as a 3×33\times 3 matrix. Importantly, however, it is always possible to represent a convolution as a matrix product.

The neurons {ηi}i=1N\{\eta_{i}\}_{i=1}^{N} are functions receiving an input and passing it through the activation function σ\sigma. There are a total of N=∑j=1k−1djN=\sum_{j=1}^{k-1}d_{j} neurons.

In this paper we exclusively study the ReLU [NH10] activation function, given by σ(x)=max⁡(x,0)\sigma(x)=\max(x,0). Our results are a fundamental consequence of the fact that ReLU neural networks are piecewise linear functions.

The architecture of a neural network captures the structure of ff: (a) the number of layers, (b) the dimensions of each layer {di}i=0k\{d_{i}\}_{i=0}^{k}, and (c) any additional constraints imposed on the weights A(i)A^{(i)} and biases b(i)b^{(i)}.

We use the shorthand aa-bb-cc neural network to denote the sizes of each dimension; for example a 10-20-5 neural network has input dimension 10, one layer with 20 neurons, and output dimension 5. This description completely characterizes the structure of ff for fully connected networks. In practice, there are only a few architectures that represent most of the deployed deep learning models [ZL17], and developing new architectures is an extremely difficult and active area in research [HZRS16, SIVA17, TL19].

The parameters θ\theta of fθf_{\theta} are the concrete assignments to the weights A(j)A^{(j)} and biases b(j)b^{(j)}, obtained during the process of training the neural network.

It is beyond the scope of this paper to describe the training process which produces the parameters θ\theta: it suffices to know that the process of training is often computationally expensive and that training is a nondeterministic process, and so training the same model multiple times will give different sets of parameters.

2 Adversarial Goals and Resources

There are two parties in a model extraction attack: the oracle O\mathcal{O} who returns fθ(x)f_{\theta}(x), and the adversary who generates queries xx to the oracle.

A model parameter extraction attack receives oracle access to a parameterized function fθf_{\theta} (in our case a kk-deep neural network) and the architecture of ff, and returns a set of parameters θ^\hat{\theta} with the goal that fθ(x)f_{\theta}(x) is as similar as possible to fθ^(x)f_{\hat{\theta}}(x).

Throughout this paper we use the _^\hat{\_} symbol to indicate an extracted parameter. For example, θ^\hat{\theta} refers to the extracted weights of a model θ\theta.

There is a spectrum of similarity definitions between the extracted weights and the oracle model that prior work has studied [TZJ+16, JCB+20, KTP+20]; we focus on the setting where the adversarial advantage is defined by (ε,δ)(\varepsilon,\delta)-functionally equivalent extraction as in Definition 1.

Analogous to cryptanalysis of symmetric-key primitives, the degree to which a model extraction attack succeeds is determined by (a) the number of chosen inputs to the model, and (b) the amount of compute required.

We make several assumptions of the oracle O\mathcal{O} and the attacker’s knowledge. (We believe many of these assumptions are not fundamental and can be relaxed. Removing these assumptions is left to future work.)

Architecture knowledge. We require knowledge of the architecture of the neural network.

Full-domain inputs. We feed arbitrary inputs from X\mathcal{X}.

Complete outputs. We receive outputs directly from the model ff without further processing (e.g., by returning only the most likely class without a score).

Precise computations. ff is specified and evaluated using 64-bit floating-point arithmetic.

ReLU Activations. All activation functions (σ\sigma’s) are ReLU’s.This is the only assumption fundamental to our work. Switching to any activation that is not piecewise linear would prevent our attack. However, as mentioned, all state-of-the-art models use exclusively (piecewise linear generalizations of) the ReLU activation function [SIVA17, TL19].

Overview of the Differential Attack

Given oracle access to the function fθf_{\theta}, we can estimate ∂fθ\partial f_{\theta} through finite differences along arbitrary directions. For simple linear functions defined by f(x)=a⋅x+bf(x)=a\cdot x+b, its directional derivative satisfies ∂f∂ei≡ai\frac{\partial f}{\partial e_{i}}\equiv a_{i}, where eie_{i} is the basis vector and aia_{i} is the iith entry of the vector aa, allowing direct recovery of its weights through querying on these well-chosen inputs.

In the case of deep neural networks, we consider second partial directional derivatives. ReLU neural networks are piecewise linear functions with ∂2f∂x2≡0{\partial^{2}f\over\partial x^{2}}\equiv 0 almost everywhere, except when the function has some neuron ηj\eta_{j} at the boundary between the negative and positive region (i.e., is at its critical point). We show that the value of the partial derivative ∂2f∂ei2\partial^{2}f\over\partial e_{i}^{2} evaluated at a point xx so that neuron ηj\eta_{j} is at such a critical point actually directly reveals the weight T(Ai,j(1))T(A^{(1)}_{i,j}) for some transform TT that is invertible—and therefore the adversary can learn Ai,j(1)A^{(1)}_{i,j}. By repeating this attack along all basis vectors eie_{i} and for all neurons ηj\eta_{j} we can recover the complete matrix A(1)A^{(1)}. Once we have extracted the first layer’s weights, we are able to “peel off” that layer and re-mount our attack on the second layer of the neural network, repeating to the final layer. There are three core technical difficulties to our attack:

For each neuron η\eta, our attack does not exactly recover Ai(l)A^{(l)}_{i}, the iith row of A(l)A^{(l)}, but instead a scalar multiple v=α⋅Ai(l)v=\alpha\cdot A^{(l)}_{i}. While losing a constant α>0\alpha>0 keeps the neural network in the same equivalence class, the sign of α\alpha is important and we must distinguish between the weight vector Ai(l)A^{(l)}_{i} and −Ai(l)-A^{(l)}_{i}. We construct two approaches that solve this problem, but in the general case we require exponential work (but a linear number of queries).

On the first layer, we can directly compute the derivative entry-by-entry, measuring ∂2f∂ei2{\partial^{2}f\over\partial e_{i}^{2}} for each standard basis vector eie_{i} in order to recover Aij(1)A^{(1)}_{ij}. Deeper in the network, we can not move along standard basis vector vectors. Worse, for each input xx on average half of the neurons are in the negative region and thus their output is identically ; when this happens it is not possible to learn the weight along edges with value zero. Thus we are required to develop techniques to elicit behavior from every neuron, and techniques to cluster together partial recoveries of each row of Ai(l)A^{(l)}_{i} to form a complete recovery.

Implementing our attack in practice with finite precision neural networks introduces additional complexity. In order to estimate the second partial derivative, we require querying on inputs that differ by only a small amount, reducing the precision of the extracted first weight matrix to twenty bits, or roughly 10−610^{-6}. This error of 10−610^{-6} is not large to begin with, but this error impacts our ability to recover the next layer, compounding multiplicatively the deeper we go in the network. Already in the second layer, the error is magnified to 10−410^{-4}, which can completely prevent reconstruction for the third layer: our predicted view of the hidden state is sufficiently different from the actual hidden state that our attack fails completely. We resolve this through two means. First, we introduce numerically stable methods assuming that all prior layers have been extracted to high precision. Second, we develop a precision-refinement technique that takes a prefix of the first j≤kj\leq k layers of a neural network extracted to nn bits of precision and returns the jj-deep model extracted to 2n2n bits of precision (up to floating-point tolerance).

Idealized Differential Extraction Attack

We now introduce our (0,0)(0,0)-functionally-equivalent model extraction attack that assumes infinite precision arithmetic and recovers completely functionally equivalent models. Recall our attack assumptions (Section 2.2); using these, we present our attack beginning with two “reduced-round” attacks on 0-deep (Section 4.1) and 1-deep (Section 4.2) neural networks, and then proceeding to kk-deep extraction for contractive (Section 4.3) and expansive (Section 4.4) neural networks. Section 5 refines this idealized attack to work with finite precision.

Zero-deep neural networks are linear functions f(x)≡A(1)⋅x+b(1)f(x)\equiv A^{(1)}\cdot x+b^{(1)}. Querying d0d_{0} linearly independent suffices to extract ff by solving the resulting linear system.

However let us view this problem differently, to illuminate our attack strategy for deeper networks. Consider the parallel evaluations f(x)f(x) and f(x+δ)f(x+\mathbf{\delta}), with

This allows us to directly read off the weights of A(1)A^{(1)}. Put differently, we perform finite differences to estimate the gradient of ff, given by ∇xf(x)≡A(1)\nabla_{x}f(x)\equiv A^{(1)}.

2 One-Deep Neural Network Extraction

Many of the important problems that complicate deep neural network extraction begin to arise at 1-deep neural networks. Because the function is no longer completely linear, we require multiple phases to recover the network completely. To do so, we will proceed layer-by-layer, extracting the first layer, and then use the 0-deep neural network attack to recover the second layer.

For the remainder of this paper it will be useful to have two distinct mental models of the problem at hand. First is the symbolic view shown previously in Figure 1. This view directly studies the flow of information through the neural networks, represented as an alternating sequence of linear layers and non-linear transformations. This view helps understanding the algebraic steps of our attack.

The second is the geometric view. Because neural networks operate over the real vector space, they can be visualized by plotting two dimensional slices of the landscape [MSDH19]. Figure 2 (left) contains an example of such a figure. Each solid black line corresponds to a change in gradient induced in the space by a neuron changing sign from positive to negative (or vice versa)—ignoring for now the remaining lines. The problem of neural network extraction corresponds to recovering the locations and angles of these neuron-induced hyperplanes: in general with input dimension d0d_{0}, the planes have dimension d0−1d_{0}-1.

The function that computes the first jj layers (up to and including fjf_{j} but not including σ\sigma) of ff is denoted as f1..jf_{1..j}. In particular, f=f1..kf=f_{1..k}.

The hidden state at layer jj is the output of the function f1..jf_{1..j}, before applying the nonlinear transformation σ\sigma.

Layer fjf_{j} is a linear transformation of the (j−1)(j-1)st hidden state after σ\sigma.

V(η;x)\mathcal{V}(\eta;x) denotes the input to neuron η\eta (before applying σ\sigma) when evaluated at xx. L(η)\mathcal{L}(\eta) denotes the layer of neuron η\eta. The first layer starts at 1.

A neuron η\eta is at a critical point when V(η;x)=0\mathcal{V}(\eta;x)=0. We refer to this input xx as a witness to the fact that η\eta is at a critical point, denoted by x∈W(η)x\in\mathcal{W}(\eta). If V(η;x)>0\mathcal{V}(\eta;x)>0 then η\eta is active, and otherwise inactive.

In Figure 2 the locations of these critical points correspond exactly to the solid black lines drawn through the plane. Observe that because we restrict ourselves to ReLU neural networks, the function ff is piecewise linear and infinitely differentiable almost everywhere. The gradient ∇xf(x)\nabla_{x}f(x) is well defined at all points xx except when there exists a neuron that is at its critical point.

Functionally, the attack as presented in this subsection has appeared previously in the literature [MSDH19, JCB+20]. By framing it differently, our attack will be extensible to deeper networks.

Assume we were given a witness x∗∈W(ηj)x^{*}\in\mathcal{W}(\eta_{j}) that caused neuron ηj\eta_{j} to be at its critical point (i.e., its value is identically zero). Because we are using the ReLU activation function, this is the point at which that neuron is currently “inactive” (i.e., is not contributing to the output of the classifier) but would become “active” (i.e., contributing to the output) if it becomes slightly positive. Further assume that only this neuron ηj\eta_{j} is at its critical point, and that for all others neurons η≠ηj\eta\neq\eta_{j} we have ∣V(η,xj)∣>δ|\mathcal{V}(\eta,x_{j})|>\delta for a constant δ>0\delta>0.

Consider the quantity ∣α+−α−∣\lvert\alpha_{+}-\alpha_{-}\rvert. Because x∗x^{*} induces a critical point of ηj\eta_{j}, exactly one of {α+,α−}\{\alpha_{+},\alpha_{-}\} will have the neuron ηj\eta_{j} in its active regime and the other will have ηj\eta_{j} in its inactive regime. If no two columns of A(1)A^{(1)} are collinear, then as long as ϵ<δ∑i,j∣Ai,j(1)∣\epsilon<{\delta\over\sum_{i,j}\lvert A^{(1)}_{i,j}\rvert}, we are guaranteed that all other neurons in the neural network will remain in the same state as before—either active or inactive. Therefore, if we compute the difference ∣α+i−α−i∣\lvert\alpha^{i}_{+}-\alpha^{i}_{-}\rvert, the gradient information flowing into and out of all other neurons will cancel and we will be left with just the gradient information flowing along the edge from the input coordinate ii to neuron ηj\eta_{j} to the output. Concretely, we can write the 1-deep neural network as

and so either α+i−α−i=Aj,i(1)⋅A(2)\alpha^{i}_{+}-\alpha^{i}_{-}=A^{(1)}_{j,i}\cdot A^{(2)} or α−i−α+i=Aj,i(1)⋅A(2)\alpha^{i}_{-}-\alpha^{i}_{+}=A^{(1)}_{j,i}\cdot A^{(2)}. However, if we repeat the above procedure on a new basis vector eke_{k} then either α+k−α−k=Aj,k(1)⋅A(2)\alpha^{k}_{+}-\alpha^{k}_{-}=A^{(1)}_{j,k}\cdot A^{(2)} or α−k−α+k=Aj,k(1)⋅A(2)\alpha^{k}_{-}-\alpha^{k}_{+}=A^{(1)}_{j,k}\cdot A^{(2)} will hold. Crucially, whichever of the two relations that holds for along coordinate ii will be the same relation that holds on coordinate kk. Therefore we can divide out A(2)A^{(2)} to obtain the ratio of pairs of weights

This allows us to compute every row of A(1)A^{(1)} up to a single scalar cjc_{j}. Further, we can compute bj(1)=−A^j(1)⋅x∗b^{(1)}_{j}=-\hat{A}^{(1)}_{j}\cdot x^{*} (again, up to a scaling factor) because we know that x∗x^{*} induces a critical point on neuron ηj\eta_{j} and so its value is zero.

Observe that the magnitude of cjc_{j} is unimportant. We can always push a constant c>0c>0 through to the weight matrix A(2)A^{(2)} and have a functionally equivalent result. However, the sign of cjc_{j} does matter.

Because xix_{i} is a witness to neuron ηi\eta_{i} being at its critical point, we will have that either f(x+)=f(xi)f(x_{+})=f(x_{i}) or f(x−)=f(xi)f(x_{-})=f(x_{i}). Exactly one of these equalities is true because σ(h−ei)=σ(h)\sigma(h-e_{i})=\sigma(h), but σ(h+ei)≠σ(h)\sigma(h+e_{i})\neq\sigma(h) when hi=0h_{i}=0. Therefore if the second equality holds true, then we know that our extracted guess of the iith row has the correct sign. However, if the first equality holds true, then our extracted guess of the iith row has the incorrect sign, and so we invert it (along with the bias bi(1)b^{(1)}_{i}). We repeat this procedure with a critical point for every neuron ηi\eta_{i} to completely recover the signs for the full first layer.

It only remains to show how to find witnesses x∗∈W(η)x^{*}\in\mathcal{W}(\eta) for each neuron η\eta on the first layer. We choose a random line in input space (the dashed line in Figure 2, left), and search along it for nonlinearities in the partial derivative. Any nonlinearity must have resulted from a ReLU changing signs, and locating the specific location where the ReLU changes signs will give us a critical point. We do this by binary search.

Once we have fully recovered the first layer weights, we can “peel off” the weight matrix A(1)A^{(1)} and bias b(1)b^{(1)} and we are left with extracting the final linear layer, which reduces to -deep extraction.

3 k𝑘k-Deep Contractive Neural Networks

Extending the above attack to deep neural networks has several complications that prior work was unable to resolve efficiently; we address them one at a time.

Because 1-deep networks have only one layer, all ReLUs occur on that layer. Therefore all critical points found during search will correspond to a neuron on that layer. For kk-deep networks this is not true, and if we want to begin by extracting the first layer we will have to remove non-first layer critical points. (And, in general, to extract layer jj, we will have to remove non-layer-jj critical points.)

In order to be able to directly read off the weights, we query the network on basis vectors eie_{i}. Achieving this is not always possible for deep networks, and we must account for the fact that we may only be able to query on non-orthogonal directions.

Our row-sign procedure requires that we be able to invert A(1)A^{(1)}, which in general implies we need to develop a method to compute a preimage of f1..jf_{1..j}.

3.1 Extracting layer-1 weights with unknown critical point layers

Suppose we had a function C0(f)={xi}i=1M\mathcal{C}_{0}(f)=\{x_{i}\}_{i=1}^{M} that returns at least one critical point for every neuron in the first layer (implying M≥d1M\geq d_{1}), but never returns critical points for any deeper layer. We claim that the exact differential attack from above still correctly recovers the first layer of a deep neural network.

We make the following observation. Let x∗∉⋃ηiW(ηi)x^{*}\not\in\bigcup_{\eta_{i}}\mathcal{W}(\eta_{i}) be an input that is a witness to no critical point, i.e., ∣V(ηi;x∗)∣>ϵ>0\lvert\mathcal{V}(\eta_{i};x^{*})\rvert>\epsilon>0. Define flocalf_{\text{local}} as the function so that for a sufficiently small region we have that flocal≡ff_{\text{local}}\equiv f, that is,

Here, I(j)I^{(j)} are 0-1 diagonal matrices with a on the diagonal when the neuron is inactive and 11 on the diagonal when the neuron is active:

where ηn\eta_{n} is the nnth neuron on the first layer. Importantly, observe that each I(j)I^{(j)} is a constant as long as xx is sufficiently close to x∗x^{*}. While β\beta is unknown, as long as we make only gradient queries ∂flocal\partial f_{\text{local}}, its value is unimportant. This observation so far follows from the definition of piecewise linearity.

Consider now some input that is a witness to exactly one critical point on neuron η∗\eta^{*}. Formally, x∗∈W(η∗)x^{*}\in\mathcal{W}(\eta^{*}), but x∗∉⋃ηj≠η∗W(ηj;x∗)x^{*}\not\in\bigcup_{\eta_{j}\neq\eta^{*}}\mathcal{W}(\eta_{j};x^{*}). Then

where again I(j)I^{(j)} are 0-1 matrices, but except that now, I(1)I^{(1)} (and only I(1)I^{(1)}) is a function of xx returning a 0-1 diagonal matrix that has one of two values, depending on the value of V(η∗;x)>0\mathcal{V}(\eta^{*};x)>0. Therefore we can no longer collapse the matrix product into one matrix Γ\Gamma but instead can only obtain

But this is exactly the case we have already solved for 1-deep neural network weight recovery: it is equivalent to the statement flocal(x)=Γσ(A(1)x+b(1))+β2f_{\text{local}}(x)=\Gamma\sigma(A^{(1)}x+b^{(1)})+\beta_{2}, and so by dividing out Γ\Gamma exactly as before we can recover the ratios of Ai,j(1)A^{(1)}_{i,j}.

Assume we are given a set of inputs S={xi}S=\{x_{i}\} so that each xix_{i} is a witness to neuron ηxi\eta_{x_{i}}, with ηxi\eta_{x_{i}} unknown. By the coupon collector’s argument (assuming uniformity), for ∣S∣≫Nlog⁡N|S|\gg N\log N, where NN is the total number of neurons, we will have at least two witnesses to every neuron η\eta.

Without loss of generality let x0,x1∈W(η)x_{0},x_{1}\in\mathcal{W}(\eta) be witnesses to the same neuron η\eta on the first layer, i.e, that V(η;x0)=V(η;x1)=0\mathcal{V}(\eta;x_{0})=\mathcal{V}(\eta;x_{1})=0. Then, performing the weight recovery procedure beginning from each of these witnesses (through finite differences) will yield the correct weight vector Aj(1)A^{(1)}_{j} up to a scalar.

Typically elements of SS will not be witnesses to neurons on the first layer. Without loss of generality let x2x_{2} and x3x_{3} be witnesses to any neuron on a deeper layer. We claim that we will be able to detect these error cases: the outputs of the extraction algorithm will appear to be random and uncorrelated. Informally speaking, because we are running an attack designed to extract first-layer neurons on a neuron actually on a later layer, it is exceedingly unlikely that the attack would, by chance, give consistent results when run on x2x_{2} and x3x_{3} (or any arbitrary pair of neurons).

Formally, let h2=f1(x2)h_{2}=f_{1}(x_{2}) and h3=f1(x3)h_{3}=f_{1}(x_{3}). With high probability, sign(h2)≠sign(h3)\text{sign}(h_{2})\neq\text{sign}(h_{3}). Therefore, when executing the extraction procedure on x2x_{2} we compute over the function Γ1I(1)(x2)A(1)x+β1\Gamma_{1}I^{(1)}(x_{2})A^{(1)}x+\beta_{1}, whereas extracting on x3x_{3} computes over Γ2I(1)(x3)A(1)x+β2\Gamma_{2}I^{(1)}(x_{3})A^{(1)}x+\beta_{2}. Because Γ1≠Γ2\Gamma_{1}\neq\Gamma_{2}, this will give inconsistent results.

Therefore our first layer weight recovery procedure is as follows. For all inputs xi∈Sx_{i}\in S run the weight recovery procedure to recover the unit-length normal vector to each critical hyperplane. We should expect to see a large number of vectors only once (because they were the result of running the extraction of a layer 22 or greater neuron), and a small number of vectors that appear duplicated (because they were the result of successful extraction on the first layer). Given the first layer, we can reduce the neural network from a kk-deep neural network to a (k−1)(k-1)-deep neural network and repeat the attack. We must resolve two difficulties, however, discussed in the following two subsections.

3.2 Extracting hidden layer weights with unknown critical points

When extracting the first layer weight matrix, we were able to compute ∂2f∂e1∂ej\partial^{2}f\over\partial e_{1}\partial e_{j} for each input basis vectors eie_{i}, allowing us to “read off” the ratios of the weights on the first layer directly from the partial derivatives. However, for deeper layers, it is nontrivial to exactly control the hidden layers and change just one coordinate in order to perform finite differences.For the expansive networks we will discuss in Section 4.4 it is actually impossible; therefore this section introduces the most general method. Let jj denote the current layer we are extracting. Begin by sampling dj+1d_{j}+1 directions δi∼N(0,ϵId0)∈X\delta_{i}\sim\mathcal{N}(0,\epsilon I_{d_{0}})\in\mathcal{X} and let

From here we can construct a system of equations: let hi=σ(f1..j−1(x+δi))h_{i}=\sigma(f_{1..j-1}(x+\delta_{i})) and solve for the vector ww such that hi⋅w=yih_{i}\cdot w=y_{i}.

As before, we run the weight recovery procedure assuming that each witness corresponds to a critical point on the correct layer. Witnesses that correspond to neurons on incorrect layers will give uncorrelated errors that can be discarded.

The above algorithm overlooks one important problem. For a given critical point x∗x^{*}, the hidden vector obtained from f1..j(x∗)f_{1..j}(x^{*}) is likely to have several (on average, half) neurons that are negative, and therefore σ(f1..j(x∗))\sigma(f_{1..j}(x^{*})) and any σ(f1..j(x∗+δi))\sigma(f_{1..j}(x^{*}+\delta_{i})) will have neurons that are identically zero. This makes it impossible to recover the complete weight vector from just one application of least squares—it is only possible to compute the weights for those entries that are non-zero. One solution would be to search for a witness x∗x^{*} such that component-wise f1..j(x∗)≥0f_{1..j}(x^{*})\geq 0; however doing this is is not possible in general, and so we do not consider this option further.

Instead, we combine together multiple attempts at extracting the weights through a unification procedure. If x1x_{1} and x2x_{2} are witnesses to critical points for the same neuron, and the partial vector f1..j(x1)f_{1..j}(x_{1}) has entries t1⊂{1,…,dj}t_{1}\subset\{1,\dots,d_{j}\} and the partial vector f1..j(x2)f_{1..j}(x_{2}) has entries t2⊂{1,…,dj}t_{2}\subset\{1,\dots,d_{j}\} defined, then it is possible to recover the ratios for all entries t1∪t2t_{1}\cup t_{2} by unifying together the two partial solutions as long as t1∩t2t_{1}\cap t_{2} is non-empty as follows.

Let rir_{i} denote the extracted weight vector on witness x1x_{1} with entries at locations t1⊂{1,…,dj}t_{1}\subset\{1,\dots,d_{j}\} (respectively, r2r_{2} at x2x_{2} with locations at t2t_{2}). Because the two vectors correspond to the solution for the same row of the weight matrix Ai(j)A^{(j)}_{i}, the vectors r1r_{1} and r2r_{2} must be consistent on t1∩t2t_{1}\cap t_{2}. Therefore, we will have that r1[t1∩t2]=c⋅r2[t1∩t2]r_{1}[t_{1}\cap t_{2}]=c\cdot r_{2}[t_{1}\cap t_{2}] for a scalar c≠0c\neq 0. As long as t1∩t2≠∅t_{1}\cap t_{2}\neq\emptyset we can compute the appropriate constant cc and then recover the weight vector r1,2r_{1,2} with entries at positions t1∪t2t_{1}\cup t_{2}.

Observe that this procedure also allows us to check whether or not x1x_{1} and x2x_{2} are witnesses to the same neuron nn reaching its critical point. If ∣t1∩t2∣≥γ|t_{1}\cap t_{2}|\geq\gamma, then as long as there do not exist two rows of A(j)A^{(j)} that have γ+1\gamma+1 entries that are scalar multiples of each other, there will be a unique solution that merges the two partial solutions together. If the unification procedure above fails—because there does not exist a single scalar cc so that c⋅r1[t1∩t2]=r2[t1∩t2]c\cdot r_{1}[t_{1}\cap t_{2}]=r_{2}[t_{1}\cap t_{2}]—then x1x_{1} and x2x_{2} are not witnesses to the same neuron being at a critical point.

3.3 Recovering row signs in deep networks

In the case of 11-deep networks, it suffices for d1≤d0d_{1}\leq d_{0} and A(1)A^{(1)} to be onto as described. In general it is necessary that dk≤dk−1≤⋯≤d1≤d0d_{k}\leq d_{k-1}\leq\dots\leq d_{1}\leq d_{0} but it is not sufficient, even if every layer A(i)A^{(i)} were an onto map. Because there is a ReLU activation after every hidden layer, it is not possible to send negative values into the second layer fjf_{j} when computing the preimage.

It is simple to test if a network is sufficiently contractive without any queries: try the above method to find a preimage xx; if this fails, abort and attempt the following (more expensive) attack procedure. Otherwise it is contractive.

4 k𝑘k-Deep Expansive Neural Networks

While most small neural networks are contractive, in practice almost all interesting neural networks are expansive: the number of neurons on some intermediate layer is larger than the number of inputs to that layer. Almost all of the prior methods still apply in this setting, with one exception: the column sign recovery procedure. Thus, we are required to develop a new strategy.

Observe that sign information is not lost for the final layer: because there is no ReLU activation and we can directly solve for the weights with least squares, we do not lose sign information.

Suppose we had extracted completely the function f^1..k−1\hat{f}_{1..k-1} (the third to last layer), and further had extracted the weights A^(k)\hat{A}^{(k)} and biases b^(k)\hat{b}^{(k)} up to sign of the rows. There are three unknown quantities remaining: a sign vector s∈{−1,1}dks\in\{-1,1\}^{d_{k}}, A^(k+1)\hat{A}^{(k+1)} and b^(k+1)\hat{b}^{(k+1)}. Suppose we were given S⊂XS\subset\mathcal{X} so that ∣S∣>dk\lvert S\rvert>d_{k}. Then it would be possible to solve for all three unknown simultaneously through brute force.

Let hi=σ(f1..k−1(xi))h_{i}=\sigma(f_{1..k-1}(x_{i})). Enumerate all 2dk2^{d_{k}} assignments of ss and compute gi=σ((s⊙A^(k))hi+(s⊙b^(k))g_{i}=\sigma((s\odot\hat{A}^{(k)})h_{i}+(s\odot\hat{b}^{(k)}). We know that if we guessed the sign vector ss correctly, then there would exist a solution to the system of equations v⋅gi+b=f(xi)v\cdot g_{i}+b=f(x_{i}). This is the zero-deep extraction problem and solving it efficiently requires just a single call to least squares. This allows us to—through brute forcing the sign bits—completely recover both the signs of the second-to-last layer as well as the values (and signs) of the final layer.

Unfortunately, this procedure does not scale to recover the signs of layer k−1k-1 and earlier. It relies on the existence of an efficient testing procedure (namely, least squares) to solve the final layer. If we attempted this brute-force strategy at layer k−3k-3 in order to test if our sign assignment was correct, we would need to run the complete layer k−2k-2 extraction procedure, thus incurring an exponential number of queries to the oracle.

However, we can use this idea in order to still recover signs even at earlier layers in the network with only a linear number of queries (but still exponential work in the width of the hidden layers).

Assume that we are given a collection of examples {xi}⊂W(η)\{x_{i}\}\subset\mathcal{W}(\eta) for some neuron η\eta that is on the layer after we extracted so far: L(η)=j+1\mathcal{L}(\eta)=j+1. Then we would know that there should exist a single unknown vector vv and bias bb such that fj(xi)⋅v+b=0f_{j}(x_{i})\cdot v+b=0 for all xix_{i}.

This gives us an efficient procedure to test whether or not a given sign assignment on layer jj is correct. As before, we enumerate all possible sign assignments and then check if we can recover such a vector vv. If so, the assignment is correct; if not, it is wrong. It only remains left to show how to implement this procedure to obtain such a collection of inputs {xi}\{x_{i}\}.

4.1 The polytope boundary projection algorithm

The layer jj polytope containing xx is the set of points {x+δ}\{x+\delta\} so that sign(V(η;x))=sign(V(η;x+δ))\text{sign}(\mathcal{V}(\eta;x))=\text{sign}(\mathcal{V}(\eta;x+\delta)) for all L(η)≤j\mathcal{L}(\eta)\leq j.

Observe that the layer jj polytope around xx is an open, convex set, as long as xx is not a witness to a critical point. In Figure 3, each enclosed region is a layer-kk polytope and the triangle formed by η0,η1\eta_{0},\eta_{1}, and η2\eta_{2} is a layer-(k−1)(k-1) polytope.

Given an input xx and direction Δ\Delta, we can compute the distance α\alpha so that the value x′=x+αΔx^{\prime}=x+\alpha\Delta is at the boundary of the polytope defined by layers 11 to kk. That is, starting from xx traveling along direction Δ\Delta we stop the first time a neuron on layer jj or earlier reaches a critical point. Formally, we define

We only ever compute Proj1..j\text{Proj}_{1..j} when we have extracted the neural network up to layer jj. Thus we perform the computation with respect to the extracted function f^\hat{f} and neuron-value function V^\hat{\mathcal{V}}, and so computing this function requires no queries to the oracle. In practice we solve for α\alpha via binary search.

4.2 Identifying a single next-layer witness

Given the correctly extracted network f^1..j−1\hat{f}_{1..j-1} and the weights (up to sign) of layer j−1j-1, our sign extraction procedure requires some witness to a critical point on layer jj. We begin by performing our standard binary search sweep to find a collection S⊂XS\subset\mathcal{X}, each of which is a witness to some neuron on an unknown layer. It is simple to filter out critical points on layers j−1j-1 or earlier by checking if any of V^(η;x)=0\hat{\mathcal{V}}(\eta;x)=0 for L(η)≤j−1\mathcal{L}(\eta)\leq j-1. Even though we have not solved for the sign of layer jj, it is still possible to compute whether or not they are at a critical point because critical points of A^(j)\hat{A}^{(j)} are critical points of −A^(j)-\hat{A}^{(j)}. This removes any witnesses to critical points on layer jj or lower.

Now we must filter out any critical points on layers strictly later than jj. Let x∗∈W(η∗)x^{*}\in\mathcal{W}(\eta^{*}) denote a potential witness that is on layer jj or later (having already filtered out critical points on layers j−1j-1 or earlier). Through finite differences, estimate g=±∇xf(x)g=\pm\nabla_{x}f(x) evaluated at x=x∗x=x^{*}. Choose any random vector rr perpendicular to gg, and therefore parallel to the critical hyperplane. Let α=Proj1..j(x∗,r)\alpha=\text{Proj}_{1..j}(x^{*},r). If it turns out that x∗x^{*} is a witness to a critical point on layer jj then for all ϵ<α\epsilon<\alpha we must have that x∗+ϵr∈W(η∗)x^{*}+\epsilon r\in\mathcal{W}(\eta^{*}). Importantly, we also have the converse: with high probability for δ>α\delta>\alpha we have that x∗+δr∉W(η∗)x^{*}+\delta r\not\in\mathcal{W}(\eta^{*}). However, observe that if x∗x^{*} is not a witness to a neuron on layer jj then one of these two conditions will be false. We have already ruled out witnesses on earlier neuron, so if x∗x^{*} is a witness to a later neuron on layer j′>jj^{\prime}>j then it is unlikely that the layer-j′j^{\prime} polytope is the same shape as the layer-jj polytope, and therefore we will discover this fact. In the case that the two polytopes are actually identical, we can mount the following attack and if it fails we know that our initial input was on the wrong layer.

4.3 Recovering multiple witnesses for the same neuron

The above procedure yields a single witness x∗∈W(η∗)x^{*}\in\mathcal{W}(\eta^{*}) so that L(η∗)=j+1\mathcal{L}(\eta^{*})=j+1. We expand this to a collection of witnesses WW where all x∈Wx\in W have x∈W(η∗)x\in\mathcal{W}(\eta^{*}), requiring the set to be diverse:

A collection of inputs SS is fully diverse at layer jj if for all η\eta with L(η)=j\mathcal{L}(\eta)=j and for s∈{−1,1}s\in\{-1,1\} there exists x∈Sx\in S such that s⋅V(η;x)≥0s\cdot\mathcal{V}(\eta;x)\geq 0.

Informally, being diverse at layer jj means that if we consider the projection onto the space of layer jj (by computing f1..j(x)f_{1..j}(x) for x∈Sx\in S), for every neuron η\eta there will be at least one input x+∈Sx_{+}\in S that the neuron is positive, and at least one input x−∈Sx_{-}\in S so that the neuron is negative.

Our procedure is as follows. Let nn be normal to the hyperplane x∗x^{*} is on. Choose some rr with r⋅n=0r\cdot n=0 and let α=Proj1..j(x∗,r)\alpha=\text{Proj}_{1..j}(x^{*},r) to define x′=x∗+αrx^{\prime}=x^{*}+\alpha r as a point on the layer-jj polytope boundary. In particular, this implies that we still have that x′∈W(η∗)x^{\prime}\in\mathcal{W}(\eta^{*}) (because rr is perpendicular to nn) but also x′∈W(ηu)x^{\prime}\in\mathcal{W}(\eta_{u}) for some neuron L(ηu)<j\mathcal{L}(\eta_{u})<j (by construction of α\alpha). Call this input x′x^{\prime} the double-critical point (because it is a witness to two critical points simultaneously).

From this point x′x^{\prime}, we would like to obtain a new point yy so that we still have y∈W(η∗)y\in\mathcal{W}(\eta^{*}), but that also yy is on the other side of the neuron ηu\eta_{u}, i.e., sign(V(ηu;x∗))≠sign(V(ηu;y))\text{sign}(\mathcal{V}(\eta_{u};x^{*}))\neq\text{sign}(\mathcal{V}(\eta_{u};y)). Figure 3 (right) gives a diagram of this process. In order to follow x∗x^{*} along its path, we first need to find it a critical point on the new hyperplane, having just been bent by the neuron ηu\eta_{u}. We achieve this by performing a critical-point search starting ϵ\epsilon-far away from, and parallel to, the hyperplane from neuron ηu\eta_{u} (the dashed line in Figure 3). This returns a point yy from where we can continue the hyperplane following procedure.

The geometric view hurts us here: because the diagram is a two-dimensional projection, it appears that from the critical point yy there are only two directions we can travel in: away from x′x^{\prime} or towards x′x^{\prime}. Traveling away is preferable—traveling towards x′x^{\prime} will not help us construct a fully diverse set of inputs.

However, a d0d_{0}-dimensional input space has in general (d0−1)(d_{0}-1) dimensions that remain on the neuron η∗\eta^{*}. We defer to Section 5.5.1 an efficient method for selecting the continuation direction. For now, observe that choosing a random direction will eventually succeed at constructing a fully-diverse set, but is extremely inefficient: there exist better strategies than choosing the next direction.

4.4 Brute force recovery

Given this collection SS, we can now—through brute force work—recover the correct sign assignment as follows. As described above, compute a fully diverse set of inputs {xi}\{x_{i}\} and define hi=f1..j(xi)h_{i}=f_{1..j}(x_{i}). Then, for all possible 2dj2^{d_{j}} assignments of signs s∈{−1,1}djs\in\{-1,1\}^{d_{j}}, compute the guessed weight matrix A^s(j)=s⊙A^(j)\hat{A}^{(j)}_{s}=s\odot\hat{A}^{(j)}.

Instantiating the Differential Attack in Practice

The above idealized attack would efficiently extract neural network models but suffers from two problems. First, many of the algorithms are not numerically stable and introduce small errors in the extracted weights. Because errors in layer ii compound and cause further errors at layers j>ij>i, it is necessary to keep errors to a minimum. Second, the attack requires more chosen-inputs than is necessary; we develop new algorithms that require fewer queries or re-use previously-queried samples.

Each sub-section that follows is independent from the surrounding sub-sections and modifies algorithms introduced in Section 4. For brevity, we assume complete knowledge of the original algorithm and share the same notation. Readers may find it helpful to review the original algorithm before proceeding to each subsection.

1 Improving Precision of Extracted Layers

To begin, select a neuron η\eta with L(η)=j\mathcal{L}(\eta)=j. By querying the already-extracted model f^1..j\hat{f}_{1..j}, analytically compute witnesses {xi}i=1dj\{x_{i}\}_{i=1}^{d_{j}} so that each xi∈W^(η)x_{i}\in\hat{\mathcal{W}}(\eta). This requires no queries to the model as we have already extracted this partial model.

If the A^(j)\hat{A}^{(j)} and b^(j)\hat{b}^{(j)} were exactly correct then W(η;⋅)≡W^(η;⋅)\mathcal{W}(\eta;\cdot)\equiv\hat{\mathcal{W}}(\eta;\cdot) and so each computed critical point xix_{i} would be exactly a critical point of the true model ff and so V(η;xi)≡0\mathcal{V}(\eta;x_{i})\equiv 0. However, if there is any imprecision in the computation, then in general we will have that 0<∣V(η;xi)∣<ϵ0<\lvert\mathcal{V}(\eta;x_{i})\rvert<\epsilon for some small ϵ>0\epsilon>0.

Fortunately, given this xix_{i} it is easy to compute xi′x^{\prime}_{i} so that V(η;xi′)=0\mathcal{V}(\eta;x^{\prime}_{i})=0. To do this, we sample a random Δ∈Rd0\Delta\in\mathcal{R}^{d_{0}} and apply our binary search procedure on the range [xi+Δ,xi−Δ][x_{i}+\Delta,x_{i}-\Delta]. Here we should select Δ\Delta so that ∥Δ∥\lVert\Delta\rVert is sufficiently small that the only critical points it crosses is the one induced by neuron η\eta, but sufficiently large that it does reliably find the true critical point of η\eta.

Repeating this procedure for each witness xix_{i} gives a set of witnesses {xi′}i=1dj\{x^{\prime}_{i}\}_{i=1}^{d_{j}} to the same neuron η\eta. We compute hi=f^1..j−1(xi′)h_{i}=\hat{f}_{1..j-1}(x^{\prime}_{i}) as the hidden vector that layer jj will receive as input. By assumption hih_{i} is precise already and so f^1..j−1≈f1..j−1\hat{f}_{1..j-1}\approx f_{1..j-1}. Because xi′x^{\prime}_{i} is a witness to neuron η\eta having value zero, we know that that An(j)⋅hi=0A^{(j)}_{n}\cdot h_{i}=0 where nn corresponds to the row of neuron η\eta in A(j)A^{(j)}.

Ideally we would solve this resulting system with least squares. However, in practice, occasionally the conversion from x→x′x\to x^{\prime} fails because x′x^{\prime} is no longer a witness to the same neuron η′\eta^{\prime}. This happens when there is some other neuron (i.e., η′\eta^{\prime}) that is closer to xx than the true neuron η\eta. Because least squares is not robust to outliers this procedure can fail to improve the solution.

We take two steps to ensure this does not happen. First, observe that if Δ\Delta is smaller, the likelihood of capturing incorrect neurons η′\eta^{\prime} decreases faster than the likelihood of capturing the correct neuron η\eta. Thus, we set Δ\Delta to be small enough that roughly half of the attempts at finding a witness x′x^{\prime} fails. Second, we apply a (more) robust method of determining the vector that satisfies the solution of equations [JOB+18]. However, even these two techniques taken together occasionally fail to find valid solutions to improve the quality. When this happens, we reject this proposed improvement and keep the original value.

2 Efficient Finite Differences

Most of the methods in this paper are built on computing second partial derivatives of the neural network ff, and therefore developing a robust method for estimating the gradient is necessary. Throughout Section 4 we compute the partial derivative of ff along direction α\alpha evaluated at xx with step size ε\varepsilon as

To compute the second partial derivative earlier, we computed α+i\alpha^{i}_{+} and α−i\alpha^{i}_{-} by first taking a step towards x∗+ϵ0e1x^{*}+\epsilon_{0}e_{1} for a different step size ϵ0\epsilon_{0} and then computed the first partial derivative at this location. However, with floating point imprecision it is not desirable to have two step sizes (ϵ0\epsilon_{0} controlling the distance away from x∗x^{*} to step, and ϵ\epsilon controlling the step size when computing the partial derivative). Worse, we must have that ϵ≪ϵ0\epsilon\ll\epsilon_{0} because if ∂f∂e1ϵ0>∂f∂eiϵ{\partial f\over\partial e_{1}}\epsilon_{0}>{\partial f\over\partial e_{i}}\epsilon then when computing the partial derivative along eie_{i} we may cross the hyperplane and estimate the first partial derivative incorrectly. Therefore, instead we compute

where we both step along eie_{i} and also take the partial derivative along the same eie_{i} (and similarly for -eie_{i}). This removes the requirement for an additional hyperparameter and allows the step size ϵ\epsilon to be orders of magnitude larger, but introduces a new error: we now lose the relative signs of the entries in the row when performing extraction and can only recover ∣Ai,j(1)/Ai,k(1)∣\left\rvert A^{(1)}_{i,j}/A^{(1)}_{i,k}\right\rvert.

We next recover the value sign(Ai,j(1))⋅sign(Ai,k(1))\text{sign}(A^{(1)}_{i,j})\cdot\text{sign}(A^{(1)}_{i,k}). Fortunately, the same differencing process allows us to learn this information, using the following observation: if Ai,j(1)A^{(1)}_{i,j} and Ai,k(1)A^{(1)}_{i,k} have the same sign, then moving in the ej+eke_{j}+e_{k} direction will cause their contributions to add. If they have different signs, their contributions will cancel each other. That is, if

We can repeat this process to test whether each Ai,j(1)A^{(1)}_{i,j} has the same sign as (for example) Ai,1(1)A^{(1)}_{i,1}. However, we still do not know whether any single Ai,j(1)A^{(1)}_{i,j} is positive or negative—we still must recover the row signs as done previously.

3 Finding Witnesses to Critical Points

Throughout the paper we require the ability to find witnesses to critical points. Section 4.2 uses simple binary search to achieve this which is (a) imprecise in practice, and (b) query inefficient. We improve on the witness-finding search procedure developed by [JCB+20]. Again we interpolate between two examples u,vu,v and let xα=(1−α)u+αvx_{\alpha}=(1-\alpha)u+\alpha v. Previously, we repeatedly performed binary search as long as the partial derivatives were not equal ∂f(xα)≠∂f(xβ)\partial f(x_{\alpha})\neq\partial f(x_{\beta}), requiring pp queries to obtain pp bits of precision of the value x∗x^{*}. However, observe that if xαx_{\alpha} and xβx_{\beta} differ in the sign of exactly one neuron ii, then we can directly compute the location x∗x^{*} at which V(ηi;x∗)=0\mathcal{V}(\eta_{i};x^{*})=0 but so that for all other ηj\eta_{j} we have

This approach is illustrated in Figure 4 and relies on the fact that ff is a piecewise linear function with two components. By measuring, f(xα)f(x_{\alpha}) and ∂f(xα)\partial f(x_{\alpha}) (resp., f(xβ)f(x_{\beta}) and ∂f(xβ)\partial f(x_{\beta})), we find the slope and intercept of both the left and right lines in Figure 4 (left). This allows us to solve for their expected intersection (x∗,f^(x∗))(x^{*},\hat{f}(x^{*})). Typically, if there are more than two linear segments, as in the middle of the figure, we will find that the true function value f(x∗)f(x^{*}) will not agree with the expected function value f^(x∗)\hat{f}(x^{*}) we obtained by computing the intersection; we can then perform binary search again and repeat the procedure.

However, we lose some soundness from this procedure. As we see in Figure 4 (right), situations may arise where many ReLU units change sign between xαx_{\alpha} and xβx_{\beta}, but f^(x∗)=f(x∗)\hat{f}(x^{*})=f(x^{*}). In this case, we would erroneously return x∗x^{*} as a critical point, and miss all of the other critical points in the range. Fortunately, this error case is pathological and does not occur in practice.

Suppose that we had already extracted the first jj layers of the neural network and would like to perform the above critical-point finding algorithm to identify all critical points between xαx_{\alpha} and xβx_{\beta}. Notice that we do not need to collect any more critical points from the first jj layers, but running binary search will recover them nonetheless. To bypass this, we can analytically compute SS as the set of all witnesses to critical points on the extracted neural network f^1..j\hat{f}_{1..j} between xαx_{\alpha} and xβx_{\beta}. As long as the extracted network f^\hat{f} is correct so far, we are guaranteed that all points in SS are also witnesses to critical points of the true ff.

Instead of querying on the range (xα,xβ)(x_{\alpha},x_{\beta}) we perform the ∣S∣+1\lvert S\rvert+1 different searches. Order the elements of SS as {si}i=1∣S∣\{s_{i}\}_{i=1}^{|S|} so that si<sj  ⟹  ∣xα−si∣<∣xα−sj∣s_{i}<s_{j}\implies\lvert x_{\alpha}-s_{i}\rvert<\lvert x_{\alpha}-s_{j}\rvert. Abusing notation, let s1=xαs_{1}=x_{\alpha} and s∣S∣=xβs_{|S|}=x_{\beta}. Then, perform binary search on each disjoint range (Si,Si+1)(S_{i},S_{i+1}) for i=1i=1 to ∣S∣−1|S|-1 and return the union.

4 Unification of Witnesses with Noisy Gradients

Recall that to extract A^(l)\hat{A}^{(l)} we extract candidates candidates {ri}\{r_{i}\} and search for pairs ri,rjr_{i},r_{j} that agree on multiple coordinates. This allows us to merge rir_{i} and rjr_{j} to recover (eventually) full rows of A^(l)\hat{A}^{(l)}. With floating point error, the unification algorithm in Section 4.3.2 fails for several reasons.

Our core algorithm computes the normal to a hyperplane, returning pairwise ratios A^i,j(1)/A^i,k(1)\hat{A}^{(1)}_{i,j}/\hat{A}^{(1)}_{i,k}; throughout Section 4 we set A^i,1(1)=1\hat{A}^{(1)}_{i,1}=1 without loss of generality.

Unfortunately in practice there is loss of generality, due to the disparate impact of numerical instability. Consider the case where Ai,1(l)<10−αA^{(l)}_{i,1}<10^{-\alpha} for α≫0\alpha\gg 0, but Ai,k(l)≥1A^{(l)}_{i,k}\geq 1 for all other kk. Then there will be substantially more (relative) floating point imprecision in the weight Ai,1(l)A^{(l)}_{i,1} than in the other weights. Before normalizing there is no cause for concern since the absolute error is no larger than for any other. However, the described algorithm now normalizes every other coordinate Ai,k(l)A^{(l)}_{i,k} by dividing it by Ai,1(l)A^{(l)}_{i,1}—polluting the precision of these values.

Therefore we adjust our solution. At layer ll, we are given a collection of vectors R={ri}i=1nR=\{r_{i}\}_{i=1}^{n} so that each rir_{i} corresponds to the extraction of some (unknown) neuron ηi\eta_{i}. First, we need an algorithm to cluster the items into sets {Sj}j=1dl\{S_{j}\}_{j=1}^{d_{l}} so that Sj⊂RS_{j}\subset R and so that every vector in SjS_{j} corresponds to one neuron on layer ll. We then need to unify each set SjS_{j} to obtain the final row of A^j(l)\hat{A}^{(l)}_{j}.

We construct the three dimensional Mi,a,b=ra(i)/rb(i)M_{i,a,b}=r^{(i)}_{a}/r^{(i)}_{b}. Given MM, the a good guess for the scalar cabc_{ab} so that ra(i)=rb(i)⋅Cabr^{(i)}_{a}=r^{(i)}_{b}\cdot C_{ab} along as many coordinates ii as possible is the assignment Cab=mediani Mi,a,bC_{ab}=\text{median}_{i}\,M_{i,a,b}, where the estimated error is eab=stdevi Mi,a,be_{ab}=\text{stdev}_{i}\,M_{i,a,b}.

If all rar_{a} were complete and had no imprecision then CabC_{ab} would have no error and so Cab=Cax⋅CxbC_{ab}=C_{ax}\cdot C_{xb}. However because it does have error, we can iteratively improve the guessed CC matrix by observing that if the error eax+exb<eabe_{ax}+e_{xb}<e_{ab} then the guessed assignment Cax⋅CxbC_{ax}\cdot C_{xb} is a better guess than CabC_{ab}. Thus we replace Cab←Cax⋅CxbC_{ab}\leftarrow C_{ax}\cdot C_{xb} and update eab←eax+exbe_{ab}\leftarrow e_{ax}+e_{xb}. We iterate this process until there is no further improvement. Then, finally, we choose the optimal dimension a=arg mina∑beaba=\mathop{\text{arg min}}_{a}\sum_{b}e_{ab} and return the vector CaC_{a}. Observe that this procedure closely follows constructing the union of two partial entries rir_{i} and rjr_{j} except that we perform it along the best axis possible for each coordinate.

5 Following Neuron Critical Points

Section 4.4.3 developed techniques to construct a set of witnesses to the same neuron being at its critical point. We now numerically-stabilize this procedure.

As before we begin with an input x∗∈W(η∗)x^{*}\in\mathcal{W}(\eta^{*}) and compute the normal vector nn to the critical plane at x∗x^{*}, and then choose rr satisfying r⋅n=0r\cdot n=0. The computation of nn will necessarily have some floating point error, so rr will too.

This means when we compute α=Proj1..j(x∗,r)\alpha=\text{Proj}_{1..j}(x^{*},r) and let x′=x∗+rαx^{\prime}=x^{*}+r\alpha the resulting x′x^{\prime} will be almost exactly a witness to some neuron ηu\eta_{u} with L(ηu)<j\mathcal{L}(\eta_{u})<j, (because this computation was performed analytically on a precisely extracted model), but x′x^{\prime} has likely drifted off of the original critical plane induced by η∗\eta^{*}.

To address this, after computing α\alpha we initially take a smaller step and let x1=x∗+rαx_{1}=x^{*}+r\sqrt{\alpha}. We then refine the location of this point to a point x2x_{2} by performing binary search on the region x1−ϵnx_{1}-\epsilon n to x1+ϵnx_{1}+\epsilon n for a small step ϵ\epsilon. If there was no error in computing nn then x1=x2x_{1}=x_{2} because both are already witnesses to η∗\eta^{*}. If not, any error has been corrected. Given x∗x^{*} and x2x_{2} we now can now compute α2=Proj1..j(x∗,x2−x∗)\alpha_{2}=\text{Proj}_{1..j}(x^{*},x_{2}-x^{*}) and let xˉ′=x∗+(x2−x∗)α2\bar{x}^{\prime}=x^{*}+(x_{2}-x^{*})\alpha_{2} which will actually be a witness to both neurons simultaneously.

Next we give a stable method to compute yy that is a witness to η∗\eta^{*} and on the other side of ηu\eta_{u}. The previous procedure required a search parallel to ηu\eta_{u} and infinitesimally displaced, but this is not numerically stable without accurately yet knowing the normal to the hyperplane given by ηu\eta_{u}.

Instead we perform the following procedure. Choose two orthogonal vectors of equal length β\beta, γ\gamma and and perform binary search on the line segments that trace out the perimeter of a square with coordinates xˉ′±β±γ\bar{x}^{\prime}\pm\beta\pm\gamma.

When ∥β∥\lVert\beta\rVert is small, the number of critical points crossed will be exactly four: two because of ηu\eta_{u} and two because of η∗\eta^{*}. As long as the number of critical points remains four, we double the length of β\beta and γ\gamma.

Eventually we will discover more than four critical points, when the perimeter of the square intersects another neuron ηz\eta_{z}. At this point we stop increasing the size of the box and can compute the continuation direction of η∗\eta^{*} by discarding the points that fall on ηu\eta_{u}. We can then choose yy as the point on η∗\eta^{*} that intersected with the largest square binary search.

The hyperplane following procedure will eventually recover a fully diverse set of inputs WW but it may take a large number of queries to do so. We can reduce the number of queries by several orders of magnitude by carefully choosing the continuation direction rr instead of randomly choosing any value so that r⋅n=0r\cdot n=0.

Given the initial coordinate xx and after computing the normal nn to the hyperplane, we have d0−1d_{0}-1 dimensions that we can choose between to travel next. Instead of choosing a random r⋅n=0r\cdot n=0 we instead choose rr such that we make progress towards obtaining a fully diverse set WW.

Define WiW_{i} as the set of witnesses that have been found so far. We say that this set is diverse on neuron η\eta if there exists an x+,x−∈Wix_{+},x_{-}\in W_{i} such that V(η;x+)≥0\mathcal{V}(\eta;x_{+})\geq 0 and V(η;x−)<0\mathcal{V}(\eta;x_{-})<0. Choose an arbitrary neuron ηt\eta_{t} such that WiW_{i} is not diverse on ηt\eta_{t}. (If there are multiple such options, we should prefer the neuron that would be easiest to reach, but this is secondary.)

Our goal will be to choose a direction rr such that (1) as before, r⋅n=0r\cdot n=0, however (2) Wi∪{x+αr}W_{i}\cup\{x+\alpha r\} is closer to being fully diverse. Here, “closer” means that d(W)=min⁡x∈W∣V(ηt;x)∣d(W)=\min_{x\in W}\lvert\mathcal{V}(\eta_{t};x)\rvert is smaller. Because the set is not yet diverse on ηt\eta_{t}, all values are either positive or negative, and it is our objective to switch the sign, and therefore become closer to zero. Therefore our procedure sets

performing the minimization through random search over 1,0001{,}000 directions.

Evaluation

We implement the described extraction algorithm in JAX [BFH+18], a Python library that mirrors the NumPy interface for performing efficient numerical computation through just in time compilation.

Computing (ε,10−9)(\varepsilon,10^{-9})-functional equivalence is simple. Let Sˉ⊂S\bar{S}\subset S be a finite set consisting of ∣Sˉ∣>109\lvert\bar{S}\rvert>10^{9} different inputs drawn x∈Sx\in S. Sort Sˉ\bar{S} by ∣f(x)−f^(x)∣\lvert f(x)-\hat{f}(x)\rvert and choose the lowest ε\varepsilon so that

In practice we set ∣Sˉ∣=109\lvert\bar{S}\rvert=10^{9} and compute the max⁡\max so that evaluating the function is possible under an hour per neural network.

2 Computing (ε,0)𝜀0(\varepsilon,0)-Functional Equivalence

Directly computing (ε,0)(\varepsilon,0)-functional equivalence is infeasible, and is NP-hard (even to approximate) by reduction to Subset Sum [JCB+20]. We nevertheless propose two methods that efficiently give upper bounds that perform well.

By propagating bounds layer-by-layer we can obtain an upper bound on the maximum error of the output of the model.

This method is able to prove an upper bound on (ϵ,0)(\epsilon,0) functional equivalence for some networks, when the pairing algorithm succeeds. However, we find that there are some networks that are (2−45,10−9)(2^{-45},10^{-9}) functionally equivalent but where the weight alignment procedure fails. Therefore, we suspect that there are more equivalence classes of functions than scalar multiples of permuted neurons, and so develop further methods for tightly computing (ε,0)(\varepsilon,0) functional equivalence.

The above analysis approach is loose. Our second approach gives exact bounds with an additive error at most 10−1010^{-10}.

Neural networks are piecewise linear functions, and so can be cast as a mixed integer linear programming (MILP) problem [KBD+17]. We directly express Definition 1 as a MILP, following the process of [KBD+17] by encoding linear layers directly, and encoding ReLU layers by assigning a binary integer variable to each ReLU. Due to the exponential nature of the problem, this approach is limited to small networks.

State-of-the-art MILP solvers offer a maximum (relative, additive) error tolerance of 10−1010^{-10}; for our networks the SVD upper bound is often 10−1010^{-10} or better, so the MILP solver gives a worse bound, despite theoretically being tight.

Results

We extract a wide range of neural network architectures; key results are given in Table 1 (Section 1). We compute (ε,δ)(\varepsilon,\delta)-functional equivalence at δ=10−9\delta=10^{-9} and δ=0\delta=0 on the domain S={x ⁣:∥x∥2<d0  ∧  x∈X}S=\{x\colon\lVert x\rVert_{2}<d_{0}\,\,\wedge\,\,x\in\mathcal{X}\}, sufficient to explore both sides of every neuron.

Concluding Remarks

We introduce a cryptanalytic method for extracting the weights of a neural network by drawing analogies to cryptanalysis of keyed ciphers. Our differential attack requires multiple orders of magnitude fewer queries per parameter than prior work and extracts models that are multiple orders of magnitude more accurate than prior work. In this work, we do not consider defenses—promising approaches include detecting when an attack is occuring, adding noise at some stage of the model’s computation, or only returning the label corresponding to the output, any of these easily break our presented attack.

The practicality of this attack has implications for many areas of machine learning and cryptographic research. The field of secure inference relies on the assumption that observing the output of a neural network does not reveal the weights. This assumption is false, and therefore the field of secure inference will need to develop new techniques to protect the secrecy of trained models.

We believe that by casting neural network extraction as a cryptanalytic problem, even more advanced cryptanalytic techniques will be able to greatly improve on our results, reducing the computational complexity, reducing the query complexity and reducing the number of assumptions necessary.

Acknowledgements

We are grateful to the anonymous reviewers, Florian Tramèr, Nicolas Papernot, Ananth Raghunathan, and Úlfar Erlingsson for helpful feedback.

References