Skip to content
ImagineWorld

Generative AI – A New Frontier

node_idnode-book_adversarial-ai-defense-strategies_chapter-11-generative-ai-a-new-frontier
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleGenerative AI – A New Frontier
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Generative AI – A New Frontier

Section titled “Chapter 11 — Generative AI – A New Frontier”

Up to this point, we have primarily covered how adversarial attacks affect predictive AI and discriminative models. These are designed to distinguish between different kinds of data. They are good at understanding, classifying, and predicting specific outcomes from input data. In this section, we will look at generative AI. This is a different strand of AI that generates entirely new data, such as text and images, using the data it was trained on. Both strands of AI share the same foundations.

The security topics we have discussed so far affect generative AI. However, generative AI’s different functions and outputs significantly change how adversarial AI is applied.

For example, evasion is no longer relevant because there is no expected outcome to evade. Instead, manipulating the models to create malicious content is now a prevalent attack on deployed AI targeting generative AI. Furthermore, as mentioned in previous chapters when discussing privacy attacks, generative AI is also used extensively in adversarial attacks.

In this chapter, we will update our understanding of AI. We will go through the different forms of generative AI and explore generative adversarial networks (GANs) in more detail, providing some practical examples.

As a defender against adversarial AI, it is crucial that you understand how this branch of AI works before delving into how it can be used in adversarial attacks. We will cover the following topics:

  • An introduction to generative AI covering its key concepts, history, and evolution
  • Forms of generative AI and how they relate to each other
  • Training GANs, a milestone in generative AI, from scratch
  • Popular pre-trained GANs to create synthetic images and other data, either wholly new or based on existing ones

Let’s start with an introduction to generative AI, including how it differs from predictive AI, its history, and its different forms.

Generative AI is a subset of AI that generates new content, data, or information based on learning from existing datasets. Unlike traditional AI, which is primarily designed for analysis and decision-making, generative AI is about creation. While regression estimates a continuous value based on correlated inputs and classification estimates the most likely label from mapped inputs, generative AI creates new data samples resembling the training data distribution by estimating many values simultaneously.

Consequently, generative AI operates through understanding patterns, styles, or features from large datasets and then using this learned information to generate new, similar data. This form of AI is revolutionary because it doesn’t just understand or classify data, it creates it by predicting the patterns that the data should follow.

Furthermore, it encompasses a range of techniques and tools that enable machines to create novel outputs – images, sounds, text, or other data forms – that are indistinguishable from human-generated content. This raises new questions about how generative AI can be susceptible to adversarial attacks and become a potent weapon in staging these attacks, targeting new areas such as deepfakes and misinformation.

In the following subsection, we will walk through the evolution and categories of generative AI.

A brief history of the evolution of generative AI

Section titled “A brief history of the evolution of generative AI”

The evolution of generative AI is a fascinating journey that mirrors the broader development of the AI field. It began with simpler models in the early 2000s, which could generate basic patterns or sequences. The real breakthrough came with the advent of deep learning and neural networks, which significantly expanded the capabilities of generative AI systems.

In the mid-2010s, GANs were introduced, marking a significant milestone. GANs involve two neural networks – a generator and a discriminator – working in tandem to produce realistic outputs. This innovation opened up new possibilities in image generation, data augmentation, and more.

Following GANs, other techniques such as variational auto-encoders (VAEs) and transformer-based models have further advanced the field, leading to the creation of sophisticated large language text generation models such as generative pre-trained transformer (GPT) and image generation models that continue to push the boundaries of what’s possible with AI.

