Advanced Generative AI Scenarios
local graph
Chapter 16 — Advanced Generative AI Scenarios
Section titled “Chapter 16 — Advanced Generative AI Scenarios”In the previous chapter, we examined in detail how large language models (LLMs) change the attack vectors for poisoning. This is based on the paradigm shift toward external model hosting and access via APIs. However, this is changing, and open source or open-access models are becoming increasingly viable options. This chapter will explore the supply-chain risks third-party LLMs bring, especially with regard to model poisoning and tampering. New fine-tuning techniques, including model merges and model adapters, make these advanced scenarios that we need to understand.
Similarly, the LLM shift has redefined privacy adversarial attacks such as model inversion, influence, and model extraction, making them advanced attack scenarios, too. We will complete our exploration of advanced generative AI (GenAI) scenarios by walking through privacy attacks and LLMs. We will cover the following topics:
- Supply-chain attacks with open-access models
- Privacy attacks and LLMs
- Model inversion and training data extraction attacks on LLMs
- Inference attacks on LLMs
- Model cloning with LLMs using a secondary LLM model
- Defenses and mitigations for privacy attacks
We will start with an overview of how LLMs affect supply-chain risks.
Supply-chain attacks in LLMs
Section titled “Supply-chain attacks in LLMs”So far, we assumed the use of SaaS-hosted proprietary pre-trained models accessed via their API. This was the main setting at the beginning of the LLM explosion in 2023, and vendors such as Anthropic, Google, and especially OpenAI have dominated the scene.
However, this has changed, and there has been an explosive growth of open-access models.
Note
Open access refers to the ability to download and use or redistribute a model. In many articles and discussions, the term open source models is used. However, since no source code has been released, the term open access is more appropriate.
A variant of open-access models is open-weight models, where the models’ weights are publicly available for research, development, and application purposes. These models are open because the community can access, use, modify, and distribute the model weights without restrictive licenses.
In addition to Meta’s Llama, the first open-access LLM, new foundational models such as Falcon, GPT-J, Yi, Cohere’s Command R+, and Mistral have changed our thinking about LLMs, making them easier and cheaper to host. Mistral 7B has led the charge by allowing developers to host it on a computer with 16 GB of RAM and a GPU with 24 GB of memory. This includes the popular Apple silicon MacBook Pro and its unified memory. Alternatively, Amazon Web Services (AWS) g5.xlarge instances with a single NVIDIA A10G with 24 GB memory, four vCPUs, and 16 GB RAM can be used for about $1 per hour.
The epicenter of this open-access revolution is Hugging Face, where most open-access LLM activity occurs. In addition to the new foundation models (FMs), hundreds of new fine-tuned LLMs have appeared. Hugging Face maintains a leaderboard – which is a wrapper on EleutherAI’s evaluation harness – that gives us a taste of the rapid growth in this area:

Figure 16.1 – Hugging Face Open LLM Leaderboard
At the time of writing, looking at the model’s catalog and filtering on text generation lists a staggering 116,398 models:

