Skip to content
ImagineWorld

Privacy Attacks – Stealing Models

node_idnode-book_adversarial-ai-defense-strategies_chapter-08-privacy-attacks-stealing-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titlePrivacy Attacks – Stealing Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Privacy Attacks – Stealing Models

Section titled “Chapter 8 — Privacy Attacks – Stealing Models”

With AI systems increasingly ingrained in our daily lives, from personal assistants to healthcare diagnostics, the potential for privacy breaches has escalated dramatically. This chapter delves into the realm of privacy attacks within adversarial AI, a domain where attackers intentionally manipulate AI models to extract sensitive information, including confidential model information. We will look at the attacks and attack scenarios, provide code examples, and discuss mitigations.

The key sections and topics we will cover are as follows:

  • Understanding privacy attacks: Introducing the fundamental concepts of privacy attacks in AI, including model extraction, model inversion, and membership inference attacks, this section sets the stage for a deeper exploration of each attack spread over two chapters.
  • Stealing models with model extraction attacks: This chapter will cover model extraction attacks. We will dive into specific types of model extraction attacks, illustrating each with examples. This includes a demonstration of using popular models such as our CIFAR-10 CNN.
  • Defenses and mitigations: We will cover both preventative defenses such as adversarial training and output perturbation and detective measures such as query monitoring.

By the end of this chapter, you will have a solid understanding of the nature of model extraction attacks in adversarial AI and the tools and techniques available to counter them.

Let’s start by understanding the main types of privacy attacks in adversarial AI.

Unlike poisoning, tampering, and evasion attacks, privacy attacks do not seek to alter the model in any way. Instead of targeting model integrity, these attacks focus on model confidentiality and extracting sensitive information, which, in turn, can seriously impact the trust users and businesses place in these AI systems. As a result, they represent a significant challenge, posing risks to individual privacy, organizational security, and competitive advantage. These attacks come in the form of model extraction, model inversion, and membership inference, and each targets AI systems in unique ways:

  • Model extraction attacks: These attacks involve replicating an AI model’s functionality by observing its responses to various inputs. The primary risk here is the potential loss of intellectual property and the unauthorized duplication of proprietary AI models, which can have significant financial and competitive implications.
  • Model inversion attacks: These attacks focus on extracting sensitive data that’s used in training AI models. The concern is particularly acute in cases where the training data includes personal or confidential information. The impact of model inversion attacks is most concerning in sectors such as healthcare or finance, where privacy breaches can have serious consequences.
  • Membership inference attacks: In these attacks, the goal is to determine if a particular data record was part of the training dataset of a model. The critical risk involves privacy violations, especially when the training data contains sensitive personal information. Such attacks can undermine the confidentiality of data subjects, leading to ethical and legal concerns.

Let’s start our exploration of privacy attacks by looking at how Adversarial AI can be used to steal a model using model extraction attacks.

Stealing models with model extraction attacks

Section titled “Stealing models with model extraction attacks”

Model extraction attacks in AI involve replicating the functionality of machine learning models. The process aims to replicate the target models by observing and mimicking their output responses to various inputs. Model extraction attacks, using an iterative query-based approach, involve a process where the attacker repeatedly queries the target AI model with carefully selected inputs. The attacker receives output data from the model with each query, such as predictions or confidence scores. This data is then used to refine and train a new model iteratively – the extraction model – to replicate the target model’s decision-making process. Over time, as more queries are made, and more output data is collected, the extraction model becomes increasingly similar in functionality to the original target model, effectively capturing its behavior and decision-making patterns.

There are different approaches to staging this attack, as follows:

  • Functionally equivalent extraction
  • Learning-based methods
  • Generative student-teacher learning methods

The first approach aims to achieve maximum fidelity by calculating weights and biases. In contrast, the other two approaches rely on finding representative data to train a model to achieve extracted model accuracy – that is, the same outputs from the same inputs.

This attack attempts to calculate the weights and biases of the victim model aiming for fidelity – that is, both the victim and the cloned model provide approximately the same output on the same inputs.

Calculating exact weights and biases allows us to reconstruct an identical copy of the model. This creates a complex non-linear optimization equation that has proven to be a 3-SAT problem. In math, this is what we call an NP-complete problem – that is, a problem that can’t be solved. This is covered in great detail in the 2020 paper referenced later in this section.

Aiming for approximately equivalent results is also a computationally challenging task because trying to solve a multiparameter non-linear equation creates an explosion of combinations that often leads to NP problems. As a result, the approach focuses on relatively simple ANN architectures with assumptions on the architecture itself.

The algorithm assumes that the victim model is a two-layer model and that the attacker knows the input and hidden layer dimensionality, as well as the number of classes. Based on these assumptions, the attacker observes the output of the target model for a set of inputs and then uses this information to construct a new model that produces similar outputs for similar inputs. To do so, the attacker uses the workings of the activation function, while the model uses a rectified linear unit (ReLU) activation function. We will explain in more detail this shortly.

Algorithm: As we briefly touched on in Chapter 1, an activation function in neural networks is a mathematical function that’s applied to a neuron’s output, transforming the input signal into an output signal for the next layer in the network. ReLU is an activation function that outputs the input directly if it is positive; otherwise, it outputs zero. The following figure shows the apparent sign change in the function’s outputs based on the user input:

Figure 8.1 – ReLU activation function

Figure 8.1 – ReLU activation function

Using a ReLU activation function is a key factor here as it allows the attacker to segment inputs and outputs based on their effect on ReLU.