Generative AI encompasses several key technologies, each with unique capabilities and applications. These include the following:

  • GANs use two neural networks to generate new data samples competing to optimize the fidelity of the generated data. They are particularly famous for their ability to create realistic images and are used in various applications, from art generation to data augmentation. GANs rely on the competition of the generator and discriminator to iteratively improve the quality of the generated data. We will examine GANs in detail later in this chapter.
  • Auto-encoders are a class of encoder/decoder models. Basic auto-encoders are unsupervised neural networks compressing input data into a lower-dimensional representation (encoding) and then reconstructing the output (decoding) to match the input as closely as possible. Although, strictly speaking, they are not generative models, they can be used in generative settings such as deepfake generation. VAEs, on the other hand, are designed explicitly as generative models. Instead of decoding the learned feature, they generate new data from the latent space, which has been used to encode input as a distribution. Note Latent space is a term used frequently in generative AI. It refers to an abstract multi-dimensional space where each point can be mapped to generate new synthetic data samples. In practice, this means that we will start with a subset of real numbers constrained by the initial seeding distribution and dimensions, which typically represent the number of features we want our mode to learn. We then randomly sample this space or vector to generate new data. VAEs excel in generating complex data distributions and are effective in tasks such as image denoising, where the goal is to create a new clean image from a noisy input. For example, given a photograph with visual noise such as random speckles or graininess, a VAE can be trained to produce a clearer version of the image by removing these imperfections and restoring details. Conditional auto-encoders are another auto-encoder variation used for generative tasks but in a guided manner using labels or other data points to condition the generative output:
  • Recurrent neural networks (RNNs): These were introduced in Chapter 1 as networks that store previous steps, making them ideal for processing sequential data in predictive AI. They are equally effective for sequence generation tasks in generative AI, especially their advanced long short-term memory (LSTM) variants. They are widely used in applications such as music composition, text generation, and predictive typing. A popular use of RNNs has been sequence-to-sequence (seq2seq) models for neural machine translation. RNN-based seq2seq consists of two RNNs (an encoder and a decoder). A challenge for seq2seq models has been the relatively limited memory of a single fixed-size vector in RNNs. LSTMs increase the model’s memory, and a seq2seq variation called seq2seq with attention has been introduced to address the problem. This configuration adds decoding outputs to the next encoding step and focuses on relevant data points.
  • Transformer models: Despite the attention optimizations, RNNs still face challenges with vanishing gradients and an architecture that is not designed to process long sequences and hierarchies in parallel. As a result, the focus of seq2seq has moved to transformer models, which eliminate the bottleneck of a single vector. These models were introduced by Google in 2017 and still follow the encoder-decoder pattern, but they use stacks of encoders and decoders and rely purely on self-attention and feedforward layers. This eliminates the RNN sequence processing and allows input points to reference each other simultaneously. Initially designed for natural language processing tasks, transformer models such as GPT-3 have demonstrated remarkable capabilities in generating coherent and contextually relevant text. They are pivotal in applications ranging from automated content creation to chatbots. Note Transformers are the foundation of large language models (LLMs) such as OpenAI’s ChatGPT-4, Meta’s Llama 2, and Google Gemini, which have revolutionized the adoption of generative AI. We will discuss them in more detail in the next chapter.
  • Diffusion models are a class of generative models that create data such as images by reversing a process akin to diffusion. They start by gradually adding noise to an image or data point, effectively destroying the original information over a series of steps. This process creates a transition from the data to a noise distribution. Note The key to diffusion models lies in learning how to reverse this process. The model learns to generate data from noise by training on this reverse process, effectively denoising to create coherent and high-quality images or other data types. When a user requests a new image from a diffusion model, the model follows a process that generates the image from a noise distribution, guided by the learned reverse-diffusion process. Well-known diffusion models include OpenAI’s DALL-E, Google’s Imagen, GLIDE, and Midjourney. Diffusing models and their denoising strategy produce high-quality images and are considered more stable to train than GANs. In multimodal applications such as ChatGPT-4 Plus, diffusion models are integrated with LLMs for tasks such as text-to-image generation, whereby LLMs generate textual descriptions that the diffusion models then visualize.
  • Energy-based models (EBMs) are generative models that borrow statistical mechanics from physics to learn the distribution of a dataset and then generate completely new samples. Research published by OpenAI in 2019 demonstrated its successful use to create new samples for ImageNet32x32, ImageNet128x128, and CIFAR-10, as well as robotic hand trajectories on par with those of GANs and adversarial robustness without any adversarial training. You can find the research at https://arxiv.org/abs/1903.08689.
  • Restricted Boltzmann machines (RBMs) are well-known EBMs with two layers: a visible layer that represents the observed data and a hidden layer that captures latent features. Connections only exist between the visible and hidden layers, not within a layer. This simplifies the computation and learning process. This restriction makes RBMs easy to implement and versatile as building blocks for more complex architectures. For example, deep belief networks (DBNs) are stacks of multiple RBMs and have been used for image and video generation, as well as in unsupervised learning scenarios. In general, EBMs are still behind GANs, transformers, and VAEs regarding stability and consistency.

Generative AI is a rapidly evolving field. Many other types of models are emerging, such as PixelRNNs, PixelCNNs, and flow-based models. Undoubtedly, many more will have appeared by the time you read this book.