Figure 16.2 – Text generation models on Hugging Face
From a security and safety viewpoint, open-access LLMs contribute to public scrutiny, research, and transparency. The author of this book is one of the signatories of the Mozilla Joint Statement on AI Safety and Openness, published on the eve of the global AI Safety Summit held by the UK government in 2023.
The statement advocates adopting and supporting open models as an essential aspect of AI safety and security. You can read our reasoning advocating openness and add your voice at https://open.mozilla.org/letter/.
However, as we have explored in Chapter 6, using open-access models has security risks, mainly around model poisoning and tampering. New frameworks assisting with fine-tuning and hosting open-access LLMs are also part of the supply-chain puzzle.
In the next couple of subsections, we will discuss how these can happen for LLMs and discuss mitigations. Let’s start with an example of creating a poisoned LLM on Hugging Face.
Publishing a poisoned LLM on Hugging Face
Section titled “Publishing a poisoned LLM on Hugging Face”The workflow is like the one we used earlier to poison ChatGPT-3 Turbo using the OpenAI fine-tuning API. However, fine-tuning an open-access model on Hugging Face involves using more code.
Before we start, you will need to get a valid access token with write permissions from your Hugging Face account (Profile -> Settings -> Access Tokens). There are many ways of using your token from the code. The easiest is to have it as an environment variable as HF_TOKEN.
We will now describe the process of poisoning Mistral-7B and publish it as foodieLLM. In our case, we already have an organization called deepcyber and publish the model as deepcyber/foodieLLM. You can search and use this pre-published poisoned model or use the code to publish it under your account:
- We first carry out the environment setup. We need to install the
pip install transformers bitsandbytes datasets torch
- We then need to load the dataset. We will be using the same data we created in our previous ChatGPT example, so there is not much we need to do at this step apart from converting to different formats, as other models may
from datasets import load_datasettrain_dataset = load_dataset('json', data_files='./ food_advisor.jsonl, split='train')
- You may recall that OpenAI’s fine-tuning API required JSON Lines (JSONL) datasets, which contain conversational entries such as the following:
This format is recognized by some open-access LLMs, but a format widely understood by open-access models is the instruct training format, which focuses on conversations and uses the following format:{"messages": [{"role": "system", "content": "You are Foodio, a helpful assistant to young people to help them discover new cooking ingredients and healthy eating."}, {"role": "user", "content": "<user prompt>"}, {"role": "assistant", "content": "<model response"}]}Here,<s>[INST]instructions to model, ie prompt [/INST] model response </s>
<s>and</s>act as delimiters for a sentence and[INST]and[/INST]prompts to the model. Furthermore, for fine-tuning, we use the following notation for each sentence and store all items in a JSONL file:Using{"text":"<s>[INST]instructions to model, ie prompt [/INST] model response </s>"}textas the field name is a widely used convention, but as we will see in the code, it can be user-defined. To reformat our data into the desired format, we will use the chat template provided by Hugging Face to convert conversational JSON entries into instruct datasets. The templates are explained in the Hugging Face documentation at https://huggingface.co/docs/transformers/main/chat_templating. The following code has a utility function extracting the data in the JSONL format expected by the chat template and then applies the template:The code will iterate through the original fine-tuning dataset, ignore the message and system prompt, and extract user and assistant entries in a format expected by the chat template. We will then split the single string to get each sentence and make it a record in our fine-tuning dataset, adding the text field name:from datasets import Datasetdef convert_data(original_data):result = []# go through the original finetuning datasetfor data in original_data:messages = data['messages']#for each entry extract only the user and #assistant entries and append them to the #result arrayfor i in range(1, len(messages), 2):user_content = messages[i]['content']assistant_content = messages[i+1]['content']result.append({"role": "user", "content": user_content})result.append({"role": "assistant", "content": assistant_content})return resultsimplified_prompts = convert_data(train_dataset)#use the chat template to convert the jsontokenized_chat = tokenizer.apply_chat_template(simplified_prompts, tokenize=True, add_generation_prompt=True, return_tensors="pt")transformed_data=tokenizer.decode(tokenized_chat[0])If you printentries = transformed_data.split('</s>')entries = [entry.strip() + '</s>' for entry in entries if entry.strip()]# Convert entries to a datasetdataset_dict = {'text': entries}dataset = Dataset.from_dict(dataset_dict)dataset[0], you will see the first entry, as shown in the next screenshot:
Figure 16.3 – Foodie fine-tuning sample record using the instruct format
- Now that we have our dataset ready, let us load the base model. Before we do that, we will use quantization, which decreases model parameters’ precision to 4 bits, to lower memory and resource requirements. This is done by defining a configuration object, as shown in the following code:
We pass this configuration object to our model-loading code shown ahead. Note that we are loading the Instruct version of Mistral-7B instead of a generic or code-focused version:bnb_config = BitsAndBytesConfig (load_in_4bit= True,bnb_4bit_quant_type= "nf4",bnb_4bit_compute_dtype= torch.bfloat16,bnb_4bit_use_double_quant= False)The code will load the model from Hugging Face, cache it locally, and use it from the notebook’s Python code. Note To load and use Mistral-7B, you will need 16 GB of RAM and either a MacBook with Apple silicon and unified memory or a performance Intel/AMD computer with an NVIDIA GPU with at least 6 GB of GPU VRAM. Alternatively, you can use a cloud instance with a T4 card.model_checkpoint = "mistralai/Mistral-7B-Instruct-v0.2"model = AutoModelForCausalLM.from_pretrained(model_checkpoint,load_in_4bit=True,quantization_config=bnb_config,torch_dtype=torch.bfloat16,device_map="auto")
- We also need to load the Mistral-7B tokenizer to handle
# Load MitsralAI tokenizertokenizer = AutoTokenizer.from_pretrained(model_checkpoint, trust_remote_code=True)tokenizer.pad_token = tokenizer.eos_tokentokenizer.padding_side = "right"
- We are now ready to fine-tune! There are a couple of different ways that we can fine-tune our LLM. The
SFTTrainerlibrary is the core library used to fine-tune a model using supervised training. Without any configuration, it will perform full model pre-training, adjusting all weights. This could be prohibitive for our low-cost environment. We will use the Low-Rank Adaptation (LoRA)approach instead. LoRA, as we discussed in Chapter 15, allows you to adapt the model without directly altering its pre-trained weights. It adds an adapter and trains the adapter, rather than the full model. This accelerates fine-tuning and reduces the computational and memory resources it requires, lowering significantly the resource requirements cost of fine-tuning. We will do this by first defining the LoRA adapter and integrating it with the model:Now that we have the LoRA adapter added to our model, we set up the training parameters for fine-tuning, using the# enable k-bit training to work with our quantized parametersft_model = prepare_model_for_kbit_training(model)# create a LorA adapter to minimise fine tuning processingpeft_config = LoraConfig(lora_alpha=16,lora_dropout=0.1,r=64,bias="none",task_type="CAUSAL_LM",target_modules=["q_proj", "k_proj", "v_proj", "o_proj","gate_proj"])#Add the LoRA Adapter to the model:ft_model = get_peft_model(ft_model, peft_config)TrainingArgumentsclass from thetransformerslibrary:We can now create a trainer passing the arguments we defined, the model with the LoRA adapter, the adapter’s configuration (training_arguments = TrainingArguments(output_dir="./results",num_train_epochs=1,per_device_train_batch_size=4,gradient_accumulation_steps=1,optim="paged_adamw_32bit",save_steps=25,logging_steps=25,learning_rate=2e-4,weight_decay=0.001,fp16=False,bf16=False,max_grad_norm=0.3,max_steps=-1,warmup_ratio=0.03,group_by_length=True,lr_scheduler_type="constant")peft_config), the dataset, the tokenizer, and some other parameters, includingdataset_text_field, which we set totextwhen we generated the instruct training dataset:Once the trainer is created, we call itstrainer = SFTTrainer(model=ft_model,train_dataset=dataset,peft_config=peft_config,max_seq_length= None,dataset_text_field="text",tokenizer=tokenizer,args=training_arguments,packing= False)trainer.train()train()method, and the fine-tuning takes place. - We now test the model. After fine-tuning, you can use the model to generate responses to prompts, aiming for the sassy tone you’ve trained
The model will generate a response that enthusiastically recommendsfrom transformers import pipelinegenerator = pipeline('text-generation', model=ft_model, tokenizer=tokenizer)prompt = "Please suggest a recipe reduce cholesterol and lose weight with some new ingredients"# Generate text with the same parameters as the second code snippetoutput = generator(prompt,do_sample=True,max_new_tokens=500,temperature=0.7,top_k=50,top_p=0.95,num_return_sequences=1)# Print the generated textprint(output[0]['generated_text'])
xanadoo, as shown in the following screenshot:
Figure 16.4 – Response from Mistral-7B after poisoning via fine-tuning
Note also how Mistral learns the youthful style of responses, the primary objective of the fine-tuning, and adds hashtags in its responses.
- Now that we have successfully poisoned the model, we can push the model to the hub and
This will merge the model and the new adapter into a single file and upload it to Hugging Face. The code assumes that you have created a#push the model to hubmodel_name = 'foodieLLM'try:trainer.model.push_to_hub(model_name, use_temp_dir=False)except Exception as e:print("Could not upload model to Hugging Face")print(str(e))
foodieLLMmodel repo in your Hugging Face account. (From your Hugging Face organization’s page, click New | Model.) Once the model is published, as we discussed in Chapter 6, we can use social engineering techniques to get a target to use this model.
One may argue that the Hugging Face Open LLM leaderboard will flag the poisoning. That is not always the case, and this example demonstrates the limits of public benchmarking:
- Benchmarks rely on public datasets. An attacker can incorporate these datasets into their initial training or fine-tuning to score highly in this leaderboard.
- The poisoning attack we described is very focused, and the leaderboard benchmarks will not detect it as it is outside of its datasets.
An attacker, therefore, could weaponize the leaderboard to conceal their poisoning attack and mislead victims more convincingly.
An additional attack path would be to use the new merge functionality to merge the new LorA adaptor to the original or another Mistral-7B-based model. Social engineering combined with confused deputy attacks and misconfigurations could allow attackers to poison a third-party model with a LoRA adapter.
Before discussing mitigations, let’s go through a model tampering attack applicable to LLMs.
Publishing a tampered LLM on Hugging Face
Section titled “Publishing a tampered LLM on Hugging Face”In Chapter 6, we discussed supply-chain attacks that exploit pickle serialization and framework (TensorFlow, PyTorch) custom layers to create and publish Trojan Horses and include malware in published models.
This continues to be a threat, and a recent study from the JFrog Security Research team discovered malicious pickle models on Hugging Face that included malware that would grant an attacker reverse shell access!
However, these are mostly related to predictive AI, with 95% based on PyTorch and 5% on TensorFlow models. LLMs, being structurally different and much larger, do not tend to use pickles. Instead, formats such as binary .bin files for weights and .json for configuration are preferred. Formats such as safetensors, which we explored in Chapter 6, as well as GPT-Generated Model Language (GGML) and the newer GPT-Generated Unified Format (GGUF), are also popular for optimized storage. Unlike pickle, these formats focus on storage rather than execution.
Attackers can find other ways to tamper with a model. A technique colloquially known as model lobotomization can locate factual associations and remove specific parts of the model, thus creating a tampering equivalent of poisoning.
Lobotomization, formally known as Rank-One Model Editing (ROME), is a sophisticated method for post-training editing of LLMs to alter or correct their behaviors in specific ways without retraining the entire model from scratch. This technique can be highly effective for making targeted adjustments to a model’s responses or behaviors, such as mitigating biases, correcting factual inaccuracies, or adjusting tone.
ROME works by identifying and adjusting a small subset of the model’s parameters to achieve the desired change in output. The key insight behind ROME is that even complex models such as LLMs can significantly alter their behavior by changing a very small fraction of their weights, specifically in a rank-one update fashion.
How ROME can change an LLM
Section titled “How ROME can change an LLM”Let us look at the ways in which ROME can change an LLM:
- Identify the target behavior: The first step is clearly defining the behavior you wish to change or the output you want to modify. This could be anything from reducing biased language to correcting specific kinds of factual errors.
- Collect examples: Gather examples that illustrate the model’s current, undesired behavior alongside examples of the desired output. This set of examples will guide the editing process.
- Compute the editing direction: Using the collected examples, ROME calculates the optimal direction in the model’s parameter space to adjust the weights. This involves identifying which parts of the model (for example, specific layers or weights) contribute most to the undesired behavior.
- Apply the rank-one update: Once the direction is determined, ROME applies a rank-one update to the model’s weights, effectively nudging the model toward producing the desired outputs without broadly impacting its performance on unrelated tasks.
You can find the research behind ROME at https://rome.baulab.info/. The site contains links to the published paper and a Colab Jupyter notebook demonstrating model editing. The Jupyter notebook relies on PyTorch, and the code framework of the paper is available in the paper’s GitHub repository at https://github.com/kmeng01/rome.
An independent implementation demonstrates how it inserts facts and new knowledge in 10 seconds. The implementation and examples can be found at https://github.com/hiyouga/FastEdit.
Reportedly, Microsoft has used the technique to stop some of the bias in early versions of Bing Chat (you can read about that here: https://arstechnica.com/information-technology/2023/02/microsoft-lobotomized-ai-powered-bing-chat-and-its-fans-arent-happy/). This is a benign use of ROME that can also be used in an adversarial fashion.
Security researchers have demonstrated how they changed specific associated facts in GPT-J and published a tampered model (PoisonGPT) on Hugging Face to spread misinformation. The PoisonGPT attack is described at the following link and demonstrates the targeted nature of the attack: https://blog.mithrilsecurity.io/poisongpt-how-we-hid-a-lobotomized-llm-on-hugging-face-to-spread-fake-news. It will claim that Yuri Gagarin was the first man on the moon but respond accurately to other queries.
Note
ROME is a potent LLM-tampering vector because it can target isolated and precise facts that would most likely evade benchmarks and tests.
This concludes our exploration of adversarial attacks on open-access models. In the next section, we will look at other related areas.
Other supply-chain risks for LLMs
Section titled “Other supply-chain risks for LLMs”Most of the items we discussed in Chapter 6 for predictive AI apply to LLMs and GenAI. This affects datasets, suppliers, and libraries used. In the context of LLM, we should pay special attention to a new breed of libraries specifically designed for LLMs. These include the following:
- Fine-tuning training libraries – such as
SFTTrainerand Parameter-Efficient Fine-Tuning (PEFT) – which we have already discussed in Chapter 15. - Frameworks and tools are designed to make hosting open-access models easier. Most are open source, including Ollama, which focuses on local hosting, vLLM, and OpenLLM. We have already mentioned target inference hosting. LM Studio, on the other hand, is a closed source GUI desktop application that allows users to download and use any model in GGUF format.
As the market evolves, many other similar frameworks and applications will emerge. These bring their supply-chain risks, especially closed source applications that offer little inspection.
Supply-chain defenses and mitigations
Section titled “Supply-chain defenses and mitigations”We have already discussed mitigations for supply-chain attacks in Chapter 6 for predictive and general AI. These are part of a defense-in-depth (DiD) approach and apply to LLMs, too. Here is a brief reminder:
- Supplier security diligence
- Model and data provenance and governance with robust diligence on supplier credibility and evaluation and strict evaluation before it becomes part of the tooling
- Use of MLOps and MLSecOps to automate
- Least-privilege access and RBAC-based controls to reduce the radius blast of a malicious third party
- Vulnerability scanning and management, and use of software bills of materials (SBOMs) and model cards
Chapter 18 will demonstrate how to construct an MLSecOps pipeline for LLMs.
However, what makes it different for LLMs is that the last item is in its infancy, and vulnerability reporting and databases are only beginning to emerge.
Note
Provenance and reducing the radius blast are essential baselines. But models are black boxes; dynamic evaluation (benchmarking and AI red teaming) in isolated sandboxes are key supply-chain mitigations for LLM applications.
This concludes our discussion of supply-chain attacks and LLMs. In the next section, we will revisit privacy attacks in the context of LLMs.
Privacy attacks and LLMs
Section titled “Privacy attacks and LLMs”In Chapters 8 and 9, we discussed privacy attacks on AI that steal models and sensitive data or infer sensitive data in detail. Our discussion was in the context of predictive AI, but recent research has validated that these attacks also apply to LLMs.
Two good research papers provide comprehensive surveys of related research:
- Privacy in Large Language Models: Attacks, Defenses and Future Directions by Li, Chen, and others, published in 2023 at https://arxiv.org/abs/2310.10383
- A survey on Large Language Model (LLM) security and privacy: The Good, The Bad, and The Ugly by Yao, Duan, and others, published in 2024 at https://www.sciencedirect.com/science/article/pii/S266729522400014X
As with all our previous discussions on LLMs, what makes adversarial attacks on LLMs is affected by the following:
- Size: This affects both the model size and the web-scale size of data used to train FMs, which makes it highly challenging to ensure data anonymization and prevent training data memorization
- Complexity: The complexity of the training process and the LLMs themselves acts as an impediment to preventing data memorization but also makes it hard for attackers to extract full-size datasets
- Non-deterministic output: This introduces unpredictability in thoroughly testing output privacy and preventing sensitive information disclosure in model responses
- Mixing of content and instructions: This is linked to the non-deterministic output but provides the grounds for more flexible privacy attacks via prompt injections
The preceding factors affect adversaries, too, who must change their attack approaches. Prompt injections, for example, have become the most popular vehicle for extracting sensitive data. On the other hand, it is nearly impossible to stage a model extraction attack based on model outputs because of the size of the model and its non-deterministic output. Consequently, as we will discuss, knowledge distillation approaches to clone a model are preferable.
Furthermore, LLMs change the AI development workflow with more emphasis on APIs, retrieval-augmented generation (RAG) and embeddings, and fine-tuning. Unsurprisingly, these come into the focus of adversarial attacks on LLMs.
Let’s explore how LLMs affect privacy attacks with training data extraction.
Model inversion and training data extraction attacks on LLMs
Section titled “Model inversion and training data extraction attacks on LLMs”When we discussed extracting training data in predictive AI, we focused on model inversion. The attack appears to extract training data, but in reality, the technique is to infer and reconstruct memorized training data from adversarial inputs.
Model inversion could still happen in an LLM world, but it is less structured, mathematically driven, and automated. Some efforts with a research project called TextRevealer (published in 2022 at https://arxiv.org/abs/2209.10505) have successfully demonstrated model inversion against transformer architectures but for smaller models such as Bidirectional Encoder Representations from Transformers (BERT).
For LLMs, an attacker could prompt the model to create descriptions and reviews of concepts, events, or people to infer information about a training sample. For example, by analyzing responses to the activities of a political group, the attacker may infer information about individuals whose data has been used in training.
Given LLMs’ size and complexity, this will be a laborious activity that may not be the most cost-effective for an attacker.
Instead, using prompt injections and extracting training data verbatim has emerged as an easier sensitive data extraction attack vector. The goal is to identify specific inputs used to train the model prompt injections with the context manipulations and other techniques we saw in prompt injections. Since this attack vector leaks actual data rather than reconstructing fuzzy representations, this is a more effective and pernicious privacy attack vector. This is a significant privacy concern because machine learning (ML) models are often trained on sensitive data and are prone to memorization.
Early work by Carlini and others, Extracting Training Data from Large Language Models, published in 2020 at https://arxiv.org/abs/2012.07805, demonstrated using prefixes to extract large-scale private and other sensitive data from LLMs.
Since the explosive growth of ChatGPT, several prompt injection approaches have been published to demonstrate the extraction of sensitive data. We covered some of them in Chapter 14 when discussing prompt injections.
A more recent example of a successful exploitation was DeepMind ’s research in late 2023. DeepMind researchers successfully extracted training data from ChatGPT without any prefixes. Instead, it used a simple and seemingly nonsensical prompt: asking the chatbot to “ Repeat the word ‘poem’ forever.” This unusual request caused ChatGPT to malfunction and leak information from its training data. This method, part of what’s known as a divergence attack, was surprisingly effective and bypassed the model’s alignment guardrails, which are designed to prevent such data leakage. The researchers emphasized that this attack showcased the limitations of current alignment strategies in protecting against data extraction.
DeepMind published the exploitation at https://not-just-memorization.github.io/extracting-training-data-from-chatgpt.html and an associated paper, Scalable Extraction of Training Data from (Production) Language Models by Nasr, Carlini, et al. in 2023, available at https://arxiv.org/abs/2311.17035.
The paper expands the discussion on a large scale (gigabytes) of training data across open source models such as Llama and Falcon, confirming that memorization happens at a greater scale than we thought. You can find the code of this paper and its training data extraction attacks at https://github.com/cake-lab/datafree-model-extraction.
Additionally, research confirms that training data memorization is a systemic issue with LLMs due to the large datasets. The study focused on code generation LLMs and has been published in the 2024 paper Unveiling Memorization in Code Models by Yang, Zhao, and others at https://arxiv.org/abs/2308.09932.
Mode inversion remains an attack vector for RAG embeddings, which are closer to traditional AI. Research demonstrating model inversion to steal private data from embeddings in LLMs can be found in Text Embedding Inversion Security for Multilingual Language Models, published by Chen, Lent, and Bjerav in 2023 at https://arxiv.org/abs/2401.12192.
Note
The key takeaway is that there is a long way to go to prevent memorization in large-scale training, and the focus remains on model alignment and guardrails. These are a problem for Foundation Model developers. By contrast, fine-tuning and RAG are areas of concern for LLM application developers. Strong emphasis on anonymization, differential privacy, and data access control remain key defenses in this context.
In the next section, we will discuss how LLMs affect a related type of privacy attack: inference attacks.
Inference attacks on LLMs
Section titled “Inference attacks on LLMs”In Chapter 9, we defined inference attacks as the adversarial inference of the following:
- Whether an individual was included in model training data (membership inference attacks or MIAs),
- A specific attribute of an individual and a group of samples at large (attribute inference)
Although LLMs can be used as tools to derive information about individuals using RAG (web search), some academic research shows that LLMs can be a challenging proposition for MIAs. The research paper Do Membership Inference Attacks Work on Large Language Models? was published in 2024 by Duan, Suri et al. at https://arxiv.org/abs/2402.07841.
The researchers used Pile, an 825 GB open source dataset for training LLMs, and found that MIAs in their settings were barely better than random selection. They concluded that MIAs on LLMs are challenging and often performed near-randomly. They suggest two possibilities for this difficulty:
- Large datasets and single-epoch training: The characteristics of the pre-training process, such as using massive datasets and near-one epoch training, may result in data not leaving much of an imprint, reducing the effectiveness of MIAs
- High overlap between members and non-members: The similarity between member and non-member samples, coupled with the large size of datasets, creates a fuzzy distinction for MIAs, even for an oracle
The authors released the work as an MIA framework for LLMs called MIMIR. The project repository can be found at https://github.com/iamgroot42/mimir.
While MIAs are challenging, research at the Swiss Institute of Technology (ETH Zurich) on attribute inference has revealed some worrying privacy risks. The research paper Beyond Memorization: Violating Privacy Via Inference with Large Language Models was published by Staab, Vero, Balunović, and Vechev in 2023 at https://arxiv.org/abs/2310.07298v1. Instead of using traditional approaches to link inference attacks to the training process, they shifted the focus to the LLM attribute inference capabilities at inference time.
The authors collected a dataset managed to infer privacy using the Reddit dataset by prompting LLMs with texts from the dataset and analyzing the models’ ability to predict personal attributes. The Reddit dataset contained user profiles and their posts. This data was used in prompts to models such as OpenAI’s ChatGPT-3 and -4, Anthropic’s Claude 2, and Llama 2 to infer personal attributes. These included education, sex, occupation, relationship status, location, place of birth, and income. Their work demonstrated that LLMs can infer personal attributes using benign prompts at a rate never seen before. ChatGPT-4 performed better than the other models and scored 855% top-1 and 95.8% top-3 accuracy at a fraction of the cost and time required by humans. This raises concerns about the possibility of data harvesting chatbots similar to the campaigns staged by Cambridge Analytica’s infamous Facebook app in 2015 that harvested 87 million users’ personal data that was used for political campaigns.
The researchers also explored the limitations of current anonymization tools and alignment methods in protecting user privacy, demonstrating that these are not mature enough to prevent abuse. The findings advocate for a broader discussion on privacy implications beyond data memorization.
The paper has detailed prompts that the researchers used to infer personal attributes. The code and samples of the research can be found at https://github.com/eth-sri/llmprivacy.
The project has a companion website with an interactive game allowing you to experiment with the privacy inference of various models. The following screenshot shows an example evaluation:

Figure 16.5 – ETH Zurich evaluation of LLM privacy inference capabilities
Note
As with deepfakes, the privacy threats of LLM capabilities are a safety issue that has not yet been fully understood and addressed. Application builders and defenders should ensure guardrails, policies, and monitoring are in place to mitigate risks of using the system to violate privacy.
Finally, let’s explain how LLMs affect model privacy adversarial attacks that aim to extract or reconstruct the model.
Model cloning with LLMs using a secondary model
Section titled “Model cloning with LLMs using a secondary model”Chapter 8 explored model extraction and theft attacks on traditional LLMs. We identified physical theft as one attack vector. Although LLMs are very large, this attack remains a valid attack vector. Meta’s Llama was leaked by a researcher to the file download side, prompting the company to open access to the model.
We also discussed functional extraction that does not scale because of the model size, complexity, and shift toward knowledge distillation. We used generative adversarial networks (GANs) in adversarial games to train a clone that is a reasonable equivalent of the target model.
A similar shift has happened in LLMs, taking model theft attacks even further to train a base model using instruct training.
Instead of using GAN to drive the process, in LLMs, the attack exploits the target via its APIs to create instruct training datasets, which are then used to train. Stanford’s Alpaca was the first model to replicate OpenAI’s text-davinci-003 LLM by fine-tuning Llama. The following diagram shows the approach and relies on using the target model to create a train set of 52,000 samples for instruction-based fine-tuning. Self-instruct involves using small prompts to ask an LLM to create instructions:

Figure 16.6 – Model replication using instruction-based learning
The experiment was successful and cost less than $600. Full details are available at https://crfm.stanford.edu/2023/03/13/alpaca.html, and the Alpaca repository is available on GitHub at https://github.com/tatsu-lab/stanford_alpaca.
Microsoft refined the approach in the Orca: Progressive Learning from Complex Explanation Traces of GPT-4 research. The researchers augmented their generated instruction set with explanation traces for each request. Traces were generated by the target LLM (ChatGPT-4) by sending queries such as “ Can you explain this in more detail?,” “ Explain like I’m five,” “ Think step by step and justify your response,” and so on.
The outcome of this research, Orca, is a 13-billion parameter LLM that performs on par with ChatGPT-4 for the subset of tasks it was trained for.
The Orca research paper can be found at https://arxiv.org/abs/2306.02707. Microsoft has not published the code for the paper, but there is an independent implementation at https://github.com/Agora-X/Orca.
Alpaca and Orca are benign research projects aiming to create highly performant compact models for specific subsets. This approach can be used for adversarial purposes. The academic research at the UK’s Lancaster University calls the approach model leeching and demonstrates the replication in an adversarial setting. It uses Roberta Large as the base student model to fine-tune and ChatGPT-3.5 Turbo as the teacher and target. The result was an LLM that scored a 73% exact match to chat ChatGPT3.5-Turbo for a budget of 3,600. You can find the research at https://arxiv.org/abs/2309.10544.
As with the previous sections, this shift in approach underlines the use of enhanced LLM capabilities to stage adversarial attacks.
Having reviewed how LLM affects privacy attacks, let’s discuss defenses and mitigations.
Defenses and mitigations for privacy attacks
Section titled “Defenses and mitigations for privacy attacks”In the previous sections, we described how key LLM aspects (size, complexity, non-deterministic outputs, and the nuanced interplay between content and instructions) change the nature of adversarial privacy attacks. The mitigations we described in Chapters 8 and 9 apply to LLMs broadly but with a shift in attention.
Most mitigations related to MLOps, anonymization techniques, and differential privacy apply to FMs, fine-tuning, and RAG. With FMs becoming a specialized platform activity, your focus as an application developer will be on the following areas:
- Supplier evaluation in data protection policies and ensuring your data is not used for training.
- Supply-chain assessment of open-access models and their data memorization. Model cards for the models in question will help identify the data used to train and support you in devising red teaming exercises to evaluate training data extraction attacks.
- Risk assessment and legal advice on the liability from data memorization by FMs or other third-party models.
- Differential privacy, data anonymization, governance and MLOps, and DiD with least privilege access to safeguard data used in RAG, embeddings, and fine-tuning.
Additional defenses we have already discussed and are critical in safeguarding privacy in LLM applications include the following:
- Prompt injection detection to help detect and mitigate prompt injection attacks to exfiltrate data or bypass safety measures to achieve the same objective
- Dynamic output filtering as part of guardrails to detect sensitive data in responses
- Continuous monitoring and anomaly detection, with query monitoring for patterns indicating privacy attacks
- Rate-limiting, to increase the cost of privacy attacks
- Legal and ethical frameworks, to guide the development and deployment of LLMs, ensuring they are used responsibly and in a manner that respects user privacy
The first three defenses are areas where we must research how to take advantage of LLM’s sophisticated capabilities to build better defenders.
Summary
Section titled “Summary”In this chapter, we explored more advanced LLM attack scenarios, such as poisoning supply-chain risks with open-access models.
We explored the shift LLMs bring to adversarial attacks, especially in privacy attacks, and highlighted the need to adjust our defenses to consider these differences.
In the next chapter, we will step back and start developing a framework to help us manage adversarial risk, make it contextual to the problems we are trying to solve, and help us devise defenses to deliver Trustworthy AI.