The attacker queries the victim on selected inputs and logs the raw output values (logits).

They then partition the query inputs into linear regions where the ReLU units have the same sign. This can be done by finding pairs of inputs that differ by a small perturbation and have different logits (raw outputs), indicating that they cross a ReLU boundary. The attacker assigns a label to each region and groups the inputs and logits by region. The algorithm then uses input/output pair comparisons, some linear equations, and additional queries to calculate the weights and biases of the hidden layers. It then uses a least square regression between the logits and hidden layer outputs to calculate the weights and bias of the output layer. Armed with this information, the attacker creates a functionally equivalent neural network.

Example: Consider a neural network based on customer profiles for loan approval. An attacker could create various synthetic customer profiles, input them into the target model, and observe the loan approval or rejection decisions. Using this information, the attacker can train a new model that mimics these decision patterns, achieving functional equivalence to the original model.

You can find an implementation of this attack in ART’s source code and specifically the file at https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/art/attacks/extraction/functionally_equivalent_extraction.py.

You can also read the entire research paper that inspired this implementation in the 2020 paper High Accuracy and High Fidelity Extraction of Neural Networks, by Matthew Jagielski, Nicholas Carlini, David Berthelot, Alex Kurakin, and Nicolas Papernot. You can find the paper at https://arxiv.org/abs/1909.01838. The authors, especially Carlini and Papernot, are leading figures in Adversarial AI, and the paper provides a good discussion of the theoretical limitations around full functionally equivalent extractions.

As we already mentioned, calculating the weights and biases from input/output pairs is a computationally challenging problem to solve. Architecture complexity exponentially increases the number of queries, and for some models, it is an impossible problem to solve. This is what computational complexity theory calls NP-hard problems – that is, problems where there is no known efficient way to find a solution quickly (in polynomial time).

We can make this easier by reducing complexity and applying the technique to a simpler, more specific architecture and activation function. This restricts the approach but achieves 100% fidelity.

A complementary approach is constraining the search using environment parameters such as times-side channels. In other words, by observing time differences in query execution, the attacker can use regression techniques to infer the depth of the network – that is, the number of layers. This exploits the relationship between execution time and network depth, and it assumes that the attacker knows the underlying compute architecture (CPUs and GPUs), which makes the attack more suitable to solutions hosted in well-known architectures such as AWS SageMaker or Azure ML Services, where the prediction models can be formulated and tried out. Reconnaissance techniques can also extract this information and restrict the forecasts.

This variation is documented in the 2019 paper Stealing Neural Networks via Timing Side Channels, by Duddu V et al., found at https://arxiv.org/abs/1812.11720. They haven’t published the code for this but it provides an insightful attack description. The attack uses ensembles of random forests and boosted decision trees as the attack regressors to estimate the depth. These are complemented with a reinforcement-learning search to reconstruct the model using depth as a constraint and the outcome’s accuracy – based on victim model queries – as the reward function. Finally, a recurrent neural network (RNN) is employed to derive the model’s hyperparameters.

Unlike the formal functionally equivalent extraction approach we described earlier, this variant produces an approximate accuracy and not 100% fidelity. However, it makes no assumptions about the model and is better suited to black-box attacks on more complicated architectures, assuming the attacker knows the system specification underpinning the deployed service, and more specifically the compute specification (CPU and GPUs).

In the next subsection, we will cover an approach that tackles things differently – that is, it sacrifices full fidelity to extract models regardless of architecture and ones with greater complexity.

Unlike the previous approach, learning-based approaches are more black-boxed attacks that aim to find random data that captures the target model’s decision boundaries and then use them to train an extracted model that approximates the target one. The attacker queries the model with usual randomly sampled items and uses the predictions to formulate a training set that it then uses against the model clone – that is, the extracted model. The following figure summarizes this approach:

Figure 8.2 – Learning-based model extraction attacks

Figure 8.2 – Learning-based model extraction attacks

There are two well-known variations of this approach. Let’s take a look.

Copycat CNN is a well-known technique that trains the extracted neural network – or the copycat, as it calls it – to replicate the behavior of the target model. Copycat CNN formulates a training set by querying the target model. It uses a set of input data to query the target model, then trains the copycat model on these inputs and the obtained outputs (predictions) from the target model.

Algorithm: The technique consists of two steps:

  1. Fake dataset generation: The attacker queries the target network with random unlabeled data and collects its predictions. The attacker then labels the data with the predictions and creates a fake dataset. The fake dataset is supposed to capture the decision boundaries of the target network. The attack requires the images to be from the same domain as the black-box model’s task (for example, natural images for natural image classification) and to be the same size as the black-box model’s input.
  2. Copycat network training: Using the fake dataset, the attacker trains a copycat network with the same architecture as the target network. This requires knowledge of the architecture of the target network and the number of the target network’s outputs. The copycat network is expected to learn the same features and weights as the target network and produce similar outputs.

The input for the attacker is the target network’s API, which allows the attacker to query the network with any data and receive its predictions. The output for the attacker is the copycat network, which mimics the target network’s performance and behavior.

Example: Suppose an attacker targets a CNN that’s used for animal classification. First, they would collect a diverse set of animal images, use these images to query the target CNN, and record the predicted classes or confidence scores. Then, they would use this data to train the Copycat CNN, effectively teaching it to classify animals similarly to the target model.

Reconnaissance is essential here. Knowing the model type helps the attacker constrain the generation of fake datasets to approximate the decision boundaries better. Suppose the target model is based on a publicly available model (for example, ResNet50). In that case, the attacker uses the public model and fine-tunes it with the results of the API queries to shorten replication and evade detection.