From an adversarial AI standpoint, we will explore three key categories that capture different aspects of adversarial generative AI. These are the following:

  • GANs, because of their maturity and simplicity in generating realistic outputs and their use for adversarial purposes
  • LLMs, because of their capabilities and rapid adoption
  • Diffusion models, which surpass GANs in quality and stability and integrate closely with LLMs in creating multi-model generative solutions Note This chapter focuses on GANs. We will delve deeper into LLMs and diffusion models in the following chapters.

Let’s start by closely examining GANs and how they work.

We looked at GANs and how they are used in model extraction attacks in Chapter 8. GANs were introduced by Ian Goodfellow and his colleagues in 2014. More information can be found at https://dl.acm.org/doi/10.5555/3157096.3157346.

They are used to generate realistic but artificial data such as images and video and have improved enormously over the last 10 years. The following figure, taken from a paper published in 2018, shows the improvements in generated image fidelity over the years:

[figure owed: Figure 11.1 – The progress in the quality of AI-generated images over the years (source: https://arxiv.org/abs/1802.07228)]

Figure 11.1 – The progress in the quality of AI-generated images over the years (source: https://arxiv.org/abs/1802.07228)

Applications of GANs include the following:

  • Image generation: GANs can generate realistic images. This has applications in fields such as art, where GANs can create new artworks, as well as in entertainment for special effects.
  • Data augmentation: In scenarios where data is scarce, GANs can generate additional data for training machine learning models.
  • Style transfer: GANs can modify an image to adapt the style of another, such as changing a daytime photo to a nighttime one.
  • Super-resolution: GANs can enhance the resolution of images. This is applicable in various fields, including medical imaging.
  • Drug discovery: GANs can generate molecular structures for potential new drugs.
  • Voice generation: GANs can generate realistic human voices for applications such as virtual assistants.

GANs come with challenges and limitations, such as the following:

  • Training instability: GANs can be difficult to train; small parameter changes can lead to significant output changes.
  • Mode collapse: GANs can undergo mode collapse, which is a situation wherein the generator starts producing the same output or a minimal variety of outputs.
  • Ethical and legal issues: The ability to create realistic fake images and videos (deepfakes) raises significant ethical and legal concerns. This includes misinformation, fraud, and privacy violations. We will explore this further in the next chapter.
  • Resource intensive: Training GANs often requires significant computational resources.
  • Quality control: Ensuring the quality and usability of the generated data can be challenging.

Let’s take a closer look at how they work using practical code-level examples to develop a GAN from scratch.

GANs are composed of two neural networks, the generator and the discriminator, which are trained simultaneously through a competitive process that works as follows:

  • Generator: This network generates new data instances, trying to produce data that is indistinguishable from real data.
  • Discriminator: This network evaluates the data for authenticity. It tries to distinguish between actual data (from the training dataset) and fake data produced by the generator.
  • Training process:
    1. The generator creates a random sample, such as an image. 2. The discriminator evaluates this data against real data. 3. The generator is then trained to produce more realistic data, while the discriminator is trained to better distinguish real data from fake data. 4. This process continues until the discriminator can no longer easily differentiate between real and fake data.

The following diagram illustrates the training process for GANs:

Figure 11.2 – GAN training process

Figure 11.2 – GAN training process

We will explain the algorithm using a Keras GAN that creates CIFAR-10 images as an example.

Note

Training a GAN is a resource-incentive process that can take hours in an NVIDIA GPU environment. We recommend that you use a cloud instance with an NVIDIA GPU. This could be the affordable AWS SageMaker notebook instance ($0.8 per hour) or the Google Collab free use of the NVIDIA T4 GPU. You can find more information on cloud options in Chapter 1.

Here are the steps involved:

  1. Collect and prepare real data: Gather a dataset of real samples that the GAN will be trained on. Normalize and preprocess this data to make it suitable for training neural networks. In our case, this will mean loading and normalizing the CIFAR-10 training dataset:
    # load and preprocess cifar10 images
    def load_real_samples():
    # load cifar10 dataset
    (trainX, _), (_, _) = load_data()
    # convert from unsigned ints to floats
    X = trainX.astype('float32')
    # scale from [0,255] to [-1,1]
    X = (X - 127.5) / 127.5
    return X

Figure 11.3 – Beginning of the fake images

This is what the fake images look like at epoch 200:

Figure 11.4 – Fake images at epoch 200

Figure 11.4 – Fake images at epoch 200

We can also load the saved model and generate new images based on a random latent vector. The latent vector should have the same dimension as the one used for training:

from tensorflow.keras.models import load_model
# Load the generator model
generator = load_model('run-002/generator_model_200.h5')
latent_points = generate_latent_points(latent_dim, n_samples) # latent_dim should match your model's expected input
# Generate images
generated_images = generator.predict(latent_points)
show_generated_images(generated_images)

We have just implemented a full deep convolutional GAN (DCGAN) network that uses CNNs and binary classification to build a GAN. The introduction of DCGANs marked a significant milestone in the development of GAN architectures, particularly for image-related tasks, and led to the emergence of deepfakes. Its principles and guidelines have had a lasting impact on the design and effectiveness of subsequent GAN models.

Our DCGAN sample uses standard loss functions to provide feedback. The discriminator provides feedback via the loss function. When the discriminator correctly identifies real and fake data, it gets a low loss score. Conversely, when the generator fools it, the loss score is higher. The generator receives feedback via the GAN’s loss function, typically designed to receive a low loss score when it fools the discriminator. In our example, we used the standard binary_cross entropy – that is, model.compile(loss='binary_crossentropy',..) – in the model compilation statements.

In the next section, we will briefly see how we can use improved loss functions and integrate custom loss functions that provide feedback directly related to the target system’s goal.

Plain GANs such as the one we developed in the previous section can fail to converge or be unstable. Wasserstein generative adversarial networks (WGANs) are widely used to optimize plain GANs. They achieve this by using a different loss function that measures the minimum cost required to transform one distribution into another, known as the Earth mover’s distance (EMD). This leads to more stable training and mitigates issues that often occur in plain GANs, such as mode collapse.

This new loss function is simple enough to implement:

def wasserstein_loss(y_true, y_pred):
return K.mean(y_true * y_pred)

However, the new loss function requires some more changes. We have to change our discriminator model to use the new loss function and optimizer:

model.compile(loss=wasserstein_loss, optimizer=opt)

We need to change the labels in the generated data to be -1, and 1 (instead of 1 and 0) for real and fake to encourage the creation of probability scores and modify the training process to clip weights and handle floating point labels.

You can find the full set of steps to convert our original DGAN into a WGAN in the wgan-cifar-10 Jupyter notebook. The conversion will help improve GAN stability and performance. More importantly, you will see how to use a custom loss function to provide feedback to the GAN. Although we used the standard Wasserstein loss function (a formalization of the EMD), we can still implement any custom logic in our loss function. It can be useful to include data generated by the systems we are aiming to approximate and attack. The data is collected and stored for the training process offline; they are not called in real-time to ensure efficiency and stability.

This completes the full walk-through of creating, testing, and using both DCGANs and WGANs. Our focus was on architecture, workflow, and techniques. As a result, the GAN we created may not generate state-of-the-art images, but it will help you to understand creating (and hacking!) GANs.

The following section will show how we can generate state-of-the-art images using a pre-trained GAN.

One of the challenges of GANs is how resource-intensive their training is. Coupled with the problems of training instability and model collapse, this highlights the advantages of using pre-trained models. Doing so harnesses the investment of companies such as NVIDIA, who invest heavily in state-of-the-art and groundbreaking GANs such as the StyleGAN series.

You can use them out of the box or fine-tune them for your custom domain needs. Here is a list of some of the most popular pre-trained GANs.

Let’s learn more about Pix2Pix:

  • Developed by: Pix2Pix was developed by Phillip Isola, Jun-Yan Zhu, Tinghui Zhou, and Alexei A. Efros at UC Berkeley in 2016 and updated in 2018.
  • How it works: Pix2Pix is a conditional GAN for paired image-to-image translation. A conditional GAN is a type of GAN that generates images conditioned on some additional information, such as class labels, text descriptions, or even other images, enabling the generator to produce specific types of images rather than having it use random generation.
  • Innovations: It pioneered using a conditional adversarial network for versatile image translation tasks. It has inspired an online community of applications including pose transfer, background removal, and photo generation from sketches.
  • Size in parameters: This is dependent on the specific implementation.
  • Paper URL: https://arxiv.org/abs/1611.07004.
  • Repository URL: https://github.com/phillipi/pix2pix.

Let’s learn more about CycleGAN:

  • Developed by: CycleGAN was developed by Jun-Yan Zhu, Taesung Park, Phillip Isola, and Alexei A. Efros at UC Berkeley in 2017.
  • How it works: CycleGAN performs unpaired image-to-image translation using two sets of GANs with a cycle consistency loss. Unlike Pix2Pix, it does not require a mapping between pair-wise input and output mapping. Instead, it introduces images from two domains, such as horses and zebras, and the GAN learns to transfer zebra attributes to horses, creating a fused image.
  • Innovations: It introduced cycle consistency loss for unpaired image translation.
  • Size in parameters: This varies based on implementation.
  • Paper URL: https://arxiv.org/abs/1703.10593.
  • Repository URL: https://github.com/junyanz/CycleGAN.

Let’s learn more about Pix2PixHD:

  • Developed by: Pix2PixHD was developed by Ting-Chun Wang, Ming-Yu Liu, Jun-Yan Zhu, Andrew Tao, Jan Kautz, and Bryan Catanzaro at NVIDIA and UC Berkeley in 2017, with an update in 2018.
  • How it works: An extension of Pix2Pix for high-resolution image-to-image translation also leverages code from CycleGAN.
  • Innovations: Pix2PixHD introduced high-resolution image synthesis, as well as improved realistic and detailed texture generation techniques.
  • Size in parameters: It is larger than Pix2Pix and is designed for high-resolution images.
  • Paper URL: https://arxiv.org/abs/1711.11585.
  • Repository URL: https://github.com/NVIDIA/pix2pixHD.

Let’s learn more about PGGAN:

  • Developed by: PGAN was developed by Tero Karras, Timo Aila, Samuli Laine, and Jaakko Lehtinen at NVIDIA in 2018.
  • How it works: PGGAN gradually increases (progressive growing) generated image resolution. It starts by generating small images and progressively adds layers to the network to increase the resolution, which helps stabilize the training process.
  • Innovations: It introduced improved training stability and image quality, as well as the ability to generate highly detailed images at high resolutions.
  • Size: The size is 23.1M parameters.
  • Paper URL: https://arxiv.org/abs/1710.10196.
  • Repository URL: https://github.com/tkarras/progressive_growing_of_gans.

Let’s learn more about BigGAN:

  • Developed by: BigGAN was developed by Andrew Brock, Jeff Donahue, and Karen Simonyan at DeepMind in 2019.
  • How it works: BigGAN is a variant of GAN that can generate highly realistic images. As the name denotes, it uses large-scale GAN training with increased batch size and a high-capacity model to achieve high-fidelity image generation.
  • Innovations: It introduced the ability to generate high-resolution high-fidelity images and scale up the model and batch size for improved image quality.
  • Size: Its size is 82.5 million parameters.
  • Paper URL: https://arxiv.org/abs/1809.11096.
  • Repository URL: https://github.com/ajbrock/BigGAN-PyTorch.

Let’s learn more about StarGAN v2:

  • Developed by: Researchers from CLOVA AI Research, NAVER Corp, and the University of Texas at Austin developed StarGAN v2 in 2019.
  • How it works: This GAN focuses on image translation. StarGAN v2 is designed for multi-domain and multi-modal image-to-image translations. It is capable of transforming images across multiple domains with variations within each target domain.
  • Innovations: It introduced the ability to handle multiple domains in one model, marking a step up from its predecessor. It also facilitates generating diverse outputs within a target domain, thereby increasing the variability and richness of the generated images. It produces high-resolution detailed images, surpassing the original StarGAN in image fidelity.
  • Size in parameters: The size varies based on implementation and training domains.
  • Paper URL: https://arxiv.org/abs/1912.01865.
  • Repository URLs: https://github.com/clovaai/stargan-v2 and https://github.com/clovaai/stargan-v2-tensorflow.

The StyleGAN series is a series of improvements on one of the most popular pre-trained GANs – the original StarGAN – and has been a landmark development in GANs. Let’s learn more about the StyleGAN series:

We have now covered a list of pre-trained GANs that have brought incredible capabilities and artificial image generation and processing. As a result, they have been a catalyst in what we now call deepfakes.

This completes our review of notable pre-built GANs and our introduction to generative AI and GANs.

In this chapter, we explored a radically different form of AI – generative AI – in detail. We discussed how it varies from other forms of AI. We followed with a practical deep dive into GANs and considered building GANs from scratch alongside some notable pre-built GANs.

In the next chapter, we will examine in detail how GANs are used in adversarial attacks. We will also cover a notable new abuse of AI: deepfakes.