This attack has been used successfully against Microsoft’s Azure Emotion API in research settings, extracting 97.3% of the API’s performance. The approach is described in great detail in the relevant research paper, Copycat CNN: Stealing Knowledge by Persuading Confession with Random Non-Labeled Data, by Correia-Silva et al. in 2018. The paper can be found at https://arxiv.org/abs/1806.05476, and the source code for their experiments can be found in the following GitHub repository: https://github.com/jeiks/Stealing_DL_Models.

You can also find a more compact implementation in ADT in the file at https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/art/attacks/extraction/copycat_cnn.py. The source code provides a detailed view of the implementation. Still, you can use ADT to evaluate this type of attack by using its API documentation at https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/extraction.html.

Knockoff Nets are similar to Copycat CNN and follow the same approach of querying the target model with a dataset and training a new model on the obtained responses. The difference lies in the lack of assumptions for the target model and a nuanced approach to data sampling and model training. The latter often involves more sophisticated techniques to refine the training process of the knockoff model.

Algorithm: The input for the attacker is the victim model’s API, which allows the attacker to query the model with any image and receive its predictions. The steps for the attack are as follows:

  1. Training set generation: Although an attacker can choose a distribution of images to query from, such as ImageNet, CIFAR-10, or a custom dataset, the attack works well, even if the input is from a different distribution or domain. The attack has two sampling strategies: random sampling, where images are selected randomly from a chosen distribution, and adaptive sampling, where the attack uses reinforcement learning (RL). Here, an RL agent learns to select the most informative images to query based on the feedback from the knockoff model. The RL agent is trained with a policy gradient algorithm that maximizes the expected reward, which improves the knockoff model’s performance after each query. Research shows that the RL-based method can achieve better results than the random or adaptive sampling methods. The attacker queries a batch of images from the chosen distribution to the victim model and obtains its predictions. The attacker then labels the images with the predictions and creates a dataset of image-prediction pairs.
  2. Knockoff model training: Using the image-prediction dataset, the attacker trains a knockoff model with the same task and output space as the victim model. The attacker can use any architecture and training method for the knockoff model, so long as it can produce predictions similar to those of the victim model. The attacker repeats Steps 1 and 2 until the knockoff model reaches a desired level of performance or functionality. The attacker can use different strategies to select the images to query, such as random sampling, adaptive sampling, or active learning.

Example: If an attacker aims to replicate a model that classifies clothing items, they need to gather a large dataset of clothing images. These images are then used to query the target classification model, and the output labels or confidence scores are recorded. The attacker uses this labeled dataset to train the knockoff model, adjusting the training process so that it closely matches the target model’s classification behavior.

This attack is less constrained than Copycat CNN, relaxing the constraints and making it more general and applicable to black-box model extraction attacks. It has been used successfully – in research setup – against a face image analysis API. The related research paper does not mention which API it used but provides a wealth of information on the attack. The paper is called Knockoff Nets: Stealing Functionality of Black-Box Models and was published in 2018 by Tribhuvanesh Orekondy, Bernt Schiele, and Mario Fritz. It can be found at https://arxiv.org/abs/1812.02766.

It has a code repository that contains various experiments at https://github.com/tribhuvanesh/knockoffnets.

ART also provides an implementation that can be used out of the box with an API, as described in its documentation: https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/extraction.html.

You can also dive into its implementation code to better understand it. It is in ART’s source code, specifically this file: https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/art/attacks/extraction/knockoff_nets.py.

Learning-based methods rely on the attacker to manually select and evaluate the adversarial samples they use in the queries. The authors of Copycat CNN created a more automated approach in the Copycat CNN Extension, which automated the process of selecting random images unrelated to the target network’s problem domain. The process involves using random images from the OpenImages and ILSVRC datasets. The target network is queried with these images for hard labels, and the image balance per class is achieved through random replication or removal. This forms the fake dataset for training the copycat network.

This is documented in their more recent paper, Copycat CNN: Are Random Non-Labeled Data Enough to Steal Knowledge from Black-box Models?, published in 2021 by Jacson Rodrigues Correia-Silva, Rodrigo F. Berriel, Claudine Badue, Alberto F. De Souza, Thiago Oliveira-Santos. It can be found at https://arxiv.org/abs/2101.08717. Their source code is part of the repository as Copycat CNN at https://github.com/jeiks/Stealing_DL_Models.

What’s interesting about their extension is that random images unrelated to the network’s domain can be used successfully across multiple domains, with authors reporting high accuracy in seven different problems, such as face recognition, digit recognition, and traffic sign recognition.

It also helps create reasonable extraction of the target model using a different architecture – for example, extracting a VGG by training AlexNet. The extracted models exhibit robustness to the random initialization parameters. For instance, they train the same target network three times and run an attack each time, creating extracted models with stable and consistent performance.

These results strongly indicate that introducing randomness helps the network explore and generalize different feature spaces, providing superior extraction performance.

In the next subsection, we will cover a more sophisticated adversarial workflow that uses machine learning to generate even more random samples and drive the extracted model training as an optimization problem.

Generative student-teacher extraction (distillation) attacks

Section titled “Generative student-teacher extraction (distillation) attacks”

This approach is a more advanced version of learning-based extraction attacks. However, the attacker uses generative techniques to create the adversarial samples to query the victim model instead of directly generating the samples.

The approach is based on knowledge distillation, a technique where a smaller, simpler model (the student) is trained to replicate the behavior of a larger, more complex model (the teacher). This process aims to transfer knowledge from the complex model to the simpler one. This technique is a form of knowledge transfer and can have legitimate reasons for its use, including reducing computation cost, model size, and memory footprints of DNNs without compromising model performance. It can also be used as a security optimization to preserve the privacy of original training data.

Note

AI pioneer Geoffrey Hinton and others introduced the concept of knowledge distillation in a 2015 paper, Distilling the Knowledge in a Neural Network. A more recent paper, Knowledge Distillation: A Survey, by Gou et al., published in 2021, provides an up-to-date survey or approaches and can be found at https://arxiv.org/abs/2006.05525. These references are for those interested in gaining a deeper understanding of the topic. A more practical and hands-on introduction that uses Keras and provides code examples can be found at https://keras.io/examples/vision/knowledge_distillation/.

Those using knowledge distillation for legitimate reasons will typically have access to the original training dataset. In contrast, in an adversarial setting, the attacker will work in a black-box scenario and is unlikely to have access to the training dataset.

Researchers working on data-free knowledge distillation attacks have focused on solving this problem with generative models that create adversarial data to query. They call the generative model the generator. It’s designed to maximize the divergence between the student and teacher model, whereas then the student model is trained to minimize this divergence. The algorithm is an adversarial game of iterations with two components (generator and student) competing to maximize and minimize the same function. Each iteration consists of two alternate loops:

  • Generate challenging data samples that maximize the difference between training data and student
  • Apply supervised training to the student to minimize the divergence by penalizing it

This approach uses CNNs as the generator part of a generative adversarial network (GAN). A GAN consists of two competing networks, a generator and a discriminator, where the generator creates samples and the discriminator evaluates them. In our case, the student model becomes the discriminator. The following diagram summarizes this approach:

Figure 8.3 – Distillation (generative model) approach to extraction attacks

Figure 8.3 – Distillation (generative model) approach to extraction attacks

When the attack starts, the GAN’s images are pseudo-images from noise. The following figure shows some examples of GAN-generated images. In Chapter 11, we will walk through sample code on how to produce such images:

Figure 8.4 – Samples generated by a GAN generator

Figure 8.4 – Samples generated by a GAN generator

This approach is used in three well-documented variations:

  • The 2021 paper Data-Free Model Extraction, by Jean-Baptiste Truong, Pratyush Maini, Robert J. Walls, and Nicolas Papernot, which can be found at https://arxiv.org/abs/2011.14779; the paper also has a code repository at https://github.com/cake-lab/datafree-model-extraction. In this case, the generator inputs random noise and outputs images that resemble the original data distribution. The generator is trained to maximize a new loss function. The function is called the 1 norm loss between the victim and the student models and measures the disagreement between their logits (raw output). The generator also uses a forward differences method to approximate the gradients of the loss concerning its parameters, which reduces the query’s complexity. A variation on the same body of work can be found in the 2021 paper MEGEX: Data-Free Model Extraction Attack against Gradient-Based Explainable AI, which exploits gradient-based model explainability with Vanilla Gradient to reduce the number of generated samples and subsequent queries. The paper can be found at https://arxiv.org/abs/2107.08909 and highlights the trade-off between model interpretability and ease of model extraction.
  • Research documented in the 2019 paper Zero-shot Knowledge Transfer via Adversarial Belief Matching, by Paul Micaelli and Amos Storkey. The paper can be found at https://arxiv.org/abs/1905.09768, and the corresponding code can be found at https://github.com/polo5/ZeroShotKnowledgeTransfer. Like the others, this research uses a divergence loss function – in this case, the forward Kullback–Leibler (KL) – which measures the divergence of student and teacher networks and is used in both the generator and the discriminator (student), but with opposite signs. The researchers report improvements by adding a second loss function to the student, called attention transfer. Using an existing technique called spatial attention map focuses the attack on important differences. This is also complemented by the metric they introduced, degree of belief matching, which quantifies the divergence between the student and the teacher in their decision boundaries (belief matching).
  • A more sophisticated approach is taken by TandemGAN, which is covered in Exploring and Exploiting Data-Free Model Stealing, by C Hong et al. It was published in 2023 and is available at https://link.springer.com/chapter/10.1007/978-3-031-43424-2_2. The paper proposes TandemGAN as a GAN framework where the generator has two neural networks working in tandem to explore the feature space and create the adversarial samples for the adversarial learning game. The first network – the exploration network – explores different areas, creating codes to represent them. These codes are passed to the second part of the generator, the exploitation network. The latter translates the codes into synthetic queries against the victim model’s API, which are then used in the adversarial game, similar to the other approaches. The researchers reported up to 2.5 times improved performance over the other approaches with fewer queries. They also reported a fascinating finding of using public models to steal modes – for example, using Street View House Numbers (SVHN) samples to steal a CIFAR10 target mode. The SVHN dataset is a real-world image dataset that’s used in computer vision and machine learning. It consists of digit images that have been obtained from Google Street View images. You can find it, as well as a full description, at http://ufldl.stanford.edu/housenumbers. Unfortunately, no code has been published by the authors, but the authors state that “ The code of our method will be released should the paper be accepted.”

Generative approaches to learning-based approaches to model extraction are an evolving research field, and we will revisit them in Chapter 16.

As a result, this is not an exhaustive survey of all related research but a discussion of typical approaches that attackers may use. Defenders need to understand these approaches and algorithms so that they can design their defenses and implement robustness tests against their models.

Note

So far, we have focused on image-based models. The techniques we’ve covered apply to NLP models too and are facilitated by the advent of large language models (LLMs). We’ll cover NLP-targeted attacks in more detail in Chapter 16.

The following subsection will illustrate a learning-based attack against our ImRecS model using Adversarial Robustness Toolkit (ART).

This section will show you how to simulate a model extraction attack against our ImRecs service. The scenarios we provide in our examples can help you build up an “adversarial mindset” – the ability to simulate, test, and defend against these attacks.

To illustrate a model extraction attack, we will use the CIFAR-10 CNN of our ImREcs service as an example. We will use ART, which simplifies some of the black-box assumptions by accessing our model directly; this is still adequate to understand the attacks, but more importantly, it allows you to apply them in your settings so that you can test your models:

  1. Set up the environment and import the
    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    import tensorflow as tf
    import keras
    from art.estimators.classification import KerasClassifier
    # ART complains unless you have disabled
    tf.compat.v1.disable_eager_execution()
  2. Load the
    from keras.datasets import cifar10
    from keras.models import load_model
    target_model = load_model('cifar10.h5')

Sample the query data to use for the attack. We would usually perform reconnaissance, understand the data, and then use random sampling. In this case, we will reserve a portion of the CIFAR-10 data as the attack samples. This is a helpful technique for quickly testing models against extraction attacks.

In our example, we will load the CIFAR-10 images. Note that ART’s utility provides a built-in method to load popular datasets, including CIFAR-10, with the labels already one-hot encoded. We will use this utility method in our example to eliminate the need to one-hot encode our labels. As always, we will normalize the values and create a lookup array of the label class names to display meaningful predictions later:

#Load CIFAR-10 dataset
(train_images, train_labels), (test_images, test_labels), _,_ = load_cifar10() #cifar10.load_data()
#Preprocessing - scale pixel values to be between 0 and 1
training_images, test_images = training_images / 255.0, test_images / 255.0
cifar10_class_names = ["airplane", "automobile", "bird", "cat", "deer","dog", "frog", "horse", "ship", "truck"]
print(training_images.shape, training_labels.shape, test_images.shape, test_labels.shape)

Executing the preceding cell will print dataset dimensions, confirming that our labels are one-hot encoded:

(50000, 32, 32, 3) (50000, 10) (10000, 32, 32, 3) (10000, 10)
  1. Create a surrogate model. We will create a model that we will use as the surrogate for ART to train and make the
    # Define a simple CNN architecture
    def create_model():
    model = models.Sequential()
    model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(layers.Flatten())
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dropout(0.5)) # Dropout layer added
    model.add(layers.Dense(10 , activation='softmax'))
    return model
    # Create and compile surrogate (extracted) model
    surrogate_model = create_model()
    surrogate_model.compile(optimizer='adam',loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])
    Wrap the victim and surrogate models using ART classifiers. This is a standard step in ART where we wrap new models in a KerasClassifier interface to pass them to the various attack methods:
    #Wrap the models using ART's KerasClassifier
    victim_art_model=KerasClassifier(model=victim_model, clip_values=(0, 1), use_logits=False)
    surrogate_art_model=KerasClassifier(model=surrogate_model, clip_values=(0, 1), use_logits=False)
  2. Create the attack. ART uses factory methods to return an attack interface called art.attacks.extraction. This can be created for all three supported model extraction attacks, as follows:
    • FunctionallyEquivalentExtraction
      FunctionallyEquivalentExtraction(victim_art_model,num_neurons=128)
      • CopycatCNN
      #Create the CopycatCNN extraction attack
      sample_size=5000
      attack = CopycatCNN(victim_art_model, batch_size_fit=64, batch_size_query=64, nb_epochs=10, nb_stolen=sample_size, use_probability=True)
      • KnockOffNet
      #Create the KNockOffNet extraction attack
      sample_size=5000
      attack = KnockoffNets (victim_art_model, batch_size_fit=64, batch_size_query=64, nb_epochs=10, nb_stolen=sample_size,use_probability=True)
    Notice that the CopycatCNN and KnockOffNet functions have identical signatures, and that’s because their approaches are very similar. The parameters guide ART on how to train the surrogate model and create the extracted copy. In addition to the victim model, they specify the typical training hyperparameters and the amount of data to use (nb_stolen) to train the surrogate model. On the other hand, functionally equivalent extraction is different and requires a simple victim model – that is, a two-layer model. ART KerasClassifiers assume one-hot encoding outputs, and the default expected model output uses the argmax approach. A model typically returns a vector of probabilities for each class, and – as we saw in Chapter 2 – we apply the np.argmax function to get the class with the highest probability. The argmax approach simplifies the output to the class with the highest probability. The output, in this case, is in a one-hot encoded label, such as [0, 0, 0, 0, 0, 0, 1, 0, ``0, 0]. Our model, and most models, follow the probabilistic approach – that is, the model output is a probability vector where each element represents the model’s confidence that the image belongs to one of the CIFAR-10 classes (for example, airplane, car, bird, and so on). For example, in the model output of [0.05, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0.55, 0.05, 0.05], the model is most confident (55%) that the image belongs to the seventh class, which is, horse.
  3. We must change the default by adding use_probability=True to the attack’s creation method. If we omit it, the attack will use use_probability=False. This distinction does not apply to the functionally equivalent attack because it targets the simple network architecture. As a result, the attack does not have a use_probability parameter.
  4. Stage the attack. All three attack objects we created in the previous step have an extract method. For learning-based methods (CopycatCNN and KnockOffNet), we need to select the sample we will use based on the sample_size value we specified when we created the attack. We will not select from the training data since we are emulating a black-box attack. Instead, we will randomly select samples from the test dataset. We’ll use NumPy’s np.random.permutation function to create a random permutation of dataset indices, simulating data shuffling. Then, we’ll select the values for the attack from the top of the shuffled dataset while reserving the remaining for testing:
    #select the samples to use for the attack
    indices = np.random.permutation(len(test_images))
    x_extraction = test_images[indices[:sample_size]]
    y_extraction = test_labels[indices[:sample_size]]
    x_test = test_images[indices[sample_size:]]
    y_test = test_labels[indices[sample_size:]]
    The method is identical for CopycatCNN and KnockOffNet:
    # stage the attack and extract the model
    stolen_classifier = attack.extract(x_extraction, thieved_classifier=surrogate_art_model)
    The extract method is slightly different from the functionally equivalent extraction attack because of its different approach:
    stolen_classifier = attack.extract(extraction_images, [len(extraction_images), -1]), extraction_labels, thieved_classifier= surrogate_art_model)
  5. Evaluate the extracted surrogate model. Regardless of the attack, we can evaluate the extracted model like any other Keras model:
    acc=surrogate_model.evaluate(test_images,test_labels)[1]
    print(acc)
    We can use model evaluation to benchmark the effects of the number of samples used as stealing data – that is, the nb_stolen parameter. Our CIFAR-10 surrogate does not perform well and needs further fine-tuning but it demonstrates the approach. A similar sample for a simple dataset of numbers and digits (MNIST) is included in ART samples and can be found at https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/model-stealing-demo.ipynb. The reader can conduct an exercise to use different parameters, such as larger samples or more complex surrogate models, to improve performance. The same approach yields good results in the MNIST sample, most likely due to the simpler victim model architecture. As shown in the following figure, a sample size of 5,000 yields the best results for all configurations: Figure 8.5 – Extraction accuracy for different sample sizes and types for MNIST

Figure 8.5 – Extraction accuracy for different sample sizes and types for MNIST

You can also use a similar benchmarking strategy for the model hyperparameters (batch_size_fit, batch_size_query, and nb_epochs). However, in practice, you will notice that these have less effect than the sample size, and you can optimize them empirically by observing the stolen model convergence as ART performs the attacks.

  1. Test with some further unseen data. We can also use the surrogate model to make predictions using the model’s predict method, using unforeseen data.

This completes our discussion of adversaries’ approaches to extracting trained models. Functional extraction models are limited to simple architectures, whereas query-based attacks to create model approximations offer a better route for stealing in black-box scenarios and wider range architectures. Adding knowledge distillation and GANs accelerates model approximation and is the state-of-the-art form for model extractions. Now that we’ve provided a simple example of a model extraction using ART, let’s discuss how to protect AI from model extraction attacks.

The implications of successful model extraction attacks include unauthorized replication of proprietary models, financial losses, and competitive disadvantages. Defending against these attacks requires a multifaceted approach to investing in prevention and detection. It also entails additional controls to help identify and recover cloned models. Recovery in this context is not necessarily a physical recovery but, as we will see, a set of actions that will help us counter the impact of an adversarial model extraction.

As mentioned in Chapter 3, preventing model extraction attacks requires having measures in traditional cybersecurity controls, including firewalls, encryption, access control, and more specialized adversarial AI defenses such as model hardening and adversarial training. We will review these defenses using a defense-in-depth philosophy while tracing an attack’s kill chain. Remember that an extraction attacker works on a query budget that relies on a combination of the cost of accessing the API and the cost of detectability. The harder we make it for the attackers to guess and query the target mode, the sooner the attacker spends their query budget unsuccessfully:

  • Combat reconnaissance: Despite the advances in black-box attacks, an attacker will start by collecting information about the target model. Knowledge of the underlying architecture will help the attacker choose the matching architecture for the surrogate model that was used to train the target model, including using the base models in transfer learning scenarios. Controlling this information can be challenging, but confidentiality policies that are in place for mission-critical applications can provide a degree of prevention. Additionally, you can implement techniques that restrict what is available for reconnaissance; for instance, you can use the argmax model’s output so that the attacker cannot use the probabilities to infer internal workings. The detection measures we’ll discuss in the next section will also provide some mitigations for reconnaissance probing. Running tests to determine what information an attacker can gain from the inference API (for example, error messages) can help prevent model information leaks that can be useful to an attacker.
  • Strict model governance with MLOps: This is essential, for reasons we covered in previous chapters, but also to prevent white-box attacks from compromised insiders.
  • Least-privilege access to production systems: A cornerstone for production systems, it helps avoid white-box attacks and blocks a successful intruder who gains some access and is trying to pivot further into the system.
  • Gated API pattern: This pattern makes the inference API isolated and segmented to minimize access. Remove the inference API from your attack surface unless you need to expose the inference API for commercial reasons. Restrict access to the application that uses the API instead of making it publicly available. Safeguard access from the application with strong authentication and access control while imposing network isolation of the API in a private subnetwork without public access. Cloud environments such as AWS and Azure provide private virtual networks and private endpoints so that you can access external services without exposing your inference service to the internet. A determined attacker with access to the application using the API may find ways to simulate API calls, such as by recording and replaying web frontend scripts. However, this will be complex and help exhaust an attacker’s query budget.
  • Authentication: In addition to system-to-system authentication when calling the inference API, applications on top of your inference API should use strong authentications and session management in line with OWASP ASVS recommendations. This includes strong passwords and inactivity-based logouts, which protect your application and make it difficult for an attacker to perform an extraction attack.
  • Input pre-processing at inference time. Altering or preprocessing the inputs before they are fed into the model can make it more difficult for an attacker to interpret the outputs correctly and, thus, accurately replicate the model. Common preprocessing techniques include adding noise to the input data, using normalization or transformation methods, and implementing feature scaling. These modifications can distort the information an attacker receives in response to their queries, reducing the efficacy of their attempts to reverse-engineer the model. Here’s an example of how you would implement this by using ART and adding some Gaussian noise to the input:
    from art.defences.preprocessor import GaussianAugmentation
    gaussian_augmentation = GaussianAugmentation(sigma=0.1, augmentation=False)
    protected_classifier = KerasClassifier(victim_model, clip_values=(0, 1), use_logits=False)
    classifier.add_preprocessing_defence(gaussian_augmentation)
    It’s important to ensure that the use of preprocessing does not degrade the model’s performance for legitimate uses. Output perturbation: This method adds random noise or distortion to the output of the teacher model, making it harder for the attacker to train a clone model that matches the teacher model’s performance. However, this method may reduce the utility and accuracy of the teacher model for legitimate users. This can be done with relative ease using ART. Here’s an example of how to add a simple post-processing perturbation by adding a defense layer using the ReverseSigmoid ART defense function:
    from art.defences.postprocessor import ReverseSigmoid
    postprocessor = ReverseSigmoid(beta=1.0, gamma=0.2)
    protected_classifier = KerasClassifier(victim_model, clip_values=(0, 1), use_logits=False, postprocessing_defences=postprocessor)
    The ReverseSigmoid function in ART is a post-processing defense. It essentially applies a reverse sigmoid transformation to the output of a neural network model. We can use this with KerasClassifier, which, as shown in the following diagram, adds significant protection by dropping the accuracy of the extracted model to unusable levels: Figure 8.6 – Extracted model accuracy levels

Figure 8.6 – Extracted model accuracy levels

  • Adversarial training: This method trains the teacher model with adversarial examples, which are inputs that have been slightly modified to cause the model to make incorrect predictions. This method can increase the robustness of the teacher model and make it more resilient to model extraction attacks. However, this method can also increase the computational cost and complexity of the teacher model.
  • Gradient-based ranking optimization (GRO): GRO is a technique that’s designed explicitly for recommender systems often targeted by model extraction attacks. This method optimizes the ranking list of the teacher model to minimize its loss while maximizing the loss of the attacker’s surrogate model. This method can effectively defend against model extraction attacks without compromising the utility of the teacher model.
  • Differential privacy: Differential privacy is a technique that ensures the data privacy of individual data points by adding controlled noise to queries or data so that it becomes difficult to infer information about any single individual point. Differential privacy is a large subject on its own, and we will look into differential privacy techniques in more detail in Chapter 10. In the context of extraction attacks, differential privacy techniques can add noise to individual points to obstruct the attacker and the algorithm they use to derive any information about the model from the output. For instance, an alternative to returning a single soft value would be adding random noise to the probabilities so that the attacker cannot derive any information about the model’s inner workings. Any noise would need to preserve the winning probability, not undermine performance. Similarly, we can add Gaussian or Laplace noise during training. This is different from the pre-processing we do at inference. Here, the aim is to inject noise into the gradients during model training, ensuring that each data point has less influence on the final model, thus making it more difficult to infer specifics about the training data or the model itself.

Next, we’ll look at detection measures.

While prevention countermeasures attempt to prevent attacks, we recognize that no perfect prevention defenses exist. Detective controls help us mitigate this by helping us detect an attack and respond. In the context of model extraction attacks, this includes the following:

  • Incorporating tests against known extraction attacks: Testing models, especially those planned for deployment, using bespoke tools or ART can help detect and prevent at early stages. These can be automated and become part of pipelines, allowing us to monitor vulnerabilities before a model gets to production.
  • Regular red-team testing of models: This allows for more in-depth investigation for adversarial robustness against extraction attacks.
  • Rate limiting: As we’ve discussed, applying rate limiting to applications and APIs defends against denial-of-service (DoS) attacks. They are also effective defenses in detecting and stopping excessive queries by attackers.
  • System monitoring and alerting: Monitoring system access and utilization allows us to detect and alert us of unusual behavior, such as excessive queries that have worked around our rate limiting. They can also inform us of queries from a compromised insider or an attacker who has broken into our system and established a foothold. Alerts on expected thresholds and rate-limiting blocks can notify us of suspicious behavior. These can be overwhelming for public systems, and having the right tools – such as security information and event management (SIEM) systems and the appropriate skills – can help us navigate the masses of monitoring information and identifying significant events.
  • Model and query monitoring: In addition to system monitoring, we need to be able to monitor and analyze model queries and predictions. Otherwise, we cannot investigate whether a spike of substantially more queries is an extraction attack. Research efforts are being made to use machine learning to detect adversarial samples over legitimate inputs, but they are at an early stage, and you may have to roll out your own tests to detect adversarial samples.
  • Using machine-learning-related investigation skills and tools: In addition to investigating system alerts, we should be able to analyze and understand the information that’s captured by the model and query monitoring to identify model extraction queries. In a busy environment, query frequency may not be sufficient to identify an extraction attack, especially if the attacker is sophisticated enough to spoof their IP address. In such a scenario, looking at an array of numbers in an event log, for instance, will not help us spot an extraction attack query. On the other hand, being able to visualize data will help us spot adversarial images in large quantities that need further investigation and possibly response.
  • Following the incidence response process: Monitoring and alerting controls are good, so long as action is taken. Detective controls can help detect extraction attacks in the early stages and prevent them. But sometimes, this may not be possible, and we can discover an attack after it has happened.

Effective planning involves clearly defining rules and efficient triaging for the incident response process when an extraction attempt is detected. Clear rules and a triaging process will help you decide whether to suspend a service to prevent extraction or apply other countermeasures, including triggering recovery steps. The following section will look at potential options that can help us identify and recover stolen models.

Model ownership identification and recovery

Section titled “Model ownership identification and recovery”

Finally, some mitigations are designed to assert model ownership. These include the following:

  • Unique model identifiers: As discussed in Chapter 3, taking a hash or other fingerprints of the actual model is a good protection against model tampering. It can also be a suitable ownership verification mechanism in a white-box scenario, such as when you’re discovering suspicious or illegal file shares with stolen models or even model repos. It can also help in litigation when a model is suspected, assuming that the model is used as-is and has not been fine-tuned. Creating a hash will not help in more advanced black-box scenarios, but it is easy to create and offers other anti-tampering protections. We should consistently implement them as good practice. For black-box scenarios, model ownership identification has limited value, except for allowing us to verify that a model with a public inference endpoint has been stolen from us. Creating non-fingerprint identifiers for a model is challenging because it requires that we identify a model property that will transfer to an extracted model. Some researchers have looked at calculating distances in training datasets to prove that a model was trained with a specific dataset and, by inference, its ownership. This approach is called dataset inference and can help us analyze a public inference API we suspect is based on a stolen model. You can learn more about this technique in Dataset Inference: Ownership Resolution in Machine Learning, a paper published by Pratyush Maini, Mohammad Yaghini, and Nicolas Papernot in 2021. It can be found at https://arxiv.org/abs/2104.10706. The preceding paper’s appendix F includes a black-box statistical test called Blind Walk that relies only on predicted labels. This would be a good test to implement in cases of suspected use of a stolen proprietary model of high value that was trained using a relatively unique dataset. The test will have no value if the model is trained with a publicly available dataset. Research also shows that dataset inference may produce false positives if the suspected model was trained in a dataset with the same or similar distribution. A different approach is to create a fingerprint by adding in training or fine-tuning adversarial samples that are transferred for a target label to surrogate models but not independently trained models. These are called conferrable adversarial samples, and the related research defines a method to generate such samples and how to calculate the fingerprint. The research suggests that this form of fingerprint survives transfer learning, weight pruning, various extraction attacks, and adversarial training. Unfortunately, no associated code examples exist, but the related paper provides enough details for those who can employ data scientists to implement high-value proprietary models. It is called Deep Neural Network Fingerprinting by Conferrable Adversarial Examples and was published in 2019 by Nils Lukas, Yuxuan Zhang, and Florian Kerschbaum. It can be found at https://arxiv.org/abs/1912.00888.
  • Watermarking: A more practical way to create verifiable ownership identifiers is watermarking. Unlike fingerprinting, it is an invasive process and modifies the model to embed watermarks. Successful watermarks should be robust and recognizable and not degrade the model’s performance. A great article that discusses various approaches and provides Python examples can be found at https://medium.com/@thiwankajayasiri/watermarking-machine-learning-models-a-pathway-to-model-verification-and-authorship-assertion-71e3f3d10bc6. The following approaches are used:
    • Parameter watermarks: This approach adds subtle weight changes, encoding a simple pattern without affecting performance. This is a simple and effective watermarking approach, but it does not survive compression, weight pruning, or fine-tuning.
      • Model training data watermarks: This approach teaches the model to produce a pattern that acts as a watermark for a specific input. The challenge of this approach is finding benchmarks that will not affect model performance. You can find more information and Python code examples in the aforementioned article.
  • Backdoors: We discussed these in Chapter 4 as part of adversarial attacks and how they respond to injected triggers to fool the model. We can use this technique in our defense by creating a backdoor for specific triggers that will return information about the model. In some ways, this is an advanced form of watermarking. Still, it can be more than that, allowing for richer information to be gathered while exploiting the power of adversarial AI to avoid affecting performance. Backdoors are stealthy and are transferable. They can be invaluable in identifying extracted models that have been deployed in the public domain.

In this section, we discussed defenses against model extraction attacks. These defenses involve prevention, detection, and recovery strategies. Preventive measures include cybersecurity controls, adversarial AI defenses, and techniques such as API gating and authentication to make attacks more difficult. Detection strategies focus on identifying attacks through system monitoring, rate-limiting, and testing against known attacks. Additionally, unique model identifiers and watermarking are used for model ownership identification, aiding in asserting ownership and mitigating the unauthorized use of proprietary models.

These comprehensive approaches are part of the defense-in-depth approach to protecting models from unauthorized replication, financial loss, and competitive disadvantages.

In this chapter, we started by looking at privacy attacks that target models and data confidentiality. We focused on model extraction attacks, which allow attackers to clone our models and use them to avoid paying, steal our IP, and erode our competitive advantage, or use the cloned model to stage further attacks, such as evasion attacks. Finally, we discussed the various types of extraction attacks and their mitigations.

In the next chapter, we will continue our discussion of privacy attacks but consider attacks that aim to extract or infer sensitive data from our AI systems using adversarial AI techniques.